@zhushanwen/subagent-core 0.2.0

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 (330) hide show
  1. package/README.md +114 -0
  2. package/dist/chunk-3VOERJPJ.js +22 -0
  3. package/dist/chunk-A4IVZWVX.js +31 -0
  4. package/dist/execution/engine/engines/zcode/constants.cjs +54 -0
  5. package/dist/execution/engine/engines/zcode/constants.d.cts +31 -0
  6. package/dist/execution/engine/engines/zcode/constants.d.ts +31 -0
  7. package/dist/execution/engine/engines/zcode/constants.js +22 -0
  8. package/dist/execution/engine/engines/zcode/reader.cjs +276 -0
  9. package/dist/execution/engine/engines/zcode/reader.d.cts +20 -0
  10. package/dist/execution/engine/engines/zcode/reader.d.ts +20 -0
  11. package/dist/execution/engine/engines/zcode/reader.js +239 -0
  12. package/dist/execution/engine/paths.cjs +55 -0
  13. package/dist/execution/engine/paths.d.cts +8 -0
  14. package/dist/execution/engine/paths.d.ts +8 -0
  15. package/dist/execution/engine/paths.js +26 -0
  16. package/dist/execution/relay-env.cjs +62 -0
  17. package/dist/execution/relay-env.d.cts +33 -0
  18. package/dist/execution/relay-env.d.ts +33 -0
  19. package/dist/execution/relay-env.js +20 -0
  20. package/dist/index.cjs +1852 -0
  21. package/dist/index.d.cts +1184 -0
  22. package/dist/index.d.ts +1184 -0
  23. package/dist/index.js +1810 -0
  24. package/dist/types-BxyAidGf.d.cts +875 -0
  25. package/dist/types-BxyAidGf.d.ts +875 -0
  26. package/package.json +99 -0
  27. package/src/__tests__/agent-opts-resolver-schema-prompt.test.ts +142 -0
  28. package/src/__tests__/append-system-prompt-assembly.test.ts +242 -0
  29. package/src/__tests__/builtin-workflows-structure.test.ts +180 -0
  30. package/src/__tests__/derive-closed-display-parity.test.ts +93 -0
  31. package/src/__tests__/fr4-get-state-handshake.test.ts +125 -0
  32. package/src/__tests__/fr8-orphan-recovery.test.ts +259 -0
  33. package/src/__tests__/m2-append-content-probe.test.ts +73 -0
  34. package/src/__tests__/manifest-store.test.ts +368 -0
  35. package/src/__tests__/record-store-cache.test.ts +335 -0
  36. package/src/__tests__/record-store-index.test.ts +560 -0
  37. package/src/__tests__/record-store-last-line.test.ts +129 -0
  38. package/src/__tests__/review-fix-loop-script.test.ts +288 -0
  39. package/src/__tests__/review-fix-loop-utils.test.ts +2377 -0
  40. package/src/__tests__/robustness-low-batch1.test.ts +286 -0
  41. package/src/__tests__/robustness-medium-batch1.test.ts +69 -0
  42. package/src/__tests__/robustness-medium-batch2.test.ts +65 -0
  43. package/src/__tests__/robustness-medium-batch3.test.ts +30 -0
  44. package/src/__tests__/robustness-medium-batch4.test.ts +358 -0
  45. package/src/__tests__/session-runner.test.ts +69 -0
  46. package/src/__tests__/smoke.test.ts +9 -0
  47. package/src/__tests__/stream-sink.test.ts +203 -0
  48. package/src/core/__tests__/host-services.test.ts +144 -0
  49. package/src/core/__tests__/logger.test.ts +78 -0
  50. package/src/core/__tests__/notify-ports.test.ts +104 -0
  51. package/src/core/host-services.ts +97 -0
  52. package/src/core/logger.ts +47 -0
  53. package/src/core/notify-ports.ts +126 -0
  54. package/src/execution/__tests__/__fixtures__/notifier-golden-snapshots.json +53 -0
  55. package/src/execution/__tests__/__fixtures__/truncline.snapshot.json +1 -0
  56. package/src/execution/__tests__/agent-result-mapper.test.ts +150 -0
  57. package/src/execution/__tests__/alive-store.test.ts +147 -0
  58. package/src/execution/__tests__/ask-user-transit-e2e.test.ts +490 -0
  59. package/src/execution/__tests__/channel-registry-handshake.test.ts +242 -0
  60. package/src/execution/__tests__/chat-engine-routing.test.ts +610 -0
  61. package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +190 -0
  62. package/src/execution/__tests__/concurrency-pool.test.ts +250 -0
  63. package/src/execution/__tests__/config.test.ts +302 -0
  64. package/src/execution/__tests__/delivery-methods.test.ts +424 -0
  65. package/src/execution/__tests__/dialog-queue.test.ts +299 -0
  66. package/src/execution/__tests__/epipe-fallback.test.ts +241 -0
  67. package/src/execution/__tests__/execute-and-await-worktree.test.ts +243 -0
  68. package/src/execution/__tests__/execute-nesting.test.ts +323 -0
  69. package/src/execution/__tests__/execute-options-mapper.test.ts +200 -0
  70. package/src/execution/__tests__/execution-record.test.ts +1394 -0
  71. package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +171 -0
  72. package/src/execution/__tests__/finalize-record.test.ts +367 -0
  73. package/src/execution/__tests__/finalized-marker.test.ts +104 -0
  74. package/src/execution/__tests__/format-schema-instruction.test.ts +169 -0
  75. package/src/execution/__tests__/gc-timer.test.ts +184 -0
  76. package/src/execution/__tests__/get-record-for-action-restart.test.ts +254 -0
  77. package/src/execution/__tests__/helpers/mock-extension-api.ts +30 -0
  78. package/src/execution/__tests__/helpers/spawn-mock.ts +242 -0
  79. package/src/execution/__tests__/host-mode.test.ts +87 -0
  80. package/src/execution/__tests__/lifecycle-manager-lock.test.ts +211 -0
  81. package/src/execution/__tests__/lifecycle-manager.test.ts +383 -0
  82. package/src/execution/__tests__/lifecycle-predicates.test.ts +116 -0
  83. package/src/execution/__tests__/manifest-parentid.test.ts +117 -0
  84. package/src/execution/__tests__/model-resolver.test.ts +465 -0
  85. package/src/execution/__tests__/nested-visibility-env-propagation.test.ts +287 -0
  86. package/src/execution/__tests__/nested-visibility.test.ts +325 -0
  87. package/src/execution/__tests__/output-collector.test.ts +358 -0
  88. package/src/execution/__tests__/path-encoding.test.ts +104 -0
  89. package/src/execution/__tests__/pi-invocation.test.ts +134 -0
  90. package/src/execution/__tests__/record-store.test.ts +1057 -0
  91. package/src/execution/__tests__/records-cwd-isolation.test.ts +91 -0
  92. package/src/execution/__tests__/recursive-visibility-baseline.test.ts +339 -0
  93. package/src/execution/__tests__/recursive-visibility-env.test.ts +273 -0
  94. package/src/execution/__tests__/relay-env.test.ts +42 -0
  95. package/src/execution/__tests__/resource-policy.test.ts +109 -0
  96. package/src/execution/__tests__/rpc-mode.test.ts +89 -0
  97. package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +267 -0
  98. package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +253 -0
  99. package/src/execution/__tests__/run-spawn-edges.test.ts +687 -0
  100. package/src/execution/__tests__/run-spawn-integration.test.ts +933 -0
  101. package/src/execution/__tests__/run-spawn-resume.test.ts +322 -0
  102. package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +196 -0
  103. package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +199 -0
  104. package/src/execution/__tests__/session-context-resolver.test.ts +167 -0
  105. package/src/execution/__tests__/session-file-gc.test.ts +293 -0
  106. package/src/execution/__tests__/session-reconstructor.test.ts +379 -0
  107. package/src/execution/__tests__/session-runner-epipe.test.ts +178 -0
  108. package/src/execution/__tests__/session-runner-schema-env.test.ts +350 -0
  109. package/src/execution/__tests__/spawn-args.test.ts +445 -0
  110. package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +189 -0
  111. package/src/execution/__tests__/spawn-event-adapter.test.ts +167 -0
  112. package/src/execution/__tests__/spawn-worktree-guidance.test.ts +207 -0
  113. package/src/execution/__tests__/spawned-children.test.ts +92 -0
  114. package/src/execution/__tests__/start-sync-model-guard.test.ts +150 -0
  115. package/src/execution/__tests__/stdin-writer.test.ts +462 -0
  116. package/src/execution/__tests__/stream-sink-retirement.test.ts +261 -0
  117. package/src/execution/__tests__/subagent-service-abort.test.ts +60 -0
  118. package/src/execution/__tests__/subagent-service-message-close.test.ts +629 -0
  119. package/src/execution/__tests__/subagent-service-parent-guard.test.ts +180 -0
  120. package/src/execution/__tests__/subagent-service.test.ts +788 -0
  121. package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +310 -0
  122. package/src/execution/__tests__/subprocess-agent-runner.test.ts +612 -0
  123. package/src/execution/__tests__/temp-prompt.test.ts +53 -0
  124. package/src/execution/__tests__/timeout-integration.test.ts +615 -0
  125. package/src/execution/__tests__/tombstone-store.test.ts +73 -0
  126. package/src/execution/__tests__/turn-limiter-semantics.test.ts +194 -0
  127. package/src/execution/__tests__/turn-limiter.test.ts +65 -0
  128. package/src/execution/__tests__/ui-channels.test.ts +187 -0
  129. package/src/execution/__tests__/ui-interaction-model.test.ts +67 -0
  130. package/src/execution/__tests__/ui-request-handler-factory.test.ts +369 -0
  131. package/src/execution/__tests__/ui-request-handler.test.ts +204 -0
  132. package/src/execution/__tests__/ui-request-observability.test.ts +113 -0
  133. package/src/execution/__tests__/ui-request-queue.test.ts +133 -0
  134. package/src/execution/__tests__/worktree-manager.test.ts +633 -0
  135. package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +229 -0
  136. package/src/execution/__tests__/worktree-reconcile.integration.test.ts +181 -0
  137. package/src/execution/__tests__/worktree-registry.test.ts +199 -0
  138. package/src/execution/agent-registry.ts +199 -0
  139. package/src/execution/agent-result-mapper.ts +90 -0
  140. package/src/execution/alive-store.ts +119 -0
  141. package/src/execution/argv-mirror.ts +113 -0
  142. package/src/execution/best-effort.ts +38 -0
  143. package/src/execution/channel-registry-access.ts +144 -0
  144. package/src/execution/concurrency-pool.ts +116 -0
  145. package/src/execution/config.ts +165 -0
  146. package/src/execution/dialog-queue.ts +330 -0
  147. package/src/execution/engine/__tests__/common/data-dir.test.ts +78 -0
  148. package/src/execution/engine/__tests__/common/errors.test.ts +132 -0
  149. package/src/execution/engine/__tests__/common/event-journal.test.ts +177 -0
  150. package/src/execution/engine/__tests__/common/kill-chain.test.ts +192 -0
  151. package/src/execution/engine/__tests__/common/nesting-guard.test.ts +81 -0
  152. package/src/execution/engine/__tests__/common/persona-router.test.ts +123 -0
  153. package/src/execution/engine/__tests__/common/pool-manager.test.ts +154 -0
  154. package/src/execution/engine/__tests__/common/schema-emulation.test.ts +128 -0
  155. package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +28 -0
  156. package/src/execution/engine/__tests__/conformance/agent-event-invariants.ts +141 -0
  157. package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +109 -0
  158. package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +101 -0
  159. package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +77 -0
  160. package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +104 -0
  161. package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +201 -0
  162. package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +76 -0
  163. package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +79 -0
  164. package/src/execution/engine/__tests__/engine-discovery.test.ts +87 -0
  165. package/src/execution/engine/__tests__/model-prompt.test.ts +197 -0
  166. package/src/execution/engine/__tests__/paths.test.ts +39 -0
  167. package/src/execution/engine/__tests__/registry.test.ts +120 -0
  168. package/src/execution/engine/__tests__/routing.test.ts +231 -0
  169. package/src/execution/engine/common/data-dir.ts +66 -0
  170. package/src/execution/engine/common/errors.ts +183 -0
  171. package/src/execution/engine/common/event-journal.ts +254 -0
  172. package/src/execution/engine/common/journal-replay.ts +62 -0
  173. package/src/execution/engine/common/kill-chain.ts +221 -0
  174. package/src/execution/engine/common/nesting-guard.ts +50 -0
  175. package/src/execution/engine/common/persona-router.ts +108 -0
  176. package/src/execution/engine/common/pool-manager.ts +226 -0
  177. package/src/execution/engine/common/schema-emulation.ts +189 -0
  178. package/src/execution/engine/common/session-view-projection.ts +51 -0
  179. package/src/execution/engine/engine-discovery.ts +65 -0
  180. package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +469 -0
  181. package/src/execution/engine/engines/pi/__tests__/reader.test.ts +155 -0
  182. package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +164 -0
  183. package/src/execution/engine/engines/pi/pi-engine.ts +415 -0
  184. package/src/execution/engine/engines/pi/reader.ts +48 -0
  185. package/src/execution/engine/engines/pi/registration.ts +35 -0
  186. package/src/execution/engine/engines/pi/task-spec-mapper.ts +100 -0
  187. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +39 -0
  188. package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +150 -0
  189. package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +246 -0
  190. package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +228 -0
  191. package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +210 -0
  192. package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +71 -0
  193. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +127 -0
  194. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +580 -0
  195. package/src/execution/engine/engines/zcode/constants.ts +43 -0
  196. package/src/execution/engine/engines/zcode/golden-sample.ts +39 -0
  197. package/src/execution/engine/engines/zcode/launcher.ts +161 -0
  198. package/src/execution/engine/engines/zcode/parser.ts +436 -0
  199. package/src/execution/engine/engines/zcode/preparer.ts +363 -0
  200. package/src/execution/engine/engines/zcode/reader.ts +381 -0
  201. package/src/execution/engine/engines/zcode/registration.ts +37 -0
  202. package/src/execution/engine/engines/zcode/zcode-engine.ts +658 -0
  203. package/src/execution/engine/host-task-spec.ts +47 -0
  204. package/src/execution/engine/model-prompt.ts +158 -0
  205. package/src/execution/engine/paths.ts +42 -0
  206. package/src/execution/engine/port.ts +153 -0
  207. package/src/execution/engine/registry.ts +133 -0
  208. package/src/execution/engine/routing.ts +218 -0
  209. package/src/execution/engine/types.ts +309 -0
  210. package/src/execution/execute-options-mapper.ts +115 -0
  211. package/src/execution/execution-record.ts +984 -0
  212. package/src/execution/finalize-record.ts +254 -0
  213. package/src/execution/finalized-marker.ts +70 -0
  214. package/src/execution/get-state-handshake.ts +104 -0
  215. package/src/execution/host-mode.ts +56 -0
  216. package/src/execution/idle-gc.ts +47 -0
  217. package/src/execution/lifecycle-manager.ts +513 -0
  218. package/src/execution/lifecycle-predicates.ts +65 -0
  219. package/src/execution/manifest-store.ts +256 -0
  220. package/src/execution/model-config-service.ts +250 -0
  221. package/src/execution/model-resolver.ts +248 -0
  222. package/src/execution/notifier.ts +372 -0
  223. package/src/execution/notify-ledger.ts +580 -0
  224. package/src/execution/output-collector.ts +228 -0
  225. package/src/execution/path-encoding.ts +60 -0
  226. package/src/execution/pi-invocation.ts +120 -0
  227. package/src/execution/record-entry.ts +132 -0
  228. package/src/execution/record-store.ts +1265 -0
  229. package/src/execution/relay-env.ts +37 -0
  230. package/src/execution/session-context-resolver.ts +64 -0
  231. package/src/execution/session-file-gc.ts +120 -0
  232. package/src/execution/session-pending.ts +170 -0
  233. package/src/execution/session-reconstructor.ts +678 -0
  234. package/src/execution/session-runner.ts +1789 -0
  235. package/src/execution/sessions-index.ts +304 -0
  236. package/src/execution/spawn-event-adapter.ts +363 -0
  237. package/src/execution/stdin-writer.ts +198 -0
  238. package/src/execution/stream-sink.ts +126 -0
  239. package/src/execution/subagent-service.ts +2268 -0
  240. package/src/execution/subprocess-agent-runner.ts +317 -0
  241. package/src/execution/temp-prompt.ts +62 -0
  242. package/src/execution/tombstone-store.ts +72 -0
  243. package/src/execution/turn-limiter.ts +102 -0
  244. package/src/execution/types.ts +1023 -0
  245. package/src/execution/ui-channels.ts +216 -0
  246. package/src/execution/ui-interaction-model.ts +48 -0
  247. package/src/execution/ui-request-handler-factory.ts +243 -0
  248. package/src/execution/ui-request-observability.ts +81 -0
  249. package/src/execution/ui-request-queue.ts +184 -0
  250. package/src/execution/worktree-manager.ts +688 -0
  251. package/src/execution/worktree-registry.ts +279 -0
  252. package/src/index.ts +87 -0
  253. package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +349 -0
  254. package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +202 -0
  255. package/src/orchestration/__tests__/agent-call-stream.test.ts +152 -0
  256. package/src/orchestration/__tests__/args-validator.test.ts +143 -0
  257. package/src/orchestration/__tests__/config-loader.test.ts +503 -0
  258. package/src/orchestration/__tests__/error-recovery-handlers.test.ts +809 -0
  259. package/src/orchestration/__tests__/error-recovery-postmessage-defense.test.ts +404 -0
  260. package/src/orchestration/__tests__/error-recovery-serialize-failed-result.test.ts +56 -0
  261. package/src/orchestration/__tests__/error-recovery-workflow-call.test.ts +166 -0
  262. package/src/orchestration/__tests__/execute-agent-call.test.ts +451 -0
  263. package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +600 -0
  264. package/src/orchestration/__tests__/lifecycle-runid-injection.test.ts +96 -0
  265. package/src/orchestration/__tests__/lifecycle.test.ts +659 -0
  266. package/src/orchestration/__tests__/non-cloneable-return-e2e.test.ts +95 -0
  267. package/src/orchestration/__tests__/review-fix-loop-scriptpath-failfast.test.ts +183 -0
  268. package/src/orchestration/__tests__/script-lint.test.ts +831 -0
  269. package/src/orchestration/__tests__/skill-discovery.test.ts +210 -0
  270. package/src/orchestration/__tests__/test-mocks.ts +197 -0
  271. package/src/orchestration/__tests__/worker-exit-without-result.test.ts +368 -0
  272. package/src/orchestration/__tests__/worker-host.test.ts +120 -0
  273. package/src/orchestration/__tests__/worker-returnmeta-passthrough.test.ts +164 -0
  274. package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +563 -0
  275. package/src/orchestration/__tests__/worker-script-builder.test.ts +309 -0
  276. package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +129 -0
  277. package/src/orchestration/__tests__/workflow-nesting-e2e.test.ts +317 -0
  278. package/src/orchestration/__tests__/workflow-script-lint-memo.test.ts +110 -0
  279. package/src/orchestration/agent-opts-resolver.ts +174 -0
  280. package/src/orchestration/args-validator.ts +127 -0
  281. package/src/orchestration/config-loader.ts +316 -0
  282. package/src/orchestration/error-recovery.ts +1018 -0
  283. package/src/orchestration/execute-agent-call.ts +256 -0
  284. package/src/orchestration/launcher.ts +455 -0
  285. package/src/orchestration/lifecycle.ts +399 -0
  286. package/src/orchestration/models/__tests__/budget.test.ts +307 -0
  287. package/src/orchestration/models/agent-call.ts +83 -0
  288. package/src/orchestration/models/budget.ts +118 -0
  289. package/src/orchestration/models/ports.ts +164 -0
  290. package/src/orchestration/models/run-runtime.ts +104 -0
  291. package/src/orchestration/models/run-spec.ts +83 -0
  292. package/src/orchestration/models/run-state.ts +44 -0
  293. package/src/orchestration/models/trace.ts +183 -0
  294. package/src/orchestration/models/types.ts +301 -0
  295. package/src/orchestration/models/workflow-run.ts +254 -0
  296. package/src/orchestration/models/workflow-script-registry.ts +35 -0
  297. package/src/orchestration/models/workflow-script.ts +117 -0
  298. package/src/orchestration/script-lint.ts +766 -0
  299. package/src/orchestration/skill-discovery.ts +135 -0
  300. package/src/orchestration/worker-handle.ts +115 -0
  301. package/src/orchestration/worker-host.ts +98 -0
  302. package/src/orchestration/worker-script-builder.ts +421 -0
  303. package/src/orchestration/workflow-files.ts +85 -0
  304. package/src/orchestration/workflow-script-registry-impl.ts +133 -0
  305. package/src/shared/__tests__/agent-ref.test.ts +34 -0
  306. package/src/shared/__tests__/meta-parser.test.ts +304 -0
  307. package/src/shared/__tests__/model-ref.test.ts +306 -0
  308. package/src/shared/__tests__/resource-discovery-manifest-cache.test.ts +288 -0
  309. package/src/shared/__tests__/resource-discovery.test.ts +749 -0
  310. package/src/shared/__tests__/resource-meta.test.ts +51 -0
  311. package/src/shared/__tests__/schema-jsonify.test.ts +81 -0
  312. package/src/shared/__tests__/timer-delay.test.ts +61 -0
  313. package/src/shared/agent-event.ts +13 -0
  314. package/src/shared/agent-ref.ts +57 -0
  315. package/src/shared/meta-parser.ts +261 -0
  316. package/src/shared/model-ref.ts +286 -0
  317. package/src/shared/resource-discovery.ts +835 -0
  318. package/src/shared/resource-meta.ts +65 -0
  319. package/src/shared/schema-env.ts +44 -0
  320. package/src/shared/schema-jsonify.ts +58 -0
  321. package/src/shared/timer-delay.ts +54 -0
  322. package/src/shared/xml-injection.ts +35 -0
  323. package/workflows/README.md +81 -0
  324. package/workflows/_shared/agent-refs.cjs +40 -0
  325. package/workflows/chain.js +137 -0
  326. package/workflows/map-reduce.js +180 -0
  327. package/workflows/parallel.js +154 -0
  328. package/workflows/review-fix-loop-utils.cjs +1542 -0
  329. package/workflows/review-fix-loop.js +1605 -0
  330. package/workflows/scatter-gather.js +184 -0
