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
@@ -0,0 +1,51 @@
1
+ import { loadSchema } from '../../config/schema-registry.js';
2
+ import { commandExists } from '../../utils/cross-platform.js';
3
+ import { GeminiAgentPlugin } from './gemini-runner.js';
4
+ import { GeminiSessionFileAdapter } from './gemini-session-file-adapter.js';
5
+ import { GeminiCapabilityProvider } from './gemini-capability-provider.js';
6
+ function card(id, implementation, availability, notes) {
7
+ return { id, level: id[0], implementation, availability, verification: 'verified', notes };
8
+ }
9
+ export default {
10
+ name: 'gemini',
11
+ displayName: 'Gemini CLI',
12
+ aliases: ['gemini', 'gemini-cli', 'gemini cli', 'geminicli', 'google', 'google-ai'],
13
+ // Preserve the published Gemini configuration contract, including existing fallback entries.
14
+ configSchema: loadSchema('agent-config').raw.properties.baseagents.properties.gemini,
15
+ probe: () => ({ available: commandExists('gemini'), reason: 'Gemini CLI must be installed on this host' }),
16
+ environments: [{
17
+ os: 'linux',
18
+ probedWith: {
19
+ cli: 'CLI fixture; real Gemini CLI and Provider require separate acceptance',
20
+ node: 'v22.19.0',
21
+ at: '2026-11-16T20:36:31Z',
22
+ },
23
+ }],
24
+ // These IDs retain the meanings in baseagent-plugin-capabilities.md. A known
25
+ // limitation is not a claim of v1 conformance or a reason to loosen Host policy.
26
+ declaredCapabilities: [
27
+ card('B01', 'adapted', 'available', 'Descriptor and configuration boundary regression tests'),
28
+ card('B02', 'host-only', 'available', 'Side-effect-free executable detection; missing CLI stays unavailable'),
29
+ card('B03', 'adapted', 'available', 'One existing GeminiRunner instance per EvolAgent'),
30
+ card('B04', 'adapted', 'unavailable', 'Text input exists; legacy CLI does not separate Host and user context'),
31
+ card('B05', 'native', 'available', 'The selected model is passed through -m'),
32
+ card('B06', 'adapted', 'available', 'Legacy AgentEvent stream and result conversion'),
33
+ card('B07', 'adapted', 'unavailable', 'Legacy interrupt lacks complete subprocess cancellation confirmation'),
34
+ card('B08', 'adapted', 'available', 'Input acceptance follows the echoed user message, not process creation'),
35
+ card('B09', 'host-only', 'unavailable', 'Task temporary paths are isolated; native Gemini home is shared'),
36
+ card('B10', 'adapted', 'unavailable', 'Host context is appended on the initial turn; no equivalent system priority'),
37
+ card('B11', 'adapted', 'available', 'Headless readonly/auto policies; request and bypass remain unavailable'),
38
+ card('B12', 'unsupported', 'unavailable', 'No validated tools.execution=none integration'),
39
+ card('B13', 'host-only', 'available', 'Existing per-run sandbox and protected-root refusal remain authoritative'),
40
+ card('B14', 'adapted', 'unavailable', 'Legacy events do not implement the candidate v1 identity/seq contract'),
41
+ card('C03', 'native', 'available', 'Resume passes the same native session ID through -r'),
42
+ card('C10', 'host-only', 'available', 'Existing shared model catalog; requires configured Provider'),
43
+ card('C11', 'unsupported', 'unavailable', 'GeminiRunner does not implement effort'),
44
+ card('C13', 'unsupported', 'unavailable', 'Headless CLI has no native permission callback'),
45
+ card('C17', 'unsupported', 'unavailable', 'Native tools are not entirely executed by the Host broker'),
46
+ card('C26', 'adapted', 'available', 'Images are passed as temporary @file attachments'),
47
+ ],
48
+ createRunner: () => new GeminiAgentPlugin(),
49
+ createSessionAdapter: () => new GeminiSessionFileAdapter(),
50
+ createCapabilityProvider: () => new GeminiCapabilityProvider(),
51
+ };
@@ -10,7 +10,7 @@ import { AUN_KEYSTORE_ENCRYPTION_SEED } from './encryption-seed-policy.js';
10
10
  import { isValidAid } from './validation.js';
11
11
  import { agentMdPath, resolvePaths } from '../../paths.js';
12
12
  import { PeerIdentityCache } from '../../core/relation/peer-identity.js';
13
- import { agentmdPutInitializationProfile, buildInitialAgentMd, invalidateAgentDisplayName, stripAgentMdSignature } from './agentmd.js';
13
+ import { agentmdPut, agentmdPutInitializationProfile, buildInitialAgentMd, invalidateAgentDisplayName, stripAgentMdSignature } from './agentmd.js';
14
14
  import { logger, logOwnershipEvent } from '../../utils/logger.js';
15
15
  const MAX_ATTEMPTS = 5;
