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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (249) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/bin/ecmsg.js +188 -58
  3. package/dist/agent-template/jobs.js +62 -0
  4. package/dist/agent-template/runtime.js +214 -0
  5. package/dist/agent-template/service.js +465 -0
  6. package/dist/agent-template/tool-runner.js +45 -0
  7. package/dist/agent-template/types.js +5 -0
  8. package/dist/agents/baseagent-availability.js +1 -1
  9. package/dist/agents/claude-runner.js +1 -1
  10. package/dist/agents/codex/app-server-client.js +22 -0
  11. package/dist/agents/codex-runner.js +69 -2
  12. package/dist/aun/aid/agentmd.js +56 -1
  13. package/dist/aun/aid/client.js +3 -1
  14. package/dist/aun/menu/client.js +3 -2
  15. package/dist/aun/msg/p2p.js +6 -1
  16. package/dist/channels/aun.js +277 -49
  17. package/dist/cli/agent-command.js +5 -0
  18. package/dist/cli/agent-create.js +7 -3
  19. package/dist/cli/agent-template.js +124 -0
  20. package/dist/cli/aun-commands.js +2 -2
  21. package/dist/cli/ctl-command.js +2 -1
  22. package/dist/cli/daemon-commands.js +11 -66
  23. package/dist/cli/daemon-lifecycle-client.js +61 -0
  24. package/dist/cli/ecmsg-gateway.js +35 -2
  25. package/dist/cli/events-command.js +109 -0
  26. package/dist/cli/index.js +60 -14
  27. package/dist/cli/invoke-command.js +182 -0
  28. package/dist/cli/managed-command-guard.js +6 -1
  29. package/dist/cli/net-check.js +1 -1
  30. package/dist/cli/restart-monitor.js +160 -83
  31. package/dist/cli/services-command.js +137 -0
  32. package/dist/cli/team-workspace-command.js +134 -0
  33. package/dist/cli/thread-command.js +103 -13
  34. package/dist/cli/watch-msg.js +1 -1
  35. package/dist/config/boot-log.js +8 -8
  36. package/dist/config/config-field-policy.js +2 -2
  37. package/dist/config/config-manager.js +0 -7
  38. package/dist/config/invoke-ipc-service.js +118 -0
  39. package/dist/config/schema-migration.js +45 -15
  40. package/dist/config-store.js +2 -1
  41. package/dist/core/agent-ipc-registration.js +25 -4
  42. package/dist/core/agent-reload-coordinator.js +6 -4
  43. package/dist/core/agent-runtime.js +106 -10
  44. package/dist/core/auth/delegation-authorization.js +66 -0
  45. package/dist/core/auth/operation-authorizer.js +2 -0
  46. package/dist/core/auth/operation-catalog.js +29 -0
  47. package/dist/core/baseagent-loader.js +60 -130
  48. package/dist/core/channel-loader.js +10 -1
  49. package/dist/core/channel-runtime.js +20 -12
  50. package/dist/core/command/agent-control.js +12 -2
  51. package/dist/core/command/agent-storage-menu.js +1 -1
  52. package/dist/core/command/agent-template-menu.js +147 -0
  53. package/dist/core/command/chatmode-config.js +2 -36
  54. package/dist/core/command/command-handler.js +80 -17
  55. package/dist/core/command/data-root-resolver.js +32 -23
  56. package/dist/core/command/eventcenter-menu.js +468 -0
  57. package/dist/core/command/menu-catalog.js +15 -0
  58. package/dist/core/command/menu-handler.js +216 -90
  59. package/dist/core/command/menu-protocol.js +71 -13
  60. package/dist/core/command/menu-query-batch.js +194 -0
  61. package/dist/core/command/slash-gate.js +1 -1
  62. package/dist/core/command/slash-handler.js +34 -42
  63. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  64. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  65. package/dist/core/command/team-workspace-initializer.js +2 -0
  66. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  67. package/dist/core/command/team-workspace-job-store.js +88 -0
  68. package/dist/core/command/team-workspace-management-service.js +2 -0
  69. package/dist/core/command/team-workspace-management-store.js +96 -0
  70. package/dist/core/command/team-workspace-management.js +265 -0
  71. package/dist/core/command/team-workspace-members-menu.js +88 -0
  72. package/dist/core/command/team-workspace-store.js +612 -0
  73. package/dist/core/command/team-workspace-team.js +193 -0
  74. package/dist/core/daemon-control.js +22 -5
  75. package/dist/core/daemon-lifecycle.js +323 -191
  76. package/dist/core/handoff/runtime.js +45 -13
  77. package/dist/core/invoke/executors/index.js +13 -0
  78. package/dist/core/invoke/executors/media.js +283 -0
  79. package/dist/core/invoke/executors/text.js +198 -0
  80. package/dist/core/invoke/invoke-service.js +157 -0
  81. package/dist/core/invoke/style-router.js +48 -0
  82. package/dist/core/invoke/types.js +19 -0
  83. package/dist/core/ipc-registration.js +50 -7
  84. package/dist/core/legacy-rename.js +41 -0
  85. package/dist/core/memory/consolidation.js +7 -5
  86. package/dist/core/message/aun-ipc-sender.js +252 -17
  87. package/dist/core/message/im-renderer.js +116 -85
  88. package/dist/core/message/message-bridge.js +4 -0
  89. package/dist/core/message/message-queue.js +66 -15
  90. package/dist/core/message/message-utils.js +10 -2
  91. package/dist/core/message/peer-mode.js +7 -34
  92. package/dist/core/message/pending-hints.js +29 -5
  93. package/dist/core/message/response-engine.js +194 -61
  94. package/dist/core/message/send-options.js +7 -4
  95. package/dist/core/message/send-routing.js +50 -5
  96. package/dist/core/ownership/owner-resolver.js +7 -0
  97. package/dist/core/pack-auth.js +94 -0
  98. package/dist/core/pack-install.js +194 -0
  99. package/dist/core/permission/ec-command-parser.js +51 -17
  100. package/dist/core/permission/protected-paths.js +12 -2
  101. package/dist/core/permission/shell-environment.js +9 -0
  102. package/dist/core/rate-window.js +48 -0
  103. package/dist/core/relation/peer-identity.js +28 -0
  104. package/dist/core/session/session-file-health.js +243 -0
  105. package/dist/core/session/session-fs-store.js +67 -28
  106. package/dist/core/session/session-idle-monitor.js +59 -19
  107. package/dist/core/session/session-manager.js +13 -4
  108. package/dist/core/task/task-recovery-service.js +13 -2
  109. package/dist/core/thread/command-parser.js +9 -2
  110. package/dist/core/thread/thread-operation.js +21 -2
  111. package/dist/core/thread/thread-route.js +13 -2
  112. package/dist/core/thread/thread-service.js +52 -3
  113. package/dist/directory/owner-directory-admission.js +40 -53
  114. package/dist/directory/owner-directory-cache.js +89 -113
  115. package/dist/directory/owner-directory-query-operation.js +8 -10
  116. package/dist/eck/kit-renderer.js +7 -5
  117. package/dist/eck/message-renderer.js +2 -0
  118. package/dist/ecweb/basic-settings-service.js +1 -1
  119. package/dist/ecweb/message-context-service.js +0 -4
  120. package/dist/ecweb/runtime/lifecycle.js +6 -2
  121. package/dist/ecweb/runtime/supervisor.js +19 -4
  122. package/dist/event-center/admission-materializer.js +124 -0
  123. package/dist/event-center/bus-gate.js +154 -0
  124. package/dist/event-center/bus-host.js +307 -0
  125. package/dist/event-center/bus-resolver.js +120 -0
  126. package/dist/event-center/center-config.js +127 -0
  127. package/dist/event-center/daemon.js +44 -0
  128. package/dist/event-center/directory-source.js +55 -0
  129. package/dist/event-center/dispatcher.js +157 -0
  130. package/dist/event-center/event-log.js +110 -0
  131. package/dist/event-center/index-generator.js +73 -0
  132. package/dist/event-center/ipc-operation.js +423 -0
  133. package/dist/event-center/ledger.js +52 -0
  134. package/dist/event-center/pack-loader.js +207 -0
  135. package/dist/event-center/pack-manager.js +85 -0
  136. package/dist/event-center/registry.js +463 -0
  137. package/dist/event-center/runtime.js +837 -0
  138. package/dist/event-center/script-runner.js +356 -0
  139. package/dist/event-center/types.js +51 -0
  140. package/dist/event-center/validation.js +435 -0
  141. package/dist/index.js +424 -135
  142. package/dist/ipc.js +106 -12
  143. package/dist/paths.js +20 -0
  144. package/dist/product.js +14 -0
  145. package/dist/proxy/manager.js +5 -1
  146. package/dist/proxy/service-supervisor.js +13 -4
  147. package/dist/response-system/engines/v1/index.js +0 -1
  148. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  149. package/dist/response-system/modes/single-session/index.js +1 -1
  150. package/dist/services/dispatcher.js +100 -0
  151. package/dist/services/idempotency.js +90 -0
  152. package/dist/services/identity.js +52 -0
  153. package/dist/services/index-generator.js +70 -0
  154. package/dist/services/index.js +449 -0
  155. package/dist/services/ipc-operation.js +550 -0
  156. package/dist/services/ledger.js +52 -0
  157. package/dist/services/message-log.js +112 -0
  158. package/dist/services/pack-manager.js +215 -0
  159. package/dist/services/reply.js +55 -0
  160. package/dist/services/router.js +98 -0
  161. package/dist/services/script-runner.js +422 -0
  162. package/dist/services/service-payload.js +70 -0
  163. package/dist/services/types.js +18 -0
  164. package/dist/services/validation.js +297 -0
  165. package/dist/trigger/application-service.js +18 -0
  166. package/dist/trigger/event-source.js +1 -1
  167. package/dist/trigger/ipc-service.js +3 -1
  168. package/dist/trigger/scheduler.js +38 -0
  169. package/dist/trigger/script-sandbox.js +170 -24
  170. package/dist/utils/cross-platform.js +24 -10
  171. package/dist/utils/evolcore-version.js +69 -27
  172. package/dist/utils/instance-registry.js +19 -13
  173. package/dist/utils/npm-ops.js +2 -1
  174. package/dist/utils/package-version-info.js +6 -3
  175. package/dist/utils/process-introspect.js +45 -9
  176. package/dist/utils/startup-trace.js +74 -37
  177. package/dist/utils/windows-shell-trust.js +80 -6
  178. package/kits/docs/INDEX.md +2 -2
  179. package/kits/docs/aun/ABILITY_CALLING.md +9 -15
  180. package/kits/docs/context-assembly.md +1 -1
  181. package/kits/docs/evolcore/INDEX.md +3 -1
  182. package/kits/docs/evolcore/ability.md +4 -0
  183. package/kits/docs/evolcore/agent.md +22 -1
  184. package/kits/docs/evolcore/aid.md +1 -1
  185. package/kits/docs/evolcore/event-center.md +227 -0
  186. package/kits/docs/evolcore/file-navigation.md +10 -264
  187. package/kits/docs/evolcore/fs.md +5 -3
  188. package/kits/docs/evolcore/group.md +1 -1
  189. package/kits/docs/evolcore/memory-architecture.md +2 -0
  190. package/kits/docs/evolcore/menu-protocol.md +28 -1
  191. package/kits/docs/evolcore/msg.md +21 -9
  192. package/kits/docs/evolcore/provider.md +3 -1
  193. package/kits/docs/evolcore/response.md +5 -5
  194. package/kits/docs/evolcore/services.md +294 -0
  195. package/kits/docs/evolcore/task.md +2 -0
  196. package/kits/docs/evolcore/team-workspace.md +41 -0
  197. package/kits/docs/evolcore/thread-chain.md +15 -3
  198. package/kits/eck_manifest.json +26 -0
  199. package/kits/rules/02-navigation.md +10 -1
  200. package/kits/rules/06-channel.md +1 -0
  201. package/kits/schemas/_meta.json +17 -6
  202. package/kits/schemas/agent-config.schema.19.json +5 -7
  203. package/kits/schemas/agent-config.schema.20.json +936 -0
  204. package/kits/schemas/relation-config.schema.12.json +2 -3
  205. package/kits/schemas/role-config.schema.2.json +4 -4
  206. package/kits/skills/.switches.json +1 -5
  207. package/kits/skills/ability/SKILL.md +56 -0
  208. package/kits/skills/ability/references/calling.md +56 -0
  209. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  210. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  211. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  212. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  213. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  214. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  215. package/kits/skills/ec-group/SKILL.md +5 -8
  216. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  217. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  218. package/kits/skills/ec-trigger/SKILL.md +4 -4
  219. package/kits/skills/personal-assistant/SKILL.md +6 -6
  220. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  221. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  222. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  223. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  224. package/kits/skills/thread-ops/SKILL.md +10 -10
  225. package/kits/templates/message-fragments/item.md +1 -1
  226. package/kits/templates/system-fragments/channel.md +3 -3
  227. package/kits/templates/system-fragments/commands.md +5 -3
  228. package/kits/templates/system-fragments/reply.md +1 -5
  229. package/kits/templates/system-fragments/thread.md +13 -10
  230. package/package.json +5 -6
  231. package/scripts/agent-template/index.mjs +40 -0
  232. package/scripts/agent-template/inspect.mjs +240 -0
  233. package/scripts/agent-template/overlay.mjs +71 -0
  234. package/scripts/agent-template/pack.mjs +169 -0
  235. package/scripts/agent-template/shared/common.mjs +235 -0
  236. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  237. package/scripts/agent-template/shared/plan.mjs +129 -0
  238. package/scripts/agent-template/shared/team-schema.json +70 -0
  239. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  240. package/scripts/agent-template/shared/template-package.mjs +265 -0
  241. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  242. package/scripts/agent-template/shared/template.mjs +142 -0
  243. package/dist/cli/pa-workspace-command.js +0 -225
  244. package/dist/core/command/pa-workspace-store.js +0 -468
  245. package/dist/core/relation/pa-team.js +0 -132
  246. package/kits/docs/evolcore/pa-workspace.md +0 -51
  247. package/kits/skills/aid-ability/SKILL.md +0 -244
  248. package/kits/skills/ec-ability/SKILL.md +0 -67
  249. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -264,13 +264,15 @@ export class HandoffRuntime {
264
264
  }
