@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.
Files changed (44) hide show
  1. package/README.md +238 -212
  2. package/dist/controller.d.ts +6 -0
  3. package/dist/controller.d.ts.map +1 -1
  4. package/dist/controller.js +118 -56
  5. package/dist/controller.js.map +1 -1
  6. package/dist/json-schema.d.ts +28 -0
  7. package/dist/json-schema.d.ts.map +1 -0
  8. package/dist/json-schema.js +54 -0
  9. package/dist/json-schema.js.map +1 -0
  10. package/dist/launcher.d.ts +9 -1
  11. package/dist/launcher.d.ts.map +1 -1
  12. package/dist/launcher.js +95 -22
  13. package/dist/launcher.js.map +1 -1
  14. package/dist/lifecycle.d.ts +7 -0
  15. package/dist/lifecycle.d.ts.map +1 -1
  16. package/dist/lifecycle.js +4 -0
  17. package/dist/lifecycle.js.map +1 -1
  18. package/dist/mcp-server.d.ts +40 -0
  19. package/dist/mcp-server.d.ts.map +1 -0
  20. package/dist/mcp-server.js +364 -0
  21. package/dist/mcp-server.js.map +1 -0
  22. package/dist/multi-worker.d.ts.map +1 -1
  23. package/dist/multi-worker.js +1 -1
  24. package/dist/multi-worker.js.map +1 -1
  25. package/dist/schema-validate.d.ts +17 -0
  26. package/dist/schema-validate.d.ts.map +1 -0
  27. package/dist/schema-validate.js +100 -0
  28. package/dist/schema-validate.js.map +1 -0
  29. package/dist/terminal-multiplexer.d.ts +25 -0
  30. package/dist/terminal-multiplexer.d.ts.map +1 -0
  31. package/dist/terminal-multiplexer.js +102 -0
  32. package/dist/terminal-multiplexer.js.map +1 -0
  33. package/package.json +81 -75
  34. package/runtime/bootstrap-support.mjs +68 -67
  35. package/runtime/bootstrap.mjs +328 -312
  36. package/runtime/terminal-support.mjs +63 -0
  37. package/src/controller.ts +101 -58
  38. package/src/json-schema.ts +61 -0
  39. package/src/launcher.ts +592 -517
  40. package/src/lifecycle.ts +289 -284
  41. package/src/mcp-server.ts +409 -0
  42. package/src/multi-worker.ts +1 -1
  43. package/src/schema-validate.ts +100 -0
  44. package/src/terminal-multiplexer.ts +108 -0
@@ -3,7 +3,7 @@
3
3
  */
4
4
  import * as net from "node:net";
5
5
  import * as crypto from "node:crypto";
6
- import { Type } from "typebox";
6
+ import { Type } from "./json-schema.js";
7
7
  import { PROTOCOL_VERSION, MAX_INBOX_EVENTS, MAX_INBOX_BYTES, MAX_REPORT_CACHE_SIZE, MAX_REPORT_CACHE_BYTES, MAX_WAIT_RESULT_SIZE, MAX_TASK_TEXT_SIZE, MAX_UNKNOWN_DELIVERIES, jsonByteLength, AUTH_TIMEOUT_MS, LAUNCH_TIMEOUT_MS, HEARTBEAT_INTERVAL_MS, HEARTBEAT_TIMEOUT_MS, ProtocolErrorCode, resolveChildRole, THINKING_LEVELS, } from "./protocol.js";
8
8
  import { encodeToolPolicy } from "./tool-policy.js";
