pi-suite 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/README.zh-CN.md +101 -0
  4. package/package.json +63 -4
  5. package/skills/pi-suite-jobs/SKILL.md +76 -0
  6. package/skills/pi-suite-workflow/SKILL.md +114 -0
  7. package/src/agents/catalog.ts +80 -0
  8. package/src/agents/child.ts +79 -0
  9. package/src/agents/commands.ts +17 -0
  10. package/src/agents/defaults.ts +78 -0
  11. package/src/agents/history.ts +112 -0
  12. package/src/agents/index.ts +211 -0
  13. package/src/agents/manager.ts +438 -0
  14. package/src/agents/mentions/clone.ts +51 -0
  15. package/src/agents/mentions/grammar.ts +64 -0
  16. package/src/agents/mentions/index.ts +76 -0
  17. package/src/agents/mentions/provider.ts +79 -0
  18. package/src/agents/model-editor.ts +95 -0
  19. package/src/agents/models.ts +43 -0
  20. package/src/agents/output/schema.ts +101 -0
  21. package/src/agents/output/tool.ts +98 -0
  22. package/src/agents/parent.ts +13 -0
  23. package/src/agents/questions.ts +63 -0
  24. package/src/agents/records.ts +90 -0
  25. package/src/agents/registry.ts +20 -0
  26. package/src/agents/render.ts +85 -0
  27. package/src/agents/resources/context.ts +48 -0
  28. package/src/agents/resources/loader.ts +86 -0
  29. package/src/agents/resources/memory.ts +67 -0
  30. package/src/agents/resources/packages.ts +96 -0
  31. package/src/agents/resources/paths.ts +8 -0
  32. package/src/agents/resources/prompts.ts +11 -0
  33. package/src/agents/resources/scope.ts +147 -0
  34. package/src/agents/resources/selectors.ts +186 -0
  35. package/src/agents/retry.ts +20 -0
  36. package/src/agents/rpc/handlers.ts +62 -0
  37. package/src/agents/rpc/index.ts +73 -0
  38. package/src/agents/rpc/options.ts +44 -0
  39. package/src/agents/run-groups.ts +16 -0
  40. package/src/agents/runner.ts +131 -0
  41. package/src/agents/runtime.ts +40 -0
  42. package/src/agents/schedules/index.ts +136 -0
  43. package/src/agents/schedules/menu.ts +38 -0
  44. package/src/agents/schedules/parse.ts +42 -0
  45. package/src/agents/schedules/store.ts +78 -0
  46. package/src/agents/schema.ts +5 -0
  47. package/src/agents/session.ts +29 -0
  48. package/src/agents/tools.ts +177 -0
  49. package/src/agents/types.ts +87 -0
  50. package/src/agents/ui/index.ts +42 -0
  51. package/src/agents/ui/runs.ts +122 -0
  52. package/src/agents/ui/types.ts +91 -0
  53. package/src/agents/viewer-info.ts +36 -0
  54. package/src/agents/viewer.ts +160 -0
  55. package/src/agents/workflow/collisions.ts +124 -0
  56. package/src/agents/workflow/entry.ts +93 -0
  57. package/src/agents/workflow/host.ts +119 -0
  58. package/src/agents/workflow/index.ts +100 -0
  59. package/src/agents/workflow/journal.ts +147 -0
  60. package/src/agents/workflow/literal.ts +57 -0
  61. package/src/agents/workflow/manager.ts +169 -0
  62. package/src/agents/workflow/meta.ts +323 -0
  63. package/src/agents/workflow/progress/format.ts +184 -0
  64. package/src/agents/workflow/progress/index.ts +3 -0
  65. package/src/agents/workflow/progress/model.ts +224 -0
  66. package/src/agents/workflow/progress/types.ts +144 -0
  67. package/src/agents/workflow/render.ts +46 -0
  68. package/src/agents/workflow/runtime/helpers.ts +236 -0
  69. package/src/agents/workflow/runtime/index.ts +3 -0
  70. package/src/agents/workflow/runtime/run.ts +646 -0
  71. package/src/agents/workflow/runtime/types.ts +273 -0
  72. package/src/agents/workflow/saved.ts +74 -0
  73. package/src/agents/workflow/store.ts +23 -0
  74. package/src/agents/workflow/task.ts +277 -0
  75. package/src/agents/workflow/tool-description.ts +32 -0
  76. package/src/agents/workflow/tools.ts +66 -0
  77. package/src/agents/workflow/ui/menu.ts +144 -0
  78. package/src/agents/workflow/ui/progress.ts +91 -0
  79. package/src/agents/workflow/worker/bootstrap.ts +316 -0
  80. package/src/agents/workflow/worker/flow.ts +218 -0
  81. package/src/agents/workflow/worker/index.ts +7 -0
  82. package/src/agents/workflow/worker/scope.ts +215 -0
  83. package/src/ask/.gitkeep +0 -0
  84. package/src/ask/form.ts +67 -0
  85. package/src/ask/index.ts +73 -0
  86. package/src/ask/keys.ts +32 -0
  87. package/src/ask/layout.ts +78 -0
  88. package/src/ask/queue.ts +40 -0
  89. package/src/ask/render.ts +62 -0
  90. package/src/ask/result.ts +56 -0
  91. package/src/ask/schema.ts +67 -0
  92. package/src/ask/tool-render.ts +49 -0
  93. package/src/ask/view.ts +406 -0
  94. package/src/goal/.gitkeep +0 -0
  95. package/src/goal/activity.ts +50 -0
  96. package/src/goal/commands.ts +75 -0
  97. package/src/goal/context.ts +36 -0
  98. package/src/goal/index.ts +38 -0
  99. package/src/goal/manager.ts +386 -0
  100. package/src/goal/presentation.ts +15 -0
  101. package/src/goal/render.ts +36 -0
  102. package/src/goal/snapshot.ts +78 -0
  103. package/src/goal/state.ts +39 -0
  104. package/src/goal/store.ts +59 -0
  105. package/src/goal/tools.ts +59 -0
  106. package/src/goal/wait.ts +39 -0
  107. package/src/index.ts +20 -0
  108. package/src/jobs/backends/linux-tree.ts +87 -0
  109. package/src/jobs/backends/pipe.ts +74 -0
  110. package/src/jobs/backends/process.ts +79 -0
  111. package/src/jobs/backends/pty-job.ts +45 -0
  112. package/src/jobs/backends/pty.ts +502 -0
  113. package/src/jobs/backends/windows-tree.ts +289 -0
  114. package/src/jobs/commands.ts +7 -0
  115. package/src/jobs/control.ts +13 -0
  116. package/src/jobs/index.ts +331 -0
  117. package/src/jobs/launch/config.ts +26 -0
  118. package/src/jobs/launch/name.ts +16 -0
  119. package/src/jobs/launch/presets.ts +61 -0
  120. package/src/jobs/log-viewer.ts +147 -0
  121. package/src/jobs/manager.ts +507 -0
  122. package/src/jobs/monitors/compile.ts +101 -0
  123. package/src/jobs/monitors/hands-free.ts +108 -0
  124. package/src/jobs/monitors/runtime.ts +165 -0
  125. package/src/jobs/output.ts +54 -0
  126. package/src/jobs/query.ts +62 -0
  127. package/src/jobs/render.ts +103 -0
  128. package/src/jobs/runtime.ts +89 -0
  129. package/src/jobs/state.ts +25 -0
  130. package/src/jobs/store.ts +168 -0
  131. package/src/jobs/terminal/keys.ts +292 -0
  132. package/src/jobs/terminal/protocol.ts +37 -0
  133. package/src/jobs/terminal/read.ts +131 -0
  134. package/src/jobs/terminal/render.ts +70 -0
  135. package/src/jobs/terminal/screen.ts +92 -0
  136. package/src/jobs/terminal/session.ts +100 -0
  137. package/src/jobs/terminal/shell.ts +22 -0
  138. package/src/jobs/terminal/snapshot.ts +8 -0
  139. package/src/jobs/terminal/visible-text.ts +53 -0
  140. package/src/jobs/tools.ts +203 -0
  141. package/src/jobs/types.ts +60 -0
  142. package/src/jobs/viewer/component.ts +209 -0
  143. package/src/jobs/viewer/metadata.ts +9 -0
  144. package/src/jobs/viewer.ts +149 -0
  145. package/src/jobs/workspace.ts +31 -0
  146. package/src/runtime/.gitkeep +0 -0
  147. package/src/runtime/binding.ts +26 -0
  148. package/src/runtime/cli-prompt.ts +24 -0
  149. package/src/runtime/clipboard.ts +16 -0
  150. package/src/runtime/config-edit.ts +31 -0
  151. package/src/runtime/config-fields.ts +65 -0
  152. package/src/runtime/config.ts +111 -0
  153. package/src/runtime/errors.ts +11 -0
  154. package/src/runtime/json-store.ts +156 -0
  155. package/src/runtime/notification-render.ts +35 -0
  156. package/src/runtime/notifications.ts +98 -0
  157. package/src/runtime/owner.ts +54 -0
  158. package/src/runtime/read.ts +200 -0
  159. package/src/runtime/renderers.ts +50 -0
  160. package/src/runtime/responses/index.ts +108 -0
  161. package/src/runtime/responses/payload.ts +78 -0
  162. package/src/runtime/settings/index.ts +24 -0
  163. package/src/runtime/settings/view.ts +84 -0
  164. package/src/runtime/suite.ts +192 -0
  165. package/src/runtime/text.ts +6 -0
  166. package/src/runtime/tools.ts +131 -0
  167. package/src/runtime/wait-render.ts +33 -0
  168. package/src/runtime/wait.ts +134 -0
  169. package/src/tasks/commands.ts +41 -0
  170. package/src/tasks/index.ts +305 -0
  171. package/src/tasks/model.ts +152 -0
  172. package/src/tasks/presentation.ts +40 -0
  173. package/src/tasks/query.ts +38 -0
  174. package/src/tasks/render.ts +54 -0
  175. package/src/tasks/schema.ts +25 -0
  176. package/src/tasks/store.ts +164 -0
  177. package/src/tasks/tools.ts +69 -0
  178. package/src/tasks/types.ts +61 -0
  179. package/src/tasks/viewer.ts +68 -0
  180. package/src/ui/.gitkeep +0 -0
  181. package/src/ui/actions.ts +50 -0
  182. package/src/ui/browser-chrome.ts +175 -0
  183. package/src/ui/browser.ts +292 -0
  184. package/src/ui/details.ts +111 -0
  185. package/src/ui/dock/line.ts +14 -0
  186. package/src/ui/dock/rows.ts +78 -0
  187. package/src/ui/dock.ts +224 -0
  188. package/src/ui/format.ts +25 -0
  189. package/src/ui/frame.ts +8 -0
  190. package/src/ui/inline-input.ts +98 -0
  191. package/src/ui/reading.ts +105 -0
  192. package/src/ui/rendering/builtin-command.ts +34 -0
  193. package/src/ui/rendering/command.ts +60 -0
  194. package/src/ui/rendering/read-page.ts +15 -0
  195. package/src/ui/rendering/shell/bash.ts +281 -0
  196. package/src/ui/rendering/shell/index.ts +24 -0
  197. package/src/ui/rendering/shell/powershell.ts +155 -0
  198. package/src/ui/rendering/shell/spans.ts +28 -0
  199. package/src/ui/scroll.ts +111 -0
  200. package/src/ui/select.ts +67 -0
  201. package/src/ui/status.ts +67 -0
  202. package/src/ui/structured-details.ts +41 -0
  203. package/src/ui/terminal.ts +137 -0
  204. package/src/ui/ticker.ts +18 -0
  205. package/src/ui/tool-render.ts +152 -0
  206. package/src/ui/transcript.ts +140 -0
  207. package/src/ui/viewer/agent-information.ts +34 -0
  208. package/src/ui/viewer/editor.ts +18 -0
  209. package/src/ui/viewer/navigation.ts +25 -0
  210. package/themes/oh-my-pi.json +95 -0
  211. package/third-party/UPSTREAM.md +88 -0
  212. package/third-party/licenses/.gitkeep +0 -0
  213. package/third-party/licenses/oh-my-pi.txt +23 -0
  214. package/third-party/licenses/pi-ask-user.txt +21 -0
  215. package/third-party/licenses/pi-background-jobs.txt +21 -0
  216. package/third-party/licenses/pi-goal.txt +21 -0
  217. package/third-party/licenses/pi-interactive-shell.txt +25 -0
  218. package/third-party/licenses/pi-subagents.txt +21 -0
  219. package/third-party/licenses/pi-tasks.txt +21 -0
  220. package/third-party/sources.json +111 -0