16
16
  export { DEFAULT_AID_DOMAIN } from './domain.js';
@@ -67,7 +67,7 @@ function readJsonFile(filePath) {
67
67
  return undefined;
68
68
  }
69
69
  }
70
- function hasCanonicalControlFrontmatter(content, aid, name, aunRoot, ownerAid) {
70
+ function readCanonicalControlName(content, aid, aunRoot, ownerAid) {
71
71
  try {
72
72
  // A frontmatter-only match is insufficient here: an unsigned or malformed
73
73
  // local card must be republished so the SDK can produce a valid signature.
@@ -75,29 +75,29 @@ function hasCanonicalControlFrontmatter(content, aid, name, aunRoot, ownerAid) {
75
75
  const payload = stripAgentMdSignature(content);
76
76
  const frontmatter = payload.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
77
77
  if (!frontmatter)
78
- return false;
78
+ return undefined;
79
79
  const document = parseDocument(frontmatter);
80
80
  if (document.errors.length > 0)
81
- return false;
81
+ return undefined;
82
82
  const fields = document.toJS();
83
83
  if (!fields || typeof fields !== 'object' || Array.isArray(fields))
84
- return false;
84
+ return undefined;
85
85
  const values = fields;
86
86
  const canonical = typeof values.aid === 'string'
87
87
  && values.aid.trim().toLowerCase() === aid.toLowerCase()
88
88
  && typeof values.name === 'string'
89
- && values.name.trim() === name
89
+ && values.name.trim().length > 0
90
90
  && typeof values.type === 'string'
91
91
  && values.type.trim().toLowerCase() === 'host';
92
92
  if (!canonical)
93
- return false;
93
+ return undefined;
94
94
  const owner = typeof values.owner === 'string' ? values.owner.trim().toLowerCase() : '';
95
95
  const statement = values.ownership?.statement;
96
96
  if (!owner || ownerAid && owner !== ownerAid.toLowerCase()
97
97
  || statement?.owner_aid !== owner || statement.sub_aid !== aid
98
98
  || typeof statement.relation_version !== 'number' || !Number.isSafeInteger(statement.relation_version)
99
99
  || statement.relation_version < 1)
100
- return false;
100
+ return undefined;
101
101
  // The SDK validator checks that a signature block is well formed, but it
102
102
  // deliberately does not verify the signature against the local cert.
103
103
  // A damaged or stale control card must be republished, otherwise peers
@@ -105,10 +105,15 @@ function hasCanonicalControlFrontmatter(content, aid, name, aunRoot, ownerAid) {
105
105
  const certPath = path.join(aunRoot, 'AIDs', aid, 'public', 'cert.pem');
106
106
  const certPem = fs.readFileSync(certPath, 'utf8');
107
107
  verifyAgentMdUpload(content, certPem, aid);
108
- return true;
108
+ // Keep first-run migration for the SDK's generated identity name.
109
+ // PA and user-authored Host profiles have their own description.
110
+ const sdkName = values.name === aid || values.name === aid.split('.', 1)[0];
111
+ if (sdkName && values.description === `AUN host ${values.name}`)
112
+ return undefined;
113
+ return values.name;
109
114
  }
110
115
  catch {
111
- return false;
116
+ return undefined;
112
117
  }
113
118
  }
114
119
  function clearControlAgentPeerCaches(aid, root = resolvePaths().root) {
@@ -147,7 +152,6 @@ export async function ensureControlAgentMd(aid, opts = {}) {
147
152
  if (pending)
148
153
  return pending;
149
154
  const run = (async () => {
150
- const name = buildControlAgentName(normalizedAid, opts.platform);
151
155
  const localPath = agentMdPath(normalizedAid, aunRoot);
152
156
  const metadataPath = path.join(path.dirname(localPath), 'agentmd.json');
153
157
  let existing;
@@ -157,7 +161,10 @@ export async function ensureControlAgentMd(aid, opts = {}) {
157
161
  catch { /* missing */ }
158
162
  const metadata = readJsonFile(metadataPath);
159
163
  const remoteMissing = String(metadata?.remote_status ?? '').trim().toLowerCase() === 'missing';
160
- const canonical = !!existing && hasCanonicalControlFrontmatter(existing, normalizedAid, name, aunRoot, opts.ownerAid);
164
+ // Only a fully verified, owned Host card can supply a custom display name.
165
+ const currentName = existing ? readCanonicalControlName(existing, normalizedAid, aunRoot, opts.ownerAid) : undefined;
166
+ const name = currentName ?? buildControlAgentName(normalizedAid, opts.platform);
167
+ const canonical = currentName !== undefined;
161
168
  const needsPublish = !canonical || remoteMissing;
162
169
  let hadOwnershipFields;
163
170
  if (existing) {
@@ -191,32 +198,45 @@ export async function ensureControlAgentMd(aid, opts = {}) {
191
198
  tags: CONTROL_AGENT_TAGS,
192
199
  });
193
200
  try {
194
- const existingOwner = (() => {
195
- if (!existing)
196
- return undefined;
197
- try {
198
- const frontmatter = stripAgentMdSignature(existing).match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
199
- if (!frontmatter)
200
- return undefined;
201
- const fields = parseDocument(frontmatter).toJS();
202
- const value = typeof fields?.owner === 'string' ? fields.owner.trim().toLowerCase() : '';
203
- return isValidAid(value) ? value : undefined;
204
- }
205
- catch {
206
- return undefined;
207
- }
208
- })();
209
- const ownerAid = opts.ownerAid ?? existingOwner;
210
- if (ownerAid) {
211
- await agentmdPutInitializationProfile(content, {
201
+ if (canonical && remoteMissing) {
202
+ // Restore the verified document, including its ownership declaration.
203
+ // A profile update requires a remote card and cannot repair a 404.
204
+ // Refuse to overwrite if the remote card has appeared since the check.
205
+ await agentmdPut(existing, {
212
206
  aid: normalizedAid,
213
- ownerAid,
214
207
  store: opts.store,
215
208
  aunPath: aunRoot,
209
+ expectedRemoteVersion: { exists: false },
216
210
  });
217
211
  }
218
212
  else {
219
- throw Object.assign(new Error('control AID Owner is unavailable; refusing to publish an unowned host agent.md'), { code: 'CONTROL_OWNER_REQUIRED' });
213
+ const existingOwner = (() => {
214
+ if (!existing)
215
+ return undefined;
216
+ try {
217
+ const frontmatter = stripAgentMdSignature(existing).match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
218
+ if (!frontmatter)
219
+ return undefined;
220
+ const fields = parseDocument(frontmatter).toJS();
221
+ const value = typeof fields?.owner === 'string' ? fields.owner.trim().toLowerCase() : '';
222
+ return isValidAid(value) ? value : undefined;
223
+ }
224
+ catch {
225
+ return undefined;
226
+ }
227
+ })();
228
+ const ownerAid = opts.ownerAid ?? existingOwner;
229
+ if (ownerAid) {
230
+ await agentmdPutInitializationProfile(content, {
231
+ aid: normalizedAid,
232
+ ownerAid,
233
+ store: opts.store,
234
+ aunPath: aunRoot,
235
+ });
236
+ }
237
+ else {
238
+ throw Object.assign(new Error('control AID Owner is unavailable; refusing to publish an unowned host agent.md'), { code: 'CONTROL_OWNER_REQUIRED' });
239
+ }
220
240
  }
221
241
  logOwnershipEvent('control.card.published', diagnostic);
222
242
  }
@@ -261,7 +261,6 @@ export async function decideGroupInvite(client, action, inviteId) {
261
261
  }
262
262
  }
263
263
  const CARD_TTL_MS = 86400_000;
264
- const RECONCILE_TICK_MS = 30_000;
265
264
  const PAGE_SIZE = 10;
266
265
  const CARD_BATCH = 20;
267
266
  function cleanText(value, limit) {
@@ -280,17 +279,9 @@ export class GroupInviteReviewService {
280
279
  bindings = new Map();
281
280
  lanes = new Map();
282
281
  syncs = new Map();
283
- timer;
284
282
  constructor(router, store = new GroupInviteReviewStore()) {
285
283
  this.router = router;
286
284
  this.store = store;
287
- this.timer = setInterval(() => {
288
- for (const runtime of this.bindings.values()) {
289
- if (runtime.channel.isConnected() && runtime.nextSync <= Date.now())
290
- this.wake(runtime);
291
- }
292
- }, RECONCILE_TICK_MS);
293
- this.timer.unref?.();
294
285
  }
295
286
  attach(binding) {
296
287
  this.detach(binding.channelKey);
@@ -298,16 +289,13 @@ export class GroupInviteReviewService {
298
289
  const previous = this.bindings.get(binding.selfAid);
299
290
  if (previous)
300
291
  this.detach(previous.channelKey);
301
- const runtime = { ...binding, ready: false, restored: false, nextSync: 0, failures: 0, registered: new Set() };
292
+ const runtime = { ...binding, ready: false, restored: false, registered: new Set() };
302
293
  this.bindings.set(binding.selfAid, runtime);
303
294
  binding.channel.setGroupInviteReviewHandlers({
304
295
  onInvite: () => this.wake(runtime),
305
- onConnected: () => { runtime.ready = false; this.wake(runtime); },
306
296
  canDeliver: (id, owner) => this.canDeliver(runtime, id, owner),
307
297
  onDelivered: (id, mid) => this.recordDelivery(runtime, id, mid),
308
298
  });
309
- if (binding.channel.isConnected())
310
- this.wake(runtime);
311
299
  }
312
300
  detach(channelKey) {
313
301
  for (const runtime of this.bindings.values()) {
@@ -322,16 +310,10 @@ export class GroupInviteReviewService {
322
310
  }
323
311
  }
324
312
  async dispose() {
325
- clearInterval(this.timer);
326
313
  for (const runtime of [...this.bindings.values()])
327
314
  this.detach(runtime.channelKey);
328
315
  await Promise.allSettled(this.lanes.values());
329
316
  }
330
- configurationChanged(selfAid) {
331
- const runtime = this.bindings.get(selfAid);
332
- if (runtime)
333
- this.wake(runtime);
334
- }
335
317
  owners(selfAid) {
336
318
  return [...new Set(listStaticAgentOwners(selfAid, { fresh: true }).filter(isValidAid))];
337
319
  }
@@ -375,21 +357,10 @@ export class GroupInviteReviewService {
375
357
  const task = this.serial(selfAid, async () => {
376
358
  if (!this.active(runtime)) {
377
359
  runtime.ready = false;
378
- runtime.failures = 0;
379
- runtime.nextSync = Date.now() + 15 * 60_000;
380
360
  return;
381
361
  }
382
- try {
383
- await this.sync(runtime);
384
- runtime.failures = 0;
385
- const open = this.store.list(selfAid, OPEN_INVITE_STATES);
386
- runtime.nextSync = Date.now() + (open.some(item => item.status !== 'pending') ? 30_000 : open.length ? 300_000 : 900_000);
387
- }
388
- catch (error) {
389
- runtime.failures++;
390
- runtime.nextSync = Date.now() + Math.min(900_000, 30_000 * 2 ** Math.min(runtime.failures, 5)) + Math.random() * 5000;
391
- throw error;
392
- }
362
+ // Invitation events and explicit review operations are the only sync triggers.
363
+ await this.sync(runtime);
393
364
  });
394
365
  this.syncs.set(selfAid, task);
395
366
  void task.finally(() => { if (this.syncs.get(selfAid) === task)
@@ -749,7 +720,6 @@ export class GroupInviteReviewService {
749
720
  item.submittedAt = Date.now();
750
721
  item.nextAttemptAt = Date.now() + 30_000;
751
722
  });
752
- runtime.nextSync = Math.min(runtime.nextSync, Date.now() + 30_000);
753
723
  logger.info(`[GroupInviteReview] decision self=${runtime.selfAid} review=${id} actor=${owner} action=${action}`);
754
724
  return { accepted: true, record: decision };
755
725
  }
@@ -793,7 +763,7 @@ export class GroupInviteReviewService {
793
763
  item.error = errorText(error);
794
764
  item.nextAttemptAt = Date.now() + 30_000;
795
765
  });
796
- await this.notice(runtime, decision.actorAid, `uncertain:${decision.attemptId}`, '群邀请决定已记录,服务端结果暂未确认。系统会继续核实,此时不接受相反决定。');
766
+ await this.notice(runtime, decision.actorAid, `uncertain:${decision.attemptId}`, '群邀请决定已记录,服务端结果暂未确认。可用 /invites 再次核实,此时不接受相反决定。');
797
767
  }
798
768
  this.log(runtime.selfAid, error);
799
769
  }
@@ -806,7 +776,7 @@ export class GroupInviteReviewService {
806
776
  const result = this.get(runtime.selfAid, id);
807
777
  return { accepted: true, groupId: result.groupId, status: result.status,
808
778
  text: result.status === 'accepted' ? `已确认加入 ${result.groupId}。` : result.status === 'rejected'
809
- ? `已拒绝 ${result.groupId} 的邀请。` : result.status === 'stale' ? '这轮邀请已不再待处理,未执行新的入群操作。' : '决定已记录,正在核实服务端结果;请稍后查看 /invites。' };
779
+ ? `已拒绝 ${result.groupId} 的邀请。` : result.status === 'stale' ? '这轮邀请已不再待处理,未执行新的入群操作。' : '决定已记录,服务端结果尚未确认;请用 /invites 核实结果。' };
810
780
  }
811
781
  async executeDecision(runtime, record, client) {
812
782
  try {
@@ -829,7 +799,7 @@ export class GroupInviteReviewService {
829
799
  item.nextAttemptAt = Date.now() + Math.min(900_000, 30_000 * 2 ** Math.min(item.attempts - 1, 5));
830
800
  });
831
801
  this.log(runtime.selfAid, error);
832
- await this.notice(runtime, record.actorAid, `uncertain:${record.attemptId}`, '群邀请决定已记录,服务端结果暂未确认。系统会继续核实,此时不接受相反决定。');
802
+ await this.notice(runtime, record.actorAid, `uncertain:${record.attemptId}`, '群邀请决定已记录,服务端结果暂未确认。可用 /invites 再次核实,此时不接受相反决定。');
833
803
  return;
834
804
  }
835
805
  // Persist the authoritative RPC outcome before best-effort invalidation and notifications.
@@ -195,6 +195,7 @@ export async function groupSend(args) {
195
195
  contentType: args.body.contentType,
196
196
  text: args.body.text,
197
197
  transcript: args.body.transcript,
198
+ title: args.body.title,
198
199
  });
199
200
  if (daemonResult) {
200
201
  const payload = { type: args.body.as || 'file' };
@@ -202,6 +203,10 @@ export async function groupSend(args) {
202
203
  return daemonGroupSendResult(args, payload, runtimeContext, daemonResult);
203
204
  }
204
205
  }
206
+ if ((args.body.mode === 'file' && args.body.as === 'widget_card')
207
+ || (args.body.mode === 'payload' && args.body.payload.type === 'widget_card')) {
208
+ return { ok: false, code: 'WIDGET_REQUIRES_DAEMON', error: 'WidgetCard requires a managed daemon send to bind its reply route' };
209
+ }
205
210
  const conn = await createShortConnection(args.from, { aunPath: args.aunPath, slotId: args.slotId });
206
211
  try {
207
212
  let payload;
@@ -218,6 +223,7 @@ export async function groupSend(args) {
218
223
  contentType: args.body.contentType,
219
224
  text: args.body.text,
220
225
  transcript: args.body.transcript,
226
+ title: args.body.title,
221
227
  onProgress: args.onUploadProgress,
222
228
  });
223
229
  payload = built.payload;
@@ -36,7 +36,7 @@ export function parseAunAttention(value) {
36
36
  export function withAunAttention(payload, fallback) {
37
37
  parseAunAttention(payload.attention);
38
38
  parseAunAttention(fallback);
39
- const attention = payload.type === 'action_card'
39
+ const attention = payload.type === 'action_card' || payload.type === 'widget_card'
40
40
  ? 'required'
41
41
  : payload.type === 'task.status' && typeof payload.status === 'string'
42
42
  ? aunStatusAttention(payload.status)
@@ -6,7 +6,8 @@ import { uploadFileAndBuildPayload } from './upload.js';
6
6
  import { appendMessageLog, buildOutboundEntry, classifyAunPayloadForLog } from '../../core/message/message-log.js';
7
7
  import { readBestTaskRuntimeContext, runtimeRefMessageIdForMsgSend } from '../../cli/task-context.js';
8
8
  import { chatDirPath } from '../../core/session/session-fs-store.js';
9
- import { resolvePaths } from '../../paths.js';
9
+ import { resolvePaths, toAttachmentMarkedPath } from '../../paths.js';
10
+ import { saveRelationAttachment, guessMime } from '../../utils/media-cache.js';
10
11
  import { ipcQuery } from '../../ipc.js';
11
12
  import { readDelegationCredential } from '../../core/auth/agent-delegation.js';
12
13
  import { loadDaemonConfig } from '../../config-store.js';
@@ -183,13 +184,14 @@ async function daemonMsgSendResult(args, payload, runtimeContext, daemonResult)
183
184
  && daemonResult.request_state === 'completed'
184
185
  && ((!!daemonResult.response && typeof daemonResult.response === 'object' && !Array.isArray(daemonResult.response))
185
186
  || (Array.isArray(daemonResult.responses) && daemonResult.responses.length > 0));
186
- if (!daemonResult.message_id && !daemonResult.handoff_id && !completedRequest) {
187
+ if (!daemonResult.message_id && !daemonResult.handoff_id && !completedRequest && daemonResult.status !== 'queued') {
187
188
  return { ok: false, error: 'daemon AUN message send returned no message_id' };
188
189
  }
189
190
  const sent = {
190
191
  ok: true,
191
192
  // handoff_id 是内部投递实例,不再冒充 message_id 回给调用方。
192
193
  message_id: daemonResult.message_id || '',
194
+ outbox_id: daemonResult.outbox_id,
193
195
  handoff_id: daemonResult.handoff_id,
194
196
  target_session_id: daemonResult.target_session_id,
195
197
  seq: daemonResult.seq,
@@ -218,10 +220,27 @@ async function daemonMsgSendResult(args, payload, runtimeContext, daemonResult)
218
220
  }
219
221
  return sent;
220
222
  }
223
+ /**
224
+ * CLI 直发文件的归档(宿主终端 `ec msg send --file`,不经 daemon)。
225
+ * 与 daemon 通道同一落点、同一命名与去重规则;失败返回 null,不阻断发送。
226
+ */
227
+ function archiveCliSentFile(selfAid, peerAid, filePath, as, contentType) {
228
+ try {
229
+ const absPath = path.resolve(filePath);
230
+ const archived = saveRelationAttachment(fs.readFileSync(absPath), selfAid, formatPeerKey('aun', peerAid), contentType || guessMime(absPath), { filename: path.basename(absPath), allowAnyExtension: true, direction: 'out' });
231
+ const label = as === 'image' ? '图片' : as === 'video' ? '视频' : as === 'voice' ? '语音' : '文件';
232
+ return `[${label}: ${path.basename(absPath)} → ${toAttachmentMarkedPath(selfAid, archived.filePath)}]`;
233
+ }
234
+ catch {
235
+ return null;
236
+ }
237
+ }
221
238
  async function appendMsgSendOutboundLog(args, result, opts) {
222
239
  const sessionsDir = resolvePaths().sessionsDir;
223
240
  const chatDir = chatDirPath(sessionsDir, 'aun', args.to, args.from);
224
241
  const log = msgSendLogMetadata(args, opts.payload, opts.runtimeContext);
242
+ if (opts.contentOverride)
243
+ log.content = opts.contentOverride;
225
244
  fs.mkdirSync(chatDir, { recursive: true });
226
245
  appendMessageLog(chatDir, buildOutboundEntry({
227
246
  from: args.from,
@@ -271,6 +290,8 @@ export async function msgSend(args) {
271
290
  let conn;
272
291
  try {
273
292
  let payload;
293
+ // CLI 直发文件时的归档文案;daemon 代发那条路径由 daemon 自己归档。
294
+ let archivedFileLog = null;
274
295
  if (args.body.mode !== 'file') {
275
296
  payload = args.body.mode === 'payload'
276
297
  ? buildSimplePayload(args.body)
@@ -291,6 +312,7 @@ export async function msgSend(args) {
291
312
  contentType: args.body.contentType,
292
313
  text: args.body.text,
293
314
  transcript: args.body.transcript,
315
+ title: args.body.title,
294
316
  });
295
317
  if (daemonResult) {
296
318
  return daemonMsgSendResult(args, { type: args.body.as || 'file' }, runtimeContext, daemonResult);
@@ -303,6 +325,10 @@ export async function msgSend(args) {
303
325
  error: 'request/reply waiting requires a managed EvolCore daemon session',
304
326
  };
305
327
  }
328
+ if ((args.body.mode === 'file' && args.body.as === 'widget_card')
329
+ || (args.body.mode === 'payload' && args.body.payload.type === 'widget_card')) {
330
+ return { ok: false, code: 'WIDGET_REQUIRES_DAEMON', error: 'WidgetCard requires a managed daemon send to bind its reply route' };
331
+ }
306
332
  conn = await createShortConnection(args.from, { aunPath: args.aunPath, slotId: args.slotId });
307
333
  if (args.body.mode === 'file') {
308
334
  const built = await uploadFileAndBuildPayload(conn, args.from, args.body.filePath, {
@@ -310,6 +336,7 @@ export async function msgSend(args) {
310
336
  contentType: args.body.contentType,
311
337
  text: args.body.text,
312
338
  transcript: args.body.transcript,
339
+ title: args.body.title,
313
340
  onProgress: args.onUploadProgress,
314
341
  });
315
342
  payload = built.payload;
@@ -317,6 +344,7 @@ export async function msgSend(args) {
317
344
  const daemonResult = await tryDaemonMsgSend(args, payload, runtimeContext);
318
345
  if (daemonResult)
319
346
  return daemonMsgSendResult(args, payload, runtimeContext, daemonResult);
347
+ archivedFileLog = archiveCliSentFile(args.from, args.to, args.body.filePath, args.body.as, args.body.contentType);
320
348
  }
321
349
  // 1. 解析对端身份(30天缓存)。身份解析走 HTTP+PKI(store),与发消息的短连接无关。
322
350
  const { agentsDir } = resolvePaths();
@@ -397,6 +425,7 @@ export async function msgSend(args) {
397
425
  runtimeContext,
398
426
  chatmode,
399
427
  encrypt,
428
+ contentOverride: archivedFileLog,
400
429
  });
401
430
  }
402
431
  catch { }
@@ -2,6 +2,113 @@ import crypto from 'crypto';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { formatSize } from '../../utils/media-cache.js';
5
+ export const MAX_WIDGET_HTML_BYTES = 1024 * 1024;
6
+ export const MAX_WIDGET_VALUES_BYTES = 64 * 1024;
7
+ /** Shared browser runtime injected into uploaded WidgetCard HTML, never generated per business field. */
8
+ export const WIDGET_CARD_FORM_SCRIPT = String.raw `(() => {
9
+ 'use strict';
10
+ let sending = false;
11
+ const forbidden = new Set(['__proto__', 'prototype', 'constructor']);
12
+ const formOf = () => {
13
+ const selected = document.querySelectorAll('form[data-widget-form]');
14
+ const forms = selected.length ? selected : document.forms;
15
+ if (forms.length !== 1) throw new Error('WidgetCard requires one form or one form[data-widget-form].');
16
+ return forms[0];
17
+ };
18
+ const collect = (form = formOf()) => {
19
+ if (!form.reportValidity()) throw new Error('Please complete the required fields.');
20
+ const entries = new FormData(form);
21
+ const groups = new Map();
22
+ for (const control of form.elements) {
23
+ if (!control.name || control.matches(':disabled') || !['INPUT', 'SELECT', 'TEXTAREA'].includes(control.tagName)) continue;
24
+ if (['submit', 'button', 'reset', 'image'].includes(control.type)) continue;
25
+ if (forbidden.has(control.name)) throw new Error('Reserved field name: ' + control.name);
26
+ if (control.type === 'file') throw new Error('File inputs are not supported by WidgetCard v1.');
27
+ if (!groups.has(control.name)) groups.set(control.name, []);
28
+ groups.get(control.name).push(control);
29
+ }
30
+ const values = Object.create(null);
31
+ for (const [name, controls] of groups) {
32
+ const first = controls[0];
33
+ const declared = first.dataset.widgetType;
34
+ if (controls.some(c => c.dataset.widgetType !== declared)) throw new Error('Conflicting field types: ' + name);
35
+ const checkboxes = controls.every(c => c.type === 'checkbox');
36
+ const radio = controls.every(c => c.type === 'radio');
37
+ const array = declared === 'array' || first.multiple || (checkboxes && controls.length > 1);
38
+ const boolean = declared === 'boolean' || (checkboxes && controls.length === 1 && !array);
39
+ if (declared && !['string', 'number', 'boolean', 'array'].includes(declared)) throw new Error('Unknown field type: ' + name);
40
+ if (boolean && (!checkboxes || controls.length !== 1)) throw new Error('Boolean fields require one checkbox: ' + name);
41
+ if (controls.length > 1 && !array && !radio) throw new Error('Repeated fields must declare array type: ' + name);
42
+ const raw = entries.getAll(name);
43
+ if (raw.some(v => typeof v !== 'string')) throw new Error('Only JSON values are supported.');
44
+ const itemType = first.dataset.widgetItemType || 'string';
45
+ if (array && !['string', 'number'].includes(itemType)) throw new Error('Invalid array item type: ' + name);
46
+ const numeric = declared === 'number' || (!declared && first.type === 'number');
47
+ const convert = (value, number) => {
48
+ if (!number) return value;
49
+ if (value.trim() === '') return null;
50
+ const result = Number(value);
51
+ if (!Number.isFinite(result)) throw new Error('Invalid number: ' + name);
52
+ return result;
53
+ };
54
+ values[name] = boolean ? first.checked : array ? raw.map(v => convert(v, itemType === 'number'))
55
+ : raw.length ? convert(raw[0], numeric) : null;
56
+ }
57
+ if (new TextEncoder().encode(JSON.stringify(values)).length > 65536) throw new Error('Form result exceeds 64 KiB.');
58
+ return values;
59
+ };
60
+ const feedback = (form, text) => {
61
+ let status = form.querySelector('[data-widget-status]');
62
+ if (!status) {
63
+ status = document.createElement('p');
64
+ status.dataset.widgetStatus = '';
65
+ status.setAttribute('role', 'status');
66
+ form.append(status);
67
+ }
68
+ status.textContent = text;
69
+ };
70
+ const send = async action => {
71
+ if (sending) return;
72
+ const form = formOf();
73
+ try {
74
+ const values = action === 'submit' ? collect(form) : undefined;
75
+ const bridge = window.EvolWidgetBridge;
76
+ if (!bridge || typeof bridge.postMessage !== 'function') throw new Error('Open this form in a WidgetCard-capable EvolApp.');
77
+ sending = true;
78
+ feedback(form, 'Sending…');
79
+ const result = await bridge.postMessage(JSON.stringify({ action, ...(values ? { values } : {}) }));
80
+ if (!result || result.ok !== true) throw new Error(result && result.error || 'The App did not confirm message delivery.');
81
+ feedback(form, 'Sent.');
82
+ } catch (error) {
83
+ sending = false;
84
+ feedback(form, error.message || String(error));
85
+ form.dispatchEvent(new CustomEvent('widget:error', { detail: { message: error.message || String(error) } }));
86
+ }
87
+ };
88
+ window.EvolWidget = Object.freeze({ collect, submit: () => send('submit'), cancel: () => send('cancel'),
89
+ retry: () => { sending = false; } });
90
+ document.addEventListener('submit', event => {
91
+ if (event.target !== formOf()) return;
92
+ event.preventDefault();
93
+ void send('submit');
94
+ });
95
+ document.addEventListener('click', event => {
96
+ if (event.target.closest('[data-widget-cancel]')) { event.preventDefault(); void send('cancel'); }
97
+ });
98
+ })();`;
99
+ export function prepareWidgetHtml(data, filename) {
100
+ if (!/\.html?$/i.test(filename))
101
+ throw new Error('WidgetCard requires an HTML file');
102
+ if (data.length > MAX_WIDGET_HTML_BYTES)
103
+ throw new Error('WidgetCard HTML exceeds 1 MiB');
104
+ const html = new TextDecoder('utf-8', { fatal: true }).decode(data);
105
+ if (!html.trim() || html.includes('\0') || !/<form\b/i.test(html)) {
106
+ throw new Error('WidgetCard requires nonempty UTF-8 HTML containing a form');
107
+ }
108
+ if (/data-evol-widget-runtime/i.test(html))
109
+ throw new Error('WidgetCard HTML already contains the injected runtime');
110
+ return Buffer.from(`${html}\n<script data-evol-widget-runtime>${WIDGET_CARD_FORM_SCRIPT}</script>\n`, 'utf8');
111
+ }
5
112
  const EXT_TYPE_MAP = {
6
113
  '.png': 'image', '.jpg': 'image', '.jpeg': 'image',
7
114
  '.gif': 'image', '.webp': 'image', '.svg': 'image',
@@ -25,7 +132,7 @@ export function inferPayloadType(filename) {
25
132
  return EXT_TYPE_MAP[ext] ?? 'file';
26
133
  }
27
134
  export function isValidPayloadType(value) {
28
- return value === 'image' || value === 'video' || value === 'voice' || value === 'file';
135
+ return value === 'image' || value === 'video' || value === 'voice' || value === 'file' || value === 'widget_card';
29
136
  }
30
137
  /** 单次上传最大大小(与 daemon sendFile 和 Menu file fetch 一致)。 */
31
138
  export const MAX_AUN_ATTACHMENT_SIZE = 256 * 1024 * 1024;
@@ -43,8 +150,17 @@ export async function uploadBufferAndBuildPayload(conn, ownerAid, data, filename
43
150
  if (data.length > MAX_AUN_ATTACHMENT_SIZE) {
44
151
  throw new Error(`文件过大 (${formatSize(data.length)}, 上限 ${formatSize(MAX_AUN_ATTACHMENT_SIZE)}): ${displayFilename}`);
45
152
  }
153
+ if (opts?.as && !isValidPayloadType(opts.as)) {
154
+ throw new Error(`--as 必须是 image|video|voice|file|widget_card,收到: ${opts.as}`);
155
+ }
156
+ if (opts?.as === 'widget_card') {
157
+ if (opts.contentType && !/^text\/html(?:\s*;|$)/i.test(opts.contentType)) {
158
+ throw new Error('WidgetCard content type must be text/html');
159
+ }
160
+ data = prepareWidgetHtml(data, displayFilename);
161
+ }
46
162
  const sha256 = crypto.createHash('sha256').update(data).digest('hex');
47
- const explicitContentType = opts?.contentType?.trim() || undefined;
163
+ const explicitContentType = opts?.as === 'widget_card' ? 'text/html' : opts?.contentType?.trim() || undefined;
48
164
  // Storage keys have a narrower character set than local filenames. Keep the
49
165
  // original basename in the attachment; only the opaque storage key is sanitized.
50
166
  const storageFilename = displayFilename.replace(/[^A-Za-z0-9._-]/g, '_');
@@ -87,7 +203,7 @@ export async function uploadBufferAndBuildPayload(conn, ownerAid, data, filename
87
203
  let type;
88
204
  if (opts?.as) {
89
205
  if (!isValidPayloadType(opts.as)) {
90
- throw new Error(`--as 必须是 image|video|voice|file,收到: ${opts.as}`);
206
+ throw new Error(`--as 必须是 image|video|voice|file|widget_card,收到: ${opts.as}`);
91
207
  }
92
208
  type = opts.as;
93
209
  }
@@ -104,6 +220,10 @@ export async function uploadBufferAndBuildPayload(conn, ownerAid, data, filename
104
220
  payload.text = `📎 ${displayFilename} (${formatSize(total)})`;
105
221
  if (type === 'voice' && opts?.transcript)
106
222
  payload.transcript = opts.transcript;
223
+ if (type === 'widget_card') {
224
+ payload.title = opts?.title?.trim() || displayFilename;
225
+ payload.text = opts?.text || '请在支持 WidgetCard 的 EvolApp 中打开并填写表单。';
226
+ }
107
227
  return { payload, type, attachment };
108
228
  }
109
229
  /**
@@ -117,6 +237,9 @@ export async function uploadFileAndBuildPayload(conn, ownerAid, filePath, opts)
117
237
  throw new Error(`文件不存在: ${absPath}`);
118
238
  }
119
239
  const stat = fs.statSync(absPath);
240
+ if (opts?.as === 'widget_card' && stat.size > MAX_WIDGET_HTML_BYTES) {
241
+ throw new Error('WidgetCard HTML exceeds 1 MiB');
242
+ }
120
243
  if (stat.size === 0) {
121
244
  throw new Error(`文件为空: ${absPath}`);
122
245
  }
@@ -1 +1 @@
1
- {"id":"sha256:76e20a438d3936bb3420763f","builtAt":"2026-11-14T05:54:02.439Z"}
1
+ {"id":"sha256:3561d8e3c0e3ce13b94f99d2","builtAt":"2026-11-17T15:02:32.541Z"}