// The terminal channel: a chat prompt in your shell. // // A channel only does input and output. It turns what you type into calls to the assistant and // prints what comes back. It never calls the model or touches the session log itself, which is // why lab 08 can add a web channel without changing the core. import { createInterface, type Interface } from 'node:readline/promises'; import { stdin, stdout } from 'node:process'; import type { AnswerResult, AssistantResult } from '../core/assistant.ts'; import type { TurnResult, TurnUsage } from '../core/turn-loop.ts'; import type { ChannelAdapter, OutboundMessage } from '../gateway/gateway.ts'; /** What the terminal shows for a waiting approval request. */ export interface ApprovalView { approvalId: string; summary: string; reason: string; } /** Prints messages the assistant starts on its own (scheduled jobs) above the prompt. */ export class TerminalAdapter implements ChannelAdapter { readonly name = 'terminal'; deliver(message: OutboundMessage): void { stdout.write(`\n[${message.source}] ${message.text}\nyou> `); } } export interface TurnIO { onText: (delta: string) => void; onTool: (event: { name: string; phase: 'start' | 'end'; isError?: boolean }) => void; signal: AbortSignal; } export interface ChatHandlers { /** Name shown in the prompt and in replies. */ assistantName: string; /** Lines printed when the chat starts (session, model, recovery notes, ...). */ banner: string; reply: (text: string, io: TurnIO) => Promise; /** Starts a fresh conversation (the /new command). Returns a line to print. */ newConversation: () => Promise; /** Text for the /usage command. */ usage: () => string | Promise; /** Approval handling (lab 05). Absent in the ephemeral chat. */ approvals?: { pending: () => ApprovalView[] | Promise; answer: ( approvalId: string, decision: 'approved' | 'denied', always: boolean, io: TurnIO, ) => Promise; }; } const HELP = [ 'Commands:', ' /new start a new conversation (the old one stays on disk)', ' /usage tokens, cost, cache hits, and context size', ' /pending tool calls waiting for your approval', ' /approve run a waiting tool call', ' /approve always run it, and allow this exact command from now on', ' /deny do not run it', ' /help this list', ' /quit leave (Ctrl+D works too)', 'Ctrl+C while the assistant is answering cancels that answer.', ].join('\n'); export async function runTerminalChat(handlers: ChatHandlers): Promise { console.log(handlers.banner); const waiting = (await handlers.approvals?.pending()) ?? []; if (waiting.length > 0) printApprovals(waiting); console.log('Type /help for commands.\n'); const rl = createInterface({ input: stdin, output: stdout, terminal: stdin.isTTY }); rl.setPrompt('you> '); // Read lines through the async iterator, not rl.question(): it queues lines that arrive while // a turn is running (piped input), and it ends when the input closes. (A pending question() // never settles on close, so Ctrl+D would skip the shutdown that follows this function.) const lines = rl[Symbol.asyncIterator](); let inputClosed = false; rl.once('close', () => (inputClosed = true)); for (;;) { // Piped input can end while lines are still queued: those are read without a prompt. if (!inputClosed) rl.prompt(); const next = await lines.next(); if (next.done) break; // Ctrl+D, or Ctrl+C at the prompt, closes the input. const line = String(next.value).trim(); if (line === '') continue; if (line.startsWith('/')) { const [command = '', id, flag] = line.split(/\s+/); const name = command.toLowerCase(); if (name === '/quit' || name === '/exit') break; if (name === '/help') console.log(HELP); else if (name === '/new') console.log(await handlers.newConversation()); else if (name === '/usage') console.log(await handlers.usage()); else if (name === '/pending') printApprovals((await handlers.approvals?.pending()) ?? []); else if ((name === '/approve' || name === '/deny') && handlers.approvals) { if (!id) { console.log(`Usage: ${name} `); continue; } const decision = name === '/approve' ? 'approved' : 'denied'; await runWithIO(rl, handlers.assistantName, async (io) => { const answer = await handlers.approvals!.answer(id, decision, flag === 'always', io); if (answer.status === 'unknown') { stdout.write(`no waiting request with id ${id} (see /pending)`); } else if (answer.status === 'waiting') { stdout.write( `noted. Still waiting for: ${answer.remaining.map((r) => r.approvalId).join(', ')}`, ); } else { return answer.result; } return undefined; }); } else console.log(`Unknown command ${line}. Type /help.`); continue; } await runWithIO(rl, handlers.assistantName, (io) => handlers.reply(line, io)); } rl.close(); } async function runWithIO( rl: Interface, assistantName: string, work: (io: TurnIO) => Promise, ): Promise { const controller = new AbortController(); const onSigint = () => controller.abort(); // In a real terminal readline owns Ctrl+C and emits SIGINT on the interface (a process // listener never fires). With piped input there is no raw mode, so listen on both. rl.on('SIGINT', onSigint); process.once('SIGINT', onSigint); stdout.write(`${assistantName.toLowerCase()}> `); let streamed = false; try { const result = await work({ signal: controller.signal, onText: (delta) => { streamed = true; stdout.write(delta); }, onTool: ({ name, phase, isError }) => { if (phase === 'start') stdout.write(`\n [tool] ${name} ... `); else stdout.write(isError ? 'failed\n' : 'done\n'); }, }); // A reply that never reached the model (the daily limit, lab 12) has text but streamed none. if (result && !streamed && result.text) stdout.write(result.text); stdout.write('\n'); if (result) { const note = stopNote(result); if (note) console.log(` (${note})`); if ('approvals' in result && result.approvals) printApprovals(result.approvals); } } catch (err) { stdout.write('\n'); console.log( controller.signal.aborted ? ' (cancelled)' : ` (error: ${(err as Error).message})`, ); } finally { rl.removeListener('SIGINT', onSigint); process.removeListener('SIGINT', onSigint); } stdout.write('\n'); } function printApprovals(requests: readonly ApprovalView[]): void { if (requests.length === 0) { console.log('Nothing is waiting for approval.'); return; } console.log('Waiting for your approval:'); for (const r of requests) { console.log(` [${r.approvalId}] ${r.summary}`); console.log(` why asked: ${r.reason}`); } console.log('Answer with /approve , /approve always, or /deny .'); } function stopNote(result: TurnResult): string | undefined { switch (result.stop) { case 'end_turn': case 'awaiting_approval': return undefined; case 'max_tokens': return 'the answer hit the output limit and was cut off'; case 'refusal': return 'the model declined this request'; case 'max_steps': return 'stopped: too many steps in one turn'; case 'context_window': return 'the conversation is too long; start a new one with /new'; default: return `stopped: ${result.stop}`; } } export function formatUsage(usage: TurnUsage): string { return ( `model calls ${usage.modelCalls}, input ${usage.inputTokens}, output ${usage.outputTokens}, ` + `cache read ${usage.cacheReadTokens}, cache write ${usage.cacheWriteTokens}` ); }