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

main
ts 63 lines 2.6 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as FileSystem from "effect/FileSystem";
3
4 import * as HostProcess from "@t3tools/shared/HostProcess";
5 import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
6
7 const SESSION_ADDRESS_PREFIX = "DBUS_SESSION_BUS_ADDRESS=";
8
9 /**
10 * gh reads its keyring through godbus, which autolaunches a `dbus-launch` daemon that outlives gh
11 * when no session bus is configured or discoverable. On WSL and headless hosts each lookup leaks one
12 * until inotify runs out, so only then turn the bus off and let the keyring read fail.
13 */
14 export const makeGhProcess = Effect.gen(function* () {
15 const { process } = yield* SourceControlHost.SourceControlHost;
16 const fileSystem = yield* FileSystem.FileSystem;
17 const environment = yield* HostProcess.Environment;
18 const platform = yield* HostProcess.Platform;
19 const userId = yield* HostProcess.UserId;
20
21 const noBusToDiscover = Effect.gen(function* () {
22 if (platform === "darwin" || userId === undefined) return false;
23 const runtimeDir = `/run/user/${userId}`;
24 // godbus takes the bus socket if stat finds anything there, but uses `dbus-session` only
25 // when it reads as `DBUS_SESSION_BUS_ADDRESS=<address>`; otherwise it still autolaunches.
26 if (yield* fileSystem.exists(`${runtimeDir}/bus`).pipe(Effect.orElseSucceed(() => true))) {
27 return false;
28 }
29 const session = yield* fileSystem
30 .readFileString(`${runtimeDir}/dbus-session`)
31 .pipe(Effect.orElseSucceed(() => ""));
32 if (!session.startsWith(SESSION_ADDRESS_PREFIX)) return true;
33 // Trailing line breaks are not an address; a loop keeps this linear on a malformed file.
34 let end = session.length;
35 while (
36 end > SESSION_ADDRESS_PREFIX.length &&
37 (session[end - 1] === "\n" || session[end - 1] === "\r")
38 ) {
39 end--;
40 }
41 return end === SESSION_ADDRESS_PREFIX.length;
42 });
43
44 return {
45 run: (input) => {
46 // The spawn's own env extends the host's, so its address is the one gh will see.
47 const address =
48 input.env !== undefined && "DBUS_SESSION_BUS_ADDRESS" in input.env
49 ? input.env.DBUS_SESSION_BUS_ADDRESS
50 : environment.DBUS_SESSION_BUS_ADDRESS;
51 if (address && address !== "autolaunch:") return process.run(input);
52 return noBusToDiscover.pipe(
53 Effect.flatMap((missing) =>
54 process.run(
55 missing
56 ? { ...input, env: { ...input.env, DBUS_SESSION_BUS_ADDRESS: "disabled:" } }
57 : input,
58 ),
59 ),
60 );
61 },
62 } satisfies SourceControlHost.SourceControlHost["Service"]["process"];
63 });