@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, 04:45 UTC

main
ts 201 lines 6.74 KB
Raw
1 /**
2 * Shared Node.js implementation of Effect's `Terminal` service.
3 *
4 * `NodeTerminal` adapts Node's `readline` APIs plus the current process
5 * `stdin` and `stdout` streams into {@link Terminal.Terminal}. The service can
6 * display output, read a line, stream key input, and read terminal dimensions.
7 * `make` manages readline and TTY raw mode in a scope, while `layer` provides
8 * the default service that ends key input on bare Esc, Ctrl+C, or Ctrl+D.
9 *
10 * @stability unstable
11 * @since 4.0.0
12 */
13 import type * as Cause from "effect/Cause"
14 import * as Effect from "effect/Effect"
15 import * as Layer from "effect/Layer"
16 import * as Option from "effect/Option"
17 import { badArgument, type PlatformError } from "effect/PlatformError"
18 import * as Predicate from "effect/Predicate"
19 import * as Queue from "effect/Queue"
20 import * as RcRef from "effect/RcRef"
21 import type * as Scope from "effect/Scope"
22 import * as Terminal from "effect/Terminal"
23 import * as readline from "node:readline"
24
25 /**
26 * Creates a scoped process-backed `Terminal` using Node `readline`, enabling
27 * TTY raw mode while key input is read. By default, Esc, Ctrl+C, and Ctrl+D
28 * end key input. Supply `shouldQuit` to override these quit keys.
29 *
30 * @stability unstable
31 * @category constructors
32 * @since 4.0.0
33 */
34 export const make: (
35 shouldQuit?: (input: Terminal.UserInput) => boolean
36 ) => Effect.Effect<Terminal.Terminal, never, Scope.Scope> = Effect.fnUntraced(
37 function*(shouldQuit: (input: Terminal.UserInput) => boolean = defaultShouldQuit) {
38 const stdin = process.stdin
39 const stdout = process.stdout
40 const lines = yield* Queue.make<string, Cause.Done>()
41
42 // stdin "end" fires once per process, so remember end-of-input for readers
43 // created after the event (Bun never sets `readableEnded`).
44 let inputEnded = stdin.readableEnded
45 let readlineActive = false
46 const onStdinEnd = () => {
47 inputEnded = true
48 if (!readlineActive) {
49 Queue.endUnsafe(lines)
50 }
51 }
52 stdin.once("end", onStdinEnd)
53 yield* Effect.addFinalizer(() => Effect.sync(() => stdin.off("end", onStdinEnd)))
54
55 const rlRef = yield* RcRef.make({
56 acquire: Effect.acquireRelease(
57 Effect.sync(() => {
58 const rl = readline.createInterface({ input: stdin, escapeCodeTimeout: 50 })
59 const onLine = (line: string) => Queue.offerUnsafe(lines, line)
60 const onClose = () => {
61 readlineActive = false
62 Queue.endUnsafe(lines)
63 }
64 readlineActive = true
65 readline.emitKeypressEvents(stdin, rl)
66 rl.on("line", onLine)
67 rl.once("close", onClose)
68 return { rl, onClose, onLine }
69 }),
70 ({ rl, onClose, onLine }) =>
71 Effect.sync(() => {
72 readlineActive = false
73 rl.off("line", onLine)
74 rl.off("close", onClose)
75 rl.close()
76 if (inputEnded) {
77 Queue.endUnsafe(lines)
78 }
79 })
80 ),
81 idleTimeToLive: "10 millis"
82 })
83
84 // Only key input needs raw mode; `readLine` never requests it.
85 const setRawMode = (enabled: boolean) =>
86 Effect.sync(() => {
87 if (stdin.isTTY) stdin.setRawMode(enabled)
88 })
89 const rawModeRef = yield* RcRef.make({
90 acquire: Effect.acquireRelease(setRawMode(true), () => setRawMode(false)),
91 idleTimeToLive: "10 millis"
92 })
93
94 const columns = Effect.sync(() => stdout.columns ?? 0)
95 const rows = Effect.sync(() => stdout.rows ?? 0)
96 const size = Effect.gen(function*() {
97 const queue = yield* Queue.sliding<Terminal.Size, Cause.Done>(1)
98 const onResize = () => Queue.offerUnsafe(queue, { columns: stdout.columns ?? 0, rows: stdout.rows ?? 0 })
99 yield* Effect.addFinalizer(() =>
100 Effect.sync(() => {
101 stdout.off("resize", onResize)
102 Queue.endUnsafe(queue)
103 })
104 )
105 stdout.on("resize", onResize)
106 onResize()
107 return queue
108 })
109
110 const readInput = Effect.gen(function*() {
111 const queue = yield* Queue.make<Terminal.UserInput, Cause.Done>()
112 const handleKeypress = (s: string | undefined, k: readline.Key) => {
113 const userInput = {
114 input: Option.fromUndefinedOr(s),
115 key: { name: k.name ?? "", ctrl: !!k.ctrl, meta: !!k.meta, shift: !!k.shift }
116 }
117 Queue.offerUnsafe(queue, userInput)
118 if (shouldQuit(userInput)) {
119 Queue.endUnsafe(queue)
120 }
121 }
122 // Deno's `process.stdin` shim does not keep the event loop alive, so a
123 // program blocked on input can exit before `end` is ever delivered. A
124 // timer holds the loop open for as long as this reader is active.
125 const keepAlive = setInterval(() => {}, 2147483647)
126 // Without this, consumers (e.g. `Prompt.run`) hang forever on closed stdin.
127 const handleEnd = () => {
128 clearInterval(keepAlive)
129 Queue.endUnsafe(queue)
130 }
131 yield* Effect.addFinalizer(() =>
132 Effect.sync(() => {
133 clearInterval(keepAlive)
134 stdin.off("keypress", handleKeypress)
135 stdin.off("end", handleEnd)
136 })
137 )
138 stdin.on("keypress", handleKeypress)
139 if (inputEnded) {
140 handleEnd()
141 } else {
142 yield* RcRef.get(rlRef)
143 yield* RcRef.get(rawModeRef)
144 stdin.once("end", handleEnd)
145 }
146 return queue as Queue.Dequeue<Terminal.UserInput, Cause.Done>
147 })
148
149 const readLine = Effect.suspend(() =>
150 Queue.poll(lines).pipe(
151 Effect.flatMap(Option.match({
152 onNone: () => Effect.scoped(Effect.andThen(RcRef.get(rlRef), Queue.take(lines))),
153 onSome: Effect.succeed
154 })),
155 Effect.mapError(() => new Terminal.QuitError({}))
156 )
157 )
158
159 const display = (prompt: string) =>
160 Effect.uninterruptible(
161 Effect.callback<void, PlatformError>((resume) => {
162 stdout.write(prompt, (err) =>
163 Predicate.isNullish(err)
164 ? resume(Effect.void)
165 : resume(Effect.fail(
166 badArgument({
167 module: "Terminal",
168 method: "display",
169 description: "Failed to write prompt to stdout",
170 cause: err
171 })
172 )))
173 })
174 )
175
176 return Terminal.make({
177 columns,
178 rows,
179 size,
180 readInput,
181 readLine,
182 display
183 })
184 }
185 )
186
187 /**
188 * Provides the default process-backed `Terminal` service, ending key input on
189 * bare Esc, Ctrl+C, or Ctrl+D.
190 *
191 * @stability unstable
192 * @category layers
193 * @since 4.0.0
194 */
195 export const layer: Layer.Layer<Terminal.Terminal> = Layer.effect(Terminal.Terminal, make(defaultShouldQuit))
196
197 function defaultShouldQuit(input: Terminal.UserInput) {
198 const key = input.key
199 return key.name === "escape" ||
200 (key.ctrl && (key.name === "c" || key.name === "d"))
201 }