xonecas.io
64875
Mc

mini-coder / files

mini-coder / src / cli.ts

3.7 KB
1import process from "node:process";
2import { clampThinkingLevel, contentText, type AssistantMessage, type Message, type UserMessage } from "@earendil-works/pi-ai";
3import { configPath, loadConfig, resolveModel } from "./config.ts";
4import { buildSystemPrompt } from "./prompt.ts";
5import { acceptsImages, toolSchemas } from "./tools/index.ts";
6import { Session } from "./session.ts";
7import { NO_INTERACTION, runAgentTurn, type AgentOptions } from "./agent.ts";
8import { runTui } from "./tui/tui.ts";
9
10function parseArgs(argv: string[]): { print: string | null } {
11  let print: string | null = null;
12  for (let i = 0; i < argv.length; i++) {
13    const match = /^(?:-p|--print)(?:=(.*))?$/.exec(argv[i]);
14    if (match === null) throw new Error(`unknown argument: ${argv[i]}`);
15    const value = match[1] ?? argv[++i];
16    if (value === undefined) throw new Error(`${argv[i - 1]} requires a prompt`);
17    print = value;
18  }
19  return { print };
20}
21
22async function runPrint(prompt: string, ctx: AgentOptions): Promise<number> {
23  const messages: Message[] = [];
24  const user: UserMessage = { role: "user", content: prompt, timestamp: Date.now() };
25  messages.push(user);
26  ctx.session.appendMessage(user);
27
28  const controller = new AbortController();
29  const onSignal = () => controller.abort();
30  process.on("SIGINT", onSignal);
31  process.on("SIGTERM", onSignal);
32
33  let failed = false;
34  let cancelled = false;
35  let noModel = false;
36  try {
37    await runAgentTurn({
38      ...ctx,
39      messages,
40      signal: controller.signal,
41      interaction: NO_INTERACTION,
42      onEvent: (event) => {
43        if (event.type === "toolCall") process.stderr.write(`[tool] ${event.name}\n`);
44        else if (event.type === "toolOutput") process.stderr.write(event.chunk);
45        else if (event.type === "noModel") {
46          noModel = true;
47          process.stderr.write(`[error] no model configured; add "provider" and "model" to ${configPath()}\n`);
48        } else if (event.type === "error") {
49          failed = true;
50          process.stderr.write(`[error] ${event.message}\n`);
51        } else if (event.type === "cancelled") {
52          cancelled = true;
53          process.stderr.write("[cancelled]\n");
54        }
55      },
56    });
57  } catch (error) {
58    failed = true;
59    process.stderr.write(`[error] ${(error as Error).message}\n`);
60  } finally {
61    process.off("SIGINT", onSignal);
62    process.off("SIGTERM", onSignal);
63    ctx.session.close();
64  }
65
66  const last = messages.filter((message): message is AssistantMessage => message.role === "assistant").at(-1);
67  if (!failed && !cancelled && !noModel && last !== undefined) {
68    const text = contentText(last.content, "");
69    if (text !== "") process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
70  }
71  return failed || cancelled || noModel ? 1 : 0;
72}
73
74async function main(): Promise<void> {
75  const args = parseArgs(process.argv.slice(2));
76  const config = loadConfig();
77  const { models, model } = resolveModel(config);
78  const session = new Session(config.sessionsDir, process.cwd());
79  const ctx: AgentOptions = {
80    models,
81    model,
82    systemPrompt: buildSystemPrompt(config),
83    tools: toolSchemas(config.tools, model !== null && acceptsImages(model)),
84    toolNames: config.tools,
85    thinkingEffort: model === null ? config.thinkingEffort : clampThinkingLevel(model, config.thinkingEffort),
86    session,
87  };
88
89  if (args.print !== null) {
90    process.exitCode = await runPrint(args.print, ctx);
91    return;
92  }
93
94  if (!process.stdin.isTTY || !process.stdout.isTTY) {
95    throw new Error("interactive mode requires a TTY; use -p for non-interactive mode");
96  }
97  await runTui(ctx);
98}
99
100main().catch((error) => {
101  process.stderr.write(`${(error as Error).message}\n`);
102  process.exit(1);
103});