diff --git a/adapters/images_test.ts b/adapters/images_test.ts index 9ddcb86..ff2cbfa 100644 --- a/adapters/images_test.ts +++ b/adapters/images_test.ts @@ -1,5 +1,5 @@ import { assertEquals, assertRejects } from "@std/assert" -import { ValidationError } from "@cliffy/command" +import { ValidationError } from "../errors.ts" import { type } from "arktype" import { resolveModel } from "../models.ts" diff --git a/adapters/openai.ts b/adapters/openai.ts index a5f3baf..fa71af7 100644 --- a/adapters/openai.ts +++ b/adapters/openai.ts @@ -2,7 +2,7 @@ import OpenAI from "openai" import type { ResponseCreateParamsNonStreaming } from "openai/resources/responses/responses" import type { ImageGenerateParamsNonStreaming } from "openai/resources/images" import { decodeBase64 } from "@std/encoding/base64" -import { ValidationError } from "@cliffy/command" +import { ValidationError } from "../errors.ts" import { match, P } from "ts-pattern" import { postprocessSchemaContent, prepareSchema } from "../schema.ts" diff --git a/adapters/request_size.ts b/adapters/request_size.ts index 138c610..611336f 100644 --- a/adapters/request_size.ts +++ b/adapters/request_size.ts @@ -1,4 +1,4 @@ -import { ValidationError } from "@cliffy/command" +import { ValidationError } from "../errors.ts" const MB = 1_000_000 const encoder = new TextEncoder() diff --git a/deno.jsonc b/deno.jsonc index 3080019..23f64cc 100644 --- a/deno.jsonc +++ b/deno.jsonc @@ -11,9 +11,9 @@ "semiColons": false }, "imports": { - "@cliffy/command": "jsr:@cliffy/command@1.2.1", - "@cliffy/prompt": "jsr:@cliffy/prompt@1.2.1", - "@cliffy/table": "jsr:@cliffy/table@1.2.1", + "@commander-js/extra-typings": "npm:@commander-js/extra-typings@^15.0.0", + "commander": "npm:commander@^15.0.0", + "@inquirer/core": "npm:@inquirer/core@^12", "@david/dax": "jsr:@david/dax@^0.49.0", "@mathjax/src": "npm:@mathjax/src@4.1.3", "@resvg/resvg-wasm": "npm:@resvg/resvg-wasm@2.6.2", diff --git a/deno.lock b/deno.lock index ff454bd..de7e056 100644 --- a/deno.lock +++ b/deno.lock @@ -1,26 +1,17 @@ { "version": "5", "specifiers": { - "jsr:@cliffy/ansi@1.2.1": "1.2.1", - "jsr:@cliffy/command@1.2.1": "1.2.1", - "jsr:@cliffy/flags@1.2.1": "1.2.1", - "jsr:@cliffy/internal@1.2.1": "1.2.1", - "jsr:@cliffy/keycode@1.2.1": "1.2.1", - "jsr:@cliffy/prompt@1.2.1": "1.2.1", - "jsr:@cliffy/table@1.2.1": "1.2.1", - "jsr:@david/console-static-text@~0.3.4": "0.3.4", + "jsr:@david/console-static-text@~0.3.4": "0.3.5", "jsr:@david/dax@0.49": "0.49.0", - "jsr:@david/path@0.3": "0.3.3", - "jsr:@david/path@~0.3.2": "0.3.3", + "jsr:@david/path@0.3": "0.3.4", + "jsr:@david/path@~0.3.2": "0.3.4", "jsr:@david/shell@0.6": "0.6.0", - "jsr:@david/which@0.7": "0.7.3", - "jsr:@david/which@~0.7.1": "0.7.3", + "jsr:@david/which@0.7": "0.7.4", + "jsr:@david/which@~0.7.1": "0.7.4", "jsr:@std/assert@^1.0.19": "1.0.19", "jsr:@std/bytes@^1.0.6": "1.0.6", - "jsr:@std/encoding@^1.0.10": "1.0.11", "jsr:@std/encoding@^1.0.11": "1.0.11", "jsr:@std/fmt@1": "1.0.10", - "jsr:@std/fmt@^1.0.10": "1.0.10", "jsr:@std/internal@^1.0.12": "1.0.14", "jsr:@std/internal@^1.0.14": "1.0.14", "jsr:@std/io@0.225": "0.225.3", @@ -28,15 +19,16 @@ "jsr:@std/path@*": "1.0.8", "jsr:@std/path@1": "1.1.6", "jsr:@std/path@^1.1.6": "1.1.6", - "jsr:@std/semver@^1.0.8": "1.0.8", - "jsr:@std/text@^1.0.19": "1.0.19", "npm:@anthropic-ai/sdk@0.123.0": "0.123.0", + "npm:@commander-js/extra-typings@15": "15.0.0_commander@15.0.0", "npm:@google/genai@2.21.0": "2.21.0", + "npm:@inquirer/core@12": "12.0.4", "npm:@mathjax/src@4.1.3": "4.1.3", "npm:@resvg/resvg-wasm@2.6.2": "2.6.2", "npm:@shikijs/cli@^4.4.3": "4.4.3", "npm:ansis@^4.3.1": "4.3.1", "npm:arktype@^2.2.3": "2.2.3", + "npm:commander@15": "15.0.0", "npm:json5@^2.2.3": "2.2.3", "npm:markdown-exit@^1.3.0": "1.3.0", "npm:openai@7.21.0": "7.21.0", @@ -45,58 +37,8 @@ "npm:ts-pattern@^5.9.0": "5.9.0" }, "jsr": { - "@cliffy/ansi@1.2.1": { - "integrity": "b8702def9c0110b6eeb2b3b71e0b26cbe0a427facbb4f9c0189da0ba19feb549", - "dependencies": [ - "jsr:@cliffy/internal", - "jsr:@std/encoding@^1.0.10", - "jsr:@std/io@~0.225.3" - ] - }, - "@cliffy/command@1.2.1": { - "integrity": "b7b017c81560d96580ea810c8564566884d8194416f6fc06bfdc8846e8fd590f", - "dependencies": [ - "jsr:@cliffy/flags", - "jsr:@cliffy/internal", - "jsr:@cliffy/table", - "jsr:@std/fmt@^1.0.10", - "jsr:@std/semver", - "jsr:@std/text" - ] - }, - "@cliffy/flags@1.2.1": { - "integrity": "10034920ef7595db586fecec5a3b10a4ec800c513cbbc368414cd748dac706fb", - "dependencies": [ - "jsr:@cliffy/internal", - "jsr:@std/text" - ] - }, - "@cliffy/internal@1.2.1": { - "integrity": "e398f41c6839d3d4d249c963bfcb1058013091425926d53a3cb482b1ca70684b" - }, - "@cliffy/keycode@1.2.1": { - "integrity": "ce0a1e00986054da31bc767274acefdc923338a47e75ad1fc2046a11c87ace16" - }, - "@cliffy/prompt@1.2.1": { - "integrity": "e468fae0f52093ff2099f5be0bbc7632348ab82a3b7337b12ddd888aeb5d6eed", - "dependencies": [ - "jsr:@cliffy/ansi", - "jsr:@cliffy/internal", - "jsr:@cliffy/keycode", - "jsr:@std/assert", - "jsr:@std/fmt@^1.0.10", - "jsr:@std/io@~0.225.3", - "jsr:@std/text" - ] - }, - "@cliffy/table@1.2.1": { - "integrity": "be333e62f2c754f8bf75a38c8177515b152040572c9f75298e9bcef1314b82ff", - "dependencies": [ - "jsr:@std/fmt@^1.0.10" - ] - }, - "@david/console-static-text@0.3.4": { - "integrity": "1c596f500b075ff3c8bab1d328ca7148a88067fd9a506b16a73eeaf230c229fd" + "@david/console-static-text@0.3.5": { + "integrity": "7a6ab3610e6f0fa5743d56f7a05347a96afa9fae19de2d84ff964f09de441101" }, "@david/dax@0.44.1": { "integrity": "200cbb2f85d833e657acd50dfceb92aa6c5330a48dd36e85e4e9f6a3a457609c" @@ -108,11 +50,11 @@ "jsr:@david/path@~0.3.2", "jsr:@david/shell", "jsr:@david/which@0.7", - "jsr:@std/fmt@1" + "jsr:@std/fmt" ] }, - "@david/path@0.3.3": { - "integrity": "19887b1c4ff36d1719b1697b4c10071853f13a85cf60e8713f6a6947e86271b0", + "@david/path@0.3.4": { + "integrity": "6e9c8e8914401fa7489c50cc9214d5593229bdeb96b23c494f43ed2a518cbf67", "dependencies": [ "jsr:@std/path@^1.1.6" ] @@ -123,13 +65,13 @@ "jsr:@david/console-static-text", "jsr:@david/path@0.3", "jsr:@david/which@~0.7.1", - "jsr:@std/fmt@1", + "jsr:@std/fmt", "jsr:@std/io@0.225", "jsr:@std/path@1" ] }, - "@david/which@0.7.3": { - "integrity": "ad6697179c4a153b774c59d06ebc056c4f87a9c27117ff74eecb120c245a2aea" + "@david/which@0.7.4": { + "integrity": "b4ed8e7f489b3689afb4b8315944211c807f91c03229e48ab888e55336c73087" }, "@std/assert@1.0.16": { "integrity": "6a7272ed1eaa77defe76e5ff63ca705d9c495077e2d5fd0126d2b53fc5bd6532" @@ -175,12 +117,6 @@ "dependencies": [ "jsr:@std/internal@^1.0.14" ] - }, - "@std/semver@1.0.8": { - "integrity": "dc830e8b8b6a380c895d53fbfd1258dc253704ca57bbe1629ac65fd7830179b7" - }, - "@std/text@1.0.19": { - "integrity": "003a0e032d360e8c3a4e0410fb792c77a66bd6553fee9d60c6ec1bce30d29223" } }, "npm": { @@ -204,6 +140,12 @@ "@babel/runtime@7.29.7": { "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==" }, + "@commander-js/extra-typings@15.0.0_commander@15.0.0": { + "integrity": "sha512-yeJlba62xqmkgELUsn7356MEnzLLu/fw2x4lofFqGnXh6YysRdEs2BaLeLtg1+KU0AXvMeqQvTTp+3hBEBK+EA==", + "dependencies": [ + "commander@15.0.0" + ] + }, "@google/genai@2.21.0": { "integrity": "sha512-+PDtco2/Z0ONdzCGekCoCT+O1VJS9xJQNN4XzQpXG/t3El/SWWMkCWlFRO1KmivOHPa4Q0VjUYu1HBKCZ/v33Q==", "dependencies": [ @@ -214,6 +156,27 @@ ], "scripts": true }, + "@inquirer/ansi@2.0.9": { + "integrity": "sha512-0Ywt3S8tqM6TWUcsRlBFQ1x+X3/o8kktX0ZiKAnByYb9GFDknnOhse1PVtfiD2BXPI8ar+BWx9PV9R0lQIcygw==" + }, + "@inquirer/core@12.0.4": { + "integrity": "sha512-M5fB67y7jPObI45vhD82RskWwCSm0scOvenV/I6K8tIi2gfr9DXqQqJ+iw+Wi6SgapikdOiJibYzz1gW47fsDg==", + "dependencies": [ + "@inquirer/ansi", + "@inquirer/figures", + "@inquirer/type", + "cli-width", + "fast-wrap-ansi", + "mute-stream", + "signal-exit" + ] + }, + "@inquirer/figures@2.0.9": { + "integrity": "sha512-EAWgUTGQ/Umgga51dE3B2PUHbufuXarDfg86uVgoSgNHNNQnyFKcOrQLWVqYMghuSyHh8+2HUH0Js9cTC1WAdg==" + }, + "@inquirer/type@4.2.0": { + "integrity": "sha512-2rnHX8RPo4glJYqnFc/v3nQeIhDcjyRRyaT7MGcfL/8xv/8K03SXYoA2tX06WVSKywWOE/ncbG3dtuzLjR5TCQ==" + }, "@mathjax/mathjax-newcm-font@4.1.3": { "integrity": "sha512-gzAB3dFHilHX1l5x2xUqRL+1jDQt3Fyza1DkEMVXWC4E8SvsGdlgEza47HYi2WhVcgfkvf4zgUGzuhbq3Pjlew==" }, @@ -413,12 +376,18 @@ "character-entities-legacy@3.0.0": { "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==" }, + "cli-width@4.1.0": { + "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==" + }, "comma-separated-tokens@2.0.3": { "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==" }, "commander@14.0.3": { "integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==" }, + "commander@15.0.0": { + "integrity": "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==" + }, "data-uri-to-buffer@4.0.1": { "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==" }, @@ -452,6 +421,21 @@ "fast-sha256@1.3.0": { "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==" }, + "fast-string-truncated-width@3.0.3": { + "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==" + }, + "fast-string-width@3.0.2": { + "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==", + "dependencies": [ + "fast-string-truncated-width" + ] + }, + "fast-wrap-ansi@0.2.2": { + "integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==", + "dependencies": [ + "fast-string-width" + ] + }, "fetch-blob@3.2.0": { "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", "dependencies": [ @@ -656,6 +640,9 @@ "ms@2.1.3": { "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" }, + "mute-stream@3.0.0": { + "integrity": "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==" + }, "node-domexception@1.0.0": { "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", "deprecated": true @@ -767,6 +754,9 @@ "@types/hast" ] }, + "signal-exit@4.1.0": { + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==" + }, "space-separated-tokens@2.0.2": { "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==" }, @@ -774,7 +764,7 @@ "integrity": "sha512-3dFcH2QtQNhtvUUc09TxoaEK4WG03B9Z57krFG9jocrKykKGu35BhIkWr0vgEAxZZomEWkeluff69y/EbYzP4Q==", "dependencies": [ "@xmldom/xmldom", - "commander", + "commander@14.0.3", "wicked-good-xpath" ], "bin": true @@ -907,21 +897,21 @@ }, "workspace": { "dependencies": [ - "jsr:@cliffy/command@1.2.1", - "jsr:@cliffy/prompt@1.2.1", - "jsr:@cliffy/table@1.2.1", "jsr:@david/dax@0.49", "jsr:@std/assert@^1.0.19", "jsr:@std/encoding@^1.0.11", "jsr:@std/io@~0.225.3", "jsr:@std/path@^1.1.6", "npm:@anthropic-ai/sdk@0.123.0", + "npm:@commander-js/extra-typings@15", "npm:@google/genai@2.21.0", + "npm:@inquirer/core@12", "npm:@mathjax/src@4.1.3", "npm:@resvg/resvg-wasm@2.6.2", "npm:@shikijs/cli@^4.4.3", "npm:ansis@^4.3.1", "npm:arktype@^2.2.3", + "npm:commander@15", "npm:json5@^2.2.3", "npm:markdown-exit@^1.3.0", "npm:openai@7.21.0", diff --git a/errors.ts b/errors.ts new file mode 100644 index 0000000..d4b3bc5 --- /dev/null +++ b/errors.ts @@ -0,0 +1,5 @@ +/** + * A problem with the user's input or state. The CLI reports these as a plain + * error message instead of a stack trace. + */ +export class ValidationError extends Error {} diff --git a/main.ts b/main.ts index e55798e..1a3cc4f 100755 --- a/main.ts +++ b/main.ts @@ -1,9 +1,9 @@ #! /usr/bin/env -S deno run --allow-env --allow-read --allow-write --allow-net --allow-run=gh,osascript,sips import { readAll } from "@std/io" -import { Command, EnumType, ValidationError } from "@cliffy/command" -import { Table } from "@cliffy/table" +import { Command, InvalidArgumentError, Option } from "@commander-js/extra-typings" import $ from "@david/dax" +import { blueBright, bold, magentaBright, red } from "ansis" import * as R from "remeda" @@ -21,6 +21,7 @@ import { shortDateFmt, } from "./display.ts" import { parseMessageSpec, resolveImage } from "./utils.ts" +import { ValidationError } from "./errors.ts" import { type Chat, resolveThink, type ThinkOverride } from "./types.ts" import { type ChatInput, @@ -35,7 +36,7 @@ import { History } from "./storage.ts" import { genMissingSummaries } from "./summarize.ts" import { parseType } from "./schema.ts" import { requestProblems, usesBackground } from "./validate.ts" -import { formatPickerOptions, pickWithAction, singleLine } from "./picker.ts" +import { alignColumns, formatPickerOptions, pickWithAction, singleLine } from "./picker.ts" const getLastModelId = (chat: Chat) => chat.messages.findLast((m) => m.role === "assistant")?.model @@ -55,14 +56,13 @@ function chatPickerOptions(chats: Chat[]) { })) } -/** use cliffy's table to align columns for message picker, then split on newline to get lines as strings */ +/** One line per message for the fork picker, with columns aligned */ function messagePickerOptions(messages: Chat["messages"]) { - const table = new Table(...messages.map((msg, i) => { + return alignColumns(messages.map((msg, i) => { const preview = truncate(msg.content.replace(/\n/g, " "), 50) const actor = msg.role === "assistant" ? msg.model : "user" return [`${i + 1}`, actor, preview] })) - return table.padding(3).toString().split("\n") } const bell = () => Deno.stdout.write(new TextEncoder().encode("\x07")) @@ -308,100 +308,6 @@ async function historyPicker() { } } -const historyCmd = new Command() - .description("Browse recent chats: resume, show, fork, or delete") - .action(historyPicker) - .command("delete", "Pick recent chats to delete") - .action(async () => { - const history = History.list() - await genMissingSummaries(history) - if (history.length === 0) throw new ValidationError("No chat history") - - const reversed = R.reverse(history) - const selected = await $.multiSelect({ - message: "Pick chats to delete", - options: chatPickerOptions(reversed), - noClear: true, - }) - if (selected.length === 0) return - const label = `${selected.length} chat${selected.length === 1 ? "" : "s"}` - const yes = await $.maybeConfirm(`Delete ${label}?`, { noClear: true }) - if (!yes) return - History.delete(selected.map((s) => reversed[s.index].id)) - console.log(`Deleted ${label}`) - }) - .command("clear", "Delete saved chat history") - .action(async () => { - const history = History.list() - const n = history.length - const yes = await $.maybeConfirm(`Delete ${n} chats?`, { noClear: true }) - if (!yes) return - History.clear() - console.log("Deleted chat history") - }) - -const showCmd = new Command() - .description("Show chat so far (last N, default 1)") - .option("-a, --all", "Show all messages") - .option("-n, --limit ", "Number of messages (default 1)", { default: 1 }) - .option( - "-p, --pick ", - "Pick specific messages (e.g., '1,3-4,7', 'even', 'odd')", - ) - .option("-v, --verbose", "Include reasoning in output") - .option("--raw", "Print LLM output directly (no metadata or reasoning)") - .action(async (opts) => { - const chat = History.current() - if (!chat) throw new ValidationError("No chat in progress") - const mode = getMode(opts) - if (opts.pick) { - const indices = parseMessageSpec(opts.pick, chat.messages.length) - await renderMd(chatToMd({ chat, indices, mode }), opts.raw) - } else { - const lastN = opts.all ? chat.messages.length : opts.limit - await renderMd(chatToMd({ chat, lastN, mode }), opts.raw) - } - }) - -const gistCmd = new Command() - .description("Save chat to GitHub Gist with gh CLI") - .option("-t, --title ", "Gist title") - .option("-a, --all", "Include all messages") - .option("-n, --limit <n:integer>", "Number of messages (default 1)", { default: 1 }) - .option( - "-p, --pick <spec:string>", - "Pick specific messages (e.g., '1,3-4,7', 'even', 'odd')", - ) - .option("--id <id:string>", "Replace contents of an existing gist by ID") - .action(async (opts) => { - const lastChat = History.current() - if (!lastChat) throw new ValidationError("No chat in progress") - await genMissingSummaries([lastChat]) - - if (!$.commandExistsSync("gh")) { - throw new Error( - "Creating a gist requires the `gh` CLI (https://cli.github.com/)", - ) - } - - let md: string - if (opts.pick) { - const indices = parseMessageSpec(opts.pick, lastChat.messages.length) - md = chatToMd({ chat: lastChat, indices, mode: "gist" }) - } else { - const n = opts.all ? lastChat.messages.length : opts.limit - md = chatToMd({ chat: lastChat, lastN: n, mode: "gist" }) - } - - if (opts.id) { - await $`gh gist edit ${opts.id} -`.stdinText(md) - } else { - const title = opts.title || lastChat.summary - const filename = title ? `LLM chat - ${title}.md` : "LLM chat.md" - await $`gh gist create -f ${filename} --web`.stdinText(md) - } - }) - function modelInfoMd(modelArg: string) { const model = resolveModel(modelArg) const { provider, key, id } = model @@ -436,80 +342,38 @@ function modelInfoMd(modelArg: string) { return lines.join("\n") } -const modelsCmd = new Command() - .description("List models or show info for a specific model") - .argument("[model:string]", "Model key or substring") - .option("-v, --verbose", "Show model keys") - .action((opts, modelArg) => { - if (modelArg) { - renderMd(modelInfoMd(modelArg)) - } else { - renderMd(modelsMd(opts.verbose)) - } - }) - function exit(msg: string): never { console.log(msg) Deno.exit() } -const bgCmd = new Command() - .description("Manage background responses") - .action(() => { - throw new ValidationError("Subcommand required") - }) - .command("status", "Check status of current chat's background request") - .action(async () => { - const chat = History.findLatestBackground() - if (!chat?.background) exit("No background task found") - - const status = await gptBg.status(chat.background.id) - const elapsed = Date.now() - chat.background.startedAt.getTime() - console.log(`${formatElapsed(elapsed)} (${status})`) - }) - .command("resume", "Resume polling for current chat's background request") - .action(async () => { - const chat = History.findLatestBackground() - if (!chat?.background) exit("No background task found") - - const model = { id: chat.background.modelId, provider: chat.background.provider } - await pollBackgroundResponse(chat, model, {}) - History.save(chat) - }) - .command("cancel", "Cancel current chat's background request") - .action(async () => { - const chat = History.findLatestBackground() - if (!chat?.background) exit("No background task found") +/** Commander option parser for integer values */ +function parseInteger(value: string) { + const n = Number(value) + if (!Number.isInteger(n)) throw new InvalidArgumentError("Not an integer.") + return n +} - await gptBg.cancel(chat.background.id) - delete chat.background - History.save(chat) - console.log("Background response cancelled") - }) +/** Commander option parser for repeatable options */ +const collect = (value: string, previous: string[] = []) => [...previous, value] -await new Command() +const program = new Command() .name("ai") - .description(` -Input from [message], stdin, or --image is required unless using a + .description(`Input from [message], stdin, or --image is required unless using a command. If both message and stdin are present, stdin will be appended -to MESSAGE. - -By default, this script will attempt to render output with glow, -but if glow is not present or output is being piped, it will print -the raw output to stdout.`) - // top level subcommands - .command("show", showCmd) - .command("history", historyCmd) - .command("gist", gistCmd) - .command("models", modelsCmd) - .command("bg", bgCmd) - .reset() - // top level `ai hello how are you` command +to MESSAGE.`) + .helpCommand(false) + // subcommands copy these settings, so they get the same colors + .configureHelp({ + styleTitle: bold, + styleOptionText: blueBright, + styleSubcommandText: blueBright, + styleArgumentText: magentaBright, + }) + .configureOutput({ outputError: (str, write) => write(red(str)) }) .argument("[message...]", "Message to send to the LLM") - .helpOption("-h, --help", "Show help") - .help({ hints: false }) .option("-r, --reply", "Continue existing chat") - .option("-m, --model <model:string>", "Select model by substring (e.g., 'sonnet')") + .option("-m, --model <model>", "Select model by substring (e.g., 'sonnet')") .option("-s, --search", "Enable web search (sticky: stays on for -r replies)") .option("--no-search", "Disable web search for this turn") .option("--think", "Enable thinking") @@ -517,35 +381,40 @@ the raw output to stdout.`) .option("-q, --quick", "Minimize thinking") .option("--think-default", "Clear inherited thinking and use the model default") .option( - "-i, --image <value:string>", + "-i, --image <value>", "Image: URL, local file path, or 'clipboard' (macOS). Repeat for multiple images", - { collect: true }, + collect, ) - .type("quality", new EnumType(imageQualities)) - .option("--quality <quality:quality>", "Image quality (image models only)") - .option("--size <size:string>", "Image size, e.g. 1024x1536 or auto (image models only)") - .option("--system <system:string>", "Override entire system prompt") + .addOption( + new Option("--quality <quality>", "Image quality (image models only)") + .choices(imageQualities), + ) + .option("--size <size>", "Image size, e.g. 1024x1536 or auto (image models only)") + .option("--system <system>", "Override entire system prompt") .option("-e, --ephemeral", "Don't save to history") .option("-b, --background", "Use background mode (OpenAI only)") .option("-v, --verbose", "Include reasoning in output") .option("--raw", "Print LLM text directly (no metadata or reasoning)") - .option("--json", "Print the full response message as JSON (for scripts)", { - conflicts: ["raw", "verbose"], - }) - .option("-o, --output-schema <schema:string>", "ArkType schema for structured output") - .example("1)", "ai 'What is the capital of France?'") - .example("2)", "cat main.ts | ai 'what is this?'") - .example("3)", "echo 'what are you?' | ai") - .example("4)", "ai -r 'elaborate on that'") - .example("5)", "ai -m 4o 'What are generic types?'") - .example( - "6)", - "ai -o '{ urgent: \"boolean\", reason: \"string\" }' 'is this urgent? server is down'", + .addOption( + new Option("--json", "Print the full response message as JSON (for scripts)") + .conflicts(["raw", "verbose"]), + ) + .option("-o, --output-schema <schema>", "ArkType schema for structured output") + .addHelpText( + "after", + ` +Examples: + ai 'What is the capital of France?' + cat main.ts | ai 'what is this?' + echo 'what are you?' | ai + ai -r 'elaborate on that' + ai -m 4o 'What are generic types?' + ai -o '{ urgent: "boolean", reason: "string" }' 'is this urgent? server is down' + ai gist -t 'Generic types' + ai -m flare --quality low 'a lighthouse at dusk' + ai -i first.png -i second.jpg 'Compare these images'`, ) - .example("7)", "ai gist -t 'Generic types'") - .example("8)", "ai -m flare --quality low 'a lighthouse at dusk'") - .example("9)", "ai -i first.png -i second.jpg 'Compare these images'") - .action(async (opts, ...args) => { + .action(async (message, opts) => { let outputSchema if (opts.outputSchema) { try { @@ -558,7 +427,7 @@ the raw output to stdout.`) const imageInputs = opts.image ?? [] const hasImages = imageInputs.length > 0 - const msg = args.join(" ") + const msg = message.join(" ") const piped = !Deno.stdin.isTerminal() const stdin = piped // read stdin to end @@ -657,4 +526,159 @@ the raw output to stdout.`) if (!opts.ephemeral) History.save(chat, { current: true, touch: true }) }) - .parse(Deno.args) + +program + .command("show") + .description("Show chat so far (last N, default 1)") + .option("-a, --all", "Show all messages") + .option("-n, --limit <n>", "Number of messages", parseInteger, 1) + .option("-p, --pick <spec>", "Pick specific messages (e.g., '1,3-4,7', 'even', 'odd')") + .option("-v, --verbose", "Include reasoning in output") + .option("--raw", "Print LLM output directly (no metadata or reasoning)") + .action(async (opts) => { + const chat = History.current() + if (!chat) throw new ValidationError("No chat in progress") + const mode = getMode(opts) + if (opts.pick) { + const indices = parseMessageSpec(opts.pick, chat.messages.length) + await renderMd(chatToMd({ chat, indices, mode }), opts.raw) + } else { + const lastN = opts.all ? chat.messages.length : opts.limit + await renderMd(chatToMd({ chat, lastN, mode }), opts.raw) + } + }) + +const historyCmd = program + .command("history") + .description("Browse recent chats: resume, show, fork, or delete") + .action(historyPicker) + +historyCmd + .command("delete") + .description("Pick recent chats to delete") + .action(async () => { + const history = History.list() + await genMissingSummaries(history) + if (history.length === 0) throw new ValidationError("No chat history") + + const reversed = R.reverse(history) + const selected = await $.multiSelect({ + message: "Pick chats to delete", + options: chatPickerOptions(reversed), + noClear: true, + }) + if (selected.length === 0) return + const label = `${selected.length} chat${selected.length === 1 ? "" : "s"}` + const yes = await $.maybeConfirm(`Delete ${label}?`, { noClear: true }) + if (!yes) return + History.delete(selected.map((s) => reversed[s.index].id)) + console.log(`Deleted ${label}`) + }) + +historyCmd + .command("clear") + .description("Delete saved chat history") + .action(async () => { + const history = History.list() + const n = history.length + const yes = await $.maybeConfirm(`Delete ${n} chats?`, { noClear: true }) + if (!yes) return + History.clear() + console.log("Deleted chat history") + }) + +program + .command("gist") + .description("Save chat to GitHub Gist with gh CLI") + .option("-t, --title <title>", "Gist title") + .option("-a, --all", "Include all messages") + .option("-n, --limit <n>", "Number of messages", parseInteger, 1) + .option("-p, --pick <spec>", "Pick specific messages (e.g., '1,3-4,7', 'even', 'odd')") + .option("--id <id>", "Replace contents of an existing gist by ID") + .action(async (opts) => { + const lastChat = History.current() + if (!lastChat) throw new ValidationError("No chat in progress") + await genMissingSummaries([lastChat]) + + if (!$.commandExistsSync("gh")) { + throw new Error( + "Creating a gist requires the `gh` CLI (https://cli.github.com/)", + ) + } + + let md: string + if (opts.pick) { + const indices = parseMessageSpec(opts.pick, lastChat.messages.length) + md = chatToMd({ chat: lastChat, indices, mode: "gist" }) + } else { + const n = opts.all ? lastChat.messages.length : opts.limit + md = chatToMd({ chat: lastChat, lastN: n, mode: "gist" }) + } + + if (opts.id) { + await $`gh gist edit ${opts.id} -`.stdinText(md) + } else { + const title = opts.title || lastChat.summary + const filename = title ? `LLM chat - ${title}.md` : "LLM chat.md" + await $`gh gist create -f ${filename} --web`.stdinText(md) + } + }) + +program + .command("models") + .description("List models or show info for a specific model") + .argument("[model]", "Model key or substring") + .option("-v, --verbose", "Show model keys") + .action((modelArg, opts) => { + if (modelArg) { + renderMd(modelInfoMd(modelArg)) + } else { + renderMd(modelsMd(opts.verbose)) + } + }) + +const bgCmd = program.command("bg").description("Manage background responses") + +bgCmd + .command("status") + .description("Check status of current chat's background request") + .action(async () => { + const chat = History.findLatestBackground() + if (!chat?.background) exit("No background task found") + + const status = await gptBg.status(chat.background.id) + const elapsed = Date.now() - chat.background.startedAt.getTime() + console.log(`${formatElapsed(elapsed)} (${status})`) + }) + +bgCmd + .command("resume") + .description("Resume polling for current chat's background request") + .action(async () => { + const chat = History.findLatestBackground() + if (!chat?.background) exit("No background task found") + + const model = { id: chat.background.modelId, provider: chat.background.provider } + await pollBackgroundResponse(chat, model, {}) + History.save(chat) + }) + +bgCmd + .command("cancel") + .description("Cancel current chat's background request") + .action(async () => { + const chat = History.findLatestBackground() + if (!chat?.background) exit("No background task found") + + await gptBg.cancel(chat.background.id) + delete chat.background + History.save(chat) + console.log("Background response cancelled") + }) + +try { + await program.parseAsync(Deno.args, { from: "user" }) +} catch (e) { + if (e instanceof ValidationError) program.error(`error: ${e.message}`) + throw e +} diff --git a/models.ts b/models.ts index 2852d8e..174fdfc 100644 --- a/models.ts +++ b/models.ts @@ -1,4 +1,4 @@ -import { ValidationError } from "@cliffy/command" +import { ValidationError } from "./errors.ts" import { type TokenCounts } from "./types.ts" import $ from "@david/dax" diff --git a/models_test.ts b/models_test.ts index 66973fb..5b1385d 100644 --- a/models_test.ts +++ b/models_test.ts @@ -1,5 +1,5 @@ import { assertAlmostEquals, assertEquals, assertThrows } from "@std/assert" -import { ValidationError } from "@cliffy/command" +import { ValidationError } from "./errors.ts" import { getCost, type Model, models, resolveModel } from "./models.ts" const testModels: Model[] = [ diff --git a/picker.ts b/picker.ts index cf5daad..adc173d 100644 --- a/picker.ts +++ b/picker.ts @@ -1,5 +1,16 @@ import stringWidth from "string-width" -import { Select } from "@cliffy/prompt/select" +import { + createPrompt, + ExitPromptError, + isDownKey, + isEnterKey, + isUpKey, + makeTheme, + useKeypress, + usePagination, + usePrefix, + useState, +} from "@inquirer/core" const COLUMN_GAP = 3 const SELECT_PREFIX_WIDTH = 2 @@ -49,6 +60,15 @@ function padEnd(text: string, width: number): string { return text + " ".repeat(width - stringWidth(text)) } +/** Pad each column to its widest cell so rows line up. The last column isn't padded. */ +export function alignColumns(rows: string[][]): string[] { + const widths = rows[0]?.map((_, i) => maxWidth(rows.map((row) => row[i]))) ?? [] + return rows.map((row) => + row.map((cell, i) => i < row.length - 1 ? padEnd(cell, widths[i]) : cell) + .join(" ".repeat(COLUMN_GAP)) + ) +} + /** Format one single-line selector option per row, fitting the summary to the terminal. */ export function formatPickerOptions( rows: PickerRow[], @@ -99,32 +119,55 @@ export function keyAction(event: KeyEvent): PickerAction | "quit" | undefined { return ACTION_KEYS[key] } -/** Cliffy select where letter keys submit the highlighted row with an action. */ -class ActionSelect extends Select<string> { - action: PickerAction | "quit" | undefined - - protected override async handleEvent(event: KeyEvent): Promise<void> { - const action = keyAction(event) - if (action) { - this.action = action - await this.submit() - return - } - // deno-lint-ignore no-explicit-any - await super.handleEvent(event as any) +type Picked = { index: number; action: PickerAction | "quit" } + +/** Select where Enter resumes and letter keys submit the highlighted row with an action. */ +const actionSelect = createPrompt< + Picked, + { + message: string + options: string[] + initialIndex?: number + hint: string + pageSize: number } +>((config, done) => { + const theme = makeTheme() + const [active, setActive] = useState(config.initialIndex ?? 0) + const [picked, setPicked] = useState<Picked | undefined>(undefined) + const status = picked ? "done" : "idle" + const prefix = usePrefix({ status, theme }) + const last = config.options.length - 1 + + useKeypress((key) => { + const action = isEnterKey(key) ? "resume" : keyAction(key) + if (action) { + const result = { index: active, action } + setPicked(result) + done(result) + } else if (isUpKey(key, ["vim"])) setActive(Math.max(0, active - 1)) + else if (isDownKey(key, ["vim"])) setActive(Math.min(last, active + 1)) + else if (key.name === "pageup") setActive(Math.max(0, active - config.pageSize)) + else if (key.name === "pagedown") setActive(Math.min(last, active + config.pageSize)) + }) - // We only use `default` to place the cursor, so don't echo it after the message - protected override defaults(): string { - return "" - } + const page = usePagination({ + items: config.options, + active, + pageSize: config.pageSize, + loop: false, + renderItem: ({ item, isActive }) => + isActive ? theme.style.highlight(`❯ ${item}`) : ` ${item}`, + }) + const message = theme.style.message(config.message, status) - protected override success(value: string): string | undefined { + if (picked) { // Quitting and deleting leave no trace of the prompt - if (this.action === "quit" || this.action === "delete") return undefined - return super.success(value) + if (picked.action === "quit" || picked.action === "delete") return "" + return `${prefix} ${message} ${theme.style.answer(config.options[picked.index])}` } -} + return [`${prefix} ${message}\n${page}`, theme.style.help(config.hint)] +}) function terminalRows(): number { try { @@ -143,25 +186,17 @@ export async function pickWithAction(opts: { options: string[] initialIndex?: number }): Promise<{ index: number; action: PickerAction } | undefined> { - const hint = "enter resume · s show last · S show all · f fork · d delete · q quit" - const select = new ActionSelect({ - message: opts.message, - options: opts.options.map((name, i) => ({ name, value: String(i) })), - default: opts.initialIndex === undefined ? undefined : String(opts.initialIndex), - hint, - // leave room for the message and hint lines - maxRows: Math.max(3, terminalRows() - 3), - // The default keymap puts several letters on navigation (d, n, u, p, h, l) - keys: { - next: ["down", "j"], - previous: ["up", "k"], - nextPage: ["pagedown"], - previousPage: ["pageup"], - open: [], - back: [], - }, - }) - const value = await select.prompt() - if (select.action === "quit") return undefined - return { index: Number(value), action: select.action ?? "resume" } + try { + const { index, action } = await actionSelect({ + ...opts, + hint: "enter resume · s show last · S show all · f fork · d delete · q quit", + // leave room for the message and hint lines + pageSize: Math.max(3, terminalRows() - 3), + }) + return action === "quit" ? undefined : { index, action } + } catch (e) { + // Ctrl+C + if (e instanceof ExitPromptError) return undefined + throw e + } } diff --git a/picker_test.ts b/picker_test.ts index 50795a7..3714aee 100644 --- a/picker_test.ts +++ b/picker_test.ts @@ -1,6 +1,6 @@ import { assert, assertEquals } from "@std/assert" import stringWidth from "string-width" -import { formatPickerOptions, keyAction } from "./picker.ts" +import { alignColumns, formatPickerOptions, keyAction } from "./picker.ts" Deno.test("picker options stay single-line and preserve their row mapping", () => { const options = formatPickerOptions([ @@ -48,3 +48,17 @@ Deno.test("picker keys map to actions and leave navigation alone", () => { assertEquals(keyAction({ name: "d", ctrl: true }), undefined) assertEquals(keyAction({ name: "c", ctrl: true }), undefined) }) + +Deno.test("alignColumns pads every column but the last to its widest cell", () => { + assertEquals( + alignColumns([ + ["1", "user", "hello"], + ["10", "opus-5 🦀", "hi"], + ]), + [ + "1 user hello", + "10 opus-5 🦀 hi", + ], + ) + assertEquals(alignColumns([]), []) +}) diff --git a/utils.ts b/utils.ts index 8467ef0..7139a72 100644 --- a/utils.ts +++ b/utils.ts @@ -1,4 +1,4 @@ -import { ValidationError } from "@cliffy/command" +import { ValidationError } from "./errors.ts" import { encodeBase64 } from "@std/encoding/base64" import { join } from "@std/path" import $ from "@david/dax" diff --git a/utils_test.ts b/utils_test.ts index 89f624d..a0365f3 100644 --- a/utils_test.ts +++ b/utils_test.ts @@ -1,5 +1,5 @@ import { assertEquals, assertRejects, assertThrows } from "@std/assert" -import { ValidationError } from "@cliffy/command" +import { ValidationError } from "./errors.ts" import { dirname, join } from "@std/path" import { parseDataUrl, parseMessageSpec, resolveImage } from "./utils.ts"