@moberg_hr/work-tree 1.15.0 → 2.0.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 (249) hide show
  1. package/README.md +56 -142
  2. package/dist/answer-2J4XLIP7.js +63 -0
  3. package/dist/answer-2J4XLIP7.js.map +1 -0
  4. package/dist/attach-CZKRNPAJ.js +59 -0
  5. package/dist/attach-CZKRNPAJ.js.map +1 -0
  6. package/dist/bin.js +26 -11892
  7. package/dist/bin.js.map +1 -1
  8. package/dist/block-RAIDCJ4F.js +84 -0
  9. package/dist/block-RAIDCJ4F.js.map +1 -0
  10. package/dist/broadcast-BSI5NDDB.js +104 -0
  11. package/dist/broadcast-BSI5NDDB.js.map +1 -0
  12. package/dist/catchup-VVOPL2S5.js +51 -0
  13. package/dist/catchup-VVOPL2S5.js.map +1 -0
  14. package/dist/chunk-3JWTO5VZ.js +135 -0
  15. package/dist/chunk-3JWTO5VZ.js.map +1 -0
  16. package/dist/chunk-4BOK2GXL.js +210 -0
  17. package/dist/chunk-4BOK2GXL.js.map +1 -0
  18. package/dist/chunk-5QK7GB5K.js +112 -0
  19. package/dist/chunk-5QK7GB5K.js.map +1 -0
  20. package/dist/chunk-6AQRYLOB.js +16 -0
  21. package/dist/chunk-6AQRYLOB.js.map +1 -0
  22. package/dist/chunk-6FTIY5M6.js +120 -0
  23. package/dist/chunk-6FTIY5M6.js.map +1 -0
  24. package/dist/chunk-6H3MLDGG.js +48 -0
  25. package/dist/chunk-6H3MLDGG.js.map +1 -0
  26. package/dist/chunk-77XFJQGC.js +103 -0
  27. package/dist/chunk-77XFJQGC.js.map +1 -0
  28. package/dist/chunk-7H4BJ2YA.js +308 -0
  29. package/dist/chunk-7H4BJ2YA.js.map +1 -0
  30. package/dist/chunk-7HEB6SQS.js +257 -0
  31. package/dist/chunk-7HEB6SQS.js.map +1 -0
  32. package/dist/chunk-7NAXFBFI.js +206 -0
  33. package/dist/chunk-7NAXFBFI.js.map +1 -0
  34. package/dist/chunk-7NCW3LUT.js +358 -0
  35. package/dist/chunk-7NCW3LUT.js.map +1 -0
  36. package/dist/chunk-7OLPI334.js +537 -0
  37. package/dist/chunk-7OLPI334.js.map +1 -0
  38. package/dist/chunk-ABQYKTG4.js +38 -0
  39. package/dist/chunk-ABQYKTG4.js.map +1 -0
  40. package/dist/chunk-AH5TM3NB.js +21 -0
  41. package/dist/chunk-AH5TM3NB.js.map +1 -0
  42. package/dist/chunk-AKMPF72Y.js +274 -0
  43. package/dist/chunk-AKMPF72Y.js.map +1 -0
  44. package/dist/chunk-C2BK6EBN.js +162 -0
  45. package/dist/chunk-C2BK6EBN.js.map +1 -0
  46. package/dist/chunk-C2THFSXA.js +37 -0
  47. package/dist/chunk-C2THFSXA.js.map +1 -0
  48. package/dist/chunk-CLGVSX36.js +668 -0
  49. package/dist/chunk-CLGVSX36.js.map +1 -0
  50. package/dist/chunk-CXEC5W5V.js +267 -0
  51. package/dist/chunk-CXEC5W5V.js.map +1 -0
  52. package/dist/chunk-DW4JPVXB.js +41 -0
  53. package/dist/chunk-DW4JPVXB.js.map +1 -0
  54. package/dist/chunk-FR3EWVXI.js +188 -0
  55. package/dist/chunk-FR3EWVXI.js.map +1 -0
  56. package/dist/chunk-H5LKMR45.js +117 -0
  57. package/dist/chunk-H5LKMR45.js.map +1 -0
  58. package/dist/chunk-HSICXDMZ.js +41 -0
  59. package/dist/chunk-HSICXDMZ.js.map +1 -0
  60. package/dist/chunk-HUXS3VAI.js +90 -0
  61. package/dist/chunk-HUXS3VAI.js.map +1 -0
  62. package/dist/chunk-HWUINPIL.js +151 -0
  63. package/dist/chunk-HWUINPIL.js.map +1 -0
  64. package/dist/chunk-IXKVCR4Y.js +487 -0
  65. package/dist/chunk-IXKVCR4Y.js.map +1 -0
  66. package/dist/chunk-JNBYNRFS.js +54 -0
  67. package/dist/chunk-JNBYNRFS.js.map +1 -0
  68. package/dist/chunk-JYTMT5DF.js +421 -0
  69. package/dist/chunk-JYTMT5DF.js.map +1 -0
  70. package/dist/chunk-KA4JVX5U.js +295 -0
  71. package/dist/chunk-KA4JVX5U.js.map +1 -0
  72. package/dist/chunk-KGZ6OZ2T.js +102 -0
  73. package/dist/chunk-KGZ6OZ2T.js.map +1 -0
  74. package/dist/chunk-LNHSBM4L.js +26 -0
  75. package/dist/chunk-LNHSBM4L.js.map +1 -0
  76. package/dist/chunk-M4FVCAT6.js +2406 -0
  77. package/dist/chunk-M4FVCAT6.js.map +1 -0
  78. package/dist/chunk-MAGGGRSB.js +9 -0
  79. package/dist/chunk-MAGGGRSB.js.map +1 -0
  80. package/dist/chunk-N4EYQKSM.js +104 -0
  81. package/dist/chunk-N4EYQKSM.js.map +1 -0
  82. package/dist/chunk-NDWSLQPB.js +112 -0
  83. package/dist/chunk-NDWSLQPB.js.map +1 -0
  84. package/dist/chunk-O3QTWVSK.js +323 -0
  85. package/dist/chunk-O3QTWVSK.js.map +1 -0
  86. package/dist/chunk-P3BL4EOP.js +37 -0
  87. package/dist/chunk-P3BL4EOP.js.map +1 -0
  88. package/dist/chunk-PN44M5EE.js +887 -0
  89. package/dist/chunk-PN44M5EE.js.map +1 -0
  90. package/dist/chunk-PZ4RG6EW.js +132 -0
  91. package/dist/chunk-PZ4RG6EW.js.map +1 -0
  92. package/dist/chunk-Q6WZCO45.js +47 -0
  93. package/dist/chunk-Q6WZCO45.js.map +1 -0
  94. package/dist/chunk-QBAZG4CY.js +230 -0
  95. package/dist/chunk-QBAZG4CY.js.map +1 -0
  96. package/dist/chunk-R2LN3JJJ.js +132 -0
  97. package/dist/chunk-R2LN3JJJ.js.map +1 -0
  98. package/dist/chunk-RCYI7SRA.js +15 -0
  99. package/dist/chunk-RCYI7SRA.js.map +1 -0
  100. package/dist/chunk-RYNBBSLY.js +67 -0
  101. package/dist/chunk-RYNBBSLY.js.map +1 -0
  102. package/dist/chunk-S5HJT7CM.js +30 -0
  103. package/dist/chunk-S5HJT7CM.js.map +1 -0
  104. package/dist/chunk-SNAQOHNL.js +285 -0
  105. package/dist/chunk-SNAQOHNL.js.map +1 -0
  106. package/dist/chunk-SOCPIHCS.js +181 -0
  107. package/dist/chunk-SOCPIHCS.js.map +1 -0
  108. package/dist/chunk-TUC4QY4O.js +147 -0
  109. package/dist/chunk-TUC4QY4O.js.map +1 -0
  110. package/dist/chunk-TUFQJXXO.js +19 -0
  111. package/dist/chunk-TUFQJXXO.js.map +1 -0
  112. package/dist/chunk-UFY7C5PP.js +90 -0
  113. package/dist/chunk-UFY7C5PP.js.map +1 -0
  114. package/dist/chunk-UQ35KLHH.js +34 -0
  115. package/dist/chunk-UQ35KLHH.js.map +1 -0
  116. package/dist/chunk-VJ7SVDED.js +177 -0
  117. package/dist/chunk-VJ7SVDED.js.map +1 -0
  118. package/dist/chunk-VJNSIDOA.js +23 -0
  119. package/dist/chunk-VJNSIDOA.js.map +1 -0
  120. package/dist/chunk-WF5SBVPZ.js +190 -0
  121. package/dist/chunk-WF5SBVPZ.js.map +1 -0
  122. package/dist/chunk-WMJIU3YW.js +29 -0
  123. package/dist/chunk-WMJIU3YW.js.map +1 -0
  124. package/dist/chunk-XJDEROHY.js +19 -0
  125. package/dist/chunk-XJDEROHY.js.map +1 -0
  126. package/dist/chunk-YKODIG22.js +221 -0
  127. package/dist/chunk-YKODIG22.js.map +1 -0
  128. package/dist/chunk-YLG6DO5Y.js +162 -0
  129. package/dist/chunk-YLG6DO5Y.js.map +1 -0
  130. package/dist/chunk-YNKWLC45.js +122 -0
  131. package/dist/chunk-YNKWLC45.js.map +1 -0
  132. package/dist/chunk-YZDD5YGE.js +165 -0
  133. package/dist/chunk-YZDD5YGE.js.map +1 -0
  134. package/dist/chunk-YZWADOEW.js +151 -0
  135. package/dist/chunk-YZWADOEW.js.map +1 -0
  136. package/dist/chunk-ZJN5RWZD.js +76 -0
  137. package/dist/chunk-ZJN5RWZD.js.map +1 -0
  138. package/dist/chunk-ZSHWP2VS.js +22 -0
  139. package/dist/chunk-ZSHWP2VS.js.map +1 -0
  140. package/dist/chunk-ZXPYWZL5.js +307 -0
  141. package/dist/chunk-ZXPYWZL5.js.map +1 -0
  142. package/dist/cleanup-X45MA74G.js +192 -0
  143. package/dist/cleanup-X45MA74G.js.map +1 -0
  144. package/dist/cli-52VWEHIQ.js +18 -0
  145. package/dist/cli-52VWEHIQ.js.map +1 -0
  146. package/dist/command-hook-installer-SGEJTZ2Y.js +204 -0
  147. package/dist/command-hook-installer-SGEJTZ2Y.js.map +1 -0
  148. package/dist/completion-MXX5TRIV.js +118 -0
  149. package/dist/completion-MXX5TRIV.js.map +1 -0
  150. package/dist/config-IEIU7A66.js +410 -0
  151. package/dist/config-IEIU7A66.js.map +1 -0
  152. package/dist/console-reporter-XU6VFUZE.js +10 -0
  153. package/dist/console-reporter-XU6VFUZE.js.map +1 -0
  154. package/dist/diff-K47HB6SA.js +582 -0
  155. package/dist/diff-K47HB6SA.js.map +1 -0
  156. package/dist/digest-FBZTBXQO.js +100 -0
  157. package/dist/digest-FBZTBXQO.js.map +1 -0
  158. package/dist/fork-BKI5UNNS.js +120 -0
  159. package/dist/fork-BKI5UNNS.js.map +1 -0
  160. package/dist/hook-SLMZT5OV.js +220 -0
  161. package/dist/hook-SLMZT5OV.js.map +1 -0
  162. package/dist/hydrate-Y2AAMZTA.js +121 -0
  163. package/dist/hydrate-Y2AAMZTA.js.map +1 -0
  164. package/dist/init-7ESFTYZC.js +187 -0
  165. package/dist/init-7ESFTYZC.js.map +1 -0
  166. package/dist/install-skills-O34BHFHD.js +14 -0
  167. package/dist/install-skills-O34BHFHD.js.map +1 -0
  168. package/dist/install-skills-bin.js +12 -0
  169. package/dist/install-skills-bin.js.map +1 -0
  170. package/dist/list-KEF73NLQ.js +126 -0
  171. package/dist/list-KEF73NLQ.js.map +1 -0
  172. package/dist/move-FKT2P5LY.js +313 -0
  173. package/dist/move-FKT2P5LY.js.map +1 -0
  174. package/dist/note-WGM6LCP2.js +78 -0
  175. package/dist/note-WGM6LCP2.js.map +1 -0
  176. package/dist/overlaps-FRLMMIGC.js +56 -0
  177. package/dist/overlaps-FRLMMIGC.js.map +1 -0
  178. package/dist/pin-MQ5ZE37R.js +45 -0
  179. package/dist/pin-MQ5ZE37R.js.map +1 -0
  180. package/dist/pr-YU3NOW6G.js +118 -0
  181. package/dist/pr-YU3NOW6G.js.map +1 -0
  182. package/dist/prune-26FYYFTO.js +92 -0
  183. package/dist/prune-26FYYFTO.js.map +1 -0
  184. package/dist/pty-host-RWIS55N4.js +826 -0
  185. package/dist/pty-host-RWIS55N4.js.map +1 -0
  186. package/dist/read-AP6T3ZGN.js +57 -0
  187. package/dist/read-AP6T3ZGN.js.map +1 -0
  188. package/dist/recent-IE3LYQ65.js +111 -0
  189. package/dist/recent-IE3LYQ65.js.map +1 -0
  190. package/dist/remove-2UHJQ4DY.js +108 -0
  191. package/dist/remove-2UHJQ4DY.js.map +1 -0
  192. package/dist/report-KM4OZCZB.js +16 -0
  193. package/dist/report-KM4OZCZB.js.map +1 -0
  194. package/dist/resume-UUP6R2IE.js +81 -0
  195. package/dist/resume-UUP6R2IE.js.map +1 -0
  196. package/dist/run-V4755W7C.js +263 -0
  197. package/dist/run-V4755W7C.js.map +1 -0
  198. package/dist/screen-DNX4K23V.js +58 -0
  199. package/dist/screen-DNX4K23V.js.map +1 -0
  200. package/dist/search-3JZXLCR2.js +46 -0
  201. package/dist/search-3JZXLCR2.js.map +1 -0
  202. package/dist/section-TXLC5XO3.js +79 -0
  203. package/dist/section-TXLC5XO3.js.map +1 -0
  204. package/dist/send-6X46WZLC.js +87 -0
  205. package/dist/send-6X46WZLC.js.map +1 -0
  206. package/dist/sessions-T3QDTNP7.js +135 -0
  207. package/dist/sessions-T3QDTNP7.js.map +1 -0
  208. package/dist/snooze-KYSFXLPY.js +65 -0
  209. package/dist/snooze-KYSFXLPY.js.map +1 -0
  210. package/dist/start-SQSDQK4F.js +56 -0
  211. package/dist/start-SQSDQK4F.js.map +1 -0
  212. package/dist/state-4DFV6SHG.js +147 -0
  213. package/dist/state-4DFV6SHG.js.map +1 -0
  214. package/dist/status-H5OW4LYE.js +118 -0
  215. package/dist/status-H5OW4LYE.js.map +1 -0
  216. package/dist/stop-HC7XPSSP.js +45 -0
  217. package/dist/stop-HC7XPSSP.js.map +1 -0
  218. package/dist/sync-3CTAXM6J.js +96 -0
  219. package/dist/sync-3CTAXM6J.js.map +1 -0
  220. package/dist/time-GN6B4QD6.js +111 -0
  221. package/dist/time-GN6B4QD6.js.map +1 -0
  222. package/dist/todo-LWMQY6XW.js +152 -0
  223. package/dist/todo-LWMQY6XW.js.map +1 -0
  224. package/dist/tree-7BMORJ6J.js +235 -0
  225. package/dist/tree-7BMORJ6J.js.map +1 -0
  226. package/dist/update-6LQNLRA4.js +57 -0
  227. package/dist/update-6LQNLRA4.js.map +1 -0
  228. package/dist/wait-MZOZQ3CI.js +57 -0
  229. package/dist/wait-MZOZQ3CI.js.map +1 -0
  230. package/dist/wd-bin.js +21 -11880
  231. package/dist/wd-bin.js.map +1 -1
  232. package/dist/web/assets/PtyView-BrP-ENHg.css +1 -0
  233. package/dist/web/assets/PtyView-M4b0GFVs.js +90 -0
  234. package/dist/web/assets/PtyView-M4b0GFVs.js.map +1 -0
  235. package/dist/web/assets/index-5hi1kMKy.js +116 -0
  236. package/dist/web/assets/index-5hi1kMKy.js.map +1 -0
  237. package/dist/web/assets/index-L8mjakHP.css +1 -0
  238. package/dist/web/index.html +3 -5
  239. package/dist/web-BI3MRQEM.js +7662 -0
  240. package/dist/web-BI3MRQEM.js.map +1 -0
  241. package/npm-shrinkwrap.json +6947 -0
  242. package/package.json +52 -34
  243. package/plugins/work-tree/.claude-plugin/plugin.json +1 -1
  244. package/plugins/work-tree/skills/wd-review/SKILL.md +4 -4
  245. package/plugins/work-tree/skills/work-sessions/SKILL.md +62 -0
  246. package/scripts/postinstall.mjs +15 -45
  247. package/dist/web/assets/index-BgVq8Uj_.js +0 -107
  248. package/dist/web/assets/index-BgVq8Uj_.js.map +0 -1
  249. package/dist/web/assets/index-ubbitWeW.css +0 -1
