@zhushanwen/subagent-core 0.6.0 → 0.7.1

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 (278) hide show
  1. package/README.md +1 -1
  2. package/dist/chunk-KXVBIVOU.js +16 -0
  3. package/dist/chunk-T2SYBW3I.js +24 -0
  4. package/dist/chunk-VURUAGMM.js +2305 -0
  5. package/dist/{types-C3fE3R9x.d.cts → engine-discovery-scan-ocpM8FmI.d.cts} +770 -668
  6. package/dist/{types-C3fE3R9x.d.ts → engine-discovery-scan-ocpM8FmI.d.ts} +770 -668
  7. package/dist/execution/engine/engine-discovery-scan.cjs +2210 -0
  8. package/dist/execution/engine/engine-discovery-scan.d.cts +4 -0
  9. package/dist/execution/engine/engine-discovery-scan.d.ts +4 -0
  10. package/dist/execution/engine/engine-discovery-scan.js +20 -0
  11. package/dist/execution/engine/paths.cjs +6 -23
  12. package/dist/execution/engine/paths.d.cts +1 -8
  13. package/dist/execution/engine/paths.d.ts +1 -8
  14. package/dist/execution/engine/paths.js +1 -1
  15. package/dist/execution/relay-env.cjs +12 -28
  16. package/dist/execution/relay-env.d.cts +1 -33
  17. package/dist/execution/relay-env.d.ts +1 -33
  18. package/dist/execution/relay-env.js +5 -3
  19. package/dist/index.cjs +14045 -16059
  20. package/dist/index.d.cts +1035 -1579
  21. package/dist/index.d.ts +1035 -1579
  22. package/dist/index.js +9838 -13800
  23. package/dist.bundle/index.cjs +28875 -30323
  24. package/package.json +20 -26
  25. package/src/__tests__/record-store-last-line.test.ts +16 -7
  26. package/src/core/error-message.ts +7 -6
  27. package/src/core/host-services.ts +8 -2
  28. package/src/core/notify-ports.ts +17 -2
  29. package/src/execution/__tests__/chat-engine-routing.test.ts +62 -28
  30. package/src/execution/__tests__/chat-round-first-round-watchdog.test.ts +255 -0
  31. package/src/execution/__tests__/collect-coordinator-service.test.ts +36 -47
  32. package/src/execution/__tests__/collect-mixed-dispatch.test.ts +20 -53
  33. package/src/execution/__tests__/delivery-methods.test.ts +179 -237
  34. package/src/execution/__tests__/execute-and-await-worktree.test.ts +0 -2
  35. package/src/execution/__tests__/execute-nesting.test.ts +20 -13
  36. package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +20 -33
  37. package/src/execution/__tests__/gc-timer.test.ts +7 -22
  38. package/src/execution/__tests__/get-record-for-action-restart.test.ts +20 -10
  39. package/src/execution/__tests__/helpers/fake-engine-port.ts +187 -0
  40. package/src/execution/__tests__/helpers/spawn-mock.ts +36 -9
  41. package/src/execution/__tests__/helpers/subagent-service-mocks.ts +1 -1
  42. package/src/execution/__tests__/idle-gc.test.ts +200 -0
  43. package/src/execution/__tests__/lifecycle-predicates.test.ts +26 -21
  44. package/src/execution/__tests__/nested-visibility-env-propagation.test.ts +5 -2
  45. package/src/execution/__tests__/reconcile-sweep.test.ts +200 -0
  46. package/src/execution/__tests__/record-store.test.ts +60 -6
  47. package/src/execution/__tests__/recursive-visibility-baseline.test.ts +20 -13
  48. package/src/execution/__tests__/round-supervisor.test.ts +293 -0
  49. package/src/execution/__tests__/session-pending.test.ts +119 -17
  50. package/src/execution/__tests__/stream-sink-retirement.test.ts +10 -10
  51. package/src/execution/__tests__/subagent-service-multiproc-guard.test.ts +1 -11
  52. package/src/execution/__tests__/subagent-service-notify-gate.test.ts +33 -30
  53. package/src/execution/__tests__/subagent-service-parent-guard.test.ts +2 -9
  54. package/src/execution/__tests__/subagent-service-recovery-bounds.test.ts +59 -129
  55. package/src/execution/__tests__/subagent-service.test.ts +2 -2
  56. package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +109 -7
  57. package/src/execution/__tests__/subprocess-agent-runner.test.ts +108 -36
  58. package/src/execution/__tests__/sync-collect-recovery.test.ts +21 -36
  59. package/src/execution/__tests__/workflow-state-root.test.ts +232 -0
  60. package/src/execution/agent-registry.ts +6 -2
  61. package/src/execution/dialog-queue.ts +6 -73
  62. package/src/execution/engine/__tests__/common/capability-gate.test.ts +115 -15
  63. package/src/execution/engine/__tests__/common/errors.test.ts +11 -18
  64. package/src/execution/engine/__tests__/common/kill-chain.test.ts +7 -0
  65. package/src/execution/engine/__tests__/common/nesting-guard.test.ts +9 -3
  66. package/src/execution/engine/__tests__/common/session-view-service.test.ts +90 -3
  67. package/src/execution/engine/__tests__/conformance/H9-test-disposition.md +116 -0
  68. package/src/execution/engine/__tests__/conformance/__fixtures__/engine-protocol/fake-engine-protocol.mjs +377 -0
  69. package/src/execution/engine/__tests__/conformance/__fixtures__/engine-protocol/recorded.fixture.json +331 -0
  70. package/src/execution/engine/__tests__/conformance/__fixtures__/engine-protocol/smoke-run.fixture.json +213 -0
  71. package/src/execution/engine/__tests__/conformance/chat-round-protocol.test.ts +230 -0
  72. package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +69 -42
  73. package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +4 -81
  74. package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +67 -44
  75. package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +81 -54
  76. package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +133 -70
  77. package/src/execution/engine/__tests__/conformance/engine-crash.test.ts +143 -0
  78. package/src/execution/engine/__tests__/conformance/fake-engine-capabilities.ts +19 -0
  79. package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +7 -2
  80. package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +6 -5
  81. package/src/execution/engine/__tests__/conformance/protocol-blackbox.test.ts +398 -0
  82. package/src/execution/engine/__tests__/conformance/registry-fork-filter.test.ts +221 -0
  83. package/src/execution/engine/__tests__/conformance/round-liveness-supervisor.test.ts +302 -0
  84. package/src/execution/engine/__tests__/conformance/static-spawn-guard.test.ts +58 -0
  85. package/src/execution/engine/__tests__/engine-discovery-scan.test.ts +558 -0
  86. package/src/execution/engine/__tests__/host-task-spec.test.ts +45 -0
  87. package/src/execution/engine/__tests__/model-ref-split.test.ts +74 -0
  88. package/src/execution/engine/__tests__/registry.test.ts +206 -1
  89. package/src/execution/engine/__tests__/routing.test.ts +97 -0
  90. package/src/execution/engine/__tests__/run-failure-worktree-cleanup.test.ts +97 -0
  91. package/src/execution/engine/client/__tests__/__fixtures__/fake-engine.mjs +294 -0
  92. package/src/execution/engine/client/__tests__/engine-client.test.ts +516 -0
  93. package/src/execution/engine/client/__tests__/mirror.test.ts +67 -0
  94. package/src/execution/engine/client/__tests__/pid-file.test.ts +257 -0
  95. package/src/execution/engine/client/__tests__/protocol-closure.test.ts +95 -0
  96. package/src/execution/engine/client/__tests__/remote-engine.test.ts +457 -0
  97. package/src/execution/engine/client/client-options.ts +103 -0
  98. package/src/execution/engine/client/engine-client.ts +687 -0
  99. package/src/execution/engine/client/mirror.ts +167 -0
  100. package/src/execution/engine/client/pid-file.ts +392 -0
  101. package/src/execution/engine/client/reaper.ts +95 -0
  102. package/src/execution/engine/client/remote-engine.ts +441 -0
  103. package/src/execution/engine/client/reverse-router.ts +255 -0
  104. package/src/execution/engine/common/capability-gate.ts +109 -22
  105. package/src/execution/engine/common/errors.ts +9 -25
  106. package/src/execution/engine/common/event-journal.ts +4 -50
  107. package/src/execution/engine/common/journal-replay.ts +3 -1
  108. package/src/execution/engine/common/kill-chain.ts +18 -251
  109. package/src/execution/engine/common/nesting-guard.ts +18 -114
  110. package/src/execution/engine/common/pool-manager.ts +4 -0
  111. package/src/execution/engine/common/session-view-service.ts +56 -84
  112. package/src/execution/engine/config.ts +151 -0
  113. package/src/execution/engine/d8-compat.ts +346 -0
  114. package/src/execution/engine/engine-discovery-roots.ts +107 -0
  115. package/src/execution/engine/engine-discovery-scan.ts +269 -0
  116. package/src/execution/engine/engine-discovery.ts +30 -7
  117. package/src/execution/engine/engine-inspect-package.ts +282 -0
  118. package/src/execution/engine/engine-manifest.ts +244 -0
  119. package/src/execution/engine/host/__tests__/host-askuser-endpoint.test.ts +123 -0
  120. package/src/execution/engine/host/__tests__/host-bridge.test.ts +135 -0
  121. package/src/execution/engine/host/__tests__/spawned-children.test.ts +73 -0
  122. package/src/execution/engine/host/host-bridge.ts +150 -0
  123. package/src/execution/engine/host/host-ui-endpoint.ts +47 -0
  124. package/src/execution/engine/host/pi-host-binding.ts +91 -0
  125. package/src/execution/engine/host/spawned-children.ts +139 -0
  126. package/src/execution/engine/host-task-spec.ts +29 -2
  127. package/src/execution/engine/model-validation.ts +55 -2
  128. package/src/execution/engine/paths.ts +16 -41
  129. package/src/execution/engine/port.ts +48 -2
  130. package/src/execution/engine/registry.ts +153 -34
  131. package/src/execution/engine/routing.ts +225 -52
  132. package/src/execution/engine/types.ts +25 -200
  133. package/src/execution/finalize-record.ts +25 -0
  134. package/src/execution/idle-gc.ts +89 -14
  135. package/src/execution/lifecycle-manager.ts +10 -7
  136. package/src/execution/lifecycle-predicates.ts +10 -8
  137. package/src/execution/record-store.ts +29 -2
  138. package/src/execution/relay-env.ts +19 -36
  139. package/src/execution/round-supervisor/domain.ts +89 -0
  140. package/src/execution/round-supervisor/index.ts +33 -0
  141. package/src/execution/round-supervisor/notify-accounting.ts +87 -0
  142. package/src/execution/round-supervisor/reconcile-sweep.ts +235 -0
  143. package/src/execution/round-supervisor/service-binding.test.ts +661 -0
  144. package/src/execution/round-supervisor/service-binding.ts +273 -0
  145. package/src/execution/round-supervisor/supervisor.ts +426 -0
  146. package/src/execution/session-pending.ts +68 -74
  147. package/src/execution/settled-watchdog.ts +39 -0
  148. package/src/execution/subagent-service.ts +746 -400
  149. package/src/execution/subprocess-agent-runner.ts +16 -8
  150. package/src/execution/types.ts +41 -117
  151. package/src/execution/ui-channels.ts +13 -214
  152. package/src/execution/ui-request-handler-factory.ts +7 -4
  153. package/src/execution/ui-request-observability.ts +2 -2
  154. package/src/execution/workflow-state-root.ts +67 -0
  155. package/src/execution/worktree-git-ops.ts +5 -0
  156. package/src/execution/worktree-manager.ts +11 -1
  157. package/src/index.ts +55 -26
  158. package/src/orchestration/__tests__/execute-agent-call.test.ts +1 -1
  159. package/src/orchestration/execute-agent-call.ts +1 -1
  160. package/src/orchestration/file-run-store.ts +144 -59
  161. package/src/orchestration/models/types.ts +43 -42
  162. package/src/shared/zcode-model-ref.ts +31 -0
  163. package/dist/chunk-43ONBFZX.js +0 -240
  164. package/dist/chunk-A4IVZWVX.js +0 -31
  165. package/dist/chunk-APZY4IME.js +0 -27
  166. package/dist/chunk-V3VHZ2VX.js +0 -59
  167. package/dist/execution/engine/engines/zcode/constants.cjs +0 -107
  168. package/dist/execution/engine/engines/zcode/constants.d.cts +0 -135
  169. package/dist/execution/engine/engines/zcode/constants.d.ts +0 -135
  170. package/dist/execution/engine/engines/zcode/constants.js +0 -54
  171. package/dist/execution/engine/engines/zcode/reader.cjs +0 -276
  172. package/dist/execution/engine/engines/zcode/reader.d.cts +0 -21
  173. package/dist/execution/engine/engines/zcode/reader.d.ts +0 -21
  174. package/dist/execution/engine/engines/zcode/reader.js +0 -9
  175. package/src/__tests__/append-system-prompt-assembly.test.ts +0 -243
  176. package/src/__tests__/fr4-get-state-handshake.test.ts +0 -125
  177. package/src/__tests__/session-runner.test.ts +0 -69
  178. package/src/execution/__tests__/ask-user-transit-e2e.test.ts +0 -490
  179. package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +0 -191
  180. package/src/execution/__tests__/descendant-sweep-guards.test.ts +0 -220
  181. package/src/execution/__tests__/descendant-sweep.test.ts +0 -269
  182. package/src/execution/__tests__/engine-model-validation.test.ts +0 -741
  183. package/src/execution/__tests__/epipe-fallback.test.ts +0 -248
  184. package/src/execution/__tests__/execution-runtime-face.test.ts +0 -272
  185. package/src/execution/__tests__/get-state-handshake.test.ts +0 -127
  186. package/src/execution/__tests__/helpers/session-runner-mocks.ts +0 -113
  187. package/src/execution/__tests__/keep-alive-no-progress.test.ts +0 -280
  188. package/src/execution/__tests__/kill-all-escalation.test.ts +0 -196
  189. package/src/execution/__tests__/max-turns-to-watchdog-ms.test.ts +0 -113
  190. package/src/execution/__tests__/output-collector.test.ts +0 -469
  191. package/src/execution/__tests__/pi-invocation.test.ts +0 -166
  192. package/src/execution/__tests__/recursive-visibility-env.test.ts +0 -149
  193. package/src/execution/__tests__/rpc-mode.test.ts +0 -89
  194. package/src/execution/__tests__/run-and-finalize-anchoring.test.ts +0 -387
  195. package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +0 -277
  196. package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +0 -254
  197. package/src/execution/__tests__/run-spawn-edges.test.ts +0 -1079
  198. package/src/execution/__tests__/run-spawn-integration.test.ts +0 -933
  199. package/src/execution/__tests__/run-spawn-resume.test.ts +0 -322
  200. package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +0 -196
  201. package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +0 -207
  202. package/src/execution/__tests__/service-kill-escalation.test.ts +0 -91
  203. package/src/execution/__tests__/session-runner-branch-cache-lru.test.ts +0 -110
  204. package/src/execution/__tests__/session-runner-close-prune.test.ts +0 -181
  205. package/src/execution/__tests__/session-runner-dispatch.test.ts +0 -489
  206. package/src/execution/__tests__/session-runner-epipe.test.ts +0 -179
  207. package/src/execution/__tests__/session-runner-heartbeat-idle-fallback.test.ts +0 -227
  208. package/src/execution/__tests__/session-runner-lifecycle-helpers.test.ts +0 -290
  209. package/src/execution/__tests__/session-runner-schema-env.test.ts +0 -352
  210. package/src/execution/__tests__/settled-watchdog.test.ts +0 -524
  211. package/src/execution/__tests__/spawn-args.test.ts +0 -446
  212. package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +0 -192
  213. package/src/execution/__tests__/spawn-event-adapter.test.ts +0 -167
  214. package/src/execution/__tests__/spawn-worktree-guidance.test.ts +0 -208
  215. package/src/execution/__tests__/spawned-children.test.ts +0 -236
  216. package/src/execution/__tests__/start-sync-model-guard.test.ts +0 -150
  217. package/src/execution/__tests__/stdin-writer.test.ts +0 -464
  218. package/src/execution/__tests__/subagent-service-message-close.test.ts +0 -693
  219. package/src/execution/__tests__/temp-prompt.test.ts +0 -53
  220. package/src/execution/__tests__/timeout-integration.test.ts +0 -616
  221. package/src/execution/__tests__/turn-limiter-semantics.test.ts +0 -194
  222. package/src/execution/__tests__/turn-limiter.test.ts +0 -65
  223. package/src/execution/__tests__/ui-request-handler.test.ts +0 -205
  224. package/src/execution/__tests__/ui-request-queue.test.ts +0 -298
  225. package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +0 -230
  226. package/src/execution/engine/__tests__/common/schema-emulation.test.ts +0 -128
  227. package/src/execution/engine/__tests__/common/session-view-service-zcode-dbpath.test.ts +0 -149
  228. package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +0 -28
  229. package/src/execution/engine/__tests__/conformance/zcode-appserver-harness.ts +0 -128
  230. package/src/execution/engine/__tests__/paths.test.ts +0 -39
  231. package/src/execution/engine/common/schema-emulation.ts +0 -189
  232. package/src/execution/engine/common/session-view-projection.ts +0 -51
  233. package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +0 -615
  234. package/src/execution/engine/engines/pi/__tests__/reader.test.ts +0 -155
  235. package/src/execution/engine/engines/pi/__tests__/spawn-opts-direct.test.ts +0 -257
  236. package/src/execution/engine/engines/pi/argv-mirror.ts +0 -135
  237. package/src/execution/engine/engines/pi/get-state-handshake.ts +0 -179
  238. package/src/execution/engine/engines/pi/output-collector.ts +0 -317
  239. package/src/execution/engine/engines/pi/pi-engine.ts +0 -811
  240. package/src/execution/engine/engines/pi/pi-invocation.ts +0 -120
  241. package/src/execution/engine/engines/pi/reader.ts +0 -59
  242. package/src/execution/engine/engines/pi/registration.ts +0 -37
  243. package/src/execution/engine/engines/pi/session-runner.ts +0 -2840
  244. package/src/execution/engine/engines/pi/spawn-event-adapter.ts +0 -404
  245. package/src/execution/engine/engines/pi/stdin-writer.ts +0 -199
  246. package/src/execution/engine/engines/pi/temp-prompt.ts +0 -62
  247. package/src/execution/engine/engines/pi/turn-limiter.ts +0 -102
  248. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/fake-appserver.mjs +0 -301
  249. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-appserver.json +0 -36
  250. package/src/execution/engine/engines/zcode/__tests__/appserver-launcher.test.ts +0 -321
  251. package/src/execution/engine/engines/zcode/__tests__/connection.test.ts +0 -473
  252. package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +0 -43
  253. package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +0 -124
  254. package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +0 -210
  255. package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +0 -71
  256. package/src/execution/engine/engines/zcode/__tests__/session-channel-dispose-harvest.test.ts +0 -247
  257. package/src/execution/engine/engines/zcode/__tests__/session-channel-turn-timers.test.ts +0 -451
  258. package/src/execution/engine/engines/zcode/__tests__/session-channel.test.ts +0 -792
  259. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-appserver.test.ts +0 -782
  260. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-degrade.test.ts +0 -168
  261. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-dispose.test.ts +0 -210
  262. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-retry.test.ts +0 -353
  263. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-status.test.ts +0 -282
  264. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-timeout.test.ts +0 -372
  265. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +0 -145
  266. package/src/execution/engine/engines/zcode/appserver-launcher.ts +0 -167
  267. package/src/execution/engine/engines/zcode/connection.ts +0 -598
  268. package/src/execution/engine/engines/zcode/constants.ts +0 -176
  269. package/src/execution/engine/engines/zcode/golden-sample.ts +0 -47
  270. package/src/execution/engine/engines/zcode/parser.ts +0 -102
  271. package/src/execution/engine/engines/zcode/preparer.ts +0 -235
  272. package/src/execution/engine/engines/zcode/reader.ts +0 -381
  273. package/src/execution/engine/engines/zcode/registration.ts +0 -37
  274. package/src/execution/engine/engines/zcode/session-channel.ts +0 -968
  275. package/src/execution/engine/engines/zcode/zcode-engine.ts +0 -1431
  276. package/src/execution/round-settlement.ts +0 -93
  277. package/src/execution/ui-request-queue.ts +0 -215
  278. package/src/shared/schema-env.ts +0 -44
