The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 2 | import * as Context from "effect/Context"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as FileSystem from "effect/FileSystem"; |
| 5 | import * as Layer from "effect/Layer"; |
| 6 | import * as Option from "effect/Option"; |
| 7 | import * as Path from "effect/Path"; |
| 8 | import * as Schema from "effect/Schema"; |
| 9 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 10 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 11 | |
| 12 | import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; |
| 13 | import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; |
| 14 | |
| 15 | const ProcessIdentity = Schema.Struct({ pid: Schema.Int, startTime: Schema.String }); |
| 16 | type ProcessIdentity = typeof ProcessIdentity.Type; |
| 17 | |
| 18 | const OpenCodeServerEntry = Schema.Struct({ |
| 19 | version: Schema.Literal(1), |
| 20 | pgid: Schema.Int, |
| 21 | pid: Schema.Int, |
| 22 | startTime: Schema.String, |
| 23 | command: Schema.String, |
| 24 | args: Schema.optionalKey(Schema.Array(Schema.String)), |
| 25 | port: Schema.Int, |
| 26 | stateDir: Schema.String, |
| 27 | owner: ProcessIdentity, |
| 28 | }); |
| 29 | type OpenCodeServerEntry = typeof OpenCodeServerEntry.Type; |
| 30 | const OpenCodeServerEntryJson = Schema.fromJsonString(OpenCodeServerEntry); |
| 31 | const decodeEntry = Schema.decodeUnknownOption(OpenCodeServerEntryJson); |
| 32 | const encodeEntry = Schema.encodeEffect(OpenCodeServerEntryJson); |
| 33 | |
| 34 | export class OpenCodeServerLedger extends Context.Service< |
| 35 | OpenCodeServerLedger, |
| 36 | { |
| 37 | readonly track: (server: { |
| 38 | readonly pid: number; |
| 39 | readonly port: number; |
| 40 | readonly args: ReadonlyArray<string>; |
| 41 | }) => Effect.Effect<Effect.Effect<void>>; |
| 42 | } |
| 43 | >()("@t3tools/provider-opencode/server/OpenCodeServerLedger") {} |
| 44 | |
| 45 | const ENTRY_DIRECTORY = "opencode-servers"; |
| 46 | const ENTRY_FILE = /^\d+\.json$/; |
| 47 | const STOP_POLL_INTERVAL = "50 millis"; |
| 48 | const STOP_POLL_ATTEMPTS = 40; |
| 49 | |
| 50 | interface ObservedProcess { |
| 51 | readonly pid: number; |
| 52 | readonly pgid: number; |
| 53 | readonly startTime: string; |
| 54 | readonly command: string; |
| 55 | readonly zombie: boolean; |
| 56 | } |
| 57 | |
| 58 | // ps lstart needs C locale and UTC for stable parsing. |
| 59 | const DARWIN_PS_LINE = |
| 60 | /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\w{3} \w{3} +\d{1,2} \d{2}:\d{2}:\d{2} \d{4})\s+(.*)$/; |
| 61 | |
| 62 | const parseDarwinPs = (output: string): ReadonlyArray<ObservedProcess> => |
| 63 | output.split("\n").flatMap((line) => { |
| 64 | const match = DARWIN_PS_LINE.exec(line); |
| 65 | if (match === null) return []; |
| 66 | return [ |
| 67 | { |
| 68 | pid: Number(match[1]), |
| 69 | pgid: Number(match[2]), |
| 70 | zombie: match[3]!.startsWith("Z"), |
| 71 | startTime: match[4]!, |
| 72 | command: match[5]!.trimEnd(), |
| 73 | }, |
| 74 | ]; |
| 75 | }); |
| 76 | |
| 77 | // A wrapper's forked child keeps the wrapper's command line until it execs; the |
| 78 | // serve arguments survive the exec, so they identify the server either way. |
| 79 | const runsServe = (observed: ObservedProcess, args: ReadonlyArray<string>) => |
| 80 | observed.command.endsWith(` ${args.join(" ")}`); |
| 81 | |
| 82 | const signalGroup = (pgid: number, signal: NodeJS.Signals) => { |
| 83 | try { |
| 84 | signalProcessGroup(pgid, signal); |
| 85 | } catch {} |
| 86 | }; |
| 87 | |
| 88 | const groupExists = (pgid: number) => { |
| 89 | try { |
| 90 | signalProcessGroup(pgid, 0); |
| 91 | return true; |
| 92 | } catch (cause) { |
| 93 | return (cause as NodeJS.ErrnoException | undefined)?.code !== "ESRCH"; |
| 94 | } |
| 95 | }; |
| 96 | |
| 97 | export const make = Effect.fn("OpenCodeServerLedger.make")(function* (input: { |
| 98 | readonly stateDir: string; |
| 99 | readonly ownerPid?: number; |
| 100 | }) { |
| 101 | const fs = yield* FileSystem.FileSystem; |
| 102 | const path = yield* Path.Path; |
| 103 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 104 | const platform = yield* HostProcess.Platform; |
| 105 | const directory = path.join(input.stateDir, ENTRY_DIRECTORY); |
| 106 | const recordable = platform === "linux" || platform === "darwin"; |
| 107 | |
| 108 | // A process-group scan calls this for every /proc entry; avoid a span per process. |
| 109 | const observeLinux = Effect.fnUntraced(function* (pid: number, group?: number) { |
| 110 | const stat = yield* fs.readFileString(`/proc/${pid}/stat`); |
| 111 | const fields = stat |
| 112 | .slice(stat.lastIndexOf(")") + 2) |
| 113 | .trim() |
| 114 | .split(/\s+/); |
| 115 | const pgid = Number(fields[2]); |
| 116 | const startTime = fields[19]; |
| 117 | if (!Number.isSafeInteger(pgid) || startTime === undefined) return undefined; |
| 118 | if (group !== undefined && pgid !== group) return undefined; |
| 119 | const cmdline = yield* fs.readFileString(`/proc/${pid}/cmdline`); |
| 120 | return { |
| 121 | pid, |
| 122 | pgid, |
| 123 | startTime, |
| 124 | command: cmdline.replace(/\0$/, "").replaceAll("\0", " "), |
| 125 | zombie: fields[0] === "Z", |
| 126 | } satisfies ObservedProcess; |
| 127 | }); |
| 128 | |
| 129 | const psDarwin = (selection: ReadonlyArray<string>) => |
| 130 | spawner |
| 131 | .string( |
| 132 | ChildProcess.make( |
| 133 | "/bin/ps", |
| 134 | ["-ww", "-o", "pid=,pgid=,stat=,lstart=,args=", ...selection], |
| 135 | { |
| 136 | env: { LC_ALL: "C", TZ: "UTC" }, |
| 137 | extendEnv: true, |
| 138 | stdin: "ignore", |
| 139 | stderr: "ignore", |
| 140 | }, |
| 141 | ), |
| 142 | ) |
| 143 | .pipe(Effect.timeout("5 seconds"), Effect.map(parseDarwinPs)); |
| 144 | |
| 145 | const observe = (pid: number): Effect.Effect<ObservedProcess | undefined> => { |
| 146 | if (platform === "linux") return observeLinux(pid).pipe(Effect.orElseSucceed(() => undefined)); |
| 147 | if (platform === "darwin") { |
| 148 | return psDarwin(["-p", String(pid)]).pipe( |
| 149 | Effect.map((found) => found.find((candidate) => candidate.pid === pid)), |
| 150 | Effect.orElseSucceed(() => undefined), |
| 151 | ); |
| 152 | } |
| 153 | return Effect.undefined; |
| 154 | }; |
| 155 | |
| 156 | const observeGroup = (pgid: number): Effect.Effect<ReadonlyArray<ObservedProcess>> => { |
| 157 | if (platform === "linux") { |
| 158 | return fs.readDirectory("/proc").pipe( |
| 159 | Effect.flatMap((names) => |
| 160 | Effect.forEach( |
| 161 | names.filter((name) => /^\d+$/.test(name)), |
| 162 | (name) => observeLinux(Number(name), pgid).pipe(Effect.orElseSucceed(() => undefined)), |
| 163 | { concurrency: 16 }, |
| 164 | ), |
| 165 | ), |
| 166 | Effect.map((found) => found.filter((candidate) => candidate !== undefined)), |
| 167 | Effect.orElseSucceed(() => []), |
| 168 | ); |
| 169 | } |
| 170 | if (platform === "darwin") { |
| 171 | return psDarwin(["-A"]).pipe( |
| 172 | Effect.map((found) => found.filter((candidate) => candidate.pgid === pgid)), |
| 173 | Effect.orElseSucceed(() => []), |
| 174 | ); |
| 175 | } |
| 176 | return Effect.succeed([]); |
| 177 | }; |
| 178 | |
| 179 | const isRunning = (identity: ProcessIdentity) => |
| 180 | observe(identity.pid).pipe( |
| 181 | Effect.map( |
| 182 | (observed) => |
| 183 | observed !== undefined && !observed.zombie && observed.startTime === identity.startTime, |
| 184 | ), |
| 185 | ); |
| 186 | |
| 187 | const ownerPid = input.ownerPid ?? process.pid; |
| 188 | const ownerProcess = yield* observe(ownerPid); |
| 189 | const owner = |
| 190 | ownerProcess === undefined ? undefined : { pid: ownerPid, startTime: ownerProcess.startTime }; |
| 191 | |
| 192 | const track: OpenCodeServerLedger["Service"]["track"] = Effect.fn("OpenCodeServerLedger.track")( |
| 193 | function* (server) { |
| 194 | if (!recordable) return Effect.void; |
| 195 | const pgid = server.pid; |
| 196 | // Any live member identifies a leaderless group; pgid cannot be reused while members remain. |
| 197 | const leader = yield* observe(pgid); |
| 198 | const members = |
| 199 | leader !== undefined && !leader.zombie && leader.pgid === pgid |
| 200 | ? [leader] |
| 201 | : (yield* observeGroup(pgid)).filter((candidate) => !candidate.zombie); |
| 202 | const member = members.find((candidate) => runsServe(candidate, server.args)) ?? members[0]; |
| 203 | if (owner === undefined || member === undefined) { |
| 204 | if (groupExists(pgid)) { |
| 205 | yield* Effect.logWarning( |
| 206 | "Could not record an OpenCode server; it will keep running if this server crashes", |
| 207 | { pid: pgid, port: server.port }, |
| 208 | ); |
| 209 | } |
| 210 | return Effect.void; |
| 211 | } |
| 212 | const entryPath = path.join(directory, `${pgid}.json`); |
| 213 | const entry: OpenCodeServerEntry = { |
| 214 | version: 1, |
| 215 | pgid, |
| 216 | pid: member.pid, |
| 217 | startTime: member.startTime, |
| 218 | command: member.command, |
| 219 | args: server.args, |
| 220 | port: server.port, |
| 221 | stateDir: input.stateDir, |
| 222 | owner, |
| 223 | }; |
| 224 | yield* writeFileStringAtomically({ |
| 225 | filePath: entryPath, |
| 226 | contents: yield* encodeEntry(entry), |
| 227 | }).pipe( |
| 228 | Effect.provideService(FileSystem.FileSystem, fs), |
| 229 | Effect.provideService(Path.Path, path), |
| 230 | ); |
| 231 | return fs |
| 232 | .remove(entryPath, { force: true }) |
| 233 | .pipe( |
| 234 | Effect.catchCause((cause) => |
| 235 | Effect.logWarning("Could not forget a stopped OpenCode server", { cause }), |
| 236 | ), |
| 237 | ); |
| 238 | }, |
| 239 | Effect.catchCause((cause) => |
| 240 | Effect.logWarning("Could not record an OpenCode server process", { cause }).pipe( |
| 241 | Effect.as(Effect.void), |
| 242 | ), |
| 243 | ), |
| 244 | ); |
| 245 | |
| 246 | // Signals only a group whose recorded member still has the same pid, start |
| 247 | // time, and group and still has the same command line or serve arguments, so |
| 248 | // a recycled pid is never touched. |
| 249 | const stopOrphan = Effect.fn("OpenCodeServerLedger.stopOrphan")(function* ( |
| 250 | entry: OpenCodeServerEntry, |
| 251 | ) { |
| 252 | const observed = yield* observe(entry.pid); |
| 253 | if ( |
| 254 | observed === undefined || |
| 255 | observed.zombie || |
| 256 | observed.startTime !== entry.startTime || |
| 257 | observed.pgid !== entry.pgid || |
| 258 | (observed.command !== entry.command && |
| 259 | (entry.args === undefined || !runsServe(observed, entry.args))) |
| 260 | ) { |
| 261 | return; |
| 262 | } |
| 263 | yield* Effect.logInfo("Stopping an OpenCode server left by a previous T3 Code server", { |
| 264 | pid: entry.pgid, |
| 265 | port: entry.port, |
| 266 | }); |
| 267 | signalGroup(entry.pgid, "SIGTERM"); |
| 268 | for (let attempt = 0; attempt < STOP_POLL_ATTEMPTS && groupExists(entry.pgid); attempt++) { |
| 269 | yield* Effect.sleep(STOP_POLL_INTERVAL); |
| 270 | } |
| 271 | // The group never emptied, so its pgid cannot have been reused. |
| 272 | if (groupExists(entry.pgid)) signalGroup(entry.pgid, "SIGKILL"); |
| 273 | }); |
| 274 | |
| 275 | const reapEntry = Effect.fn("OpenCodeServerLedger.reapEntry")( |
| 276 | function* (entryPath: string) { |
| 277 | const entry = decodeEntry(yield* fs.readFileString(entryPath)); |
| 278 | if (Option.isSome(entry) && entry.value.stateDir === input.stateDir) { |
| 279 | if (yield* isRunning(entry.value.owner)) return; |
| 280 | yield* stopOrphan(entry.value); |
| 281 | } |
| 282 | yield* fs.remove(entryPath, { force: true }); |
| 283 | }, |
| 284 | (effect, entryPath) => |
| 285 | effect.pipe( |
| 286 | Effect.catchCause((cause) => |
| 287 | Effect.logWarning("Could not clean up a recorded OpenCode server", { entryPath, cause }), |
| 288 | ), |
| 289 | ), |
| 290 | ); |
| 291 | |
| 292 | const reapOrphans = Effect.gen(function* () { |
| 293 | const names = yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => [])); |
| 294 | yield* Effect.forEach( |
| 295 | names.filter((name) => ENTRY_FILE.test(name)), |
| 296 | (name) => reapEntry(path.join(directory, name)), |
| 297 | { concurrency: "unbounded", discard: true }, |
| 298 | ); |
| 299 | }); |
| 300 | |
| 301 | return { track, reapOrphans }; |
| 302 | }); |
| 303 | |
| 304 | export const layer = (input: { readonly stateDir: string }) => |
| 305 | Layer.effect( |
| 306 | OpenCodeServerLedger, |
| 307 | Effect.gen(function* () { |
| 308 | const ledger = yield* make(input); |
| 309 | yield* ledger.reapOrphans.pipe(Effect.forkScoped); |
| 310 | return OpenCodeServerLedger.of({ track: ledger.track }); |
| 311 | }), |
| 312 | ); |
| 313 | |
| 314 | export const layerTest = Layer.succeed( |
| 315 | OpenCodeServerLedger, |
| 316 | OpenCodeServerLedger.of({ |
| 317 | track: Effect.fn("OpenCodeServerLedger.track")(function () { |
| 318 | return Effect.succeed(Effect.void); |
| 319 | }), |
| 320 | }), |
| 321 | ); |