9
9
  /**
@@ -123,16 +123,7 @@ function isDeliveryUnknownError(err) {
123
123
  import { JsonlConnection, AckTimeoutError, getPipePath, timingSafeCompare, } from "./transport.js";
124
124
  import { SingleWorkerManager, SessionGenerationManager, CleanupRegistry, } from "./lifecycle.js";
125
125
  import { validateAndPrepareLaunch, detectTerminalBackends, encodeDescriptor, buildTerminalLaunch, launchWorkerWindow, } from "./launcher.js";
126
- class TerminalSpawnError extends Error {
127
- backend;
128
- cause;
129
- constructor(backend, cause) {
130
- super(`终端后端 ${backend} 启动失败: ${cause.message}`);
131
- this.backend = backend;
132
- this.name = "TerminalSpawnError";
133
- this.cause = cause;
134
- }
135
- }
126
+ import { launchMultiplexer, TerminalSpawnError } from "./terminal-multiplexer.js";
136
127
  /**
137
128
  * Worker (子代理) 默认模型配置:`worker_start` 未显式指定 provider/model/thinkingLevel 时使用。
138
129
  * 只影响新拉起的 Worker,不影响主 Pi 会话自身的默认模型,也不改动全局 Pi 设置。
@@ -249,6 +240,19 @@ export class ControllerManager {
249
240
  ];
250
241
  /** 可注入的终端启动器,单元测试不实际开窗 */
251
242
  launchSpawner = null;