@@ -1,5 +1,317 @@
1
+ import { WorktreeHandle, AgentFailureKind, AgentOutcomeUsage, ToolCallEntry, Turn, ToolCall, AgentUsageTotal, EngineHandleData, EngineCapabilities, ProbeReport, AgentEvent, ResumeAnchor, HostRoundLifecycleParams, AgentOutcome, InteractAction, InteractResult, SessionView, ModelCatalogEntry } from '@zhushanwen/subagent-engine-sdk';
2
+ import { ChildProcess } from 'node:child_process';
1
3
  import { GuiRenderResult } from '@xyz-agent/extension-protocol';
2
4
 
5
+ /**
6
+ * Workflow Extension — Engine 共享类型
7
+ *
8
+ * Engine 层全局基础类型。零 infra 依赖——不 import 任何 infra 文件,
9
+ * 可独立编译测试(D-12 三层架构,AC-1)。
10
+ *
11
+ * 核心内容:
12
+ * - 状态机:RunStatus = "running" | "done"(2 态,一次性生命周期,FR-3)
13
+ * + DoneReason(completed/failed/aborted/budget_limited/time_limited)
14
+ * - AgentCallOpts / AgentResult(单次 agent 调用的输入/输出,宿主面 SSOT 留守本地)
15
+ * + AgentUsage / ToolCallEntry / AgentFailureKind(自 SDK re-export,S4 簇 3 收编)
16
+ * - ExecutionTraceNode / TracePatch / ToolCallEntry / WorkerLogEntry(trace 数据)
17
+ *
18
+ * 层归属:Engine(数据结构 + 不变式守卫)。
19
+ */
20
+
21
+ /**
22
+ * 状态机:2 态(D-12 / FR-3,一次性生命周期——run 不可挂起)。
23
+ *
24
+ * running → done
25
+ *
26
+ * `done` 是唯一终态,具体原因由 DoneReason 区分。
27
+ */
28
+ type RunStatus = "running" | "done";
29
+ /** 终态原因。done 时必有(WorkflowRun 不变式)。 */
30
+ type DoneReason = "completed" | "failed" | "aborted" | "budget_limited" | "time_limited" | "invalid_args";
31
+ /**
32
+ * slug 最大长度(D6 合流迁入本文件,原权威定义在已删除的 execution/execute-options-mapper.ts)。
33
+ * 历史值 20 偏紧——描述性 slug 如 "audit-structured-output"(23)/ "fix-subagent-wf-tools"(21)
34
+ * 会撞上限,放宽到 35 兼顾「短到能塞进 TUI 标题行」与「容纳合理描述性 kebab-case 名」。
35
+ * 放本文件的原因:约束对象是 AgentCallOpts.description(slug 的源字段,见下方 slug 派生说明),
36
+ * 与字段同文件;worker-message-pump(live record slug 截断)与壳侧 tool schema maxLength 共享引用。
37
+ */
38
+ declare const SLUG_MAX_LENGTH = 35;
39
+ /**
40
+ * 单次 agent 调用的任务声明(D6 任务形状合流后的单一形状)。
41
+ *
42
+ * [D6 合流裁决] 本类型 = 原 AgentCallOpts(workflow 调用方声明,18 字段)与原
43
+ * AgentTaskSpec(engine 中立任务声明,已删除)的合流形态,从模型脚本 agent() API
44
+ * 到 EnginePort.run 直达 pi 边界一次映射——SAR 链路上的 ExecuteOptions/AgentTaskSpec
45
+ * 中间态消除(设计 docs/design/subagent-dual-track-convergence.md §3.3 D6 / 终态四)。
46
+ *
47
+ * 终态命名按变化轴裁定为 AgentCallOpts,理由:
48
+ * - 字段演进的首要驱动轴是「调用方要表达的任务语义」(agent() API 是唯一生产写入方,
49
+ * 合流字段中 prompt/description/skill/skillPath/schemaEnv/thinkingLevel 等多数派
50
+ * 已是调用方命名);
51
+ * - 原 AgentTaskSpec 的中立重命名层(task/slug/effort/persona)与调用方命名是
52
+ * 形式同构、语义同构的假差异(prompt≡task、slug=description 截断、effort≡thinkingLevel、
53
+ * persona≡skillPath+appendSystemPrompt 平铺),按「消假差异」原则并入调用方命名;
54
+ * - 持久化兼容反向锁定 prompt 形态:jsonl run 快照的 AgentCall.opts 与 worker 消息
55
+ * opts 均以 prompt 字段落盘,改名会破坏旧快照重水合。
56
+ *
57
+ * 引擎中立字段的并入方式(可选字段,原 AgentTaskSpec 独有字段去向):
58
+ * - graceTurns / conversation / idleTimeoutMs / denyTools / permissionMode:可选并入;
59
+ * - persona.agentRef:裁撤(无生产写入方、无消费者——pi 走 agent 字段解析身份);
60
+ * - requires:裁撤(P4 形状预留、无生产写入方;且并入需 import EngineCapabilities
61
+ * 形成 orchestration↔engine 类型环)。将来能力依赖声明下钻时在本形状上加回。
62
+ *
63
+ * D-12 仅重组执行编排,AgentCallOpts 形状保持兼容。
64
+ */
65
+ interface AgentCallOpts {
66
+ /** The task prompt to send to the agent. */
67
+ prompt: string;
68
+ /**
69
+ * Optional JSON schema for structured output.
70
+ * When provided, the schema is passed via PI_WORKFLOW_SCHEMA env to the subprocess,
71
+ * which activates the structured-output tool + turn_end hook.
72
+ * The tool's execute validates model output against the schema.
73
+ * On success, `parsedOutput` on the result is set to `tool_execution_end.result.details`
74
+ * (the validated, parsed data object — not the raw tool call args).
75
+ */
76
+ schema?: Record<string, unknown>;
77
+ /**
78
+ * Model to use (e.g. "router-openai/glm-5.1").
79
+ * When omitted, pi's default model is used.
80
+ */
81
+ model?: string;
82
+ /**
83
+ * Thinking level override (e.g. "high", "medium", "low").
84
+ * M2: Added to align with subagent path's ExecuteOptions.thinkingLevel.
85
+ * When omitted, agent .md frontmatter thinkingLevel is used (via resolveIdentity/getAgentConfig).
86
+ */
87
+ thinkingLevel?: string;
88
+ /** Scene name passed through to the worker for model-selection hints. */
89
+ scene?: string;
90
+ /**
91
+ * Wall-clock timeout in milliseconds. When > 0, aborts the subprocess
92
+ * if it runs longer than this, regardless of external signal.
93
+ * Per-call,归 AgentCall 实体(G-027)。
94
+ */
95
+ timeoutMs?: number;
96
+ /**
97
+ * Turn 上限(turn limiter 用)。
98
+ *
99
+ * [预算语义对齐] 未传或 <=0 = 不限 turn;此时也不按 turns 估算 spawn watchdog——
100
+ * 仅当 env XYZ_SUBAGENT_SPAWN_WATCHDOG_MS 设置时才按绝对时限挂 watchdog(见
101
+ * session-runner.resolveSpawnWatchdogMs)。pi 边界直出为 ExecuteOptions.maxTurns
102
+ * → runSpawn(D6 合流后无中间映射层)。
103
+ */
104
+ maxTurns?: number;
105
+ /**
106
+ * Turn limiter 的宽限轮数(原 AgentTaskSpec.graceTurns 并入):超 maxTurns 后
107
+ * 允许继续的轮数(等待在途工具收尾)。pi 引擎消费;workflow agent() 无写入方,
108
+ * chat 域(ExecuteOptions.graceTurns 同名透传)经 host-task-spec 填充。
109
+ */
110
+ graceTurns?: number;
111
+ /**
112
+ * Skill name to load (e.g. "code-review"). Resolved to SKILL.md path
113
+ * and injected via --skill flag in the subprocess.
114
+ */
115
+ skill?: string;
116
+ /**
117
+ * Resolved absolute path to the skill directory or SKILL.md file.
118
+ * Set by agent-opts-resolver when opts.skill is present.
119
+ */
120
+ skillPath?: string;
121
+ /** Human-readable description for logging and debugging. */
122
+ description?: string;
123
+ /**
124
+ * Agent ref (absolute .md path). Resolved by resolveIdentity via getAgentConfig,
125
+ * which injects the agent's systemPrompt/model/tools/thinkingLevel. Not handled by
126
+ * resolveAgentOpts (single-responsibility: agent ref ownership belongs to resolveIdentity,
127
+ * M2 fix — previously overlapped causing double-injection + model-tier confusion).
128
+ */
129
+ agent?: string;
130
+ /**
131
+ * System prompt injection CONTENT (not file paths).
132
+ * Set by agent-opts-resolver: schema structured-output instruction string.
133
+ * Agent systemPrompt is NOT included here (handled by resolveIdentity/agentConfig).
134
+ * pi 边界直出为 ExecuteOptions.appendSystemPrompt(同名同义透传,D6 合流后无中间映射层)。
135
+ */
136
+ appendSystemPrompt?: string[];
137
+ /**
138
+ * Schema JSON for PI_WORKFLOW_SCHEMA env var.
139
+ * Set by agent-opts-resolver when opts.schema is present (值 = stringifySchemaCached
140
+ * compact,与 schema 派生等值); passed as env var to activate the structured-output
141
+ * tool + hook. pi 边界直出时 schema 派生优先、本字段兜底(解耦形态通道,生产不可达)。
142
+ */
143
+ schemaEnv?: string;
144
+ /**
145
+ * Per-call 工作目录(ADR-029 决策 1)。传给 child_process.spawn 的 cwd option。
146
+ *
147
+ * 用于 worktree 隔离:传入 worktree 绝对路径,spawn 的 pi 子进程绑定到该目录,
148
+ * 其内部的 createAgentSession/ResourceLoader/bash 工具都在该目录运行。
149
+ * undefined 时 spawn 继承 workflow 进程的 cwd(向后兼容)。
150
+ */
151
+ cwd?: string;
152
+ /** Inherit parent session context (fork mode). Independent of worktree (file isolation). */
153
+ fork?: boolean;
154
+ /**
155
+ * fork-from 显式分叉源 session 文件(fork-from 断联恢复通道的唯一 lossless 载体)。
156
+ * 来源 = ExecuteOptions.forkFromSessionFile(host-task-spec 映射时的唯一改名点——
157
+ * 本形状起与 SDK 协议字段、引擎侧 SpawnRunParams.forkSource 三层同名,降低跨层
158
+ * 双名漂移面)。区别于 fork:true(主 session 作分叉源):本字段点名任意已有
159
+ * session 文件。chat 域唯一写入方 = fork-from action。
160
+ */
161
+ forkSource?: string;
162
+ /**
163
+ * 执行引擎 id(P4 D9 三层优先级的第一层:调用参数级,workflow step 显式指定)。
164
+ * 仅限「必须某引擎独有能力」的场景使用并注释原因(D9③ workflow 脚本不写死
165
+ * engine——环境差异由 frontmatter/全局默认承载);透传链 worker-script-builder
166
+ * agent() → execute-agent-call → SAR 路由层。
167
+ */
168
+ engine?: string;
169
+ /** Filesystem isolation: when true, creates a new git worktree for the agent. Independent of fork.
170
+ * [D6 合流] 类型扩展为 boolean | WorktreeHandle(原 AgentTaskSpec.worktree 的超集)——
171
+ * WorktreeHandle 形态仅在 chat 域(复用外部已创建的 worktree)出现,workflow agent()
172
+ * 恒传 boolean。 */
173
+ worktree?: boolean | WorktreeHandle;
174
+ /** When true, agent() resolves {value, sessionFile, worktreePath, error} instead of a bare value.
175
+ * Worker-layer flag only — not consumed by any engine (dropped at the pi boundary). */
176
+ returnMeta?: boolean;
177
+ /**
178
+ * 可持续对话模式(原 AgentTaskSpec.conversation 并入):true = record 标记 chatMode,
179
+ * 轮次完成进 idle 态等待 message 续聊。chat 域(ExecuteOptions.conversation 同名)经
180
+ * host-task-spec 填充;workflow agent() 无写入方。
181
+ */
182
+ conversation?: boolean;
183
+ /**
184
+ * 空闲超时毫秒数(原 AgentTaskSpec.idleTimeoutMs 并入,仅 conversation 模式有意义)。
185
+ * 优先级:参数 > env XYZ_SUBAGENT_IDLE_TIMEOUT_MS > 默认 300000ms;显式 0/负 = 禁用
186
+ * idle GC。chat 域经 host-task-spec 填充。
187
+ */
188
+ idleTimeoutMs?: number;
189
+ /**
190
+ * 工具 denylist(原 AgentTaskSpec.denyTools 并入,中立新增面):各引擎做语法映射
191
+ * (zcode buildZcodeArgv 消费;pi 链路暂无对应面)。无 workflow 写入方,预留形状。
192
+ */
193
+ denyTools?: string[];
194
+ /**
195
+ * 中立权限模式(原 AgentTaskSpec.permissionMode 并入,预留形状):映射按各引擎
196
+ * capabilities.permissionMode。无生产写入方/消费者。
197
+ */
198
+ permissionMode?: string;
199
+ }
200
+
201
+ /**
202
+ * 单次 agent 调用的结果(统一形态)。
203
+ *
204
+ * Engine 直接消费 SubprocessAgentRunner 返回值;callCache replay 时 worker
205
+ * 取 parsedOutput ?? content(见 worker-script-builder.ts 消息处理)。
206
+ */
207
+ interface AgentResult$1 {
208
+ /** Raw text output from the agent. */
209
+ content: string;
210
+ /**
211
+ * [D5-③] 失败分诊结构化标签(AgentFailureKind)。产出侧唯一识别点 =
212
+ * execution/engine/inproc pi 引擎目录/output-collector.ts(collectResult 对最终 error
213
+ * 分类后写入,经 agent-result-mapper / AgentOutcome 透传到本形态);消费侧
214
+ * execute-agent-call 读本字段分诊,不再扫 error 文案子串。
215
+ *
216
+ * 仅在 error !== undefined 时有意义(成功时缺省);缺省视为 unknown = 可重试
217
+ * (语义守恒,见 AgentFailureKind)。
218
+ */
219
+ failureKind?: AgentFailureKind;
220
+ /**
221
+ * Parsed structured output.
222
+ * Present when `schema` was provided and the output was valid JSON.
223
+ * Source: tool_execution_end.result.details(validated data object)。
224
+ */
225
+ parsedOutput?: unknown;
226
+ /** Token and cost usage accumulated across all assistant turns. */
227
+ usage?: AgentOutcomeUsage;
228
+ /** Wall-clock duration in milliseconds. */
229
+ durationMs?: number;
230
+ /** True when the pi process exited with code 0. */
231
+ error?: string;
232
+ /**
233
+ * Pi session ID for the subagent process (uuidv7).
234
+ * Present when pi emits a session header (default in --mode json).
235
+ * Can be used to locate the session JSONL file for post-run inspection (G-017)。
236
+ */
237
+ sessionId?: string;
238
+ /**
239
+ * Session JSONL 绝对路径(不含目录的文件名在 subagents 侧 AgentResult.sessionFile)。
240
+ * 由 mapToWorkflowAgentResult 从 subagents AgentResult 透传——让 workflow 编排层
241
+ * 继承 subagent 执行管道产出的 session 文件路径,overlay/GUI 可直接定位。
242
+ * 窗口期内可能 undefined(session 尚未创建成功)。
243
+ */
244
+ sessionFile?: string;
245
+ /**
246
+ * Absolute path of the git worktree used for filesystem isolation (set when
247
+ * worktree isolation is active). Injected by executeAndAwait from record.worktreeHandle.path.
248
+ *
249
+ * ⚠️ Diagnostic only, may not exist: executeAndAwait's finalizeRecord cleans up the
250
+ * worktree (git worktree remove --force) before returning, so by the time this field
251
+ * reaches the caller the directory has typically been deleted. Use it only for log/trace
252
+ * correlation (e.g. attributing a session jsonl to its worktree origin) — never as a cwd
253
+ * for a subsequent agent or filesystem operation (would ENOENT).
254
+ */
255
+ worktreePath?: string;
256
+ /** All tool calls collected from JSONL stream (FR-7). */
257
+ toolCalls?: ToolCallEntry[];
258
+ }
259
+ /**
260
+ * 执行追踪节点(事件流 D-10 单一来源)。
261
+ */
262
+ interface ExecutionTraceNode {
263
+ stepIndex: number;
264
+ agent: string;
265
+ task: string;
266
+ model: string;
267
+ status: "pending" | "running" | "completed" | "failed";
268
+ /** Phase name for TUI grouping. Set from explicit opts.phase or global _currentPhase. */
269
+ phase?: string;
270
+ startedAt?: string;
271
+ completedAt?: string;
272
+ result?: AgentResult$1;
273
+ error?: string;
274
+ /**
275
+ * Pi session ID (uuidv7) for the subagent process.
276
+ * Used to locate the session JSONL for post-run inspection.
277
+ */
278
+ sessionId?: string;
279
+ /**
280
+ * Session JSONL 绝对路径。finalizeCall 从 result.sessionFile 透传。
281
+ * 持久化到快照(serializeRun),跨 session 重水合后保留。
282
+ */
283
+ sessionFile?: string;
284
+ /**
285
+ * Live 执行进度对象(running 时存在,done 时由 dispatchAgentCall 清除)。
286
+ *
287
+ * 挂在 node 上(D-10 单源延伸:AgentCall.traceNode 与 Trace.nodes 共享同一引用)。
288
+ * TUI 通过 trace.toArray() 读 node.live,派生 getEventLog/getCurrentActivity 实时展示。
289
+ * 不持久化(序列化时 strip;重跑时由 dispatchAgentCall 重建)。
290
+ */
291
+ live?: ExecutionRecord;
292
+ }
293
+ /**
294
+ * Trace.update 用的 patch(字段全可选)。
295
+ *
296
+ * 不变式:只改单个 node 的 status/result/error/completedAt/sessionId。
297
+ * callId 不存在时 update 为 no-op(D-10)。
298
+ */
299
+ interface TracePatch {
300
+ status?: "pending" | "running" | "completed" | "failed";
301
+ result?: AgentResult$1;
302
+ error?: string;
303
+ completedAt?: string;
304
+ sessionId?: string;
305
+ sessionFile?: string;
306
+ }
307
+ /**
308
+ * Worker console.* 捕获条目(run 级诊断,仅展示在 TUI widget,不泄漏到 input area)。
309
+ */
310
+ interface WorkerLogEntry {
311
+ level: "log" | "warn" | "error" | "info";
312
+ message: string;
313
+ }
314
+
3
315
  /**
4
316
  * ModelRegistry 的最小接口(duck-typed,测试可 mock)。
5
317
  * 字段结构与 Pi SDK 的 ctx.modelRegistry 对齐。
@@ -128,75 +440,17 @@ type ProjectedOutcome = ExecutionOutcome | "closed-legacy";
128
440
  * running → active / closed → ended(closed 统一终态,含 cancelled)。
129
441
  * mapExternalState 不消费 ClosedReason——closed 恒映射 ended。
130
442
  *
131
- * waiting / error 是历史多态映射(idle→waiting / failed+crashed→error)的遗留声明:
132
- * 对外四态联合契约不变,但当前状态机不产生这两个值。
133
- *
134
- * 原始 ExecutionStatus 进 list item 的 status 字段供调试;state 是对外主字段。
135
- * 映射实现见 subagent-actions.ts mapExternalState——未来内部加态必须扩展该处,
136
- * 漏加会在 default 分支编译报错,不影响对外契约。
137
- */
138
- type ExternalState = "active" | "waiting" | "ended" | "error";
139
- /** 执行模式。background = 调用方立即拿 handle 返回,子 agent 在 detached promise 里跑。 */
140
- type ExecutionMode = "background";
141
- /**
142
- * Pi session.subscribe 上报的事件。Runtime 把它喂给 updateFromEvent。
143
- *
144
- * 设计:AgentEvent 携带 updateFromEvent 收口进 record 所需的**全部数据**——
145
- * tool_end 带 result(供 turn.toolCalls 存完整 ToolCall),无需翻译层旁路累积。
146
- *
147
- * ACP 词汇对照(D11 注记级校准,零行为变更;新引擎实现者按本表对齐语义,
148
- * 详见 docs/architecture/subagent-engine-gui-visibility.md §3.3 D11):
149
- * text_delta / thinking_delta ↔ ACP content blocks(text / thinking)
150
- * tool_start / tool_end ↔ ACP tool_call / tool_call_update
151
- * turn_end / message_end ↔ ACP prompt turn 终态(stop_reason + usage)
152
- * compaction ↔ ACP session/compaction
153
- * 本协议以 pi 为语义锚点(D3)——命名不迁移,对照表仅保证未来 AcpEngine 适配器
154
- * 与跨引擎 trace 映射的翻译成本最低。
155
- */
156
- type AgentEvent = {
157
- type: "tool_start";
158
- toolName: string;
159
- args?: unknown;
160
- } | {
161
- type: "tool_end";
162
- toolName: string;
163
- args?: unknown;
164
- result?: ToolCallResult;
165
- isError?: boolean;
166
- } | {
167
- type: "text_delta";
168
- delta: string;
169
- } | {
170
- type: "thinking_delta";
171
- delta: string;
172
- } | {
173
- type: "turn_end";
174
- summary?: string;
175
- } | {
176
- type: "message_end";
177
- usage?: AgentUsage$1;
178
- error?: string;
179
- } | {
180
- type: "compaction";
181
- } | {
182
- type: "error";
183
- message: string;
184
- };
185
- /** token 用量(message_end 时由 Core 累加进 record.totalTokens)。 */
186
- interface AgentUsage$1 {
187
- input: number;
188
- output: number;
189
- cacheRead: number;
190
- cacheWrite: number;
191
- /** 本 message 的成本(USD,来自 SDK usage.cost.total)。可选——无成本数据时缺省。 */
192
- cost?: number;
193
- }
194
- interface AgentUsageTotal extends AgentUsage$1 {
195
- /** 上述四项之和。投影时不再手工求和。 */
196
- total: number;
197
- /** 累计成本(USD,来自 SdkEvent.message.usage.cost.total 求和)。无成本数据时为 0。 */
198
- cost: number;
199
- }
443
+ * waiting / error 是历史多态映射(idle→waiting / failed+crashed→error)的遗留声明:
444
+ * 对外四态联合契约不变,但当前状态机不产生这两个值。
445
+ *
446
+ * 原始 ExecutionStatus 进 list item 的 status 字段供调试;state 是对外主字段。
447
+ * 映射实现见 subagent-actions.ts mapExternalState——未来内部加态必须扩展该处,
448
+ * 漏加会在 default 分支编译报错,不影响对外契约。
449
+ */
450
+ type ExternalState = "active" | "waiting" | "ended" | "error";
451
+ /** 执行模式。background = 调用方立即拿 handle 返回,子 agent 在 detached promise 里跑。 */
452
+ type ExecutionMode = "background";
453
+
200
454
  /**
201
455
  * eventLog 条目(getEventLog 派生产出的元素)。所有字段 readonly。
202
456
  *
@@ -230,67 +484,8 @@ interface DisplayItem {
230
484
  /** text:assistant 正文(compact 时取首行/截断)。 */
