@zhushanwen/pi-subagent-workflow 8.4.0 → 8.5.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 (101) hide show
  1. package/package.json +18 -4
  2. package/relay/relay.mjs +390 -0
  3. package/skills/subagent-ext-config/SKILL.md +80 -0
  4. package/src/execution/__tests__/agent-registry.test.ts +110 -0
  5. package/src/execution/__tests__/chat-engine-routing.test.ts +597 -0
  6. package/src/execution/__tests__/execution-record.test.ts +127 -1
  7. package/src/execution/__tests__/pi-invocation.test.ts +62 -1
  8. package/src/execution/__tests__/relay-agent.test.ts +448 -0
  9. package/src/execution/__tests__/relay-env.test.ts +42 -0
  10. package/src/execution/__tests__/startup-config-declaration.test.ts +35 -0
  11. package/src/execution/__tests__/stream-sink-retirement.test.ts +261 -0
  12. package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +310 -0
  13. package/src/execution/__tests__/subprocess-agent-runner.test.ts +53 -5
  14. package/src/execution/agent-registry.ts +10 -0
  15. package/src/execution/config.ts +25 -2
  16. package/src/execution/engine/__tests__/common/data-dir.test.ts +53 -0
  17. package/src/execution/engine/__tests__/common/errors.test.ts +132 -0
  18. package/src/execution/engine/__tests__/common/event-journal.test.ts +177 -0
  19. package/src/execution/engine/__tests__/common/kill-chain.test.ts +192 -0
  20. package/src/execution/engine/__tests__/common/nesting-guard.test.ts +81 -0
  21. package/src/execution/engine/__tests__/common/persona-router.test.ts +123 -0
  22. package/src/execution/engine/__tests__/common/pool-manager.test.ts +154 -0
  23. package/src/execution/engine/__tests__/common/schema-emulation.test.ts +128 -0
  24. package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +28 -0
  25. package/src/execution/engine/__tests__/conformance/agent-event-invariants.ts +141 -0
  26. package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +109 -0
  27. package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +101 -0
  28. package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +77 -0
  29. package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +104 -0
  30. package/src/execution/engine/__tests__/conformance/contract.relay.test.ts +342 -0
  31. package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +201 -0
  32. package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +76 -0
  33. package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +79 -0
  34. package/src/execution/engine/__tests__/engine-discovery.test.ts +87 -0
  35. package/src/execution/engine/__tests__/engines-declaration.test.ts +36 -0
  36. package/src/execution/engine/__tests__/model-prompt.test.ts +85 -0
  37. package/src/execution/engine/__tests__/paths.test.ts +39 -0
  38. package/src/execution/engine/__tests__/registry.test.ts +120 -0
  39. package/src/execution/engine/__tests__/routing.test.ts +231 -0
  40. package/src/execution/engine/common/data-dir.ts +62 -0
  41. package/src/execution/engine/common/errors.ts +183 -0
  42. package/src/execution/engine/common/event-journal.ts +254 -0
  43. package/src/execution/engine/common/journal-replay.ts +62 -0
  44. package/src/execution/engine/common/kill-chain.ts +221 -0
  45. package/src/execution/engine/common/nesting-guard.ts +50 -0
  46. package/src/execution/engine/common/persona-router.ts +108 -0
  47. package/src/execution/engine/common/pool-manager.ts +226 -0
  48. package/src/execution/engine/common/schema-emulation.ts +189 -0
  49. package/src/execution/engine/common/session-view-projection.ts +51 -0
  50. package/src/execution/engine/engine-discovery.ts +65 -0
  51. package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +469 -0
  52. package/src/execution/engine/engines/pi/__tests__/reader.test.ts +155 -0
  53. package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +164 -0
  54. package/src/execution/engine/engines/pi/pi-engine.ts +415 -0
  55. package/src/execution/engine/engines/pi/reader.ts +48 -0
  56. package/src/execution/engine/engines/pi/registration.ts +35 -0
  57. package/src/execution/engine/engines/pi/task-spec-mapper.ts +100 -0
  58. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +39 -0
  59. package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +150 -0
  60. package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +246 -0
  61. package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +228 -0
  62. package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +210 -0
  63. package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +64 -0
  64. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +127 -0
  65. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +567 -0
  66. package/src/execution/engine/engines/zcode/constants.ts +43 -0
  67. package/src/execution/engine/engines/zcode/golden-sample.ts +39 -0
  68. package/src/execution/engine/engines/zcode/launcher.ts +161 -0
  69. package/src/execution/engine/engines/zcode/parser.ts +436 -0
  70. package/src/execution/engine/engines/zcode/preparer.ts +363 -0
  71. package/src/execution/engine/engines/zcode/reader.ts +381 -0
  72. package/src/execution/engine/engines/zcode/registration.ts +37 -0
  73. package/src/execution/engine/engines/zcode/zcode-engine.ts +648 -0
  74. package/src/execution/engine/host-task-spec.ts +47 -0
  75. package/src/execution/engine/model-prompt.ts +59 -0
  76. package/src/execution/engine/paths.ts +42 -0
  77. package/src/execution/engine/port.ts +153 -0
  78. package/src/execution/engine/registry.ts +123 -0
  79. package/src/execution/engine/routing.ts +218 -0
  80. package/src/execution/engine/types.ts +304 -0
  81. package/src/execution/execute-options-mapper.ts +5 -1
  82. package/src/execution/execution-record.ts +6 -0
  83. package/src/execution/model-resolver.ts +6 -0
  84. package/src/execution/pi-invocation.ts +32 -2
  85. package/src/execution/record-entry.ts +14 -0
  86. package/src/execution/record-store.ts +34 -0
  87. package/src/execution/relay-env.ts +37 -0
  88. package/src/execution/session-runner.ts +24 -0
  89. package/src/execution/stream-sink.ts +26 -0
  90. package/src/execution/subagent-service.ts +249 -11
  91. package/src/execution/subprocess-agent-runner.ts +196 -14
  92. package/src/execution/types.ts +56 -0
  93. package/src/index.ts +46 -1
  94. package/src/interface/subagent-actions.ts +3 -0
  95. package/src/interface/subagent-tool.ts +6 -0
  96. package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +5 -2
  97. package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +3 -3
  98. package/src/orchestration/models/types.ts +7 -0
  99. package/src/orchestration/worker-script-builder.ts +5 -2
  100. package/src/shared/meta-parser.ts +5 -1
  101. package/src/shared/resource-meta.ts +5 -0