@@ -0,0 +1,826 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ resolveWorkBinPath
4
+ } from "./chunk-AH5TM3NB.js";
5
+ import {
6
+ adoptLegacyRestoreList,
7
+ dbPtySessions
8
+ } from "./chunk-ZJN5RWZD.js";
9
+ import {
10
+ PROTOCOL_VERSION,
11
+ PtyHostBusyError,
12
+ PtyHostClient,
13
+ PtyHostVersionError,
14
+ ensureHost,
15
+ findHost,
16
+ hostInfoPath,
17
+ hostStartLockPath,
18
+ isPersistedPty,
19
+ keepEnv,
20
+ probeHostDetailed,
21
+ readHostInfo
22
+ } from "./chunk-QBAZG4CY.js";
23
+ import {
24
+ bestEffort,
25
+ loadHistory,
26
+ logSwallowed,
27
+ swallow
28
+ } from "./chunk-M4FVCAT6.js";
29
+ import {
30
+ sessionIdFor
31
+ } from "./chunk-7NCW3LUT.js";
32
+ import {
33
+ agentById,
34
+ buildAiLaunchArgs,
35
+ killTree
36
+ } from "./chunk-PN44M5EE.js";
37
+ import "./chunk-RCYI7SRA.js";
38
+ import {
39
+ report
40
+ } from "./chunk-DW4JPVXB.js";
41
+ import {
42
+ debug
43
+ } from "./chunk-N4EYQKSM.js";
44
+ import {
45
+ atomicWriteFile,
46
+ ensureFile,
47
+ loadConfig,
48
+ withFileLock,
49
+ withFileLockSync
50
+ } from "./chunk-7HEB6SQS.js";
51
+
52
+ // src/commands/pty-host.ts
53
+ import fs3 from "fs";
54
+ import chalk from "chalk";
55
+
56
+ // src/core/pty/pty-host.ts
57
+ import http from "http";
58
+ import crypto from "crypto";
59
+ import fs2 from "fs";
60
+ import { WebSocketServer } from "ws";
61
+
62
+ // src/core/pty/pty-registry.ts
63
+ import fs from "fs";
64
+
65
+ // src/core/pty/pty-session.ts
66
+ import pty from "node-pty";
67
+ import crossSpawn from "cross-spawn";
68
+ import xtermHeadless from "@xterm/headless";
69
+ import xtermSerialize from "@xterm/addon-serialize";
70
+ import childProcess from "child_process";
71
+ var HIDDEN = /* @__PURE__ */ Symbol.for("work.forkHidesConsole");
72
+ function hideForkConsoles(cp) {
73
+ if (cp.fork[HIDDEN]) return;
74
+ const orig = cp.fork;
75
+ const wrapped = function(modulePath, a, b) {
76
+ const args = Array.isArray(a) ? a : [];
77
+ const options = (Array.isArray(a) || a == null ? b : a) ?? {};
78
+ return orig.call(cp, modulePath, args, { windowsHide: true, ...options });
79
+ };
80
+ wrapped[HIDDEN] = true;
81
+ cp.fork = wrapped;
82
+ }
83
+ if (process.platform === "win32") hideForkConsoles(childProcess);
84
+ var { Terminal } = xtermHeadless;
85
+ var { SerializeAddon } = xtermSerialize;
86
+ function resolvePtyCommand(cmd, args, opts = {}) {
87
+ if (process.platform !== "win32") return { file: cmd, args };
88
+ const parse = crossSpawn._parse;
89
+ const parsed = parse(cmd, args, opts);
90
+ if (parsed.options.windowsVerbatimArguments) {
91
+ return { file: parsed.command, args: parsed.args.join(" ") };
92
+ }
93
+ return { file: parsed.file ?? parsed.command, args: parsed.args };
94
+ }
95
+ var PtySession = class {
96
+ pty;
97
+ terminal;
98
+ serializer = new SerializeAddon();
99
+ cwd;
100
+ outputHandler;
101
+ _exited = false;
102
+ _outputBuffer = "";
103
+ _loggedOutput = false;
104
+ onExit;
105
+ constructor(cwd, cols, rows, command, aiOptions) {
106
+ this.cwd = cwd;
107
+ this.terminal = new Terminal({
108
+ cols,
109
+ rows,
110
+ scrollback: 200,
111
+ allowProposedApi: true
112
+ });
113
+ this.terminal.loadAddon(this.serializer);
114
+ let rawCmd;
115
+ let rawArgs;
116
+ if (command) {
117
+ rawCmd = command.cmd;
118
+ rawArgs = command.args;
119
+ } else if (aiOptions) {
120
+ ({ cmd: rawCmd, args: rawArgs } = buildAiLaunchArgs(aiOptions.tool, {
121
+ unsafe: aiOptions.unsafe,
122
+ resume: aiOptions.resume,
123
+ promptFile: aiOptions.promptFile,
124
+ initialPrompt: aiOptions.initialPrompt
125
+ }));
126
+ } else {
127
+ throw new Error("PtySession requires either a custom command or aiOptions");
128
+ }
129
+ const env = Object.fromEntries(
130
+ Object.entries(agentById(aiOptions?.tool.cmd ?? "claude").launch.cleanEnv(aiOptions?.env ?? process.env)).filter(
131
+ (e) => e[1] != null
132
+ )
133
+ );
134
+ if (aiOptions?.port !== void 0) {
135
+ env.PORT = String(aiOptions.port);
136
+ }
137
+ const { file: spawnCmd, args: spawnArgs } = resolvePtyCommand(rawCmd, rawArgs, { env, cwd });
138
+ debug("PtySession spawn", { spawnCmd, spawnArgs, cwd, cols, rows });
139
+ this.pty = pty.spawn(spawnCmd, spawnArgs, {
140
+ name: "xterm-256color",
141
+ cwd,
142
+ cols,
143
+ rows,
144
+ env
145
+ });
146
+ debug("PtySession spawned pid=", this.pty.pid);
147
+ this.pty.onData((data) => {
148
+ this.terminal.write(data);
149
+ this.outputHandler?.(data);
150
+ if (!this._loggedOutput) {
151
+ this._outputBuffer = (this._outputBuffer || "") + data;
152
+ if (this._outputBuffer.length > 500) {
153
+ debug("PtySession first output", { cwd, output: this._outputBuffer.slice(0, 500) });
154
+ this._loggedOutput = true;
155
+ this._outputBuffer = "";
156
+ }
157
+ }
158
+ });
159
+ this.pty.onExit(({ exitCode }) => {
160
+ if (!this._loggedOutput && this._outputBuffer) {
161
+ debug("PtySession output before exit", { cwd, output: this._outputBuffer.slice(0, 500) });
162
+ }
163
+ this._outputBuffer = "";
164
+ debug("PtySession exited", { cwd, exitCode });
165
+ this._exited = true;
166
+ this.onExit?.(exitCode);
167
+ });
168
+ }
169
+ get exited() {
170
+ return this._exited;
171
+ }
172
+ write(data) {
173
+ if (!this._exited) {
174
+ try {
175
+ this.pty.write(data);
176
+ } catch {
177
+ }
178
+ }
179
+ }
180
+ resize(cols, rows) {
181
+ if (!this._exited) {
182
+ try {
183
+ this.pty.resize(cols, rows);
184
+ } catch {
185
+ }
186
+ this.terminal.resize(cols, rows);
187
+ }
188
+ }
189
+ /**
190
+ * The current screen + scrollback as escape sequences that redraw it
191
+ * exactly (colors, cursor, modes, alt screen). What a late attacher is
192
+ * sent instead of raw output history — raw bytes can start mid-sequence
193
+ * and were drawn for another client's grid (VS Code does the same).
194
+ */
195
+ serialize() {
196
+ try {
197
+ return this.serializer.serialize();
198
+ } catch {
199
+ return "";
200
+ }
201
+ }
202
+ /**
203
+ * serialize(), once the screen has parsed everything written to it so far:
204
+ * xterm queues writes, and a write's callback runs right after that write
205
+ * is parsed — before any written later. What a new client is sent first.
206
+ */
207
+ serializeSettled() {
208
+ return new Promise((resolve) => {
209
+ try {
210
+ this.terminal.write("", () => resolve(this.serialize()));
211
+ } catch {
212
+ resolve(this.serialize());
213
+ }
214
+ });
215
+ }
216
+ /** The visible screen as plain text, one line per row (no colors).
217
+ * What the dashboard checks before answering a prompt by keystroke. */
218
+ screenText() {
219
+ try {
220
+ const buf = this.terminal.buffer.active;
221
+ const lines = [];
222
+ for (let y = buf.viewportY; y < buf.viewportY + this.terminal.rows; y++) {
223
+ lines.push(buf.getLine(y)?.translateToString(true) ?? "");
224
+ }
225
+ return lines.join("\n");
226
+ } catch {
227
+ return "";
228
+ }
229
+ }
230
+ setOutputHandler(handler) {
231
+ this.outputHandler = handler;
232
+ }
233
+ dispose() {
234
+ this.setOutputHandler(void 0);
235
+ if (!this._exited) {
236
+ try {
237
+ this.pty.kill();
238
+ } catch {
239
+ }
240
+ }
241
+ this.terminal.dispose();
242
+ }
243
+ };
244
+
245
+ // src/core/pty/pty-registry.ts
246
+ var REPLAY_MAX = 256 * 1024;
247
+ var FORGET_EXITED_MS = 5e3;
248
+ var defaultSpawner = (spec) => new PtySession(spec.cwd, spec.cols ?? 120, spec.rows ?? 32, void 0, {
249
+ tool: spec.tool,
250
+ resume: spec.resume,
251
+ port: spec.port,
252
+ unsafe: spec.unsafe,
253
+ initialPrompt: spec.initialPrompt,
254
+ env: spec.env
255
+ });
256
+ function fileSessionsStore(file) {
257
+ return {
258
+ read() {
259
+ const out = {};
260
+ try {
261
+ const raw = JSON.parse(fs.readFileSync(file, "utf-8"));
262
+ if (raw && typeof raw === "object") {
263
+ for (const [id, entry] of Object.entries(raw)) if (isPersistedPty(entry)) out[id] = entry;
264
+ }
265
+ } catch {
266
+ }
267
+ return out;
268
+ },
269
+ write(all) {
270
+ ensureFile(file, "{}");
271
+ withFileLockSync(file, () => atomicWriteFile(file, JSON.stringify(all, null, 2)));
272
+ }
273
+ };
274
+ }
275
+ var PtyRegistry = class {
276
+ entries = /* @__PURE__ */ new Map();
277
+ spawner;
278
+ hasConversation;
279
+ store;
280
+ cwdExists;
281
+ keepEnvNames;
282
+ /** Serializes persistence writes inside this process. */
283
+ writeChain = Promise.resolve();
284
+ constructor(deps = {}) {
285
+ this.spawner = deps.spawner ?? defaultSpawner;
286
+ this.hasConversation = deps.hasConversation ?? ((cwd, tool) => agentById(tool).launch.canResume(cwd));
287
+ this.store = deps.sessions ?? (deps.sessionsPath ? fileSessionsStore(deps.sessionsPath) : dbPtySessions);
288
+ this.cwdExists = deps.cwdExists ?? ((p) => fs.existsSync(p));
289
+ this.keepEnvNames = deps.keepEnvNames ?? (() => loadConfig()?.hostEnv ?? []);
290
+ }
291
+ list() {
292
+ return [...this.entries.values()].map((e) => this.info(e));
293
+ }
294
+ get(id) {
295
+ const e = this.entries.get(id);
296
+ return e ? this.info(e) : null;
297
+ }
298
+ /** Spawn unless a live PTY already exists for `id` (idempotent). */
299
+ spawn(id, spec, restored = false) {
300
+ const existing = this.entries.get(id);
301
+ if (existing && !existing.pty.exited) return this.info(existing);
302
+ const kept = spec.env ? keepEnv(spec.env, this.keepEnvNames()) : spec.keptEnv ?? existing?.spec.keptEnv;
303
+ if (!spec.env && kept) spec = { ...spec, env: { ...process.env, ...kept } };
304
+ const cols = spec.cols ?? 120;
305
+ const rows = spec.rows ?? 32;
306
+ const pty2 = this.spawner({
307
+ ...spec,
308
+ cols,
309
+ rows,
310
+ // `--continue` hard-errors in a directory Claude never ran in;
311
+ // `--fresh` opts out even when one exists.
312
+ resume: !spec.fresh && this.hasConversation(spec.cwd, spec.tool.cmd)
313
+ });
314
+ const entry = {
315
+ id,
316
+ // Only what a restore may reuse: env/prompt/fresh are one-shot (and
317
+ // env can hold secrets), so they never reach pty-sessions.json — but
318
+ // the variables config `hostEnv` names do (keepEnv), so a restore after
319
+ // a reboot gets the JAVA_HOME / PATH it was started with.
320
+ spec: { cwd: spec.cwd, tool: spec.tool, port: spec.port, unsafe: spec.unsafe, ...kept ? { keptEnv: kept } : {} },
321
+ pty: pty2,
322
+ cols,
323
+ rows,
324
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
325
+ restored,
326
+ replay: "",
327
+ subscribers: /* @__PURE__ */ new Set(),
328
+ exitSubscribers: /* @__PURE__ */ new Set(),
329
+ exitCode: null,
330
+ lastOutputAt: Date.now()
331
+ };
332
+ const keepRaw = !pty2.serialize;
333
+ pty2.setOutputHandler((data) => {
334
+ entry.lastOutputAt = Date.now();
335
+ if (keepRaw) {
336
+ entry.replay += data;
337
+ if (entry.replay.length > REPLAY_MAX) {
338
+ entry.replay = entry.replay.slice(entry.replay.length - REPLAY_MAX);
339
+ }
340
+ }
341
+ for (const cb of entry.subscribers) {
342
+ try {
343
+ cb(data);
344
+ } catch {
345
+ }
346
+ }
347
+ });
348
+ pty2.onExit = (code) => {
349
+ entry.exitCode = code;
350
+ for (const cb of entry.exitSubscribers) {
351
+ try {
352
+ cb(code);
353
+ } catch {
354
+ }
355
+ }
356
+ setTimeout(() => {
357
+ if (this.entries.get(id) === entry) {
358
+ this.entries.delete(id);
359
+ void this.persist();
360
+ }
361
+ }, FORGET_EXITED_MS).unref?.();
362
+ };
363
+ this.entries.set(id, entry);
364
+ void this.persist();
365
+ return this.info(entry);
366
+ }
367
+ /** The live PTY's visible screen as text; null when there is none (or
368
+ * it can't render one — test fakes). */
369
+ screen(id) {
370
+ const e = this.entries.get(id);
371
+ if (!e || e.pty.exited || !e.pty.screenText) return null;
372
+ return e.pty.screenText();
373
+ }
374
+ write(id, data) {
375
+ const e = this.entries.get(id);
376
+ if (!e || e.pty.exited) return false;
377
+ e.pty.write(data);
378
+ return true;
379
+ }
380
+ /** Last writer wins — with several clients attached (browser + a real
381
+ * terminal) the one that most recently resized sets the grid, like
382
+ * tmux's `window-size latest`. */
383
+ resize(id, cols, rows) {
384
+ const e = this.entries.get(id);
385
+ if (!e || e.pty.exited) return;
386
+ if (cols < 2 || rows < 2 || cols === e.cols && rows === e.rows) return;
387
+ e.cols = cols;
388
+ e.rows = rows;
389
+ e.pty.resize(cols, rows);
390
+ }
391
+ /**
392
+ * Attach a client: the screen snapshot, a disposer, and — for a real
393
+ * session — `ready`, the snapshot once the screen has parsed everything
394
+ * that arrived before this attach, then `start()` once it was sent.
395
+ *
396
+ * Output reaches clients the moment it arrives, but the screen parses it a
397
+ * moment later (xterm's write is queued). A client attaching in between got
398
+ * a snapshot without that output and subscribed too late to be sent it: it
399
+ * was lost (a Linux PTY answers fast enough to land there). So output
400
+ * arriving from the attach on is held for this client until `start()`, and
401
+ * `ready` is the screen exactly as of the attach — nothing lost, nothing
402
+ * twice. `replay` (taken at once) is for screens with no parsing step.
403
+ */
404
+ attach(id, onData, onExit) {
405
+ const e = this.entries.get(id);
406
+ if (!e) return null;
407
+ const exitedWith = e.pty.exited ? e.exitCode ?? 0 : null;
408
+ const settled = e.pty.serializeSettled;
409
+ let held = settled ? [] : null;
410
+ const sub = (d) => held ? held.push(d) : onData(d);
411
+ if (exitedWith === null) {
412
+ e.subscribers.add(sub);
413
+ e.exitSubscribers.add(onExit);
414
+ }
415
+ const snapshot = (data) => ({ data, cols: e.cols, rows: e.rows });
416
+ const replay = snapshot(e.pty.serialize?.() || e.replay);
417
+ return {
418
+ exitedWith,
419
+ replay,
420
+ ready: settled ? settled.call(e.pty).then((d) => snapshot(d || e.replay)) : Promise.resolve(replay),
421
+ start: () => {
422
+ const q = held;
423
+ held = null;
424
+ for (const d of q ?? []) onData(d);
425
+ },
426
+ detach: () => {
427
+ e.subscribers.delete(sub);
428
+ e.exitSubscribers.delete(onExit);
429
+ }
430
+ };
431
+ }
432
+ /**
433
+ * Explicit kill (worktree removal, user closed the session). Removed
434
+ * from the persisted list so it is NOT restored.
435
+ *
436
+ * Resolves once the process has actually exited (or after `timeoutMs`):
437
+ * on Windows a just-killed process still holds its cwd for a moment, and
438
+ * the caller's next step is usually deleting that very directory.
439
+ */
440
+ async kill(id, timeoutMs = 3e3) {
441
+ const e = this.entries.get(id);
442
+ if (!e) return;
443
+ this.entries.delete(id);
444
+ e.subscribers.clear();
445
+ e.exitSubscribers.clear();
446
+ const exited = e.pty.exited ? Promise.resolve() : new Promise((resolve) => {
447
+ const timer = setTimeout(resolve, timeoutMs);
448
+ e.pty.onExit = () => {
449
+ clearTimeout(timer);
450
+ resolve();
451
+ };
452
+ });
453
+ e.pty.dispose();
454
+ await Promise.all([exited, this.persist()]);
455
+ }
456
+ /**
457
+ * Respawn everything in the persisted list. Called once at host startup.
458
+ * Worktrees that no longer exist are dropped.
459
+ */
460
+ async restore() {
461
+ const saved = this.readPersisted();
462
+ const restored = [];
463
+ for (const [id, entry] of Object.entries(saved)) {
464
+ if (!this.cwdExists(entry.cwd)) continue;
465
+ try {
466
+ this.spawn(id, entry, true);
467
+ restored.push(id);
468
+ } catch (err) {
469
+ logSwallowed(`restore session ${id} in ${entry.cwd}`, err);
470
+ }
471
+ }
472
+ await this.persist();
473
+ return restored;
474
+ }
475
+ /** Host shutdown: kill every PTY but KEEP the persisted list, so the next
476
+ * host start restores them. */
477
+ disposeAllKeepingState() {
478
+ for (const e of this.entries.values()) {
479
+ e.pty.onExit = void 0;
480
+ e.subscribers.clear();
481
+ e.exitSubscribers.clear();
482
+ e.pty.dispose();
483
+ }
484
+ this.entries.clear();
485
+ }
486
+ /** Resolves once every queued persistence write has landed. */
487
+ flush() {
488
+ return this.writeChain;
489
+ }
490
+ info(e) {
491
+ return {
492
+ id: e.id,
493
+ cwd: e.spec.cwd,
494
+ pid: e.pty.pty.pid,
495
+ exited: e.pty.exited,
496
+ cols: e.cols,
497
+ rows: e.rows,
498
+ startedAt: e.startedAt,
499
+ restored: e.restored,
500
+ clients: e.subscribers.size,
501
+ lastOutputAt: new Date(e.lastOutputAt).toISOString(),
502
+ tool: e.spec.tool.cmd
503
+ };
504
+ }
505
+ readPersisted() {
506
+ try {
507
+ return this.store.read();
508
+ } catch (err) {
509
+ logSwallowed("read the PTY restore list", err);
510
+ return {};
511
+ }
512
+ }
513
+ persist() {
514
+ const snapshot = {};
515
+ for (const e of this.entries.values()) {
516
+ snapshot[e.id] = { ...e.spec, startedAt: e.startedAt };
517
+ }
518
+ this.writeChain = this.writeChain.then(() => this.store.write(snapshot)).catch(swallow("persist the PTY restore list (next change retries)"));
519
+ return this.writeChain;
520
+ }
521
+ };
522
+
523
+ // src/core/pty/pty-host.ts
524
+ var ATTACH_PATH = /^\/ptys\/([^/?]+)\/attach(?:\?|$)/;
525
+ var PTY_PATH = /^\/ptys\/([^/?]+)(\/write|\/screen)?$/;
526
+ var MAX_BODY = 1024 * 1024;
527
+ function readBody(req) {
528
+ return new Promise((resolve, reject) => {
529
+ let size = 0;
530
+ const chunks = [];
531
+ req.on("data", (c) => {
532
+ size += c.length;
533
+ if (size > MAX_BODY) {
534
+ reject(new Error("body too large"));
535
+ req.destroy();
536
+ return;
537
+ }
538
+ chunks.push(c);
539
+ });
540
+ req.on("end", () => {
541
+ try {
542
+ const text = Buffer.concat(chunks).toString("utf-8");
543
+ resolve(text ? JSON.parse(text) : {});
544
+ } catch (err) {
545
+ reject(err);
546
+ }
547
+ });
548
+ req.on("error", reject);
549
+ });
550
+ }
551
+ function send(res, status, body) {
552
+ res.writeHead(status, { "Content-Type": "application/json" });
553
+ res.end(JSON.stringify(body));
554
+ }
555
+ function isSpawnSpec(v) {
556
+ if (!v || typeof v !== "object") return false;
557
+ const s = v;
558
+ return typeof s.cwd === "string" && s.cwd.length > 0 && !!s.tool && typeof s.tool.cmd === "string" && Array.isArray(s.tool.baseArgs);
559
+ }
560
+ async function startPtyHost(opts = {}) {
561
+ const registry = opts.registry ?? new PtyRegistry();
562
+ const token = crypto.randomBytes(24).toString("hex");
563
+ let allowedHosts = /* @__PURE__ */ new Set();
564
+ const authorized = (req, url) => {
565
+ if (!req.headers.host || !allowedHosts.has(req.headers.host)) return false;
566
+ const given = req.headers["x-work-token"] ?? url.searchParams.get("token") ?? "";
567
+ const a = Buffer.from(given);
568
+ const b = Buffer.from(token);
569
+ return a.length === b.length && crypto.timingSafeEqual(a, b);
570
+ };
571
+ const server = http.createServer(async (req, res) => {
572
+ const url = new URL(req.url ?? "/", "http://localhost");
573
+ if (!authorized(req, url)) return send(res, 403, { error: "forbidden" });
574
+ try {
575
+ if (req.method === "GET" && url.pathname === "/health") {
576
+ return send(res, 200, { version: PROTOCOL_VERSION, pid: process.pid });
577
+ }
578
+ if (req.method === "GET" && url.pathname === "/ptys") {
579
+ return send(res, 200, registry.list());
580
+ }
581
+ const m = url.pathname.match(PTY_PATH);
582
+ if (m) {
583
+ const id = decodeURIComponent(m[1]);
584
+ if (m[2] === "/screen" && req.method === "GET") {
585
+ const text = registry.screen(id);
586
+ return text === null ? send(res, 404, { error: "not found" }) : send(res, 200, { text });
587
+ }
588
+ if (m[2] === "/write" && req.method === "POST") {
589
+ const body = await readBody(req);
590
+ if (typeof body.data !== "string") return send(res, 400, { error: "data required" });
591
+ return send(res, registry.write(id, body.data) ? 200 : 404, {});
592
+ }
593
+ if (!m[2] && req.method === "POST") {
594
+ const spec = await readBody(req);
595
+ if (!isSpawnSpec(spec)) return send(res, 400, { error: "invalid spawn spec" });
596
+ if (!fs2.existsSync(spec.cwd)) return send(res, 400, { error: "cwd does not exist" });
597
+ return send(res, 200, registry.spawn(id, spec));
598
+ }
599
+ if (!m[2] && req.method === "GET") {
600
+ const info3 = registry.get(id);
601
+ return info3 ? send(res, 200, info3) : send(res, 404, { error: "not found" });
602
+ }
603
+ if (!m[2] && req.method === "DELETE") {
604
+ await registry.kill(id);
605
+ return send(res, 200, {});
606
+ }
607
+ }
608
+ return send(res, 404, { error: "not found" });
609
+ } catch (err) {
610
+ return send(res, 500, { error: err.message });
611
+ }
612
+ });
613
+ const wss = new WebSocketServer({ noServer: true });
614
+ server.on("upgrade", (req, socket, head) => {
615
+ const url = new URL(req.url ?? "/", "http://localhost");
616
+ const m = (req.url ?? "").match(ATTACH_PATH);
617
+ if (!m || !authorized(req, url)) {
618
+ socket.destroy();
619
+ return;
620
+ }
621
+ const id = decodeURIComponent(m[1]);
622
+ wss.handleUpgrade(req, socket, head, (ws) => {
623
+ const attached = registry.attach(
624
+ id,
625
+ (data) => {
626
+ try {
627
+ ws.send(Buffer.from(data, "utf-8"), { binary: true });
628
+ } catch {
629
+ }
630
+ },
631
+ (code) => {
632
+ try {
633
+ ws.send(JSON.stringify({ type: "exit", code }));
634
+ ws.close(1e3);
635
+ } catch {
636
+ }
637
+ }
638
+ );
639
+ if (!attached) {
640
+ try {
641
+ ws.send(JSON.stringify({ type: "error", message: "no such pty" }));
642
+ ws.close(1011);
643
+ } catch {
644
+ }
645
+ return;
646
+ }
647
+ void attached.ready.then((replay) => {
648
+ try {
649
+ ws.send(JSON.stringify({ type: "replay", ...replay }));
650
+ } catch {
651
+ }
652
+ if (attached.exitedWith !== null) {
653
+ try {
654
+ ws.send(JSON.stringify({ type: "exit", code: attached.exitedWith }));
655
+ ws.close(1e3);
656
+ } catch {
657
+ }
658
+ return;
659
+ }
660
+ attached.start();
661
+ });
662
+ if (attached.exitedWith !== null) return;
663
+ ws.on("message", (raw, isBinary) => {
664
+ if (isBinary) return;
665
+ let msg;
666
+ try {
667
+ msg = JSON.parse(raw.toString("utf-8"));
668
+ } catch {
669
+ return;
670
+ }
671
+ if (msg.type === "input" && typeof msg.data === "string") {
672
+ registry.write(id, msg.data);
673
+ } else if (msg.type === "resize" && Number.isInteger(msg.cols) && Number.isInteger(msg.rows)) {
674
+ registry.resize(id, msg.cols, msg.rows);
675
+ }
676
+ });
677
+ ws.on("close", () => attached.detach());
678
+ ws.on("error", () => attached.detach());
679
+ });
680
+ });
681
+ await new Promise((resolve, reject) => {
682
+ server.once("error", reject);
683
+ server.listen(0, "127.0.0.1", () => resolve());
684
+ });
685
+ const port = server.address().port;
686
+ allowedHosts = /* @__PURE__ */ new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
687
+ const info2 = { pid: process.pid, port, token, version: PROTOCOL_VERSION };
688
+ if (opts.writeInfo !== false) {
689
+ atomicWriteFile(hostInfoPath(), JSON.stringify(info2));
690
+ }
691
+ if (opts.restore !== false) {
692
+ if (!opts.registry) {
693
+ const adopted = bestEffort("adopt the old pty-sessions.json", () => adoptLegacyRestoreList(), null);
694
+ if (adopted !== null && adopted !== void 0)
695
+ report("info", `[pty-host] adopted ${adopted} session(s) from an older host's pty-sessions.json`);
696
+ }
697
+ await registry.restore();
698
+ }
699
+ return {
700
+ info: info2,
701
+ registry,
702
+ async stop() {
703
+ registry.disposeAllKeepingState();
704
+ wss.close();
705
+ await new Promise((r) => server.close(() => r()));
706
+ if (opts.writeInfo !== false) {
707
+ try {
708
+ const cur = JSON.parse(fs2.readFileSync(hostInfoPath(), "utf-8"));
709
+ if (cur.pid === process.pid) fs2.unlinkSync(hostInfoPath());
710
+ } catch {
711
+ }
712
+ }
713
+ }
714
+ };
715
+ }
716
+
717
+ // src/commands/pty-host.ts
718
+ function info(message) {
719
+ process.stderr.write(message + "\n");
720
+ }
721
+ async function stopHost(kill = killTree, probeTimeoutMs = 5e3) {
722
+ const hostInfo = readHostInfo();
723
+ if (!hostInfo) return "not-running";
724
+ const probe = await probeHostDetailed(hostInfo, probeTimeoutMs);
725
+ if (probe.kind === "timeout") {
726
+ return "unresponsive";
727
+ }
728
+ if (probe.kind !== "host" || probe.pid !== hostInfo.pid) {
729
+ try {
730
+ fs3.unlinkSync(hostInfoPath());
731
+ } catch {
732
+ }
733
+ return "stale-file";
734
+ }
735
+ const ok = kill(hostInfo.pid);
736
+ try {
737
+ fs3.unlinkSync(hostInfoPath());
738
+ } catch {
739
+ }
740
+ return ok ? "stopped" : "failed";
741
+ }
742
+ async function printStatus() {
743
+ let host;
744
+ try {
745
+ host = await findHost();
746
+ } catch (err) {
747
+ if (err instanceof PtyHostVersionError || err instanceof PtyHostBusyError) {
748
+ info(chalk.yellow(err.message));
749
+ return;
750
+ }
751
+ throw err;
752
+ }
753
+ if (!host) {
754
+ info(chalk.gray("No PTY host running."));
755
+ return;
756
+ }
757
+ const ptys = await new PtyHostClient(host).list();
758
+ const names = new Map(loadHistory().map((s) => [sessionIdFor(s), `${s.target} \xB7 ${s.branch}`]));
759
+ info(chalk.gray(`PTY host PID ${host.pid}, port ${host.port} \u2014 ${ptys.length} session(s)`));
760
+ for (const p of ptys) {
761
+ const state = p.exited ? chalk.red("exited") : chalk.green("live");
762
+ const tag = p.restored ? chalk.gray(" (restored)") : "";
763
+ info(` ${state} ${names.get(p.id) ?? p.id}${tag} ${chalk.gray(p.cwd)}`);
764
+ }
765
+ }
766
+ var ptyHostCommand = {
767
+ command: "pty-host",
768
+ describe: false,
769
+ // internal — started on demand by `work web` / `work attach`
770
+ builder: (yargs) => yargs.option("stop", { type: "boolean", default: false, describe: "Stop the PTY host (sessions restore on next start)." }).option("restart", { type: "boolean", default: false, describe: "Restart the PTY host, e.g. after upgrading work." }).option("status", { type: "boolean", default: false, describe: "List the sessions the PTY host owns." }),
771
+ handler: async (argv) => {
772
+ if (argv.status) {
773
+ await printStatus();
774
+ return;
775
+ }
776
+ if (argv.stop || argv.restart) {
777
+ const outcome = await stopHost();
778
+ info(
779
+ chalk.gray(
780
+ {
781
+ stopped: "Stopped the PTY host.",
782
+ "not-running": "No PTY host running.",
783
+ "stale-file": "No PTY host running (removed a stale discovery file; nothing was killed).",
784
+ unresponsive: "The PTY host is not responding (busy?). Nothing was stopped \u2014 try again in a moment.",
785
+ failed: "Could not stop the PTY host."
786
+ }[outcome]
787
+ )
788
+ );
789
+ if (outcome === "failed" || outcome === "unresponsive") {
790
+ process.exitCode = 1;
791
+ return;
792
+ }
793
+ if (argv.stop) return;
794
+ await new Promise((r) => setTimeout(r, 500));
795
+ const host = await ensureHost(resolveWorkBinPath(process.argv[1]));
796
+ info(chalk.gray(`PTY host restarted (PID ${host.pid}); sessions are being restored.`));
797
+ return;
798
+ }
799
+ const lock = hostStartLockPath();
800
+ ensureFile(lock, "");
801
+ const handle = await withFileLock(lock, async () => {
802
+ const running = await findHost().catch(
803
+ (err) => err instanceof PtyHostVersionError || err instanceof PtyHostBusyError ? true : null
804
+ );
805
+ if (running) return null;
806
+ return startPtyHost();
807
+ });
808
+ if (!handle) {
809
+ info(chalk.gray("PTY host already running."));
810
+ return;
811
+ }
812
+ info(chalk.gray(`PTY host listening on 127.0.0.1:${handle.info.port} (PID ${process.pid})`));
813
+ const shutdown = () => {
814
+ void handle.stop().finally(() => process.exit(0));
815
+ };
816
+ process.on("SIGINT", shutdown);
817
+ process.on("SIGTERM", shutdown);
818
+ await new Promise(() => {
819
+ });
820
+ }
821
+ };
822
+ export {
823
+ ptyHostCommand,
824
+ stopHost
825
+ };
826
+ //# sourceMappingURL=pty-host-RWIS55N4.js.map