@mozhi0012/pi-terminal-worker 0.3.0 → 0.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.
- package/README.md +238 -212
- package/dist/controller.d.ts +6 -0
- package/dist/controller.d.ts.map +1 -1
- package/dist/controller.js +118 -56
- package/dist/controller.js.map +1 -1
- package/dist/json-schema.d.ts +28 -0
- package/dist/json-schema.d.ts.map +1 -0
- package/dist/json-schema.js +54 -0
- package/dist/json-schema.js.map +1 -0
- package/dist/launcher.d.ts +9 -1
- package/dist/launcher.d.ts.map +1 -1
- package/dist/launcher.js +95 -22
- package/dist/launcher.js.map +1 -1
- package/dist/lifecycle.d.ts +7 -0
- package/dist/lifecycle.d.ts.map +1 -1
- package/dist/lifecycle.js +4 -0
- package/dist/lifecycle.js.map +1 -1
- package/dist/mcp-server.d.ts +40 -0
- package/dist/mcp-server.d.ts.map +1 -0
- package/dist/mcp-server.js +364 -0
- package/dist/mcp-server.js.map +1 -0
- package/dist/multi-worker.d.ts.map +1 -1
- package/dist/multi-worker.js +1 -1
- package/dist/multi-worker.js.map +1 -1
- package/dist/schema-validate.d.ts +17 -0
- package/dist/schema-validate.d.ts.map +1 -0
- package/dist/schema-validate.js +100 -0
- package/dist/schema-validate.js.map +1 -0
- package/dist/terminal-multiplexer.d.ts +25 -0
- package/dist/terminal-multiplexer.d.ts.map +1 -0
- package/dist/terminal-multiplexer.js +102 -0
- package/dist/terminal-multiplexer.js.map +1 -0
- package/package.json +81 -75
- package/runtime/bootstrap-support.mjs +68 -67
- package/runtime/bootstrap.mjs +328 -312
- package/runtime/terminal-support.mjs +63 -0
- package/src/controller.ts +101 -58
- package/src/json-schema.ts +61 -0
- package/src/launcher.ts +592 -517
- package/src/lifecycle.ts +289 -284
- package/src/mcp-server.ts +409 -0
- package/src/multi-worker.ts +1 -1
- package/src/schema-validate.ts +100 -0
- package/src/terminal-multiplexer.ts +108 -0
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* pi-terminal-worker 的 MCP stdio 入口:让 Claude Code 等 MCP 客户端担任主控(L0),
|
|
4
|
+
* 派发并监督交互式 Worker Pi。Worker / lead 侧仍是加载本扩展的完整 pi,管道协议不变。
|
|
5
|
+
*
|
|
6
|
+
* 实现要点:
|
|
7
|
+
* - 零运行时依赖:手写换行分隔的 JSON-RPC 2.0,stdout 只写协议帧,诊断信息走 stderr;
|
|
8
|
+
* - 复用 MultiWorkerCoordinator:用一个最小 pi 适配对象收集它注册的 7 个工具,
|
|
9
|
+
* tools/call 先按 schema 校验参数,再调用原工具的 execute;
|
|
10
|
+
* - 默认没有主动唤醒,客户端用 worker_wait 阻塞等待;
|
|
11
|
+
* PI_TERMINAL_WORKER_MCP_CHANNEL=1 时把关键事件转发为 Claude Code channel 通知(研究预览功能)。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import * as fs from "node:fs";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
import type { Readable, Writable } from "node:stream";
|
|
17
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
18
|
+
import type { ControllerManager } from "./controller.js";
|
|
19
|
+
import { MultiWorkerCoordinator, type MultiWorkerCoordinatorOptions } from "./multi-worker.js";
|
|
20
|
+
import { validateToolArguments } from "./schema-validate.js";
|
|
21
|
+
import type { JsonSchema } from "./json-schema.js";
|
|
22
|
+
|
|
23
|
+
export const MCP_SERVER_NAME = "pi-terminal-worker";
|
|
24
|
+
export const MCP_SERVER_VERSION = readPackageVersion();
|
|
25
|
+
|
|
26
|
+
function readPackageVersion(): string {
|
|
27
|
+
try {
|
|
28
|
+
const pkgPath = fileURLToPath(new URL("../package.json", import.meta.url));
|
|
29
|
+
const version = JSON.parse(fs.readFileSync(pkgPath, "utf8")).version;
|
|
30
|
+
return typeof version === "string" ? version : "0.0.0";
|
|
31
|
+
} catch {
|
|
32
|
+
return "0.0.0";
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export const SUPPORTED_PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"] as const;
|
|
36
|
+
export const CHANNEL_ENV = "PI_TERMINAL_WORKER_MCP_CHANNEL";
|
|
37
|
+
export const CHANNEL_NOTIFICATION_METHOD = "notifications/claude/channel";
|
|
38
|
+
|
|
39
|
+
const WAIT_HINT =
|
|
40
|
+
"Claude Code 不会被 Worker 事件自动唤醒:请调用 worker_wait 阻塞等待回执(单次最长 600000ms)," +
|
|
41
|
+
"返回 wait_timeout 且 Worker 仍在运行时可再次调用。";
|
|
42
|
+
|
|
43
|
+
const CHANNEL_HINT =
|
|
44
|
+
"关键事件会以 <channel source=\"pi-terminal-worker\"> 消息推送到本会话;推送不可用时用 worker_wait 阻塞等待。";
|
|
45
|
+
|
|
46
|
+
/** MCP 侧的工具描述:去掉 pi 专属的"自动唤醒"说法 */
|
|
47
|
+
function mcpDescriptions(channel: boolean): Record<string, string> {
|
|
48
|
+
const wake = channel ? CHANNEL_HINT : WAIT_HINT;
|
|
49
|
+
return {
|
|
50
|
+
worker_start:
|
|
51
|
+
"在独立终端(Windows Terminal/PowerShell/CMD、herdr pane 或 tmux)中启动一个交互式 Worker Pi,派发初始任务并建立监督通信。" +
|
|
52
|
+
"返回 workerId/taskId,后续操作都按 workerId 定位。" + wake,
|
|
53
|
+
worker_send:
|
|
54
|
+
"向存活的 Worker 发送补充说明 (supplement)、回复提问 (reply) 或发起返修 (revision,要求 ready_for_review 状态)。" + wake,
|
|
55
|
+
worker_wait:
|
|
56
|
+
"阻塞等待指定 Worker 的关键事件(交付/提问/阻塞/停止/断连/退出等)。默认从上次已消费游标之后匹配,不重复返回同一事件;" +
|
|
57
|
+
"显式传 afterCursor 可重放。timeoutMs 默认 300000,最小 1000,最大 600000。",
|
|
58
|
+
worker_status: "查询 Worker 状态、模型、生命周期及回执详情;传 eventId 可分页读取长事件内容。",
|
|
59
|
+
worker_list: "无参数列出当前活跃或未确认退出的 Worker 有界摘要;明细请按 workerId 用 worker_status。",
|
|
60
|
+
worker_stop: "请求 Worker 合作式中止当前任务,不关闭窗口。",
|
|
61
|
+
worker_close: "完成任务验收 (accepted) 或放弃任务 (abandoned),关闭指定 Worker 并释放名额。不允许 force。",
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface RegisteredTool {
|
|
66
|
+
name: string;
|
|
67
|
+
description: string;
|
|
68
|
+
parameters: JsonSchema;
|
|
69
|
+
execute: (toolCallId: string, params: any, signal?: AbortSignal) => Promise<{ content: unknown; details?: unknown }>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface JsonRpcMessage {
|
|
73
|
+
jsonrpc?: unknown;
|
|
74
|
+
id?: unknown;
|
|
75
|
+
method?: unknown;
|
|
76
|
+
params?: unknown;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface McpWorkerServerOptions {
|
|
80
|
+
input: Readable;
|
|
81
|
+
output: Writable;
|
|
82
|
+
/** 是否声明 claude/channel 能力并推送关键事件;默认读取 PI_TERMINAL_WORKER_MCP_CHANNEL */
|
|
83
|
+
channel?: boolean;
|
|
84
|
+
/** 测试注入:用内部 pi 适配对象构造 ControllerManager */
|
|
85
|
+
controllerFactory?: (pi: ExtensionAPI) => ControllerManager;
|
|
86
|
+
coordinatorOptions?: Omit<MultiWorkerCoordinatorOptions, "controllerFactory">;
|
|
87
|
+
/** 诊断输出,默认 stderr */
|
|
88
|
+
log?: (message: string) => void;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface McpWorkerServer {
|
|
92
|
+
coordinator: MultiWorkerCoordinator;
|
|
93
|
+
/** 输入结束(客户端退出)时 resolve */
|
|
94
|
+
closed: Promise<void>;
|
|
95
|
+
dispose(): Promise<void>;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
99
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function errorMessage(err: unknown): string {
|
|
103
|
+
return err instanceof Error ? err.message : String(err);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** channel meta 键只允许字母、数字和下划线,值必须是字符串 */
|
|
107
|
+
function channelMeta(details: unknown): Record<string, string> {
|
|
108
|
+
const meta: Record<string, string> = {};
|
|
109
|
+
if (!isRecord(details)) return meta;
|
|
110
|
+
for (const key of ["workerId", "taskId", "type", "eventId", "revision"]) {
|
|
111
|
+
const value = details[key];
|
|
112
|
+
if (value === undefined || value === null) continue;
|
|
113
|
+
meta[key.replace(/[^A-Za-z0-9_]/g, "_")] = String(value);
|
|
114
|
+
}
|
|
115
|
+
return meta;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export async function createMcpWorkerServer(options: McpWorkerServerOptions): Promise<McpWorkerServer> {
|
|
119
|
+
const { input, output } = options;
|
|
120
|
+
const channel = options.channel ?? process.env[CHANNEL_ENV] === "1";
|
|
121
|
+
const log = options.log ?? ((message: string) => console.error(`[pi-terminal-worker:mcp] ${message}`));
|
|
122
|
+
const tools = new Map<string, RegisteredTool>();
|
|
123
|
+
let outputBroken = false;
|
|
124
|
+
let initialized = false;
|
|
125
|
+
|
|
126
|
+
const writeFrame = (frame: unknown): void => {
|
|
127
|
+
if (outputBroken) return;
|
|
128
|
+
try {
|
|
129
|
+
output.write(JSON.stringify(frame) + "\n");
|
|
130
|
+
} catch (err) {
|
|
131
|
+
outputBroken = true;
|
|
132
|
+
log(`写出失败,停止输出: ${errorMessage(err)}`);
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
output.on("error", (err) => {
|
|
136
|
+
outputBroken = true;
|
|
137
|
+
log(`输出流错误: ${errorMessage(err)}`);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
// 最小 pi 适配对象:只实现协调器/控制器实际使用的方法
|
|
141
|
+
const piAdapter = {
|
|
142
|
+
registerTool(tool: RegisteredTool) {
|
|
143
|
+
tools.set(tool.name, tool);
|
|
144
|
+
},
|
|
145
|
+
registerCommand() {
|
|
146
|
+
// MCP 没有斜杠命令
|
|
147
|
+
},
|
|
148
|
+
on() {
|
|
149
|
+
return () => {};
|
|
150
|
+
},
|
|
151
|
+
sendMessage(message: { content?: Array<{ type: string; text?: string }>; details?: unknown }) {
|
|
152
|
+
if (!channel || !initialized) return;
|
|
153
|
+
try {
|
|
154
|
+
const text = (message.content ?? [])
|
|
155
|
+
.map((part) => (part.type === "text" ? part.text ?? "" : ""))
|
|
156
|
+
.join("\n")
|
|
157
|
+
.replace("无需立即处理时可结束当前轮,后续关键事件会自动唤醒,不必循环调用 worker_wait。", "推送不可靠时用 worker_wait 兜底。");
|
|
158
|
+
writeFrame({
|
|
159
|
+
jsonrpc: "2.0",
|
|
160
|
+
method: CHANNEL_NOTIFICATION_METHOD,
|
|
161
|
+
params: { content: text, meta: channelMeta(message.details) },
|
|
162
|
+
});
|
|
163
|
+
} catch (err) {
|
|
164
|
+
log(`channel 通知发送失败(已忽略,worker_wait 仍可用): ${errorMessage(err)}`);
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
} as unknown as ExtensionAPI;
|
|
168
|
+
|
|
169
|
+
const factory = options.controllerFactory;
|
|
170
|
+
const coordinator = new MultiWorkerCoordinator(piAdapter, {
|
|
171
|
+
strictProtocol: true,
|
|
172
|
+
...options.coordinatorOptions,
|
|
173
|
+
...(factory ? { controllerFactory: () => factory(piAdapter) } : {}),
|
|
174
|
+
});
|
|
175
|
+
coordinator.registerToolsAndCommands();
|
|
176
|
+
await coordinator.handleSessionStart();
|
|
177
|
+
|
|
178
|
+
const descriptions = mcpDescriptions(channel);
|
|
179
|
+
const inFlight = new Map<string, AbortController>();
|
|
180
|
+
/** 已消费默认游标但因客户端取消而未送达的 worker_wait 结果,按 workerId 暂存 */
|
|
181
|
+
const undeliveredWaits = new Map<string, unknown>();
|
|
182
|
+
let toolCallSeq = 0;
|
|
183
|
+
|
|
184
|
+
const listTools = () => ({
|
|
185
|
+
tools: [...tools.values()].map((tool) => ({
|
|
186
|
+
name: tool.name,
|
|
187
|
+
description: descriptions[tool.name] ?? tool.description,
|
|
188
|
+
inputSchema: tool.parameters,
|
|
189
|
+
})),
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
const callTool = async (params: unknown, signal: AbortSignal) => {
|
|
193
|
+
if (!isRecord(params) || typeof params.name !== "string") {
|
|
194
|
+
throw Object.assign(new Error("tools/call 缺少 name"), { rpcCode: -32602 });
|
|
195
|
+
}
|
|
196
|
+
const tool = tools.get(params.name);
|
|
197
|
+
if (!tool) {
|
|
198
|
+
return { content: [{ type: "text", text: `未知工具: ${params.name}` }], isError: true };
|
|
199
|
+
}
|
|
200
|
+
const validated = validateToolArguments(tool.parameters, params.arguments);
|
|
201
|
+
if (!validated.ok) {
|
|
202
|
+
return { content: [{ type: "text", text: `参数无效: ${validated.error}` }], isError: true };
|
|
203
|
+
}
|
|
204
|
+
const args = validated.value;
|
|
205
|
+
const workerId = typeof args.workerId === "string" ? args.workerId : undefined;
|
|
206
|
+
// 上一次默认游标的 worker_wait 已消费事件却因取消没能回包:本次默认等待先补发它
|
|
207
|
+
if (tool.name === "worker_wait" && workerId && args.afterCursor === undefined && undeliveredWaits.has(workerId)) {
|
|
208
|
+
const pending = undeliveredWaits.get(workerId);
|
|
209
|
+
undeliveredWaits.delete(workerId);
|
|
210
|
+
return { content: [{ type: "text", text: JSON.stringify(pending, null, 2) }] };
|
|
211
|
+
}
|
|
212
|
+
try {
|
|
213
|
+
const res = await tool.execute(`mcp-${++toolCallSeq}`, args, signal);
|
|
214
|
+
let details = res.details;
|
|
215
|
+
if (tool.name === "worker_wait" && signal.aborted && workerId && args.afterCursor === undefined) {
|
|
216
|
+
const event = isRecord(details) && isRecord(details.event) ? details.event : undefined;
|
|
217
|
+
if (event && event.type !== "wait_timeout") undeliveredWaits.set(workerId, details);
|
|
218
|
+
}
|
|
219
|
+
if (tool.name === "worker_close" && workerId && isRecord(details) && details.ok) undeliveredWaits.delete(workerId);
|
|
220
|
+
if (!channel && (tool.name === "worker_start" || tool.name === "worker_send") && isRecord(details) && details.ok) {
|
|
221
|
+
details = { ...details, message: `${tool.name === "worker_start" ? "Worker 已启动并接收初始任务。" : "消息已送达 Worker。"}${WAIT_HINT}` };
|
|
222
|
+
}
|
|
223
|
+
return {
|
|
224
|
+
content: [{ type: "text", text: JSON.stringify(details ?? null, null, 2) }],
|
|
225
|
+
isError: isRecord(details) && details.ok === false ? true : undefined,
|
|
226
|
+
};
|
|
227
|
+
} catch (err) {
|
|
228
|
+
return { content: [{ type: "text", text: errorMessage(err) }], isError: true };
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
const respond = (id: unknown, result: unknown) => writeFrame({ jsonrpc: "2.0", id, result });
|
|
233
|
+
const respondError = (id: unknown, code: number, message: string) =>
|
|
234
|
+
writeFrame({ jsonrpc: "2.0", id, error: { code, message } });
|
|
235
|
+
|
|
236
|
+
const handleRequest = async (id: string | number, method: string, params: unknown): Promise<void> => {
|
|
237
|
+
const key = JSON.stringify(id);
|
|
238
|
+
const controller = new AbortController();
|
|
239
|
+
inFlight.set(key, controller);
|
|
240
|
+
try {
|
|
241
|
+
let result: unknown;
|
|
242
|
+
switch (method) {
|
|
243
|
+
case "initialize": {
|
|
244
|
+
const requested = isRecord(params) ? params.protocolVersion : undefined;
|
|
245
|
+
const protocolVersion =
|
|
246
|
+
typeof requested === "string" && (SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(requested)
|
|
247
|
+
? requested
|
|
248
|
+
: SUPPORTED_PROTOCOL_VERSIONS[0];
|
|
249
|
+
result = {
|
|
250
|
+
protocolVersion,
|
|
251
|
+
capabilities: channel ? { tools: {}, experimental: { "claude/channel": {} } } : { tools: {} },
|
|
252
|
+
serverInfo: { name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION },
|
|
253
|
+
instructions:
|
|
254
|
+
"pi-terminal-worker:派发并监督独立终端中的 Worker Pi。worker_start 后" +
|
|
255
|
+
(channel ? CHANNEL_HINT : WAIT_HINT) +
|
|
256
|
+
"收到 ready_for_review 后核对交付,再用 worker_send(kind=\"revision\") 返修或 worker_close 验收。",
|
|
257
|
+
};
|
|
258
|
+
break;
|
|
259
|
+
}
|
|
260
|
+
case "ping":
|
|
261
|
+
result = {};
|
|
262
|
+
break;
|
|
263
|
+
case "tools/list":
|
|
264
|
+
result = listTools();
|
|
265
|
+
break;
|
|
266
|
+
case "tools/call":
|
|
267
|
+
result = await callTool(params, controller.signal);
|
|
268
|
+
break;
|
|
269
|
+
default:
|
|
270
|
+
if (!controller.signal.aborted) respondError(id, -32601, `Method not found: ${method}`);
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
if (!controller.signal.aborted) respond(id, result);
|
|
274
|
+
} catch (err) {
|
|
275
|
+
if (!controller.signal.aborted) {
|
|
276
|
+
const code = isRecord(err) && typeof err.rpcCode === "number" ? err.rpcCode : -32603;
|
|
277
|
+
respondError(id, code, errorMessage(err));
|
|
278
|
+
}
|
|
279
|
+
} finally {
|
|
280
|
+
if (inFlight.get(key) === controller) inFlight.delete(key);
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
const handleNotification = (method: string, params: unknown): void => {
|
|
285
|
+
if (method === "notifications/initialized") {
|
|
286
|
+
initialized = true;
|
|
287
|
+
} else if (method === "notifications/cancelled" && isRecord(params) && params.requestId !== undefined) {
|
|
288
|
+
inFlight.get(JSON.stringify(params.requestId))?.abort();
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
const handleLine = (line: string): void => {
|
|
293
|
+
const trimmed = line.trim();
|
|
294
|
+
if (!trimmed) return;
|
|
295
|
+
let msg: JsonRpcMessage;
|
|
296
|
+
try {
|
|
297
|
+
msg = JSON.parse(trimmed);
|
|
298
|
+
} catch {
|
|
299
|
+
respondError(null, -32700, "Parse error");
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (!isRecord(msg)) {
|
|
303
|
+
respondError(null, -32600, "Invalid Request");
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
const hasId = "id" in msg && msg.id !== undefined && msg.id !== null;
|
|
307
|
+
const validId = hasId && (typeof msg.id === "string" || typeof msg.id === "number");
|
|
308
|
+
if (msg.jsonrpc !== "2.0") {
|
|
309
|
+
// 只接受 JSON-RPC 2.0:版本不符的请求一律不执行,通知直接丢弃
|
|
310
|
+
if (hasId) respondError(validId ? msg.id : null, -32600, "Invalid Request: jsonrpc 必须为 \"2.0\"");
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
if (typeof msg.method !== "string") {
|
|
314
|
+
// 客户端发来的响应(本服务不发请求)直接忽略
|
|
315
|
+
if (!hasId || !("result" in msg || "error" in msg)) respondError(hasId ? msg.id : null, -32600, "Invalid Request");
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
if (!hasId) {
|
|
319
|
+
handleNotification(msg.method, msg.params);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
if (!validId) {
|
|
323
|
+
respondError(null, -32600, "Invalid Request: id 必须是 string 或 number");
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
// 异步派发:长时间的 worker_wait 不阻塞后续 ping / cancelled / 并发调用
|
|
327
|
+
void handleRequest(msg.id as string | number, msg.method, msg.params);
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
let buffer = "";
|
|
331
|
+
let resolveClosed!: () => void;
|
|
332
|
+
const closed = new Promise<void>((resolve) => {
|
|
333
|
+
resolveClosed = resolve;
|
|
334
|
+
});
|
|
335
|
+
input.setEncoding?.("utf8");
|
|
336
|
+
input.on("data", (chunk: string | Buffer) => {
|
|
337
|
+
buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
338
|
+
let idx: number;
|
|
339
|
+
while ((idx = buffer.indexOf("\n")) >= 0) {
|
|
340
|
+
const line = buffer.slice(0, idx).replace(/\r$/, "");
|
|
341
|
+
buffer = buffer.slice(idx + 1);
|
|
342
|
+
handleLine(line);
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
const onEnd = () => {
|
|
346
|
+
if (buffer.trim()) handleLine(buffer);
|
|
347
|
+
buffer = "";
|
|
348
|
+
resolveClosed();
|
|
349
|
+
};
|
|
350
|
+
input.on("end", onEnd);
|
|
351
|
+
input.on("close", onEnd);
|
|
352
|
+
input.on("error", (err) => {
|
|
353
|
+
log(`输入流错误: ${errorMessage(err)}`);
|
|
354
|
+
onEnd();
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
let disposing: Promise<void> | null = null;
|
|
358
|
+
const dispose = (): Promise<void> => {
|
|
359
|
+
if (!disposing) {
|
|
360
|
+
for (const controller of inFlight.values()) controller.abort();
|
|
361
|
+
disposing = coordinator.dispose();
|
|
362
|
+
}
|
|
363
|
+
return disposing;
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
return { coordinator, closed, dispose };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** 判断当前模块是否为进程入口(两侧都 realpath,Windows 忽略大小写) */
|
|
370
|
+
function isMainModule(): boolean {
|
|
371
|
+
const entry = process.argv[1];
|
|
372
|
+
if (!entry) return false;
|
|
373
|
+
try {
|
|
374
|
+
const self = fs.realpathSync(fileURLToPath(import.meta.url));
|
|
375
|
+
const main = fs.realpathSync(entry);
|
|
376
|
+
return process.platform === "win32" ? self.toLowerCase() === main.toLowerCase() : self === main;
|
|
377
|
+
} catch {
|
|
378
|
+
return false;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const DISPOSE_TIMEOUT_MS = 10_000;
|
|
383
|
+
|
|
384
|
+
async function main(): Promise<void> {
|
|
385
|
+
const server = await createMcpWorkerServer({ input: process.stdin, output: process.stdout });
|
|
386
|
+
let exiting = false;
|
|
387
|
+
const shutdown = async (code: number) => {
|
|
388
|
+
if (exiting) return;
|
|
389
|
+
exiting = true;
|
|
390
|
+
const timer = setTimeout(() => process.exit(code), DISPOSE_TIMEOUT_MS);
|
|
391
|
+
timer.unref();
|
|
392
|
+
try {
|
|
393
|
+
await server.dispose();
|
|
394
|
+
} catch (err) {
|
|
395
|
+
console.error(`[pi-terminal-worker:mcp] 清理失败: ${errorMessage(err)}`);
|
|
396
|
+
}
|
|
397
|
+
process.exit(code);
|
|
398
|
+
};
|
|
399
|
+
server.closed.then(() => shutdown(0));
|
|
400
|
+
process.on("SIGINT", () => void shutdown(0));
|
|
401
|
+
process.on("SIGTERM", () => void shutdown(0));
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
if (isMainModule()) {
|
|
405
|
+
main().catch((err) => {
|
|
406
|
+
console.error(`[pi-terminal-worker:mcp] 启动失败: ${errorMessage(err)}`);
|
|
407
|
+
process.exit(1);
|
|
408
|
+
});
|
|
409
|
+
}
|
package/src/multi-worker.ts
CHANGED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 针对本包工具 schema 子集的参数校验器(object/required/properties/string/number/boolean/array.items/anyOf+const)。
|
|
3
|
+
*
|
|
4
|
+
* pi 在调用 execute 之前会按 schema 校验参数;MCP 客户端不保证这一点,所以 MCP 入口在分发前自行校验。
|
|
5
|
+
* 未声明的字段与 pi 一致不报错,但会被剥离,不传给协调器。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { JsonSchema } from "./json-schema.js";
|
|
9
|
+
|
|
10
|
+
export type ValidationResult =
|
|
11
|
+
| { ok: true; value: Record<string, unknown> }
|
|
12
|
+
| { ok: false; error: string };
|
|
13
|
+
|
|
14
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
15
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
16
|
+
const proto = Object.getPrototypeOf(value);
|
|
17
|
+
return proto === Object.prototype || proto === null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function typeName(value: unknown): string {
|
|
21
|
+
if (value === null) return "null";
|
|
22
|
+
if (Array.isArray(value)) return "array";
|
|
23
|
+
return typeof value;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function check(schema: JsonSchema, value: unknown, path: string): { ok: true; value: unknown } | { ok: false; error: string } {
|
|
27
|
+
if (Array.isArray(schema.anyOf)) {
|
|
28
|
+
for (const option of schema.anyOf as JsonSchema[]) {
|
|
29
|
+
const res = check(option, value, path);
|
|
30
|
+
if (res.ok) return res;
|
|
31
|
+
}
|
|
32
|
+
const allowed = (schema.anyOf as JsonSchema[])
|
|
33
|
+
.map((option) => ("const" in option ? JSON.stringify(option.const) : String(option.type)))
|
|
34
|
+
.join(" | ");
|
|
35
|
+
return { ok: false, error: `${path} 取值无效:${JSON.stringify(value)},允许 ${allowed}` };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
switch (schema.type) {
|
|
39
|
+
case "string":
|
|
40
|
+
if (typeof value !== "string") return { ok: false, error: `${path} 应为 string,实际为 ${typeName(value)}` };
|
|
41
|
+
break;
|
|
42
|
+
case "number":
|
|
43
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
44
|
+
return { ok: false, error: `${path} 应为有限 number,实际为 ${typeName(value)}` };
|
|
45
|
+
}
|
|
46
|
+
break;
|
|
47
|
+
case "boolean":
|
|
48
|
+
if (typeof value !== "boolean") return { ok: false, error: `${path} 应为 boolean,实际为 ${typeName(value)}` };
|
|
49
|
+
break;
|
|
50
|
+
case "array": {
|
|
51
|
+
if (!Array.isArray(value)) return { ok: false, error: `${path} 应为 array,实际为 ${typeName(value)}` };
|
|
52
|
+
const items = schema.items as JsonSchema | undefined;
|
|
53
|
+
const out: unknown[] = [];
|
|
54
|
+
for (let i = 0; i < value.length; i++) {
|
|
55
|
+
if (!items) {
|
|
56
|
+
out.push(value[i]);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
const res = check(items, value[i], `${path}[${i}]`);
|
|
60
|
+
if (!res.ok) return res;
|
|
61
|
+
out.push(res.value);
|
|
62
|
+
}
|
|
63
|
+
return { ok: true, value: out };
|
|
64
|
+
}
|
|
65
|
+
case "object":
|
|
66
|
+
return checkObject(schema, value, path);
|
|
67
|
+
default:
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if ("const" in schema && value !== schema.const) {
|
|
72
|
+
return { ok: false, error: `${path} 应为 ${JSON.stringify(schema.const)},实际为 ${JSON.stringify(value)}` };
|
|
73
|
+
}
|
|
74
|
+
return { ok: true, value };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function checkObject(schema: JsonSchema, value: unknown, path: string): { ok: true; value: Record<string, unknown> } | { ok: false; error: string } {
|
|
78
|
+
if (!isPlainObject(value)) return { ok: false, error: `${path} 应为 object,实际为 ${typeName(value)}` };
|
|
79
|
+
const properties = (schema.properties ?? {}) as Record<string, JsonSchema>;
|
|
80
|
+
const required = (schema.required ?? []) as string[];
|
|
81
|
+
for (const key of required) {
|
|
82
|
+
if (value[key] === undefined) return { ok: false, error: `缺少必填参数 ${path === "参数" ? key : `${path}.${key}`}` };
|
|
83
|
+
}
|
|
84
|
+
const out: Record<string, unknown> = {};
|
|
85
|
+
for (const [key, propSchema] of Object.entries(properties)) {
|
|
86
|
+
const v = value[key];
|
|
87
|
+
// 与 pi 一致:可选字段为 null 时视为未提供
|
|
88
|
+
if (v === undefined || (v === null && !required.includes(key))) continue;
|
|
89
|
+
const res = check(propSchema, v, path === "参数" ? key : `${path}.${key}`);
|
|
90
|
+
if (!res.ok) return res;
|
|
91
|
+
out[key] = res.value;
|
|
92
|
+
}
|
|
93
|
+
return { ok: true, value: out };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 校验工具参数;undefined 视为空对象(MCP tools/call 的 arguments 可省略) */
|
|
97
|
+
export function validateToolArguments(schema: JsonSchema, args: unknown): ValidationResult {
|
|
98
|
+
const res = checkObject(schema, args === undefined ? {} : args, "参数");
|
|
99
|
+
return res.ok ? { ok: true, value: res.value } : res;
|
|
100
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/** Multi-step CLI launchers. The Windows launchWorkerWindow API remains synchronous. */
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { assertCmdSafeValues, type TerminalLaunchSpec } from "./launcher.js";
|
|
4
|
+
|
|
5
|
+
export class TerminalSpawnError extends Error {
|
|
6
|
+
constructor(public readonly backend: string, public readonly cause: Error) {
|
|
7
|
+
super(`终端后端 ${backend} 启动失败: ${cause.message}`);
|
|
8
|
+
this.name = "TerminalSpawnError";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type TerminalCommandRunner = (
|
|
13
|
+
command: string, args: string[], options: { cwd: string; env: NodeJS.ProcessEnv },
|
|
14
|
+
) => Promise<string>;
|
|
15
|
+
|
|
16
|
+
export const runTerminalCommand: TerminalCommandRunner = (command, args, options) => new Promise((resolve, reject) => {
|
|
17
|
+
execFile(command, args, { ...options, shell: false, windowsHide: true, encoding: "utf8", timeout: 10_000, maxBuffer: 1024 * 1024 },
|
|
18
|
+
(error, stdout, stderr) => error ? reject(new Error(`${error.message}${stderr ? `: ${stderr.trim()}` : ""}`)) : resolve(stdout));
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
export interface TerminalHandle {
|
|
22
|
+
backend: "herdr" | "tmux";
|
|
23
|
+
paneId?: string;
|
|
24
|
+
windowId?: string;
|
|
25
|
+
sessionName?: string;
|
|
26
|
+
close: () => Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Only controlled variable references are sent to the interactive shell. */
|
|
30
|
+
export function buildHerdrRunCommand(shellName: string, values: Record<string, string>): string {
|
|
31
|
+
const shell = shellName.replace(/\\/g, "/").split("/").pop()!.replace(/^-/, "").toLowerCase().replace(/\.exe$/, "");
|
|
32
|
+
if (shell === "powershell" || shell === "pwsh") {
|
|
33
|
+
return "& $env:PITW_BOOTSTRAP_NODE $env:PITW_BOOTSTRAP_FILE --descriptor $env:PITW_BOOTSTRAP_DESC";
|
|
34
|
+
}
|
|
35
|
+
if (shell === "cmd") {
|
|
36
|
+
assertCmdSafeValues(Object.entries(values));
|
|
37
|
+
return '"%PITW_BOOTSTRAP_NODE%" "%PITW_BOOTSTRAP_FILE%" --descriptor %PITW_BOOTSTRAP_DESC%';
|
|
38
|
+
}
|
|
39
|
+
if (["bash", "zsh", "sh", "dash", "ksh", "fish"].includes(shell)) {
|
|
40
|
+
return '"$PITW_BOOTSTRAP_NODE" "$PITW_BOOTSTRAP_FILE" --descriptor "$PITW_BOOTSTRAP_DESC"';
|
|
41
|
+
}
|
|
42
|
+
throw new Error(`不支持的 herdr pane shell: ${shellName}`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function launchMultiplexer(
|
|
46
|
+
spec: TerminalLaunchSpec,
|
|
47
|
+
{ run = runTerminalCommand, assertActive = () => {} }: {
|
|
48
|
+
run?: TerminalCommandRunner;
|
|
49
|
+
assertActive?: () => void;
|
|
50
|
+
} = {},
|
|
51
|
+
): Promise<TerminalHandle> {
|
|
52
|
+
const options = { cwd: spec.cwd, env: { ...process.env } };
|
|
53
|
+
let handle: TerminalHandle | undefined;
|
|
54
|
+
function makeHandle(data: Omit<TerminalHandle, "close">, closeArgs: string[]): TerminalHandle {
|
|
55
|
+
let closing: Promise<void> | undefined;
|
|
56
|
+
return { ...data, close: () => closing ??= run(spec.command, closeArgs, options).then(() => {}, () => {}) };
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
assertActive();
|
|
60
|
+
if (spec.backend === "tmux") {
|
|
61
|
+
const output = await run(spec.command, spec.args, options);
|
|
62
|
+
const windowId = output.trim();
|
|
63
|
+
// A new session's name is already known, including if output parsing fails.
|
|
64
|
+
if (spec.tmuxSession) handle = makeHandle({ backend: "tmux", sessionName: spec.tmuxSession, windowId }, ["kill-session", "-t", spec.tmuxSession]);
|
|
65
|
+
else if (/^@\d+$/.test(windowId)) handle = makeHandle({ backend: "tmux", windowId }, ["kill-window", "-t", windowId]);
|
|
66
|
+
assertActive();
|
|
67
|
+
if (!/^@\d+$/.test(windowId)) throw new Error(`tmux 未返回窗口 ID: ${output}`);
|
|
68
|
+
return handle!;
|
|
69
|
+
}
|
|
70
|
+
if (spec.backend !== "herdr" || !spec.workerCommand) throw new Error("缺少 herdr 启动描述");
|
|
71
|
+
const values = {
|
|
72
|
+
PITW_BOOTSTRAP_NODE: spec.workerCommand[0],
|
|
73
|
+
PITW_BOOTSTRAP_FILE: spec.workerCommand[1],
|
|
74
|
+
PITW_BOOTSTRAP_DESC: spec.workerCommand[3],
|
|
75
|
+
PITW_BOOTSTRAP_HERDR: spec.command,
|
|
76
|
+
};
|
|
77
|
+
// Fixed right split preserves focus and avoids a separate layout race/CLI round-trip.
|
|
78
|
+
const split = await run(spec.command, ["pane", "split", "--current", "--direction", "right", "--cwd", spec.cwd,
|
|
79
|
+
"--no-focus", ...Object.entries(values).flatMap(([key, value]) => ["--env", `${key}=${value}`])], options);
|
|
80
|
+
const paneId = JSON.parse(split)?.result?.pane?.pane_id;
|
|
81
|
+
if (typeof paneId !== "string" || !paneId) throw new Error("herdr split 未返回 pane_id");
|
|
82
|
+
handle = makeHandle({ backend: "herdr", paneId }, ["pane", "close", paneId]);
|
|
83
|
+
assertActive();
|
|
84
|
+
try { await run(spec.command, ["pane", "rename", paneId, spec.title], options); } catch { /* title is cosmetic */ }
|
|
85
|
+
assertActive();
|
|
86
|
+
let shell: string | undefined;
|
|
87
|
+
for (let attempt = 0; attempt < 40; attempt++) {
|
|
88
|
+
const output = await run(spec.command, ["pane", "process-info", "--pane", paneId], options);
|
|
89
|
+
assertActive();
|
|
90
|
+
const info = JSON.parse(output)?.result?.process_info;
|
|
91
|
+
const process = info?.foreground_processes?.find((p: { pid: number }) => p.pid === info.shell_pid);
|
|
92
|
+
shell = process?.argv0 ?? process?.name;
|
|
93
|
+
if (shell) break;
|
|
94
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
95
|
+
assertActive();
|
|
96
|
+
}
|
|
97
|
+
if (!shell) throw new Error("herdr pane shell 尚未就绪");
|
|
98
|
+
const command = buildHerdrRunCommand(shell, values);
|
|
99
|
+
await run(spec.command, ["pane", "run", paneId, command], options);
|
|
100
|
+
assertActive();
|
|
101
|
+
return handle;
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (handle) await handle.close();
|
|
104
|
+
// A cancellation must never turn into a fallback launch in a new session.
|
|
105
|
+
assertActive();
|
|
106
|
+
throw new TerminalSpawnError(spec.backend, error instanceof Error ? error : new Error(String(error)));
|
|
107
|
+
}
|
|
108
|
+
}
|