@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,63 @@
|
|
|
1
|
+
/** Terminal/process cleanup shared by supervisor and focused tests. */
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
|
|
5
|
+
export function closeHerdrPane(env = process.env, run = spawnSync) {
|
|
6
|
+
// Only the bootstrap launched by our herdr backend gets this marker.
|
|
7
|
+
if (!env.PITW_BOOTSTRAP_HERDR || !env.HERDR_PANE_ID) return;
|
|
8
|
+
try {
|
|
9
|
+
run(env.PITW_BOOTSTRAP_HERDR, ["pane", "close", env.HERDR_PANE_ID], {
|
|
10
|
+
env, stdio: "ignore", windowsHide: true, shell: false, timeout: 3000,
|
|
11
|
+
});
|
|
12
|
+
} catch { /* Already closed is success; Controller also has a cleanup handle. */ }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function listProcessParents(platform = process.platform) {
|
|
16
|
+
if (platform === "linux") {
|
|
17
|
+
const result = [];
|
|
18
|
+
for (const entry of fs.readdirSync("/proc")) {
|
|
19
|
+
if (!/^\d+$/.test(entry)) continue;
|
|
20
|
+
try {
|
|
21
|
+
const stat = fs.readFileSync(`/proc/${entry}/stat`, "utf8");
|
|
22
|
+
// comm may contain spaces and parentheses; fields after its final ')' are stable.
|
|
23
|
+
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
24
|
+
result.push({ pid: Number(entry), ppid: Number(fields[1]) });
|
|
25
|
+
} catch { /* Process exited during enumeration. */ }
|
|
26
|
+
}
|
|
27
|
+
return result;
|
|
28
|
+
}
|
|
29
|
+
const result = spawnSync("ps", ["-eo", "pid=,ppid="], { encoding: "utf8", timeout: 3000 });
|
|
30
|
+
if (result.error || result.status !== 0) throw new Error("无法枚举进程树");
|
|
31
|
+
return result.stdout.trim().split("\n").map((line) => {
|
|
32
|
+
const [pid, ppid] = line.trim().split(/\s+/).map(Number);
|
|
33
|
+
return { pid, ppid };
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Freeze parents before rescanning, then kill descendants bottom-up without detaching from the TTY. */
|
|
38
|
+
export function killProcessTree(pid, { list = listProcessParents, signal = process.kill } = {}) {
|
|
39
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return;
|
|
40
|
+
const ordered = [pid];
|
|
41
|
+
const known = new Set(ordered);
|
|
42
|
+
const send = (target, name) => { try { signal(target, name); } catch { /* exited or inaccessible */ } };
|
|
43
|
+
send(pid, "SIGSTOP");
|
|
44
|
+
try {
|
|
45
|
+
// Once a discovered parent is frozen it cannot fork new descendants.
|
|
46
|
+
for (let pass = 0; pass < 64; pass++) {
|
|
47
|
+
const snapshot = list();
|
|
48
|
+
let added = false;
|
|
49
|
+
for (let index = 0; index < ordered.length; index++) {
|
|
50
|
+
for (const process of snapshot) {
|
|
51
|
+
if (process.ppid !== ordered[index] || known.has(process.pid)) continue;
|
|
52
|
+
known.add(process.pid);
|
|
53
|
+
ordered.push(process.pid);
|
|
54
|
+
send(process.pid, "SIGSTOP");
|
|
55
|
+
added = true;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (!added) break;
|
|
59
|
+
}
|
|
60
|
+
} finally {
|
|
61
|
+
for (const target of ordered.reverse()) send(target, "SIGKILL");
|
|
62
|
+
}
|
|
63
|
+
}
|
package/src/controller.ts
CHANGED
|
@@ -10,7 +10,7 @@ import type {
|
|
|
10
10
|
ExtensionContext,
|
|
11
11
|
ExtensionCommandContext,
|
|
12
12
|
} from "@earendil-works/pi-coding-agent";
|
|
13
|
-
import { Type } from "
|
|
13
|
+
import { Type } from "./json-schema.js";
|
|
14
14
|
import {
|
|
15
15
|
PROTOCOL_VERSION,
|
|
16
16
|
MAX_INBOX_EVENTS,
|
|
@@ -226,15 +226,7 @@ import {
|
|
|
226
226
|
} from "./launcher.js";
|
|
227
227
|
import { updateWorkerUiStatus, notifyWorker } from "./ui.js";
|
|
228
228
|
|
|
229
|
-
|
|
230
|
-
public readonly cause: Error;
|
|
231
|
-
|
|
232
|
-
constructor(public readonly backend: string, cause: Error) {
|
|
233
|
-
super(`终端后端 ${backend} 启动失败: ${cause.message}`);
|
|
234
|
-
this.name = "TerminalSpawnError";
|
|
235
|
-
this.cause = cause;
|
|
236
|
-
}
|
|
237
|
-
}
|
|
229
|
+
import { launchMultiplexer, TerminalSpawnError, type TerminalCommandRunner, type TerminalHandle } from "./terminal-multiplexer.js";
|
|
238
230
|
|
|
239
231
|
/**
|
|
240
232
|
* Worker (子代理) 默认模型配置:`worker_start` 未显式指定 provider/model/thinkingLevel 时使用。
|
|
@@ -414,6 +406,19 @@ export class ControllerManager {
|
|
|
414
406
|
|
|
415
407
|
/** 可注入的终端启动器,单元测试不实际开窗 */
|
|
416
408
|
public launchSpawner: ((command: string, args: string[], options: SpawnOptions) => ChildProcess) | null = null;
|
|
409
|
+
public terminalRunner: TerminalCommandRunner | undefined;
|
|
410
|
+
private terminalHandle: TerminalHandle | null = null;
|
|
411
|
+
private terminalClosing: Promise<void> = Promise.resolve();
|
|
412
|
+
private terminalCleanup: (() => void) | null = null;
|
|
413
|
+
|
|
414
|
+
private closeTerminal(): Promise<void> {
|
|
415
|
+
const handle = this.terminalHandle;
|
|
416
|
+
this.terminalHandle = null;
|
|
417
|
+
this.terminalCleanup?.();
|
|
418
|
+
this.terminalCleanup = null;
|
|
419
|
+
if (handle) this.terminalClosing = handle.close();
|
|
420
|
+
return this.terminalClosing;
|
|
421
|
+
}
|
|
417
422
|
|
|
418
423
|
constructor(
|
|
419
424
|
private pi: ExtensionAPI,
|
|
@@ -1108,12 +1113,14 @@ export class ControllerManager {
|
|
|
1108
1113
|
this.childExitConfirmed = true;
|
|
1109
1114
|
this.workerManager.updateLifecycleState("closed");
|
|
1110
1115
|
this.appendInbox("child_exit", p, undefined, undefined, undefined, { notify: !expectedExit });
|
|
1116
|
+
void this.closeTerminal();
|
|
1111
1117
|
this.stopHeartbeat();
|
|
1112
1118
|
} else if (env.type === "launch_failed") {
|
|
1113
1119
|
const p = env.payload as LaunchFailedPayload;
|
|
1114
1120
|
this.childExitConfirmed = true;
|
|
1115
1121
|
this.workerManager.updateLifecycleState("closed");
|
|
1116
1122
|
this.appendInbox("launch_failed", p);
|
|
1123
|
+
void this.closeTerminal();
|
|
1117
1124
|
}
|
|
1118
1125
|
} catch (err) {
|
|
1119
1126
|
this.reportEnvelopeRejected(conn, env, err);
|
|
@@ -1621,39 +1628,39 @@ export class ControllerManager {
|
|
|
1621
1628
|
};
|
|
1622
1629
|
const descB64 = encodeDescriptor(desc);
|
|
1623
1630
|
|
|
1624
|
-
const spec = buildTerminalLaunch(env, params.title, descB64);
|
|
1625
|
-
|
|
1626
1631
|
const terminalBackends = detectTerminalBackends(probes);
|
|
1627
|
-
let
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
launchError = null;
|
|
1649
|
-
break;
|
|
1650
|
-
} catch (fallbackErr: unknown) {
|
|
1651
|
-
lastError = fallbackErr;
|
|
1652
|
-
if (!(fallbackErr instanceof TerminalSpawnError)) throw fallbackErr;
|
|
1632
|
+
for (let index = 0; index < terminalBackends.length; index++) {
|
|
1633
|
+
const backend = terminalBackends[index];
|
|
1634
|
+
this.assertStartActive(startGen);
|
|
1635
|
+
const spec = buildTerminalLaunch({ ...env, terminal: backend }, params.title, descB64);
|
|
1636
|
+
try {
|
|
1637
|
+
let child: ChildProcess | undefined;
|
|
1638
|
+
if (backend.backend === "herdr" || backend.backend === "tmux") {
|
|
1639
|
+
const handle = await launchMultiplexer(spec, {
|
|
1640
|
+
run: this.terminalRunner,
|
|
1641
|
+
assertActive: () => this.assertStartActive(startGen),
|
|
1642
|
+
});
|
|
1643
|
+
try { this.assertStartActive(startGen); } catch (err) { await handle.close(); throw err; }
|
|
1644
|
+
this.terminalHandle = handle;
|
|
1645
|
+
this.terminalCleanup = this.cleanupRegistry.register(() => handle.close());
|
|
1646
|
+
this.workerManager.setTerminalInfo({
|
|
1647
|
+
backend: handle.backend, paneId: handle.paneId,
|
|
1648
|
+
windowId: handle.windowId, sessionName: handle.sessionName,
|
|
1649
|
+
});
|
|
1650
|
+
} else {
|
|
1651
|
+
try { child = launchWorkerWindow(spec, { spawnFn: this.launchSpawner ?? undefined }); }
|
|
1652
|
+
catch (err) { throw new TerminalSpawnError(backend.backend, err instanceof Error ? err : new Error(String(err))); }
|
|
1653
1653
|
}
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1654
|
+
// Only explicit CLI/spawn failure permits fallback; a handshake timeout is ambiguous.
|
|
1655
|
+
await this.waitForSupervisor(launchTimeoutMs, backend.backend, child, startGen);
|
|
1656
|
+
this.assertStartActive(startGen);
|
|
1657
|
+
break;
|
|
1658
|
+
} catch (err) {
|
|
1659
|
+
this.assertStartActive(startGen);
|
|
1660
|
+
if (!(err instanceof TerminalSpawnError)) throw err;
|
|
1661
|
+
await this.closeTerminal();
|
|
1662
|
+
this.assertStartActive(startGen);
|
|
1663
|
+
if (index === terminalBackends.length - 1) throw err;
|
|
1657
1664
|
}
|
|
1658
1665
|
}
|
|
1659
1666
|
|
|
@@ -1763,6 +1770,11 @@ export class ControllerManager {
|
|
|
1763
1770
|
throw err;
|
|
1764
1771
|
}
|
|
1765
1772
|
const inst = this.workerManager.getInstance();
|
|
1773
|
+
if (err instanceof TerminalSpawnError) {
|
|
1774
|
+
this.workerManager.updateLifecycleState("closed");
|
|
1775
|
+
this.workerManager.releaseSlot();
|
|
1776
|
+
throw new Error(`[${ProtocolErrorCode.LAUNCH_FAILED}] ${err.message}`);
|
|
1777
|
+
}
|
|
1766
1778
|
if (inst?.lifecycleState === "closed") {
|
|
1767
1779
|
// 「进程已确认退出」优先级高于「投递未知」:Supervisor 已明确上报
|
|
1768
1780
|
// launch_failed / child_exit → 必须释放单实例名额;若同时存在投递未知,
|
|
@@ -1807,21 +1819,30 @@ export class ControllerManager {
|
|
|
1807
1819
|
const onError = (err: Error) => {
|
|
1808
1820
|
spawnError = new TerminalSpawnError(backend, err);
|
|
1809
1821
|
};
|
|
1822
|
+
const onExit = (code: number | null) => {
|
|
1823
|
+
if (code !== null && code !== 0) onError(new Error(`启动命令退出码 ${code}`));
|
|
1824
|
+
};
|
|
1810
1825
|
child?.once?.("error", onError);
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1826
|
+
child?.once?.("exit", onExit);
|
|
1827
|
+
if (child?.exitCode !== null && child?.exitCode !== undefined) onExit(child.exitCode);
|
|
1828
|
+
try {
|
|
1829
|
+
while (Date.now() - start < timeoutMs) {
|
|
1830
|
+
if (this.isDisposed || !this.isCurrentGeneration(gen)) {
|
|
1831
|
+
throw new Error("会话已切换,等待 Supervisor 握手已取消");
|
|
1832
|
+
}
|
|
1833
|
+
if (this.supervisorConn) return;
|
|
1834
|
+
if (spawnError) throw spawnError;
|
|
1835
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
1815
1836
|
}
|
|
1816
|
-
if (this.supervisorConn) return;
|
|
1817
1837
|
if (spawnError) throw spawnError;
|
|
1818
|
-
|
|
1838
|
+
throw new Error(
|
|
1839
|
+
`等待终端窗口与 Supervisor 握手超时 (${timeoutMs}ms,后端: ${backend})。` +
|
|
1840
|
+
`为避免重复开窗,不会自动重开窗口;请检查新窗口是否已出现,可用 /worker-forget 手动解除占位。`,
|
|
1841
|
+
);
|
|
1842
|
+
} finally {
|
|
1843
|
+
child?.removeListener?.("error", onError);
|
|
1844
|
+
child?.removeListener?.("exit", onExit);
|
|
1819
1845
|
}
|
|
1820
|
-
if (spawnError) throw spawnError;
|
|
1821
|
-
throw new Error(
|
|
1822
|
-
`等待终端窗口与 Supervisor 握手超时 (${timeoutMs}ms,后端: ${backend})。` +
|
|
1823
|
-
`为避免重复开窗,不会自动重开窗口;请检查新窗口是否已出现,可用 /worker-forget 手动解除占位。`,
|
|
1824
|
-
);
|
|
1825
1846
|
}
|
|
1826
1847
|
|
|
1827
1848
|
/**
|
|
@@ -2263,6 +2284,7 @@ export class ControllerManager {
|
|
|
2263
2284
|
);
|
|
2264
2285
|
}
|
|
2265
2286
|
|
|
2287
|
+
let closeTarget: TerminalHandle | null | undefined;
|
|
2266
2288
|
const run = async (): Promise<{ ok: boolean; disposition: string; message: string }> => {
|
|
2267
2289
|
const gen = this.activeGeneration;
|
|
2268
2290
|
const inst = this.workerManager.getInstance();
|
|
@@ -2305,6 +2327,7 @@ export class ControllerManager {
|
|
|
2305
2327
|
}
|
|
2306
2328
|
|
|
2307
2329
|
this.workerManager.updateLifecycleState("closing");
|
|
2330
|
+
closeTarget = this.terminalHandle;
|
|
2308
2331
|
|
|
2309
2332
|
// 关闭指令的投递结果未知时记录请求 ID,供后续未确认退出的错误信息诊断
|
|
2310
2333
|
let closeUnknownRequestId: string | null = null;
|
|
@@ -2369,21 +2392,33 @@ export class ControllerManager {
|
|
|
2369
2392
|
}
|
|
2370
2393
|
|
|
2371
2394
|
const confirmed = this.workerManager.getInstance();
|
|
2395
|
+
let unconfirmedExitMessage: string | undefined;
|
|
2372
2396
|
if (confirmed?.lifecycleState !== "closed") {
|
|
2373
2397
|
const unknownSuffix = closeUnknownRequestId
|
|
2374
2398
|
? `;关闭指令送达未知 (req: ${closeUnknownRequestId}),结果待确认`
|
|
2375
2399
|
: "";
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2400
|
+
if (params.force || !closeTarget) {
|
|
2401
|
+
throw new Error(
|
|
2402
|
+
"未确认 Worker 进程退出;保留单实例占位,请检查状态后重试关闭" + unknownSuffix,
|
|
2403
|
+
);
|
|
2404
|
+
}
|
|
2405
|
+
// 非强制关闭超时后仍会关闭终端:收敛到终态,避免留下永远 closing 的占位。
|
|
2406
|
+
// closed 在此表示终端已关闭;不伪造 child_exit,返回值仍明确说明退出未确认。
|
|
2407
|
+
await this.closeTerminal();
|
|
2408
|
+
if (!this.isCurrentGeneration(gen)) throw new Error("会话已切换,关闭流程已终止");
|
|
2409
|
+
this.workerManager.updateLifecycleState("closed");
|
|
2410
|
+
unconfirmedExitMessage =
|
|
2411
|
+
`Worker 终端已关闭并释放名额,但未确认 Worker 进程退出 (disposition: ${params.disposition})` + unknownSuffix;
|
|
2379
2412
|
}
|
|
2413
|
+
await this.closeTerminal();
|
|
2414
|
+
if (!this.isCurrentGeneration(gen)) throw new Error("会话已切换,关闭流程已终止");
|
|
2380
2415
|
this.workerManager.releaseSlot();
|
|
2381
2416
|
this.stopHeartbeat();
|
|
2382
2417
|
|
|
2383
2418
|
return {
|
|
2384
2419
|
ok: true,
|
|
2385
2420
|
disposition: params.disposition,
|
|
2386
|
-
message: `Worker 已关闭 (disposition: ${params.disposition})`,
|
|
2421
|
+
message: unconfirmedExitMessage ?? `Worker 已关闭 (disposition: ${params.disposition})`,
|
|
2387
2422
|
};
|
|
2388
2423
|
};
|
|
2389
2424
|
|
|
@@ -2396,6 +2431,9 @@ export class ControllerManager {
|
|
|
2396
2431
|
try {
|
|
2397
2432
|
return await promise;
|
|
2398
2433
|
} finally {
|
|
2434
|
+
// Even a missing/failed supervisor ACK must not leave an abandoned pane behind.
|
|
2435
|
+
// Capture identity after validation so a stale close can never touch a new terminal.
|
|
2436
|
+
if (closeTarget && this.terminalHandle === closeTarget) await this.closeTerminal();
|
|
2399
2437
|
if (this.closeInFlight && this.closeInFlight.promise === promise) {
|
|
2400
2438
|
this.closeInFlight = null;
|
|
2401
2439
|
}
|
|
@@ -2416,13 +2454,13 @@ export class ControllerManager {
|
|
|
2416
2454
|
name: "worker_start",
|
|
2417
2455
|
label: "Worker Start",
|
|
2418
2456
|
description:
|
|
2419
|
-
"
|
|
2457
|
+
"在独立终端中启动交互式 Worker Pi(herdr pane、Linux tmux 或 Windows Terminal/PowerShell/CMD),派发初始任务并建立监督通信。" +
|
|
2420
2458
|
"Worker 的关键事件(交付/提问/阻塞/停止/断连等)会主动唤醒本会话:空闲时开新轮,忙碌时 followUp 排队,无需轮询。",
|
|
2421
2459
|
executionMode: "sequential",
|
|
2422
2460
|
parameters: Type.Object({
|
|
2423
2461
|
role: Type.Optional(Type.Union([Type.Literal("worker"), Type.Literal("lead")], { description: "角色,默认 worker;仅顶层主控可启动 lead" })),
|
|
2424
2462
|
cwd: Type.String({ description: "Worker 工作的根目录 (必须为绝对路径)" }),
|
|
2425
|
-
title: Type.String({ description: "
|
|
2463
|
+
title: Type.String({ description: "Worker 终端窗口或 pane 的标题" }),
|
|
2426
2464
|
task: Type.String({ description: "初始任务需求与指令说明" }),
|
|
2427
2465
|
context: Type.Optional(Type.String({ description: "任务背景与前置上下文" })),
|
|
2428
2466
|
allowedPaths: Type.Optional(Type.Array(Type.String(), { description: "允许修改的文件或目录契约" })),
|
|
@@ -2630,6 +2668,8 @@ export class ControllerManager {
|
|
|
2630
2668
|
this.isDisposed = false;
|
|
2631
2669
|
this.closeInFlight = null;
|
|
2632
2670
|
|
|
2671
|
+
// Capture cleanup before awaiting: never close a new generation's terminal.
|
|
2672
|
+
const closePreviousTerminal = this.closeTerminal();
|
|
2633
2673
|
// 结束上一会话的连接与 pipe 服务
|
|
2634
2674
|
this.stopHeartbeat();
|
|
2635
2675
|
this.resetStaleConnections();
|
|
@@ -2670,6 +2710,7 @@ export class ControllerManager {
|
|
|
2670
2710
|
this.resetSessionScopedState();
|
|
2671
2711
|
|
|
2672
2712
|
// 清空上一会话的清理器并复位,使本实例可被下一次会话继续复用
|
|
2713
|
+
await closePreviousTerminal;
|
|
2673
2714
|
await this.cleanupRegistry.disposeAll();
|
|
2674
2715
|
this.cleanupRegistry.reset();
|
|
2675
2716
|
this.serverCleanup = null;
|
|
@@ -2715,6 +2756,8 @@ export class ControllerManager {
|
|
|
2715
2756
|
return;
|
|
2716
2757
|
}
|
|
2717
2758
|
|
|
2759
|
+
await this.closeTerminal();
|
|
2760
|
+
if (!this.isCurrentGeneration(gen)) return;
|
|
2718
2761
|
this.rejectWaiters(new Error("Controller 已关闭,等待已被取消"));
|
|
2719
2762
|
this.resetSessionScopedState();
|
|
2720
2763
|
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 零依赖 JSON Schema 构造器。
|
|
3
|
+
*
|
|
4
|
+
* API 与本包用到的 TypeBox 子集一致(Object/String/Number/Boolean/Array/Literal/Union/Optional),
|
|
5
|
+
* 输出与 TypeBox 序列化结果相同的纯 JSON Schema 对象。这样 controller / multi-worker 在 pi 之外
|
|
6
|
+
* (如 Claude Code 的 MCP server)运行时不需要 typebox:typebox 是 pi 宿主提供的包,不能放进 dependencies。
|
|
7
|
+
*
|
|
8
|
+
* 与 TypeBox 一样,额外写入不可枚举的 `~kind` / `~optional` 标记:JSON 序列化结果不变,
|
|
9
|
+
* 旧版 pi(pi-ai 用 TypeBox Value.Convert 做参数转换)仍按 TypeBox schema 处理,行为与原来一致。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export type JsonSchema = Record<string, unknown>;
|
|
13
|
+
|
|
14
|
+
type Options = { description?: string };
|
|
15
|
+
|
|
16
|
+
function mark(schema: JsonSchema, kind: string): JsonSchema {
|
|
17
|
+
Object.defineProperty(schema, "~kind", { value: kind, enumerable: false, writable: true, configurable: true });
|
|
18
|
+
return schema;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function withOptions(schema: JsonSchema, options?: Options): JsonSchema {
|
|
22
|
+
return options ? { ...schema, ...options } : schema;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function isOptionalSchema(schema: unknown): boolean {
|
|
26
|
+
return typeof schema === "object" && schema !== null && (schema as JsonSchema)["~optional"] === true;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const Type = {
|
|
30
|
+
String(options?: Options): JsonSchema {
|
|
31
|
+
return mark(withOptions({ type: "string" }, options), "String");
|
|
32
|
+
},
|
|
33
|
+
Number(options?: Options): JsonSchema {
|
|
34
|
+
return mark(withOptions({ type: "number" }, options), "Number");
|
|
35
|
+
},
|
|
36
|
+
Boolean(options?: Options): JsonSchema {
|
|
37
|
+
return mark(withOptions({ type: "boolean" }, options), "Boolean");
|
|
38
|
+
},
|
|
39
|
+
Literal(value: string, options?: Options): JsonSchema {
|
|
40
|
+
return mark(withOptions({ type: "string", const: value }, options), "Literal");
|
|
41
|
+
},
|
|
42
|
+
Array(items: JsonSchema, options?: Options): JsonSchema {
|
|
43
|
+
return mark(withOptions({ type: "array", items }, options), "Array");
|
|
44
|
+
},
|
|
45
|
+
Union(anyOf: JsonSchema[], options?: Options): JsonSchema {
|
|
46
|
+
return mark(withOptions({ anyOf }, options), "Union");
|
|
47
|
+
},
|
|
48
|
+
/** 仅作为 Object 的属性使用:标记为非必填,输出不带额外的可枚举字段 */
|
|
49
|
+
Optional(schema: JsonSchema): JsonSchema {
|
|
50
|
+
const copy = mark({ ...schema }, String(schema["~kind"] ?? ""));
|
|
51
|
+
Object.defineProperty(copy, "~optional", { value: true, enumerable: false, writable: true, configurable: true });
|
|
52
|
+
return copy;
|
|
53
|
+
},
|
|
54
|
+
Object(properties: Record<string, JsonSchema>, options?: Options): JsonSchema {
|
|
55
|
+
const required = Object.keys(properties).filter((key) => !isOptionalSchema(properties[key]));
|
|
56
|
+
const schema: JsonSchema = required.length > 0
|
|
57
|
+
? { type: "object", required, properties }
|
|
58
|
+
: { type: "object", properties };
|
|
59
|
+
return mark(withOptions(schema, options), "Object");
|
|
60
|
+
},
|
|
61
|
+
};
|