@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 163 lines 5.37 KB
Raw
1 import * as Duration from "effect/Duration";
2 import * as Effect from "effect/Effect";
3 import * as ChildProcess from "effect/process/ChildProcess";
4 import type { ChildProcessHandle } from "effect/process/ChildProcessSpawner";
5 import * as Schedule from "effect/Schedule";
6 import type * as Scope from "effect/Scope";
7 import * as Stream from "effect/Stream";
8
9 /**
10 * Wait for the child to exit (with timeout). Uses `handle.isRunning`
11 * rather than `handle.exitCode` because the latter raises a
12 * `PlatformError` for processes killed by signal (no exit code), which
13 * is a perfectly normal outcome for the SIGKILL test cases.
14 */
15 export const waitForExit = (
16 handle: ChildProcessHandle,
17 timeout: Duration.Input,
18 ): Effect.Effect<void, Error> =>
19 handle.isRunning.pipe(
20 Effect.orElseSucceed(() => false),
21 Effect.repeat({
22 schedule: Schedule.spaced(Duration.millis(50)),
23 until: (running) => !running,
24 }),
25 Effect.timeout(timeout),
26 Effect.catchTag("TimeoutError", () => Effect.fail(new Error("child did not exit in time"))),
27 );
28
29 export const assertPidExited = (pid: number): Effect.Effect<void, Error> =>
30 isAlive(pid).pipe(
31 Effect.orElseSucceed(() => false),
32 Effect.repeat({
33 schedule: Schedule.spaced(Duration.millis(50)),
34 until: (alive) => !alive,
35 }),
36 Effect.timeout("5 seconds"),
37 Effect.catchTag("TimeoutError", () => Effect.fail(new Error("child did not exit in time"))),
38 );
39
40 /**
41 * `process.kill(pid, 0)` is a sync syscall that probes a pid we don't
42 * own a handle to (e.g. a grandchild spawned by the parent fixture).
43 * Wrapped in `Effect.sync` so it participates in the runtime.
44 */
45 export const isAlive = (pid: number): Effect.Effect<boolean> =>
46 Effect.sync(() => {
47 try {
48 process.kill(pid, 0);
49 return true;
50 } catch {
51 return false;
52 }
53 });
54
55 /**
56 * Resolves the pid currently LISTENing on the port of `wsUrl`. Uses an
57 * `lsof` invocation (`netstat -ano` on Windows, which has no `lsof`); we
58 * don't own a handle to whatever process is listening so there's no
59 * ChildProcessHandle equivalent.
60 */
61 export const pidListeningOn = (wsUrl: string) => {
62 const port = new URL(wsUrl).port;
63 if (process.platform === "win32") {
64 return ChildProcess.make("netstat", ["-ano", "-p", "TCP"], {
65 stdout: "pipe",
66 }).pipe(
67 Effect.flatMap((handle) => handle.stdout.pipe(Stream.decodeText, Stream.mkString)),
68 Effect.map((stdout) => {
69 // Columns: Proto | Local Address | Foreign Address | State | PID
70 const line = stdout
71 .split("\n")
72 .find((l) => l.includes("LISTENING") && l.includes(`:${port} `));
73 return Number.parseInt(line?.trim().split(/\s+/).at(-1) ?? "", 10);
74 }),
75 );
76 }
77 return ChildProcess.make("lsof", [`-iTCP:${port}`, "-sTCP:LISTEN", "-t"], {
78 stdout: "pipe",
79 }).pipe(
80 Effect.flatMap((handle) => handle.stdout.pipe(Stream.decodeText, Stream.mkString)),
81 Effect.map((stdout) => Number.parseInt(stdout.trim().split("\n")[0]!, 10)),
82 );
83 };
84
85 /**
86 * POSIX process-group id of a pid via `ps` (no Node API exposes another
87 * process's pgid). Returns NaN when the pid is gone.
88 */
89 export const pgidOf = (pid: number) =>
90 ChildProcess.make("ps", ["-o", "pgid=", "-p", String(pid)], {
91 stdout: "pipe",
92 }).pipe(
93 Effect.flatMap((handle) => handle.stdout.pipe(Stream.decodeText, Stream.mkString)),
94 Effect.map((stdout) => Number.parseInt(stdout.trim(), 10)),
95 );
96
97 /** Send a signal to a pid we don't own a handle to. */
98 export const killPid = (pid: number, signal: NodeJS.Signals): Effect.Effect<void> =>
99 Effect.sync(() => {
100 try {
101 process.kill(pid, signal);
102 } catch {}
103 });
104
105 /**
106 * Open a WebSocket inside a scope so it's reliably closed at scope
107 * end. Resolves once `open` fires or fails on error / close.
108 */
109 export const openWebSocket = (url: string | URL): Effect.Effect<WebSocket, Error, Scope.Scope> =>
110 Effect.acquireRelease(
111 Effect.callback<WebSocket, Error>((resume) => {
112 const ws = new WebSocket(url);
113 const cleanup = () => {
114 ws.removeEventListener("open", onOpen);
115 ws.removeEventListener("error", onError);
116 };
117 const onOpen = () => {
118 cleanup();
119 resume(Effect.succeed(ws));
120 };
121 const onError = () => {
122 cleanup();
123 try {
124 ws.close();
125 } catch {}
126 resume(Effect.fail(new Error(`websocket connect failed: ${url}`)));
127 };
128 ws.addEventListener("open", onOpen, { once: true });
129 ws.addEventListener("error", onError, { once: true });
130 }),
131 (ws) =>
132 Effect.sync(() => {
133 try {
134 ws.close();
135 } catch {}
136 }),
137 );
138
139 /** Probe whether a websocket can be opened. Never fails. */
140 export const canOpenWebSocket = (
141 url: string | URL,
142 timeout: Duration.Input = Duration.millis(1_500),
143 ): Effect.Effect<boolean> =>
144 Effect.callback<boolean>((resume) => {
145 const ws = new WebSocket(url);
146 let settled = false;
147 const settle = (v: boolean) => {
148 if (settled) return;
149 settled = true;
150 try {
151 ws.close();
152 } catch {}
153 resume(Effect.succeed(v));
154 };
155 ws.addEventListener("open", () => settle(true), { once: true });
156 ws.addEventListener("error", () => settle(false), { once: true });
157 ws.addEventListener("close", () => settle(false), { once: true });
158 }).pipe(
159 Effect.timeoutOrElse({
160 duration: timeout,
161 orElse: () => Effect.succeed(false),
162 }),
163 );