265
265
  return response;
266
266
  }
267
- async enqueueOrigin(selfAid, handoffId, resultId) {
267
+ async enqueueOrigin(selfAid, handoffId, resultId, recovery) {
268
268
  const operationSequence = ++this.lifecycleSequence;
269
269
  await this.mutexes.forKey(this.returnKey(selfAid, handoffId)).runExclusive(async () => {
270
- await this.enqueueOriginUnlocked(selfAid, handoffId, resultId, operationSequence);
270
+ await this.enqueueOriginUnlocked(selfAid, handoffId, resultId, operationSequence, recovery);
271
271
  });
272
272
  }
273
- async enqueueOriginUnlocked(selfAid, handoffId, resultId, operationSequence) {
273
+ async enqueueOriginUnlocked(selfAid, handoffId, resultId, operationSequence, recovery) {
274
+ if (recovery?.isCancelled?.())
275
+ return;
274
276
  const instance = this.store.get(selfAid, handoffId);
275
277
  const result = resultId
276
278
  ? instance?.return_results?.find(item => item.result_id === resultId)
@@ -286,11 +288,15 @@ export class HandoffRuntime {
286
288
  if (!instance || !deliveryContent)
287
289
  return;
288
290
  const origin = await this.sessionManager.getSessionById(instance.origin_session_id);
291
+ if (recovery?.isCancelled?.())
292
+ return;
289
293
  if (!origin) {
290
294
  if (result)
291
295
  this.store.recordOriginResultEnqueueFailed(selfAid, handoffId, result.result_id, 'origin session not found');
292
296
  else
293
297
  this.store.recordOriginEnqueueFailed(selfAid, handoffId, 'origin session not found');
298
+ if (recovery?.prioritizeOrigin)
299
+ throw new Error(`Handoff origin session not found: ${instance.origin_session_id}`);
294
300
  return;
295
301
  }
296
302
  if ((this.sessionDiscardSequence.get(this.sessionKey(selfAid, instance.origin_session_id)) ?? 0) > operationSequence) {
@@ -339,6 +345,7 @@ export class HandoffRuntime {
339
345
  };
340
346
  try {
341
347
  await this.messageQueue.enqueuePersisted(origin.id, message, origin.projectPath, {
348
+ priority: recovery?.prioritizeOrigin,
342
349
  interruptible: false,
343
350
  interruptSamePeer: false,
344
351
  agentName: selfAid,
@@ -372,6 +379,8 @@ export class HandoffRuntime {
372
379
  else if (current?.state === 'origin_queued') {
373
380
  this.store.recordOriginEnqueueFailed(selfAid, handoffId, error instanceof Error ? error.message : String(error));
374
381
  }
382
+ if (recovery?.prioritizeOrigin)
383
+ throw error;
375
384
  }
376
385
  }
377
386
  isOriginDeliveryPending(instance, resultId) {
@@ -664,7 +673,7 @@ export class HandoffRuntime {
664
673
  }
665
674
  return discarded;
666
675
  }
667
- async discardExpiredCandidates(selfAid, snapshots, retentionMs = HANDOFF_RETENTION_MS) {
676
+ async discardExpiredCandidates(selfAid, snapshots, retentionMs = HANDOFF_RETENTION_MS, isCancelled) {
668
677
  const now = this.now?.() ?? Date.now();
669
678
  const candidates = snapshots.filter(instance => !['failed', 'completed', 'discarded'].includes(instance.state)
670
679
  && now - instance.created_at >= retentionMs);
@@ -681,12 +690,14 @@ export class HandoffRuntime {
681
690
  }
682
691
  for (const instance of candidates) {
683
692
  await yieldToIo();
693
+ if (isCancelled?.())
694
+ break;
684
695
  if ((latestEventVersions.get(instance.handoff_id) ?? 0) !== instance.version)
685
696
  continue;
686
697
  const result = await this.discardWithTargetLock(selfAid, instance.handoff_id, 'retention_expired', {
687
698
  retention_ms: retentionMs,
688
699
  age_ms: now - instance.created_at,
689
- }, instance.version, now);
700
+ }, instance.version, now, isCancelled);
690
701
  if (result) {
691
702
  discarded++;
692
703
  logger.info(`[Handoff] discarded expired handoff: ${instance.handoff_id}`);
@@ -695,17 +706,23 @@ export class HandoffRuntime {
695
706
  return discarded;
696
707
  }
697
708
  async prepareRecovery(selfAid, options = {}) {
709
+ if (options.isCancelled?.())
710
+ return [];
698
711
  let started = Date.now();
699
712
  let scanDetail;
700
713
  const snapshots = options.snapshots ?? await this.store.listAsync(selfAid, stats => {
701
714
  scanDetail = Object.entries(stats).map(([key, value]) => `${key}=${Math.round(value)}`).join('; ');
702
715
  });
703
- options.onPhase?.('scan', started, Date.now(), scanDetail);
716
+ options.onPhase?.('scan', started, Date.now(), scanDetail, options.snapshots ? 'skipped' : 'ok');
717
+ if (options.isCancelled?.())
718
+ return [];
704
719
  started = Date.now();
705
720
  if (options.discardExpired !== false)
706
- await this.discardExpiredCandidates(selfAid, snapshots);
721
+ await this.discardExpiredCandidates(selfAid, snapshots, HANDOFF_RETENTION_MS, options.isCancelled);
707
722
  for (const snapshot of snapshots.filter(instance => instance.state === 'queued'
708
723
  || (instance.return_policy === 'none' && instance.state === 'return_pending'))) {
724
+ if (options.isCancelled?.())
725
+ break;
709
726
  // Only legacy return=none entries can need this migration. Its store
710
727
  // method rechecks the current state before changing anything.
711
728
  if (snapshot.return_policy === 'none' && snapshot.state === 'return_pending') {
@@ -715,7 +732,7 @@ export class HandoffRuntime {
715
732
  this.dispatcher.expireQueued(selfAid, undefined, [snapshot]);
716
733
  await yieldToIo();
717
734
  }
718
- options.onPhase?.('cleanup', started, Date.now());
735
+ options.onPhase?.('cleanup', started, Date.now(), undefined, snapshots.length ? 'ok' : 'skipped');
719
736
  return snapshots;
720
737
  }
721
738
  async recover(selfAids, options = {}) {
@@ -808,25 +825,40 @@ export class HandoffRuntime {
808
825
  }
809
826
  }
810
827
  else if (instance.state === 'origin_queued') {
811
- originEnqueues.push(this.enqueueOrigin(selfAid, instance.handoff_id));
828
+ const handoffId = instance.handoff_id;
829
+ originEnqueues.push(() => this.enqueueOrigin(selfAid, handoffId, undefined, options));
812
830
  }
813
831
  else if (Array.isArray(instance.return_results)) {
814
832
  for (const result of instance.return_results.filter(item => item.state === 'origin_queued')) {
815
- originEnqueues.push(this.enqueueOrigin(selfAid, instance.handoff_id, result.result_id));
833
+ const handoffId = instance.handoff_id;
834
+ originEnqueues.push(() => this.enqueueOrigin(selfAid, handoffId, result.result_id, options));
816
835
  }
817
836
  }
818
837
  }
819
838
  options.onPhase?.('reconcile', started, Date.now());
820
839
  }
821
840
  const started = Date.now();
822
- await Promise.all(originEnqueues);
823
- options.onPhase?.('origin', started, Date.now());
841
+ // Register startup results in snapshot/result order while the session gate
842
+ // is held. Deferring execution until here also keeps origin I/O out of the
843
+ // reconciliation measurement and observes failed writes immediately.
844
+ if (options.prioritizeOrigin) {
845
+ for (const enqueue of originEnqueues) {
846
+ if (options.isCancelled?.())
847
+ break;
848
+ await enqueue();
849
+ }
850
+ }
851
+ else
852
+ await Promise.all(originEnqueues.map(enqueue => enqueue()));
853
+ options.onPhase?.('origin', started, Date.now(), undefined, originEnqueues.length ? 'ok' : 'skipped');
824
854
  }
825
- async discardWithTargetLock(selfAid, handoffId, reason, details, expectedVersion, now = this.now?.()) {
855
+ async discardWithTargetLock(selfAid, handoffId, reason, details, expectedVersion, now = this.now?.(), isCancelled) {
826
856
  const snapshot = this.store.get(selfAid, handoffId);
827
857
  if (!snapshot)
828
858
  return false;
829
859
  const discarded = await this.mutexes.forKey(this.targetKey(selfAid, snapshot.target_session_id)).runExclusive(async () => {
860
+ if (isCancelled?.())
861
+ return null;
830
862
  const current = this.store.get(selfAid, handoffId);
831
863
  if (!current || current.state === 'failed' || current.state === 'completed' || current.state === 'discarded') {
832
864
  return null;
@@ -0,0 +1,13 @@
1
+ import { TEXT_EXECUTORS } from './text.js';
2
+ import { MEDIA_EXECUTORS } from './media.js';
3
+ /**
4
+ * 全部内置执行器。
5
+ *
6
+ * 新增内置形态时在这里登记,并在 `style-router.ts` 的路由说明里同步。
7
+ * 路由是显式的,不做动态探测。
8
+ */
9
+ export const BUILTIN_EXECUTORS = [
10
+ ...TEXT_EXECUTORS,
11
+ ...MEDIA_EXECUTORS,
12
+ ];
13
+ export { TEXT_EXECUTORS, MEDIA_EXECUTORS };
@@ -0,0 +1,283 @@
1
+ /**
2
+ * 多模态内置执行器:openai-images / openai-audio(speech|transcribe) / openai-embeddings。
3
+ *
4
+ * 设计见 `docs/model-intent/invoke-design.md` 第十节。
5
+ *
6
+ * 产物统一归一成 `InvokeArtifact`:端点返回 URL、返回 base64、还是直接回二进制,
7
+ * 调用方看到的都是同一个结构。落盘位置**只由调用方的 `--out` 决定**,
8
+ * 执行器不自己挑路径。
9
+ */
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { appendRequestPath, appendRequestQueryParams } from '../../../agents/request-identity.js';
13
+ import { InvokeError } from '../types.js';
14
+ const MIME_EXTENSION = {
15
+ 'image/png': '.png',
16
+ 'image/jpeg': '.jpg',
17
+ 'image/webp': '.webp',
18
+ 'image/gif': '.gif',
19
+ 'audio/mpeg': '.mp3',
20
+ 'audio/wav': '.wav',
21
+ 'audio/opus': '.opus',
22
+ 'audio/aac': '.aac',
23
+ 'audio/flac': '.flac',
24
+ 'video/mp4': '.mp4',
25
+ 'application/json': '.json',
26
+ };
27
+ function extensionFor(mimeType, fallback) {
28
+ return (mimeType && MIME_EXTENSION[mimeType]) ?? fallback;
29
+ }
30
+ function asRecord(value) {
31
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
32
+ throw new InvokeError('INVALID_INPUT', 'invoke input must be a JSON object');
33
+ }
34
+ return value;
35
+ }
36
+ async function fetchOnce(url, init, options) {
37
+ const timeout = AbortSignal.timeout(options.timeoutMs);
38
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
39
+ try {
40
+ return await fetch(url, { ...init, signal });
41
+ }
42
+ catch (error) {
43
+ if (error?.name === 'AbortError' && options.signal?.aborted) {
44
+ throw new InvokeError('ABORTED', 'Invoke was aborted');
45
+ }
46
+ throw new InvokeError('TRANSPORT_ERROR', error?.message ?? 'Network request failed');
47
+ }
48
+ }
49
+ async function parseFailure(response) {
50
+ let raw = '';
51
+ try {
52
+ raw = await response.text();
53
+ }
54
+ catch { }
55
+ let detail = raw;
56
+ try {
57
+ const body = JSON.parse(raw);
58
+ detail = body?.error?.message || body?.message || body?.detail || raw;
59
+ }
60
+ catch { }
61
+ const code = response.status >= 500 ? 'UPSTREAM_ERROR' : 'UPSTREAM_REJECTED';
62
+ const suffix = detail ? `: ${String(detail).slice(0, 500)}` : '';
63
+ return new InvokeError(code, `Endpoint returned HTTP ${response.status}${suffix}`, { status: response.status });
64
+ }
65
+ /**
66
+ * 把一段产物写到 `--out`。
67
+ *
68
+ * `outPath` 是文件时只允许一个产物;多个产物时把它当目录,按序号命名。
69
+ */
70
+ function writeArtifact(input) {
71
+ if (!input.outPath)
72
+ return undefined;
73
+ let target = input.outPath;
74
+ if (input.count === 1 && !input.outPath.endsWith(path.sep) && !input.outPath.endsWith('/')) {
75
+ target = input.outPath;
76
+ }
77
+ else {
78
+ const directory = input.outPath;
79
+ fs.mkdirSync(directory, { recursive: true });
80
+ const ext = extensionFor(input.mimeType, input.fallbackExt);
81
+ target = path.join(directory, `${path.basename(directory)}-${input.index + 1}${ext}`);
82
+ }
83
+ fs.mkdirSync(path.dirname(target), { recursive: true });
84
+ fs.writeFileSync(target, input.data);
85
+ return target;
86
+ }
87
+ async function materialize(outPath, source, options, meta) {
88
+ if (source.base64) {
89
+ const data = Buffer.from(source.base64, 'base64');
90
+ const mimeType = meta.mimeType ?? 'application/octet-stream';
91
+ const file = writeArtifact({ outPath, data, mimeType, fallbackExt: meta.fallbackExt, index: meta.index, count: meta.count });
92
+ return { kind: meta.kind, ...(file ? { path: file } : {}), mimeType, bytes: data.byteLength };
93
+ }
94
+ if (source.url) {
95
+ if (!outPath)
96
+ return { kind: meta.kind, url: source.url, ...(meta.mimeType ? { mimeType: meta.mimeType } : {}) };
97
+ // 端点只给了 URL,需要下载后才落盘。
98
+ const response = await fetchOnce(source.url, { method: 'GET' }, options);
99
+ if (!response.ok)
100
+ throw await parseFailure(response);
101
+ const data = Buffer.from(await response.arrayBuffer());
102
+ const mimeType = meta.mimeType ?? response.headers.get('content-type') ?? 'application/octet-stream';
103
+ const file = writeArtifact({ outPath, data, mimeType, fallbackExt: meta.fallbackExt, index: meta.index, count: meta.count });
104
+ return { kind: meta.kind, ...(file ? { path: file } : {}), url: source.url, mimeType, bytes: data.byteLength };
105
+ }
106
+ throw new InvokeError('EMPTY_RESPONSE', 'Endpoint returned neither a URL nor inline data');
107
+ }
108
+ /** openai-images:`POST /v1/images/generations`。 */
109
+ export const openaiImagesExecutor = {
110
+ id: 'builtin:openai-images',
111
+ handles: ['openai-images'],
112
+ services: ['image', 'images'],
113
+ async invoke(context, options) {
114
+ const input = asRecord(context.input);
115
+ const prompt = input.prompt ?? input.input;
116
+ if (typeof prompt !== 'string' || !prompt.trim()) {
117
+ throw new InvokeError('INVALID_INPUT', 'image generation requires a non-empty "prompt"');
118
+ }
119
+ const n = typeof input.n === 'number' && input.n > 0 ? Math.min(input.n, 10) : 1;
120
+ const response = await fetchOnce(appendRequestQueryParams(appendRequestPath(context.provider.baseUrl, 'images/generations'), context.provider.queryParams), {
121
+ method: 'POST',
122
+ headers: {
123
+ 'Content-Type': 'application/json',
124
+ ...(context.provider.apiKey ? { Authorization: `Bearer ${context.provider.apiKey}` } : {}),
125
+ ...context.provider.headers,
126
+ },
127
+ body: JSON.stringify({
128
+ model: context.model,
129
+ prompt,
130
+ n,
131
+ ...(input.size ? { size: input.size } : {}),
132
+ ...(input.quality ? { quality: input.quality } : {}),
133
+ ...(input.style ? { style: input.style } : {}),
134
+ ...(context.outPath ? { response_format: 'b64_json' } : {}),
135
+ }),
136
+ }, options);
137
+ if (!response.ok)
138
+ throw await parseFailure(response);
139
+ const body = await response.json();
140
+ const rows = Array.isArray(body?.data) ? body.data : [];
141
+ if (!rows.length)
142
+ throw new InvokeError('EMPTY_RESPONSE', 'Image endpoint returned no data');
143
+ // 生图端点一般不回 content-type;按请求的输出格式推断,缺省 png。
144
+ const requestedFormat = typeof input.output_format === 'string'
145
+ ? input.output_format
146
+ : typeof input.response_format === 'string' ? input.response_format : 'png';
147
+ const imageMime = requestedFormat === 'jpeg' || requestedFormat === 'jpg' ? 'image/jpeg'
148
+ : requestedFormat === 'webp' ? 'image/webp'
149
+ : 'image/png';
150
+ const artifacts = [];
151
+ for (const [index, row] of rows.entries()) {
152
+ artifacts.push(await materialize(context.outPath, {
153
+ url: typeof row?.url === 'string' ? row.url : undefined,
154
+ base64: typeof row?.b64_json === 'string' ? row.b64_json : undefined,
155
+ }, options, { kind: 'image', mimeType: imageMime, index, count: rows.length, fallbackExt: '.png' }));
156
+ }
157
+ return { output: body, artifacts, latencyMs: 0 };
158
+ },
159
+ };
160
+ /** openai-audio(speech):`POST /v1/audio/speech`,返回音频二进制。 */
161
+ export const openaiSpeechExecutor = {
162
+ id: 'builtin:openai-speech',
163
+ handles: ['openai-audio', 'openai-speech'],
164
+ services: ['speech', 'tts'],
165
+ async invoke(context, options) {
166
+ const input = asRecord(context.input);
167
+ const text = input.text ?? input.input;
168
+ if (typeof text !== 'string' || !text.trim()) {
169
+ throw new InvokeError('INVALID_INPUT', 'speech synthesis requires a non-empty "text"');
170
+ }
171
+ const response = await fetchOnce(appendRequestQueryParams(appendRequestPath(context.provider.baseUrl, 'audio/speech'), context.provider.queryParams), {
172
+ method: 'POST',
173
+ headers: {
174
+ 'Content-Type': 'application/json',
175
+ ...(context.provider.apiKey ? { Authorization: `Bearer ${context.provider.apiKey}` } : {}),
176
+ ...context.provider.headers,
177
+ },
178
+ body: JSON.stringify({
179
+ model: context.model,
180
+ input: text,
181
+ ...(input.voice ? { voice: input.voice } : {}),
182
+ ...(input.format ? { response_format: input.format } : {}),
183
+ ...(input.speed ? { speed: input.speed } : {}),
184
+ }),
185
+ }, options);
186
+ if (!response.ok)
187
+ throw await parseFailure(response);
188
+ const data = Buffer.from(await response.arrayBuffer());
189
+ const mimeType = response.headers.get('content-type') ?? 'audio/mpeg';
190
+ const file = writeArtifact({
191
+ outPath: context.outPath, data, mimeType, fallbackExt: '.mp3', index: 0, count: 1,
192
+ });
193
+ return {
194
+ output: { bytes: data.byteLength, mimeType },
195
+ artifacts: [{ kind: 'audio', ...(file ? { path: file } : {}), mimeType, bytes: data.byteLength }],
196
+ latencyMs: 0,
197
+ };
198
+ },
199
+ };
200
+ /** openai-audio(transcription):`POST /v1/audio/transcriptions`,multipart 上传。 */
201
+ export const openaiTranscriptionExecutor = {
202
+ id: 'builtin:openai-transcribe',
203
+ handles: ['openai-audio', 'openai-transcribe'],
204
+ services: ['transcribe', 'transcription', 'stt'],
205
+ async invoke(context, options) {
206
+ const input = asRecord(context.input);
207
+ const filePath = typeof input.file === 'string' ? input.file : undefined;
208
+ if (!filePath)
209
+ throw new InvokeError('INVALID_INPUT', 'transcription requires "file" (absolute path)');
210
+ if (!path.isAbsolute(filePath))
211
+ throw new InvokeError('INVALID_INPUT', 'transcription "file" must be an absolute path');
212
+ let data;
213
+ try {
214
+ data = fs.readFileSync(filePath);
215
+ }
216
+ catch (error) {
217
+ throw new InvokeError('INVALID_INPUT', `cannot read audio file: ${error.message}`);
218
+ }
219
+ const form = new FormData();
220
+ // Uint8Array 的底层 buffer 类型与 BlobPart 对齐;直接用 Buffer 会因
221
+ // ArrayBufferLike 的 SharedArrayBuffer 分支报类型不兼容。
222
+ form.append('file', new Blob([new Uint8Array(data)]), path.basename(filePath));
223
+ form.append('model', context.model);
224
+ if (typeof input.language === 'string')
225
+ form.append('language', input.language);
226
+ if (typeof input.prompt === 'string')
227
+ form.append('prompt', input.prompt);
228
+ if (typeof input.response_format === 'string')
229
+ form.append('response_format', input.response_format);
230
+ const response = await fetchOnce(appendRequestQueryParams(appendRequestPath(context.provider.baseUrl, 'audio/transcriptions'), context.provider.queryParams), {
231
+ method: 'POST',
232
+ headers: {
233
+ ...(context.provider.apiKey ? { Authorization: `Bearer ${context.provider.apiKey}` } : {}),
234
+ ...context.provider.headers,
235
+ },
236
+ body: form,
237
+ }, options);
238
+ if (!response.ok)
239
+ throw await parseFailure(response);
240
+ const text = await response.text();
241
+ let output = text;
242
+ try {
243
+ output = JSON.parse(text);
244
+ }
245
+ catch { }
246
+ return { output, latencyMs: 0 };
247
+ },
248
+ };
249
+ /** openai-embeddings:`POST /v1/embeddings`。 */
250
+ export const openaiEmbeddingsExecutor = {
251
+ id: 'builtin:openai-embeddings',
252
+ handles: ['openai-embeddings'],
253
+ services: ['embedding', 'embeddings'],
254
+ async invoke(context, options) {
255
+ const input = asRecord(context.input);
256
+ const value = input.input ?? input.text;
257
+ if (value === undefined)
258
+ throw new InvokeError('INVALID_INPUT', 'embeddings require "input"');
259
+ const response = await fetchOnce(appendRequestQueryParams(appendRequestPath(context.provider.baseUrl, 'embeddings'), context.provider.queryParams), {
260
+ method: 'POST',
261
+ headers: {
262
+ 'Content-Type': 'application/json',
263
+ ...(context.provider.apiKey ? { Authorization: `Bearer ${context.provider.apiKey}` } : {}),
264
+ ...context.provider.headers,
265
+ },
266
+ body: JSON.stringify({
267
+ model: context.model,
268
+ input: value,
269
+ ...(input.dimensions ? { dimensions: input.dimensions } : {}),
270
+ ...(input.encoding_format ? { encoding_format: input.encoding_format } : {}),
271
+ }),
272
+ }, options);
273
+ if (!response.ok)
274
+ throw await parseFailure(response);
275
+ return { output: await response.json(), latencyMs: 0 };
276
+ },
277
+ };
278
+ export const MEDIA_EXECUTORS = [
279
+ openaiImagesExecutor,
280
+ openaiSpeechExecutor,
281
+ openaiTranscriptionExecutor,
282
+ openaiEmbeddingsExecutor,
283
+ ];
@@ -0,0 +1,198 @@
1
+ /**
2
+ * 文本类内置执行器:claude / codex / openai-compatible / systemone / gemini。
3
+ *
4
+ * 这些执行器**不复用** `text-inference.ts` 里为 runner 设计的
5
+ * `TextInferenceProvider.completeText`——那条路径把 `max_tokens`、system/user
6
+ * 双段消息等业务假设写死了。`ec invoke` 是通用入口,入参由调用方直接给出,
7
+ * 所以这里按 style 组装**原生请求体**,只做「发送 + 解析」。
8
+ */
9
+ import { appendRequestPath, appendV1RequestPath, appendRequestQueryParams, } from '../../../agents/request-identity.js';
10
+ import { InvokeError } from '../types.js';
11
+ /** 单次尝试的超时包装。 */
12
+ async function fetchOnce(url, init, options) {
13
+ const timeout = AbortSignal.timeout(options.timeoutMs);
14
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
15
+ try {
16
+ return await fetch(url, { ...init, signal });
17
+ }
18
+ catch (error) {
19
+ if (error?.name === 'AbortError' && options.signal?.aborted) {
20
+ throw new InvokeError('ABORTED', 'Invoke was aborted');
21
+ }
22
+ // 网络错误统一成可重试的传输层错误。
23
+ throw new InvokeError('TRANSPORT_ERROR', error?.message ?? 'Network request failed');
24
+ }
25
+ }
26
+ /** 解析失败响应,保留状态码供重试判定。 */
27
+ async function parseFailure(response) {
28
+ let raw = '';
29
+ try {
30
+ raw = await response.text();
31
+ }
32
+ catch { }
33
+ let detail = raw;
34
+ try {
35
+ const body = JSON.parse(raw);
36
+ detail = body?.error?.message || body?.message || body?.detail || raw;
37
+ }
38
+ catch { }
39
+ const code = response.status >= 500 ? 'UPSTREAM_ERROR' : 'UPSTREAM_REJECTED';
40
+ const suffix = detail ? `: ${String(detail).slice(0, 500)}` : '';
41
+ return new InvokeError(code, `Endpoint returned HTTP ${response.status}${suffix}`, { status: response.status });
42
+ }
43
+ function asRecord(value) {
44
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
45
+ throw new InvokeError('INVALID_INPUT', 'invoke input must be a JSON object');
46
+ }
47
+ return value;
48
+ }
49
+ function stringArray(value) {
50
+ if (!Array.isArray(value))
51
+ return undefined;
52
+ return value.filter((item) => !!item && typeof item === 'object');
53
+ }
54
+ /** claude / anthropic:`POST /v1/messages`。 */
55
+ export const anthropicExecutor = {
56
+ id: 'builtin:claude',
57
+ handles: ['claude', 'anthropic'],
58
+ services: ['*'],
59
+ async invoke(context, options) {
60
+ const input = asRecord(context.input);
61
+ const endpoint = appendV1RequestPath(context.provider.baseUrl, 'messages');
62
+ const response = await fetchOnce(appendRequestQueryParams(endpoint, context.provider.queryParams), {
63
+ method: 'POST',
64
+ headers: {
65
+ 'Content-Type': 'application/json',
66
+ 'anthropic-version': '2023-06-01',
67
+ ...(context.provider.apiKey ? { 'x-api-key': context.provider.apiKey } : {}),
68
+ ...context.provider.headers,
69
+ },
70
+ body: JSON.stringify({
71
+ model: context.model,
72
+ max_tokens: typeof input.max_tokens === 'number' ? input.max_tokens : 1024,
73
+ ...(input.system !== undefined ? { system: input.system } : {}),
74
+ messages: input.messages ?? [{ role: 'user', content: String(input.input ?? input.prompt ?? '') }],
75
+ ...(input.effort ? { output_config: { effort: input.effort } } : {}),
76
+ }),
77
+ }, options);
78
+ if (!response.ok)
79
+ throw await parseFailure(response);
80
+ return { output: await response.json(), latencyMs: 0 };
81
+ },
82
+ };
83
+ /** codex / openai-responses:`POST /v1/responses`。 */
84
+ export const openaiResponsesExecutor = {
85
+ id: 'builtin:codex',
86
+ handles: ['codex', 'openai-responses'],
87
+ services: ['*'],
88
+ async invoke(context, options) {
89
+ const input = asRecord(context.input);
90
+ const endpoint = appendRequestPath(context.provider.baseUrl, 'responses');
91
+ const response = await fetchOnce(appendRequestQueryParams(endpoint, context.provider.queryParams), {
92
+ method: 'POST',
93
+ headers: {
94
+ 'Content-Type': 'application/json',
95
+ ...(context.provider.apiKey ? { Authorization: `Bearer ${context.provider.apiKey}` } : {}),
96
+ ...context.provider.headers,
97
+ },
98
+ body: JSON.stringify({
99
+ model: context.model,
100
+ ...(input.instructions !== undefined ? { instructions: input.instructions } : {}),
101
+ input: input.input ?? String(input.prompt ?? ''),
102
+ store: input.store === true,
103
+ max_output_tokens: typeof input.max_output_tokens === 'number' ? input.max_output_tokens : 1024,
104
+ ...(input.effort ? { reasoning: { effort: input.effort } } : {}),
105
+ }),
106
+ }, options);
107
+ if (!response.ok)
108
+ throw await parseFailure(response);
109
+ return { output: await response.json(), latencyMs: 0 };
110
+ },
111
+ };
112
+ /** openai-compatible:`POST /v1/chat/completions`。 */
113
+ export const openaiCompatibleExecutor = {
114
+ id: 'builtin:openai-compatible',
115
+ handles: ['openai-compatible'],
116
+ services: ['*'],
117
+ async invoke(context, options) {
118
+ const input = asRecord(context.input);
119
+ const endpoint = appendRequestPath(context.provider.baseUrl, 'chat/completions');
120
+ const response = await fetchOnce(appendRequestQueryParams(endpoint, context.provider.queryParams), {
121
+ method: 'POST',
122
+ headers: {
123
+ 'Content-Type': 'application/json',
124
+ ...(context.provider.apiKey ? { Authorization: `Bearer ${context.provider.apiKey}` } : {}),
125
+ ...context.provider.headers,
126
+ },
127
+ body: JSON.stringify({
128
+ model: context.model,
129
+ messages: input.messages ?? [{ role: 'user', content: String(input.input ?? input.prompt ?? '') }],
130
+ ...(typeof input.max_tokens === 'number' ? { max_tokens: input.max_tokens } : {}),
131
+ ...(input.effort ? { reasoning_effort: input.effort } : {}),
132
+ }),
133
+ }, options);
134
+ if (!response.ok)
135
+ throw await parseFailure(response);
136
+ return { output: await response.json(), latencyMs: 0 };
137
+ },
138
+ };
139
+ /** systemone:`POST {baseUrl}` + `{model, state, questions}`。 */
140
+ export const systemoneExecutor = {
141
+ id: 'builtin:systemone',
142
+ handles: ['systemone'],
143
+ services: ['*'],
144
+ async invoke(context, options) {
145
+ const input = asRecord(context.input);
146
+ const response = await fetchOnce(appendRequestQueryParams(context.provider.baseUrl, context.provider.queryParams), {
147
+ method: 'POST',
148
+ headers: {
149
+ 'Content-Type': 'application/json',
150
+ ...(context.provider.apiKey ? { Authorization: `Bearer ${context.provider.apiKey}` } : {}),
151
+ ...context.provider.headers,
152
+ },
153
+ body: JSON.stringify({
154
+ model: context.model,
155
+ state: input.state,
156
+ questions: input.questions,
157
+ }),
158
+ }, options);
159
+ if (!response.ok)
160
+ throw await parseFailure(response);
161
+ // systemone 返回 JSON;原样透传(可能是字符串化的 JSON)。
162
+ return { output: await response.json(), latencyMs: 0 };
163
+ },
164
+ };
165
+ /** gemini:`POST /v1beta/models/{model}:generateContent`,头带 x-goog-api-key。 */
166
+ export const geminiExecutor = {
167
+ id: 'builtin:gemini',
168
+ handles: ['gemini'],
169
+ services: ['*'],
170
+ async invoke(context, options) {
171
+ const input = asRecord(context.input);
172
+ const base = context.provider.baseUrl.replace(/\/+$/u, '');
173
+ const resource = `${base}/v1beta/models/${encodeURIComponent(context.model)}:generateContent`;
174
+ const contents = stringArray(input.contents) ?? [{
175
+ role: 'user',
176
+ parts: [{ text: String(input.input ?? input.prompt ?? '') }],
177
+ }];
178
+ const response = await fetchOnce(appendRequestQueryParams(resource, context.provider.queryParams), {
179
+ method: 'POST',
180
+ headers: {
181
+ 'Content-Type': 'application/json',
182
+ ...(context.provider.apiKey ? { 'x-goog-api-key': context.provider.apiKey } : {}),
183
+ ...context.provider.headers,
184
+ },
185
+ body: JSON.stringify({ contents }),
186
+ }, options);
187
+ if (!response.ok)
188
+ throw await parseFailure(response);
189
+ return { output: await response.json(), latencyMs: 0 };
190
+ },
191
+ };
192
+ export const TEXT_EXECUTORS = [
193
+ anthropicExecutor,
194
+ openaiResponsesExecutor,
195
+ openaiCompatibleExecutor,
196
+ systemoneExecutor,
197
+ geminiExecutor,
198
+ ];