@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, 06:00 UTC

main
ts 83 lines 2.54 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as FileSystem from "effect/FileSystem";
3 import * as Path from "effect/Path";
4 import * as ChildProcess from "effect/process/ChildProcess";
5 import * as Schedule from "effect/Schedule";
6 import * as Stream from "effect/Stream";
7
8 export const pidAlive = (pid: number) =>
9 Effect.sync(() => {
10 try {
11 process.kill(pid, 0);
12 return true;
13 } catch (error) {
14 if (typeof error === "object" && error !== null && "code" in error && error.code === "ESRCH")
15 return false;
16 throw error;
17 }
18 });
19
20 export const assertDead = (pid: number) =>
21 pidAlive(pid).pipe(
22 Effect.repeat({
23 schedule: Schedule.spaced("25 millis"),
24 until: (alive) => !alive,
25 times: 120,
26 }),
27 Effect.flatMap((alive) =>
28 alive ? Effect.fail(new Error(`Fixture PID ${pid} survived cleanup`)) : Effect.void,
29 ),
30 );
31
32 export const pgid = (pid: number) =>
33 ChildProcess.make("ps", ["-o", "pgid=", "-p", String(pid)]).pipe(
34 Effect.flatMap((child) => child.stdout.pipe(Stream.decodeText, Stream.mkString)),
35 Effect.map((text) => Number(text.trim())),
36 Effect.scoped,
37 );
38
39 export const lifecycleFixture = Effect.fn(function* (mode = "cooperative") {
40 const fs = yield* FileSystem.FileSystem;
41 const path = yield* Path.Path;
42 const directory = yield* fs.makeTempDirectoryScoped({
43 directory: "/tmp",
44 prefix: "command-lifecycle-",
45 });
46 const entry = yield* path.fromFileUrl(new URL("./lifecycle.ts", import.meta.url));
47 const manifest = path.join(directory, "pids.json");
48 const read = fs
49 .readFileString(manifest)
50 .pipe(Effect.map((text) => JSON.parse(text) as { wrapper: number; leaf: number }));
51 yield* Effect.addFinalizer(() =>
52 Effect.gen(function* () {
53 if (!(yield* fs.exists(manifest))) return;
54 const pids = yield* read;
55 yield* Effect.sync(() => {
56 for (const pid of [pids.leaf, pids.wrapper]) {
57 try {
58 process.kill(pid, "SIGKILL");
59 } catch {}
60 }
61 });
62 }).pipe(Effect.orDie),
63 );
64 const ready = fs.exists(path.join(directory, "wrapper.ready")).pipe(
65 Effect.repeat({
66 schedule: Schedule.spaced("25 millis"),
67 until: Boolean,
68 times: 300,
69 }),
70 Effect.andThen(read),
71 );
72 return {
73 directory,
74 entry,
75 ready,
76 props: {
77 command: `bun run ${entry}`,
78 env: { LIFECYCLE_DIR: directory, LIFECYCLE_MODE: mode },
79 },
80 crash: fs.writeFileString(path.join(directory, "crash"), "crash"),
81 has: (name: string) => fs.exists(path.join(directory, name)),
82 };
83 });