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
| 1 | // @effect-diagnostics nodeBuiltinImport:off -- the SDK's synchronous spawn callback must record ownership before releasing the child. |
| 2 | import * as NodeCrypto from "node:crypto"; |
| 3 | import * as NodeFS from "node:fs"; |
| 4 | import * as NodeOS from "node:os"; |
| 5 | import * as NodePath from "node:path"; |
| 6 | |
| 7 | import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; |
| 8 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 9 | import * as Context from "effect/Context"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Layer from "effect/Layer"; |
| 12 | import * as Schema from "effect/Schema"; |
| 13 | |
| 14 | import * as ServerConfig from "../config.ts"; |
| 15 | |
| 16 | const ProcessIdentity = Schema.Struct({ |
| 17 | pid: Schema.Int.check(Schema.isBetween({ minimum: 2, maximum: Number.MAX_SAFE_INTEGER })), |
| 18 | startTime: Schema.String, |
| 19 | }); |
| 20 | const OwnershipRecord = Schema.Struct({ |
| 21 | version: Schema.Literal(1), |
| 22 | instanceId: Schema.String, |
| 23 | hostname: Schema.String, |
| 24 | stateDir: Schema.String, |
| 25 | owner: ProcessIdentity, |
| 26 | processes: Schema.Array(Schema.Struct({ ...ProcessIdentity.fields, pgid: Schema.Int })), |
| 27 | }); |
| 28 | const decodeRecord = Schema.decodeUnknownSync(Schema.fromJsonString(OwnershipRecord)); |
| 29 | |
| 30 | // A concurrent exit can remove the record. Incomplete/unknown records never authorize a signal. |
| 31 | const readRecord = (recordPath: string) => { |
| 32 | try { |
| 33 | return decodeRecord(NodeFS.readFileSync(recordPath, "utf8")); |
| 34 | } catch { |
| 35 | return undefined; |
| 36 | } |
| 37 | }; |
| 38 | |
| 39 | export const ProviderProcesses = Context.Reference<{ |
| 40 | readonly register?: (pid: number) => () => void; |
| 41 | readonly hasOtherLiveOwner: boolean; |
| 42 | }>("t3/process/ProviderProcesses", { defaultValue: () => ({ hasOtherLiveOwner: false }) }); |
| 43 | |
| 44 | const make = Effect.gen(function* () { |
| 45 | const platform = yield* HostProcess.Platform; |
| 46 | if (platform !== "linux") return { hasOtherLiveOwner: false }; |
| 47 | const { stateDir } = yield* ServerConfig.ServerConfig; |
| 48 | const directory = NodePath.join(stateDir, "provider-processes"); |
| 49 | const hostname = NodeOS.hostname(); |
| 50 | const boot = NodeFS.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(); |
| 51 | const controller = AcpSessionRuntime.makePosixProcessTreeController(platform); |
| 52 | const identity = (pid: number) => { |
| 53 | const observed = controller.identity(pid); |
| 54 | if (observed === undefined || AcpSessionRuntime.posixProcessIsZombie(observed)) |
| 55 | return undefined; |
| 56 | return { ...observed, startTime: `${boot}:${observed.startTime}` }; |
| 57 | }; |
| 58 | const matches = (expected: typeof ProcessIdentity.Type) => |
| 59 | identity(expected.pid)?.startTime === expected.startTime; |
| 60 | const kill = (survivor: typeof ProcessIdentity.Type) => { |
| 61 | try { |
| 62 | controller.signalProcess(survivor.pid, "SIGKILL"); |
| 63 | } catch {} |
| 64 | }; |
| 65 | const owner = identity(process.pid); |
| 66 | if (owner === undefined) return yield* Effect.die(new Error("Cannot identify provider owner")); |
| 67 | NodeFS.mkdirSync(directory, { recursive: true }); |
| 68 | |
| 69 | const writeRecord = (processes: (typeof OwnershipRecord.Type)["processes"]) => { |
| 70 | const instanceId = NodeCrypto.randomUUID(); |
| 71 | const recordPath = NodePath.join(directory, `${instanceId}.json`); |
| 72 | const pendingPath = `${recordPath}.pending`; |
| 73 | NodeFS.writeFileSync( |
| 74 | pendingPath, |
| 75 | JSON.stringify({ |
| 76 | version: 1, |
| 77 | instanceId, |
| 78 | hostname, |
| 79 | stateDir, |
| 80 | owner: { pid: owner.pid, startTime: owner.startTime }, |
| 81 | processes, |
| 82 | } satisfies typeof OwnershipRecord.Type), |
| 83 | ); |
| 84 | NodeFS.renameSync(pendingPath, recordPath); |
| 85 | return () => NodeFS.rmSync(recordPath, { force: true }); |
| 86 | }; |
| 87 | // Publish the server identity even before its first provider. Another server |
| 88 | // using this home must not stop the shared systemd slice while we are alive. |
| 89 | const forgetOwner = writeRecord([]); |
| 90 | yield* Effect.addFinalizer(() => Effect.sync(forgetOwner)); |
| 91 | let hasOtherLiveOwner = false; |
| 92 | |
| 93 | // Only immutable per-launch records are shared between server instances. A |
| 94 | // live owner's records belong to that server, even when it uses this home. |
| 95 | for (const file of NodeFS.readdirSync(directory)) { |
| 96 | if (!file.endsWith(".json")) continue; |
| 97 | const recordPath = NodePath.join(directory, file); |
| 98 | const record = readRecord(recordPath); |
| 99 | if (record === undefined) continue; |
| 100 | if (record.hostname !== hostname || record.stateDir !== stateDir) continue; |
| 101 | if (matches(record.owner)) { |
| 102 | if (record.owner.pid !== process.pid) hasOtherLiveOwner = true; |
| 103 | continue; |
| 104 | } |
| 105 | let survived = false; |
| 106 | for (const survivor of record.processes) { |
| 107 | if (survivor.pid === process.pid || !matches(survivor)) continue; |
| 108 | // Never infer ownership from argv, executable names, or group membership. |
| 109 | // As in the ACP controller, starttime blocks reuse between observations. |
| 110 | // Node has no pidfd_send_signal, so the final read-to-signal race remains. |
| 111 | kill(survivor); |
| 112 | for (let attempt = 0; matches(survivor) && !survived; attempt++) { |
| 113 | survived = attempt === 100; |
| 114 | if (!survived) yield* Effect.sleep("10 millis"); |
| 115 | } |
| 116 | } |
| 117 | // Like a failed slice stop, an unkillable CLI must not keep the server down; |
| 118 | // its record stays so the next start retries. |
| 119 | if (survived) { |
| 120 | yield* Effect.logWarning("Could not stop a provider left by a previous server", { file }); |
| 121 | continue; |
| 122 | } |
| 123 | NodeFS.rmSync(recordPath, { force: true }); |
| 124 | } |
| 125 | |
| 126 | return { |
| 127 | hasOtherLiveOwner, |
| 128 | register: (pid: number) => { |
| 129 | const provider = identity(pid); |
| 130 | if (provider === undefined || provider.ppid !== process.pid) { |
| 131 | throw new Error("Cannot identify spawned provider"); |
| 132 | } |
| 133 | // A rename keeps startup from seeing a partial write. The child is gated |
| 134 | // until this returns, so an abrupt death cannot leave an unrecorded CLI. |
| 135 | return writeRecord([{ pid, startTime: provider.startTime, pgid: provider.pgid }]); |
| 136 | }, |
| 137 | }; |
| 138 | }); |
| 139 | |
| 140 | export const layer = Layer.effect(ProviderProcesses, make); |