231
485
  readonly text?: string;
232
486
  }
233
- /** tool 调用结果(tool_execution_end 时累积,含 structured-output 的 details)。 */
234
- interface ToolCallResult {
235
- content?: unknown[];
236
- details?: unknown;
237
- }
238
- /**
239
- * tool 调用(导出的纯净数据形状,不含内部状态)。
240
- *
241
- * tool_start 到达但 tool_end 未到时,调用为进行中;一旦 tool_end 到达,
242
- * result/isError 填充完成。对外投影(AgentResult.toolCalls / getAllToolCalls)
243
- * 一律返回此类型——**不泄漏 running/done/failed 内部状态机**。
244
- *
245
- * 进行中状态由 execution-record 内部的 `InternalToolCall`(= ToolCall + _status)承载,
246
- * 只存在于 record.turns[].toolCalls,跨边界导出时由 getAllToolCalls strip _status。
247
- */
248
- interface ToolCall {
249
- toolName: string;
250
- args?: unknown;
251
- result?: ToolCallResult;
252
- isError?: boolean;
253
- }
254
- /**
255
- * 内部 ToolCall:在 ToolCall 基础上追加 _status 进行中状态标记与 startedTs 时间戳。
256
- *
257
- * running = tool_start 已收到但 tool_end 未到;
258
- * done/failed = tool_end 已到。
259
- *
260
- * 仅存在于 ExecutionRecord.turns[].toolCalls(Core 内部可变状态)。
261
- * 跨边界导出(getAllToolCalls → AgentResult.toolCalls / 持久化)由 getAllToolCalls
262
- * 映射回 ToolCall(丢弃 _status / startedTs),保证导出形状清洁。
263
- */
264
- interface InternalToolCall extends ToolCall {
265
- _status: "running" | "done" | "failed";
266
- /** tool_start 到达时的墙钟时间戳(Date.now(),ms)。getEventLog 派生 tool 条目 ts 用。 */
267
- startedTs: number;
268
- }
269
- /**
270
- * 一个 turn 的完整内容(ExecutionRecord.turns[] 的元素)。
271
- *
272
- * 收口设计:text/thinking 流式累积**完整内容**(非 100 字切片),
273
- * toolCalls 存完整 ToolCall(含 result + _status 内部状态)。turn_end 到达后 closed=true,
274
- * 下次 text/thinking/tool 时开新 turn。
275
- *
276
- * eventLog / currentActivity / result 均从 turns[] 派生,不再独立存储。
277
- */
278
- interface Turn {
279
- /** 本 turn assistant 正文(text_delta 流式累积,完整)。 */
280
- text: string;
281
- /** 本 turn 推理(thinking_delta 流式累积,完整)。 */
282
- thinking: string;
283
- /** 本 turn 工具调用(InternalToolCall:含完整 result + _status 进行中标记)。 */
284
- toolCalls: InternalToolCall[];
285
- /** 本 turn message_end 的 token 增量(聚合得 totalUsage)。 */
286
- usageDelta?: AgentUsage$1;
287
- /** turn_end 是否已到达。false=正在进行;true=已闭合,下次内容开新 turn。 */
288
- closed: boolean;
289
- /** turn_end 到达时的墙钟时间戳(Date.now(),ms)。getEventLog 派生 turn_end 条目 ts 用。 */
290
- closedTs?: number;
291
- }
292
487
  /** 一次 session 执行的完整结果。collectResult 产出,写入 Record.outcome。 */