@@ -0,0 +1,304 @@
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
+ /** 原样(ExecuteOptions.maxTurns)。 */
93
+ maxTurns?: number;
94
+ /** 原样(ExecuteOptions.graceTurns)。 */
95
+ graceTurns?: number;
96
+ /** 原样(ExecuteOptions.fork)。pi 专属;其他引擎 prepare 期按 capabilities 拒绝。 */
97
+ fork?: boolean;
98
+ /**
99
+ * 原样(ExecuteOptions.worktree)。公共层职责(worktree-manager),非引擎职责——
100
+ * 引擎只把它当 spawn cwd 的来源之一。
101
+ */
102
+ worktree?: boolean | WorktreeHandle;
103
+ /** 原样(ExecuteOptions.cwd)。 */
104
+ cwd?: string;
105
+ /** 原样(ExecuteOptions.conversation,interact 控制面的 task 标志,D1)。 */
106
+ conversation?: boolean;
107
+ /** 原样(ExecuteOptions.idleTimeoutMs,同上)。 */
108
+ idleTimeoutMs?: number;
109
+ /** 新增:中立工具 denylist。各引擎做语法映射(附录 A「工具 denylist」行的载体)。 */
110
+ denyTools?: string[];
111
+ /** 新增:中立权限模式。映射按 capabilities.permissionMode(kimi fixed auto = ignored)。 */
112
+ permissionMode?: string;
113
+ /**
114
+ * [P4 形状预留,D9① 守卫 b 的独立载体] 任务对引擎能力的显式依赖声明。
115
+ * 首期无生产写入方:守卫 b 与守卫 a 合流(显式 engine 即能力依赖声明)——调用方
116
+ * 按引擎 id 表达依赖。下钻时机(AgentTaskSpec 泛化成熟后):调用方改按能力表达
117
+ * (如 requires: { sandbox: 'native' }),路由层将本字段与各引擎 capabilities()
118
+ * 对照,无引擎满足时报 engine_capability_unsupported(调用前拒绝,D11 处置三级)。
119
+ */
120
+ requires?: Partial<EngineCapabilities>;
121
+ }
122
+
123
+ // ============================================================
124
+ // AgentOutcome(锚定 orchestration 层 AgentResult,§3.3.5)
125
+ // ============================================================
126
+
127
+ /**
128
+ * 一次引擎执行的终态。锚定 orchestration/models/types.ts 的 AgentResult(workflow
129
+ * 引擎消费的那份——content/parsedOutput/usage/error)并追加引擎层字段;见文件头消歧说明。
130
+ */
131
+ export interface AgentOutcome {
132
+ /** 原样(AgentResult.content)。 */
133
+ content: string;
134
+ /**
135
+ * 原样(AgentResult.parsedOutput)。native 引擎直传 / 仿真层 ajv 产出(D4 硬分流:
136
+ * native 路径公共层不做二次校验、不改写其结果)。
137
+ */
138
+ parsedOutput?: unknown;
139
+ /** 原样(AgentResult.usage,orchestration 版 AgentUsage:含 contextTokens/turns)。 */
140
+ usage?: AgentUsage;
141
+ /** 原样(AgentResult.durationMs)。 */
142
+ durationMs?: number;
143
+ /** 原样(AgentResult.error,错误码前缀格式见设计 §3.3.3 错误规格表)。 */
144
+ error?: string;
145
+ /** 原样(AgentResult.sessionId,引擎语义 session id)。 */
146
+ sessionId?: string;
147
+ /** 原样(AgentResult.sessionFile)。 */
148
+ sessionFile?: string;
149
+ /** 原样(AgentResult.worktreePath,仅诊断——目录可能已被 finalize 清理)。 */
150
+ worktreePath?: string;
151
+ /** 原样(AgentResult.toolCalls,ToolCallEntry[])。 */
152
+ toolCalls?: ToolCallEntry[];
153
+ /** 新增:实际执行引擎(fallback 后可能 ≠ 请求值,D9①)。 */
154
+ engineId: string;
155
+ /** 新增:fallback 留痕(record 同步投影,GUI 警告条数据源)。P1 恒缺省(无 fallback 路由)。 */
156
+ engineFallback?: { from: string; reason: string };
157
+ /** 新增:null = 被信号杀死(杀链/abort 合成终态的判据)。P1 pi 链路不暴露 exit code,恒缺省。 */
158
+ exitCode?: number | null;
159
+ }
160
+
161
+ // ============================================================
162
+ // EngineHandle(run/interact/read 三面的连接件,D1/§3.3.6)
163
+ // ============================================================
164
+
165
+ /**
166
+ * EngineHandle 的持久化形态(设计 §3.3.6,JSON v1)。
167
+ * 内存态 EngineHandle = 本数据 + 引擎运行时引用(各引擎自持)。
168
+ */
169
+ export interface EngineHandleData {
170
+ v: 1;
171
+ /** 引擎 id('pi' | 'zcode' | ...,registry key)。 */
172
+ engineId: string;
173
+ /**
174
+ * 引擎自定义键值(定位符)。pi = { recordId?, sessionFile? }——recordId 是
175
+ * interact 控制面的 key(subagent record id),sessionFile 是 read 第①级(JSONL
176
+ * 直读)的定位符;zcode = { sessionId, dbPath }。
177
+ */
178
+ sessionRef: Record<string, string>;
179
+ /** 隔离池定位(设计 §3.3.9)。pi 无池化(PI_CODING_AGENT_DIR 全局一份)恒 'shared'。 */
180
+ poolKey: string;
181
+ /**
182
+ * journal 绝对路径(read 第②级数据源;runtime 读前校验前缀白名单)。
183
+ * P2 event journal 落地后由宿主回填;P1 无 journal 写入者,缺省 undefined——
184
+ * read 降级链第②级不可达,直接走 ①/③。
185
+ */
186
+ journalPath?: string;
187
+ /** probe 实测版本(漂移排查锚点)。 */
188
+ engineVersion?: string;
189
+ /** 适配器版本(golden 样本对齐排查)。 */
190
+ adapterVersion: string;
191
+ }
192
+
193
+ /**
194
+ * 引擎会话句柄(run 返回、interact/read 入参)。
195
+ *
196
+ * 契约三条(D1):不透明(上层不解构——唯一例外是 record 持久化层序列化 data 字段与
197
+ * read 降级链)、可持久化(data 是纯 JSON,主会话 reload 后 read/interact 仍可用)、
198
+ * 自描述(data 含 engineId + 引擎 session 定位符 + pool key + adapter 版本)。
199
+ *
200
+ * 对进程已死的 handle 调 interact 必须返回 engine_session_not_resumable(指向 cold
201
+ * resume 路径),而非笼统失败——由各引擎 interact 实现保证。
202
+ */
203
+ export interface EngineHandle {
204
+ /** 持久化数据。上层不得解构其内部字段(见契约三条)。 */
205
+ readonly data: EngineHandleData;
206
+ }
207
+
208
+ // ============================================================
209
+ // SessionView(read 返回,D6/§3.3.6)
210
+ // ============================================================
211
+
212
+ /**
213
+ * read(handle) 的返回:turns[] 派生数据。与 Turn 同构但无内部态(_status/startedTs
214
+ * 剥离,closed 恒 true)。
215
+ */
216
+ export interface ReplayedTurn {
217
+ text: string;
218
+ thinking: string;
219
+ /** 导出的纯净形状(execution 层 ToolCall,无 _status)。 */
220
+ toolCalls: ToolCall[];
221
+ closed: true;
222
+ }
223
+
224
+ /**
225
+ * session 历史的引擎中立视图。降级链三级(D6):①引擎原生读取(pi JSONL / zcode
226
+ * sqlite)→ ②宿主 event journal 重放(P2)→ ③outcome-only。source 字段是 GUI 降级
227
+ * 标记数据源(A8)。
228
+ */
229
+ export interface SessionView {
230
+ engineId: string;
231
+ sessionId?: string;
232
+ /** turns[] 派生数据(重放/重建产物)。 */
233
+ turns: ReplayedTurn[];
234
+ /** 各 turn usageDelta 聚合(execution 层 AgentUsageTotal)。 */
235
+ usage?: AgentUsageTotal;
236
+ source: "native" | "journal" | "outcome-only";
237
+ }
238
+
239
+ // ============================================================
240
+ // EngineCapabilities(D3,三级声明)
241
+ // ============================================================
242
+
243
+ /**
244
+ * 引擎能力声明(设计 D3 原样落地)。三级:native / emulated / unsupported。
245
+ *
246
+ * 易错点(D3):声明的是**本仓 subagent 链路实际接通的能力**,不是引擎 RPC 层的理论
247
+ * 能力——pi 的 RPC 有 steer 但现有 spawn 链路未接通(session-runner steer no-op),
248
+ * 故 PiEngine 声明 unsupported,接通后再升级。上层据声明选择策略(schema 为 emulated
249
+ * 时自动走公共降级层;steer/conversation unsupported 时 UI 隐藏对应入口),而非
250
+ * try-catch 运行时试错。
251
+ */
252
+ export interface EngineCapabilities {
253
+ /** native: --json-schema/--output-schema/env 注入(pi = PI_WORKFLOW_SCHEMA 链路)。 */
254
+ schemaEnforcement: "native" | "emulated";
255
+ /** 注意区分「引擎 RPC 层有此能力」与「subagent 链路已接通」。 */
256
+ steer: "native" | "emulated" | "unsupported";
257
+ /** interact 控制面(message/close/cancel + idle)。 */
258
+ conversation: "native" | "unsupported";
259
+ /** 决定 persona 路由策略(公共降级层按此选择 file/flag/prompt 通道)。 */
260
+ personaInjection: "file" | "flag" | "prompt";
261
+ /** 粗粒度引擎:GUI 显示降级为阶段态。 */
262
+ eventGranularity: "stream" | "coarse";
263
+ /** emulated = worktree 隔离(无 OS sandbox 的引擎用文件写维度隔离补齐)。 */
264
+ sandbox: "native" | "emulated" | "none";
265
+ /** 重建历史的能力(read 降级链第①级的保真度上限)。 */
266
+ sessionRead: "full" | "partial" | "outcome-only";
267
+ resume: "native" | "cold" | "unsupported";
268
+ /** 优雅中断 or 只能杀进程(公共杀链兜底,见 D1 abort 分级)。 */
269
+ interrupt: "native" | "kill-only";
270
+ /** kimi headless 固定 auto = ignored;GUI 据此隐藏/提示。 */
271
+ permissionMode: "native" | "fixed" | "ignored";
272
+ }
273
+
274
+ // ============================================================
275
+ // probe(D7)与 interact(D1)的负载类型
276
+ // ============================================================
277
+
278
+ /** 引擎探针报告(probe() 返回)。探针在引擎 factory 初始化与版本变化检测时触发(P4 接线)。 */
279
+ export interface ProbeReport {
280
+ ok: boolean;
281
+ /** 实测版本(handle.engineVersion 数据源)。探测不到时为空串。 */
282
+ engineVersion: string;
283
+ /** 二进制存在/版本解析/干跑回归逐项。 */
284
+ checks: Array<{ name: string; ok: boolean; detail?: string }>;
285
+ /** engine_probe_failed 的恢复指引(设计 §3.3.3 终态四样例;ok=false 时必填)。 */
286
+ error?: { code: string; recovery: string };
287
+ }
288
+
289
+ /**
290
+ * interact 的 action(D1 交互控制面)。pi 首期原生实现(现有 chatMode 行为直通);
291
+ * 声明 conversation unsupported 的引擎调用前拒绝(engine_capability_unsupported)。
292
+ */
293
+ export type InteractAction =
294
+ | { kind: "message"; payload: string }
295
+ | { kind: "close"; payload?: { force: boolean } }
296
+ | { kind: "cancel" };
297
+
298
+ /**
299
+ * interact 的结果。失败码取自设计 §3.3.3:engine_session_not_resumable(死 handle)/
300
+ * engine_capability_unsupported(能力声明拒绝)等。
301
+ */
302
+ export type InteractResult =
303
+ | { ok: true; delivered: true }
304
+ | { ok: false; code: string; message: string };
@@ -6,6 +6,7 @@
6
6
  // 接线层级:[模块内直调] —— SAR.run 内调。