@@ -0,0 +1,218 @@
1
+ // src/execution/engine/routing.ts
2
+ //
3
+ // 配置路由与探针 fallback 编排(P4)。设计权威源:
4
+ // docs/architecture/subagent-engine-abstraction.md D9(配置路由三层 + 故障 fallback
5
+ // 三守卫 + model/engine 正交 + workflow 脚本不写死 engine)+ D7(探针分级与触发时机)
6
+ // + §3.3.3 错误规格(engine_probe_failed / model_not_available 行)。
7
+ //
8
+ // 职责边界:本模块只做「选哪个引擎」的决策(纯路由 + probe 编排),不 spawn、不读
9
+ // 任务正文。三层优先级与守卫的判定规则集中于此单一权威点——上层(SAR)只消费
10
+ // routeEngine 的结果,散落的 if engine === ... 分派被结构性排除。
11
+ //
12
+ // probe 触发时机(D7「引擎 factory 初始化与版本变化检测时触发」的 P4 落地口径):
13
+ // 路由期触发、结果缓存于引擎实例(probeCache)。缺省引擎 'pi' 免探——pi 契约稳定
14
+ // (rpc.md 官方,D7 稳定性光谱的轻探针端)且「缺省路径行为零变化」是 A1 硬约束
15
+ // (每次 run 前强探会引入 pi --version 子进程开销与新的失败面);显式 engine='pi'
16
+ // 同样免探(fallback 无处可去,守卫 a 对 pi 不可达是自然结果而非缺口)。进程存活
17
+ // 期间缓存不失效——版本变化(运行中 CLI 被升级)由 engine_run_failed 运行中兜底
18
+ // (D11 规则②封边界的既有设计),重启进程 / registerEngine 覆盖后重探。
19
+
20
+ import { EngineError } from "./common/errors.ts";
21
+ import type { EnginePort } from "./port.ts";
22
+ import { DEFAULT_ENGINE_ID, EngineNotFoundError, getEngine, hasEngine, listEngines } from "./registry.ts";
23
+ import type { ProbeReport } from "./types.ts";
24
+
25
+ // ============================================================
26
+ // 三层优先级(D9)
27
+ // ============================================================
28
+
29
+ /** 三层路由的输入(各层值由调用方装配;undefined = 该层不指定)。 */
30
+ export interface EngineRoutingInput {
31
+ /** 第一层:调用参数 engine(workflow step 级 / AgentCallOpts.engine)。 */
32
+ callEngine?: string;
33
+ /** 第二层:agent .md frontmatter engine(解析期已对注册表校验)。 */
34
+ agentEngine?: string;
35
+ /** 第三层:全局默认引擎(config.json defaultEngine;缺省 'pi')。 */
36
+ globalDefaultEngine?: string;
37
+ }
38
+
39
+ /** 生效层标记(守卫 a 的判据:'call' = 显式指定,probe 失败不兜底)。 */
40
+ export type EngineRoutingSource = "call" | "frontmatter" | "default";
41
+
42
+ export interface EngineRouting {
43
+ engineId: string;
44
+ source: EngineRoutingSource;
45
+ }
46
+
47
+ /** 非空文本判据:路由层各配置入口统一口径——undefined 与空串同视为未指定。 */
48
+ function hasText(v: string | undefined): v is string {
49
+ return v !== undefined && v !== "";
50
+ }
51
+
52
+ /**
53
+ * 纯三层解析:调用参数 > agent frontmatter > 全局默认(缺省 'pi')。
54
+ * 不校验注册表(frontmatter 层已前置校验;调用参数层的校验归 routeEngine)——
55
+ * 保持纯函数可独立单测。
56
+ */
57
+ export function resolveEngineRouting(input: EngineRoutingInput): EngineRouting {
58
+ if (hasText(input.callEngine)) {
59
+ return { engineId: input.callEngine, source: "call" };
60
+ }
61
+ if (hasText(input.agentEngine)) {
62
+ return { engineId: input.agentEngine, source: "frontmatter" };
63
+ }
64
+ if (hasText(input.globalDefaultEngine)) {
65
+ return { engineId: input.globalDefaultEngine, source: "default" };
66
+ }
67
+ return { engineId: DEFAULT_ENGINE_ID, source: "default" };
68
+ }
69
+
70
+ // ============================================================
71
+ // routeEngine:probe 编排 + fallback 三守卫(D9①/D7)
72
+ // ============================================================
73
+
74
+ /** routeEngine 的参数(probe/getEngine 注入——测试可 mock,SAR 提供生产实现)。 */
75
+ export interface EngineRouteOptions {
76
+ routing: EngineRoutingInput;
77
+ /**
78
+ * 显式 model(守卫 c 判据:model 与引擎 provider 体系绑定,D9②)。短名 model 的
79
+ * provider 缺省决策在 zcode preparer 的 defaultProviderForShortName——显式默认引擎
80
+ * 模型配置(config.json per-engine model)引入时,两处须同步让位配置值优先
81
+ * (对齐点⑦,详见 preparer.ts 该函数注释)。
82
+ */
83
+ taskModel?: string;
84
+ /** engineRouting.strict(config.json):true = 一切 probe 失败直接报错。 */
85
+ strict: boolean;
86
+ /** 探针执行体(返回 ProbeReport;引擎实例内部有缓存语义)。 */
87
+ probe: (engineId: string) => Promise<ProbeReport>;
88
+ /** 引擎获取(缺省 registry.getEngine;测试/SAR 可注入)。 */
89
+ getEngineFn?: (engineId: string) => EnginePort;
90
+ /** 注册表存在性检查(缺省 registry.hasEngine)。 */
91
+ hasEngineFn?: (engineId: string) => boolean;
92
+ /** 注册表清单(缺省 registry.listEngines——engine_not_found 文案的数据源)。 */
93
+ listEnginesFn?: () => string[];
94
+ }
95
+
96
+ export interface EngineRouteResult {
97
+ engine: EnginePort;
98
+ /** 实际执行引擎 id(fallback 后可能 ≠ 请求值)。 */
99
+ engineId: string;
100
+ /** 路由决策时的请求引擎 id(fallback 留痕的 from 值)。 */
101
+ requestedEngineId: string;
102
+ /** 生效层(守卫 a 判据的留痕)。 */
103
+ source: EngineRoutingSource;
104
+ /** fallback 留痕(record/outcome 投影,GUI 警告条数据源)。无 fallback 缺省。 */
105
+ engineFallback?: { from: string; reason: string };
106
+ }
107
+
108
+ /**
109
+ * 路由 + 探针 + fallback 编排(SAR run 入口调用)。
110
+ *
111
+ * 失败形态(全部抛结构化错误,调用方转 AgentResult.error):
112
+ * - 未注册 id(调用参数层漏网):EngineNotFoundError(engine_not_found)
113
+ * - strict 或守卫命中:EngineError(engine_probe_failed)
114
+ * - 守卫 c(显式 model + 将换引擎):EngineError(model_not_available)
115
+ */
116
+ export async function routeEngine(opts: EngineRouteOptions): Promise<EngineRouteResult> {
117
+ const has = opts.hasEngineFn ?? hasEngine;
118
+ const get = opts.getEngineFn ?? getEngine;
119
+ const routing = resolveEngineRouting(opts.routing);
120
+
121
+ // 调用参数层的注册表校验(frontmatter 层已在 agent 解析期抛过;这里兜调用参数
122
+ // 直传的未注册 id——错误含注册清单,配置错误前置到路由期而非 getEngine 深处)
123
+ if (!has(routing.engineId)) {
124
+ throw new EngineNotFoundError(routing.engineId, opts.listEnginesFn?.() ?? listEngines(), describeRoutingSource(opts.routing));
125
+ }
126
+
127
+ // 缺省引擎免探(见文件头「probe 触发时机」)——直接取引擎
128
+ if (routing.engineId === DEFAULT_ENGINE_ID) {
129
+ return {
130
+ engine: get(routing.engineId),
131
+ engineId: routing.engineId,
132
+ requestedEngineId: routing.engineId,
133
+ source: routing.source,
134
+ };
135
+ }
136
+
137
+ const report = await opts.probe(routing.engineId);
138
+ if (report.ok) {
139
+ return {
140
+ engine: get(routing.engineId),
141
+ engineId: routing.engineId,
142
+ requestedEngineId: routing.engineId,
143
+ source: routing.source,
144
+ };
145
+ }
146
+
147
+ // ── probe 失败:strict / 三守卫 / fallback(D9①)──
148
+ if (opts.strict) {
149
+ throw probeFailedError(routing.engineId, report, "engineRouting.strict=true:probe 失败一律报错(不 fallback)");
150
+ }
151
+ // 守卫 a/b(首期合流):显式指定(调用参数或 step 级)= 能力依赖声明,静默换引擎
152
+ // 违反意图——沙箱类任务被静默卸除安全能力正是要防的形态(D9① 原文)。守卫 b 的
153
+ // 独立载体(AgentTaskSpec.requires)下钻后在本分支前独立判定,首期显式 engine 即声明。
154
+ if (routing.source === "call") {
155
+ throw probeFailedError(routing.engineId, report, "engine 来自调用参数显式指定(能力依赖声明)——不兜底");
156
+ }
157
+
158
+ const fallbackId = fallbackTargetId(opts.routing, routing);
159
+ // 守卫 c:显式 model 与引擎 provider 体系绑定(D9② model/engine 正交)——换引擎
160
+ // 后 model 可解析性无法保证,静默换引擎跑 = 「以为用了 X 实际用 Y」。判定取保守
161
+ // 口径(显式 model + 引擎切换即拒):路由层无各引擎 provider 注册表的访问面,
162
+ // 精确可解析性判定归引擎 prepare 期(ZcodePrepareError.model_not_available 已有)。
163
+ if (hasText(opts.taskModel) && fallbackId !== routing.engineId) {
164
+ throw new EngineError(
165
+ "model_not_available",
166
+ `engine '${routing.engineId}' probe 失败且任务显式指定 model '${opts.taskModel}'——model 与引擎 provider 体系绑定,换引擎(fallback 到 '${fallbackId}')不静默执行`,
167
+ `修复 engine '${routing.engineId}' 的探针失败(见上方恢复指引)后重试,或去掉 model 指定 / 显式传 engine: '${fallbackId}' 确认模型可用后再派发`,
168
+ );
169
+ }
170
+
171
+ return {
172
+ engine: get(fallbackId),
173
+ engineId: fallbackId,
174
+ requestedEngineId: routing.engineId,
175
+ source: "default",
176
+ engineFallback: { from: routing.engineId, reason: "engine_probe_failed" },
177
+ };
178
+ }
179
+
180
+ /**
181
+ * fallback 目标:请求来自 frontmatter/调用参数 → 全局默认引擎;请求即全局默认
182
+ * (defaultEngine 配了坏引擎,source='default')→ 内置缺省 'pi'(零风险回退——设计
183
+ * 终态四口径:fallback 回「缺省 pi」而非原地重试坏引擎)。全局默认与请求引擎相同
184
+ * (frontmatter engine === defaultEngine,如 agent .md engine: zcode + config
185
+ * defaultEngine: zcode)同样回 'pi'——回退到刚 probe 失败的同一引擎 = 原地重试坏
186
+ * 引擎(from==to 误导留痕),违背「回缺省 pi」的设计意图。
187
+ */
188
+ function fallbackTargetId(routingInput: EngineRoutingInput, resolved: EngineRouting): string {
189
+ // source 与 engineId 由 resolved 承载配对关系,杜绝调用方传错配对的口子
190
+ if (resolved.source === "default") return DEFAULT_ENGINE_ID;
191
+ const global = routingInput.globalDefaultEngine;
192
+ if (hasText(global) && global !== DEFAULT_ENGINE_ID && global !== resolved.engineId) {
193
+ return global;
194
+ }
195
+ return DEFAULT_ENGINE_ID;
196
+ }
197
+
198
+ /** engine_probe_failed 的结构化构造(detail 含逐 check 摘要,recovery 用探针产出)。 */
199
+ function probeFailedError(engineId: string, report: ProbeReport, guard: string): EngineError {
200
+ const checks = report.checks.map((c) => `${c.name}:${c.ok ? "ok" : "FAIL"}`).join(", ");
201
+ return new EngineError(
202
+ "engine_probe_failed",
203
+ `engine '${engineId}' probe 失败(${guard})。checks: [${checks}]`,
204
+ report.error?.recovery ??
205
+ `Confirm the engine binary and version, then re-run the probe (probe({force:true}) or re-initialize the engine).`,
206
+ );
207
+ }
208
+
209
+ /** 路由来源描述(EngineNotFoundError 的 source 定位)。 */
210
+ function describeRoutingSource(routing: EngineRoutingInput): string | undefined {
211
+ if (hasText(routing.callEngine)) {
212
+ return `call parameter engine='${routing.callEngine}'`;
213
+ }
214
+ if (hasText(routing.agentEngine)) {
215
+ return `agent frontmatter engine='${routing.agentEngine}'`;
216
+ }
217
+ return undefined;
218
+ }
@@ -0,0 +1,309 @@
1
+ // src/execution/engine/types.ts
2
+ //
3
+ // 引擎中立类型层(P1)。设计权威源:docs/architecture/subagent-engine-abstraction.md
4
+ // §3.3.5(EnginePort 与中立类型完整契约)+ §3.3.6(EngineHandle/journal/SessionView 格式)。
5
+ //
6
+ // 为什么单独一层:执行层现有四个核心类型(ExecuteOptions/AgentEvent/AgentResult/AgentRunner
7
+ // port)的中立是「碰巧的,不是设计的」——thinkingLevel 是 pi 7 档枚举、skillPath 假设引擎有
8
+ // --skill flag、conversation/idleTimeoutMs 是 pi chatMode 专属形态(设计 §2.1)。本文件把
9
+ // 「agent 调用」的引擎无关语义显式化为 AgentTaskSpec / AgentOutcome 等类型,EnginePort
10
+ // (port.ts)与其下各引擎适配器都以本层为唯一契约点。
11
+ //
12
+ // 泛化原则(D2):从现有类型泛化,不另起炉灶——字段与 execution/types.ts 的
13
+ // ExecuteOptions、orchestration/models/types.ts 的 AgentResult 逐一锚定,标注「泛化」的
14
+ // 条目语义有变,标注「新增」为引擎层新引入。
15
+ //
16
+ // AgentResult 消歧(设计 §2.1/§3.3.5):仓内有两个同名 AgentResult——
17
+ // ① orchestration 层 workflow 消费的那份(orchestration/models/types.ts,主字段
18
+ // content/parsedOutput/usage/error)——中立层锚定这份,AgentOutcome 的字段就是它的
19
+ // 超集(+ engineId/engineFallback/exitCode);
20
+ // ② execution 层的同名类型(execution/types.ts,主字段 text/turns/sessionId/toolCalls)
21
+ // ——record 内部投影,保持原名不动。
22
+ // 引擎层终态命名 AgentOutcome,与两者不同名,消除「同名不同义」。
23
+
24
+ import type { AgentUsage, ToolCallEntry } from "../../orchestration/models/types.ts";
25
+ import type { AgentUsageTotal, ToolCall, WorktreeHandle } from "../types.ts";
26
+
27
+ // AgentEvent 8 种事件原样保留,唯一权威定义仍是 execution/types.ts——引擎层 re-export
28
+ // 不复制第二份(设计 §3.3.5);经 shared/agent-event.ts 的既有出口转发,维持「shared/
29
+ // 是类型共享层」的架构约定。新增粗粒度约束(coarse 引擎至少合成一次 message_end +
30
+ // 一次 turn_end)由 conformance 套件断言(P4),不在类型层编码。
31
+ export type { AgentEvent } from "../../shared/agent-event.ts";
32
+
33
+ // ============================================================
34
+ // AgentTaskSpec(= 现有 ExecuteOptions 泛化,D2)
35
+ // ============================================================
36
+
37
+ /** 人设(persona)注入规格:原 skillPath + appendSystemPrompt 收拢进一个语义单元(D2)。 */
38
+ export interface PersonaSpec {
39
+ /**
40
+ * agent 名/路径。与 AgentTaskSpec.agent 的分工:agent 是 resolveIdentity 的身份解析
41
+ * 键(模型/系统提示等身份语义);agentRef 是 persona 注入通道的定位符——引擎按
42
+ * capabilities.personaInjection 决定注入通道(file/flag/prompt)时用它定位人设。
43
+ * pi 引擎不消费此字段(身份解析走 spec.agent),留给 flag/file 通道的引擎。
44
+ */
45
+ agentRef?: string;
46
+ /**
47
+ * 原 ExecuteOptions.skillPath。公共 persona 路由三策略(file/flag/prompt)的分流
48
+ * 载体(D4)——超长 prompt 时优先 file/flag 通道分流的落点。
49
+ */
50
+ skillPath?: string;
51
+ /** 追加系统提示内容数组(原样透传;schema 仿真段由公共降级层拼装后放入,P2)。 */
52
+ appendSystemPrompt?: string[];
53
+ }
54
+
55
+ /**
56
+ * 引擎无关的 agent 任务声明(= ExecuteOptions 泛化,字段逐条锚定设计 §3.3.5)。
57
+ *
58
+ * 与 ExecuteOptions 的差异(泛化点):
59
+ * - thinkingLevel(pi 7 档枚举语义)→ effort?: string,各引擎自行映射或忽略;
60
+ * - skillPath + appendSystemPrompt → persona(PersonaSpec);
61
+ * - conversation/idleTimeoutMs 保留原名透传——属 interact 交互控制面的 task 标志(D1),
62
+ * 不是 pi 专有语义的泄漏,而是「任务声明里声明交互模式」的中立表达;
63
+ * - 删字段去向:signal/ctxModel/onComplete 是运行期句柄,移入 RunContext(port.ts);
64
+ * schemaEnv 内化到 PiEngine(从 task.schema 派生,见 engines/pi/task-spec-mapper.ts)。
65
+ *
66
+ * 新增(为后续 wave 预留形状,P1 无生产写入方):
67
+ * - denyTools:中立工具 denylist(附录 A 该行的载体);
68
+ * - permissionMode:中立权限模式(映射按 capabilities.permissionMode)。
69
+ */
70
+ export interface AgentTaskSpec {
71
+ /** 原样(ExecuteOptions.task)。 */
72
+ task: string;
73
+ /** 原样(ExecuteOptions.slug,≤35 字符)。 */
74
+ slug: string;
75
+ /** 原样(ExecuteOptions.agent,resolveIdentity 的 agent ref)。 */
76
+ agent?: string;
77
+ /** 原样(ExecuteOptions.model;在引擎 provider 体系内解释,D9②)。 */
78
+ model?: string;
79
+ /**
80
+ * 泛化:原 ExecuteOptions.thinkingLevel。引擎无关的推理投入档位字符串——
81
+ * pi 引擎把它原值映射回 thinkingLevel 7 档;其他引擎自行映射(CC 5 档)或忽略
82
+ * (kimi ❌)。不定义联合枚举:档位集合是引擎私有语义,中立层只透传字符串。
83
+ */
84
+ effort?: string;
85
+ /** 泛化:原 skillPath + appendSystemPrompt 收拢(D2)。 */
86
+ persona?: PersonaSpec;
87
+ /**
88
+ * 原样(ExecuteOptions.schema)。native/emulated 分流依据(D4 硬边界):pi 的
89
+ * PI_WORKFLOW_SCHEMA env 注入链路按 native 直传,公共仿真层只服务 emulated 引擎。
90
+ */
91
+ schema?: Record<string, unknown>;
92
+ /**
93
+ * 原样(ExecuteOptions.maxTurns)。pi 引擎专属(turn limiter + spawn watchdog
94
+ * 估算依赖 pi 的 turn_end 事件流);其他引擎 prepare 期显式拒绝(U4,同 fork 模式)。
95
+ * 显式 0 压过 SPAWN_WATCHDOG_ENV 兑底(SP-6 参数 > env,U5);undefined 未传才由
96
+ * env 兑底。
97
+ */
98
+ maxTurns?: number;
99
+ /** 原样(ExecuteOptions.graceTurns)。 */
100
+ graceTurns?: number;
101
+ /** 原样(ExecuteOptions.fork)。pi 专属;其他引擎 prepare 期按 capabilities 拒绝。 */
102
+ fork?: boolean;
103
+ /**
104
+ * 原样(ExecuteOptions.worktree)。公共层职责(worktree-manager),非引擎职责——
105
+ * 引擎只把它当 spawn cwd 的来源之一。
106
+ */
107
+ worktree?: boolean | WorktreeHandle;
108
+ /** 原样(ExecuteOptions.cwd)。 */
109
+ cwd?: string;
110
+ /** 原样(ExecuteOptions.conversation,interact 控制面的 task 标志,D1)。 */
111
+ conversation?: boolean;
112
+ /** 原样(ExecuteOptions.idleTimeoutMs,同上)。 */
113
+ idleTimeoutMs?: number;
114
+ /** 新增:中立工具 denylist。各引擎做语法映射(附录 A「工具 denylist」行的载体)。 */
115
+ denyTools?: string[];
116
+ /** 新增:中立权限模式。映射按 capabilities.permissionMode(kimi fixed auto = ignored)。 */
117
+ permissionMode?: string;
118
+ /**
119
+ * [P4 形状预留,D9① 守卫 b 的独立载体] 任务对引擎能力的显式依赖声明。
120
+ * 首期无生产写入方:守卫 b 与守卫 a 合流(显式 engine 即能力依赖声明)——调用方
121
+ * 按引擎 id 表达依赖。下钻时机(AgentTaskSpec 泛化成熟后):调用方改按能力表达
122
+ * (如 requires: { sandbox: 'native' }),路由层将本字段与各引擎 capabilities()
123
+ * 对照,无引擎满足时报 engine_capability_unsupported(调用前拒绝,D11 处置三级)。
124
+ */
125
+ requires?: Partial<EngineCapabilities>;
126
+ }
127
+
128
+ // ============================================================
129
+ // AgentOutcome(锚定 orchestration 层 AgentResult,§3.3.5)
130
+ // ============================================================
131
+
132
+ /**
133
+ * 一次引擎执行的终态。锚定 orchestration/models/types.ts 的 AgentResult(workflow
134
+ * 引擎消费的那份——content/parsedOutput/usage/error)并追加引擎层字段;见文件头消歧说明。
135
+ */
136
+ export interface AgentOutcome {
137
+ /** 原样(AgentResult.content)。 */
138
+ content: string;
139
+ /**
140
+ * 原样(AgentResult.parsedOutput)。native 引擎直传 / 仿真层 ajv 产出(D4 硬分流:
141
+ * native 路径公共层不做二次校验、不改写其结果)。
142
+ */
143
+ parsedOutput?: unknown;
144
+ /** 原样(AgentResult.usage,orchestration 版 AgentUsage:含 contextTokens/turns)。 */
145
+ usage?: AgentUsage;
146
+ /** 原样(AgentResult.durationMs)。 */
147
+ durationMs?: number;
148
+ /** 原样(AgentResult.error,错误码前缀格式见设计 §3.3.3 错误规格表)。 */
149
+ error?: string;
150
+ /** 原样(AgentResult.sessionId,引擎语义 session id)。 */
151
+ sessionId?: string;
152
+ /** 原样(AgentResult.sessionFile)。 */
153
+ sessionFile?: string;
154
+ /** 原样(AgentResult.worktreePath,仅诊断——目录可能已被 finalize 清理)。 */
155
+ worktreePath?: string;
156
+ /** 原样(AgentResult.toolCalls,ToolCallEntry[])。 */
157
+ toolCalls?: ToolCallEntry[];
158
+ /** 新增:实际执行引擎(fallback 后可能 ≠ 请求值,D9①)。 */
159
+ engineId: string;
160
+ /** 新增:fallback 留痕(record 同步投影,GUI 警告条数据源)。P1 恒缺省(无 fallback 路由)。 */
161
+ engineFallback?: { from: string; reason: string };
162
+ /** 新增:null = 被信号杀死(杀链/abort 合成终态的判据)。P1 pi 链路不暴露 exit code,恒缺省。 */
163
+ exitCode?: number | null;
164
+ }
165
+
166
+ // ============================================================
167
+ // EngineHandle(run/interact/read 三面的连接件,D1/§3.3.6)
168
+ // ============================================================
169
+
170
+ /**
171
+ * EngineHandle 的持久化形态(设计 §3.3.6,JSON v1)。
172
+ * 内存态 EngineHandle = 本数据 + 引擎运行时引用(各引擎自持)。
173
+ */
174
+ export interface EngineHandleData {
175
+ v: 1;
176
+ /** 引擎 id('pi' | 'zcode' | ...,registry key)。 */
177
+ engineId: string;
178
+ /**
179
+ * 引擎自定义键值(定位符)。pi = { recordId?, sessionFile? }——recordId 是
180
+ * interact 控制面的 key(subagent record id),sessionFile 是 read 第①级(JSONL
181
+ * 直读)的定位符;zcode = { sessionId, dbPath }。
182
+ */
183
+ sessionRef: Record<string, string>;
184
+ /** 隔离池定位(设计 §3.3.9)。pi 无池化(PI_CODING_AGENT_DIR 全局一份)恒 'shared'。 */
185
+ poolKey: string;
186
+ /**
187
+ * journal 绝对路径(read 第②级数据源;runtime 读前校验前缀白名单)。
188
+ * P2 event journal 落地后由宿主回填;P1 无 journal 写入者,缺省 undefined——
189
+ * read 降级链第②级不可达,直接走 ①/③。
190
+ */
191
+ journalPath?: string;
192
+ /** probe 实测版本(漂移排查锚点)。 */
193
+ engineVersion?: string;
194
+ /** 适配器版本(golden 样本对齐排查)。 */
195
+ adapterVersion: string;
196
+ }
197
+
198
+ /**
199
+ * 引擎会话句柄(run 返回、interact/read 入参)。
200
+ *
201
+ * 契约三条(D1):不透明(上层不解构——唯一例外是 record 持久化层序列化 data 字段与
202
+ * read 降级链)、可持久化(data 是纯 JSON,主会话 reload 后 read/interact 仍可用)、
203
+ * 自描述(data 含 engineId + 引擎 session 定位符 + pool key + adapter 版本)。
204
+ *
205
+ * 对进程已死的 handle 调 interact 必须返回 engine_session_not_resumable(指向 cold
206
+ * resume 路径),而非笼统失败——由各引擎 interact 实现保证。
207
+ */
208
+ export interface EngineHandle {
209
+ /** 持久化数据。上层不得解构其内部字段(见契约三条)。 */
210
+ readonly data: EngineHandleData;
211
+ }
212
+
213
+ // ============================================================
214
+ // SessionView(read 返回,D6/§3.3.6)
215
+ // ============================================================
216
+
217
+ /**
218
+ * read(handle) 的返回:turns[] 派生数据。与 Turn 同构但无内部态(_status/startedTs
219
+ * 剥离,closed 恒 true)。
220
+ */
221
+ export interface ReplayedTurn {
222
+ text: string;
223
+ thinking: string;
224
+ /** 导出的纯净形状(execution 层 ToolCall,无 _status)。 */
225
+ toolCalls: ToolCall[];
226
+ closed: true;
227
+ }
228
+
229
+ /**
230
+ * session 历史的引擎中立视图。降级链三级(D6):①引擎原生读取(pi JSONL / zcode
231
+ * sqlite)→ ②宿主 event journal 重放(P2)→ ③outcome-only。source 字段是 GUI 降级
232
+ * 标记数据源(A8)。
233
+ */
234
+ export interface SessionView {
235
+ engineId: string;
236
+ sessionId?: string;
237
+ /** turns[] 派生数据(重放/重建产物)。 */
238
+ turns: ReplayedTurn[];
239
+ /** 各 turn usageDelta 聚合(execution 层 AgentUsageTotal)。 */
240
+ usage?: AgentUsageTotal;
241
+ source: "native" | "journal" | "outcome-only";
242
+ }
243
+
244
+ // ============================================================
245
+ // EngineCapabilities(D3,三级声明)
246
+ // ============================================================
247
+
248
+ /**
249
+ * 引擎能力声明(设计 D3 原样落地)。三级:native / emulated / unsupported。
250
+ *
251
+ * 易错点(D3):声明的是**本仓 subagent 链路实际接通的能力**,不是引擎 RPC 层的理论
252
+ * 能力——pi 的 RPC 有 steer 但现有 spawn 链路未接通(session-runner steer no-op),
253
+ * 故 PiEngine 声明 unsupported,接通后再升级。上层据声明选择策略(schema 为 emulated
254
+ * 时自动走公共降级层;steer/conversation unsupported 时 UI 隐藏对应入口),而非
255
+ * try-catch 运行时试错。
256
+ */
257
+ export interface EngineCapabilities {
258
+ /** native: --json-schema/--output-schema/env 注入(pi = PI_WORKFLOW_SCHEMA 链路)。 */
259
+ schemaEnforcement: "native" | "emulated";
260
+ /** 注意区分「引擎 RPC 层有此能力」与「subagent 链路已接通」。 */
261
+ steer: "native" | "emulated" | "unsupported";
262
+ /** interact 控制面(message/close/cancel + idle)。 */
263
+ conversation: "native" | "unsupported";
264
+ /** 决定 persona 路由策略(公共降级层按此选择 file/flag/prompt 通道)。 */
265
+ personaInjection: "file" | "flag" | "prompt";
266
+ /** 粗粒度引擎:GUI 显示降级为阶段态。 */
267
+ eventGranularity: "stream" | "coarse";
268
+ /** emulated = worktree 隔离(无 OS sandbox 的引擎用文件写维度隔离补齐)。 */
269
+ sandbox: "native" | "emulated" | "none";
270
+ /** 重建历史的能力(read 降级链第①级的保真度上限)。 */
271
+ sessionRead: "full" | "partial" | "outcome-only";
272
+ resume: "native" | "cold" | "unsupported";
273
+ /** 优雅中断 or 只能杀进程(公共杀链兜底,见 D1 abort 分级)。 */
274
+ interrupt: "native" | "kill-only";
275
+ /** kimi headless 固定 auto = ignored;GUI 据此隐藏/提示。 */
276
+ permissionMode: "native" | "fixed" | "ignored";
277
+ }
278
+
279
+ // ============================================================
280
+ // probe(D7)与 interact(D1)的负载类型
281
+ // ============================================================
282
+
283
+ /** 引擎探针报告(probe() 返回)。探针在引擎 factory 初始化与版本变化检测时触发(P4 接线)。 */
284
+ export interface ProbeReport {
285
+ ok: boolean;
286
+ /** 实测版本(handle.engineVersion 数据源)。探测不到时为空串。 */
287
+ engineVersion: string;
288
+ /** 二进制存在/版本解析/干跑回归逐项。 */
289
+ checks: Array<{ name: string; ok: boolean; detail?: string }>;
290
+ /** engine_probe_failed 的恢复指引(设计 §3.3.3 终态四样例;ok=false 时必填)。 */
291
+ error?: { code: string; recovery: string };
292
+ }
293
+
294
+ /**
295
+ * interact 的 action(D1 交互控制面)。pi 首期原生实现(现有 chatMode 行为直通);
296
+ * 声明 conversation unsupported 的引擎调用前拒绝(engine_capability_unsupported)。
297
+ */
298
+ export type InteractAction =
299
+ | { kind: "message"; payload: string }
300
+ | { kind: "close"; payload?: { force: boolean } }
301
+ | { kind: "cancel" };
302
+
303
+ /**
304
+ * interact 的结果。失败码取自设计 §3.3.3:engine_session_not_resumable(死 handle)/
305
+ * engine_capability_unsupported(能力声明拒绝)等。
306
+ */
307
+ export type InteractResult =
308
+ | { ok: true; delivered: true }
309
+ | { ok: false; code: string; message: string };
@@ -0,0 +1,115 @@
1
+ // src/execution/execute-options-mapper.ts
2
+ //
3
+ // D-A2: AgentCallOpts → ExecuteOptions 映射(adapter 职责)
4
+ // D-A9: per-call timeoutMs 合并进 AbortSignal
5
+ //
6
+ // 接线层级:[模块内直调] —— SAR.run 内调。
7
+
8
+ import type { AgentCallOpts } from "../orchestration/models/types.ts";
9
+ import { HOST_TIMEOUT_ABORT_REASON } from "./engine/common/kill-chain.ts";
10
+ import type { ModelInfo } from "./model-resolver.ts";
11
+ import type { ExecuteOptions } from "./types.ts";
12
+
13
+ // SLUG_MAX_LENGTH 权威定义(subagent-core 包抽离 u1-move 内化):core 切面不得反向
14
+ // import 壳侧 interface(D1 依赖闭包判据),常量定义回归 execution 侧本文件——
15
+ // 与 tool schema 的 maxLength 语义同源(壳侧 subagent-tool-schema.ts 改经本文件 import)。
16
+ /**
17
+ * slug 最大长度。历史值 20 偏紧——描述性 slug 如 "audit-structured-output"(23)/
18
+ * "fix-subagent-wf-tools"(21)会撞上限,放宽到 35 兼顾「短到能塞进 TUI 标题行」
19
+ * 与「容纳合理描述性 kebab-case 名」。
20
+ */
21
+ export const SLUG_MAX_LENGTH = 35;
22
+
23
+ /**
24
+ * D-A2: AgentCallOpts → ExecuteOptions 映射。
25
+ *
26
+ * adapter 职责——SubagentService 的 ExecuteOptions 是稳定内部契约,不为 workflow 的
27
+ * AgentCallOpts 做适配(映射归调用方 SAR)。
28
+ *
29
+ * 映射规则:
30
+ * prompt → task
31
+ * description → slug(≤35 字符,超长截断。缺失时回落 agent 名)
32
+ * agent → agent
33
+ * schema → schema
34
+ * schemaEnv → schemaEnv(D-A6 bridge)
35
+ * cwd → cwd
36
+ * model → model(显式 override 透传,ctxModel 不再压扁为 id 填底)
37
+ * ctxModel → ctxModel(完整 ModelInfo 对象透传,让 resolveModel 走第 3 层透明传递)
38
+ * skillPath → skillPath
39
+ * thinkingLevel → thinkingLevel(M1: 否则下游 subagent-service 读到 undefined)
40
+ * appendSystemPrompt → appendSystemPrompt(内容数组,同名同义透传)
41
+ * maxTurns → maxTurns(turn limiter 上限;undefined = 不限,不挂 turns 估算 watchdog)
42
+ *
43
+ * 忽略字段(委托后由 executeAndAwait 内部机制替代):
44
+ * timeoutMs —— mergeTimeoutSignal 单独处理
45
+ * scene —— subagents 不消费
46
+ *
47
+ * description 原先被忽略,现作为 slug 透传(ExecuteOptions.slug 必填)。
48
+ */
49
+ export function mapToExecuteOptions(
50
+ opts: AgentCallOpts,
51
+ ctxModel?: ModelInfo,
52
+ ): ExecuteOptions {
53
+ // slug:优先 description,缺失回落 agent 名(保证非空)。超长截断。
54
+ const rawSlug = opts.description ?? opts.agent ?? "workflow-agent";
55
+ return {
56
+ task: opts.prompt,
57
+ slug: rawSlug.length > SLUG_MAX_LENGTH ? rawSlug.slice(0, SLUG_MAX_LENGTH) : rawSlug,
58
+ agent: opts.agent,
59
+ schema: opts.schema,
60
+ schemaEnv: opts.schemaEnv,
61
+ cwd: opts.cwd,
62
+ fork: opts.fork,
63
+ worktree: opts.worktree,
64
+ model: opts.model,
65
+ ctxModel,
66
+ skillPath: opts.skillPath,
67
+ thinkingLevel: opts.thinkingLevel,
68
+ appendSystemPrompt: opts.appendSystemPrompt,
69
+ maxTurns: opts.maxTurns,
70
+ };
71
+ }
72
+
73
+ /**
74
+ * D-A9: per-call timeoutMs 合并进 AbortSignal。
75
+ *
76
+ * 墙钟 timeoutMs(per-call)+ 外部 signal(run 级 abort)都生效。
77
+ * 缺此合并则 agent({timeoutMs:5000}) 静默无效(BC-9)。
78
+ *
79
+ * @param signal 外部 signal(workflow run 级 controller.signal)
80
+ * @param timeoutMs per-call 墙钟超时;undefined/<=0 → 不设超时,原样返回 signal
81
+ * @returns 合并后的 signal(timeoutMs 或外部 signal 任一 abort 都触发)
82
+ */
83
+ export function mergeTimeoutSignal(
84
+ signal: AbortSignal,
85
+ timeoutMs?: number,
86
+ ): AbortSignal {
87
+ if (!timeoutMs || timeoutMs <= 0) {
88
+ return signal;
89
+ }
90
+
91
+ const controller = new AbortController();
92
+ // 超时 abort 带 reason 标记(对齐点④):引擎合成终态时判别「宿主超时」
93
+ // (engine_timeout 公共合成)vs「外部 cancel」(中止标记)——pi 链路不读 reason,
94
+ // 行为不变。外部 signal abort 不带标记(用户/编排层 cancel 语义)。
95
+ const timer = setTimeout(() => controller.abort(HOST_TIMEOUT_ABORT_REASON), timeoutMs);
96
+ timer.unref();
97
+
98
+ const onExternalAbort = (): void => controller.abort();
99
+ if (signal.aborted) {
100
+ controller.abort();
101
+ } else {
102
+ signal.addEventListener("abort", onExternalAbort, { once: true });
103
+ }
104
+
105
+ controller.signal.addEventListener(
106
+ "abort",
107
+ () => {
108
+ clearTimeout(timer);
109
+ if (!signal.aborted) signal.removeEventListener("abort", onExternalAbort);
110
+ },
111
+ { once: true },
112
+ );
113
+
114
+ return controller.signal;
115
+ }