Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 499 lines 18.4 KB
Raw
1 import process from 'node:process';
2 import type { Writable } from 'node:stream';
3 import { getColumns } from '@clack/core';
4 import * as p from '@clack/prompts';
5 import stringWidth from 'fast-string-width';
6 import { Context, Data, Deferred, Effect, Exit, Layer, Predicate } from 'effect';
7
8 export type TtyLikeStream = {
9 readonly isTTY?: boolean;
10 };
11
12 export type TerminalStdio = {
13 readonly stdin: TtyLikeStream;
14 readonly stdout: TtyLikeStream;
15 readonly stderr: TtyLikeStream;
16 };
17
18 /**
19 * Per-stream terminal capabilities.
20 *
21 * The three streams are independent contracts, so each derived capability
22 * depends only on the streams that actually serve it:
23 *
24 * - `canPrompt` — stdin must accept human input and stderr must display the
25 * Clack prompt. stdout is irrelevant: piping data must not change prompting
26 * or authentication behavior.
27 * - `canDecorate` — decoration (spinners, logs, notes) renders on stderr, so it
28 * only needs stderr.
29 * - machine output — `TerminalUI.output()` consults `stdoutIsTTY` alone.
30 *
31 * There is deliberately no aggregate "interactive" flag: it conflated these
32 * concerns and let output routing change program behavior.
33 */
34 export type TerminalCapabilities = {
35 readonly stdinIsTTY: boolean;
36 readonly stdoutIsTTY: boolean;
37 readonly stderrIsTTY: boolean;
38 /** Whether Clack prompts can run (`stdinIsTTY && stderrIsTTY`). */
39 readonly canPrompt: boolean;
40 /** Whether stderr decoration can render (`stderrIsTTY`). */
41 readonly canDecorate: boolean;
42 };
43
44 /** Classify terminal streams without coupling callers or tests to Node globals. */
45 export const getTerminalCapabilities = (stdio: TerminalStdio): TerminalCapabilities => {
46 const stdinIsTTY = Boolean(stdio.stdin.isTTY);
47 const stdoutIsTTY = Boolean(stdio.stdout.isTTY);
48 const stderrIsTTY = Boolean(stdio.stderr.isTTY);
49
50 return {
51 stdinIsTTY,
52 stdoutIsTTY,
53 stderrIsTTY,
54 canPrompt: stdinIsTTY && stderrIsTTY,
55 canDecorate: stderrIsTTY,
56 };
57 };
58
59 // ---------------------------------------------------------------------------
60 // SpinnerHandle — returned by `useMakeSpinner` for manual control
61 // ---------------------------------------------------------------------------
62
63 export interface SpinnerHandle {
64 /** Update the spinner message while it's running. */
65 readonly message: (msg: string) => Effect.Effect<void>;
66 /** Stop the spinner with a success message. */
67 readonly stop: (msg?: string) => Effect.Effect<void>;
68 /** Stop the spinner with an error message. */
69 readonly error: (msg?: string) => Effect.Effect<void>;
70 }
71
72 // ---------------------------------------------------------------------------
73 // TerminalUI — Effect service for structured terminal output
74 // ---------------------------------------------------------------------------
75
76 /**
77 * A Clack prompt (`select`/`confirm`) rejected instead of resolving.
78 * Cancellation is NOT this error — cancel returns the documented
79 * fallback value. This fires when the streams backing the prompt fail
80 * mid-session (e.g. the terminal disappears while the question is
81 * open), which the caller cannot meaningfully recover from.
82 */
83 export class TerminalPromptError extends Data.TaggedError('TerminalPromptError')<{
84 readonly message: string;
85 readonly cause: unknown;
86 }> {}
87
88 export interface TerminalUI {
89 /** Capabilities of the streams backing this terminal service. */
90 readonly capabilities: Effect.Effect<TerminalCapabilities>;
91
92 /**
93 * Write raw data to stdout for piping and scripting.
94 *
95 * This is the ONLY method that writes to stdout — everything else goes to stderr.
96 * When stdout is a TTY (a human is watching it), this is a no-op — the human already
97 * sees the data via decoration on stderr. When stdout is redirected (pipe, subshell,
98 * file), the raw value is written for machine consumption. Only stdout's own TTY
99 * state participates in this decision; redirecting stdin or stderr must never make
100 * data leak onto a visible stdout terminal.
101 *
102 * It completes once the stream took the data. After a reader closed stdout early (EPIPE),
103 * the data is dropped and the command goes on; any other write failure is a defect.
104 *
105 * Use this for values that scripts should capture (API keys, version strings, etc.).
106 */
107 readonly output: (data: string, options?: { readonly force?: boolean }) => Effect.Effect<void>;
108
109 /**
110 * Completes once a reader closed stdout early (EPIPE), from which point `output` drops its
111 * data; never completes otherwise. A command that keeps producing data until stopped (a
112 * listener) races it, so it stops once nobody reads what it writes.
113 */
114 readonly stdoutClosed: Effect.Effect<void>;
115
116 /**
117 * Write an unformatted line to stderr even when stderr is redirected.
118 *
119 * Use this for diagnostics and protocol metadata that must survive piping.
120 * Human-facing decoration belongs in `log`, `note`, `intro`, or `outro`.
121 */
122 readonly error: (data: string) => Effect.Effect<void>;
123
124 /** Display a session start marker (e.g., `┌ title`). Writes to stderr. */
125 readonly intro: (title: string) => Effect.Effect<void>;
126 /** Display a session end marker (e.g., `└ message`). Writes to stderr. */
127 readonly outro: (message: string) => Effect.Effect<void>;
128
129 /** Structured log output with severity-specific symbols. */
130 readonly log: {
131 /** Blue info marker. */
132 readonly info: (message: string) => Effect.Effect<void>;
133 /** Green success marker. */
134 readonly success: (message: string) => Effect.Effect<void>;
135 /** Yellow warning marker. */
136 readonly warn: (message: string) => Effect.Effect<void>;
137 /** Red error marker. */
138 readonly error: (message: string) => Effect.Effect<void>;
139 /** Green step marker (for completed steps). */
140 readonly step: (message: string) => Effect.Effect<void>;
141 /** Generic log message with bar guide. */
142 readonly message: (message: string) => Effect.Effect<void>;
143 };
144
145 /** Display a boxed note with optional title. */
146 readonly note: (message: string, title?: string) => Effect.Effect<void>;
147
148 /**
149 * Wrap an Effect computation in a spinner.
150 * The spinner starts before the effect runs and stops/errors on completion.
151 */
152 readonly withSpinner: <A, E, R>(
153 message: string,
154 effect: Effect.Effect<A, E, R>,
155 options?: {
156 readonly successMessage?: string | ((result: A) => string);
157 readonly errorMessage?: string;
158 }
159 ) => Effect.Effect<A, E, R>;
160
161 /**
162 * Ask the user a yes/no confirmation question.
163 * When prompting is unavailable, returns `defaultValue` (defaults to `true`).
164 * Fails with `TerminalPromptError` if the prompt's streams fail mid-session.
165 */
166 readonly confirm: (
167 message: string,
168 options?: { readonly defaultValue?: boolean }
169 ) => Effect.Effect<boolean, TerminalPromptError>;
170
171 /**
172 * Present a single-select list to the user.
173 * When prompting is unavailable, returns the first option's value.
174 * Fails with `TerminalPromptError` if the prompt's streams fail mid-session.
175 */
176 readonly select: <Value>(
177 message: string,
178 options: ReadonlyArray<{
179 readonly value: Value;
180 readonly label: string;
181 readonly hint?: string;
182 }>
183 ) => Effect.Effect<Value, TerminalPromptError>;
184
185 /**
186 * Create a controllable spinner that is automatically stopped on error or interruption.
187 * The `use` function receives a SpinnerHandle and must return an Effect.
188 * On success: the caller should call `spinner.stop(...)` inside `use`.
189 * On failure: the spinner is automatically stopped with an error message.
190 * On interruption: the spinner is automatically cancelled.
191 */
192 readonly useMakeSpinner: <A, E, R>(
193 message: string,
194 use: (spinner: SpinnerHandle) => Effect.Effect<A, E, R>
195 ) => Effect.Effect<A, E, R>;
196 }
197
198 export const TerminalUI = Context.Service<TerminalUI>('services/TerminalUI');
199
200 // ---------------------------------------------------------------------------
201 // makeTerminalUI — build a TerminalUI from explicit streams
202 // ---------------------------------------------------------------------------
203
204 /**
205 * Intentionally a Node.js Writable rather than an Effect Sink: Clack accepts
206 * Writable streams and writes to them synchronously.
207 */
208 type TerminalWritable = TtyLikeStream & Writable;
209
210 type TerminalUIStreams = {
211 readonly stdin: TtyLikeStream;
212 readonly stdout: TerminalWritable;
213 readonly stderr: TerminalWritable;
214 };
215
216 // Clack's spinner erases the previous frame by re-wrapping the raw message,
217 // but it renders `${frame} ${message}${dots}` — three prefix columns plus up
218 // to three animated dots the erase math never sees. Once those extras push the
219 // rendered frame across a wrap boundary, the erase under-counts lines and
220 // every tick leaks one: an endless scroll in terminals narrower than the
221 // message. Keep live spinner messages to a single terminal row so the redraw
222 // arithmetic cannot diverge.
223 //
224 // The invariant holds for terminals of at least SPINNER_RENDER_OVERHEAD + 1
225 // columns. Below that the frame prefix alone overflows the row and no message
226 // length can keep it on one line, so the budget degrades to just the ellipsis.
227 const SPINNER_RENDER_OVERHEAD = 7; // frame + two spaces (3) + animated dots (3) + last-column safety (1)
228 const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
229
230 export const clampSpinnerMessage = (columns: number, message: string): string => {
231 const singleLine = message.replace(/\s*\r?\n\s*/g, ' ');
232 if (singleLine.includes('\u001b')) {
233 return singleLine; // truncating could split an ANSI escape sequence
234 }
235
236 const budget = Math.max(columns - SPINNER_RENDER_OVERHEAD, 1);
237 if (stringWidth(singleLine) <= budget) {
238 return singleLine;
239 }
240
241 // Measure whole grapheme clusters in display columns. Measuring individual
242 // code points under-counts sequences such as keycap emoji, while slicing by
243 // UTF-16 length can split surrogate pairs or joined emoji. One column is
244 // reserved for the ellipsis.
245 let clamped = '';
246 let width = 0;
247 for (const { segment } of graphemeSegmenter.segment(singleLine)) {
248 const segmentWidth = stringWidth(segment);
249 if (width + segmentWidth > budget - 1) {
250 break;
251 }
252 clamped += segment;
253 width += segmentWidth;
254 }
255 return `${clamped}…`;
256 };
257
258 type StartedClackSpinner = {
259 readonly raw: p.SpinnerResult;
260 readonly updateMessage: (message: string) => void;
261 };
262
263 function createClackSpinnerHandle(
264 spinner: StartedClackSpinner,
265 defaultMessage: string
266 ): { handle: SpinnerHandle; isStopped: () => boolean } {
267 let stopped = false;
268 return {
269 handle: {
270 message: (msg: string) => Effect.sync(() => spinner.updateMessage(msg)),
271 stop: (msg?: string) =>
272 Effect.sync(() => {
273 stopped = true;
274 spinner.raw.stop(msg ?? defaultMessage);
275 }),
276 error: (msg?: string) =>
277 Effect.sync(() => {
278 stopped = true;
279 spinner.raw.error(msg ?? defaultMessage);
280 }),
281 },
282 isStopped: () => stopped,
283 };
284 }
285
286 /** Whether a write failed because the reader of the pipe went away. */
287 const isBrokenPipe = (error: unknown): boolean =>
288 Predicate.hasProperty(error, 'code') && error.code === 'EPIPE';
289
290 /** No-op spinner handle used when decoration is suppressed (stderr redirected). */
291 const silentSpinnerHandle: SpinnerHandle = {
292 message: () => Effect.void,
293 stop: () => Effect.void,
294 error: () => Effect.void,
295 };
296
297 /**
298 * Build a TerminalUI backed by the given streams.
299 *
300 * Each stream governs exactly one concern:
301 * - stdin + stderr decide prompting (`canPrompt`);
302 * - stdout alone decides machine output (`output()` writes only when stdout
303 * is not a TTY, or when `force` is set);
304 * - stderr alone decides decoration (`canDecorate`).
305 */
306 export const makeTerminalUI = (streams: TerminalUIStreams): TerminalUI => {
307 const capabilities = getTerminalCapabilities(streams);
308 const { canPrompt, canDecorate, stdoutIsTTY } = capabilities;
309 const stderr = streams.stderr;
310
311 const decorate = (render: () => void): Effect.Effect<void> => {
312 if (!canDecorate) {
313 return Effect.void;
314 }
315 return Effect.sync(render);
316 };
317
318 // Done once the reader of stdout went away: nothing written after can reach it.
319 const stdoutClosed = Deferred.makeUnsafe<void>();
320 // A failed write reaches its callback and is also emitted as an `error` event, which crashes
321 // the process when nothing listens. `writeStdout` reports every failure from the callback, and
322 // listens only once it writes, so a process that never writes data keeps the default.
323 let ignoringStdoutErrorEvents = false;
324
325 /**
326 * Writes `chunk` to stdout once the stream took it. A reader that closed the pipe early
327 * (EPIPE, as `head` can) chose to stop reading, so the data is dropped and the command goes
328 * on; any other write failure is a defect.
329 */
330 const writeStdout = (chunk: string): Effect.Effect<void> =>
331 Effect.suspend(() => {
332 if (Deferred.isDoneUnsafe(stdoutClosed)) {
333 return Effect.void;
334 }
335 if (!ignoringStdoutErrorEvents) {
336 ignoringStdoutErrorEvents = true;
337 streams.stdout.on('error', () => {});
338 }
339 return Effect.callback<void>(resume => {
340 streams.stdout.write(chunk, error => {
341 if (error === null || error === undefined) {
342 resume(Effect.void);
343 } else if (isBrokenPipe(error)) {
344 Deferred.doneUnsafe(stdoutClosed, Effect.void);
345 resume(Effect.void);
346 } else {
347 resume(Effect.die(error));
348 }
349 });
350 });
351 });
352
353 /** Start a clack spinner on stderr, clamped to a single terminal row. */
354 const startSpinner = (message: string): StartedClackSpinner => {
355 // Clack captures this width during construction and continues wrapping
356 // against it. Updates may respect a later narrower terminal, but must never
357 // grow beyond Clack's fixed width.
358 const initialColumns = getColumns(stderr);
359 const raw = p.spinner({ output: stderr });
360 raw.start(clampSpinnerMessage(initialColumns, message));
361 return {
362 raw,
363 updateMessage: msg =>
364 raw.message(clampSpinnerMessage(Math.min(initialColumns, getColumns(stderr)), msg)),
365 };
366 };
367
368 return {
369 capabilities: Effect.succeed(capabilities),
370
371 output: (data, options) =>
372 options?.force || !stdoutIsTTY ? writeStdout(`${data}\n`) : Effect.void,
373
374 stdoutClosed: Deferred.await(stdoutClosed),
375
376 error: data => Effect.sync(() => stderr.write(`${data}\n`)),
377
378 intro: title => decorate(() => p.intro(title, { output: stderr })),
379 outro: message => decorate(() => p.outro(message, { output: stderr })),
380
381 log: {
382 info: message => decorate(() => p.log.info(message, { output: stderr })),
383 success: message => decorate(() => p.log.success(message, { output: stderr })),
384 warn: message => decorate(() => p.log.warn(message, { output: stderr })),
385 error: message => decorate(() => p.log.error(message, { output: stderr })),
386 step: message => decorate(() => p.log.step(message, { output: stderr })),
387 message: message => decorate(() => p.log.message(message, { output: stderr })),
388 },
389
390 note: (message, title) =>
391 decorate(() => p.note(message, title ?? '', { format: line => line, output: stderr })),
392
393 select: ((
394 message: string,
395 options: ReadonlyArray<{ value: unknown; label: string; hint?: string }>
396 ) => {
397 if (!canPrompt) {
398 return Effect.succeed(options[0].value);
399 }
400
401 // The prompt itself is fallible (stream failure while the question is
402 // open), so it surfaces as a typed TerminalPromptError rather than an
403 // Effect.promise defect.
404 return Effect.tryPromise({
405 try: async () => {
406 const result = await p.select({
407 message,
408 options: [...options],
409 output: stderr,
410 });
411 // p.select returns Value | symbol (symbol on cancel)
412 if (typeof result === 'symbol') return options[0].value;
413 return result;
414 },
415 catch: cause => new TerminalPromptError({ message: 'Select prompt failed.', cause }),
416 });
417 }) as TerminalUI['select'],
418
419 confirm: (message, options) => {
420 if (!canPrompt) {
421 return Effect.succeed(options?.defaultValue ?? true);
422 }
423
424 return Effect.tryPromise({
425 try: async () => {
426 const result = await p.confirm({
427 message,
428 initialValue: options?.defaultValue ?? true,
429 output: stderr,
430 });
431 if (p.isCancel(result)) return false;
432 return result;
433 },
434 catch: cause => new TerminalPromptError({ message: 'Confirm prompt failed.', cause }),
435 });
436 },
437
438 withSpinner: (message, effect, options) => {
439 if (!canDecorate) {
440 return effect;
441 }
442
443 return Effect.acquireUseRelease(
444 Effect.sync(() => startSpinner(message)),
445 () => effect,
446 (spinner, exit) =>
447 Effect.sync(() => {
448 if (Exit.isSuccess(exit)) {
449 let successMessage = message;
450 const configuredSuccessMessage = options?.successMessage;
451 if (typeof configuredSuccessMessage === 'function') {
452 successMessage = configuredSuccessMessage(exit.value);
453 } else if (configuredSuccessMessage !== undefined) {
454 successMessage = configuredSuccessMessage;
455 }
456 spinner.raw.stop(successMessage);
457 } else {
458 spinner.raw.error(options?.errorMessage ?? message);
459 }
460 })
461 );
462 },
463
464 useMakeSpinner: (message, use) => {
465 if (!canDecorate) {
466 return use(silentSpinnerHandle);
467 }
468
469 return Effect.acquireUseRelease(
470 Effect.sync(() => {
471 const spinner = startSpinner(message);
472 const { handle, isStopped } = createClackSpinnerHandle(spinner, message);
473 return { raw: spinner.raw, handle, isStopped };
474 }),
475 ({ handle }) => use(handle),
476 ({ raw, isStopped }, exit) =>
477 Effect.sync(() => {
478 // Only clean up if the spinner hasn't been stopped/errored by the callback
479 if (Exit.isFailure(exit) && !isStopped()) {
480 raw.error(message);
481 }
482 })
483 );
484 },
485 };
486 };
487
488 // ---------------------------------------------------------------------------
489 // TerminalUILive — production layer using @clack/prompts
490 // ---------------------------------------------------------------------------
491
492 export const TerminalUILive = Layer.succeed(
493 TerminalUI,
494 makeTerminalUI({
495 stdin: process.stdin,
496 stdout: process.stdout,
497 stderr: process.stderr,
498 })
499 );