@zhushanwen/pi-subagent-workflow 0.2.0 → 0.3.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 (64) hide show
  1. package/README.md +56 -0
  2. package/agents/{scout.md → explorer.md} +1 -1
  3. package/agents/orchestrator.md +48 -0
  4. package/package.json +1 -1
  5. package/src/execution/__tests__/agent-registry.test.ts +3 -3
  6. package/src/execution/__tests__/ask-user-transit-e2e.test.ts +484 -0
  7. package/src/execution/__tests__/channel-registry-handshake.test.ts +233 -0
  8. package/src/execution/__tests__/crash-recovery.test.ts +5 -1
  9. package/src/execution/__tests__/dialog-queue.test.ts +299 -0
  10. package/src/execution/__tests__/execute-nesting.test.ts +1 -1
  11. package/src/execution/__tests__/execute-options-mapper.test.ts +1 -1
  12. package/src/execution/__tests__/finalize-record.test.ts +173 -0
  13. package/src/execution/__tests__/gui-mode-dispatch.test.ts +2 -3
  14. package/src/execution/__tests__/helpers/spawn-mock.ts +209 -0
  15. package/src/execution/__tests__/host-mode.test.ts +87 -0
  16. package/src/execution/__tests__/index-session-start.test.ts +342 -0
  17. package/src/execution/__tests__/list-component.test.ts +1 -1
  18. package/src/execution/__tests__/notifier-flush.test.ts +78 -0
  19. package/src/execution/__tests__/path-encoding.test.ts +30 -1
  20. package/src/execution/__tests__/record-store.test.ts +86 -2
  21. package/src/execution/__tests__/records-cwd-isolation.test.ts +91 -0
  22. package/src/execution/__tests__/rpc-mode.test.ts +89 -0
  23. package/src/execution/__tests__/run-spawn-edges.test.ts +157 -153
  24. package/src/execution/__tests__/run-spawn-integration.test.ts +85 -151
  25. package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +193 -0
  26. package/src/execution/__tests__/session-file-gc.test.ts +46 -0
  27. package/src/execution/__tests__/session-start-reaper.test.ts +7 -1
  28. package/src/execution/__tests__/spawn-args.test.ts +14 -19
  29. package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +189 -0
  30. package/src/execution/__tests__/stdin-writer.test.ts +353 -0
  31. package/src/execution/__tests__/subagent-service.test.ts +73 -3
  32. package/src/execution/__tests__/tool-action.test.ts +1 -1
  33. package/src/execution/__tests__/ui-channels.test.ts +187 -0
  34. package/src/execution/__tests__/ui-interaction-model.test.ts +67 -0
  35. package/src/execution/__tests__/ui-request-handler-factory.test.ts +166 -0
  36. package/src/execution/__tests__/ui-request-handler.test.ts +204 -0
  37. package/src/execution/__tests__/ui-request-observability.test.ts +101 -0
  38. package/src/execution/__tests__/ui-request-queue.test.ts +133 -0
  39. package/src/execution/__tests__/worktree-manager.test.ts +1 -1
  40. package/src/execution/agent-registry.ts +1 -1
  41. package/src/execution/channel-registry-access.ts +138 -0
  42. package/src/execution/dialog-queue.ts +329 -0
  43. package/src/execution/finalize-record.ts +160 -0
  44. package/src/execution/get-state-handshake.ts +104 -0
  45. package/src/execution/host-mode.ts +52 -0
  46. package/src/execution/manifest-store.ts +206 -0
  47. package/src/execution/notifier.ts +5 -1
  48. package/src/execution/path-encoding.ts +18 -0
  49. package/src/execution/pi-invocation.ts +1 -1
  50. package/src/execution/record-store.ts +108 -2
  51. package/src/execution/session-file-gc.ts +25 -3
  52. package/src/execution/session-runner.ts +216 -32
  53. package/src/execution/spawn-event-adapter.ts +219 -6
  54. package/src/execution/stdin-writer.ts +106 -0
  55. package/src/execution/subagent-service.ts +167 -197
  56. package/src/execution/ui-channels.ts +216 -0
  57. package/src/execution/ui-interaction-model.ts +48 -0
  58. package/src/execution/ui-request-handler-factory.ts +175 -0
  59. package/src/execution/ui-request-observability.ts +77 -0
  60. package/src/execution/ui-request-queue.ts +168 -0
  61. package/src/index.ts +90 -6
  62. package/src/interface/format.ts +2 -0
  63. package/src/interface/subagent-actions.ts +9 -2
  64. package/src/interface/subagent-tool.ts +9 -8