7
7
 
8
8
  import type { AgentCallOpts } from "../orchestration/models/types.ts";
9
+ import { HOST_TIMEOUT_ABORT_REASON } from "./engine/common/kill-chain.ts";
9
10
  import type { ModelInfo } from "./model-resolver.ts";
10
11
  import type { ExecuteOptions } from "./types.ts";
11
12
 
@@ -84,7 +85,10 @@ export function mergeTimeoutSignal(
84
85
  }
85
86
 
86
87
  const controller = new AbortController();
87
- const timer = setTimeout(() => controller.abort(), timeoutMs);
88
+ // 超时 abort reason 标记(对齐点④):引擎合成终态时判别「宿主超时」
89
+ // (engine_timeout 公共合成)vs「外部 cancel」(中止标记)——pi 链路不读 reason,
90
+ // 行为不变。外部 signal abort 不带标记(用户/编排层 cancel 语义)。
91
+ const timer = setTimeout(() => controller.abort(HOST_TIMEOUT_ABORT_REASON), timeoutMs);
88
92
  timer.unref();
89
93
 
90
94
  const onExternalAbort = (): void => controller.abort();
@@ -161,6 +161,10 @@ export function createRecord(
161
161
  chatMode?: boolean;
162
162
  /** 空闲超时毫秒数(仅 chatMode 有意义)。覆盖默认 5min。 */
163
163
  idleTimeoutMs?: number;
164
+ /** 实际执行引擎 id(P4 路由留痕,D9①)。缺省 = pi 投影(存量零迁移)。 */
165
+ engine?: string;
166
+ /** 引擎 fallback 留痕(probe 失败路由回默认引擎)。GUI 警告条数据源。 */
167
+ engineFallback?: { from: string; reason: string };
164
168
  controller?: AbortController;
165
169
  },
