From c7b60d3be5a09fbdc56eb05e90116259d8cd1b21 Mon Sep 17 00:00:00 2001 From: David Crespo Date: Tue, 20 Oct 2026 16:42:20 -0500 Subject: [PATCH 1/2] Switch formatter to oxfmt --- .github/workflows/ci.yml | 4 - .oxfmtrc.json | 7 + deno.jsonc | 9 - package-lock.json | 414 +++++++++++++++++++++++++++++++++++++++ package.json | 5 +- 5 files changed, 424 insertions(+), 15 deletions(-) create mode 100644 .oxfmtrc.json delete mode 100644 deno.jsonc diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b0f8855..2fa330a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,9 +18,5 @@ jobs: with: node-version: 24 cache: npm - # deno fmt until the switch to oxfmt - - uses: denoland/setup-deno@v2 - with: - deno-version: v2.x - run: npm ci - run: npm run ci diff --git a/.oxfmtrc.json b/.oxfmtrc.json new file mode 100644 index 0000000..c42978f --- /dev/null +++ b/.oxfmtrc.json @@ -0,0 +1,7 @@ +{ + "$schema": "./node_modules/oxfmt/configuration_schema.json", + "printWidth": 92, + "semi": false, + "proseWrap": "always", + "ignorePatterns": ["fixtures/terminal-math.md", "package-lock.json", ".claude"] +} diff --git a/deno.jsonc b/deno.jsonc deleted file mode 100644 index dc8fc9d..0000000 --- a/deno.jsonc +++ /dev/null @@ -1,9 +0,0 @@ -// Only `deno fmt` still uses Deno, until it's replaced by oxfmt. -{ - "fmt": { - // Preserve math delimiters and TeX lines that look like Markdown syntax. - "exclude": ["fixtures/terminal-math.md", "package-lock.json", ".claude"], - "lineWidth": 92, - "semiColons": false - } -} diff --git a/package-lock.json b/package-lock.json index 4f2478b..6b93368 100644 --- a/package-lock.json +++ b/package-lock.json @@ -32,6 +32,7 @@ }, "devDependencies": { "@types/node": "^24.19.2", + "oxfmt": "^0.74.0", "oxlint": "^1.89.0", "typescript": "^7.0.2" }, @@ -479,6 +480,353 @@ "speech-rule-engine": "5.0.0-rc.4" } }, + "node_modules/@oxfmt/binding-android-arm-eabi": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.74.0.tgz", + "integrity": "sha512-xxQwrf5EPI5zxvuCTW8r6tzCTjPQ+h6+HqJ0iRKRy2zS1yBllt/xLVjoIyUc+FnR7g0a5g1SZv2yyDYhTItLbA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-android-arm64": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.74.0.tgz", + "integrity": "sha512-FJW3sATVvrWbV64al8xofCPZj4500Z/1W0ad7Tg1rcCUyh0EMbuSrsf3jsZS7CEbwQ5fQ0mRhmkc129GFgofSQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-darwin-arm64": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.74.0.tgz", + "integrity": "sha512-TfmNKBD30dGyMu9GCLiaw2rt/z7fms9LS+5cKcNOyWst0QgAs8oZs6wPxMbVaaDVE0/PCdCosgWM1vbu6f5NUg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-darwin-x64": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.74.0.tgz", + "integrity": "sha512-5Usf8+DfC4Q3o/MD8FkN47GrI6y0KbhQ4KhZ2HGzMZcXjcW1AeldwbUn51aKih+1TVuJFF9qkNm6X1nzm6NYng==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-freebsd-x64": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.74.0.tgz", + "integrity": "sha512-eL+1O3gykw1XihbZh2MRAciQvU2988LByrnjhyo/dmNG74X4oZ7XzigRoWPRFLfJCp8hzRkp/LbEhwe7uuT2eA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm-gnueabihf": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.74.0.tgz", + "integrity": "sha512-Xt0QtO2hJ4stnul8IL4LJGVLyp0xnc6ccN9fZ30yuubv8FWSRYxWwd1Za62KsEqAfmPSazoS/cLSUUJpja6npA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm-musleabihf": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.74.0.tgz", + "integrity": "sha512-/4wYQ0gZl4vUR0QoBTGaay73FmQ1GAjUa9z9101TR2xbGNrg4a+grazlR0yzEOe3/E+PJr5BGfj66MMzm/54vg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm64-gnu": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.74.0.tgz", + "integrity": "sha512-846bKzF+HJd+JkOFh3rxzmYvSq4Cm+GMT+p+mW7S13ZYo6GAAGv8bL8cAOi/XcdeMqxEJDCIMTVQLVBXHMCdig==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm64-musl": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.74.0.tgz", + "integrity": "sha512-nI5FJwZ4Flo6CBdscpwxymZXxO3m3IErQJX55ZS6h+ObfGXu8FostL85L/RWPFaCLnIVE4/WfLw+2q8XvVEeUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-ppc64-gnu": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.74.0.tgz", + "integrity": "sha512-BoQYKuqUdsKAFAkK6DLBvkdv4+t0hppSm79sB0wIcE2o/eOwNj+6Z3OlKY4q3Eta/tlssP65FaS9vHn8TeF7vQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-riscv64-gnu": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.74.0.tgz", + "integrity": "sha512-FSroRrM12+jCdSQklF9aOxsKpI6wFs4ZCo/1cSYG80RWZS6z4LV+l9tXRMT8lDGu+yohIZBwi9M76FzGPFDE2A==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-riscv64-musl": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.74.0.tgz", + "integrity": "sha512-0VLQD0dhGBLY9Ik/w+otMvD81D0YXi4VDwql65macV+O9UzmSWmUr6CKf+dMtysDeC0PnG3y6kBkRO08BJx52g==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-s390x-gnu": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.74.0.tgz", + "integrity": "sha512-6X7BbZNz34+OHM6Oqjf6TRcUyRn6aRcB4VtIDZAF/uQRyeVhg+G2hv6MlMvmnRekVSyTJ/8rG/u8W2dRFW6glg==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-x64-gnu": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.74.0.tgz", + "integrity": "sha512-4kYIQK53yJXrxwxSzx8H2bojlf6/KezLGYLRXzV9QCCkoiCsvBTCid9Bg83dUPTLPa3g9K0730f6MKDbck1+OA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-x64-musl": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.74.0.tgz", + "integrity": "sha512-MfWz4wDREjp/JQDmuxtKieix4FHGa1z5rBvB3betdcPwZvf5fqeQrlCm1mmoyuUVQOh9Pt3M61HwN94kJCxw7Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-openharmony-arm64": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.74.0.tgz", + "integrity": "sha512-6rmAApkq5s1kbDjvNI6Nl5A+JqQkLORb2sR941pf5HWsrd01WGKyagK/B4vX9+kh1FfvRkNgEu59FHvVk4H8cQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-win32-arm64-msvc": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.74.0.tgz", + "integrity": "sha512-+5SpRUnZNGeXTyumHnpHa791tQtt04qZs076WT8eTcGF2OJ631VLnf7S0kQSPuDG+PtJM0phadEB2WAr5n1w9g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-win32-ia32-msvc": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.74.0.tgz", + "integrity": "sha512-1Fg+wYBO3Dsti1QX+/6EYHjeQzLC84tLOAqPu/r7ah3UJlUs9C/DB703Ay9Vcg+8VMzqZA2P5VGhzJraVUD4OQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-win32-x64-msvc": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.74.0.tgz", + "integrity": "sha512-y9jXUgPBm2TZIWbQhMYRRYAQM57+r4fbykgc+j24ICIIZl+pcuoNhnq1CRGm3oFiHnEUnZO00qOtSPGQdJ2ziQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, "node_modules/@oxlint/binding-android-arm-eabi": { "version": "1.89.0", "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.89.0.tgz", @@ -2330,6 +2678,62 @@ } } }, + "node_modules/oxfmt": { + "version": "0.74.0", + "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.74.0.tgz", + "integrity": "sha512-G4OP7FgwGYZR5ttRpCOOfJdyRsSyvtn34vSXnjDq6Oqed5Dufg5mB44mank+51nAdHOKuTJ0lj0mksY7L+N61A==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinypool": "2.2.0" + }, + "bin": { + "oxfmt": "bin/oxfmt" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + }, + "optionalDependencies": { + "@oxfmt/binding-android-arm-eabi": "0.74.0", + "@oxfmt/binding-android-arm64": "0.74.0", + "@oxfmt/binding-darwin-arm64": "0.74.0", + "@oxfmt/binding-darwin-x64": "0.74.0", + "@oxfmt/binding-freebsd-x64": "0.74.0", + "@oxfmt/binding-linux-arm-gnueabihf": "0.74.0", + "@oxfmt/binding-linux-arm-musleabihf": "0.74.0", + "@oxfmt/binding-linux-arm64-gnu": "0.74.0", + "@oxfmt/binding-linux-arm64-musl": "0.74.0", + "@oxfmt/binding-linux-ppc64-gnu": "0.74.0", + "@oxfmt/binding-linux-riscv64-gnu": "0.74.0", + "@oxfmt/binding-linux-riscv64-musl": "0.74.0", + "@oxfmt/binding-linux-s390x-gnu": "0.74.0", + "@oxfmt/binding-linux-x64-gnu": "0.74.0", + "@oxfmt/binding-linux-x64-musl": "0.74.0", + "@oxfmt/binding-openharmony-arm64": "0.74.0", + "@oxfmt/binding-win32-arm64-msvc": "0.74.0", + "@oxfmt/binding-win32-ia32-msvc": "0.74.0", + "@oxfmt/binding-win32-x64-msvc": "0.74.0" + }, + "peerDependencies": { + "@astrojs/compiler-rs": "^0.4.0 || ^0.5.0", + "svelte": "^5.0.0", + "vite-plus": "*" + }, + "peerDependenciesMeta": { + "@astrojs/compiler-rs": { + "optional": true + }, + "svelte": { + "optional": true + }, + "vite-plus": { + "optional": true + } + } + }, "node_modules/oxlint": { "version": "1.89.0", "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.89.0.tgz", @@ -2682,6 +3086,16 @@ "url": "https://github.com/chalk/supports-hyperlinks?sponsor=1" } }, + "node_modules/tinypool": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-2.2.0.tgz", + "integrity": "sha512-jBrmx4lYmaC9k/mgPbylxs7kBUxHtD8256up+HjLaDFfXScKJQyil+SWXSvhAtT7XHo+yTVlpB81PGmHP8oLSQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.0.0 || >=22.0.0" + } + }, "node_modules/trim-lines": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", diff --git a/package.json b/package.json index d4ffdf2..a9dc870 100644 --- a/package.json +++ b/package.json @@ -10,8 +10,8 @@ }, "scripts": { "ci": "npm run fmt:check && npm run lint && npm run check && npm test", - "fmt": "deno fmt", - "fmt:check": "deno fmt --check", + "fmt": "oxfmt", + "fmt:check": "oxfmt --check", "lint": "oxlint --deny-warnings", "check": "tsc", "test": "node --test '**/*_test.ts'", @@ -41,6 +41,7 @@ }, "devDependencies": { "@types/node": "^24.19.2", + "oxfmt": "^0.74.0", "oxlint": "^1.89.0", "typescript": "^7.0.2" } From e737c4a2e6cbec1ba46cea0a595a589922105071 Mon Sep 17 00:00:00 2001 From: David Crespo Date: Tue, 20 Oct 2026 16:42:43 -0500 Subject: [PATCH 2/2] Reformat with oxfmt --- adapters/claude.ts | 33 ++++++---- adapters/gemini.ts | 57 ++++++++++------- adapters/images_test.ts | 131 +++++++++++++++++++------------------- adapters/openai.ts | 48 +++++++------- adapters/openai_test.ts | 16 ++--- adapters/request_size.ts | 7 +- adapters/types.ts | 2 +- display.ts | 25 +++++--- display_test.ts | 14 ++-- image-input.ts | 37 +++++------ image-input_test.ts | 86 ++++++++++++++----------- main.ts | 90 +++++++++++++------------- markdown-exit-terminal.ts | 47 ++++++-------- math-image.ts | 26 ++++---- md-render_test.ts | 121 ++++++++++++++++------------------- message-spec.ts | 5 +- models.ts | 38 +++++------ package.json | 8 +-- picker.ts | 46 +++++++------ picker_test.ts | 47 ++++++++------ schema_test.ts | 5 +- storage.ts | 21 +++--- storage_test.ts | 10 ++- summarize.ts | 26 ++++---- terminal-image.ts | 6 +- terminal-image_test.ts | 26 ++++---- terminal-math.ts | 94 +++++++++++++++------------ terminal-math_test.ts | 87 ++++++++++++------------- utils_test.ts | 14 +++- 29 files changed, 619 insertions(+), 554 deletions(-) diff --git a/adapters/claude.ts b/adapters/claude.ts index cbe41c3..196eebc 100644 --- a/adapters/claude.ts +++ b/adapters/claude.ts @@ -31,8 +31,9 @@ function claudeMsg( function renderClaudeContentBlock(msg: Anthropic.Beta.Messages.BetaContentBlock) { if (msg.type === "text") { - const citations = (msg.citations || []) - .filter((c) => c.type === "web_search_result_location") + const citations = (msg.citations || []).filter( + (c) => c.type === "web_search_result_location", + ) if (citations.length === 0) return msg.text const unique = uniqueBy(citations, (c) => c.url) const sources = unique.map((c) => `[${c.title || c.url}](${c.url})`).join(" · ") @@ -79,9 +80,13 @@ export function claudeThinkParams(think: ThinkLevel | undefined): ClaudeThinkPar return { thinking, output_config: { effort }, max_tokens, effort } } -export async function claudeCreateMessage( - { chat, model, config, signal, outputSchema }: ChatInput, -) { +export async function claudeCreateMessage({ + chat, + model, + config, + signal, + outputSchema, +}: ChatInput) { const toolsList: Anthropic.Beta.BetaToolUnion[] = [] if (config.search) { toolsList.push({ type: "web_search_20260209", name: "web_search", max_uses: 5 }) @@ -101,7 +106,7 @@ export async function claudeCreateMessage( cache_control: { type: "ephemeral" }, system: chat.systemPrompt, messages: chat.messages.map((m) => - claudeMsg(m.role, m.content, m.role === "user" ? m.image_urls : undefined) + claudeMsg(m.role, m.content, m.role === "user" ? m.image_urls : undefined), ), max_tokens, thinking, @@ -109,16 +114,18 @@ export async function claudeCreateMessage( tools: toolsList.length > 0 ? toolsList : undefined, } validateRequestSize("Claude", params) - const response = await new Anthropic().beta.messages.create({ - ...params, - betas: ["code-execution-web-tools-2026-02-09"], - }, { signal }) + const response = await new Anthropic().beta.messages.create( + { + ...params, + betas: ["code-execution-web-tools-2026-02-09"], + }, + { signal }, + ) const searches = response.usage.server_tool_use?.web_search_requests ?? 0 - const blocks = response.content.filter((msg) => - msg.type === "text" || (!prep && msg.type === "server_tool_use") - ) + const blocks = response.content + .filter((msg) => msg.type === "text" || (!prep && msg.type === "server_tool_use")) .map(renderClaudeContentBlock) .filter((x): x is string => !!x) diff --git a/adapters/gemini.ts b/adapters/gemini.ts index d7c981f..9a9db10 100644 --- a/adapters/gemini.ts +++ b/adapters/gemini.ts @@ -40,9 +40,13 @@ export function geminiThinkParams(key: string, think: ThinkLevel | undefined) { : { thinkingLevel: ThinkingLevel.LOW, effort: "low" } } -export async function geminiCreateMessage( - { chat, model, config, signal, outputSchema }: ChatInput, -) { +export async function geminiCreateMessage({ + chat, + model, + config, + signal, + outputSchema, +}: ChatInput) { const apiKey = process.env.GEMINI_API_KEY if (!apiKey) throw Error("GEMINI_API_KEY missing") @@ -66,17 +70,19 @@ export async function geminiCreateMessage( { urlContext: {} }, ...(config.search ? [{ googleSearch: {} }] : []), ] - const contents = await Promise.all(chat.messages.map(async (msg) => { - const parts: Part[] = msg.content ? [{ text: msg.content }] : [] - if (msg.role === "user" && msg.image_urls?.length) { - parts.unshift(...await Promise.all(msg.image_urls.map(imageToInlinePart))) - } - return { - // gemini uses model instead of assistant - role: msg.role === "assistant" ? "model" : "user", - parts, - } - })) + const contents = await Promise.all( + chat.messages.map(async (msg) => { + const parts: Part[] = msg.content ? [{ text: msg.content }] : [] + if (msg.role === "user" && msg.image_urls?.length) { + parts.unshift(...(await Promise.all(msg.image_urls.map(imageToInlinePart)))) + } + return { + // gemini uses model instead of assistant + role: msg.role === "assistant" ? "model" : "user", + parts, + } + }), + ) // The SDK moves systemInstruction/tools out of config and places its remaining // fields in generationConfig. Measure that REST body after inlining URL images. validateRequestSize("Gemini", { contents, systemInstruction, tools, generationConfig }) @@ -89,17 +95,23 @@ export async function geminiCreateMessage( // console.log(JSON.stringify(result, null, 2)) const parts = result.candidates?.[0].content?.parts ?? [] - const reasoning = parts.filter((p) => p.text && p.thought).map((p) => p.text!).join( - "\n\n", - ) - let content = parts.filter((p) => p.text && !p.thought).map((p) => p.text!).join("\n\n") + const reasoning = parts + .filter((p) => p.text && p.thought) + .map((p) => p.text!) + .join("\n\n") + let content = parts + .filter((p) => p.text && !p.thought) + .map((p) => p.text!) + .join("\n\n") const searchResults = result.candidates?.[0].groundingMetadata?.groundingChunks const searches = searchResults && searchResults.length > 0 ? 1 : 0 const searchResultsMd = searchResults - ? "\n\n### Sources\n\n" + searchResults - .filter((chunk) => chunk.web) - .map((chunk) => `- [${chunk.web!.title}](${chunk.web!.uri})`).join("\n") + ? "\n\n### Sources\n\n" + + searchResults + .filter((chunk) => chunk.web) + .map((chunk) => `- [${chunk.web!.title}](${chunk.web!.uri})`) + .join("\n") : "" if (!prep) content += searchResultsMd @@ -108,7 +120,8 @@ export async function geminiCreateMessage( const tokens = { input: result.usageMetadata?.promptTokenCount || 0, - output: (result.usageMetadata?.candidatesTokenCount || 0) + + output: + (result.usageMetadata?.candidatesTokenCount || 0) + (result.usageMetadata?.thoughtsTokenCount || 0), input_cache_hit: result.usageMetadata?.cachedContentTokenCount || 0, } diff --git a/adapters/images_test.ts b/adapters/images_test.ts index 3bee72c..8408e56 100644 --- a/adapters/images_test.ts +++ b/adapters/images_test.ts @@ -121,7 +121,7 @@ for (const testCase of cases) { headers: { "content-type": "image/webp; charset=binary" }, }) } - requestBody = await request.json() as Record + requestBody = (await request.json()) as Record return Response.json(testCase.response) } try { @@ -197,7 +197,7 @@ test("OpenAI background requests use high image detail and send only the chained let requestBody: Record | undefined process.env["OPENAI_API_KEY"] = "test-key" globalThis.fetch = async (input, init) => { - requestBody = await new Request(input, init).json() as Record + requestBody = (await new Request(input, init).json()) as Record return Response.json({ id: "new-response", output: [], status: "queued" }) } try { @@ -235,13 +235,15 @@ test("OpenAI background requests use high image detail and send only the chained ], }, }) - assert.deepEqual(requestBody?.input, [{ - role: "user", - content: [ - { type: "input_image", image_url: secondImage, detail: "high" }, - { type: "input_image", image_url: imageUrl, detail: "high" }, - ], - }]) + assert.deepEqual(requestBody?.input, [ + { + role: "user", + content: [ + { type: "input_image", image_url: secondImage, detail: "high" }, + { type: "input_image", image_url: imageUrl, detail: "high" }, + ], + }, + ]) assert.deepEqual(requestBody?.previous_response_id, "previous-response") assert.deepEqual(requestBody?.background, true) assert.deepEqual(requestBody?.store, true) @@ -252,42 +254,40 @@ test("OpenAI background requests use high image detail and send only the chained } }) -for ( - const testCase of [ - { - model: "sonnet", - env: "ANTHROPIC_API_KEY", - images: ["data:image/png;base64," + "A".repeat(10_000_004)], - prompt: "Describe this", - error: "Claude image is larger than the 10 MB base64 limit", - }, - { - model: "sonnet", - env: "ANTHROPIC_API_KEY", - images: Array.from( - { length: 4 }, - () => "data:image/png;base64," + "A".repeat(8_000_000), - ), - prompt: "Compare these", - error: "Claude request is larger than the 32 MB limit", - }, - { - model: "gemini-3.8-flash", - env: "GEMINI_API_KEY", - images: ["data:image/png;base64," + "A".repeat(19_999_000)], - // UTF-8 text and JSON overhead push an otherwise in-limit image over the limit. - prompt: "猫".repeat(400), - error: "Gemini request is larger than the 20 MB limit", - }, - { - model: "gemini-3.8-flash", - env: "GEMINI_API_KEY", - images: [imageUrl], - prompt: "Describe this", - error: "Gemini request is larger than the 20 MB limit", - }, - ] -) { +for (const testCase of [ + { + model: "sonnet", + env: "ANTHROPIC_API_KEY", + images: ["data:image/png;base64," + "A".repeat(10_000_004)], + prompt: "Describe this", + error: "Claude image is larger than the 10 MB base64 limit", + }, + { + model: "sonnet", + env: "ANTHROPIC_API_KEY", + images: Array.from( + { length: 4 }, + () => "data:image/png;base64," + "A".repeat(8_000_000), + ), + prompt: "Compare these", + error: "Claude request is larger than the 32 MB limit", + }, + { + model: "gemini-3.8-flash", + env: "GEMINI_API_KEY", + images: ["data:image/png;base64," + "A".repeat(19_999_000)], + // UTF-8 text and JSON overhead push an otherwise in-limit image over the limit. + prompt: "猫".repeat(400), + error: "Gemini request is larger than the 20 MB limit", + }, + { + model: "gemini-3.8-flash", + env: "GEMINI_API_KEY", + images: [imageUrl], + prompt: "Describe this", + error: "Gemini request is larger than the 20 MB limit", + }, +]) { test(`${testCase.model} rejects oversized encoded images and requests before sending: ${testCase.error}`, async () => { const originalFetch = globalThis.fetch const oldKey = process.env[testCase.env] @@ -307,25 +307,28 @@ for ( return Promise.resolve(Response.json(response)) } try { - await assert.rejects(() => - createMessage({ - model: resolveModel(testCase.model), - config: { search: false, think: undefined }, - chat: { - id: "test", - createdAt: new Date(0), - systemPrompt: "test", - messages: [ - { - role: "user", - content: testCase.prompt, - image_urls: testCase.images, - createdAt: new Date(0), - }, - { role: "user", content: "Follow up", createdAt: new Date(0) }, - ], - }, - }), errorIncluding(ValidationError, testCase.error)) + await assert.rejects( + () => + createMessage({ + model: resolveModel(testCase.model), + config: { search: false, think: undefined }, + chat: { + id: "test", + createdAt: new Date(0), + systemPrompt: "test", + messages: [ + { + role: "user", + content: testCase.prompt, + image_urls: testCase.images, + createdAt: new Date(0), + }, + { role: "user", content: "Follow up", createdAt: new Date(0) }, + ], + }, + }), + errorIncluding(ValidationError, testCase.error), + ) assert.deepEqual(apiCalls, 0) } finally { globalThis.fetch = originalFetch diff --git a/adapters/openai.ts b/adapters/openai.ts index d938e59..30afd2c 100644 --- a/adapters/openai.ts +++ b/adapters/openai.ts @@ -50,9 +50,7 @@ export function openAIEffort(think: ThinkLevel | undefined) { .exhaustive() } -function gptConfig( - chatInput: ChatInput, -): { +function gptConfig(chatInput: ChatInput): { params: ResponseCreateParamsNonStreaming wrapped: boolean effort: string @@ -73,9 +71,7 @@ function gptConfig( // response.id — chain via previous_response_id so encrypted reasoning items // carry over and we only need to send the new user message. // https://developers.openai.com/api/docs/guides/conversation-state - const lastAssistantMessage = chat.messages - .filter((m) => m.role === "assistant") - .at(-1) + const lastAssistantMessage = chat.messages.filter((m) => m.role === "assistant").at(-1) const previous_response_id = match(lastAssistantMessage?.provider) .with({ type: "openai" }, (p) => p.responseId) .with(P.nullish, () => undefined) @@ -113,13 +109,13 @@ function gptConfig( instructions: chat.systemPrompt, text: prep ? { - format: { - type: "json_schema", - name: "output", - schema: prep.schema, - strict: true, - }, - } + format: { + type: "json_schema", + name: "output", + schema: prep.schema, + strict: true, + }, + } : undefined, }, wrapped: prep?.wrapped ?? false, @@ -171,12 +167,16 @@ export const gptBg = { } /** Image generation currently accepts only a fresh text prompt. */ -export function gptImageParams( - { chat, model, imageOptions }: ChatInput, -): ImageGenerateParamsNonStreaming { +export function gptImageParams({ + chat, + model, + imageOptions, +}: ChatInput): ImageGenerateParamsNonStreaming { const [message] = chat.messages if ( - chat.messages.length !== 1 || message?.role !== "user" || message.image_urls?.length + chat.messages.length !== 1 || + message?.role !== "user" || + message.image_urls?.length ) { throw new ValidationError("Image generation requires a fresh text-only prompt") } @@ -197,7 +197,7 @@ export function processGptImageResponse( save: (bytes: Uint8Array, index: number) => string, ): ModelResponse { const images = (response.data ?? []).flatMap((d, i) => - d.b64_json ? [save(Buffer.from(d.b64_json, "base64"), i)] : [] + d.b64_json ? [save(Buffer.from(d.b64_json, "base64"), i)] : [], ) if (images.length === 0) throw new Error("No image in response") // Image models don't report cached input, and we don't send input images @@ -220,10 +220,8 @@ export function processGptImageResponse( export async function gptImageCreateMessage(chatInput: ChatInput): Promise { const params = gptImageParams(chatInput) const response = await new OpenAI().images.generate(params, { signal: chatInput.signal }) - return processGptImageResponse( - response, - chatInput.model, - (bytes, i) => saveImage(bytes, params.prompt, "png", i), + return processGptImageResponse(response, chatInput.model, (bytes, i) => + saveImage(bytes, params.prompt, "png", i), ) } @@ -253,9 +251,9 @@ const makeOpenAIFunc = messages, response_format: prep ? { - type: "json_schema", - json_schema: { name: "output", schema: prep.schema, strict: true }, - } + type: "json_schema", + json_schema: { name: "output", schema: prep.schema, strict: true }, + } : undefined, } if (opts.think) { diff --git a/adapters/openai_test.ts b/adapters/openai_test.ts index 5b6432f..fb1ef8b 100644 --- a/adapters/openai_test.ts +++ b/adapters/openai_test.ts @@ -50,16 +50,16 @@ test("image generation rejects history and input images before requesting", () = config: { search: false, think: undefined }, } assert.deepEqual(gptImageParams(input).prompt, "a cat") - for ( - const messages of [ - [user, { ...user, content: "make it blue" }], - [{ + for (const messages of [ + [user, { ...user, content: "make it blue" }], + [ + { ...user, image_urls: ["data:image/png;base64,AQID", "https://example.com/image.jpg"], - }], - [], - ] - ) { + }, + ], + [], + ]) { input.chat.messages = messages assert.throws( () => gptImageParams(input), diff --git a/adapters/request_size.ts b/adapters/request_size.ts index 611336f..d5e3af4 100644 --- a/adapters/request_size.ts +++ b/adapters/request_size.ts @@ -16,11 +16,10 @@ export function validateRequestSize( const bytes = encoder.encode(JSON.stringify(body)).byteLength const limit = requestLimitsMB[provider] if (bytes > limit * MB) { + const size = (bytes / MB).toFixed(2) throw new ValidationError( - `${provider} request is larger than the ${limit} MB limit ` + - `(${ - (bytes / MB).toFixed(2) - } MB). Remove images or shorten the chat before sending.`, + `${provider} request is larger than the ${limit} MB limit (${size} MB). ` + + "Remove images or shorten the chat before sending.", ) } } diff --git a/adapters/types.ts b/adapters/types.ts index 2fd4cf3..e53c7c7 100644 --- a/adapters/types.ts +++ b/adapters/types.ts @@ -32,7 +32,7 @@ export type ChatInput = { export const imageQualities = ["low", "medium", "high", "xhigh", "max", "auto"] as const export type ImageOptions = { - quality?: typeof imageQualities[number] + quality?: (typeof imageQualities)[number] /** `WIDTHxHEIGHT` or `auto` */ size?: string } diff --git a/display.ts b/display.ts index fa41a37..cb880b6 100644 --- a/display.ts +++ b/display.ts @@ -43,12 +43,17 @@ const modelsTable = (verbose: boolean) => ]) /** Split, add `"> "` to the beginning of each line, and rejoin */ -const quote = (s: string) => s.split("\n").map((line) => "> " + line).join("\n") +const quote = (s: string) => + s + .split("\n") + .map((line) => "> " + line) + .join("\n") -export const modelsMd = (verbose = false) => - `Models are matched on ID or key. Prices are per million tokens. Image model output is priced per image token.\n\n${ - modelsTable(verbose) - }` +const modelsIntro = + "Models are matched on ID or key. Prices are per million tokens. " + + "Image model output is priced per image token." + +export const modelsMd = (verbose = false) => `${modelsIntro}\n\n${modelsTable(verbose)}` // Collapse long user inputs in gists, unless the input already contains a //
block (e.g., from `cb`), in which case the user has already @@ -74,9 +79,7 @@ export function formatElapsed(ms: number) { } const escapeThinkTags = (content: string) => - content - .replace("", "\\") - .replace("", "\\") + content.replace("", "\\").replace("", "\\") // TODO: add `verbose` mode and hide reasoning from `nice` mode @@ -106,7 +109,8 @@ export function metaLineMd(msg: ChatMessage): string { out += ` | ${moneyFmt.format(msg.cost)}` // show cached tokens in parens if there are any - const input = msg.tokens.input + + const input = + msg.tokens.input + (msg.tokens.input_cache_hit ? ` (${msg.tokens.input_cache_hit})` : "") out += ` | ${input} -> ${msg.tokens.output}` @@ -154,7 +158,8 @@ export function messageContentMd(msg: ChatMessage, mode: DisplayMode) { } // For long user inputs in gist mode, collapse in a details block if ( - msg.role === "user" && mode === "gist" && + msg.role === "user" && + mode === "gist" && !hasDetails(msg.content) && msg.content.split("\n").length > COLLAPSE_LINES ) { diff --git a/display_test.ts b/display_test.ts index c76432d..2488631 100644 --- a/display_test.ts +++ b/display_test.ts @@ -21,12 +21,14 @@ test("chatToMd includes every attached image in order", () => { id: "images", createdAt: new Date(0), systemPrompt: systemBase, - messages: [{ - role: "user", - content: "Compare these", - createdAt: new Date(0), - image_urls: ["data:image/png;base64,AQID", "https://example.com/second.jpg"], - }], + messages: [ + { + role: "user", + content: "Compare these", + createdAt: new Date(0), + image_urls: ["data:image/png;base64,AQID", "https://example.com/second.jpg"], + }, + ], } const md = chatToMd({ chat }) assert.deepEqual( diff --git a/image-input.ts b/image-input.ts index fa4ce0d..310906a 100644 --- a/image-input.ts +++ b/image-input.ts @@ -8,13 +8,8 @@ import $ from "dax" import { isErrno, ValidationError } from "./errors.ts" -const IMAGE_MIME_TYPES = [ - "image/png", - "image/jpeg", - "image/gif", - "image/webp", -] as const -export type ImageMimeType = typeof IMAGE_MIME_TYPES[number] +const IMAGE_MIME_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"] as const +export type ImageMimeType = (typeof IMAGE_MIME_TYPES)[number] function isImageMimeType(s: string): s is ImageMimeType { return (IMAGE_MIME_TYPES as readonly string[]).includes(s) @@ -47,21 +42,19 @@ export function parseDataUrl( */ async function readClipboardImage(): Promise { if (process.platform !== "darwin") { - throw new ValidationError( - "Clipboard image paste is only supported on macOS", - ) + throw new ValidationError("Clipboard image paste is only supported on macOS") } const tmpPath = join(tmpdir(), `llm-clipboard-${crypto.randomUUID()}.png`) + const file = JSON.stringify(tmpPath) try { const result = await $`osascript \ -e ${`set png_data to (the clipboard as «class PNGf»)`} \ - -e ${`set f to open for access POSIX file ${ - JSON.stringify(tmpPath) - } with write permission`} \ + -e ${`set f to open for access POSIX file ${file} with write permission`} \ -e ${`set eof f to 0`} \ -e ${`write png_data to f`} \ -e ${`close access f`}` - .stderr("piped").noThrow() + .stderr("piped") + .noThrow() if (result.code !== 0) { // osascript -1700 = "can't make ... into type PNGf" → no image on clipboard const noImage = /-1700|class PNGf/.test(result.stderr) @@ -85,7 +78,7 @@ const execSips: SipsRunner = (args) => execFile("sips", args, (error, _stdout, stderr) => { // A string code like ENOENT means the process never ran. if (typeof error?.code === "string") reject(error) - else resolve({ code: error ? error.code ?? 1 : 0, stderr }) + else resolve({ code: error ? (error.code ?? 1) : 0, stderr }) }) }) @@ -139,8 +132,11 @@ async function convertHeicImage(value: string, runSips: SipsRunner): Promise ({ code, stderr }) for (const extension of ["HEIC", "heif"]) { test(`resolveImage converts ${extension} to JPEG and cleans up without changing the original`, async () => { - await withFakeSips(async (args) => { - await writeFile(args.at(-1)!, new Uint8Array([0xff, 0xd8, 0xff, 0xd9])) - return commandOutput() - }, async (input, calls, sips) => { - assert.deepEqual(await resolveImage(input, sips), "data:image/jpeg;base64,/9j/2Q==") - assert.deepEqual(calls.length, 1) - assert.deepEqual(calls[0].slice(0, -2), [ - "--setProperty", - "format", - "jpeg", - "--setProperty", - "formatOptions", - "90", - await realpath(input), - ]) - assert.deepEqual(calls[0].at(-2), "--out") - assert.deepEqual([...await readFile(input)], [1, 2, 3]) - assert.deepEqual(existsSync(dirname(calls[0].at(-1)!)), false) - }, extension) + await withFakeSips( + async (args) => { + await writeFile(args.at(-1)!, new Uint8Array([0xff, 0xd8, 0xff, 0xd9])) + return commandOutput() + }, + async (input, calls, sips) => { + assert.deepEqual(await resolveImage(input, sips), "data:image/jpeg;base64,/9j/2Q==") + assert.deepEqual(calls.length, 1) + assert.deepEqual(calls[0].slice(0, -2), [ + "--setProperty", + "format", + "jpeg", + "--setProperty", + "formatOptions", + "90", + await realpath(input), + ]) + assert.deepEqual(calls[0].at(-2), "--out") + assert.deepEqual([...(await readFile(input))], [1, 2, 3]) + assert.deepEqual(existsSync(dirname(calls[0].at(-1)!)), false) + }, + extension, + ) }) } @@ -124,28 +128,34 @@ test("resolveImage reports conversion failure and cleans up", async () => { }) test("resolveImage rejects incomplete sips output even when the process succeeds", async () => { - await withFakeSips(async (args) => { - await writeFile(args.at(-1)!, new Uint8Array([0xff, 0xd8, 0xff, 0xe0])) - return commandOutput() - }, async (input, calls, sips) => { - await assert.rejects( - () => resolveImage(input, sips), - errorIncluding(ValidationError, "incomplete JPEG"), - ) - assert.deepEqual(calls.length, 1) - assert.deepEqual(existsSync(dirname(calls[0].at(-1)!)), false) - }) + await withFakeSips( + async (args) => { + await writeFile(args.at(-1)!, new Uint8Array([0xff, 0xd8, 0xff, 0xe0])) + return commandOutput() + }, + async (input, calls, sips) => { + await assert.rejects( + () => resolveImage(input, sips), + errorIncluding(ValidationError, "incomplete JPEG"), + ) + assert.deepEqual(calls.length, 1) + assert.deepEqual(existsSync(dirname(calls[0].at(-1)!)), false) + }, + ) }) test("resolveImage reports missing converter output and cleans up", async () => { - await withFakeSips(() => Promise.resolve(commandOutput()), async (input, calls, sips) => { - await assert.rejects( - () => resolveImage(input, sips), - errorIncluding(ValidationError, "did not produce a JPEG"), - ) - assert.deepEqual(calls.length, 1) - assert.deepEqual(existsSync(dirname(calls[0].at(-1)!)), false) - }) + await withFakeSips( + () => Promise.resolve(commandOutput()), + async (input, calls, sips) => { + await assert.rejects( + () => resolveImage(input, sips), + errorIncluding(ValidationError, "did not produce a JPEG"), + ) + assert.deepEqual(calls.length, 1) + assert.deepEqual(existsSync(dirname(calls[0].at(-1)!)), false) + }, + ) }) test("resolveImage leaves ordinary local images unchanged without invoking sips", async () => { diff --git a/main.ts b/main.ts index 140ed6c..571f6ad 100755 --- a/main.ts +++ b/main.ts @@ -54,23 +54,27 @@ const truncate = (str: string, maxLength: number) => /** Keep one width-aware selector option per chat so option indexes stay aligned. */ function chatPickerOptions(chats: Chat[]) { - return formatPickerOptions(chats.map((chat) => { - const date = shortDateFmt.format(chat.createdAt).replace(",", "") - return { - summary: chat.summary || "", - model: getLastModelId(chat) || "", - meta: `${date} (${chat.messages.length})`, - } - })) + return formatPickerOptions( + chats.map((chat) => { + const date = shortDateFmt.format(chat.createdAt).replace(",", "") + return { + summary: chat.summary || "", + model: getLastModelId(chat) || "", + meta: `${date} (${chat.messages.length})`, + } + }), + ) } /** One line per message for the fork picker, with columns aligned */ function messagePickerOptions(messages: Chat["messages"]) { - 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 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] + }), + ) } const bell = () => new Promise((resolve) => process.stdout.write("\x07", resolve)) @@ -135,7 +139,7 @@ async function pollBackgroundResponse( if (chat.background.status === "completed") { const response = { - ...await gptBg.retrieve(id, resolveModel(modelId)), + ...(await gptBg.retrieve(id, resolveModel(modelId))), effort, } const assistantMsg = makeAssMsg(model.id, startTime, response) @@ -157,10 +161,7 @@ async function pollBackgroundResponse( /** * Generate a response for a chat with the given input and options */ -async function genResponse( - chatInput: ChatInput, - displayOpts: DisplayOpts = {}, -) { +async function genResponse(chatInput: ChatInput, displayOpts: DisplayOpts = {}) { // don't want progress spinner when piping output const showProgress = process.stdout.isTTY && !displayOpts.raw && !displayOpts.json const label = chatInput.model.kind === "image" ? "Generating image..." : "Thinking..." @@ -226,7 +227,10 @@ async function pickModel(defaultId: string | undefined) { const index = await selectIndex({ message: "Pick a model to answer", options: textModels.map((m) => m.id), - initialIndex: Math.max(0, textModels.findIndex((m) => m.id === defaultId)), + initialIndex: Math.max( + 0, + textModels.findIndex((m) => m.id === defaultId), + ), }) return textModels[index] } @@ -251,8 +255,9 @@ async function forkChat(chat: Chat) { if (selectedMessage.role === "user") { // default to the model that originally answered this message - const nextModel = chat.messages.slice(selectedIdx).find((m) => m.role === "assistant") - ?.model + const nextModel = chat.messages + .slice(selectedIdx) + .find((m) => m.role === "assistant")?.model const model = await pickModel(nextModel) const chatInput: ChatInput = { chat: newChat, @@ -282,9 +287,8 @@ async function historyPicker() { const picked = await pickWithAction({ message: "Chat history", options: chatPickerOptions(chats), - initialIndex: initialIndex === undefined - ? undefined - : Math.min(initialIndex, chats.length - 1), + initialIndex: + initialIndex === undefined ? undefined : Math.min(initialIndex, chats.length - 1), }) if (!picked) return const chat = chats[picked.index] @@ -392,8 +396,9 @@ to MESSAGE.`) collect, ) .addOption( - new Option("--quality ", "Image quality (image models only)") - .choices(imageQualities), + new Option("--quality ", "Image quality (image models only)").choices( + imageQualities, + ), ) .option("--size ", "Image size, e.g. 1024x1536 or auto (image models only)") .option("--system ", "Override entire system prompt") @@ -402,8 +407,9 @@ to MESSAGE.`) .option("-v, --verbose", "Include reasoning in output") .option("--raw", "Print LLM text directly (no metadata or reasoning)") .addOption( - new Option("--json", "Print the full response message as JSON (for scripts)") - .conflicts(["raw", "verbose"]), + new Option("--json", "Print the full response message as JSON (for scripts)").conflicts( + ["raw", "verbose"], + ), ) .option("-o, --output-schema ", "ArkType schema for structured output") .addHelpText( @@ -438,17 +444,15 @@ Examples: const msg = message.join(" ") const piped = !process.stdin.isTTY const stdin = piped - // read stdin to end - ? (await text(process.stdin)).trim() + ? // read stdin to end + (await text(process.stdin)).trim() : null // Input was piped but arrived empty — the upstream command likely failed or // produced nothing (e.g. `cb x | ai ...` where `cb` errors). Abort rather // than calling the API with only the message. if (piped && !stdin && !hasImages) { - throw new ValidationError( - "Piped input was empty (did an upstream command fail?)", - ) + throw new ValidationError("Piped input was empty (did an upstream command fail?)") } if (!msg && !stdin && !hasImages) { @@ -466,12 +470,12 @@ Examples: const thinkOverride: ThinkOverride = opts.quick ? "off" : opts.thinkHard - ? "high" - : opts.think - ? "on" - : opts.thinkDefault - ? "default" - : undefined + ? "high" + : opts.think + ? "on" + : opts.thinkDefault + ? "default" + : undefined // Search is sticky across replies: an explicit -s/--no-search wins, else a // reply inherits the chat's last setting. Persisting it keeps the search // tool stable across turns so prompt caching keeps hitting — every provider @@ -576,7 +580,7 @@ historyCmd }) if (selected.length === 0) return const label = `${selected.length} chat${selected.length === 1 ? "" : "s"}` - if (!await confirmed(`Delete ${label}?`)) return + if (!(await confirmed(`Delete ${label}?`))) return History.delete(selected.map((i) => reversed[i].id)) console.log(`Deleted ${label}`) }) @@ -587,7 +591,7 @@ historyCmd .action(async () => { const history = History.list() const n = history.length - if (!await confirmed(`Delete ${n} chats?`)) return + if (!(await confirmed(`Delete ${n} chats?`))) return History.clear() console.log("Deleted chat history") }) @@ -606,9 +610,7 @@ program await genMissingSummaries([lastChat]) if (!$.commandExistsSync("gh")) { - throw new Error( - "Creating a gist requires the `gh` CLI (https://cli.github.com/)", - ) + throw new Error("Creating a gist requires the `gh` CLI (https://cli.github.com/)") } let md: string diff --git a/markdown-exit-terminal.ts b/markdown-exit-terminal.ts index c8c4d70..d1d9f4c 100644 --- a/markdown-exit-terminal.ts +++ b/markdown-exit-terminal.ts @@ -43,9 +43,8 @@ function renderTable(rows: string[][], headerCount: number): string { if (rows.length === 0) return "" const cols = Math.max(...rows.map((r) => r.length)) - const widths = Array.from( - { length: cols }, - (_, c) => Math.max(3, ...rows.map((r) => stringWidth(r[c] ?? ""))), + const widths = Array.from({ length: cols }, (_, c) => + Math.max(3, ...rows.map((r) => stringWidth(r[c] ?? ""))), ) const pad = (s: string, w: number) => s + " ".repeat(w - stringWidth(s)) @@ -112,15 +111,19 @@ async function highlightCode(code: string, lang: string, theme = "ayu-mirage") { } catch { highlighted = code } - return highlighted.split("\n").map((l) => " " + l).join("\n") + "\n\n" + return ( + highlighted + .split("\n") + .map((l) => " " + l) + .join("\n") + "\n\n" + ) } // --- Post-processing --------------------------------------------------- function postProcessLinks(text: string): string { - return text.replace( - /\x00LINK:(.*?)\x00([\s\S]*?)\x00\/LINK\x00/g, - (_, href, linkText) => hyperlink(href, linkText), + return text.replace(/\x00LINK:(.*?)\x00([\s\S]*?)\x00\/LINK\x00/g, (_, href, linkText) => + hyperlink(href, linkText), ) } @@ -133,17 +136,12 @@ function postProcessBlockquotes(text: string, width: number): string { let result = text for (let depth = maxDepth; depth > 0; depth--) { result = result.replace( - new RegExp( - `\x00BQ_OPEN:${depth}\x00([\\s\\S]*?)\x00BQ_CLOSE:${depth}\x00`, - "g", - ), + new RegExp(`\x00BQ_OPEN:${depth}\x00([\\s\\S]*?)\x00BQ_CLOSE:${depth}\x00`, "g"), (_, content: string) => { const prefix = gray(" │ ") const blankPrefix = gray(" │") const maxWidth = width - 3 // account for " │ " prefix - const paragraphs = content - .split("\x00BQ_PARA\x00") - .filter((p) => p.trim()) + const paragraphs = content.split("\x00BQ_PARA\x00").filter((p) => p.trim()) const reflowed = paragraphs.map((p) => { const lines = reflowText(p.trimEnd(), maxWidth).split("\n") return lines.map((l: string) => prefix + italic(l)).join("\n") @@ -159,16 +157,14 @@ function postProcessTables(text: string): string { const extractCells = (row: string) => [...row.matchAll(/\x00CELL\x00([\s\S]*?)\x00\/CELL\x00/g)].map((m) => m[1].trim()) - return text.replace( - /\x00TABLE\x00([\s\S]*?)\x00\/TABLE\x00/g, - (_, content: string) => { - const rows = [...content.matchAll(/\x00TR\x00([\s\S]*?)\x00\/TR\x00/g)] - .map((m) => extractCells(m[1])) - const thead = content.match(/\x00THEAD\x00([\s\S]*?)\x00\/THEAD\x00/) - const headerRows = thead ? [...thead[1].matchAll(/\x00TR\x00/g)].length : 0 - return renderTable(rows, headerRows) + "\n\n" - }, - ) + return text.replace(/\x00TABLE\x00([\s\S]*?)\x00\/TABLE\x00/g, (_, content: string) => { + const rows = [...content.matchAll(/\x00TR\x00([\s\S]*?)\x00\/TR\x00/g)].map((m) => + extractCells(m[1]), + ) + const thead = content.match(/\x00THEAD\x00([\s\S]*?)\x00\/THEAD\x00/) + const headerRows = thead ? [...thead[1].matchAll(/\x00TR\x00/g)].length : 0 + return renderTable(rows, headerRows) + "\n\n" + }) } function reflowParagraphs(text: string, width: number): string { @@ -216,8 +212,7 @@ export default function terminalPlugin(md: MarkdownExit): void { link_close: () => "\x00/LINK\x00", image: (tokens, idx) => { const src = tokens[idx].attrGet("src") ?? "" - const alt = tokens[idx].content || - tokens[idx].children?.[0]?.content || "image" + const alt = tokens[idx].content || tokens[idx].children?.[0]?.content || "image" return dim(`![${alt}](${src})`) }, diff --git a/math-image.ts b/math-image.ts index d85ff64..a7288d9 100644 --- a/math-image.ts +++ b/math-image.ts @@ -41,7 +41,10 @@ export async function renderMathImage( const markup = adaptor.serializeXML(node) if (markup.includes('data-mml-node="merror"')) throw new Error("Invalid TeX") const svg = markup.match(//)?.[0] - const viewBox = svg?.match(/viewBox="([^"]+)"/)?.[1].split(/\s+/).map(Number) + const viewBox = svg + ?.match(/viewBox="([^"]+)"/)?.[1] + .split(/\s+/) + .map(Number) if (!svg || !viewBox || viewBox.length !== 4) throw new Error("Missing math SVG") const [x, y, width, height] = viewBox if (!(width > 0 && height > 0)) throw new Error("Empty math SVG") @@ -52,10 +55,12 @@ export async function renderMathImage( const scale = Math.min( (display ? 20 : 16) / 1000, (maxColumns * 10 - horizontalPadding) / width, - display ? 300 / height : Math.min( - inlineBaseline / Math.max(1, -y), - (20 - inlineBaseline) / Math.max(1, y + height), - ), + display + ? 300 / height + : Math.min( + inlineBaseline / Math.max(1, -y), + (20 - inlineBaseline) / Math.max(1, y + height), + ), ) const columns = Math.max(1, Math.ceil((width * scale + horizontalPadding) / 10)) const rows = display ? Math.max(1, Math.ceil((height * scale + 4) / 20)) : 1 @@ -66,12 +71,11 @@ export async function renderMathImage( // MathJax's SVG baseline is y=0. Align it with the text baseline rather than // centering each glyph's bounds; short letters such as nu otherwise float. const offsetY = display ? (rows * 20 - height * scale) / 2 : inlineBaseline + y * scale - const padded = - `${inner}` + const padded = `${inner}` const renderer = new Resvg(padded) try { const rendered = renderer.render() diff --git a/md-render_test.ts b/md-render_test.ts index d9c7273..ed911ab 100644 --- a/md-render_test.ts +++ b/md-render_test.ts @@ -45,21 +45,13 @@ test("renderMarkdown sizes tables from visible link text", async () => { }) test("renderMarkdown sizes emoji grapheme clusters as width 2 in tables", async () => { - const output = stripAnsi( - await renderMarkdown("| x |\n| - |\n| 👨‍👩‍👧‍👦 |\n| 🇯🇵 |\n| 🏴‍☠️ |"), - ) + const output = stripAnsi(await renderMarkdown("| x |\n| - |\n| 👨‍👩‍👧‍👦 |\n| 🇯🇵 |\n| 🏴‍☠️ |")) assert.deepEqual( output, - [ - "╭─────╮", - "│ x │", - "├─────┤", - "│ 👨‍👩‍👧‍👦 │", - "│ 🇯🇵 │", - "│ 🏴‍☠️ │", - "╰─────╯", - ].join("\n"), + ["╭─────╮", "│ x │", "├─────┤", "│ 👨‍👩‍👧‍👦 │", "│ 🇯🇵 │", "│ 🏴‍☠️ │", "╰─────╯"].join( + "\n", + ), ) }) @@ -106,65 +98,64 @@ test("renderMarkdown handles basic lists", async () => { }) test("renderMarkdown handles basic fenced code blocks", async () => { - const output = stripAnsi( - await renderMarkdown("```ts\nconst x = 1\nconsole.log(x)\n```"), - ) + const output = stripAnsi(await renderMarkdown("```ts\nconst x = 1\nconsole.log(x)\n```")) assert.deepEqual(output, " const x = 1\n console.log(x)") }) -test("renderMarkdown keeps codespans on a single line when wrapped", { - // Without colors there is no styled span to split - skip: !codespan.open && "colors are disabled", -}, async () => { - // wrap-ansi will split a styled codespan if it contains breakable spaces, - // which either leaks bg color to end-of-line (BCE) or strands a lone styled - // space at the line edge. Codespans pad with NBSP and replace internal - // spaces with NBSP so wrap-ansi treats them as a single unbreakable word. - const text = - "The function takes any iterable of `T` (arrays, sets, generators, etc.) and a `keyFn` that derives a grouping key from each item.\n\n" + - "The type parameter `K extends PropertyKey` constrains keys to `string | number | symbol` — the only types JavaScript allows as object keys. This lets the return type be a precise `Record` rather than a loose `Record`.\n\n" + - "Inside the loop, `result[key] ??= []` uses the operator: if `result[key]` is `undefined`, more text. The classic `if (!result[key]) result[key] = []; result[key].push(item);` form." - - // The escape codes depend on the color level: `node --test` sets - // FORCE_COLOR=1 for test files when its own output is a terminal. - const { open, close } = codespan - // A codespan whose visible content is only whitespace means wrap-ansi sliced one out - const lone = new RegExp(`${RegExp.escape(open)}\\s*${RegExp.escape(close)}`) - - const { stdout } = process - const original = Object.getOwnPropertyDescriptors(stdout) - stdout.isTTY = true - try { - for (const columns of [50, 62, 70, 80, 85, 88, 90, 92, 95, 100, 120]) { - stdout.columns = columns - const out = await renderMarkdown(text) - for (const [i, line] of out.split("\n").entries()) { - const opens = line.split(open).length - 1 - const closes = line.split(close).length - 1 - assert.deepEqual( - opens, - closes, - `columns=${columns} line ${i} has unbalanced codespan SGR: ${ - JSON.stringify(line) - }`, - ) - assert.deepEqual( - lone.test(line), - false, - `columns=${columns} line ${i} contains a whitespace-only codespan: ${ - JSON.stringify(line) - }`, - ) +test( + "renderMarkdown keeps codespans on a single line when wrapped", + { + // Without colors there is no styled span to split + skip: !codespan.open && "colors are disabled", + }, + async () => { + // wrap-ansi will split a styled codespan if it contains breakable spaces, + // which either leaks bg color to end-of-line (BCE) or strands a lone styled + // space at the line edge. Codespans pad with NBSP and replace internal + // spaces with NBSP so wrap-ansi treats them as a single unbreakable word. + const text = + "The function takes any iterable of `T` (arrays, sets, generators, etc.) and a `keyFn` that derives a grouping key from each item.\n\n" + + "The type parameter `K extends PropertyKey` constrains keys to `string | number | symbol` — the only types JavaScript allows as object keys. This lets the return type be a precise `Record` rather than a loose `Record`.\n\n" + + "Inside the loop, `result[key] ??= []` uses the operator: if `result[key]` is `undefined`, more text. The classic `if (!result[key]) result[key] = []; result[key].push(item);` form." + + // The escape codes depend on the color level: `node --test` sets + // FORCE_COLOR=1 for test files when its own output is a terminal. + const { open, close } = codespan + // A codespan whose visible content is only whitespace means wrap-ansi sliced one out + const lone = new RegExp(`${RegExp.escape(open)}\\s*${RegExp.escape(close)}`) + + const { stdout } = process + const original = Object.getOwnPropertyDescriptors(stdout) + stdout.isTTY = true + try { + for (const columns of [50, 62, 70, 80, 85, 88, 90, 92, 95, 100, 120]) { + stdout.columns = columns + const out = await renderMarkdown(text) + for (const [i, line] of out.split("\n").entries()) { + const shown = JSON.stringify(line) + const opens = line.split(open).length - 1 + const closes = line.split(close).length - 1 + assert.deepEqual( + opens, + closes, + `columns=${columns} line ${i} has unbalanced codespan SGR: ${shown}`, + ) + assert.deepEqual( + lone.test(line), + false, + `columns=${columns} line ${i} contains a whitespace-only codespan: ${shown}`, + ) + } + } + } finally { + for (const key of ["isTTY", "columns"] as const) { + if (original[key]) Object.defineProperty(stdout, key, original[key]) + else delete stdout[key] } } - } finally { - for (const key of ["isTTY", "columns"] as const) { - if (original[key]) Object.defineProperty(stdout, key, original[key]) - else delete stdout[key] - } - } -}) + }, +) test("renderMarkdown handles simple tables", async () => { const output = stripAnsi(await renderMarkdown("| a | b |\n| - | - |\n| 1 | 2 |")) diff --git a/message-spec.ts b/message-spec.ts index 009cee9..3545103 100644 --- a/message-spec.ts +++ b/message-spec.ts @@ -33,7 +33,10 @@ const parsePart = (part: string, msgCount: number): number[] => { * Throws if a range has start > end or if any number is out of bounds. */ export function parseMessageSpec(spec: string, msgCount: number): number[] { - const parts = spec.replaceAll(" ", "").split(",").filter((p) => p.length > 0) + const parts = spec + .replaceAll(" ", "") + .split(",") + .filter((p) => p.length > 0) const numbers = parts.flatMap((part) => parsePart(part, msgCount)) const indices = [...new Set(numbers)].sort((a, b) => a - b) diff --git a/models.ts b/models.ts index cfc2dbc..2dd27f1 100644 --- a/models.ts +++ b/models.ts @@ -52,7 +52,7 @@ export const models: Model[] = [ key: "claude-opus-5-5", id: "opus-5.5", input: 4, - input_cached: 0.20, + input_cached: 0.2, input_cache_write: 5, output: 20, search_cost: 0.01, @@ -62,8 +62,8 @@ export const models: Model[] = [ key: "claude-sonnet-5-5", id: "sonnet-5.5", input: 2, - input_cached: 0.10, - input_cache_write: 2.50, + input_cached: 0.1, + input_cache_write: 2.5, output: 10, search_cost: 0.01, }, @@ -71,18 +71,18 @@ export const models: Model[] = [ provider: "anthropic", key: "claude-haiku-5-5", id: "haiku-5.5", - input: 0.10, + input: 0.1, input_cached: 0.01, input_cache_write: 0.125, - output: 0.50, + output: 0.5, search_cost: 0.01, }, { provider: "openai", key: "gpt-6-astra", id: "gpt-6-astra", - input: 10.00, - input_cached: 1.00, + input: 10.0, + input_cached: 1.0, output: 50, search_cost: 0.01, }, @@ -91,7 +91,7 @@ export const models: Model[] = [ key: "gpt-6.1-sol", id: "gpt-6.1-sol", input: 2, - input_cached: 0.10, + input_cached: 0.1, output: 10, search_cost: 0.01, }, @@ -99,9 +99,9 @@ export const models: Model[] = [ provider: "openai", key: "gpt-6-luna", id: "gpt-6-luna", - input: 0.10, + input: 0.1, input_cached: 0.01, - output: 0.50, + output: 0.5, search_cost: 0.01, }, { @@ -127,7 +127,7 @@ export const models: Model[] = [ key: "gemini-4-argon", id: "gemini-4-argon", input: 2, - input_cached: 0.10, + input_cached: 0.1, output: 10, // Introductory pricing through November 30, 2026; doubles to 4/20/0.20 // starting December 1, 2026. @@ -152,9 +152,9 @@ export const models: Model[] = [ provider: "google", key: "gemini-3.5-flash-lite", id: "gemini-3.5-flash-lite", - input: .30, + input: 0.3, input_cached: 0.03, - output: 2.50, + output: 2.5, // 5,000 search queries/month free (shared across 3.x models), then $14 / 1,000. // We never get anywhere near the limit, so treat as free. search_cost: 0, @@ -174,7 +174,8 @@ export function resolveModel( // First look for an exact match, then find the first model containing the arg // as a substring. See comment at allModels definition about ordering. Without // this logic, you could never match o1 if o1-mini is present. - const match = availableModels.find((m) => m.key === lower || m.id === lower) || + const match = + availableModels.find((m) => m.key === lower || m.id === lower) || availableModels.find((m) => m.key.includes(lower) || m.id.includes(lower)) if (!match) { @@ -195,9 +196,10 @@ export function getCost(model: Model, tokens: TokenCounts, searches = 0) { // Cache hits and writes are subsets of tokens.input. Price them separately // when the model has the corresponding price, otherwise at the input rate. - const hits = input_cached ? tokens.input_cache_hit ?? 0 : 0 - const writes = input_cache_write ? tokens.input_cache_write ?? 0 : 0 - const tokenCost = (input_cached ?? 0) * hits + + const hits = input_cached ? (tokens.input_cache_hit ?? 0) : 0 + const writes = input_cache_write ? (tokens.input_cache_write ?? 0) : 0 + const tokenCost = + (input_cached ?? 0) * hits + (input_cache_write ?? 0) * writes + input * (tokens.input - hits - writes) + output * tokens.output @@ -206,7 +208,7 @@ export function getCost(model: Model, tokens: TokenCounts, searches = 0) { // cached tokens) exceeds 100k. Hack until another model needs tiers. const multiplier = model.key === "claude-haiku-5-5" && tokens.input > 100_000 ? 5 : 1 - return multiplier * tokenCost / M + (search_cost ?? 0) * searches + return (multiplier * tokenCost) / M + (search_cost ?? 0) * searches } export const systemBase = $.dedent` diff --git a/package.json b/package.json index a9dc870..eb27eba 100644 --- a/package.json +++ b/package.json @@ -1,13 +1,10 @@ { "name": "llm-cli", "private": true, - "type": "module", "bin": { "ai": "./main.ts" }, - "engines": { - "node": ">=24" - }, + "type": "module", "scripts": { "ci": "npm run fmt:check && npm run lint && npm run check && npm test", "fmt": "oxfmt", @@ -44,5 +41,8 @@ "oxfmt": "^0.74.0", "oxlint": "^1.89.0", "typescript": "^7.0.2" + }, + "engines": { + "node": ">=24" } } diff --git a/picker.ts b/picker.ts index 885f5fe..fb29fd1 100644 --- a/picker.ts +++ b/picker.ts @@ -61,8 +61,9 @@ function padEnd(text: string, width: number): string { 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)) + row + .map((cell, i) => (i < row.length - 1 ? padEnd(cell, widths[i]) : cell)) + .join(" ".repeat(COLUMN_GAP)), ) } @@ -88,11 +89,9 @@ export function formatPickerOptions( return normalized.map((row) => { const summary = truncateWidth(row.summary, summaryWidth) - return [ - padEnd(summary, summaryWidth), - padEnd(row.model, modelWidth), - row.meta, - ].join(" ".repeat(COLUMN_GAP)) + return [padEnd(summary, summaryWidth), padEnd(row.model, modelWidth), row.meta].join( + " ".repeat(COLUMN_GAP), + ) }) } @@ -212,23 +211,28 @@ export function selectIndex(opts: { options: string[] initialIndex?: number }): Promise { - return exitOnCancel(select({ - message: opts.message, - choices: indexChoices(opts.options), - default: opts.initialIndex, - pageSize: Math.max(3, terminalRows() - 2), - })) + return exitOnCancel( + select({ + message: opts.message, + choices: indexChoices(opts.options), + default: opts.initialIndex, + pageSize: Math.max(3, terminalRows() - 2), + }), + ) } /** Pick any number of `options` and return their indexes. */ -export function selectIndexes( - opts: { message: string; options: string[] }, -): Promise { - return exitOnCancel(checkbox({ - message: opts.message, - choices: indexChoices(opts.options), - pageSize: Math.max(3, terminalRows() - 3), - })) +export function selectIndexes(opts: { + message: string + options: string[] +}): Promise { + return exitOnCancel( + checkbox({ + message: opts.message, + choices: indexChoices(opts.options), + pageSize: Math.max(3, terminalRows() - 3), + }), + ) } /** A yes/no question that defaults to no. Ctrl+C also counts as no. */ diff --git a/picker_test.ts b/picker_test.ts index d0e617d..23993a5 100644 --- a/picker_test.ts +++ b/picker_test.ts @@ -4,18 +4,21 @@ import stringWidth from "string-width" import { alignColumns, formatPickerOptions, keyAction } from "./picker.ts" test("picker options stay single-line and preserve their row mapping", () => { - const options = formatPickerOptions([ - { - summary: "A summary with an embedded newline\nand a long second thought", - model: "gpt-5.6-sol", - meta: "8/28 12:44 (2)", - }, - { - summary: "Short summary", - model: "opus-5", - meta: "8/27 09:24 (4)", - }, - ], 60) + const options = formatPickerOptions( + [ + { + summary: "A summary with an embedded newline\nand a long second thought", + model: "gpt-5.6-sol", + meta: "8/28 12:44 (2)", + }, + { + summary: "Short summary", + model: "opus-5", + meta: "8/27 09:24 (4)", + }, + ], + 60, + ) assert.deepEqual(options.length, 2) assert(options.every((option) => !option.includes("\n"))) @@ -26,11 +29,16 @@ test("picker options stay single-line and preserve their row mapping", () => { }) test("picker options retain full summaries when they fit", () => { - const [option] = formatPickerOptions([{ - summary: " Emoji 🦀 summary ", - model: "opus-5", - meta: "8/28 12:44 (2)", - }], 80) + const [option] = formatPickerOptions( + [ + { + summary: " Emoji 🦀 summary ", + model: "opus-5", + meta: "8/28 12:44 (2)", + }, + ], + 80, + ) assert(option.startsWith("Emoji 🦀 summary")) assert(!option.includes("…")) @@ -56,10 +64,7 @@ test("alignColumns pads every column but the last to its widest cell", () => { ["1", "user", "hello"], ["10", "opus-5 🦀", "hi"], ]), - [ - "1 user hello", - "10 opus-5 🦀 hi", - ], + ["1 user hello", "10 opus-5 🦀 hi"], ) assert.deepEqual(alignColumns([]), []) }) diff --git a/schema_test.ts b/schema_test.ts index c5b1306..aa3bf32 100644 --- a/schema_test.ts +++ b/schema_test.ts @@ -4,10 +4,7 @@ import { errorIncluding } from "./testing.ts" import { parseType, postprocessSchemaContent, prepareSchema } from "./schema.ts" function schema(input: string): Record { - const { $schema: _, ...rest } = parseType(input).toJsonSchema() as Record< - string, - unknown - > + const { $schema: _, ...rest } = parseType(input).toJsonSchema() as Record return rest } diff --git a/storage.ts b/storage.ts index af2e79b..bedfd14 100644 --- a/storage.ts +++ b/storage.ts @@ -20,8 +20,7 @@ export type StoredChat = Chat & { } function stateRoot(): string { - const stateHome = process.env.XDG_STATE_HOME || - join(process.env.HOME!, ".local", "state") + const stateHome = process.env.XDG_STATE_HOME || join(process.env.HOME!, ".local", "state") return join(stateHome, "llm-cli") } @@ -41,9 +40,13 @@ const pad = (n: number) => String(n).padStart(2, "0") /** `20260923-143012-a-cat-in-a-hat.png`, local time */ export function imageFilename(prompt: string, date: Date, ext: string, index = 0) { - const stamp = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-` + + const stamp = + `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-` + `${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}` - const slug = prompt.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40) + const slug = prompt + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .slice(0, 40) .replace(/^-+|-+$/g, "") const suffix = index > 0 ? `-${index + 1}` : "" return [stamp, slug].filter(Boolean).join("-") + suffix + "." + ext @@ -62,7 +65,7 @@ export function saveImage( ) { const dir = imagesPath() mkdirSync(dir, { recursive: true }) - for (let i = index;; i++) { + for (let i = index; ; i++) { const path = join(dir, imageFilename(prompt, date, ext, i)) try { writeFileSync(path, bytes, { flag: "wx" }) @@ -81,7 +84,9 @@ function currentPath(): string { function parseJson(contents: string): T { return JSON.parse(contents, (key, value) => { if ( - (key === "createdAt" || key === "startedAt" || key === "updatedAt" || + (key === "createdAt" || + key === "startedAt" || + key === "updatedAt" || key === "lastActiveAt") && typeof value === "string" ) { @@ -152,9 +157,7 @@ function assertCurrentRevision(chat: StoredChat) { try { const current = readChatFile(chatPath(chat.id)) if (current.revision !== chat.revision) { - throw new Error( - `Chat ${chat.id} changed concurrently; reload it before saving`, - ) + throw new Error(`Chat ${chat.id} changed concurrently; reload it before saving`) } } catch (e) { if (isErrno(e, "ENOENT")) return diff --git a/storage_test.ts b/storage_test.ts index 220ab17..aad879e 100644 --- a/storage_test.ts +++ b/storage_test.ts @@ -38,7 +38,10 @@ test("History.save stores chats independently and tracks current", () => { History.save(chat("one", "2026-01-01T00:00:00Z"), { current: true }) History.save(chat("two", "2026-01-02T00:00:00Z"), { current: true }) - assert.deepEqual(History.list().map((c) => c.id), ["one", "two"]) + assert.deepEqual( + History.list().map((c) => c.id), + ["one", "two"], + ) assert.deepEqual(History.current()?.id, "two") }) }) @@ -87,7 +90,10 @@ test("History.delete removes selected chat without rewriting others", () => { History.delete(["one"]) - assert.deepEqual(History.list().map((c) => c.id), ["two"]) + assert.deepEqual( + History.list().map((c) => c.id), + ["two"], + ) assert.deepEqual(History.current()?.id, "two") }) }) diff --git a/summarize.ts b/summarize.ts index f73755e..f1bf621 100644 --- a/summarize.ts +++ b/summarize.ts @@ -30,11 +30,13 @@ export async function summarize(chat: Chat): Promise { id: crypto.randomUUID(), systemPrompt: "You are summarizing an LLM chat in as few words as possible. Ideally 4-6 words, but up to 10 if necessary. This is for a list of chats in an LLM client UI. You will receive an excerpt of the beginning and end of the first two messages. Be concise and accurate. Only provide the summary; do not include explanation or followup questions. Do not end with a period. Do not use slashes.", - messages: [{ - role: "user", - content: `${abridged1}${abridged2}`, - createdAt: new Date(), - }], + messages: [ + { + role: "user", + content: `${abridged1}${abridged2}`, + createdAt: new Date(), + }, + ], createdAt: new Date(), }, model: luna, @@ -47,11 +49,13 @@ export async function summarize(chat: Chat): Promise { /** Create and save summaries for any chat without one */ export async function genMissingSummaries(history: Chat[]) { const pb = $.progress("Summarizing...") - await Promise.all((history - .filter((chat) => !chat.summary)) - .map(async (chat) => { - chat.summary = await summarize(chat) - History.save(chat) - })) + await Promise.all( + history + .filter((chat) => !chat.summary) + .map(async (chat) => { + chat.summary = await summarize(chat) + History.save(chat) + }), + ) pb.finish() } diff --git a/terminal-image.ts b/terminal-image.ts index 5687eec..a05be11 100644 --- a/terminal-image.ts +++ b/terminal-image.ts @@ -6,8 +6,10 @@ export function supportsKittyGraphics( env: (key: string) => string | undefined = (key) => process.env[key], ): boolean { if (!isTerminal || env("TMUX") || env("STY") || env("TERM") === "dumb") return false - return env("TERM_PROGRAM") === "ghostty" || + return ( + env("TERM_PROGRAM") === "ghostty" || ["xterm-ghostty", "xterm-kitty"].includes(env("TERM") ?? "") + ) } /** @@ -41,7 +43,7 @@ type TermSize = { columns: number; rows: number } */ export function imageColumns(png: Uint8Array, term: TermSize): number { const { width, height } = pngDimensions(png) - const fitHeight = Math.floor((term.rows - 4) * 2 * width / height) + const fitHeight = Math.floor(((term.rows - 4) * 2 * width) / height) return Math.max(1, Math.min(term.columns, 80, fitHeight)) } diff --git a/terminal-image_test.ts b/terminal-image_test.ts index 8d3d54f..cb58763 100644 --- a/terminal-image_test.ts +++ b/terminal-image_test.ts @@ -40,24 +40,24 @@ test("kittyPng places in one command with chunked payload", () => { }) test("Kitty detection requires a supported terminal outside multiplexers", () => { - for ( - const env of [{ TERM_PROGRAM: "ghostty" }, { TERM: "xterm-ghostty" }, { + for (const env of [ + { TERM_PROGRAM: "ghostty" }, + { TERM: "xterm-ghostty" }, + { TERM: "xterm-kitty", - }] - ) { + }, + ]) { const get = (key: string) => (env as Record)[key] assert(supportsKittyGraphics(true, get)) assert(!supportsKittyGraphics(false, get)) } - for ( - const env of [ - {}, - { TERM: "xterm-256color" }, - { TERM_PROGRAM: "ghostty", TMUX: "/tmp/tmux" }, - { TERM_PROGRAM: "ghostty", STY: "screen" }, - { TERM_PROGRAM: "ghostty", TERM: "dumb" }, - ] - ) { + for (const env of [ + {}, + { TERM: "xterm-256color" }, + { TERM_PROGRAM: "ghostty", TMUX: "/tmp/tmux" }, + { TERM_PROGRAM: "ghostty", STY: "screen" }, + { TERM_PROGRAM: "ghostty", TERM: "dumb" }, + ]) { assert( !supportsKittyGraphics( true, diff --git a/terminal-math.ts b/terminal-math.ts index d9df91f..8879fd2 100644 --- a/terminal-math.ts +++ b/terminal-math.ts @@ -23,12 +23,15 @@ export function kittyImage(image: MathImage, id: number): string[] { const transmit = kittyTransmit(image.png, `a=t,f=100,t=d,i=${id},q=2`) // Place one slice per text row. This keeps tall equations intact when output // starts near the bottom of the screen and scrolls during printing. - return Array.from({ length: image.rows }, (_, row) => - (row === 0 ? transmit : "") + - `\x1b_Ga=p,i=${id},q=2,C=1,y=${ - row * image.rowPixels - },h=${image.rowPixels},c=${image.columns},r=1\x1b\\` + - " ".repeat(image.columns)) + return Array.from( + { length: image.rows }, + (_, row) => + (row === 0 ? transmit : "") + + `\x1b_Ga=p,i=${id},q=2,C=1,y=${ + row * image.rowPixels + },h=${image.rowPixels},c=${image.columns},r=1\x1b\\` + + " ".repeat(image.columns), + ) } export function restoreMath(output: string, env: MathEnv): string { @@ -43,15 +46,18 @@ export default function mathPlugin(md: MarkdownExit): void { // and indented code blocks, link destinations, and escaped dollar signs. md.inline.ruler.before("escape", "math", (state, silent) => { const src = state.src.slice(state.pos) - const match = src.match(/^\$\$([\s\S]+?)\$\$|^\\\[([\s\S]+?)\\\]|^\\\(([^\n]+?)\\\)/) ?? + const match = + src.match(/^\$\$([\s\S]+?)\$\$|^\\\[([\s\S]+?)\\\]|^\\\(([^\n]+?)\\\)/) ?? src.match(/^\$(?![ $])((?:\\\$|[^$\n])+?)(? { - if (state.sCount[start] - state.blkIndent >= 4) return false - const first = state.src.slice( - state.bMarks[start] + state.tShift[start], - state.eMarks[start], - ) - const open = first.startsWith("$$") ? "$$" : first.startsWith("\\[") ? "\\[" : "" - if (!open) return false - const close = open === "$$" ? "$$" : "\\]" - const lines = [first.slice(2)] - let last = start - while (!lines.at(-1)!.includes(close) && last + 1 < end) { - last++ - if ( - state.sCount[last] < state.blkIndent && - state.src.slice(state.bMarks[last], state.eMarks[last]).trim() - ) return false - lines.push( - state.src.slice(state.bMarks[last] + state.tShift[last], state.eMarks[last]), + md.block.ruler.before( + "fence", + "math", + (state, start, end, silent) => { + if (state.sCount[start] - state.blkIndent >= 4) return false + const first = state.src.slice( + state.bMarks[start] + state.tShift[start], + state.eMarks[start], ) - } - const content = lines.join("\n") - const index = content.indexOf(close) - if (index < 0 || content.slice(index + 2).trim()) return false - if (silent) return true - const token = state.push("math_block", "", 0) - token.block = true - token.content = content.slice(0, index).trim() - token.markup = open + content - token.map = [start, last + 1] - state.line = last + 1 - return true - }, { alt: ["paragraph", "reference", "blockquote", "list"] }) + const open = first.startsWith("$$") ? "$$" : first.startsWith("\\[") ? "\\[" : "" + if (!open) return false + const close = open === "$$" ? "$$" : "\\]" + const lines = [first.slice(2)] + let last = start + while (!lines.at(-1)!.includes(close) && last + 1 < end) { + last++ + if ( + state.sCount[last] < state.blkIndent && + state.src.slice(state.bMarks[last], state.eMarks[last]).trim() + ) + return false + lines.push( + state.src.slice(state.bMarks[last] + state.tShift[last], state.eMarks[last]), + ) + } + const content = lines.join("\n") + const index = content.indexOf(close) + if (index < 0 || content.slice(index + 2).trim()) return false + if (silent) return true + const token = state.push("math_block", "", 0) + token.block = true + token.content = content.slice(0, index).trim() + token.markup = open + content + token.map = [start, last + 1] + state.line = last + 1 + return true + }, + { alt: ["paragraph", "reference", "blockquote", "list"] }, + ) const render: RenderRule = async (tokens, idx, _options, environment) => { const env = environment as MathEnv diff --git a/terminal-math_test.ts b/terminal-math_test.ts index c16b44b..354c410 100644 --- a/terminal-math_test.ts +++ b/terminal-math_test.ts @@ -24,10 +24,10 @@ test("inline glyphs share a baseline regardless of their height", async () => { const header = new DataView(image.png.buffer, image.png.byteOffset) const width = header.getUint32(16) const height = header.getUint32(20) + const href = `data:image/png;base64,${Buffer.from(image.png).toString("base64")}` const decoder = new Resvg( - ``, + `` + + ``, ) try { const decoded = decoder.render() @@ -50,16 +50,14 @@ test("inline glyphs share a baseline regardless of their height", async () => { }) test("math delimiters render inside prose without consuming punctuation", async () => { - for ( - const math of [ - String.raw`$\nu>0$`, - "$f=0$", - String.raw`\(x_i^2\)`, - "$$x^2$$", - String.raw`\[x^2\]`, - String.raw`$\sim\$900$`, - ] - ) { + for (const math of [ + String.raw`$\nu>0$`, + "$f=0$", + String.raw`\(x_i^2\)`, + "$$x^2$$", + String.raw`\[x^2\]`, + String.raw`$\sim\$900$`, + ]) { const out = await renderMarkdown(`Before **${math}**, after.`, { math: true }) assert.deepEqual(imageCount(out), 1, math) assert(strip(out).startsWith("Before ")) @@ -69,34 +67,30 @@ test("math delimiters render inside prose without consuming punctuation", async }) test("math leaves currency, escaped dollars, and code alone", async () => { - for ( - const text of [ - "between $50 to $100", - "between $50-$100", - "between $1,200-$1,500", - "between $5 + $10", - "**$30.7k** versus **$13.6k**", - String.raw`\$not math$`, - "`$x^2$`", - "`` `$x^2$` ``", - "```tex\n$x^2$\n```", - "~~~tex\n$x^2$\n~~~", - " $x^2$", - "[link](https://example.com/$x$)", - ] - ) { + for (const text of [ + "between $50 to $100", + "between $50-$100", + "between $1,200-$1,500", + "between $5 + $10", + "**$30.7k** versus **$13.6k**", + String.raw`\$not math$`, + "`$x^2$`", + "`` `$x^2$` ``", + "```tex\n$x^2$\n```", + "~~~tex\n$x^2$\n~~~", + " $x^2$", + "[link](https://example.com/$x$)", + ]) { assert.deepEqual(imageCount(await renderMarkdown(text, { math: true })), 0, text) } }) test("disabled and invalid math preserve the raw TeX", async () => { - for ( - const text of [ - String.raw`With $x_i^2$ and \(\nu>0\).`, - "$$\nx_i^2\n$$", - String.raw`\[x_i^2\]`, - ] - ) { + for (const text of [ + String.raw`With $x_i^2$ and \(\nu>0\).`, + "$$\nx_i^2\n$$", + String.raw`\[x_i^2\]`, + ]) { assert.deepEqual(strip(await renderMarkdown(text, { math: false })), text) } const invalid = String.raw`$\notARealCommand{$` @@ -111,16 +105,14 @@ test("display math interrupts paragraphs and retains following text", async () = }) test("math graphics survive wrapping, blockquotes, lists, and tables", async () => { - for ( - const text of [ - "word ".repeat(20) + "$x^2$ after", - "> $x^2$ and $y$", - "> $$\n> x^2\n> $$", - "- $x^2$\n- $y$", - "| value |\n| --- |\n| $x^2$ |", - "User private character: \ue000, then $x$ and $y$.", - ] - ) { + for (const text of [ + "word ".repeat(20) + "$x^2$ after", + "> $x^2$ and $y$", + "> $$\n> x^2\n> $$", + "- $x^2$\n- $y$", + "| value |\n| --- |\n| $x^2$ |", + "User private character: \ue000, then $x$ and $y$.", + ]) { const out = await renderMarkdown(text, { math: true }) assert(imageCount(out) > 0, text) assert(!out.includes("\x00"), text) @@ -151,8 +143,7 @@ test("PNG chunks roundtrip and row placements reserve the correct cells", () => }) test("MathJax rasterizes the example and constrains narrow/tall equations", async () => { - const tex = String - .raw`\partial_t u + (u\cdot\nabla)u = -\nabla p + \nu\Delta u + f, \qquad \nabla\cdot u = 0` + const tex = String.raw`\partial_t u + (u\cdot\nabla)u = -\nabla p + \nu\Delta u + f, \qquad \nabla\cdot u = 0` for (const width of [20, 80]) { const image = await renderMathImage(tex, true, width, "#c8c8c8") assert.deepEqual(Array.from(image.png.slice(0, 8)), [137, 80, 78, 71, 13, 10, 26, 10]) diff --git a/utils_test.ts b/utils_test.ts index b4f5087..cb40cf7 100644 --- a/utils_test.ts +++ b/utils_test.ts @@ -10,8 +10,18 @@ test("range excludes the end and is empty when end <= start", () => { }) test("uniqueBy keeps the first item for each key", () => { - const items = [{ k: "a", n: 1 }, { k: "b", n: 2 }, { k: "a", n: 3 }] - assert.deepEqual(uniqueBy(items, (i) => i.k), [{ k: "a", n: 1 }, { k: "b", n: 2 }]) + const items = [ + { k: "a", n: 1 }, + { k: "b", n: 2 }, + { k: "a", n: 3 }, + ] + assert.deepEqual( + uniqueBy(items, (i) => i.k), + [ + { k: "a", n: 1 }, + { k: "b", n: 2 }, + ], + ) }) test("pick copies only the given keys", () => {