243
+ terminalRunner;
244
+ terminalHandle = null;
245
+ terminalClosing = Promise.resolve();
246
+ terminalCleanup = null;
247
+ closeTerminal() {
248
+ const handle = this.terminalHandle;
249
+ this.terminalHandle = null;
250
+ this.terminalCleanup?.();
251
+ this.terminalCleanup = null;
252
+ if (handle)
253
+ this.terminalClosing = handle.close();
254
+ return this.terminalClosing;
255
+ }
252
256
  constructor(pi, strictProtocol = false) {
253
257
  this.pi = pi;
254
258
  this.strictProtocol = strictProtocol;
@@ -820,6 +824,7 @@ export class ControllerManager {
820
824
  this.childExitConfirmed = true;
821
825
  this.workerManager.updateLifecycleState("closed");
822
826
  this.appendInbox("child_exit", p, undefined, undefined, undefined, { notify: !expectedExit });
827
+ void this.closeTerminal();
823
828
  this.stopHeartbeat();
824
829
  }
825
830
  else if (env.type === "launch_failed") {
@@ -827,6 +832,7 @@ export class ControllerManager {
827
832
  this.childExitConfirmed = true;
828
833
  this.workerManager.updateLifecycleState("closed");
829
834
  this.appendInbox("launch_failed", p);
835
+ void this.closeTerminal();
830
836
  }
831
837
  }
832
838
  catch (err) {
@@ -1250,41 +1256,53 @@ export class ControllerManager {
1250
1256
  ...(ownerPid === undefined ? {} : { ownerPid }),
1251
1257
  };
1252
1258
  const descB64 = encodeDescriptor(desc);
1253
- const spec = buildTerminalLaunch(env, params.title, descB64);
1254
1259
  const terminalBackends = detectTerminalBackends(probes);
1255
- let launchedBackend = spec.backend;
1256
- let launchError = null;
1257
- this.assertStartActive(startGen);
1258
- let child = launchWorkerWindow(spec, { spawnFn: this.launchSpawner ?? undefined });
1259
- // 仅在 spawn 明确失败时回退。握手超时不是安全的回退信号,避免重复开窗。
1260
- try {
1261
- await this.waitForSupervisor(launchTimeoutMs, launchedBackend, child);
1262
- }
1263
- catch (err) {
1264
- if (!(err instanceof TerminalSpawnError))
1265
- throw err;
1266
- launchError = err;
1267
- const startIndex = terminalBackends.findIndex((x) => x.backend === launchedBackend);
1268
- const fallback = terminalBackends.slice(startIndex + 1);
1269
- let lastError = err;
1270
- for (const backend of fallback) {
1271
- const fallbackEnv = { ...env, terminal: backend };
1272
- const fallbackSpec = buildTerminalLaunch(fallbackEnv, params.title, descB64);
1273
- try {
1274
- child = launchWorkerWindow(fallbackSpec, { spawnFn: this.launchSpawner ?? undefined });
1275
- launchedBackend = backend.backend;
1276
- await this.waitForSupervisor(launchTimeoutMs, launchedBackend, child);
1277
- launchError = null;
1278
- break;
1260
+ for (let index = 0; index < terminalBackends.length; index++) {
1261
+ const backend = terminalBackends[index];
1262
+ this.assertStartActive(startGen);
1263
+ const spec = buildTerminalLaunch({ ...env, terminal: backend }, params.title, descB64);
1264
+ try {
1265
+ let child;
1266
+ if (backend.backend === "herdr" || backend.backend === "tmux") {
1267
+ const handle = await launchMultiplexer(spec, {
1268
+ run: this.terminalRunner,
1269
+ assertActive: () => this.assertStartActive(startGen),
1270
+ });
1271
+ try {
1272
+ this.assertStartActive(startGen);
1273
+ }
1274
+ catch (err) {
1275
+ await handle.close();
1276
+ throw err;
1277
+ }
1278
+ this.terminalHandle = handle;
1279
+ this.terminalCleanup = this.cleanupRegistry.register(() => handle.close());
1280
+ this.workerManager.setTerminalInfo({
1281
+ backend: handle.backend, paneId: handle.paneId,
1282
+ windowId: handle.windowId, sessionName: handle.sessionName,
1283
+ });
1279
1284
  }
1280
- catch (fallbackErr) {
1281
- lastError = fallbackErr;
1282
- if (!(fallbackErr instanceof TerminalSpawnError))
1283
- throw fallbackErr;
1285
+ else {
1286
+ try {
1287
+ child = launchWorkerWindow(spec, { spawnFn: this.launchSpawner ?? undefined });
1288
+ }
1289
+ catch (err) {
1290
+ throw new TerminalSpawnError(backend.backend, err instanceof Error ? err : new Error(String(err)));
1291
+ }
1284
1292
  }
1293
+ // Only explicit CLI/spawn failure permits fallback; a handshake timeout is ambiguous.
1294
+ await this.waitForSupervisor(launchTimeoutMs, backend.backend, child, startGen);
1295
+ this.assertStartActive(startGen);
1296
+ break;
1285
1297
  }
1286
- if (launchError) {
1287
- throw lastError;
1298
+ catch (err) {
1299
+ this.assertStartActive(startGen);
1300
+ if (!(err instanceof TerminalSpawnError))
1301
+ throw err;
1302
+ await this.closeTerminal();
1303
+ this.assertStartActive(startGen);
1304
+ if (index === terminalBackends.length - 1)
1305
+ throw err;
1288
1306
  }
1289
1307
  }
1290
1308
  // spawn 之后、发送 launch 之前再次复核代际
@@ -1383,6 +1401,11 @@ export class ControllerManager {
1383
1401
  throw err;
1384
1402
  }
1385
1403
  const inst = this.workerManager.getInstance();
1404
+ if (err instanceof TerminalSpawnError) {
1405
+ this.workerManager.updateLifecycleState("closed");
1406
+ this.workerManager.releaseSlot();
1407
+ throw new Error(`[${ProtocolErrorCode.LAUNCH_FAILED}] ${err.message}`);
1408
+ }
1386
1409
  if (inst?.lifecycleState === "closed") {
1387
1410
  // 「进程已确认退出」优先级高于「投递未知」:Supervisor 已明确上报
1388
1411
  // launch_failed / child_exit → 必须释放单实例名额;若同时存在投递未知,
@@ -1420,21 +1443,34 @@ export class ControllerManager {
1420
1443
  const onError = (err) => {
1421
1444
  spawnError = new TerminalSpawnError(backend, err);
1422
1445
  };
1446
+ const onExit = (code) => {
1447
+ if (code !== null && code !== 0)
1448
+ onError(new Error(`启动命令退出码 ${code}`));
1449
+ };
1423
1450
  child?.once?.("error", onError);
1424
- while (Date.now() - start < timeoutMs) {
1425
- if (this.isDisposed || !this.isCurrentGeneration(gen)) {
1426
- throw new Error("会话已切换,等待 Supervisor 握手已取消");
1451
+ child?.once?.("exit", onExit);
1452
+ if (child?.exitCode !== null && child?.exitCode !== undefined)
1453
+ onExit(child.exitCode);
1454
+ try {
1455
+ while (Date.now() - start < timeoutMs) {
1456
+ if (this.isDisposed || !this.isCurrentGeneration(gen)) {
1457
+ throw new Error("会话已切换,等待 Supervisor 握手已取消");
1458
+ }
1459
+ if (this.supervisorConn)
1460
+ return;
1461
+ if (spawnError)
1462
+ throw spawnError;
1463
+ await new Promise((r) => setTimeout(r, 200));
1427
1464
  }
1428
- if (this.supervisorConn)
1429
- return;
1430
1465
  if (spawnError)
1431
1466
  throw spawnError;
1432
- await new Promise((r) => setTimeout(r, 200));
1467
+ throw new Error(`等待终端窗口与 Supervisor 握手超时 (${timeoutMs}ms,后端: ${backend})。` +
1468
+ `为避免重复开窗,不会自动重开窗口;请检查新窗口是否已出现,可用 /worker-forget 手动解除占位。`);
1469
+ }
1470
+ finally {
1471
+ child?.removeListener?.("error", onError);
1472
+ child?.removeListener?.("exit", onExit);
1433
1473
  }
1434
- if (spawnError)
1435
- throw spawnError;
1436
- throw new Error(`等待终端窗口与 Supervisor 握手超时 (${timeoutMs}ms,后端: ${backend})。` +
1437
- `为避免重复开窗,不会自动重开窗口;请检查新窗口是否已出现,可用 /worker-forget 手动解除占位。`);
1438
1474
  }
1439
1475
  /**
1440
1476
  * 等待真实的 worker_ready 消息 (不只是管道连接):
@@ -1760,6 +1796,7 @@ export class ControllerManager {
1760
1796
  throw new Error(`[${ProtocolErrorCode.INVALID_STATE}] 已有一次进行中的 worker_close (disposition: ${this.closeInFlight.disposition}),` +
1761
1797
  `不能同时以 ${params.disposition} 再次关闭;请等待上一次关闭结束`);
1762
1798
  }
1799
+ let closeTarget;
1763
1800
  const run = async () => {
1764
1801
  const gen = this.activeGeneration;
1765
1802
  const inst = this.workerManager.getInstance();
@@ -1793,6 +1830,7 @@ export class ControllerManager {
1793
1830
  this.workerManager.updateTaskState("abandoned");
1794
1831
  }
1795
1832
  this.workerManager.updateLifecycleState("closing");
1833
+ closeTarget = this.terminalHandle;
1796
1834
  // 关闭指令的投递结果未知时记录请求 ID,供后续未确认退出的错误信息诊断
1797
1835
  let closeUnknownRequestId = null;
1798
1836
  // 发送关闭或强杀指令
@@ -1853,18 +1891,32 @@ export class ControllerManager {
1853
1891
  throw new Error("会话已切换,关闭流程已终止;保留单实例占位,请在新会话确认状态");
1854
1892
  }
1855
1893
  const confirmed = this.workerManager.getInstance();
1894
+ let unconfirmedExitMessage;
1856
1895
  if (confirmed?.lifecycleState !== "closed") {
1857
1896
  const unknownSuffix = closeUnknownRequestId
1858
1897
  ? `;关闭指令送达未知 (req: ${closeUnknownRequestId}),结果待确认`
1859
1898
  : "";
1860
- throw new Error("未确认 Worker 进程退出;保留单实例占位,请检查状态后重试关闭" + unknownSuffix);
1899
+ if (params.force || !closeTarget) {
1900
+ throw new Error("未确认 Worker 进程退出;保留单实例占位,请检查状态后重试关闭" + unknownSuffix);
1901
+ }
1902
+ // 非强制关闭超时后仍会关闭终端:收敛到终态,避免留下永远 closing 的占位。
1903
+ // closed 在此表示终端已关闭;不伪造 child_exit,返回值仍明确说明退出未确认。
1904
+ await this.closeTerminal();
1905
+ if (!this.isCurrentGeneration(gen))
1906
+ throw new Error("会话已切换,关闭流程已终止");
1907
+ this.workerManager.updateLifecycleState("closed");
1908
+ unconfirmedExitMessage =
1909
+ `Worker 终端已关闭并释放名额,但未确认 Worker 进程退出 (disposition: ${params.disposition})` + unknownSuffix;
1861
1910
  }
1911
+ await this.closeTerminal();
1912
+ if (!this.isCurrentGeneration(gen))
1913
+ throw new Error("会话已切换,关闭流程已终止");
1862
1914
  this.workerManager.releaseSlot();
1863
1915
  this.stopHeartbeat();
1864
1916
  return {
1865
1917
  ok: true,
1866
1918
  disposition: params.disposition,
1867
- message: `Worker 已关闭 (disposition: ${params.disposition})`,
1919
+ message: unconfirmedExitMessage ?? `Worker 已关闭 (disposition: ${params.disposition})`,
1868
1920
  };
1869
1921
  };
1870
1922
  const promise = run();
@@ -1877,6 +1929,10 @@ export class ControllerManager {
1877
1929
  return await promise;
1878
1930
  }
1879
1931
  finally {
1932
+ // Even a missing/failed supervisor ACK must not leave an abandoned pane behind.
1933
+ // Capture identity after validation so a stale close can never touch a new terminal.
1934
+ if (closeTarget && this.terminalHandle === closeTarget)
1935
+ await this.closeTerminal();
1880
1936
  if (this.closeInFlight && this.closeInFlight.promise === promise) {
1881
1937
  this.closeInFlight = null;
1882
1938
  }
@@ -1894,13 +1950,13 @@ export class ControllerManager {
1894
1950
  this.pi.registerTool({
1895
1951
  name: "worker_start",
1896
1952
  label: "Worker Start",
1897
- description: "在独立的终端窗口 (Windows Terminal,缺失时回退 PowerShell/CMD) 中启动一个交互式 Worker Pi,派发初始任务并建立监督通信。" +
1953
+ description: "在独立终端中启动交互式 Worker Pi(herdr pane、Linux tmux 或 Windows Terminal/PowerShell/CMD),派发初始任务并建立监督通信。" +
1898
1954
  "Worker 的关键事件(交付/提问/阻塞/停止/断连等)会主动唤醒本会话:空闲时开新轮,忙碌时 followUp 排队,无需轮询。",
1899
1955
  executionMode: "sequential",
1900
1956
  parameters: Type.Object({
1901
1957
  role: Type.Optional(Type.Union([Type.Literal("worker"), Type.Literal("lead")], { description: "角色,默认 worker;仅顶层主控可启动 lead" })),
1902
1958
  cwd: Type.String({ description: "Worker 工作的根目录 (必须为绝对路径)" }),
1903
- title: Type.String({ description: "Windows Terminal 窗口的标题" }),
1959
+ title: Type.String({ description: "Worker 终端窗口或 pane 的标题" }),
1904
1960
  task: Type.String({ description: "初始任务需求与指令说明" }),
1905
1961
  context: Type.Optional(Type.String({ description: "任务背景与前置上下文" })),
1906
1962
  allowedPaths: Type.Optional(Type.Array(Type.String(), { description: "允许修改的文件或目录契约" })),
@@ -2085,6 +2141,8 @@ export class ControllerManager {
2085
2141
  this.staleCallbacksIgnored = 0;
2086
2142
  this.isDisposed = false;
2087
2143
  this.closeInFlight = null;
2144
+ // Capture cleanup before awaiting: never close a new generation's terminal.
2145
+ const closePreviousTerminal = this.closeTerminal();
2088
2146
  // 结束上一会话的连接与 pipe 服务
2089
2147
  this.stopHeartbeat();
2090
2148
  this.resetStaleConnections();
@@ -2120,6 +2178,7 @@ export class ControllerManager {
2120
2178
  this.childExitConfirmed = false;
2121
2179
  this.resetSessionScopedState();
2122
2180
  // 清空上一会话的清理器并复位,使本实例可被下一次会话继续复用
2181
+ await closePreviousTerminal;
2123
2182
  await this.cleanupRegistry.disposeAll();
2124
2183
  this.cleanupRegistry.reset();
2125
2184
  this.serverCleanup = null;
@@ -2158,6 +2217,9 @@ export class ControllerManager {
2158
2217
  // 会话已切换:本轮 dispose 已过时,不再改写新会话状态与资源引用
2159
2218
  return;
2160
2219
  }
2220
+ await this.closeTerminal();
2221
+ if (!this.isCurrentGeneration(gen))
2222
+ return;
2161
2223
  this.rejectWaiters(new Error("Controller 已关闭,等待已被取消"));
2162
2224
  this.resetSessionScopedState();
2163
2225
  // 统一清理 server / 两个连接 / 心跳 / 认证定时器 / waiters