166
170
  ): ExecutionRecord {
@@ -178,6 +182,8 @@ export function createRecord(
178
182
  depth: identity.depth ?? 0,
179
183
  chatMode: identity.chatMode,
180
184
  idleTimeoutMs: identity.idleTimeoutMs,
185
+ engine: identity.engine,
186
+ engineFallback: identity.engineFallback,
181
187
 
182
188
  // 状态(实时更新)
183
189
  status: "running",
@@ -48,6 +48,12 @@ export interface AgentConfig {
48
48
  thinkingLevel?: string;
49
49
  /** 默认 background 模式(true 时无显式 wait 走 background)。 */
50
50
  defaultBackground?: boolean;
51
+ /**
52
+ * 执行引擎 id(agent .md frontmatter engine 字段,D9 per-agent 主通道)。
53
+ * 解析期已对注册表校验(未注册 id 在 agent-registry 抛 EngineNotFoundError);
54
+ * 执行侧(P4 路由层)按 调用参数 > 本字段 > 全局默认 三层取值。
55
+ */
56
+ engine?: string;
51
57
  }
52
58
 
53
59
  /** 解析结果(model 实例 + 生效的 thinkingLevel)。 */
@@ -1,4 +1,4 @@
1
- // src/core/pi-invocation.ts
1
+ // src/execution/pi-invocation.ts
2
2
  //
3
3
  // 定位 pi 二进制并组装 spawn 调用。Core 叶子原语(仅依赖 node 内置)。
4
4
  //
@@ -16,6 +16,8 @@
16
16
  import * as fs from "node:fs";
17
17
  import * as path from "node:path";
18
18
 
19
+ import { isRelayActive, RELAY_ENV_NODE, RELAY_ENV_SCRIPT } from "./relay-env.ts";
20
+
19
21
  /** spawn 调用描述符:command + args(透传给 child_process.spawn)。 */
20
22
  export interface PiInvocation {
21
23
  /** 可执行文件路径(node/bun/pi 二进制)。 */
@@ -24,6 +26,16 @@ export interface PiInvocation {
24
26
  args: string[];
25
27
  }
26
28
 
29
+ /** getPiInvocation 可选项。 */
30
+ export interface PiInvocationOptions {
31
+ /**
32
+ * false = 强制直连 spawn 真实 pi(不经 relay 代理)。唯一现役消费点是 PiEngine.probe
33
+ * ——探针意图是 pi 本体可解析性,经 relay 探到的是 runtime 健康,语义错位(E 方案 §5.1)。
34
+ * 缺省(undefined / true)时按 relay env 激活判定走代理。
35
+ */
36
+ relay?: boolean;
37
+ }
38
+
27
39
  /**
28
40
  * bun 虚拟文件系统前缀。bun bundle 模式下 process.argv[1] 形如
29
41
  * /$bunfs/root/pi——这不是磁盘上的真实文件,不能直接 spawn。
@@ -43,9 +55,12 @@ function isGenericRuntime(execPath: string): boolean {
43
55
  * 组装 pi 子进程的 spawn 调用。
44
56
  *
45
57
  * @param userArgs pi CLI 参数(如 ["--mode", "rpc", "--session-dir", "..."])
58
+ * @param opts 可选项(relay:false 强制直连——probe 用,见 PiInvocationOptions)
46
59
  * @returns spawn 描述符(command + 完整 args)
47
60
  *
48
61
  * 决策链(按优先级):
62
+ * 0. relay 激活(三 env 齐备且未显式禁用)→ <RELAY_NODE> <RELAY_SCRIPT> <userArgs>
63
+ * (E 方案 §5.1:xyz-agent runtime 存在时经代理 spawn,改的是进程拓扑不是 pi 语义)
49
64
  * 1. process.argv[1] 是真实磁盘文件且非 bun 虚拟路径 → <execPath> <argv[1]> <userArgs>
50
65
  * (复现当前 pi 进程的启动方式,确保扩展/配置/版本一致)
51
66
  * 2. execPath 非通用运行时(pi standalone binary)→ <execPath> <userArgs>
@@ -71,10 +86,25 @@ function currentScriptExists(): boolean {
71
86
  return scriptExistsCache.exists;
72
87
  }
73
88
 
74
- export function getPiInvocation(userArgs: string[]): PiInvocation {
89
+ export function getPiInvocation(userArgs: string[], opts?: PiInvocationOptions): PiInvocation {
75
90
  const currentScript = process.argv[1];
76
91
  const isBunVirtualScript = currentScript?.startsWith(BUN_VIRTUAL_PREFIX);
77
92
 
93
+ // 分支 0(前置):relay 激活(E 方案 §5.1)——runtime 注入三 env 齐备且未显式禁用时,
94
+ // spawn 目标切换为 <RELAY_NODE> <RELAY_SCRIPT> <原 pi spawnArgs>,形态与分支 1「node +
95
+ // script」同构(command 是执行器、args[0] 是脚本)。ELECTRON_RUN_AS_NODE 不在此补:
96
+ // 打包态执行器为 Electron 时由 runtime 与三 env 同点注入主 pi 进程 env(E-2
97
+ // getRelaySpawnEnv),本进程 {...process.env} 继承即达代理进程,extension 不重复判定。
98
+ // isRelayActive 已保证三 env 非空,下方取局部变量仅为 TS 收窄(isRelayActive 的
99
+ // 收窄不跨函数边界传导)。
100
+ if (opts?.relay !== false && isRelayActive(process.env)) {
101
+ const relayNode = process.env[RELAY_ENV_NODE];
102
+ const relayScript = process.env[RELAY_ENV_SCRIPT];
103
+ if (relayNode !== undefined && relayScript !== undefined) {
104
+ return { command: relayNode, args: [relayScript, ...userArgs] };
105
+ }
106
+ }
107
+
78
108
  // 分支 1:有真实脚本路径 → 复现启动方式(node <pi-script> <args>)
79
109
  if (currentScript && !isBunVirtualScript && currentScriptExists()) {
80
110
  return { command: process.execPath, args: [currentScript, ...userArgs] };
@@ -82,6 +82,17 @@ export interface SubagentRecordEntryData {
82
82
  chatMode?: boolean;
83
83
  /** 执行态信号(residual-fixes):true = 无活进程驱动的 running(轮终/孤儿兜底)。 */
84
84
  resumable?: boolean;
85
+ /**
86
+ * 实际执行引擎 id(P4 路由留痕,D9①)。缺省(存量 entry)= pi 投影,消费方零迁移。
87
+ */
88
+ engine?: string;
89
+ /** 引擎 fallback 留痕(probe 失败路由回默认引擎)。GUI 警告条数据源。 */
90
+ engineFallback?: { from: string; reason: string };
91
+ /**
92
+ * 引擎自描述定位符(U1:read 降级链①②级数据源)。引擎无关——sessionRef 整体
93
+ * 透传不枚举内部键(zcode = { sessionId, dbPath });缺省 = pi(存量 entry 零迁移)。
94
+ */
95
+ engineHandle?: { sessionRef: Record<string, string>; journalPath?: string; poolKey: string };
85
96
  }
86
97
 
87
98
  /** SubagentRecord → 自描述 entry data(快照投影,不 mutate 源)。 */
@@ -114,5 +125,8 @@ export function toSubagentRecordEntry(record: SubagentRecord): SubagentRecordEnt
114
125
  round: record.round,
115
126
  chatMode: record.chatMode,
116
127
  resumable: record.resumable,
128
+ engine: record.engine,
129
+ engineFallback: record.engineFallback,
130
+ engineHandle: record.engineHandle,
117
131
  };
118
132
  }
