refactor: extract config and conversation handling into separate modules

This commit is contained in:
mitchell 2026-04-18 18:59:51 -04:00
parent f50280364d
commit 6dc55bc3f3
3 changed files with 64 additions and 23 deletions

View file

@ -1,9 +1,13 @@
import os from "node:os";
import { parseArgs } from "node:util";
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
import { type ModelMessage, streamText } from "ai";
import chalk from "chalk";
import { streamText } from "ai";
import { loadConfig, saveConfig } from "./src/config";
import {
type Conversation,
loadConversation,
saveConversation,
} from "./src/conversation";
import Renderer from "./src/render";
const { values: args, positionals } = parseArgs({
@ -23,23 +27,13 @@ const { values: args, positionals } = parseArgs({
allowPositionals: true,
});
const home = os.homedir();
const convoFile = Bun.file(`${home}/.aicl_convo.json`);
const configFile = Bun.file(`${home}/.aicl_config.json`);
async function main() {
const newConvo = args.new ?? args.n;
const plainOut = args.plainOut ?? args.plain ?? !process.stdout.isTTY;
const plainErr = args.plainErr ?? args.plain ?? !process.stderr.isTTY;
let saveConfig = args.save ?? args.s;
const saveConfigFlag = args.save ?? args.s;
let config: { model?: string };
try {
config = await configFile.json();
} catch {
config = {};
saveConfig = true;
}
const { config } = await loadConfig();
config.model = args.model ?? args.m ?? config.model;
@ -48,9 +42,8 @@ async function main() {
process.exit(1);
}
if (saveConfig) {
await configFile.write(JSON.stringify(config, null, " "));
console.log(chalk.green("Configuration saved!"));
if (saveConfigFlag) {
await saveConfig(config);
return;
}
@ -63,15 +56,13 @@ async function main() {
includeUsage: true, // Include usage information in streaming responses
});
let convo: { model: string; messages: ModelMessage[] } = {
let convo: Conversation = {
model: config.model,
messages: [],
};
if (!newConvo) {
try {
convo = await convoFile.json();
} catch {}
convo = await loadConversation(config.model);
if (args.model || args.m) {
convo.model = args.model ?? args.m ?? config.model;
@ -91,7 +82,7 @@ async function main() {
const stop = Date.now();
convo.messages.push({ role: "assistant", content: await text });
await convoFile.write(JSON.stringify(convo));
await saveConversation(convo);
await renderer.renderStats(totalUsage, start, stop);
}