293
- interface AgentResult$1 {
488
+ interface AgentResult {
294
489
  text: string;
295
490
  turns: number;
296
491
  durationMs: number;
@@ -310,19 +505,7 @@ interface AgentResult$1 {
310
505
  /** schema 模式下,structured-output tool 的 result.details(已通过 schema 校验)。 */
311
506
  parsedOutput?: unknown;
312
507
  }
313
- /**
314
- * worktree handle 值对象。仅 worktree:true 时持有——worktree 是独立维度,
315
- * 需显式开启,fork alone 不创建 worktree。
316
- * Object.freeze 守卫保证不可变。
317
- */
318
- interface WorktreeHandle {
319
- /** checkout 目录(子 agent 工作目录,tmpdir 下)。 */
320
- readonly path: string;
321
- readonly branch: string;
322
- readonly baseCommit: string;
323
- /** 主仓库根目录(cleanup/scan 需要,不再靠路径反推)。 */
324
- readonly mainCwd: string;
325
- }
508
+
326
509
  /** alive marker:子进程存活标记,用于心跳检测和 crash 推断。 */
327
510
  interface AliveMarker {
328
511
  readonly pid: number;
@@ -501,7 +684,7 @@ interface ExecutionRecord {
501
684
  result: string | undefined;
502
685
  error: string | undefined;
503
686
  /** 完整 AgentResult(含 usage/toolCalls,完成时填)。 */
504
- agentResult: AgentResult$1 | undefined;
687
+ agentResult: AgentResult | undefined;
505
688
  /** session jsonl 文件名。session 创建成功后由 session-runner.run() 回填(窗口期内 undefined)。 */
506
689
  sessionFile?: string;
507
690
  /**
@@ -917,590 +1100,509 @@ interface CollectSyncConfig {
917
1100
  * 模型解析已退化为「主 agent model 优先,仅 override 时查 registry」——
918
1101
  * 不再有 category/fallback/yolo 字段。config.json 只保留 maxConcurrent
919
1102
  * (pool 大小)。旧 config.json 中的 categories/fallback 等字段读取时忽略。
920
- */
921
- interface SubagentsGlobalConfig {
922
- version: number;
923
- maxConcurrent: number;
924
- /**
925
- * 全局默认执行引擎(D9 三层优先级的最底层:调用参数 > agent frontmatter > 本值)。
926
- * 缺省 'pi'(P4 路由层 DEFAULT_ENGINE_ID)。加载期只做类型校验,注册表校验归路由层。
927
- */
928
- defaultEngine?: string;
929
- /** 引擎路由策略(D9①):strict=true 时一切 probe 失败直接报错(不 fallback)。 */
930
- engineRouting?: {
931
- strict: boolean;
932
- };
933
- /**
934
- * 同步收集配置节(subagent-sync-collect 设计 §3.1.3,U1 foundation)。
935
- * 整节缺省 = DEFAULT_COLLECT_SYNC(config.ts);逐字段 sanitize 回默认(E5)。
936
- */
937
- collectSync?: CollectSyncConfig;
938
- }
939
- /**
940
- * Record 的只读视图。store.snapshot() 返回。
941
- * TUI 拿到此类型,保证不会回写 Core 状态。
942
- *
943
- * 不含 eventLog——snapshot 的消费点(cancel 判 mode/status、hasRunning 判 mode、
944
- * toNotifyRecord 取 result/error)均不读 eventLog。需要 eventLog 的场景用 project()
945
- * 投影的 SubagentToolDetails。需要完整内容用 record.turns[](Core 内部)。
946
- */
947
- interface RecordSnapshot {
948
- readonly id: string;
949
- readonly agent: string;
950
- readonly model: string;
951
- readonly thinkingLevel: string | undefined;
952
- readonly mode: ExecutionMode;
953
- readonly task: string;
954
- /** 短标签(≤35 字符)。来自 record.slug。 */
955
- readonly slug: string;
956
- readonly status: ExecutionStatus;
957
- /** 对话模式标志(与 ExecutionRecord.chatMode 同源)。cancel 别名判定用。 */
958
- readonly chatMode?: boolean;
959
- readonly turns: number;
960
- readonly totalTokens: number;
961
- readonly startedAt: number;
962
- readonly endedAt: number | undefined;
963
- readonly result: string | undefined;
964
- readonly error: string | undefined;
965
- readonly sessionFile: string | undefined;
966
- }
967
-
968
- /**
969
- * Workflow Extension — Engine 共享类型
970
- *
971
- * Engine 层全局基础类型。零 infra 依赖——不 import 任何 infra 文件,
972
- * 可独立编译测试(D-12 三层架构,AC-1)。
973
- *
974
- * 核心内容:
975
- * - 状态机:RunStatus = "running" | "done"(2 态,一次性生命周期,FR-3)
976
- * + DoneReason(completed/failed/aborted/budget_limited/time_limited)
977
- * - AgentCallOpts / AgentResult / AgentUsage(单次 agent 调用的输入/输出)
978
- * - ExecutionTraceNode / TracePatch / ToolCallEntry / WorkerLogEntry(trace 数据)
979
- *
980
- * 层归属:Engine(数据结构 + 不变式守卫)。
981
- */
982
-
983
- /**
984
- * 状态机:2 态(D-12 / FR-3,一次性生命周期——run 不可挂起)。
985
- *
986
- * running → done
987
- *
988
- * `done` 是唯一终态,具体原因由 DoneReason 区分。
989
- */
990
- type RunStatus = "running" | "done";
991
- /** 终态原因。done 时必有(WorkflowRun 不变式)。 */
992
- type DoneReason = "completed" | "failed" | "aborted" | "budget_limited" | "time_limited" | "invalid_args";
993
- /**
994
- * slug 最大长度(D6 合流迁入本文件,原权威定义在已删除的 execution/execute-options-mapper.ts)。
995
- * 历史值 20 偏紧——描述性 slug 如 "audit-structured-output"(23)/ "fix-subagent-wf-tools"(21)
996
- * 会撞上限,放宽到 35 兼顾「短到能塞进 TUI 标题行」与「容纳合理描述性 kebab-case 名」。
997
- * 放本文件的原因:约束对象是 AgentCallOpts.description(slug 的源字段,见下方 slug 派生说明),
998
- * 与字段同文件;worker-message-pump(live record slug 截断)与壳侧 tool schema maxLength 共享引用。
999
- */
1000
- declare const SLUG_MAX_LENGTH = 35;
1001
- /**
1002
- * 单次 agent 调用的任务声明(D6 任务形状合流后的单一形状)。
1003
- *
1004
- * [D6 合流裁决] 本类型 = 原 AgentCallOpts(workflow 调用方声明,18 字段)与原
1005
- * AgentTaskSpec(engine 中立任务声明,已删除)的合流形态,从模型脚本 agent() API
1006
- * 到 EnginePort.run 直达 pi 边界一次映射——SAR 链路上的 ExecuteOptions/AgentTaskSpec
1007
- * 中间态消除(设计 docs/design/subagent-dual-track-convergence.md §3.3 D6 / 终态四)。
1008
- *
1009
- * 终态命名按变化轴裁定为 AgentCallOpts,理由:
1010
- * - 字段演进的首要驱动轴是「调用方要表达的任务语义」(agent() API 是唯一生产写入方,
1011
- * 合流字段中 prompt/description/skill/skillPath/schemaEnv/thinkingLevel 等多数派
1012
- * 已是调用方命名);
1013
- * - 原 AgentTaskSpec 的中立重命名层(task/slug/effort/persona)与调用方命名是
1014
- * 形式同构、语义同构的假差异(prompt≡task、slug=description 截断、effort≡thinkingLevel、
1015
- * persona≡skillPath+appendSystemPrompt 平铺),按「消假差异」原则并入调用方命名;
1016
- * - 持久化兼容反向锁定 prompt 形态:jsonl run 快照的 AgentCall.opts 与 worker 消息
1017
- * opts 均以 prompt 字段落盘,改名会破坏旧快照重水合。
1018
- *
1019
- * 引擎中立字段的并入方式(可选字段,原 AgentTaskSpec 独有字段去向):
1020
- * - graceTurns / conversation / idleTimeoutMs / denyTools / permissionMode:可选并入;
1021
- * - persona.agentRef:裁撤(无生产写入方、无消费者——pi 走 agent 字段解析身份);
1022
- * - requires:裁撤(P4 形状预留、无生产写入方;且并入需 import EngineCapabilities
1023
- * 形成 orchestration↔engine 类型环)。将来能力依赖声明下钻时在本形状上加回。
1024
- *
1025
- * D-12 仅重组执行编排,AgentCallOpts 形状保持兼容。
1026
- */
1027
- interface AgentCallOpts {
1028
- /** The task prompt to send to the agent. */
1029
- prompt: string;
1030
- /**
1031
- * Optional JSON schema for structured output.
1032
- * When provided, the schema is passed via PI_WORKFLOW_SCHEMA env to the subprocess,
1033
- * which activates the structured-output tool + turn_end hook.
1034
- * The tool's execute validates model output against the schema.
1035
- * On success, `parsedOutput` on the result is set to `tool_execution_end.result.details`
1036
- * (the validated, parsed data object — not the raw tool call args).
1037
- */
1038
- schema?: Record<string, unknown>;
1039
- /**
1040
- * Model to use (e.g. "router-openai/glm-5.1").
1041
- * When omitted, pi's default model is used.
1042
- */
1043
- model?: string;
1044
- /**
1045
- * Thinking level override (e.g. "high", "medium", "low").
1046
- * M2: Added to align with subagent path's ExecuteOptions.thinkingLevel.
1047
- * When omitted, agent .md frontmatter thinkingLevel is used (via resolveIdentity/getAgentConfig).
1048
- */
1049
- thinkingLevel?: string;
1050
- /** Scene name passed through to the worker for model-selection hints. */
1051
- scene?: string;
1052
- /**
1053
- * Wall-clock timeout in milliseconds. When > 0, aborts the subprocess
1054
- * if it runs longer than this, regardless of external signal.
1055
- * Per-call,归 AgentCall 实体(G-027)。
1056
- */
1057
- timeoutMs?: number;
1058
- /**
1059
- * Turn 上限(turn limiter 用)。
1060
- *
1061
- * [预算语义对齐] 未传或 <=0 = 不限 turn;此时也不按 turns 估算 spawn watchdog——
1062
- * 仅当 env XYZ_SUBAGENT_SPAWN_WATCHDOG_MS 设置时才按绝对时限挂 watchdog(见
1063
- * session-runner.resolveSpawnWatchdogMs)。pi 边界直出为 ExecuteOptions.maxTurns
1064
- * → runSpawn(D6 合流后无中间映射层)。
1065
- */
1066
- maxTurns?: number;
1067
- /**
1068
- * Turn limiter 的宽限轮数(原 AgentTaskSpec.graceTurns 并入):超 maxTurns 后
1069
- * 允许继续的轮数(等待在途工具收尾)。pi 引擎消费;workflow agent() 无写入方,
1070
- * chat 域(ExecuteOptions.graceTurns 同名透传)经 host-task-spec 填充。
1071
- */
1072
- graceTurns?: number;
1073
- /**
1074
- * Skill name to load (e.g. "code-review"). Resolved to SKILL.md path
1075
- * and injected via --skill flag in the subprocess.
1076
- */
1077
- skill?: string;
1078
- /**
1079
- * Resolved absolute path to the skill directory or SKILL.md file.
1080
- * Set by agent-opts-resolver when opts.skill is present.
1081
- */
1082
- skillPath?: string;
1083
- /** Human-readable description for logging and debugging. */
1084
- description?: string;
1085
- /**
1086
- * Agent ref (absolute .md path). Resolved by resolveIdentity via getAgentConfig,
1087
- * which injects the agent's systemPrompt/model/tools/thinkingLevel. Not handled by
1088
- * resolveAgentOpts (single-responsibility: agent ref ownership belongs to resolveIdentity,
1089
- * M2 fix — previously overlapped causing double-injection + model-tier confusion).
1090
- */
1091
- agent?: string;
1092
- /**
1093
- * System prompt injection CONTENT (not file paths).
1094
- * Set by agent-opts-resolver: schema structured-output instruction string.
1095
- * Agent systemPrompt is NOT included here (handled by resolveIdentity/agentConfig).
1096
- * pi 边界直出为 ExecuteOptions.appendSystemPrompt(同名同义透传,D6 合流后无中间映射层)。
1097
- */
1098
- appendSystemPrompt?: string[];
1099
- /**
1100
- * Schema JSON for PI_WORKFLOW_SCHEMA env var.
1101
- * Set by agent-opts-resolver when opts.schema is present (值 = stringifySchemaCached
1102
- * compact,与 schema 派生等值); passed as env var to activate the structured-output
1103
- * tool + hook. pi 边界直出时 schema 派生优先、本字段兜底(解耦形态通道,生产不可达)。
1104
- */
1105
- schemaEnv?: string;
1106
- /**
1107
- * Per-call 工作目录(ADR-029 决策 1)。传给 child_process.spawn 的 cwd option。
1108
- *
1109
- * 用于 worktree 隔离:传入 worktree 绝对路径,spawn 的 pi 子进程绑定到该目录,
1110
- * 其内部的 createAgentSession/ResourceLoader/bash 工具都在该目录运行。
1111
- * undefined 时 spawn 继承 workflow 进程的 cwd(向后兼容)。
1112
- */
1113
- cwd?: string;
1114
- /** Inherit parent session context (fork mode). Independent of worktree (file isolation). */
1115
- fork?: boolean;
1116
- /**
1117
- * 执行引擎 id(P4 D9 三层优先级的第一层:调用参数级,workflow step 显式指定)。
1118
- * 仅限「必须某引擎独有能力」的场景使用并注释原因(D9③ workflow 脚本不写死
1119
- * engine——环境差异由 frontmatter/全局默认承载);透传链 worker-script-builder
1120
- * agent() → execute-agent-call → SAR 路由层。
1121
- */
1122
- engine?: string;
1123
- /** Filesystem isolation: when true, creates a new git worktree for the agent. Independent of fork.
1124
- * [D6 合流] 类型扩展为 boolean | WorktreeHandle(原 AgentTaskSpec.worktree 的超集)——
1125
- * WorktreeHandle 形态仅在 chat 域(复用外部已创建的 worktree)出现,workflow agent()
1126
- * 恒传 boolean。 */
1127
- worktree?: boolean | WorktreeHandle;
1128
- /** When true, agent() resolves {value, sessionFile, worktreePath, error} instead of a bare value.
1129
- * Worker-layer flag only — not consumed by any engine (dropped at the pi boundary). */
1130
- returnMeta?: boolean;
1131
- /**
1132
- * 可持续对话模式(原 AgentTaskSpec.conversation 并入):true = record 标记 chatMode,
1133
- * 轮次完成进 idle 态等待 message 续聊。chat 域(ExecuteOptions.conversation 同名)经
1134
- * host-task-spec 填充;workflow agent() 无写入方。
1135
- */
1136
- conversation?: boolean;
1137
- /**
1138
- * 空闲超时毫秒数(原 AgentTaskSpec.idleTimeoutMs 并入,仅 conversation 模式有意义)。
1139
- * 优先级:参数 > env XYZ_SUBAGENT_IDLE_TIMEOUT_MS > 默认 300000ms;显式 0/负 = 禁用
1140
- * idle GC。chat 域经 host-task-spec 填充。
1141
- */
1142
- idleTimeoutMs?: number;
1103
+ */
1104
+ interface SubagentsGlobalConfig {
1105
+ version: number;
1106
+ maxConcurrent: number;
1143
1107
  /**
1144
- * 工具 denylist(原 AgentTaskSpec.denyTools 并入,中立新增面):各引擎做语法映射
1145
- * (zcode buildZcodeArgv 消费;pi 链路暂无对应面)。无 workflow 写入方,预留形状。
1108
+ * 全局默认执行引擎(D9 三层优先级的最底层:调用参数 > agent frontmatter > 本值)。
1109
+ * 缺省 'pi'(P4 路由层 DEFAULT_ENGINE_ID)。加载期只做类型校验,注册表校验归路由层。
1146
1110
  */
1147
- denyTools?: string[];
1111
+ defaultEngine?: string;
1112
+ /** 引擎路由策略(D9①):strict=true 时一切 probe 失败直接报错(不 fallback)。 */
1113
+ engineRouting?: {
1114
+ strict: boolean;
1115
+ };
1148
1116
  /**
1149
- * 中立权限模式(原 AgentTaskSpec.permissionMode 并入,预留形状):映射按各引擎
1150
- * capabilities.permissionMode。无生产写入方/消费者。
1117
+ * 同步收集配置节(subagent-sync-collect 设计 §3.1.3,U1 foundation)。
1118
+ * 整节缺省 = DEFAULT_COLLECT_SYNC(config.ts);逐字段 sanitize 回默认(E5)。
1151
1119
  */
1152
- permissionMode?: string;
1120
+ collectSync?: CollectSyncConfig;
1153
1121
  }
1154
1122
  /**
1155
- * 单次 agent 调用的资源用量(FR-7 跨 turn 累积)。
1123
+ * Record 的只读视图。store.snapshot() 返回。
1124
+ * TUI 拿到此类型,保证不会回写 Core 状态。
1125
+ *
1126
+ * 不含 eventLog——snapshot 的消费点(cancel 判 mode/status、hasRunning 判 mode、
1127
+ * toNotifyRecord 取 result/error)均不读 eventLog。需要 eventLog 的场景用 project()
1128
+ * 投影的 SubagentToolDetails。需要完整内容用 record.turns[](Core 内部)。
1156
1129
  */
1157
- interface AgentUsage {
1158
- input: number;
1159
- output: number;
1160
- cacheRead: number;
1161
- cacheWrite: number;
1162
- cost: number;
1163
- contextTokens: number;
1164
- turns: number;
1130
+ interface RecordSnapshot {
1131
+ readonly id: string;
1132
+ readonly agent: string;
1133
+ readonly model: string;
1134
+ readonly thinkingLevel: string | undefined;
1135
+ readonly mode: ExecutionMode;
1136
+ readonly task: string;
1137
+ /** 短标签(≤35 字符)。来自 record.slug。 */
1138
+ readonly slug: string;
1139
+ readonly status: ExecutionStatus;
1140
+ /** 对话模式标志(与 ExecutionRecord.chatMode 同源)。cancel 别名判定用。 */
1141
+ readonly chatMode?: boolean;
1142
+ readonly turns: number;
1143
+ readonly totalTokens: number;
1144
+ readonly startedAt: number;
1145
+ readonly endedAt: number | undefined;
1146
+ readonly result: string | undefined;
1147
+ readonly error: string | undefined;
1148
+ readonly sessionFile: string | undefined;
1165
1149
  }
1150
+
1166
1151
  /**
1167
- * 单次 tool 调用记录(FR-7 从 agent JSONL 流采)。
1152
+ * 引擎会话句柄(run 返回、interact/read 入参)。
1153
+ *
1154
+ * 契约三条(D1):不透明(上层不解构——唯一例外是 record 持久化层序列化 data 字段与
1155
+ * read 降级链)、可持久化(data 是纯 JSON,主会话 reload 后 read/interact 仍可用)、
1156
+ * 自描述(data 含 engineId + 引擎 session 定位符 + pool key + adapter 版本)。
1157
+ *
1158
+ * 对进程已死的 handle 调 interact 必须返回 engine_session_not_resumable(指向 cold
1159
+ * resume 路径),而非笼统失败——由各引擎 interact 实现保证。
1168
1160
  */
1169
- interface ToolCallEntry {
1170
- /** Tool name. */
1171
- name: string;
1172
- /** Args preview string. */
1173
- input: string;
1161
+ interface EngineHandle {
1162
+ /** 持久化数据。上层不得解构其内部字段(见契约三条)。 */
1163
+ readonly data: EngineHandleData;
1174
1164
  }
1165
+
1175
1166
  /**
1176
- * 失败分诊结构化标签(D5-③,r1 MF4 钉正语义)。
1167
+ * subagent text_delta streaming sink。
1177
1168
  *
1178
- * - stale_context:pi session context compact/cancel/替换——重试无意义(同 call
1179
- * 再次失败),不重试。
1180
- * - schema_deterministic:确定性 schema 失败(SO tool 从未调用 / gate 终止 /
1181
- * 不可满足 schema)——同 schema 重试必同结果,不重试。
1182
- * - unknown:其余一切失败(瞬态 provider 错误、spawn 失败等)——**默认可重试**。
1169
+ * background subagent 执行期间,session-runner agentEvent 出口把每个 text_delta
1170
+ * 传到 SubagentStream.onDelta。本模块做 100ms 时间窗合并后,通过 StreamSink.setWidget
1171
+ * 转发到 RPC stdout(经 ctx.ui.setWidget extension_ui_request 通道)。
1183
1172
  *
1184
- * **语义守恒(最高优先约束)**:unknown(含字段缺省)= 可重试——保持收敛前的
1185
- * 默认重试语义;仅 stale_context schema_deterministic 两态维持不重试特判。
1186
- * 词表归属(产出侧单点识别):stale_context / schema_deterministic 的识别词表
1187
- * (stale 词表与确定性 schema 失败标记前缀)保留在产出侧
1188
- * execution/engine/engines/pi/output-collector.ts 包内——词表漂移的失效模式是
1189
- * failureKind=unknown 保守重试(安全默认),不再是静默漏诊。
1173
+ * SubagentStream 是一个生命周期对象——内聚 buffer/timer 状态 + onDelta/dispose 方法。
1174
+ * 调用方(subagent-service)创建后只需在 text_delta 时调 onDelta、终态时调 dispose,
1175
+ * 不需要拆散 push/clear 两个函数跨层透传。
1176
+ *
1177
+ * 设计要点:
1178
+ * - leading edge:第一个 delta 立即 flush(前端尽快看到开始)
1179
+ * - trailing edge:后续 delta 追加 buffer,timer 到期后 flush
1180
+ * - 每次 flush 把 buffer 的累积文本 split("\n") 截尾 MAX_WIDGET_LINES 行传给 setWidget
1181
+ * - dispose 清除 widget + 清 timer
1190
1182
  */
1191
- type AgentFailureKind = "stale_context" | "schema_deterministic" | "unknown";
1183
+
1184
+ /** UI streaming sink 的最小接口(ctx.ui.setWidget 的 duck-typed 子集)。
1185
+ *
1186
+ * 当前只有一个 adapter(index.ts session_start 包装 ctx.ui.setWidget)。
1187
+ * 保留接口而非裸函数类型,因为 StreamSink 的语义是「UI sink 契约」——
1188
+ * 测试 mock 和未来可能的第二 sink(如写文件)都走此契约。 */
1189
+ interface StreamSink {
1190
+ setWidget(key: string, lines: string[] | undefined): void;
1191
+ }
1192
1192
  /**
1193
- * 单次 agent 调用的结果(统一形态)。
1193
+ * subagent text_delta streaming 生命周期对象。
1194
1194
  *
1195
- * Engine 直接消费 SubprocessAgentRunner 返回值;callCache replay 时 worker
1196
- * parsedOutput ?? content(见 worker-script-builder.ts 消息处理)。
1195
+ * 创建后:
1196
+ * - `onDelta(delta)`:session-runner 每次 text_delta
1197
+ * - `dispose()`:subagent 终态时调,清除 widget + 清 timer
1198
+ *
1199
+ * buffer/timer 状态全部内聚在此对象,调用方不需要关心合并逻辑。
1197
1200
  */
1198
- interface AgentResult {
1199
- /** Raw text output from the agent. */
1200
- content: string;
1201
- /**
1202
- * [D5-③] 失败分诊结构化标签(AgentFailureKind)。产出侧唯一识别点 =
1203
- * execution/engine/engines/pi/output-collector.ts(collectResult 对最终 error
1204
- * 分类后写入,经 agent-result-mapper / AgentOutcome 透传到本形态);消费侧
1205
- * execute-agent-call 读本字段分诊,不再扫 error 文案子串。
1206
- *
1207
- * 仅在 error !== undefined 时有意义(成功时缺省);缺省视为 unknown = 可重试
1208
- * (语义守恒,见 AgentFailureKind)。
1209
- */
1210
- failureKind?: AgentFailureKind;
1211
- /**
1212
- * Parsed structured output.
1213
- * Present when `schema` was provided and the output was valid JSON.
1214
- * Source: tool_execution_end.result.details(validated data object)。
1215
- */
1216
- parsedOutput?: unknown;
1217
- /** Token and cost usage accumulated across all assistant turns. */
1218
- usage?: AgentUsage;
1219
- /** Wall-clock duration in milliseconds. */
1220
- durationMs?: number;
1221
- /** True when the pi process exited with code 0. */
1222
- error?: string;
1223
- /**
1224
- * Pi session ID for the subagent process (uuidv7).
1225
- * Present when pi emits a session header (default in --mode json).
1226
- * Can be used to locate the session JSONL file for post-run inspection (G-017)。
1227
- */
1228
- sessionId?: string;
1229
- /**
1230
- * Session JSONL 绝对路径(不含目录的文件名在 subagents 侧 AgentResult.sessionFile)。
1231
- * 由 mapToWorkflowAgentResult 从 subagents AgentResult 透传——让 workflow 编排层
1232
- * 继承 subagent 执行管道产出的 session 文件路径,overlay/GUI 可直接定位。
1233
- * 窗口期内可能 undefined(session 尚未创建成功)。
1234
- */
1235
- sessionFile?: string;
1236
- /**
1237
- * Absolute path of the git worktree used for filesystem isolation (set when
1238
- * worktree isolation is active). Injected by executeAndAwait from record.worktreeHandle.path.
1239
- *
1240
- * ⚠️ Diagnostic only, may not exist: executeAndAwait's finalizeRecord cleans up the
1241
- * worktree (git worktree remove --force) before returning, so by the time this field
1242
- * reaches the caller the directory has typically been deleted. Use it only for log/trace
1243
- * correlation (e.g. attributing a session jsonl to its worktree origin) — never as a cwd
1244
- * for a subsequent agent or filesystem operation (would ENOENT).
1245
- */
1246
- worktreePath?: string;
1247
- /** All tool calls collected from JSONL stream (FR-7). */
1248
- toolCalls?: ToolCallEntry[];
1201
+ declare class SubagentStream {
1202
+ private readonly widgetKey;
1203
+ private readonly sink;
1204
+ private buffer;
1205
+ private timer;
1206
+ private hasFlushed;
1207
+ private disposed;
1208
+ constructor(recordId: string, sink: StreamSink);
1209
+ /** 接收一个 text_delta 增量。空串静默丢弃(不消耗 leading edge)。 */
1210
+ onDelta(delta: string): void;
1211
+ /** 终态清理:清除 widget + 清 timer(幂等)。 */
1212
+ dispose(): void;
1213
+ private flush;
1249
1214
  }
1215
+
1250
1216
  /**
1251
- * 执行追踪节点(事件流 D-10 单一来源)。
1217
+ * run 的运行期上下文。任务声明(AgentCallOpts,D6 合流后的单一形状)与运行期句柄
1218
+ * 分离——signal/ctxModel/onComplete 从 ExecuteOptions 移出(设计 §3.3.5 删字段去向),
1219
+ * 因为它们是宿主注入的运行期对象,不属于跨引擎持久化的任务声明。
1220
+ *
1221
+ * 常驻进程友好(D1):onEvent 回调式(而非迭代器式)+ AbortSignal——引擎内部换常驻
1222
+ * server 实现(未来 driver host)时接口不动。
1252
1223
  */
1253
- interface ExecutionTraceNode {
1254
- stepIndex: number;
1255
- agent: string;
1256
- task: string;
1257
- model: string;
1258
- status: "pending" | "running" | "completed" | "failed";
1259
- /** Phase name for TUI grouping. Set from explicit opts.phase or global _currentPhase. */
1260
- phase?: string;
1261
- startedAt?: string;
1262
- completedAt?: string;
1263
- result?: AgentResult;
1264
- error?: string;
1224
+ interface RunContext {
1225
+ /** = record.id(bg-N-xxx / run-N)——journal 文件名与池引用计数 key(P2 消费)。 */
1226
+ taskId: string;
1227
+ /** D5 隔离池(宿主分配,设计 §3.3.9;pi 无池化恒 'shared')。 */
1228
+ poolKey: string;
1229
+ /** abort 分级入口(D1:引擎原生中断 公共杀链兜底)。 */
1230
+ signal?: AbortSignal;
1231
+ /** 事件流出口(host 消费后统一落 journal,D6 第②级)。 */
1232
+ onEvent?: (event: AgentEvent) => void;
1233
+ /**
1234
+ * model 解析第三层兜底(现有 D-008 语义不变)——**pi 链路专属兜底**:经
1235
+ * taskSpecToExecuteOptions → resolveModel 第三层消费(PiEngine 直通)。自带
1236
+ * provider 体系与缺省模型的引擎(如 zcode:requested > 引擎缺省常量链)按自身
1237
+ * 默认链解析,不消费本字段(zcode 侧在「ctx 有模型但被忽略」时出声留痕,
1238
+ * zcode-engine.warnIgnoredCtxModel)。
1239
+ */
1240
+ ctxModel?: ModelInfo;
1265
1241
  /**
1266
- * Pi session ID (uuidv7) for the subagent process.
1267
- * Used to locate the session JSONL for post-run inspection.
1268
- */
1269
- sessionId?: string;
1242
+ * text_delta streaming 通道(宿主侧 UI widget)。与 onEvent 平行的 text_delta 出口:
1243
+ * background 路径 onEvent=undefined 但流式仍需送达(双通道互斥设计,见 session-runner
1244
+ * agentEvent 出口注释)。pi 回填期承载 AgentRunner port 的 stream 透传(行为零变化),
1245
+ * 语义上是宿主设施而非引擎专有——未来引擎的 text_delta 同样可走此通道。
1246
+ */
1247
+ stream?: SubagentStream;
1270
1248
  /**
1271
- * Session JSONL 绝对路径。finalizeCall result.sessionFile 透传。
1272
- * 持久化到快照(serializeRun),跨 session 重水合后保留。
1273
- */
1274
- sessionFile?: string;
1249
+ * [P1 pi 回填透传] 调用方已持有的 schema 激活预编码值(AgentCallOpts.schemaEnv 直传
1250
+ * 形态)。生产路径中 resolveAgentOpts 恒耦合产出 schema+schemaEnv(值 = JSON.stringify
1251
+ * (schema)),引擎从 task.schema 派生即可逐字节等值;解耦形态(有 schemaEnv 无
1252
+ * schema)生产不可达、仅见于直构调用,派生无源——本字段是其唯一透交通道。
1253
+ * 引擎在 task.schema 存在时忽略此值(派生优先,设计 §3.3.5 删字段去向)。
1254
+ */
1255
+ schemaEnv?: string;
1275
1256
  /**
1276
- * Live 执行进度对象(running 时存在,done 时由 dispatchAgentCall 清除)。
1277
- *
1278
- * 挂在 node 上(D-10 单源延伸:AgentCall.traceNode 与 Trace.nodes 共享同一引用)。
1279
- * TUI 通过 trace.toArray() 读 node.live,派生 getEventLog/getCurrentActivity 实时展示。
1280
- * 不持久化(序列化时 strip;重跑时由 dispatchAgentCall 重建)。
1281
- */
1282
- live?: ExecutionRecord;
1257
+ * [P4 D9①] 引擎 fallback 留痕(probe 失败路由回默认引擎)。路由层(routing.ts)
1258
+ * 产出,引擎投影到 outcome.engineFallback(zcode 等无 record 通路的引擎以此留痕;
1259
+ * pi 引擎另经 ExecuteOptions 投影进 record)。
1260
+ */
1261
+ engineFallback?: {
1262
+ from: string;
1263
+ reason: string;
1264
+ };
1265
+ /**
1266
+ * [P4 对齐点③] 引擎声明实际隔离池 key(journal 落盘路径权威)。宿主创建 journal
1267
+ * writer 时只能用缺省占位 poolKey(pi 恒 'shared'),非池化稳定的引擎(zcode 按
1268
+ * provider+model 池化)在 prepare 期确定 poolKey 后回调本方法重定向 writer——
1269
+ * 保证 journal 落盘路径与 handle.poolKey 同源(单一权威,不再两边推导)。
1270
+ * 契约:必须在首个事件 emit 之前调用(zcode coarse 事件在终态后合成,天然满足;
1271
+ * 未来流式引擎需在事件出口前调用)。
1272
+ */
1273
+ onPoolResolved?: (poolKey: string) => void;
1274
+ /**
1275
+ * [R4 §3.4 不变量 3] 运行中句柄回填通道:引擎在「session/create 应答到达后」
1276
+ * 立即回调(早于 run resolve——stream 引擎的 run 生命周期远长于会话建立)。
1277
+ * 与 onPoolResolved 分立两个时点:poolKey 在 prepare 期(onPoolResolved,连接
1278
+ * 建立前即可知),sessionRef 在 create 应答后(本回调)。编排层收到后立即回填
1279
+ * record.engineHandle 并落 entry——运行中的 GUI 经 entry 重建 record 即拿到
1280
+ * ①②级读取钥匙,不再等 run resolve 后的终态回填。可选回调:不支持运行中回填
1281
+ * 的引擎(spawn 单轮、终态即回填)不调用,宿主语义不受影响。
1282
+ */
1283
+ onHandleReady?: (partial: Pick<EngineHandleData, "sessionRef" | "poolKey">) => void;
1284
+ /**
1285
+ * [U0 D10] 引擎 spawn 的子进程句柄注册钩子(宿主终止链记账)。引擎在 spawn 成功后
1286
+ * 同步回调(与 pi runSpawn 的 spawnedChildren.set 同构时机);宿主据此把 child 注册进
1287
+ * session-runner 的 spawnedChildren Map(cancel SIGTERM / dispose 收割兜底 / killAll
1288
+ * 全量清理对非 pi 引擎 record 生效)。close/error 后由宿主按句守卫移除。可选:引擎
1289
+ * 内部不 spawn 进程(如未来常驻 driver host 实现)时不调用,宿主记账自然为空。
1290
+ *
1291
+ * 边界声明(R1 D6):本钩子只用于 per-record 一次性 spawn(一任务一进程模态)。
1292
+ * 引擎持有的常驻进程(跨任务共享,如 app-server 常驻连接)不经本钩子注册、不进
1293
+ * spawnedChildren Map——其生命周期完全归引擎 dispose 管理(防 per-record 重复
1294
+ * SIGTERM / 单任务 abort 误杀共享进程)。
1295
+ */
1296
+ onChildSpawned?: (child: ChildProcess) => void;
1297
+ /**
1298
+ * [W3 v1.x] chat 会话形态参数(协议 run.params.chat 的 RunContext 承载位):
1299
+ * - recordId:core 预建 record 的关联键(引擎据此上报首轮 runId 键之外的反向
1300
+ * 载荷与 interact 定位)——task.conversation === true 的 chat 轮必传;
1301
+ * - resume:冷续锚点(重开已 idle 的 session 续聊;pi 消费 sessionRef.sessionFile
1302
+ * ——对照协议化设计前 SpawnResumeOpts.sessionFile 的锚点面)。
1303
+ * 类型权威 = SDK RunChatParams(remote-engine 直传,结构互证由 implements 关系
1304
+ * 在 typecheck 期承载)。非 chat 轮不传,wire 上不出现该键。
1305
+ */
1306
+ chat?: {
1307
+ recordId: string;
1308
+ resume?: ResumeAnchor;
1309
+ };
1310
+ /**
1311
+ * [W3 v1.x] host/roundLifecycle 轮次生命周期消费口(第 9 反向通道,settled/idle/
1312
+ * failed 三相位;关联键 runId|recordId 互斥)。首轮(run 会话形态)经 run 作用域
1313
+ * 路由到达(runId 键);续聊轮(interact)无 runId——经 EnginePort
1314
+ * registerChatRoundRoute 的 recordId 键路由到达(见下)。消费语义(arm/disarm/
1315
+ * settled 交棒)归宿主编排层(settled-watchdog 协议事件面接线,W4 三入口)。
1316
+ */
1317
+ onRoundLifecycle?: (phase: HostRoundLifecycleParams) => void;
1283
1318
  }
1284
1319
  /**
1285
- * Trace.update 用的 patch(字段全可选)。
1286
- *
1287
- * 不变式:只改单个 node status/result/error/completedAt/sessionId。
1288
- * callId 不存在时 update 为 no-op(D-10)。
1320
+ * [W3 v1.x] chat 轮次反向通道路由(recordId 键)——interact 续聊轮的 streamDelta /
1321
+ * roundLifecycle 分发目标(协议关联键裁定 D1-A:续聊轮无独立 runId)。与 run 作用域
1322
+ * RunRoute 同构的薄消费面;注册/注销时机归宿主 chat 编排(轮开始注册、record 终态注销)。
1289
1323
  */
1290
- interface TracePatch {
1291
- status?: "pending" | "running" | "completed" | "failed";
1292
- result?: AgentResult;
1293
- error?: string;
1294
- completedAt?: string;
1295
- sessionId?: string;
1296
- sessionFile?: string;
1324
+ interface ChatRoundRoute {
1325
+ onStreamDelta?: (delta: string) => void | Promise<void>;
1326
+ onRoundLifecycle?: (phase: HostRoundLifecycleParams) => void | Promise<void>;
1297
1327
  }
1298
1328
  /**
1299
- * Worker console.* 捕获条目(run 级诊断,仅展示在 TUI widget,不泄漏到 input area)。
1329
+ * run 的返回:终态 + 可持久化 handle。
1330
+ *
1331
+ * handle 语义(设计 §3.3.5 run 错误语义三条):prepare 期错误(credential_missing /
1332
+ * model_not_available / prompt_too_large)在进程创建前 reject、不产生 handle;运行中
1333
+ * 失败不 reject——合成 error outcome + 正常 handle 返回(record 必须收尾);abort 走
1334
+ * 完杀链后同前(exitCode=null + error 含杀链标记)。
1300
1335
  */
1301
- interface WorkerLogEntry {
1302
- level: "log" | "warn" | "error" | "info";
1303
- message: string;
1336
+ interface EngineRunResult {
1337
+ handle: EngineHandle;
1338
+ outcome: AgentOutcome;
1304
1339
  }
1305
-
1306
1340
  /**
1307
- * 一次引擎执行的终态。锚定 orchestration/models/types.ts 的 AgentResultworkflow
1308
- * 引擎消费的那份——content/parsedOutput/usage/error)并追加引擎层字段;见文件头消歧说明。
1341
+ * subagent 执行引擎的唯一契约点(D1)。实现方:PiEngine(回填)/ ZcodeEngineP3)/
1342
+ * 未来各引擎适配器。上层(工具面/workflow 引擎/GUI)只消费中立类型,不感知引擎。
1343
+ *
1344
+ * 贯穿纪律(设计 §3.3.1):宿主编排——引擎只当单 agent 执行器,六家原生多 agent 机制
1345
+ * 一律禁用不依赖。
1309
1346
  */
1310
- interface AgentOutcome {
1311
- /** 原样(AgentResult.content)。 */
1312
- content: string;
1313
- /**
1314
- * 原样(AgentResult.failureKind,D5-③ 失败分诊结构化标签)。产出侧唯一识别点 =
1315
- * engines/pi/output-collectorcollectResult 分类写入);缺省 = unknown = 可重试
1316
- * (消费侧 executeAgentCall 只读字段分诊,不扫 error 文案)。非 pi 引擎不产出,
1317
- * 恒缺省(unknown 语义)。
1347
+ interface EnginePort {
1348
+ /** 注册表 key('pi' | 'zcode' | ...)。 */
1349
+ readonly id: string;
1350
+ /** D3(同步无副作用——调用前拒绝的判据)。 */
1351
+ capabilities(): EngineCapabilities;
1352
+ /** D7factory 初始化 + 版本变化检测触发;opts.force 跳过缓存强探)。 */
1353
+ probe(opts?: {
1354
+ force?: boolean;
1355
+ }): Promise<ProbeReport>;
1356
+ /** D1 主语义:fire-to-completion。[D6 合流] task = AgentCallOpts(单一任务形状,
1357
+ * 原 AgentTaskSpec 已并入——字段裁定见 orchestration/models/types.ts)。 */
1358
+ run(task: AgentCallOpts, ctx: RunContext): Promise<EngineRunResult>;
1359
+ /**
1360
+ * D1 可选面:交互控制面。pi 首期原生实现(现有 chatMode 行为直通);不支持
1361
+ * conversation 的引擎返回 engine_capability_unsupported(同步拒绝、不创建进程)。
1318
1362
  */
1319
- failureKind?: AgentFailureKind;
1320
- /**
1321
- * 原样(AgentResult.parsedOutput)。native 引擎直传 / 仿真层 ajv 产出(D4 硬分流:
1322
- * native 路径公共层不做二次校验、不改写其结果)。
1363
+ interact(handle: EngineHandle, action: InteractAction): Promise<InteractResult>;
1364
+ /** D6 三级降级链:①引擎原生读取 → ②宿主 event journal(P2)→ ③outcome-only。 */
1365
+ read(handle: EngineHandle): Promise<SessionView>;
1366
+ /**
1367
+ * [W3 v1.x] 可选面:chat 轮次反向通道路由注册(recordId 键)。interact 续聊轮的
1368
+ * streamDelta / roundLifecycle 按 recordId 关联(无 runId,D1-A),引擎进程发射后
1369
+ * 经协议客户端分发到本路由。与 validateModel/listModels 同款的 additively-optional
1370
+ * 演进:宿主 feature-detect(`typeof registerChatRoundRoute === "function"`),
1371
+ * 未实现的引擎(不支持 chat 域或旧客户端)续聊轮 delta/生命周期静默不可达——
1372
+ * conversation gate 已在派发前拦住无 chat 能力的引擎,本缺省只在「能力声明与
1373
+ * 客户端实现错位」的诊断形态出现。返回注销函数(record 终态时宿主调用)。
1323
1374
  */
1324
- parsedOutput?: unknown;
1325
- /** 原样(AgentResult.usage,orchestration 版 AgentUsage:含 contextTokens/turns)。 */
1326
- usage?: AgentUsage;
1327
- /** 原样(AgentResult.durationMs)。 */
1328
- durationMs?: number;
1329
- /** 原样(AgentResult.error,错误码前缀格式见设计 §3.3.3 错误规格表)。 */
1330
- error?: string;
1331
- /** 原样(AgentResult.sessionId,引擎语义 session id)。 */
1332
- sessionId?: string;
1333
- /** 原样(AgentResult.sessionFile)。 */
1334
- sessionFile?: string;
1335
- /** 原样(AgentResult.worktreePath,仅诊断——目录可能已被 finalize 清理)。 */
1336
- worktreePath?: string;
1337
- /** 原样(AgentResult.toolCalls,ToolCallEntry[])。 */
1338
- toolCalls?: ToolCallEntry[];
1339
- /** 新增:实际执行引擎(fallback 后可能 ≠ 请求值,D9①)。 */
1340
- engineId: string;
1341
- /** 新增:fallback 留痕(record 同步投影,GUI 警告条数据源)。P1 恒缺省(无 fallback 路由)。 */
1342
- engineFallback?: {
1343
- from: string;
1344
- reason: string;
1375
+ registerChatRoundRoute?(recordId: string, route: ChatRoundRoute): () => void;
1376
+ /**
1377
+ * [U7] 可选面:模型可发现性——引擎自带 provider/model 体系时(如 zcode 的 v2 桌面
1378
+ * 登录态),列出当前环境实际可用的模型清单(带凭据校验),供 system prompt 引擎段
1379
+ * 与 GUI 引擎选择器消费。省略/返回 null = 「与主 agent 模型体系一致」(pi 的语义:
1380
+ * system prompt 已有 <available_provider_models> 段,无需引擎再列)。
1381
+ * engine-neutral:未来引擎(AcpEngine 等)实现本方法即自动获得注入与展示,宿主
1382
+ * 侧零改动。
1383
+ */
1384
+ listModels?(): Array<{
1385
+ id: string;
1386
+ name?: string;
1387
+ }> | null;
1388
+ /**
1389
+ * [u-h2 D2-2] 可选面:派发同步期 model 校验(引擎 registry 单源裁决)。实现引擎复用其
1390
+ * prepare 期同一校验函数(zcode: resolveZcodeModelRef——同一函数两处消费,canonicalRef
1391
+ * 归一化与短名缺省 provider 决策不产生双实现漂移);校验失败同步 throw(编排层包装为
1392
+ * 「引擎与模型不配套」错误,见 engine/model-validation.ts)。
1393
+ *
1394
+ * modelRef undefined = 查询引擎缺省模型(D2-1:主 agent 的 pi id 不透传给非 pi 引擎,
1395
+ * 缺省语义归引擎——zcode 落 ZCODE_FALLBACK_DEFAULT_MODEL)。返回 canonical ref 供
1396
+ * record.model 留痕。[W3 契约变更④] 协议化后 canonicalRef 允许**无斜杠**形态
1397
+ * (引擎原样返回的 ref)——core 侧按 provider=""/id=ref/整串进 name 拆分留痕
1398
+ * (splitEngineModelRef 单一权威),不落 "<ref>/" 畸形。
1399
+ *
1400
+ * 未实现:model 透传,引擎自身 prepare 期校验兜底(现状语义);pi 不实现(pi 链走
1401
+ * 既有三层解析 + assertCanonicalModelRef 裁决,搬迁是大重构,设计 D2-2 被否②)。
1402
+ */
1403
+ validateModel?(modelRef: string | undefined): {
1404
+ canonicalRef: string;
1345
1405
  };
1346
- /** 新增:null = 被信号杀死(杀链/abort 合成终态的判据)。P1 pi 链路不暴露 exit code,恒缺省。 */
1347
- exitCode?: number | null;
1406
+ /**
1407
+ * [R1 D6] 可选停机面:释放引擎持有的常驻资源(如 app-server 常驻进程 / 长连接)。
1408
+ * 幂等契约(§3.4 不变量 4):重复调用无副作用;dispose 后首个 run 自动重建(与
1409
+ * 「进程死后重建」同一代码路径)。可选成员保持向后兼容——无常驻资源的引擎(pi
1410
+ * 现状 spawn 单轮)不必实现。等待策略(D6①「触发不等待」):宿主收割入口
1411
+ * (registry disposeEngines → killAllSpawnedChildren)只同步调用拿 Promise 不
1412
+ * await,引擎实现须自行保证同步面(立即 fire close 帧 + 同步 SIGTERM)在返回
1413
+ * Promise 前完成;grace→SIGKILL 升级序列属异步面(promise 段)。
1414
+ */
1415
+ dispose?(): Promise<void>;
1348
1416
  }
1417
+
1418
+ /** 引擎工厂:惰性创建引擎实例(getEngine 首次取用时执行)。 */
1419
+ type EngineFactory = () => EnginePort;
1349
1420
  /**
1350
- * EngineHandle 的持久化形态(设计 §3.3.6,JSON v1)。
1351
- * 内存态 EngineHandle = 本数据 + 引擎运行时引用(各引擎自持)。
1421
+ * 引擎包 manifest 注册期快照(session_start 扫描所得,非握手缓存——设计 §3.3「同步
1422
+ * 成员清单」单一同步源原则)。descriptor 携带,cli 形态 port(RemoteEngine)的同步
1423
+ * 成员(capabilities/listModels/validateModel)直读本快照。
1424
+ *
1425
+ * 与 client/remote-engine.ts 的 RemoteEngineManifestSnapshot 是结构闭包(后者多出
1426
+ * core 中立类型包装;漂移由 protocol-closure 同族结构互证断言守卫)。
1352
1427
  */
1353
- interface EngineHandleData {
1354
- v: 1;
1355
- /** 引擎 id('pi' | 'zcode' | ...,registry key)。 */
1356
- engineId: string;
1428
+ interface EngineManifestSnapshot {
1429
+ /** manifest `capabilities`(同步能力位权威,注册期读,无缓存)。 */
1430
+ capabilities: EngineCapabilities;
1357
1431
  /**
1358
- * 引擎自定义键值(定位符)。pi = { recordId?, sessionFile? }——recordId
1359
- * interact 控制面的 key(subagent record id),sessionFile 是 read 第①级(JSONL
1360
- * 直读)的定位符;zcode = { sessionId, dbPath }。
1432
+ * manifest `modelCatalog` 三态(W4 §2.4:缺省 = 不注入保持 undefined;null 合法等价
1433
+ * 省略;`models: []` 仅作者显式声明)。解析器不得把省略填成 `[]`——否则「无枚举面」
1434
+ * 语义不可达。
1361
1435
  */
1362
- sessionRef: Record<string, string>;
1363
- /** 隔离池定位(设计 §3.3.9)。pi 无池化(PI_CODING_AGENT_DIR 全局一份)恒 'shared'。 */
1364
- poolKey: string;
1365
- /**
1366
- * journal 绝对路径(read 第②级数据源;runtime 读前校验前缀白名单)。
1367
- * P2 event journal 落地后由宿主回填;P1 无 journal 写入者,缺省 undefined——
1368
- * read 降级链第②级不可达,直接走 ①/③。
1436
+ modelCatalog?: {
1437
+ dynamic: boolean;
1438
+ models: ModelCatalogEntry[];
1439
+ } | null;
1440
+ /** manifest `displayName`(可选,缺省 = id;D4 缺省引擎回落序的排序键)。 */
1441
+ displayName?: string;
1442
+ }
1443
+ /** cli 形态 descriptor(目标形态):引擎 CLI 启动参数 + manifest 快照 + port 装配器。 */
1444
+ interface CliEngineDescriptor {
1445
+ kind: "cli";
1446
+ /** 引擎 CLI 命令(发现器解析后的绝对路径/可执行名;不依赖 PATH)。 */
1447
+ command: string;
1448
+ /** 引擎 CLI 参数(不含 command 本身)。 */
1449
+ args: readonly string[];
1450
+ /** manifest `capabilities`(同步能力位权威——gate 同步消费,无缓存)。 */
1451
+ capabilities: EngineCapabilities;
1452
+ /**
1453
+ * cli 形态 EnginePort 实例装配器(core 侧接线通道,非 manifest 面)。生产 = W4
1454
+ * 发现器装载 descriptor 时装配(W2 `RemoteEngine` + `EngineClient` + 宿主侧参数
1455
+ * dataDir/hostKind/engineConfig 等——registry 不越权猜宿主形态)。必须构造同步、
1456
+ * 不 throw(§3.5.3 代理形态:缺包/坏包的失败推迟到首次协议调用)。
1369
1457
  */
1370
- journalPath?: string;
1371
- /** probe 实测版本(漂移排查锚点)。 */
1372
- engineVersion?: string;
1373
- /** 适配器版本(golden 样本对齐排查)。 */
1374
- adapterVersion: string;
1458
+ portFactory: EngineFactory;
1459
+ /** manifest 快照余项(modelCatalog/displayName;capabilities 已提升为直读字段)。 */
1460
+ manifest?: Omit<EngineManifestSnapshot, "capabilities">;
1375
1461
  }
1376
1462
  /**
1377
- * 引擎会话句柄(run 返回、interact/read 入参)。
1378
- *
1379
- * 契约三条(D1):不透明(上层不解构——唯一例外是 record 持久化层序列化 data 字段与
1380
- * read 降级链)、可持久化(data 是纯 JSON,主会话 reload 后 read/interact 仍可用)、
1381
- * 自描述(data 含 engineId + 引擎 session 定位符 + pool key + adapter 版本)。
1382
- *
1383
- * 对进程已死的 handle 调 interact 必须返回 engine_session_not_resumable(指向 cold
1384
- * resume 路径),而非笼统失败——由各引擎 interact 实现保证。
1463
+ * 缺省引擎 id(D4 重定义:**配置的缺省引擎 id**——config defaultEngine 未配置时的
1464
+ * 归一名,不再表达「内置 pi 永久兜底」)。配置值不在已发现清单 → warn + 回落第一个
1465
+ * 可用引擎(manifest displayName 稳定序,D4);全不可用 派发期 engine_not_found
1466
+ * (「未发现任何引擎包」+ 安装指引)。
1385
1467
  */
1386
- interface EngineHandle {
1387
- /** 持久化数据。上层不得解构其内部字段(见契约三条)。 */
1388
- readonly data: EngineHandleData;
1389
- }
1468
+ declare const DEFAULT_ENGINE_ID = "pi";
1390
1469
  /**
1391
- * read(handle) 的返回:turns[] 派生数据。与 Turn 同构但无内部态(_status/startedTs
1392
- * 剥离,closed true)。
1470
+ * defaultEngine 缺省归一(单一权威源):空白 / undefined 归一到缺省引擎('pi')。
1471
+ * 引擎感知检测 diff 与状态段渲染必须对同一读取结果给出同一引擎 id——若两处各自
1472
+ * 内联归一,一致性只靠注释人工耦合,漂移即两处说谎;故收敛到本函数供各处调用。
1473
+ * sanitize 保证透传值非空,但可能带首尾空格,故 trim 后再判。
1393
1474
  */
1394
- interface ReplayedTurn {
1395
- text: string;
1396
- thinking: string;
1397
- /** 导出的纯净形状(execution ToolCall,无 _status)。 */
1398
- toolCalls: ToolCall[];
1399
- closed: true;
1475
+ declare function normalizeEngineId(engine: string | undefined): string;
1476
+
1477
+ /** 单个引擎包的检查产物。 */
1478
+ type PackageInspection = {
1479
+ status: "ok";
1480
+ entry: DiscoveredEngine;
1481
+ } | {
1482
+ status: "skip";
1483
+ reason: string;
1484
+ } | {
1485
+ status: "unusable";
1486
+ id: string | undefined;
1487
+ reason: string;
1488
+ };
1489
+ /** 发现成功的引擎条目(装载序;同 id 后者覆盖前者)。 */
1490
+ interface DiscoveredEngine {
1491
+ id: string;
1492
+ /** 发现源标签(env 名 / 宿主根 source / node-modules / config.json)。 */
1493
+ source: string;
1494
+ /** L3 显式 config(initialize.engineConfig 透传;L1/L2 manifest 发现无此项)。 */
1495
+ engineConfig?: Record<string, string>;
1496
+ descriptor: CliEngineDescriptor;
1400
1497
  }
1401
1498
  /**
1402
- * session 历史的引擎中立视图。降级链三级(D6):①引擎原生读取(pi JSONL / zcode
1403
- * sqlite)→ ②宿主 event journal 重放(P2)→ ③outcome-only。source 字段是 GUI 降级
1404
- * 标记数据源(A8)。
1499
+ * 检查单个候选包目录(读 package.json manifest 字段级解析 → bin 可执行验证)。
1500
+ * 三态:ok(装载)/ skip(必需字段缺失/不可解析——warn 跳过该包)/ unusable
1501
+ * (protocol 不兼容、bin 不可执行——标记不可用,不进清单)。
1405
1502
  */
1406
- interface SessionView {
1407
- engineId: string;
1408
- sessionId?: string;
1409
- /** turns[] 派生数据(重放/重建产物)。 */
1410
- turns: ReplayedTurn[];
1411
- /** turn usageDelta 聚合(execution 层 AgentUsageTotal)。 */
1412
- usage?: AgentUsageTotal;
1413
- source: "native" | "journal" | "outcome-only";
1414
- }
1503
+ declare function inspectEnginePackage(pkgDir: string, source: string, hostKind: string, env: NodeJS.ProcessEnv): PackageInspection;
1504
+
1505
+ /** L1 引擎发现根 env(设计 §3.4;值形态 = path.delimiter 分隔的绝对路径列表)。 */
1506
+ declare const ENGINE_ROOTS_ENV = "XYZ_AGENT_ENGINE_ROOTS";
1507
+ /** L1 env 根解析:path.delimiter 分隔;空段跳过;非绝对路径丢弃 + warn;去重(大小写敏感)。 */
1508
+ declare function parseEngineRootsEnv(env: NodeJS.ProcessEnv): string[];
1415
1509
  /**
1416
- * 引擎能力声明(设计 D3 原样落地)。三级:native / emulated / unsupported。
1417
- *
1418
- * 易错点(D3):声明的是**本仓 subagent 链路实际接通的能力**,不是引擎 RPC 层的理论
1419
- * 能力——pi RPC steer 但现有 spawn 链路未接通(session-runner steer no-op),
1420
- * PiEngine 声明 unsupported,接通后再升级。上层据声明选择策略(schema emulated
1421
- * 时自动走公共降级层;steer/conversation unsupported 时 UI 隐藏对应入口),而非
1422
- * try-catch 运行时试错。
1510
+ * L2 根推导:宿主进程入口(process.argv[1])所在目录逐级上溯的 node_modules——与
1511
+ * createRequire(<宿主入口>) 的 require.resolve 候选目录链同构(「宿主 node_modules
1512
+ * require.resolve」的扫描化:零枚举发现要求扫目录而非 resolve 具体包名)。打包态
1513
+ * (staged 扩展 / Bun standalone node_modules 结构)与 zsw vendor 态自然为空——
1514
+ * 规格明确两态 L2 无效。argv[1] 不可得(嵌入式 / worker)→ L2 缺席。
1423
1515
  */
1424
- interface EngineCapabilities {
1425
- /** native: --json-schema/--output-schema/env 注入(pi = PI_WORKFLOW_SCHEMA 链路)。 */
1426
- schemaEnforcement: "native" | "emulated";
1427
- /** 注意区分「引擎 RPC 层有此能力」与「subagent 链路已接通」。 */
1428
- steer: "native" | "emulated" | "unsupported";
1429
- /** interact 控制面(message/close/cancel + idle)。 */
1430
- conversation: "native" | "unsupported";
1431
- /** 决定 persona 路由策略(公共降级层按此选择 file/flag/prompt 通道)。 */
1432
- personaInjection: "file" | "flag" | "prompt";
1433
- /** 粗粒度引擎:GUI 显示降级为阶段态。 */
1434
- eventGranularity: "stream" | "coarse";
1435
- /** emulated = worktree 隔离(无 OS sandbox 的引擎用文件写维度隔离补齐)。 */
1436
- sandbox: "native" | "emulated" | "none";
1437
- /** 重建历史的能力(read 降级链第①级的保真度上限)。 */
1438
- sessionRead: "full" | "partial" | "outcome-only";
1439
- resume: "native" | "cold" | "unsupported";
1440
- /** 优雅中断 or 只能杀进程(公共杀链兜底,见 D1 abort 分级)。 */
1441
- interrupt: "native" | "kill-only";
1442
- /** kimi headless 固定 auto = ignored;GUI 据此隐藏/提示。 */
1443
- permissionMode: "native" | "fixed" | "ignored";
1444
- /**
1445
- * [D3-④ r3 裁定] maxTurns 轮数上限的执行能力位(pi = true:turn limiter + spawn
1446
- * watchdog 估算兑现;zcode = false:无 turn_end 语义,静默丢弃会造成「传了上限却
1447
- * 失控」假象)。调用前预检(common/capability-gate)按本位拦「声明不支持的能力」
1448
- * ——pi 不拦 maxTurns(已支持能力,由 turn-limiter 执行)、zcode 同步拒绝。
1449
- * 现状 11 个能力位无可承载 maxTurns 的语义位(fork 拦截可借 session 分叉通道族判,
1450
- * maxTurns 无可借位),故扩位而非保留引擎内硬编码 shape 检查。
1451
- */
1452
- maxTurns: boolean;
1516
+ declare function deriveNodeModuleRoots(argvEntry?: string | undefined): string[];
1517
+
1518
+ /** 日志级别。对齐 @zhushanwen/pi-extension-logger 的 LogLevel(三值,无 info)。 */
1519
+ type LogLevel = "debug" | "warn" | "error";
1520
+ /** core logger 接口。与 pi-extension-logger 的 ExtensionLogger 结构兼容——
1521
+ * u0-log 批次替换是纯 import 源替换,调用面(方法名/参数序)逐文件等价。 */
1522
+ interface CoreLogger {
1523
+ debug(msg: string, data?: unknown): void;
1524
+ warn(msg: string, data?: unknown): void;
1525
+ error(msg: string, data?: unknown): void;
1453
1526
  }
1454
- /** 引擎探针报告(probe() 返回)。探针在引擎 factory 初始化与版本变化检测时触发(P4 接线)。 */
1455
- interface ProbeReport {
1456
- ok: boolean;
1457
- /** 实测版本(handle.engineVersion 数据源)。探测不到时为空串。 */
1458
- engineVersion: string;
1459
- /** 二进制存在/版本解析/干跑回归逐项。 */
1460
- checks: Array<{
1461
- name: string;
1462
- ok: boolean;
1463
- detail?: string;
1464
- }>;
1465
- /** engine_probe_failed 的恢复指引(设计 §3.3.3 终态四样例;ok=false 时必填)。 */
1466
- error?: {
1467
- code: string;
1468
- recovery: string;
1527
+ declare function getLogger(component: string): CoreLogger;
1528
+
1529
+ /** 发现根条目:dir 为扫描根路径;source 是宿主提供的语义标签(遮蔽报告透传用)。
1530
+ * source 不枚举封闭集——core 只透传不解释(宿主如 pi 壳用 user-pi/npm/npm-dev)。 */
1531
+ interface DiscoveryRoot {
1532
+ dir: string;
1533
+ source: string;
1534
+ }
1535
+ interface HostServices {
1536
+ /** 数据根目录:引擎隔离池 / journal / record 派生存放的锚点。
1537
+ * pi 壳返回 getAgentDir()(独立 pi 用户 journal 不漂目录);zsw 壳返回 zsw 数据根。 */
1538
+ dataRoot(): string;
1539
+ /** 结构化日志:对齐现 getLogger 调用面(level/component/message/data)。缺省 sink 按级分化:
1540
+ * warn/error 走 console、debug no-op(对齐 pi-extension-logger 语义,见 NULL_HOST.log)。 */
1541
+ log(level: LogLevel, component: string, message: string, data?: unknown): void;
1542
+ /** agent/skill/workflow/引擎包 资源发现根(可选端口,缺席 = 调用方降级)。宿主只提供根列表
1543
+ * (按优先级低→高);扫描 / 同名遮蔽(last-writer-wins)/ 遮蔽报告语义归 core 统一。
1544
+ *
1545
+ * engines kind(W4,设计 §3.4 L1 第二通道):引擎包发现根——dir 下一级(及 org 分组
1546
+ * 二级)子项 = 候选引擎包目录,命中 package.json `xyz-agent.subagentEngine` manifest
1547
+ * 即发现。打包态主通道是 env `XYZ_AGENT_ENGINE_ROOTS`(W9 注入),此端口承载宿主
1548
+ * 自身模块域(如 pi 宿主包 node_modules 的引擎包 dependencies 安装位)。 */
1549
+ discoveryRoots?(): {
1550
+ agents?: DiscoveryRoot[];
1551
+ skills?: DiscoveryRoot[];
1552
+ workflows?: DiscoveryRoot[];
1553
+ engines?: DiscoveryRoot[];
1469
1554
  };
1470
1555
  }
1556
+ /** core 缺省数据根(~/.subagent-core,homedir 推导——禁止写死绝对路径,排查规则)。
1557
+ * 供无自有数据根的轻宿主显式采用;core 自身不静默兜底到该值。 */
1558
+ declare const DEFAULT_DATA_ROOT: string;
1559
+ declare function configureCore(host: HostServices): void;
1560
+ declare function getHostServices(): HostServices;
1561
+
1562
+ /** 扫描结果(诊断面:skip/unusable 逐包留痕原因,对应 A12 负面场景)。 */
1563
+ interface DiscoveryScanResult {
1564
+ discovered: DiscoveredEngine[];
1565
+ skipped: Array<{
1566
+ pkgDir: string;
1567
+ reason: string;
1568
+ }>;
1569
+ unusable: Array<{
1570
+ pkgDir: string;
1571
+ id: string | undefined;
1572
+ reason: string;
1573
+ }>;
1574
+ }
1575
+ interface DiscoverEnginesOptions {
1576
+ /** 宿主种类(EngineClient pidfile 实例维度命名段:pi 壳 'pi'、runtime 'runtime')。 */
1577
+ hostKind: string;
1578
+ /** L3 显式配置目录(<dir>/subagents/config.json 的 engines 段)。缺省 = 无 L3。 */
1579
+ agentDir?: string;
1580
+ /** 引擎数据根(EngineClient dataDir;缺省 portFactory 执行期 getEngineDataDir 解析)。 */
1581
+ dataDir?: string;
1582
+ /** env 覆盖(L1 根读取;缺省 process.env——测试注入隔离宿主 env)。 */
1583
+ env?: NodeJS.ProcessEnv;
1584
+ /** L2 覆盖(测试注入;缺省 = 宿主入口上溯 node_modules 链)。 */
1585
+ nodeModuleRoots?: string[];
1586
+ /** 附加发现根(调用方/测试追加的 L1 根,语义同 HostServices.engines)。 */
1587
+ extraRoots?: DiscoveryRoot[];
1588
+ }
1589
+ /** 纯扫描(不装载注册表)。装载序 = L1 env → L1 宿主/附加根 → L2 → L3(后者覆盖前者)。 */
1590
+ declare function scanEngines(opts: DiscoverEnginesOptions): DiscoveryScanResult;
1471
1591
  /**
1472
- * interact action(D1 交互控制面)。pi 首期原生实现(现有 chatMode 行为直通);
1473
- * 声明 conversation unsupported 的引擎调用前拒绝(engine_capability_unsupported)。
1592
+ * 扫描 + 装载:descriptor registerEngineDescriptor 进注册表(幂等覆盖——重复扫描
1593
+ * 安全)。装载覆盖既有注册(含过渡期 inproc pi/zcode——auto 模式下 cli descriptor
1594
+ * 胜出即设计 D3 语义)时 debug 留痕。
1474
1595
  */
1475
- type InteractAction =
1596
+ declare function discoverAndRegisterEngines(opts: DiscoverEnginesOptions): DiscoveryScanResult;
1476
1597
  /**
1477
- * interrupt:true = steer(抢占)/ false|缺省 = followUp(排队)——pi streamingBehavior
1478
- * 语义的中立承载(D1 §3.3.5「后续 wave 如需抢占语义再扩展 InteractAction」的兑现,
1479
- * chat 域投递经 engine.interact 接通时落地;不支持抢占的引擎忽略)。
1598
+ * 历史发现装载的引擎 id 快照(投影源计算消费面,见 engine-discovery.ts)。
1480
1599
  */
1481
- {
1482
- kind: "message";
1483
- payload: string;
1484
- interrupt?: boolean;
1485
- } | {
1486
- kind: "close";
1487
- payload?: {
1488
- force: boolean;
1489
- };
1490
- } | {
1491
- kind: "cancel";
1492
- };
1600
+ declare function loadedDiscoveryIds(): string[];
1493
1601
  /**
1494
- * interact 的结果。失败码取自设计 §3.3.3:engine_session_not_resumable(死 handle)/
1495
- * engine_capability_unsupported(能力声明拒绝)等。
1602
+ * hasEngine 的补扫面(§3.4 发现时机:快照未命中触发一次同步补扫,只读 manifest
1603
+ * 不握手)。消费方 = agent 解析期/路由期的存在性校验接线(宿主侧注入 hasEngineFn
1604
+ * 时用本函数替代裸 hasEngine)——「装了包 → 下次解析即可用」。
1496
1605
  */
1497
- type InteractResult = {
1498
- ok: true;
1499
- delivered: true;
1500
- } | {
1501
- ok: false;
1502
- code: string;
1503
- message: string;
1504
- };
1606
+ declare function ensureEngineDiscovered(id: string, opts: DiscoverEnginesOptions): boolean;
1505
1607
 
1506
- export { type SubagentToolResult as $, type AgentCallOpts as A, type DisplayItem as B, type ClosedReason as C, type DoneReason as D, type EngineCapabilities as E, type CancelResponse as F, type CloseResponse as G, type ForkFromResponse as H, type InteractAction as I, type MessageResponse as J, type BgResponse as K, type ListResponse as L, type ModelInfo as M, type ExternalState as N, type SubagentListItem as O, type ProbeReport as P, CLOSED_REASONS as Q, type RecordSnapshot as R, type SessionView as S, type ToolCall as T, DEFAULT_AGENT_NAME as U, DirtyWorktreeError as V, type WorktreeHandle as W, ForkDepthExceededError as X, type ReplayedTurn as Y, ResurrectDeniedError as Z, SLUG_MAX_LENGTH as _, type AgentEvent as a, type ToolCallEntry as a0, type EngineHandleData as b, type EngineHandle as c, type AgentOutcome as d, type InteractResult as e, type ExecutionRecord as f, type SubagentRecord as g, type ExecuteOptions as h, type AgentResult as i, type AgentConfig as j, type ResolvedModel as k, type AgentResult$1 as l, type ExecutionOutcome as m, type AgentEventLogEntry as n, type ExecutionStatus as o, type ProjectedOutcome as p, type SubagentsGlobalConfig as q, type ModelRegistryLike as r, type ExecutionHandle as s, type ExecutionMode as t, type PatchResult as u, type AgentUsage as v, type ExecutionTraceNode as w, type TracePatch as x, type RunStatus as y, type WorkerLogEntry as z };
1608
+ export { type SubagentToolResult as $, type AgentEventLogEntry as A, type BgResponse as B, type ClosedReason as C, type DiscoverEnginesOptions as D, type EnginePort as E, type ForkFromResponse as F, CLOSED_REASONS as G, type CoreLogger as H, DEFAULT_AGENT_NAME as I, DEFAULT_DATA_ROOT as J, DEFAULT_ENGINE_ID as K, type ListResponse as L, type ModelRegistryLike as M, DirtyWorktreeError as N, type EngineHandle as O, type ProjectedOutcome as P, type EngineRunResult as Q, type RecordSnapshot as R, type SubagentRecord as S, type TracePatch as T, ForkDepthExceededError as U, type HostServices as V, type WorkerLogEntry as W, type LogLevel as X, ResurrectDeniedError as Y, type RunContext as Z, SLUG_MAX_LENGTH as _, type ExecutionRecord as a, configureCore as a0, getHostServices as a1, getLogger as a2, normalizeEngineId as a3, type DiscoveredEngine as a4, type DiscoveryScanResult as a5, ENGINE_ROOTS_ENV as a6, type PackageInspection as a7, deriveNodeModuleRoots as a8, discoverAndRegisterEngines as a9, ensureEngineDiscovered as aa, inspectEnginePackage as ab, loadedDiscoveryIds as ac, parseEngineRootsEnv as ad, scanEngines as ae, type ExecutionOutcome as b, type ExecutionStatus as c, type ExecuteOptions as d, SubagentStream as e, type AgentResult$1 as f, type AgentResult as g, type SubagentsGlobalConfig as h, type ModelInfo as i, type AgentConfig as j, type ResolvedModel as k, type StreamSink as l, type ExecutionHandle as m, type ExecutionMode as n, type PatchResult as o, type AgentCallOpts as p, type ExecutionTraceNode as q, type RunStatus as r, type DoneReason as s, type DisplayItem as t, type CancelResponse as u, type CloseResponse as v, type MessageResponse as w, type ExternalState as x, type SubagentListItem as y, type DiscoveryRoot as z };