@@ -267,9 +267,39 @@ function rebuildEntryRecord(id: string, d: Record<string, unknown>): SubagentRec
267
267
  sessionFile: undefined,
268
268
  chatMode: d.chatMode === true,
269
269
  round: num("round"),
270
+ engine: str("engine"),
271
+ engineFallback:
272
+ isEngineFallbackShape(d.engineFallback) ? d.engineFallback : undefined,
273
+ engineHandle: isEngineHandleShape(d.engineHandle) ? d.engineHandle : undefined,
270
274
  };
271
275
  }
272
276
 
277
+ /** engineFallback entry 值的运行时 guard(未知 JSON 不裸收)。 */
278
+ function isEngineFallbackShape(v: unknown): v is { from: string; reason: string } {
279
+ if (typeof v !== "object" || v === null) return false;
280
+ const r = v as Record<string, unknown>;
281
+ return typeof r.from === "string" && typeof r.reason === "string";
282
+ }
283
+
284
+ /** engineHandle entry 值的运行时 guard(未知 JSON 不裸收;形状与 runtime 读侧
285
+ * subagent-engine-history 的 extractRecordEngineHandle 守卫语义对齐:poolKey
286
+ * 必有非空 string + sessionRef 值全 string 才收,journalPath 可选 string)。 */
287
+ function isEngineHandleShape(
288
+ v: unknown,
289
+ ): v is { sessionRef: Record<string, string>; journalPath?: string; poolKey: string } {
290
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
291
+ const h = v as Record<string, unknown>;
292
+ if (typeof h.poolKey !== "string" || h.poolKey.length === 0) return false;
293
+ if (typeof h.sessionRef !== "object" || h.sessionRef === null || Array.isArray(h.sessionRef)) {
294
+ return false;
295
+ }
296
+ for (const value of Object.values(h.sessionRef as Record<string, unknown>)) {
297
+ if (typeof value !== "string") return false;
298
+ }
299
+ if (h.journalPath !== undefined && typeof h.journalPath !== "string") return false;
300
+ return true;
301
+ }
302
+
273
303
  /** stat 戳(不存在 → null)。 */