@@ -0,0 +1,502 @@
1
+ // Imported from pi-interactive-shell 0.18.0 pty-process.ts (MIT, third-party/licenses/pi-interactive-shell.txt).
2
+ // Linux uses openpty plus a process-group pin so the whole PTY workload can be signalled as a group;
3
+ // other platforms use zigpty spawn (ConPTY on Windows). pi-suite stops Windows trees via windows-tree.
4
+ import { closeSync, openSync, write } from "node:fs";
5
+ import { constants as osConstants } from "node:os";
6
+ import { spawn as spawnChild, type ChildProcess } from "node:child_process";
7
+ import type { Duplex } from "node:stream";
8
+ import { StringDecoder } from "node:string_decoder";
9
+ import { ReadStream } from "node:tty";
10
+ import { hasNative, open, spawn, type IPty } from "zigpty";
11
+
12
+ export type PtyExitEvent = { exitCode: number; signal: number };
13
+
14
+ export interface PtyProcess {
15
+ readonly pid: number;
16
+ readonly processExited: boolean;
17
+ onData(listener: (data: string | Buffer) => void): { dispose(): void };
18
+ onExit(listener: (event: PtyExitEvent) => void): { dispose(): void };
19
+ write(data: string): void;
20
+ resize(cols: number, rows: number): void;
21
+ kill(signal?: NodeJS.Signals): void;
22
+ close(): void;
23
+ }
24
+
25
+ export interface PtyProcessOptions {
26
+ name: string;
27
+ cols: number;
28
+ rows: number;
29
+ cwd: string;
30
+ env: Record<string, string>;
31
+ }
32
+
33
+ class ZigPtyProcess implements PtyProcess {
34
+ constructor(private readonly pty: IPty) {}
35
+
36
+ get pid(): number {
37
+ return this.pty.pid;
38
+ }
39
+
40
+ get processExited(): boolean {
41
+ return this.pty.exitCode !== null;
42
+ }
43
+
44
+ onData(listener: (data: string | Buffer) => void): { dispose(): void } {
45
+ return this.pty.onData(listener);
46
+ }
47
+
48
+ onExit(listener: (event: PtyExitEvent) => void): { dispose(): void } {
49
+ return this.pty.onExit(listener);
50
+ }
51
+
52
+ write(data: string): void {
53
+ this.pty.write(data);
54
+ }
55
+
56
+ resize(cols: number, rows: number): void {
57
+ this.pty.resize(cols, rows);
58
+ }
59
+
60
+ kill(signal: NodeJS.Signals = "SIGHUP"): void {
61
+ if (this.processExited) return;
62
+ const groupError = process.platform !== "win32" && this.pid
63
+ ? signalProcessGroup(this.pid, signal)
64
+ : null;
65
+ this.pty.kill(signal);
66
+ if (groupError !== null) throw groupError;
67
+ }
68
+
69
+ close(): void {
70
+ this.pty.close();
71
+ }
72
+ }
73
+
74
+ // The double-forked helper stays in the command's process group without becoming
75
+ // its child or retaining the PTY slave. Its control pipe pins the PGID until the
76
+ // parent has finished natural cleanup or sent the final cancellation signal.
77
+ const BOOTSTRAP = `
78
+ (
79
+ trap '' HUP INT QUIT TERM
80
+ (
81
+ exec </dev/null >/dev/null 2>&1
82
+ while IFS= read -r _ <&3; do :; done
83
+ ) &
84
+ ) &
85
+ pin_launcher=$!
86
+ wait "$pin_launcher" || exit 125
87
+ exec 3<&-
88
+ exec < "$1" > "$1" 2>&1
89
+ shift
90
+ exec "$@"
91
+ `;
92
+
93
+ const UNIX_SANITIZE_KEYS = [
94
+ "TMUX",
95
+ "TMUX_PANE",
96
+ "STY",
97
+ "WINDOW",
98
+ "WINDOWID",
99
+ "TERMCAP",
100
+ "COLUMNS",
101
+ "LINES",
102
+ ] as const;
103
+
104
+ function signalNumber(signal: NodeJS.Signals | null): number {
105
+ return signal ? (osConstants.signals[signal] ?? 0) : 0;
106
+ }
107
+
108
+ function signalProcessGroup(pid: number, signal: NodeJS.Signals): unknown | null {
109
+ try {
110
+ process.kill(-pid, signal);
111
+ return null;
112
+ } catch (error) {
113
+ return error instanceof Error && "code" in error && error.code === "ESRCH" ? null : error;
114
+ }
115
+ }
116
+
117
+ const ignoreChildProcessError = (): void => {};
118
+
119
+ // zigpty's openpty descriptors are not close-on-exec. Keep every live raw PTY
120
+ // descriptor masked in this adapter's child spawns, including concurrent PTYs.
121
+ const rawPtyFdOwners = new Map<number, number>();
122
+
123
+ function registerRawPtyFd(fd: number): void {
124
+ rawPtyFdOwners.set(fd, (rawPtyFdOwners.get(fd) ?? 0) + 1);
125
+ }
126
+
127
+ function unregisterRawPtyFd(fd: number): void {
128
+ const owners = rawPtyFdOwners.get(fd);
129
+ if (owners === undefined) return;
130
+ if (owners === 1) rawPtyFdOwners.delete(fd);
131
+ else rawPtyFdOwners.set(fd, owners - 1);
132
+ }
133
+
134
+ function maskedChildStdio(firstThree: [number | "ignore", number | "ignore", number | "pipe"], controlPipe: boolean): {
135
+ stdio: Array<number | "ignore" | "pipe" | undefined>;
136
+ nullFd: number;
137
+ } {
138
+ const nullFd = openSync("/dev/null", "r+");
139
+ const stdio: Array<number | "ignore" | "pipe" | undefined> = [...firstThree, controlPipe ? "pipe" : nullFd];
140
+ for (const fd of rawPtyFdOwners.keys()) {
141
+ if (fd > 3) stdio[fd] = nullFd;
142
+ }
143
+ return { stdio: Array.from(stdio), nullFd };
144
+ }
145
+
146
+ class LinuxPtyProcess implements PtyProcess {
147
+ readonly pid: number;
148
+
149
+ private readonly child: ChildProcess;
150
+ private readonly master: number;
151
+ private readonly ptyPath: string;
152
+ private readonly reader: ReadStream;
153
+ private readonly decoder = new StringDecoder("utf8");
154
+ private readonly groupPin: Duplex;
155
+ private readonly processEstablished: boolean;
156
+ private readonly dataListeners: Array<(data: string | Buffer) => void> = [];
157
+ private readonly exitListeners: Array<(event: PtyExitEvent) => void> = [];
158
+ private childStatus: PtyExitEvent | null = null;
159
+ private outputFinished = false;
160
+ private terminationPending = false;
161
+ private completed = false;
162
+ private closed = false;
163
+ private decoderFlushed = false;
164
+ private resumeImmediate: ReturnType<typeof setImmediate> | null = null;
165
+ private writeQueue = Promise.resolve();
166
+ private pendingResize: { cols: number; rows: number } | null = null;
167
+ private resizeProcess: ChildProcess | null = null;
168
+ private readonly resizeWaiters: Array<() => void> = [];
169
+ private readonly childErrorHandler = (error: Error): void => {
170
+ if (this.processEstablished) {
171
+ console.error("interactive-shell: PTY child process error:", error);
172
+ return;
173
+ }
174
+ this.emitFailure("PTY process failed", error);
175
+ if (this.childStatus === null) {
176
+ this.childStatus = { exitCode: -1, signal: 0 };
177
+ this.tryComplete();
178
+ }
179
+ };
180
+ private readonly childExitHandler = (code: number | null, signal: NodeJS.Signals | null): void => {
181
+ if (this.childStatus !== null) return;
182
+ this.childStatus = {
183
+ exitCode: code ?? 0,
184
+ signal: signalNumber(signal),
185
+ };
186
+ this.tryComplete();
187
+ };
188
+
189
+ constructor(file: string, args: string[], options: PtyProcessOptions) {
190
+ const opened = open({ cols: options.cols, rows: options.rows });
191
+ registerRawPtyFd(opened.master);
192
+ registerRawPtyFd(opened.slave);
193
+ this.master = opened.master;
194
+ this.ptyPath = opened.pty;
195
+ const childEnv = { ...options.env };
196
+ for (const key of UNIX_SANITIZE_KEYS) delete childEnv[key];
197
+
198
+ let nullFd: number | null = null;
199
+ try {
200
+ const masked = maskedChildStdio([opened.slave, opened.slave, opened.slave], true);
201
+ nullFd = masked.nullFd;
202
+ this.child = spawnChild(
203
+ "/bin/sh",
204
+ ["-c", BOOTSTRAP, "pty-bootstrap", opened.pty, file, ...args],
205
+ {
206
+ cwd: options.cwd,
207
+ env: childEnv,
208
+ detached: true,
209
+ stdio: masked.stdio,
210
+ },
211
+ );
212
+ } catch (error) {
213
+ closeSync(opened.slave);
214
+ closeSync(opened.master);
215
+ unregisterRawPtyFd(opened.slave);
216
+ unregisterRawPtyFd(opened.master);
217
+ throw error;
218
+ } finally {
219
+ if (nullFd !== null) closeSync(nullFd);
220
+ }
221
+
222
+ closeSync(opened.slave);
223
+ unregisterRawPtyFd(opened.slave);
224
+ this.pid = this.child.pid ?? 0;
225
+ this.processEstablished = this.pid !== 0;
226
+ const groupPin = this.child.stdio[3];
227
+ if (!groupPin) {
228
+ closeSync(this.master);
229
+ unregisterRawPtyFd(this.master);
230
+ this.child.kill("SIGKILL");
231
+ throw new Error("Failed to establish PTY process-group ownership");
232
+ }
233
+ this.groupPin = groupPin as Duplex;
234
+
235
+ try {
236
+ this.reader = new ReadStream(this.master, {
237
+ onread: {
238
+ buffer: Buffer.allocUnsafe(64 * 1024),
239
+ callback: (bytesRead, buffer) => {
240
+ if (!this.closed && !this.outputFinished && bytesRead > 0) {
241
+ const data = this.decoder.write(Buffer.from(buffer.subarray(0, bytesRead)));
242
+ this.scheduleReaderResume();
243
+ this.emitDecoded(data);
244
+ }
245
+ return false;
246
+ },
247
+ },
248
+ });
249
+ } catch (error) {
250
+ try {
251
+ if (this.pid) process.kill(-this.pid, "SIGKILL");
252
+ else this.child.kill("SIGKILL");
253
+ } catch {
254
+ this.child.kill("SIGKILL");
255
+ }
256
+ closeSync(this.master);
257
+ unregisterRawPtyFd(this.master);
258
+ throw error;
259
+ }
260
+ this.reader.once("close", () => unregisterRawPtyFd(this.master));
261
+ this.reader.on("end", () => this.finishOutput());
262
+ this.reader.on("error", (error: NodeJS.ErrnoException) => {
263
+ if (error.code === "EIO") {
264
+ this.finishOutput();
265
+ return;
266
+ }
267
+ this.emitFailure("PTY read failed", error);
268
+ this.finishOutput();
269
+ });
270
+
271
+ this.child.once("exit", this.childExitHandler);
272
+ this.child.on("error", this.childErrorHandler);
273
+ this.scheduleReaderResume();
274
+ }
275
+
276
+ get processExited(): boolean {
277
+ return this.childStatus !== null;
278
+ }
279
+
280
+ onData(listener: (data: string | Buffer) => void): { dispose(): void } {
281
+ this.dataListeners.push(listener);
282
+ return {
283
+ dispose: () => {
284
+ const index = this.dataListeners.indexOf(listener);
285
+ if (index >= 0) this.dataListeners.splice(index, 1);
286
+ },
287
+ };
288
+ }
289
+
290
+ onExit(listener: (event: PtyExitEvent) => void): { dispose(): void } {
291
+ this.exitListeners.push(listener);
292
+ return {
293
+ dispose: () => {
294
+ const index = this.exitListeners.indexOf(listener);
295
+ if (index >= 0) this.exitListeners.splice(index, 1);
296
+ },
297
+ };
298
+ }
299
+
300
+ write(data: string): void {
301
+ if (this.closed || this.outputFinished) return;
302
+ const bytes = Buffer.from(data, "utf8");
303
+ this.writeQueue = this.writeQueue
304
+ .then(async () => {
305
+ await this.waitForResize();
306
+ await this.writeAll(bytes);
307
+ })
308
+ .catch((error: unknown) => {
309
+ if (!this.closed) console.error("PTY write failed:", error);
310
+ });
311
+ }
312
+
313
+ resize(cols: number, rows: number): void {
314
+ if (this.closed || this.outputFinished) return;
315
+ this.pendingResize = { cols, rows };
316
+ this.startNextResize();
317
+ }
318
+
319
+ kill(signal: NodeJS.Signals = "SIGHUP"): void {
320
+ if (this.closed) return;
321
+ if (signal !== "SIGKILL") this.terminationPending = true;
322
+ const groupError = this.pid && !this.groupPin.destroyed
323
+ ? signalProcessGroup(this.pid, signal)
324
+ : null;
325
+ let childError: unknown | null = null;
326
+ try {
327
+ if (!this.processExited && !this.child.kill(signal)) {
328
+ childError = new Error(`Direct PTY child ${signal} request was not accepted`);
329
+ }
330
+ } catch (error) {
331
+ childError = error;
332
+ }
333
+ if (signal === "SIGKILL") {
334
+ this.terminationPending = false;
335
+ if (groupError === null) this.releaseGroupPin();
336
+ this.tryComplete();
337
+ }
338
+ if (groupError !== null) throw groupError;
339
+ if (childError !== null) throw childError;
340
+ }
341
+
342
+ close(): void {
343
+ if (this.closed) return;
344
+ this.closed = true;
345
+ if (this.resumeImmediate !== null) {
346
+ clearImmediate(this.resumeImmediate);
347
+ this.resumeImmediate = null;
348
+ }
349
+ this.pendingResize = null;
350
+ this.resizeProcess?.kill("SIGKILL");
351
+ this.resizeProcess = null;
352
+ this.resolveResizeWaiters();
353
+ this.releaseGroupPin();
354
+ this.dataListeners.length = 0;
355
+ this.exitListeners.length = 0;
356
+ this.child.removeListener("error", this.childErrorHandler);
357
+ this.child.removeListener("exit", this.childExitHandler);
358
+ this.child.on("error", ignoreChildProcessError);
359
+ this.reader.destroy();
360
+ }
361
+
362
+ private finishOutput(): void {
363
+ if (this.closed || this.outputFinished) return;
364
+ if (this.resumeImmediate !== null) {
365
+ clearImmediate(this.resumeImmediate);
366
+ this.resumeImmediate = null;
367
+ }
368
+ if (!this.decoderFlushed) {
369
+ this.decoderFlushed = true;
370
+ this.emitDecoded(this.decoder.end());
371
+ }
372
+ this.outputFinished = true;
373
+ this.pendingResize = null;
374
+ this.resolveResizeWaiters();
375
+ this.tryComplete();
376
+ }
377
+
378
+ private emitDecoded(data: string): void {
379
+ if (!data || this.closed || this.outputFinished) return;
380
+ for (const listener of [...this.dataListeners]) {
381
+ if (this.closed) break;
382
+ listener(data);
383
+ }
384
+ }
385
+
386
+ private scheduleReaderResume(): void {
387
+ if (this.closed || this.outputFinished || this.reader.destroyed || this.resumeImmediate !== null) return;
388
+ this.resumeImmediate = setImmediate(() => {
389
+ this.resumeImmediate = null;
390
+ if (!this.closed && !this.outputFinished && !this.reader.destroyed) this.reader.resume();
391
+ });
392
+ }
393
+
394
+ private emitFailure(label: string, error: Error): void {
395
+ if (this.closed) return;
396
+ const message = `\n[${label}: ${error.message}]\n`;
397
+ for (const listener of [...this.dataListeners]) listener(message);
398
+ }
399
+
400
+ private tryComplete(): void {
401
+ if (this.closed || this.completed || this.terminationPending || !this.outputFinished || this.childStatus === null) return;
402
+ this.completed = true;
403
+ this.releaseGroupPin();
404
+ const status = this.childStatus;
405
+ const listeners = [...this.exitListeners];
406
+ this.dataListeners.length = 0;
407
+ this.exitListeners.length = 0;
408
+ for (const listener of listeners) listener(status);
409
+ }
410
+
411
+ private writeAll(bytes: Buffer): Promise<void> {
412
+ const done = Promise.withResolvers<void>();
413
+ let offset = 0;
414
+ const next = (): void => {
415
+ if (this.closed || this.outputFinished) {
416
+ done.resolve();
417
+ return;
418
+ }
419
+ write(this.master, bytes, offset, bytes.length - offset, null, (error, written) => {
420
+ if (error) {
421
+ if (error.code === "EAGAIN" || error.code === "EWOULDBLOCK") setImmediate(next);
422
+ else done.reject(error);
423
+ return;
424
+ }
425
+ offset += written;
426
+ if (offset === bytes.length) done.resolve();
427
+ else setImmediate(next);
428
+ });
429
+ };
430
+ next();
431
+ return done.promise;
432
+ }
433
+
434
+ private startNextResize(): void {
435
+ if (this.closed || this.outputFinished || this.resizeProcess !== null || this.pendingResize === null) return;
436
+ const { cols, rows } = this.pendingResize;
437
+ this.pendingResize = null;
438
+ let stderr = "";
439
+ let settled = false;
440
+ try {
441
+ const masked = maskedChildStdio(["ignore", "ignore", "pipe"], false);
442
+ let child: ChildProcess;
443
+ try {
444
+ child = spawnChild(
445
+ "/usr/bin/stty",
446
+ ["-F", this.ptyPath, "rows", String(rows), "cols", String(cols)],
447
+ { stdio: masked.stdio },
448
+ );
449
+ } finally {
450
+ closeSync(masked.nullFd);
451
+ }
452
+ this.resizeProcess = child;
453
+ child.stderr?.setEncoding("utf8");
454
+ child.stderr?.on("data", (chunk: string) => { stderr += chunk; });
455
+ child.once("error", (error) => {
456
+ if (settled) return;
457
+ settled = true;
458
+ this.finishResize(error);
459
+ });
460
+ child.once("close", (code) => {
461
+ if (settled) return;
462
+ settled = true;
463
+ this.finishResize(code === 0 ? null : new Error(stderr.trim() || `stty exited with code ${code}`));
464
+ });
465
+ } catch (error) {
466
+ this.finishResize(error instanceof Error ? error : new Error(String(error)));
467
+ }
468
+ }
469
+
470
+ private finishResize(error: Error | null): void {
471
+ this.resizeProcess = null;
472
+ if (error && !this.closed) console.error("interactive-shell: PTY resize failed:", error);
473
+ if (this.pendingResize !== null && !this.closed) this.startNextResize();
474
+ else this.resolveResizeWaiters();
475
+ }
476
+
477
+ private waitForResize(): Promise<void> {
478
+ if (this.resizeProcess === null && this.pendingResize === null) return Promise.resolve();
479
+ const done = Promise.withResolvers<void>();
480
+ this.resizeWaiters.push(done.resolve);
481
+ return done.promise;
482
+ }
483
+
484
+ private resolveResizeWaiters(): void {
485
+ for (const resolve of this.resizeWaiters.splice(0)) resolve();
486
+ }
487
+
488
+ private releaseGroupPin(): void {
489
+ if (this.groupPin.destroyed) return;
490
+ this.groupPin.destroy();
491
+ }
492
+ }
493
+
494
+ export function createPtyProcess(file: string, args: string[], options: PtyProcessOptions): PtyProcess {
495
+ if (process.platform === "linux") {
496
+ if (!hasNative) {
497
+ throw new Error("Linux interactive sessions require zigpty native PTY bindings; reinstall zigpty for this platform or provide a compatible native build.");
498
+ }
499
+ return new LinuxPtyProcess(file, args, options);
500
+ }
501
+ return new ZigPtyProcess(spawn(file, args, options));
502
+ }