From 1594ed4f4cdc26f813ec48b3cdf906610342cba7 Mon Sep 17 00:00:00 2001 From: Kenny Daniel Date: Tue, 9 Dec 2025 00:38:57 -0800 Subject: [PATCH] Use readline for better chat input --- bin/chat.js | 48 ++++++++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/bin/chat.js b/bin/chat.js index e2b06a9..6b534e3 100644 --- a/bin/chat.js +++ b/bin/chat.js @@ -1,3 +1,4 @@ +import readline from 'readline' import { tools } from './tools/tools.js' /** @type {'text' | 'tool'} */ @@ -241,26 +242,33 @@ function writeWithColor() { export function chat() { /** @type {Message[][]} */ const messages = [] - process.stdin.setEncoding('utf-8') - - write(colors.system, 'question: ', colors.normal) + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + terminal: true, + }) - process.stdin.on('data', async (/** @type {string} */ input) => { - input = input.trim() - if (input === 'exit') { - process.exit() - } else if (input) { - try { - write(colors.user, 'answer: ', colors.normal) - outputMode = 'text' // switch to text output mode - messages.push([{ role: 'user', content: input.trim() }]) - await sendMessages(messages) - } catch (error) { - console.error(colors.error, '\n' + error) - } finally { - write('\n\n') + function prompt() { + rl.question(`${colors.system}question: ${colors.normal}`, async (input) => { + input = input.trim() + if (input === 'exit') { + rl.close() + process.exit() + } else if (input) { + try { + write(colors.user, 'answer: ', colors.normal) + outputMode = 'text' // switch to text output mode + messages.push([{ role: 'user', content: input }]) + await sendMessages(messages) + } catch (error) { + console.error(colors.error, '\n' + error) + } finally { + write('\n\n') + } } - } - write(colors.system, 'question: ', colors.normal) - }) + prompt() + }) + } + + prompt() }