274
304
  function statStamp(p: string): Stamp | null {
275
305
  try {
@@ -1195,6 +1225,10 @@ export class RecordStore {
1195
1225
  resumable: r.resumable,
1196
1226
  // [review round2] worktree 隔离标志:内存源有 handle 或跨重启重建带 hadWorktree 均为 true。
1197
1227
  worktree: r.worktreeHandle !== undefined || r.hadWorktree === true,
1228
+ engine: r.engine,
1229
+ engineFallback: r.engineFallback,
1230
+ // U2:engineHandle 经 entry 持久化(register/archive 双写点均经本投影),无则 undefined 自然省略
1231
+ engineHandle: r.engineHandle,
1198
1232
  };
1199
1233
  }
1200
1234
  }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * subagent relay 通道 env 名与协议常量 SSOT(docs/architecture/subagent-realtime-channel.md §5.1/§5.2/§3.1)。
3
+ *
4
+ * 为什么独立成模块:三方消费同一份常量——extension 侧(pi-invocation 激活判定 /
5
+ * buildChildEnv 归属写入)、runtime 侧(env 注入与镜像校验)、代理脚本 relay.mjs
6
+ * (零依赖脚本不能 import workspace 包,只能内嵌镜像,镜像一致性由 conformance
7
+ * relay 变体断言锁定)。禁各处手写字符串。
8
+ *
9
+ * env 语义:SOCKET/NODE/SCRIPT 三者同时非空 = relay 激活(全有或全无,无中间态);
10
+ * SESSION_ID/RECORD_ID 是 tee 帧归属键(缺失由代理握手前自检拒绝,退出码 13)。
11
+ */
12
+
13
+ export const RELAY_ENV_SOCKET = 'XYZ_SUBAGENT_RELAY_SOCKET';
14
+ export const RELAY_ENV_NODE = 'XYZ_SUBAGENT_RELAY_NODE';
15
+ export const RELAY_ENV_SCRIPT = 'XYZ_SUBAGENT_RELAY_SCRIPT';
16
+ export const RELAY_ENV_SESSION_ID = 'XYZ_SUBAGENT_RELAY_SESSION_ID';
17
+ export const RELAY_ENV_RECORD_ID = 'XYZ_SUBAGENT_RELAY_RECORD_ID';
18
+
19
+ /** relay 协议版本(握手帧 v 字段;runtime 与代理同包分发,不匹配=安装损坏)。 */
20
+ export const RELAY_PROTOCOL_VERSION = 1;
21
+
22
+ /** 代理专用退出码(extension 侧表现为「子进程非零退出」→ engine_run_failed 语义)。 */
23
+ export const RELAY_EXIT_CODES = {
24
+ /** 握手被拒:协议版本不匹配(安装损坏,重装应用)。 */
25
+ VERSION_MISMATCH: 10,
26
+ /** relay socket 不可达(runtime 未运行或已重启)。 */
27
+ SOCKET_UNREACHABLE: 11,
28
+ /** socket 中途断开(runtime 崩溃等)——代理生命线断即退。 */
29
+ SOCKET_CLOSED: 12,
30
+ /** 归属 env(SESSION_ID/RECORD_ID)缺失——防无归属帧污染广播。 */
31
+ MISSING_IDENTITY: 13,
32
+ } as const;
33
+
34
+ /** 激活判定:三 env 同时非空才走 relay,任一缺失回落直连 spawn 真实 pi(TUI/独立 pi 零回归)。 */
35
+ export function isRelayActive(env: NodeJS.ProcessEnv | Record<string, string | undefined>): boolean {
36
+ return Boolean(env[RELAY_ENV_SOCKET] && env[RELAY_ENV_NODE] && env[RELAY_ENV_SCRIPT]);
37
+ }
@@ -25,6 +25,7 @@ import type { AgentConfig, ResolvedModel } from "./model-resolver.ts";
25
25
  import { collectResult } from "./output-collector.ts";