@@ -0,0 +1,216 @@
1
+ // src/execution/ui-channels.ts
2
+ //
3
+ // UI channel 提取(marker 解析)+ channel 注册表。
4
+ //
5
+ // channel 是扩展协议自定义的业务路由标识,由 NUL 前缀 marker 标记。
6
+ // 已知 marker(来自 @xyz-agent/extension-protocol):
7
+ // - ASK_USER_MARKER = "\0XYZ_ASK_USER" 走 select method,出现在 title
8
+ // (options[0] = JSON payload {questions, allowCancel})
9
+ // - GUI_WIDGET_MARKER = "\0XYZ_GUI_WIDGET:" 走 setWidget method,出现在 widgetLines[0]
10
+ // (同行 marker 后紧跟 JSON payload {component})
11
+ //
12
+ // channel 提取位置随 method 变(.fix-plans/00-master-summary.md §一冲突 2):
13
+ // - select → 从 title 解析 NUL 前缀(payload 从 options[0] 取)
14
+ // - setWidget → 从 widgetLines[0] 解析 NUL 前缀(payload 从同行 marker 后取)
15
+ // - 其他 method → 无 channel(返回 {})
16
+ //
17
+ // channel 名规范化:去 "XYZ_" 命名空间前缀,去尾部 ":",小写化。
18
+ // XYZ_ASK_USER → ask_user
19
+ // XYZ_GUI_WIDGET → gui_widget
20
+ //
21
+ // 本模块是协议层工具(method/marker 都是协议概念),不感知业务。
22
+
23
+ /** NUL 前缀字符。Pi extension-protocol 用 NUL(\0)标记控制行,
24
+ * 避免与用户可见文本冲突。 */
25
+ const NUL = "\0";
26
+
27
+ /** channel 提取结果。channel 无 NUL 前缀、字段缺失、JSON parse 失败时
28
+ * channel 与 channelPayload 均为 undefined(返回 {})。 */
29
+ export interface ParsedChannel {
30
+ /** 规范化后的 channel 名(如 "ask_user"、"gui_widget")。
31
+ * 无 marker 或解析失败时为 undefined。 */
32
+ channel?: string;
33
+ /** marker 标记的结构化 payload(已 JSON.parse)。
34
+ * ask_user: {questions, allowCancel};gui_widget: {component}。
35
+ * payload 来源缺失或 JSON parse 失败时为 undefined(channel 仍可解析)。 */
36
+ channelPayload?: unknown;
37
+ }
38
+
39
+ /** parseChannel 入参的最小形状。
40
+ * method 是判别字段;按 method 不同,对应字段(select 的 title/options、
41
+ * setWidget 的 widgetLines)可选出现。其他 method 的字段统称 [key:string]。 */
42
+ export interface ExtensionUiRequestLike {
43
+ method: string;
44
+ /** select method:title 字段(可能含 ASK_USER_MARKER NUL 前缀)。 */
45
+ title?: string;
46
+ /** select method:options 数组(options[0] 可能是 channel payload 的 JSON)。 */
47
+ options?: string[];
48
+ /** setWidget method:widgetKey 字段。 */
49
+ widgetKey?: string;
50
+ /** setWidget method:widgetLines 数组(widgetLines[0] 可能含 GUI_WIDGET_MARKER)。 */
51
+ widgetLines?: string[] | undefined;
52
+ /** 其他 method 的任意字段(容错:允许测试和未来扩展传入额外字段)。 */
53
+ [key: string]: unknown;
54
+ }
55
+
56
+ /** channel handler 签名:接收 UiRequest,返回 UiResponse。
57
+ * 具体类型定义在 session-runner.ts(W2 工作),此处用最小形状避免循环依赖。
58
+ * handler 实现方按 channel 注册,由 session-runner 按 req.channel 分派。 */
59
+ export type ChannelHandler = (req: unknown) => Promise<unknown>;
60
+
61
+ /** channel 注册表接口。职责单一:只管业务路由,不管排队、不管透传判定。
62
+ * - register(channel, handler):注册 channel 对应的 handler(同名覆盖)
63
+ * - resolve(channel):取 channel 对应的 handler,未注册返回 undefined
64
+ * - list():列举所有已注册 channel 名 */
65
+ export interface UiChannelRegistry {
66
+ register(channel: string, handler: ChannelHandler): void;
67
+ resolve(channel: string): ChannelHandler | undefined;
68
+ list(): string[];
69
+ }
70
+
71
+ /** 规范化 channel 名。
72
+ * 输入是 NUL 前缀后的字面量(如 "XYZ_ASK_USER"、"XYZ_GUI_WIDGET:")。
73
+ * 规则:
74
+ * 1. 去 "XYZ_" 命名空间前缀(协议命名空间标识,非业务语义)
75
+ * 2. 去尾部 ":"(GUI_WIDGET 等"行内 payload"型 marker 的分隔符)
76
+ * 3. 小写化(XYZ_ASK_USER → ask_user)
77
+ *
78
+ * 例:
79
+ * "XYZ_ASK_USER" → "ask_user"
80
+ * "XYZ_GUI_WIDGET:" → "gui_widget"
81
+ * "FOO_BAR" → "foo_bar"(无 XYZ_ 前缀也容忍,去前缀仅当字面量以 XYZ_ 开头) */
82
+ function normalizeChannelName(markerLiteral: string): string {
83
+ let name = markerLiteral;
84
+ // 去 "XYZ_" 命名空间前缀(仅当以此开头)
85
+ if (name.startsWith("XYZ_")) {
86
+ name = name.slice("XYZ_".length);
87
+ }
88
+ // 去尾部 ":"(行内 payload 型 marker 的分隔符)
89
+ if (name.endsWith(":")) {
90
+ name = name.slice(0, -1);
91
+ }
92
+ return name.toLowerCase();
93
+ }
94
+
95
+ /** 从 marker 字面量字符串解析 channel 名。
96
+ * 输入 str 形如 "\0XYZ_ASK_USER"(marker 占满整个字段,payload 在别处)。
97
+ * 无 NUL 前缀返回 undefined。 */
98
+ function parseMarkerFromField(str: string): string | undefined {
99
+ if (!str.startsWith(NUL)) return undefined;
100
+ // 去掉 NUL 前缀,取剩余字面量作为 marker literal
101
+ const literal = str.slice(NUL.length);
102
+ if (literal === "") return undefined;
103
+ return normalizeChannelName(literal);
104
+ }
105
+
106
+ /** 从 marker + 行内 payload 字符串解析 channel 名 + payload。
107
+ * 输入 str 形如 "\0XYZ_GUI_WIDGET:{...json...}"(marker 与 payload 在同一行)。
108
+ * 无 NUL 前缀返回 undefined。
109
+ * payload 解析失败时不抛(返回 channel 名,payload 由调用方处理)。 */
110
+ function parseInlineMarkerFromField(str: string): { channel: string } | undefined {
111
+ if (!str.startsWith(NUL)) return undefined;
112
+ const rest = str.slice(NUL.length);
113
+ // marker literal 与 payload 的分界:第一个 ":" 或行尾
114
+ // GUI_WIDGET_MARKER 格式为 "\0XYZ_GUI_WIDGET:" + json,分界是 ":"
115
+ const colonIdx = rest.indexOf(":");
116
+ let literal: string;
117
+ if (colonIdx >= 0) {
118
+ literal = rest.slice(0, colonIdx + 1); // 含 ":",normalizeChannelName 会去尾部 ":"
119
+ } else {
120
+ literal = rest;
121
+ }
122
+ if (literal === "") return undefined;
123
+ return { channel: normalizeChannelName(literal) };
124
+ }
125
+
126
+ /** 从 select.title 解析 channel(payload 从 options[0] 取)。
127
+ * - title 无 NUL 前缀 → undefined
128
+ * - title 含 marker → channel 名;payload 从 options[0] JSON.parse(失败/缺失 → undefined) */
129
+ function parseFromMarkerString(
130
+ title: string | undefined,
131
+ options: string[] | undefined,
132
+ ): ParsedChannel {
133
+ if (title === undefined) return {};
134
+ const channel = parseMarkerFromField(title);
135
+ if (channel === undefined) return {};
136
+ // payload 从 options[0] 取(ask_user 协议:title 是 marker,options[0] 是 JSON payload)
137
+ let payload: unknown;
138
+ if (options !== undefined && options.length > 0) {
139
+ try {
140
+ payload = JSON.parse(options[0]);
141
+ } catch {
142
+ payload = undefined; // JSON parse 失败:不抛,channel 仍解析
143
+ }
144
+ }
145
+ return { channel, channelPayload: payload };
146
+ }
147
+
148
+ /** 从 setWidget.widgetLines[0] 解析 channel(payload 从同行 marker 后取)。
149
+ * - widgetLines 缺失/空数组/首行无 NUL 前缀 → undefined
150
+ * - 首行含 marker → channel 名;payload 从 marker 后的 JSON 取(失败 → undefined) */
151
+ function parseFromMarkerArray(
152
+ widgetLines: string[] | undefined,
153
+ ): ParsedChannel {
154
+ if (widgetLines === undefined || widgetLines.length === 0) return {};
155
+ const firstLine = widgetLines[0];
156
+ if (typeof firstLine !== "string") return {};
157
+ const parsed = parseInlineMarkerFromField(firstLine);
158
+ if (parsed === undefined) return {};
159
+ // payload 从 marker 后的 JSON 取(GUI_WIDGET 协议:marker 与 payload 同行)
160
+ let payload: unknown;
161
+ const rest = firstLine.slice(NUL.length);
162
+ const colonIdx = rest.indexOf(":");
163
+ if (colonIdx >= 0) {
164
+ const jsonStr = rest.slice(colonIdx + 1);
165
+ if (jsonStr !== "") {
166
+ try {
167
+ payload = JSON.parse(jsonStr);
168
+ } catch {
169
+ payload = undefined; // JSON parse 失败:不抛,channel 仍解析
170
+ }
171
+ }
172
+ }
173
+ return { channel: parsed.channel, channelPayload: payload };
174
+ }
175
+
176
+ /** 按 method 分派解析 channel。
177
+ *
178
+ * - select → 从 title 解析 NUL 前缀(payload 从 options[0])
179
+ * - setWidget → 从 widgetLines[0] 解析 NUL 前缀(payload 从同行 marker 后)
180
+ * - 其他 method → {}(无 channel 提取位置)
181
+ *
182
+ * 边界(均不抛错):
183
+ * - title/widgetLines 字段缺失 → {}
184
+ * - 无 NUL 前缀 → {}
185
+ * - JSON parse 失败 → channel 仍解析,channelPayload 为 undefined
186
+ *
187
+ * @param req ExtensionUiRequestLike(method + 对应字段)
188
+ * @returns ParsedChannel(channel/channelPayload 可选) */
189
+ export function parseChannel(req: ExtensionUiRequestLike): ParsedChannel {
190
+ switch (req.method) {
191
+ case "select":
192
+ return parseFromMarkerString(req.title, req.options);
193
+ case "setWidget":
194
+ return parseFromMarkerArray(req.widgetLines);
195
+ default:
196
+ return {};
197
+ }
198
+ }
199
+
200
+ /** 创建 channel 注册表实例。
201
+ * 进程级单例(通常由 SubagentService 持有一个实例,跨所有子进程共享)。
202
+ * register 同名 channel 会覆盖旧 handler。 */
203
+ export function createUiChannelRegistry(): UiChannelRegistry {
204
+ const handlers = new Map<string, ChannelHandler>();
205
+ return {
206
+ register(channel: string, handler: ChannelHandler): void {
207
+ handlers.set(channel, handler);
208
+ },
209
+ resolve(channel: string): ChannelHandler | undefined {
210
+ return handlers.get(channel);
211
+ },
212
+ list(): string[] {
213
+ return Array.from(handlers.keys());
214
+ },
215
+ };
216
+ }
@@ -0,0 +1,48 @@
1
+ // src/execution/ui-interaction-model.ts
2
+ //
3
+ // Pi ctx.ui method 的交互模型分类。
4
+ //
5
+ // 固化 Pi rpc-mode.ts(--mode rpc 子进程的 ctx.ui 实现)中 10 个会发
6
+ // extension_ui_request 的 method 的交互模型分类,供 session-runner 决定:
7
+ // - 是否透传到主进程 handler(dialog 类才透传,fire-and-forget 不透传)
8
+ // - 是否进 L2 全局串行队列(dialog 类才排队,争输入焦点)
9
+ //
10
+ // 分类依据(.fix-plans/00-master-summary.md §一冲突 2「维度 1」):
11
+ //
12
+ // | 交互模型 | method | 行为 | 子进程不回会怎样 |
13
+ // |---|---|---|---|
14
+ // | dialog(占输入焦点,等响应) | select confirm input editor |
15
+ // 子进程在 pendingExtensionRequests 注册 Promise 等 id 对应 response |
16
+ // Promise 永挂 + 内存泄漏 |
17
+ // | fire-and-forget(纯展示/写入,不等响应) |
18
+ // notify setStatus setWidget setTitle set_editor_text | output() 完即返回 |
19
+ // 无影响 |
20
+ //
21
+ // 未知 method 默认按 fire-and-forget 处理(保守:不透传、不排队),
22
+ // 避免 Pi 未来新增 method 时误判为 dialog 导致不必要的串行。
23
+
24
+ /** dialog 类 method 集合:占输入焦点、等响应、需透传 + 排队。
25
+ * 与 Pi rpc-mode.ts 的 pendingExtensionRequests 注册逻辑一一对应。 */
26
+ const DIALOG_METHODS: ReadonlySet<string> = new Set([
27
+ "select",
28
+ "confirm",
29
+ "input",
30
+ "editor",
31
+ ]);
32
+
33
+ /** 判断 method 是否为 dialog 类(占输入焦点,等响应)。
34
+ *
35
+ * dialog 类(select/confirm/input/editor):
36
+ * - 子进程在 pendingExtensionRequests 注册 Promise 等对应 id 的 response
37
+ * - 主进程必须透传 + 进 L2 全局串行队列(争输入焦点)
38
+ * - 不响应会导致子进程 Promise 永挂 + 内存泄漏
39
+ *
40
+ * fire-and-forget 类(notify/setStatus/setWidget/setTitle/set_editor_text 及未知 method):
41
+ * - 子进程 output() 完即返回,不注册 pending
42
+ * - 默认不透传(TUI 下不影响输入交互),不排队
43
+ *
44
+ * @param method Pi rpc-types.ts 的 method 字段值
45
+ * @returns dialog 类返回 true,fire-and-forget 类(含未知 method)返回 false */
46
+ export function isDialogMethod(method: string): boolean {
47
+ return DIALOG_METHODS.has(method);
48
+ }
@@ -0,0 +1,175 @@
1
+ // src/execution/ui-request-handler-factory.ts
2
+ //
3
+ // UI 请求 handler 工厂(透传 + 排队总控)。
4
+ //
5
+ // 按 ctx.mode(ExtensionMode)创建合适的 UiRequestHandler,让 SubagentService 持有后
6
+ // 经 session-runner 透传给子进程的 extension_ui_request。本模块是「handler 注入链路」的
7
+ // 组装点:把 channel registry(业务路由)+ dialog queue(L2 跨子进程串行)+ mode 分流
8
+ //(TUI/GUI/headless)粘合成一个 handler。
9
+ //
10
+ // 设计依据(.fix-plans/00-master-summary.md):
11
+ // - §一冲突 2「透传矩阵」:
12
+ // TUI dialog 透传 + L2 排队;fire-and-forget 不透传(回 ack,不影响 TUI 输入交互)
13
+ // GUI 全透传;dialog 走 L2 排队,fire-and-forget 直接转发
14
+ // headless 不注入(返回 undefined)
15
+ // - §一冲突 3「L2 队列接入点」:dialog 类进 dialogQueue.enqueue 串行
16
+ // - §二 2.7「handler 工厂 + 透传/排队总控」:createUiRequestHandlerForMode 完整实现
17
+ //
18
+ // SR-3:调用方(index.ts session_start)无论 new 还是 existing SubagentService 都必须调
19
+ // setUiRequestHandler——/resume /fork 复用 existingService 时旧 handler 可能已失效。
20
+
21
+ import type { ExtensionContext } from "@mariozechner/pi-coding-agent";
22
+
23
+ import { DialogGlobalQueue, type UiRequest, type UiRequestHandler, type UiResponse } from "./dialog-queue.ts";
24
+ import { type HostMode, resolveHostMode } from "./host-mode.ts";
25
+ import type { UiChannelRegistry } from "./ui-channels.ts";
26
+ import { isDialogMethod } from "./ui-interaction-model.ts";
27
+
28
+ /** 按 ctx.mode 创建 UI 请求 handler(透传 + 排队总控)。
29
+ *
30
+ * 透传矩阵(§一冲突 2):
31
+ * - headless(json/print/undefined):返回 undefined(不注入任何 UI handler)
32
+ * - TUI:dialog 透传 + L2 排队;fire-and-forget 回 ack 不透传(不影响 TUI 输入交互)
33
+ * - GUI(rpc):全透传;dialog 走 L2 排队,fire-and-forget 直接转发
34
+ *
35
+ * 业务路由(§一冲突 2 维度 2):
36
+ * - channel 命中 registry(ask_user/gui_widget)→ 走注册的 channel handler
37
+ * - 无 channel 的 dialog → defaultDialogForward(调主 agent ctx.ui.select/confirm/...)
38
+ *
39
+ * SR-3:调用方(index.ts session_start)无论 new 还是 existing SubagentService 都必须调
40
+ * setUiRequestHandler。headless 下本函数返回 undefined,调用方应据此走不注入路径。
41
+ *
42
+ * @param ctx Pi ExtensionContext(读 ctx.mode 分流)
43
+ * @param registry channel 注册表(业务路由;W3 当前为空,ask-user 扩展 Stage 4a 注册)
44
+ * @param dialogQueue L2 跨子进程全局 dialog 串行队列
45
+ * @returns UiRequestHandler(tui/gui);headless 返回 undefined */
46
+ export function createUiRequestHandlerForMode(
47
+ ctx: ExtensionContext,
48
+ registry: UiChannelRegistry,
49
+ dialogQueue: DialogGlobalQueue,
50
+ ): UiRequestHandler | undefined {
51
+ const hostMode = resolveHostMode(ctx.mode);
52
+ if (hostMode === "headless") return undefined;
53
+
54
+ const realHandler = createRealHandler(ctx, hostMode, registry);
55
+
56
+ return async (req: UiRequest): Promise<UiResponse> => {
57
+ // 维度 1:TUI 下 fire-and-forget 不透传(回 ack,不写 stdin——由 session-runner respond 处理)
58
+ if (hostMode === "tui" && !isDialogMethod(req.method)) {
59
+ return { ack: true };
60
+ }
61
+ // L2 全局队列:dialog 类必须串行(争输入焦点)。fire-and-forget(GUI 下)直接转发。
62
+ // [SR-4] 透传 req._childPid(session-runner 从 child.pid 填入)给 enqueue——
63
+ // L2 据此关联 child close 时的 rejectChildDialogs 批量 reject(防全局死锁)。
64
+ if (isDialogMethod(req.method)) {
65
+ return dialogQueue.enqueue(req, realHandler, {
66
+ child: req._childPid !== undefined ? { pid: req._childPid } : undefined,
67
+ });
68
+ }
69
+ // GUI 下 fire-and-forget 直接转发
70
+ return realHandler(req);
71
+ };
72
+ }
73
+
74
+ /** 创建实际处理请求的 handler(channel 路由 + 默认转发)。
75
+ * - channel 命中 registry(ask_user)→ channel handler(结果经 coerceUiResponse 形变)
76
+ * - 无 channel 的 dialog → defaultDialogForward(主 agent ctx.ui.*) */
77
+ function createRealHandler(
78
+ ctx: ExtensionContext,
79
+ _hostMode: HostMode,
80
+ registry: UiChannelRegistry,
81
+ ): UiRequestHandler {
82
+ return async (req: UiRequest): Promise<UiResponse> => {
83
+ // 维度 2:channel 业务路由。channel handler 签名是 (unknown)=>Promise<unknown>
84
+ //(ui-channels.ts 定义,避免循环依赖),此处经 coerceUiResponse 形变为 UiResponse。
85
+ const channelHandler = registry.resolve(req.channel ?? "");
86
+ if (channelHandler) {
87
+ const raw = await channelHandler(req);
88
+ return coerceUiResponse(raw, req.id);
89
+ }
90
+
91
+ // 无 channel 的 dialog → 默认转发到主 agent ctx.ui.*
92
+ return defaultDialogForward(req, ctx);
93
+ };
94
+ }
95
+
96
+ /** channel handler 返回值(unknown)形变为 UiResponse。
97
+ * channel handler 由扩展注册(如 ask-user 扩展返回 {value}/{confirmed}/{cancelled}),
98
+ * 但 ChannelHandler 类型签名用 unknown(协议层避免循环依赖)。本函数做运行时收窄:
99
+ * - 已是合法 UiResponse shape → 原样返回
100
+ * - 形状不匹配 → 降级 {cancelled:true}(保守,不阻塞队列) */
101
+ function coerceUiResponse(raw: unknown, reqId: string): UiResponse {
102
+ if (typeof raw !== "object" || raw === null) {
103
+ console.warn("[subagents] channel handler returned non-object, coercing to cancelled (req=", reqId, ")");
104
+ return { cancelled: true };
105
+ }
106
+ const obj = raw as Record<string, unknown>;
107
+ if (typeof obj.value === "string") return { value: obj.value };
108
+ if (typeof obj.confirmed === "boolean") return { confirmed: obj.confirmed };
109
+ if (obj.cancelled === true) return { cancelled: true };
110
+ if (obj.ack === true) return { ack: true };
111
+ console.warn("[subagents] channel handler returned unrecognized shape, coercing to cancelled (req=", reqId, ")");
112
+ return { cancelled: true };
113
+ }
114
+
115
+ /** 无 channel 的 dialog 默认转发:调主 agent 的 ctx.ui.select/confirm/input/editor。
116
+ * ask_user channel 未注册时(ask-user 扩展未安装)也会落到这里——
117
+ * select 请求转发为普通 select(title 可能含 marker,主 agent 会忽略或当普通 select 渲染)。
118
+ *
119
+ * 实现依据(SDK ExtensionUIContext 真实签名,read from
120
+ * @mariozechner/pi-coding-agent dist/core/extensions/types.d.ts):
121
+ * select(title: string, options: string[], opts?): Promise<string | undefined>
122
+ * confirm(title: string, message: string, opts?): Promise<boolean>
123
+ * input(title: string, placeholder?: string, opts?): Promise<string | undefined>
124
+ * editor(title: string, prefill?: string): Promise<string | undefined>
125
+ * 注意:SDK 是位置参数(非对象参数);返回 undefined 表示用户取消。
126
+ *
127
+ * Stage 4 风险点:TUI 下 ask_user channel 未注册时,select 会以普通列表渲染
128
+ * (title 可能含 marker)。channel 注册后由 createRealHandler 优先走 channel handler,
129
+ * 不进这里。editor 不可用/抛错时降级 cancelled + warn,不卡队列。 */
130
+ async function defaultDialogForward(
131
+ req: UiRequest,
132
+ ctx: ExtensionContext,
133
+ ): Promise<UiResponse> {
134
+ const ui = ctx.ui;
135
+ switch (req.method) {
136
+ case "select": {
137
+ const selected = await ui.select(req.title ?? "", req.options ?? []);
138
+ return selected === undefined ? { cancelled: true } : { value: selected };
139
+ }
140
+ case "confirm": {
141
+ // SDK confirm 必传 message(req.message 缺失时降级空串,不报错阻塞)
142
+ const confirmed = await ui.confirm(req.title ?? "", req.message ?? "");
143
+ return { confirmed };
144
+ }
145
+ case "input": {
146
+ const text = await ui.input(req.title ?? "", req.placeholder);
147
+ return text === undefined ? { cancelled: true } : { value: text };
148
+ }
149
+ case "editor": {
150
+ // SDK editor 必填,但部分 host 运行时未实现——try/catch 降级 cancelled + warn(不卡队列)。
151
+ // 不用 typeof 守卫:editor 在类型上必填,typeof 检查会被 TS2367 拒(条件永假)。
152
+ try {
153
+ const text = await ui.editor(req.title ?? "", req.prefill);
154
+ return text === undefined ? { cancelled: true } : { value: text };
155
+ } catch (err) {
156
+ console.warn(
157
+ "[subagents] ctx.ui.editor unavailable/threw, returning cancelled for",
158
+ req.id,
159
+ err,
160
+ );
161
+ return { cancelled: true };
162
+ }
163
+ }
164
+ default: {
165
+ // 未知 dialog method(非 select/confirm/input/editor)——保守 cancelled 不阻塞子进程
166
+ console.warn(
167
+ "[subagents] defaultDialogForward: unknown dialog method",
168
+ req.method,
169
+ "for",
170
+ req.id,
171
+ );
172
+ return { cancelled: true };
173
+ }
174
+ }
175
+ }
@@ -0,0 +1,77 @@
1
+ // src/execution/ui-request-observability.ts
2
+ //
3
+ // UI 请求可观测性状态(从 subagent-service.ts 提取,降低主文件行数)。
4
+ // 持有 sessionMode + handler 缺失告警去重集合,供 SubagentService 委托调用。
5
+
6
+ import type { ExtensionMode } from "@mariozechner/pi-coding-agent";
7
+
8
+ // ── 跨模块桥接(ui-request-queue 无 ctx.service 引用时走这里) ──
9
+ //
10
+ // ui-request-queue.handleUiRequest 在 ctx.uiRequestHandler 缺失时需要触发去重告警,
11
+ // 但 SessionRunnerContext 不持有 service 引用(改 ctx 签名超出本组 4 文件范围)。
12
+ // 解法:SubagentService 构造后调 registerGlobalObservability(this.uiObservability)
13
+ // 把进程单例挂到 globalThis;queue 走 notifyMissingHandlerGlobal 路径调到同一实例,
14
+ // 共享 warnedMissingHandlerSessions 去重集合。
15
+ //
16
+ // 遗留:SubagentService 接线(构造/初始化时调 registerGlobalObservability)需在后续 PR 完成,
17
+ // 本组仅提供桥接入口 + queue 侧调用。未注册时 notifyMissingHandlerGlobal 走 fallback warn(不去重),
18
+ // 保证可观测性不回归。
19
+ const GLOBAL_OBSERVABILITY_KEY = Symbol.for("pi-subagent-workflow.ui-observability");
20
+
21
+ /** 注册进程级 observability 单例(SubagentService 构造后调用一次)。 */
22
+ export function registerGlobalObservability(obs: UiRequestObservability): void {
23
+ (globalThis as Record<symbol, unknown>)[GLOBAL_OBSERVABILITY_KEY] = obs;
24
+ }
25
+
26
+ /** 触发 handler 缺失告警(经全局单例,per-session 去重)。
27
+ * 未注册全局单例时走 fallback warn(不去重),保证可观测性不丢。 */
28
+ export function notifyMissingHandlerGlobal(sessionId: string): void {
29
+ const obs = (globalThis as Record<symbol, unknown>)[GLOBAL_OBSERVABILITY_KEY] as
30
+ | UiRequestObservability
31
+ | undefined;
32
+ if (obs) {
33
+ obs.notifyMissingHandler(sessionId);
34
+ } else {
35
+ console.warn(
36
+ `[subagents] uiRequestHandler missing (session=${sessionId}, global observability not registered)`,
37
+ );
38
+ }
39
+ }
40
+
41
+ /** warnedMissingHandlerSessions 容量上限(#14 防 Set 无界增长)。
42
+ * 长生命周期进程(GUI 主进程长开)下,不同子进程会话 id 不断积累;
43
+ * 超过阈值时清空集合(简单策略,LRU 留作后续优化)。 */
44
+ const MAX_WARNED_SESSIONS = 1024;
45
+
46
+ /** UI 请求可观测性状态。
47
+ * 持有 sessionMode(主进程运行模式,W4 守卫透传)+ handler 缺失告警去重集合。
48
+ * 外部通过 setMode/resetMissingHandlerWarnings/notifyMissingHandler 驱动。 */
49
+ export class UiRequestObservability {
50
+ private sessionMode: ExtensionMode | undefined;
51
+ private warnedMissingHandlerSessions = new Set<string>();
52
+
53
+ setMode(mode: ExtensionMode | undefined): void {
54
+ this.sessionMode = mode;
55
+ }
56
+
57
+ getMode(): ExtensionMode | undefined {
58
+ return this.sessionMode;
59
+ }
60
+
61
+ /** handler 变化时重置告警去重(新 handler 就位后允许重新 warn)。 */
62
+ resetMissingHandlerWarnings(): void {
63
+ this.warnedMissingHandlerSessions.clear();
64
+ }
65
+
66
+ /** 记录 handler 缺失(per-session 去重,每 session 只 warn 一次)。
67
+ * #14:Set 加 cap——超 MAX_WARNED_SESSIONS 时先清空再 add,防无界增长。
68
+ * 清空策略:当前会话首条告警丢失可接受(去重本身只是降噪,非数据完整性约束)。 */
69
+ notifyMissingHandler(sessionId: string): void {
70
+ if (this.warnedMissingHandlerSessions.has(sessionId)) return;
71
+ if (this.warnedMissingHandlerSessions.size >= MAX_WARNED_SESSIONS) {
72
+ this.warnedMissingHandlerSessions.clear();
73
+ }
74
+ this.warnedMissingHandlerSessions.add(sessionId);
75
+ console.warn(`[subagents] uiRequestHandler missing (session=${sessionId}, mode=${this.sessionMode})`);
76
+ }
77
+ }