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 | import * as Queue from "effect/Queue"; |
| 2 | import * as Stream from "effect/Stream"; |
| 3 | import * as Cause from "effect/Cause"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Sink from "effect/Sink"; |
| 6 | import * as Stdio from "effect/Stdio"; |
| 7 | import { ChildProcessSpawner } from "effect/process"; |
| 8 | |
| 9 | import * as AcpError from "../errors.ts"; |
| 10 | |
| 11 | const encoder = new TextEncoder(); |
| 12 | |
| 13 | export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) => |
| 14 | Stdio.make({ |
| 15 | args: Effect.succeed([]), |
| 16 | stdin: handle.stdout, |
| 17 | stdout: () => |
| 18 | Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) => |
| 19 | typeof chunk === "string" ? encoder.encode(chunk) : chunk, |
| 20 | ), |
| 21 | stderr: () => Sink.drain, |
| 22 | }); |
| 23 | |
| 24 | export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () { |
| 25 | const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>(); |
| 26 | const output = yield* Queue.unbounded<string>(); |
| 27 | const decoder = new TextDecoder(); |
| 28 | |
| 29 | return { |
| 30 | stdio: Stdio.make({ |
| 31 | args: Effect.succeed([]), |
| 32 | stdin: Stream.fromQueue(input), |
| 33 | stdout: () => |
| 34 | Sink.forEach((chunk: string | Uint8Array) => |
| 35 | Queue.offer( |
| 36 | output, |
| 37 | typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true }), |
| 38 | ), |
| 39 | ), |
| 40 | stderr: () => Sink.drain, |
| 41 | }), |
| 42 | input, |
| 43 | output, |
| 44 | }; |
| 45 | }); |
| 46 | |
| 47 | type ChildProcessTerminationHandle = Pick< |
| 48 | ChildProcessSpawner.ChildProcessHandle, |
| 49 | "exitCode" | "pid" |
| 50 | >; |
| 51 | |
| 52 | export const makeTerminationError = ( |
| 53 | handle: ChildProcessTerminationHandle, |
| 54 | ): Effect.Effect<AcpError.AcpError> => |
| 55 | Effect.match(handle.exitCode, { |
| 56 | onFailure: (cause) => { |
| 57 | // The Node spawner reports signal exits as a platform error rather than an exit code. |
| 58 | const signal = |
| 59 | cause.reason.module === "ChildProcess" && |
| 60 | cause.reason.method === "exitCode" && |
| 61 | cause.reason.cause instanceof Error |
| 62 | ? /^Process interrupted due to receipt of signal: '(SIG[A-Z0-9]+)'$/.exec( |
| 63 | cause.reason.cause.message, |
| 64 | )?.[1] |
| 65 | : undefined; |
| 66 | return signal === undefined |
| 67 | ? new AcpError.AcpTransportError({ |
| 68 | operation: "read-process-exit-status", |
| 69 | pid: handle.pid, |
| 70 | cause, |
| 71 | }) |
| 72 | : new AcpError.AcpProcessExitedError({ signal, pid: handle.pid, cause }); |
| 73 | }, |
| 74 | onSuccess: (code) => new AcpError.AcpProcessExitedError({ code, pid: handle.pid }), |
| 75 | }); |