26
26
  import { getSubagentSessionDir } from "./path-encoding.ts";
27
27
  import { getPiInvocation } from "./pi-invocation.ts";
28
+ import { isRelayActive, RELAY_ENV_RECORD_ID, RELAY_ENV_SESSION_ID } from "./relay-env.ts";
28
29
  import { stringifySchemaCached } from "../shared/schema-jsonify.ts";
29
30
  import { MAX_FORK_DEPTH } from "./session-context-resolver.ts";
30
31
  import { EPIPE_FAILURE_THRESHOLD, recordEpipeFailure, sendPromptCommand } from "./stdin-writer.ts";
@@ -335,6 +336,20 @@ function removeChildRegistration(recordId: string, child: ChildProcess): void {
335
336
  }
336
337
  }
337
338
 
339
+ /**
340
+ * [U0 D10] 非 pi 引擎路径的子进程记账注册入口(宿主经 RunContext.onChildSpawned 调用)。
341
+ *
342
+ * 与 pi runSpawn 内联注册同构:set 进 Map + close/error 按句守卫移除(M4 竞态守卫语义
343
+ * 复用 removeChildRegistration)。pi 路径保持内联不动(其 close/error handler 还承担
344
+ * EPIPE 记账等 pi 专属副作用,不适合收敛到本函数)——两入口写同一 Map,dispose 的
345
+ * killAllSpawnedChildren / cancelBackground 的 getChildByRecord 对两域 record 均生效。
346
+ */
347
+ export function registerSpawnedChildForRecord(recordId: string, child: ChildProcess): void {
348
+ spawnedChildren.set(recordId, child);
349
+ child.once("close", () => removeChildRegistration(recordId, child));
350
+ child.once("error", () => removeChildRegistration(recordId, child));
351
+ }
352
+
338
353
  // ============================================================
339
354
  // 依赖注入容器 + 入参
340
355
  // ============================================================
@@ -963,6 +978,15 @@ function buildChildEnv(
963
978
  //(同进程内保留),子进程 identity entry 据此记 worktree:true——跨重启重建时据此拒绝续聊
964
979
  //(WorktreeHandle 不可序列化,reattach 不可行,静默回落主 repo 会破坏隔离)。
965
980
  childEnv.PI_SUBAGENT_WORKTREE = opts.worktree !== undefined ? "true" : undefined;
981
+ // [E 方案 §5.2-2] relay 帧归属 env:tee 帧路由键(→ 虚拟分区 subagent:<sid>:<rid>)。
982
+ // 仅 relay 激活时写入实际值——未激活环境下子 pi 进程携带 record 值 env 是误导噪声
983
+ //(归属 env 无消费者);{...process.env} 继承值照旧保持。同源性对齐上方 PI_SUBAGENT_*
984
+ // 四元组:SESSION_ID = ctx.sessionRootId(嵌套 spawn 时孙进程仍归属真 ROOT 会话),
985
+ // RECORD_ID = record.id。
986
+ if (isRelayActive(process.env)) {
987
+ childEnv[RELAY_ENV_SESSION_ID] = ctx.sessionRootId;
988
+ childEnv[RELAY_ENV_RECORD_ID] = record.id;
989
+ }
966
990
  // D-A6 bridge: schema 激活 structured-output 扩展注册 tool(workflow 编排层需要)
967
991
  applySchemaEnvToChildEnv(childEnv, opts.schemaEnv);
968
992
  return childEnv;
@@ -16,6 +16,10 @@
16
16
  * - dispose 清除 widget + 清 timer
17
17
  */
18
18
 
19
+ import type { ExtensionMode } from "./host-mode.ts";
20
+ import { resolveHostMode } from "./host-mode.ts";
21
+ import { isRelayActive } from "./relay-env.ts";
22
+
19
23
  /** UI streaming sink 的最小接口(ctx.ui.setWidget 的 duck-typed 子集)。
20
24
  *
21
25
  * 当前只有一个 adapter(index.ts session_start 包装 ctx.ui.setWidget)。
@@ -98,3 +102,25 @@ export class SubagentStream {
98
102
  ]);
99
103
  }
100
104
  }
105
+
106
+ /**
107
+ * background stream 创建策略(widget 私货通道退役步骤 2,E 方案 §6.3)。
108
+ *
109
+ * GUI(mode=rpc)+ relay 激活时不创建——drawer 实时改由 runtime tee 供数
110
+ * (session.subagentEntriesAppended 帧),extension 停发 setWidget 私货,主 pi stdout
111
+ * 卸载。TUI(widget 行是 TUI 用户的实时预览)与 relay 未激活环境(独立 pi / 无
112
+ * xyz-agent runtime)原样创建——universal 包自足性不绑架。
113
+ *
114
+ * env/mode 显式入参而非内部读 process.env:调用方语义(本 record 的宿主形态)一次
115
+ * 确定,测试可注入,函数保持纯判定。
116
+ */
117
+ export function createBackgroundStream(
118
+ recordId: string,
119
+ sink: StreamSink | null,
120
+ mode: ExtensionMode | undefined,
121
+ env: NodeJS.ProcessEnv | Record<string, string | undefined>,
122
+ ): SubagentStream | undefined {
123
+ if (sink === null) return undefined;
124
+ if (isRelayActive(env) && resolveHostMode(mode) === "gui") return undefined;
125
+ return new SubagentStream(recordId, sink);
126
+ }