diff --git a/packages/agent/CHANGELOG.md b/packages/agent/CHANGELOG.md index 24828d65..8d94ef1e 100644 --- a/packages/agent/CHANGELOG.md +++ b/packages/agent/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +### Breaking Changes + +- Migrated public TypeBox-facing types and examples from `@sinclair/typebox` 0.34.x to `typebox` 1.x. Install and import from `typebox` instead of relying on `@sinclair/typebox` transitively ([#3112](https://github.com/badlogic/pi-mono/issues/3112)) + ### Added - Added `terminate: true` tool-result hints to skip the automatic follow-up LLM call when every finalized tool result in the current batch opts into early termination ([#3525](https://github.com/badlogic/pi-mono/issues/3525)) diff --git a/packages/agent/README.md b/packages/agent/README.md index f3a5b9c1..56ccc69f 100644 --- a/packages/agent/README.md +++ b/packages/agent/README.md @@ -367,7 +367,7 @@ const agent = new Agent({ Define tools using `AgentTool`: ```typescript -import { Type } from "@sinclair/typebox"; +import { Type } from "typebox"; const readFileTool: AgentTool = { name: "read_file", diff --git a/packages/ai/CHANGELOG.md b/packages/ai/CHANGELOG.md index 2be9dbdb..f384bf5b 100644 --- a/packages/ai/CHANGELOG.md +++ b/packages/ai/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +### Breaking Changes + +- Migrated TypeBox support from `@sinclair/typebox` 0.34.x plus AJV to `typebox` 1.x plus TypeBox's built-in validator and value-conversion APIs. Tool argument validation now runs in eval-restricted JavaScript runtimes such as Cloudflare Workers and other environments that disallow `eval` / `new Function`, instead of being silently skipped. Migration: install and import from `typebox` instead of `@sinclair/typebox`, and retest any coercion-sensitive tool paths that serialize schemas to plain JSON because those now go through the new TypeBox-based validation and coercion path rather than AJV ([#3112](https://github.com/badlogic/pi-mono/issues/3112)) + ### Fixed - Fixed `google-gemini-cli` built-in model discovery to include `gemini-3.1-flash-lite-preview`, so Cloud Code Assist model lists expose it without requiring manual `--model` fallback selection ([#3545](https://github.com/badlogic/pi-mono/issues/3545)) diff --git a/packages/ai/src/models.generated.ts b/packages/ai/src/models.generated.ts index 8e7e2433..578f6253 100644 --- a/packages/ai/src/models.generated.ts +++ b/packages/ai/src/models.generated.ts @@ -7234,7 +7234,7 @@ export const MODELS = { cacheWrite: 0, }, contextWindow: 262144, - maxTokens: 64000, + maxTokens: 128000, } satisfies Model<"openai-completions">, "mimo-v2-pro": { id: "mimo-v2-pro", @@ -7251,7 +7251,41 @@ export const MODELS = { cacheWrite: 0, }, contextWindow: 1048576, - maxTokens: 64000, + maxTokens: 128000, + } satisfies Model<"openai-completions">, + "mimo-v2.5": { + id: "mimo-v2.5", + name: "MiMo V2.5", + api: "openai-completions", + provider: "opencode-go", + baseUrl: "https://opencode.ai/zen/go/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.4, + output: 2, + cacheRead: 0.08, + cacheWrite: 0, + }, + contextWindow: 262144, + maxTokens: 128000, + } satisfies Model<"openai-completions">, + "mimo-v2.5-pro": { + id: "mimo-v2.5-pro", + name: "MiMo V2.5 Pro", + api: "openai-completions", + provider: "opencode-go", + baseUrl: "https://opencode.ai/zen/go/v1", + reasoning: true, + input: ["text"], + cost: { + input: 1, + output: 3, + cacheRead: 0.2, + cacheWrite: 0, + }, + contextWindow: 1048576, + maxTokens: 128000, } satisfies Model<"openai-completions">, "minimax-m2.5": { id: "minimax-m2.5", @@ -7697,6 +7731,23 @@ export const MODELS = { contextWindow: 1000000, maxTokens: 128000, } satisfies Model<"openai-completions">, + "arcee-ai/trinity-large-preview": { + id: "arcee-ai/trinity-large-preview", + name: "Arcee AI: Trinity Large Preview", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.15, + output: 0.44999999999999996, + cacheRead: 0, + cacheWrite: 0, + }, + contextWindow: 131000, + maxTokens: 4096, + } satisfies Model<"openai-completions">, "arcee-ai/trinity-large-preview:free": { id: "arcee-ai/trinity-large-preview:free", name: "Arcee AI: Trinity Large Preview (free)", @@ -8085,7 +8136,7 @@ export const MODELS = { cacheRead: 0.024999999999999998, cacheWrite: 0.08333333333333334, }, - contextWindow: 1000000, + contextWindow: 1048576, maxTokens: 8192, } satisfies Model<"openai-completions">, "google/gemini-2.0-flash-lite-001": { @@ -11301,6 +11352,40 @@ export const MODELS = { contextWindow: 1048576, maxTokens: 131072, } satisfies Model<"openai-completions">, + "xiaomi/mimo-v2.5": { + id: "xiaomi/mimo-v2.5", + name: "Xiaomi: MiMo-V2.5", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.39999999999999997, + output: 2, + cacheRead: 0.08, + cacheWrite: 0, + }, + contextWindow: 1048576, + maxTokens: 131072, + } satisfies Model<"openai-completions">, + "xiaomi/mimo-v2.5-pro": { + id: "xiaomi/mimo-v2.5-pro", + name: "Xiaomi: MiMo-V2.5-Pro", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 1, + output: 3, + cacheRead: 0.19999999999999998, + cacheWrite: 0, + }, + contextWindow: 1048576, + maxTokens: 131072, + } satisfies Model<"openai-completions">, "z-ai/glm-4-32b": { id: "z-ai/glm-4-32b", name: "Z.ai: GLM 4 32B ", diff --git a/packages/ai/test/anthropic-sse-parsing.test.ts b/packages/ai/test/anthropic-sse-parsing.test.ts index 55af15af..48599408 100644 --- a/packages/ai/test/anthropic-sse-parsing.test.ts +++ b/packages/ai/test/anthropic-sse-parsing.test.ts @@ -1,5 +1,5 @@ import type Anthropic from "@anthropic-ai/sdk"; -import { Type } from "@sinclair/typebox"; +import { Type } from "typebox"; import { describe, expect, it } from "vitest"; import { getModel } from "../src/models.js"; import { streamAnthropic } from "../src/providers/anthropic.js"; diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md index addd18b5..2e769c45 100644 --- a/packages/coding-agent/CHANGELOG.md +++ b/packages/coding-agent/CHANGELOG.md @@ -2,18 +2,20 @@ ## [Unreleased] +### Breaking Changes + +- Migrated first-party coding-agent code, SDK/examples/docs, and package metadata from `@sinclair/typebox` 0.34.x to `typebox` 1.x. New extensions, SDK integrations, and pi packages should depend on and import from `typebox`. Legacy extension loading still aliases the root `@sinclair/typebox` package, but `@sinclair/typebox/compiler` is no longer shimmed. This migration also picks up the new `@mariozechner/pi-ai` TypeBox-native validator path, so tool argument validation now works in eval-restricted runtimes such as Cloudflare Workers instead of being skipped ([#3112](https://github.com/badlogic/pi-mono/issues/3112)) +- Session-replacement commands now invalidate captured pre-replacement session-bound extension objects after `ctx.newSession()`, `ctx.fork()`, and `ctx.switchSession()`. Old `pi` and command `ctx` references now throw instead of silently targeting the replaced session. Migration: if code needs to keep working in the replacement session after one of those calls, pass `withSession` to that same method and do the post-switch work there. In practice, move post-switch `pi.sendUserMessage()`, `pi.sendMessage()`, and command-ctx/session-manager access into `withSession`, and use only the `ReplacedSessionContext` passed to that callback for session-bound operations. Footguns: `withSession` runs after the old extension instance has already received `session_shutdown`, old cleanup may already have invalidated captured state, captured old `pi` / old command `ctx` are stale, and previously extracted raw objects such as `const sm = ctx.sessionManager` remain the caller's responsibility and must not be reused after the switch. + ### Added -- Added `structured-output.ts` extension example plus extension docs for terminating tool results, showing how a custom tool can return `terminate: true` so the agent ends on the tool call without an extra follow-up LLM turn ([#3525](https://github.com/badlogic/pi-mono/issues/3525)) +- Added support for terminating tool results via `terminate: true`, allowing custom tools to end the current tool batch without an automatic follow-up LLM call, plus a `structured-output.ts` extension example and extension docs showing the pattern ([#3525](https://github.com/badlogic/pi-mono/issues/3525)) - Added OSC 9;4 terminal progress indicators during agent streaming and compaction, so terminals like iTerm2, WezTerm, Windows Terminal, and Kitty show activity in their tab bar - Added `ctx.ui.addAutocompleteProvider(...)` for stacking extension autocomplete providers on top of the built-in slash/path provider, plus a `github-issue-autocomplete.ts` example and extension docs ([#2983](https://github.com/badlogic/pi-mono/issues/2983)) -### Breaking Changes - -- Session-replacement commands now invalidate captured pre-replacement session-bound extension objects after `ctx.newSession()`, `ctx.fork()`, and `ctx.switchSession()`. Old `pi` and command `ctx` references now throw instead of silently targeting the replaced session. Migration: if code needs to keep working in the replacement session after one of those calls, pass `withSession` to that same method and do the post-switch work there. In practice, move post-switch `pi.sendUserMessage()`, `pi.sendMessage()`, and command-ctx/session-manager access into `withSession`, and use only the `ReplacedSessionContext` passed to that callback for session-bound operations. Footguns: `withSession` runs after the old extension instance has already received `session_shutdown`, old cleanup may already have invalidated captured state, captured old `pi` / old command `ctx` are stale, and previously extracted raw objects such as `const sm = ctx.sessionManager` remain the caller's responsibility and must not be reused after the switch. - ### Fixed +- Fixed exported session HTML to sanitize markdown link URLs before rendering them into anchor tags, blocking `javascript:`-style payloads while preserving safe links in shared/exported sessions ([#3532](https://github.com/badlogic/pi-mono/issues/3532)) - Fixed `ctx.getSystemPrompt()` inside `before_agent_start` to reflect chained system-prompt changes made by earlier `before_agent_start` handlers, and clarified the extension docs around provider-payload rewrites and what `ctx.getSystemPrompt()` does and does not report ([#3539](https://github.com/badlogic/pi-mono/issues/3539)) - Fixed built-in `google-gemini-cli` model lists and selector entries to include `gemini-3.1-flash-lite-preview`, so Cloud Code Assist users no longer need manual `--model` fallback selection to use it ([#3545](https://github.com/badlogic/pi-mono/issues/3545)) - Fixed extension session-replacement flows so `ctx.newSession()`, `ctx.fork()`, `ctx.switchSession()`, and imported-session replacements fully rebind before post-switch work runs, added `withSession` replacement callbacks with fresh `ReplacedSessionContext` helpers, and make stale pre-replacement `pi` / `ctx` session-bound accesses throw instead of silently targeting the wrong session ([#2860](https://github.com/badlogic/pi-mono/issues/2860)) diff --git a/packages/coding-agent/docs/extensions.md b/packages/coding-agent/docs/extensions.md index 8aa49eff..3b07a369 100644 --- a/packages/coding-agent/docs/extensions.md +++ b/packages/coding-agent/docs/extensions.md @@ -57,7 +57,7 @@ Create `~/.pi/agent/extensions/my-extension.ts`: ```typescript import type { ExtensionAPI } from "@mariozechner/pi-coding-agent"; -import { Type } from "@sinclair/typebox"; +import { Type } from "typebox"; export default function (pi: ExtensionAPI) { // React to events @@ -139,7 +139,7 @@ To share extensions via npm or git as pi packages, see [packages.md](packages.md | Package | Purpose | |---------|---------| | `@mariozechner/pi-coding-agent` | Extension types (`ExtensionAPI`, `ExtensionContext`, events) | -| `@sinclair/typebox` | Schema definitions for tool parameters | +| `typebox` | Schema definitions for tool parameters | | `@mariozechner/pi-ai` | AI utilities (`StringEnum` for Google-compatible enums) | | `@mariozechner/pi-tui` | TUI components for custom rendering | @@ -1139,7 +1139,7 @@ Example tool the LLM can call to trigger reload: ```typescript import type { ExtensionAPI } from "@mariozechner/pi-coding-agent"; -import { Type } from "@sinclair/typebox"; +import { Type } from "typebox"; export default function (pi: ExtensionAPI) { pi.registerCommand("reload-runtime", { @@ -1186,7 +1186,7 @@ Use `promptSnippet` to opt a custom tool into a one-line entry in `Available too See [dynamic-tools.ts](../examples/extensions/dynamic-tools.ts) for a full example. ```typescript -import { Type } from "@sinclair/typebox"; +import { Type } from "typebox"; import { StringEnum } from "@mariozechner/pi-ai"; pi.registerTool({ @@ -1657,7 +1657,7 @@ async execute(_toolCallId, params, _signal, _onUpdate, ctx) { ### Tool Definition ```typescript -import { Type } from "@sinclair/typebox"; +import { Type } from "typebox"; import { StringEnum } from "@mariozechner/pi-ai"; import { Text } from "@mariozechner/pi-tui"; diff --git a/packages/coding-agent/docs/packages.md b/packages/coding-agent/docs/packages.md index 6a7bf19a..23413c18 100644 --- a/packages/coding-agent/docs/packages.md +++ b/packages/coding-agent/docs/packages.md @@ -158,7 +158,7 @@ If no `pi` manifest is present, pi auto-discovers resources from these directori Third party runtime dependencies belong in `dependencies` in `package.json`. Dependencies that do not register extensions, skills, prompt templates, or themes also belong in `dependencies`. When pi installs a package from npm or git, it runs `npm install`, so those dependencies are installed automatically. -Pi bundles core packages for extensions and skills. If you import any of these, list them in `peerDependencies` with a `"*"` range and do not bundle them: `@mariozechner/pi-ai`, `@mariozechner/pi-agent-core`, `@mariozechner/pi-coding-agent`, `@mariozechner/pi-tui`, `@sinclair/typebox`. +Pi bundles core packages for extensions and skills. If you import any of these, list them in `peerDependencies` with a `"*"` range and do not bundle them: `@mariozechner/pi-ai`, `@mariozechner/pi-agent-core`, `@mariozechner/pi-coding-agent`, `@mariozechner/pi-tui`, `typebox`. Other pi packages must be bundled in your tarball. Add them to `dependencies` and `bundledDependencies`, then reference their resources through `node_modules/` paths. Pi loads packages with separate module roots, so separate installs do not collide or share modules. diff --git a/packages/coding-agent/docs/sdk.md b/packages/coding-agent/docs/sdk.md index c6579f76..d84ca0a1 100644 --- a/packages/coding-agent/docs/sdk.md +++ b/packages/coding-agent/docs/sdk.md @@ -529,7 +529,7 @@ const { session } = await createAgentSession({ ### Custom Tools ```typescript -import { Type } from "@sinclair/typebox"; +import { Type } from "typebox"; import { createAgentSession, defineTool } from "@mariozechner/pi-coding-agent"; // Inline custom tool @@ -882,7 +882,7 @@ interface LoadExtensionsResult { ```typescript import { getModel } from "@mariozechner/pi-ai"; -import { Type } from "@sinclair/typebox"; +import { Type } from "typebox"; import { AuthStorage, bashTool, diff --git a/packages/coding-agent/examples/extensions/README.md b/packages/coding-agent/examples/extensions/README.md index 8fdbdbee..d62f7d74 100644 --- a/packages/coding-agent/examples/extensions/README.md +++ b/packages/coding-agent/examples/extensions/README.md @@ -140,7 +140,7 @@ See [docs/extensions.md](../../docs/extensions.md) for full documentation. ```typescript import type { ExtensionAPI } from "@mariozechner/pi-coding-agent"; -import { Type } from "@sinclair/typebox"; +import { Type } from "typebox"; export default function (pi: ExtensionAPI) { // Subscribe to lifecycle events diff --git a/packages/coding-agent/examples/extensions/structured-output.ts b/packages/coding-agent/examples/extensions/structured-output.ts index 9fb6a426..17f19938 100644 --- a/packages/coding-agent/examples/extensions/structured-output.ts +++ b/packages/coding-agent/examples/extensions/structured-output.ts @@ -7,7 +7,7 @@ import { defineTool, type ExtensionAPI } from "@mariozechner/pi-coding-agent"; import { Text } from "@mariozechner/pi-tui"; -import { Type } from "@sinclair/typebox"; +import { Type } from "typebox"; interface StructuredOutputDetails { headline: string; diff --git a/packages/coding-agent/src/core/extensions/loader.ts b/packages/coding-agent/src/core/extensions/loader.ts index 56688a6b..893bd728 100644 --- a/packages/coding-agent/src/core/extensions/loader.ts +++ b/packages/coding-agent/src/core/extensions/loader.ts @@ -29,7 +29,6 @@ import { createEventBus, type EventBus } from "../event-bus.js"; import type { ExecOptions } from "../exec.js"; import { execCommand } from "../exec.js"; import { createSyntheticSourceInfo } from "../source-info.js"; -import * as _bundledTypeboxCompilerCompat from "./typebox-compiler-compat.js"; import type { Extension, ExtensionAPI, @@ -47,11 +46,9 @@ const VIRTUAL_MODULES: Record = { typebox: _bundledTypebox, "typebox/compile": _bundledTypeboxCompile, "typebox/value": _bundledTypeboxValue, - "typebox/compiler": _bundledTypeboxCompilerCompat, "@sinclair/typebox": _bundledTypebox, "@sinclair/typebox/compile": _bundledTypeboxCompile, "@sinclair/typebox/value": _bundledTypeboxValue, - "@sinclair/typebox/compiler": _bundledTypeboxCompilerCompat, "@mariozechner/pi-agent-core": _bundledPiAgentCore, "@mariozechner/pi-tui": _bundledPiTui, "@mariozechner/pi-ai": _bundledPiAi, @@ -67,14 +64,6 @@ const require = createRequire(import.meta.url); */ let _aliases: Record | null = null; -function resolveTypeboxCompilerCompatPath(baseDir: string): string { - const jsPath = path.resolve(baseDir, "typebox-compiler-compat.js"); - if (fs.existsSync(jsPath)) { - return jsPath; - } - return path.resolve(baseDir, "typebox-compiler-compat.ts"); -} - function getAliases(): Record { if (_aliases) return _aliases; @@ -84,7 +73,6 @@ function getAliases(): Record { const typeboxEntry = require.resolve("typebox"); const typeboxCompileEntry = require.resolve("typebox/compile"); const typeboxValueEntry = require.resolve("typebox/value"); - const typeboxCompilerCompat = resolveTypeboxCompilerCompatPath(__dirname); const packagesRoot = path.resolve(__dirname, "../../../../"); const resolveWorkspaceOrImport = (workspaceRelativePath: string, specifier: string): string => { @@ -104,11 +92,9 @@ function getAliases(): Record { typebox: typeboxEntry, "typebox/compile": typeboxCompileEntry, "typebox/value": typeboxValueEntry, - "typebox/compiler": typeboxCompilerCompat, "@sinclair/typebox": typeboxEntry, "@sinclair/typebox/compile": typeboxCompileEntry, "@sinclair/typebox/value": typeboxValueEntry, - "@sinclair/typebox/compiler": typeboxCompilerCompat, }; return _aliases; diff --git a/packages/coding-agent/src/core/extensions/typebox-compiler-compat.ts b/packages/coding-agent/src/core/extensions/typebox-compiler-compat.ts deleted file mode 100644 index 94bdcd24..00000000 --- a/packages/coding-agent/src/core/extensions/typebox-compiler-compat.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Code, Compile, Validator } from "typebox/compile"; - -export { Code, Compile, Validator }; - -// Legacy @sinclair/typebox/compiler compatibility for extensions. -export const TypeCompiler = { - Compile, -}; - -// In TypeBox 0.x this was a named export. Map it to the v1 Validator class. -export const TypeCheck = Validator; - -export default { - Code, - Compile, - Validator, - TypeCompiler, - TypeCheck, -}; diff --git a/packages/coding-agent/test/fixtures/large-session.jsonl b/packages/coding-agent/test/fixtures/large-session.jsonl index 5a6fb54e..d95287af 100644 --- a/packages/coding-agent/test/fixtures/large-session.jsonl +++ b/packages/coding-agent/test/fixtures/large-session.jsonl @@ -5,7 +5,7 @@ {"type":"message","timestamp":"2025-11-20T23:33:50.804Z","message":{"role":"user","content":[{"type":"text","text":"read packages/coding-agent/docs/theme.md in full, then theme.ts, and then oauth-selector or any of the other selectors. we still need to port over user-message-selector.ts based on the patterns you find in the other files"}],"timestamp":1763681630791}} {"type":"message","timestamp":"2025-11-20T23:33:54.572Z","message":{"role":"assistant","content":[{"type":"text","text":"I'll read the theme documentation, theme.ts, and the selector files to understand the patterns, then help port over user-message-selector.ts."},{"type":"toolCall","id":"toolu_017qEkVzzPb7b7o4FkgJLF23","name":"read","arguments":{"path":"packages/coding-agent/docs/theme.md"}},{"type":"toolCall","id":"toolu_01FnVNKzWWm2s2SFJmJttiWh","name":"read","arguments":{"path":"packages/coding-agent/src/theme/theme.ts"}},{"type":"toolCall","id":"toolu_016aKHTkjrTJcMds3wsEou2R","name":"bash","arguments":{"command":"find packages/coding-agent/src -name \"*selector.ts\" -type f"}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-4-5","usage":{"input":3,"output":191,"cacheRead":0,"cacheWrite":1684,"cost":{"input":0.000009,"output":0.002865,"cacheRead":0,"cacheWrite":0.006315,"total":0.009189}},"stopReason":"toolUse","timestamp":1763681630793}} {"type":"message","timestamp":"2025-11-20T23:33:54.575Z","message":{"role":"toolResult","toolCallId":"toolu_017qEkVzzPb7b7o4FkgJLF23","toolName":"read","content":[{"type":"text","text":"# Pi Coding Agent Themes\n\nThemes allow you to customize the colors used throughout the coding agent TUI.\n\n## Color Tokens\n\nEvery theme must define all color tokens. There are no optional colors.\n\n### Core UI (10 colors)\n\n| Token | Purpose | Examples |\n|-------|---------|----------|\n| `accent` | Primary accent color | Logo, selected items, cursor (›) |\n| `border` | Normal borders | Selector borders, horizontal lines |\n| `borderAccent` | Highlighted borders | Changelog borders, special panels |\n| `borderMuted` | Subtle borders | Editor borders, secondary separators |\n| `success` | Success states | Success messages, diff additions |\n| `error` | Error states | Error messages, diff deletions |\n| `warning` | Warning states | Warning messages |\n| `muted` | Secondary/dimmed text | Metadata, descriptions, output |\n| `dim` | Very dimmed text | Less important info, placeholders |\n| `text` | Default text color | Main content (usually `\"\"`) |\n\n### Backgrounds & Content Text (6 colors)\n\n| Token | Purpose |\n|-------|---------|\n| `userMessageBg` | User message background |\n| `userMessageText` | User message text color |\n| `toolPendingBg` | Tool execution box (pending state) |\n| `toolSuccessBg` | Tool execution box (success state) |\n| `toolErrorBg` | Tool execution box (error state) |\n| `toolText` | Tool execution box text color (all states) |\n\n### Markdown (9 colors)\n\n| Token | Purpose |\n|-------|---------|\n| `mdHeading` | Heading text (`#`, `##`, etc) |\n| `mdLink` | Link text and URLs |\n| `mdCode` | Inline code (backticks) |\n| `mdCodeBlock` | Code block content |\n| `mdCodeBlockBorder` | Code block fences (```) |\n| `mdQuote` | Blockquote text |\n| `mdQuoteBorder` | Blockquote border (`│`) |\n| `mdHr` | Horizontal rule (`---`) |\n| `mdListBullet` | List bullets/numbers |\n\n### Tool Diffs (3 colors)\n\n| Token | Purpose |\n|-------|---------|\n| `toolDiffAdded` | Added lines in tool diffs |\n| `toolDiffRemoved` | Removed lines in tool diffs |\n| `toolDiffContext` | Context lines in tool diffs |\n\nNote: Diff colors are specific to tool execution boxes and must work with tool background colors.\n\n### Syntax Highlighting (9 colors)\n\nFuture-proofing for syntax highlighting support:\n\n| Token | Purpose |\n|-------|---------|\n| `syntaxComment` | Comments |\n| `syntaxKeyword` | Keywords (`if`, `function`, etc) |\n| `syntaxFunction` | Function names |\n| `syntaxVariable` | Variable names |\n| `syntaxString` | String literals |\n| `syntaxNumber` | Number literals |\n| `syntaxType` | Type names |\n| `syntaxOperator` | Operators (`+`, `-`, etc) |\n| `syntaxPunctuation` | Punctuation (`;`, `,`, etc) |\n\n**Total: 37 color tokens** (all required)\n\n## Theme Format\n\nThemes are defined in JSON files with the following structure:\n\n```json\n{\n \"$schema\": \"https://raw.githubusercontent.com/badlogic/pi-mono/main/packages/coding-agent/theme-schema.json\",\n \"name\": \"my-theme\",\n \"vars\": {\n \"blue\": \"#0066cc\",\n \"gray\": 242,\n \"brightCyan\": 51\n },\n \"colors\": {\n \"accent\": \"blue\",\n \"muted\": \"gray\",\n \"text\": \"\",\n ...\n }\n}\n```\n\n### Color Values\n\nFour formats are supported:\n\n1. **Hex colors**: `\"#ff0000\"` (6-digit hex RGB)\n2. **256-color palette**: `39` (number 0-255, xterm 256-color palette)\n3. **Color references**: `\"blue\"` (must be defined in `vars`)\n4. **Terminal default**: `\"\"` (empty string, uses terminal's default color)\n\n### The `vars` Section\n\nThe optional `vars` section allows you to define reusable colors:\n\n```json\n{\n \"vars\": {\n \"nord0\": \"#2E3440\",\n \"nord1\": \"#3B4252\",\n \"nord8\": \"#88C0D0\",\n \"brightBlue\": 39\n },\n \"colors\": {\n \"accent\": \"nord8\",\n \"muted\": \"nord1\",\n \"mdLink\": \"brightBlue\"\n }\n}\n```\n\nBenefits:\n- Reuse colors across multiple tokens\n- Easier to maintain theme consistency\n- Can reference standard color palettes\n\nVariables can be hex colors (`\"#ff0000\"`), 256-color indices (`42`), or references to other variables.\n\n### Terminal Default (empty string)\n\nUse `\"\"` (empty string) to inherit the terminal's default foreground/background color:\n\n```json\n{\n \"colors\": {\n \"text\": \"\" // Uses terminal's default text color\n }\n}\n```\n\nThis is useful for:\n- Main text color (adapts to user's terminal theme)\n- Creating themes that blend with terminal appearance\n\n## Built-in Themes\n\nPi comes with two built-in themes:\n\n### `dark` (default)\n\nOptimized for dark terminal backgrounds with bright, saturated colors.\n\n### `light`\n\nOptimized for light terminal backgrounds with darker, muted colors.\n\n## Selecting a Theme\n\nThemes are configured in the settings (accessible via `/settings`):\n\n```json\n{\n \"theme\": \"dark\"\n}\n```\n\nOr use the `/theme` command interactively.\n\nOn first run, Pi detects your terminal's background and sets a sensible default (`dark` or `light`).\n\n## Custom Themes\n\n### Theme Locations\n\nCustom themes are loaded from `~/.pi/agent/themes/*.json`.\n\n### Creating a Custom Theme\n\n1. **Create theme directory:**\n ```bash\n mkdir -p ~/.pi/agent/themes\n ```\n\n2. **Create theme file:**\n ```bash\n vim ~/.pi/agent/themes/my-theme.json\n ```\n\n3. **Define all colors:**\n ```json\n {\n \"$schema\": \"https://raw.githubusercontent.com/badlogic/pi-mono/main/packages/coding-agent/theme-schema.json\",\n \"name\": \"my-theme\",\n \"vars\": {\n \"primary\": \"#00aaff\",\n \"secondary\": 242,\n \"brightGreen\": 46\n },\n \"colors\": {\n \"accent\": \"primary\",\n \"border\": \"primary\",\n \"borderAccent\": \"#00ffff\",\n \"borderMuted\": \"secondary\",\n \"success\": \"brightGreen\",\n \"error\": \"#ff0000\",\n \"warning\": \"#ffff00\",\n \"muted\": \"secondary\",\n \"text\": \"\",\n \n \"userMessageBg\": \"#2d2d30\",\n \"userMessageText\": \"\",\n \"toolPendingBg\": \"#1e1e2e\",\n \"toolSuccessBg\": \"#1e2e1e\",\n \"toolErrorBg\": \"#2e1e1e\",\n \"toolText\": \"\",\n \n \"mdHeading\": \"#ffaa00\",\n \"mdLink\": \"primary\",\n \"mdCode\": \"#00ffff\",\n \"mdCodeBlock\": \"#00ff00\",\n \"mdCodeBlockBorder\": \"secondary\",\n \"mdQuote\": \"secondary\",\n \"mdQuoteBorder\": \"secondary\",\n \"mdHr\": \"secondary\",\n \"mdListBullet\": \"#00ffff\",\n \n \"toolDiffAdded\": \"#00ff00\",\n \"toolDiffRemoved\": \"#ff0000\",\n \"toolDiffContext\": \"secondary\",\n \n \"syntaxComment\": \"secondary\",\n \"syntaxKeyword\": \"primary\",\n \"syntaxFunction\": \"#00aaff\",\n \"syntaxVariable\": \"#ffaa00\",\n \"syntaxString\": \"#00ff00\",\n \"syntaxNumber\": \"#ff00ff\",\n \"syntaxType\": \"#00aaff\",\n \"syntaxOperator\": \"primary\",\n \"syntaxPunctuation\": \"secondary\"\n }\n }\n ```\n\n4. **Select your theme:**\n - Use `/settings` command and set `\"theme\": \"my-theme\"`\n - Or use `/theme` command interactively\n\n## Tips\n\n### Light vs Dark Themes\n\n**For dark terminals:**\n- Use bright, saturated colors\n- Higher contrast\n- Example: `#00ffff` (bright cyan)\n\n**For light terminals:**\n- Use darker, muted colors\n- Lower contrast to avoid eye strain\n- Example: `#008888` (dark cyan)\n\n### Color Harmony\n\n- Start with a base palette (e.g., Nord, Gruvbox, Tokyo Night)\n- Define your palette in `defs`\n- Reference colors consistently\n\n### Testing\n\nTest your theme with:\n- Different message types (user, assistant, errors)\n- Tool executions (success and error states)\n- Markdown content (headings, code, lists, etc)\n- Long text that wraps\n\n## Color Format Reference\n\n### Hex Colors\n\nStandard 6-digit hex format:\n- `\"#ff0000\"` - Red\n- `\"#00ff00\"` - Green\n- `\"#0000ff\"` - Blue\n- `\"#808080\"` - Gray\n- `\"#ffffff\"` - White\n- `\"#000000\"` - Black\n\nRGB values: `#RRGGBB` where each component is `00-ff` (0-255)\n\n### 256-Color Palette\n\nUse numeric indices (0-255) to reference the xterm 256-color palette:\n\n**Colors 0-15:** Basic ANSI colors (terminal-dependent, may be themed)\n- `0` - Black\n- `1` - Red\n- `2` - Green\n- `3` - Yellow\n- `4` - Blue\n- `5` - Magenta\n- `6` - Cyan\n- `7` - White\n- `8-15` - Bright variants\n\n**Colors 16-231:** 6×6×6 RGB cube (standardized)\n- Formula: `16 + 36×R + 6×G + B` where R, G, B are 0-5\n- Example: `39` = bright cyan, `196` = bright red\n\n**Colors 232-255:** Grayscale ramp (standardized)\n- `232` - Darkest gray\n- `255` - Near white\n\nExample usage:\n```json\n{\n \"vars\": {\n \"gray\": 242,\n \"brightCyan\": 51,\n \"darkBlue\": 18\n },\n \"colors\": {\n \"muted\": \"gray\",\n \"accent\": \"brightCyan\"\n }\n}\n```\n\n**Benefits:**\n- Works everywhere (`TERM=xterm-256color`)\n- No truecolor detection needed\n- Standardized RGB cube (16-231) looks the same on all terminals\n\n### Terminal Compatibility\n\nPi uses 24-bit RGB colors (`\\x1b[38;2;R;G;Bm`). Most modern terminals support this:\n\n- ✅ iTerm2, Alacritty, Kitty, WezTerm\n- ✅ Windows Terminal\n- ✅ VS Code integrated terminal\n- ✅ Modern GNOME Terminal, Konsole\n\nFor older terminals with only 256-color support, Pi automatically falls back to the nearest 256-color approximation.\n\nTo check if your terminal supports truecolor:\n```bash\necho $COLORTERM # Should output \"truecolor\" or \"24bit\"\n```\n\n## Example Themes\n\nSee the built-in themes for complete examples:\n- [Dark theme](../src/themes/dark.json)\n- [Light theme](../src/themes/light.json)\n\n## Schema Validation\n\nThemes are validated on load using [TypeBox](https://github.com/sinclairzx81/typebox) + [Ajv](https://ajv.js.org/).\n\nInvalid themes will show an error with details about what's wrong:\n```\nError loading theme 'my-theme':\n - colors.accent: must be string or number\n - colors.mdHeading: required property missing\n```\n\nFor editor support, the JSON schema is available at:\n```\nhttps://raw.githubusercontent.com/badlogic/pi-mono/main/packages/coding-agent/theme-schema.json\n```\n\nAdd to your theme file for auto-completion and validation:\n```json\n{\n \"$schema\": \"https://raw.githubusercontent.com/badlogic/pi-mono/main/packages/coding-agent/theme-schema.json\",\n ...\n}\n```\n\n## Implementation\n\n### Theme Class\n\nThemes are loaded and converted to a `Theme` class that provides type-safe color methods:\n\n```typescript\nclass Theme {\n // Apply foreground color\n fg(color: ThemeColor, text: string): string\n \n // Apply background color\n bg(color: ThemeBg, text: string): string\n \n // Text attributes (preserve current colors)\n bold(text: string): string\n dim(text: string): string\n italic(text: string): string\n}\n```\n\n### Global Theme Instance\n\nThe active theme is available as a global singleton in `coding-agent`:\n\n```typescript\n// theme.ts\nexport let theme: Theme;\n\nexport function setTheme(name: string) {\n theme = loadTheme(name);\n}\n\n// Usage throughout coding-agent\nimport { theme } from './theme.js';\n\ntheme.fg('accent', 'Selected')\ntheme.bg('userMessageBg', content)\n```\n\n### TUI Component Theming\n\nTUI components (like `Markdown`, `SelectList`, `Editor`) are in the `@mariozechner/pi-tui` package and don't have direct access to the theme. Instead, they define interfaces for the colors they need:\n\n```typescript\n// In @mariozechner/pi-tui\nexport interface MarkdownTheme {\n heading: (text: string) => string;\n link: (text: string) => string;\n code: (text: string) => string;\n codeBlock: (text: string) => string;\n codeBlockBorder: (text: string) => string;\n quote: (text: string) => string;\n quoteBorder: (text: string) => string;\n hr: (text: string) => string;\n listBullet: (text: string) => string;\n}\n\nexport class Markdown {\n constructor(\n text: string,\n paddingX: number,\n paddingY: number,\n defaultTextStyle?: DefaultTextStyle,\n theme?: MarkdownTheme // Optional theme functions\n )\n \n // Usage in component\n renderHeading(text: string) {\n return this.theme.heading(text); // Applies color\n }\n}\n```\n\nThe `coding-agent` provides themed functions when creating components:\n\n```typescript\n// In coding-agent\nimport { theme } from './theme.js';\nimport { Markdown } from '@mariozechner/pi-tui';\n\n// Helper to create markdown theme functions\nfunction getMarkdownTheme(): MarkdownTheme {\n return {\n heading: (text) => theme.fg('mdHeading', text),\n link: (text) => theme.fg('mdLink', text),\n code: (text) => theme.fg('mdCode', text),\n codeBlock: (text) => theme.fg('mdCodeBlock', text),\n codeBlockBorder: (text) => theme.fg('mdCodeBlockBorder', text),\n quote: (text) => theme.fg('mdQuote', text),\n quoteBorder: (text) => theme.fg('mdQuoteBorder', text),\n hr: (text) => theme.fg('mdHr', text),\n listBullet: (text) => theme.fg('mdListBullet', text),\n };\n}\n\n// Create markdown with theme\nconst md = new Markdown(\n text,\n 1, 1,\n { bgColor: theme.bg('userMessageBg') },\n getMarkdownTheme()\n);\n```\n\nThis approach:\n- Keeps TUI components theme-agnostic (reusable in other projects)\n- Maintains type safety via interfaces\n- Allows components to have sensible defaults if no theme provided\n- Centralizes theme access in `coding-agent`\n\n**Example usage:**\n```typescript\nconst theme = loadTheme('dark');\n\n// Apply foreground colors\ntheme.fg('accent', 'Selected')\ntheme.fg('success', '✓ Done')\ntheme.fg('error', 'Failed')\n\n// Apply background colors\ntheme.bg('userMessageBg', content)\ntheme.bg('toolSuccessBg', output)\n\n// Combine styles\ntheme.bold(theme.fg('accent', 'Title'))\ntheme.dim(theme.fg('muted', 'metadata'))\n\n// Nested foreground + background\nconst userMsg = theme.bg('userMessageBg',\n theme.fg('userMessageText', 'Hello')\n)\n```\n\n**Color resolution:**\n\n1. **Detect terminal capabilities:**\n - Check `$COLORTERM` env var (`truecolor` or `24bit` → truecolor support)\n - Check `$TERM` env var (`*-256color` → 256-color support)\n - Fallback to 256-color mode if detection fails\n\n2. **Load JSON theme file**\n\n3. **Resolve `vars` references recursively:**\n ```json\n {\n \"vars\": {\n \"primary\": \"#0066cc\",\n \"accent\": \"primary\"\n },\n \"colors\": {\n \"accent\": \"accent\" // → \"primary\" → \"#0066cc\"\n }\n }\n ```\n\n4. **Convert colors to ANSI codes based on terminal capability:**\n \n **Truecolor mode (24-bit):**\n - Hex (`\"#ff0000\"`) → `\\x1b[38;2;255;0;0m`\n - 256-color (`42`) → `\\x1b[38;5;42m` (keep as-is)\n - Empty string (`\"\"`) → `\\x1b[39m`\n \n **256-color mode:**\n - Hex (`\"#ff0000\"`) → convert to nearest RGB cube color → `\\x1b[38;5;196m`\n - 256-color (`42`) → `\\x1b[38;5;42m` (keep as-is)\n - Empty string (`\"\"`) → `\\x1b[39m`\n \n **Hex to 256-color conversion:**\n ```typescript\n // Convert RGB to 6x6x6 cube (colors 16-231)\n r_index = Math.round(r / 255 * 5)\n g_index = Math.round(g / 255 * 5)\n b_index = Math.round(b / 255 * 5)\n color_index = 16 + 36 * r_index + 6 * g_index + b_index\n ```\n\n5. **Cache as `Theme` instance**\n\nThis ensures themes work correctly regardless of terminal capabilities, with graceful degradation from truecolor to 256-color.\n"}],"isError":false,"timestamp":1763681634574}} -{"type":"message","timestamp":"2025-11-20T23:33:54.580Z","message":{"role":"toolResult","toolCallId":"toolu_01FnVNKzWWm2s2SFJmJttiWh","toolName":"read","content":[{"type":"text","text":"import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { EditorTheme, MarkdownTheme, SelectListTheme } from \"@mariozechner/pi-tui\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport { TypeCompiler } from \"@sinclair/typebox/compiler\";\nimport chalk from \"chalk\";\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\n// ============================================================================\n// Types & Schema\n// ============================================================================\n\nconst ColorValueSchema = Type.Union([\n\tType.String(), // hex \"#ff0000\", var ref \"primary\", or empty \"\"\n\tType.Integer({ minimum: 0, maximum: 255 }), // 256-color index\n]);\n\ntype ColorValue = Static;\n\nconst ThemeJsonSchema = Type.Object({\n\t$schema: Type.Optional(Type.String()),\n\tname: Type.String(),\n\tvars: Type.Optional(Type.Record(Type.String(), ColorValueSchema)),\n\tcolors: Type.Object({\n\t\t// Core UI (10 colors)\n\t\taccent: ColorValueSchema,\n\t\tborder: ColorValueSchema,\n\t\tborderAccent: ColorValueSchema,\n\t\tborderMuted: ColorValueSchema,\n\t\tsuccess: ColorValueSchema,\n\t\terror: ColorValueSchema,\n\t\twarning: ColorValueSchema,\n\t\tmuted: ColorValueSchema,\n\t\tdim: ColorValueSchema,\n\t\ttext: ColorValueSchema,\n\t\t// Backgrounds & Content Text (6 colors)\n\t\tuserMessageBg: ColorValueSchema,\n\t\tuserMessageText: ColorValueSchema,\n\t\ttoolPendingBg: ColorValueSchema,\n\t\ttoolSuccessBg: ColorValueSchema,\n\t\ttoolErrorBg: ColorValueSchema,\n\t\ttoolText: ColorValueSchema,\n\t\t// Markdown (9 colors)\n\t\tmdHeading: ColorValueSchema,\n\t\tmdLink: ColorValueSchema,\n\t\tmdCode: ColorValueSchema,\n\t\tmdCodeBlock: ColorValueSchema,\n\t\tmdCodeBlockBorder: ColorValueSchema,\n\t\tmdQuote: ColorValueSchema,\n\t\tmdQuoteBorder: ColorValueSchema,\n\t\tmdHr: ColorValueSchema,\n\t\tmdListBullet: ColorValueSchema,\n\t\t// Tool Diffs (3 colors)\n\t\ttoolDiffAdded: ColorValueSchema,\n\t\ttoolDiffRemoved: ColorValueSchema,\n\t\ttoolDiffContext: ColorValueSchema,\n\t\t// Syntax Highlighting (9 colors)\n\t\tsyntaxComment: ColorValueSchema,\n\t\tsyntaxKeyword: ColorValueSchema,\n\t\tsyntaxFunction: ColorValueSchema,\n\t\tsyntaxVariable: ColorValueSchema,\n\t\tsyntaxString: ColorValueSchema,\n\t\tsyntaxNumber: ColorValueSchema,\n\t\tsyntaxType: ColorValueSchema,\n\t\tsyntaxOperator: ColorValueSchema,\n\t\tsyntaxPunctuation: ColorValueSchema,\n\t}),\n});\n\ntype ThemeJson = Static;\n\nconst validateThemeJson = TypeCompiler.Compile(ThemeJsonSchema);\n\nexport type ThemeColor =\n\t| \"accent\"\n\t| \"border\"\n\t| \"borderAccent\"\n\t| \"borderMuted\"\n\t| \"success\"\n\t| \"error\"\n\t| \"warning\"\n\t| \"muted\"\n\t| \"dim\"\n\t| \"text\"\n\t| \"userMessageText\"\n\t| \"toolText\"\n\t| \"mdHeading\"\n\t| \"mdLink\"\n\t| \"mdCode\"\n\t| \"mdCodeBlock\"\n\t| \"mdCodeBlockBorder\"\n\t| \"mdQuote\"\n\t| \"mdQuoteBorder\"\n\t| \"mdHr\"\n\t| \"mdListBullet\"\n\t| \"toolDiffAdded\"\n\t| \"toolDiffRemoved\"\n\t| \"toolDiffContext\"\n\t| \"syntaxComment\"\n\t| \"syntaxKeyword\"\n\t| \"syntaxFunction\"\n\t| \"syntaxVariable\"\n\t| \"syntaxString\"\n\t| \"syntaxNumber\"\n\t| \"syntaxType\"\n\t| \"syntaxOperator\"\n\t| \"syntaxPunctuation\";\n\nexport type ThemeBg = \"userMessageBg\" | \"toolPendingBg\" | \"toolSuccessBg\" | \"toolErrorBg\";\n\ntype ColorMode = \"truecolor\" | \"256color\";\n\n// ============================================================================\n// Color Utilities\n// ============================================================================\n\nfunction detectColorMode(): ColorMode {\n\tconst colorterm = process.env.COLORTERM;\n\tif (colorterm === \"truecolor\" || colorterm === \"24bit\") {\n\t\treturn \"truecolor\";\n\t}\n\tconst term = process.env.TERM || \"\";\n\tif (term.includes(\"256color\")) {\n\t\treturn \"256color\";\n\t}\n\treturn \"256color\";\n}\n\nfunction hexToRgb(hex: string): { r: number; g: number; b: number } {\n\tconst cleaned = hex.replace(\"#\", \"\");\n\tif (cleaned.length !== 6) {\n\t\tthrow new Error(`Invalid hex color: ${hex}`);\n\t}\n\tconst r = parseInt(cleaned.substring(0, 2), 16);\n\tconst g = parseInt(cleaned.substring(2, 4), 16);\n\tconst b = parseInt(cleaned.substring(4, 6), 16);\n\tif (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) {\n\t\tthrow new Error(`Invalid hex color: ${hex}`);\n\t}\n\treturn { r, g, b };\n}\n\nfunction rgbTo256(r: number, g: number, b: number): number {\n\tconst rIndex = Math.round((r / 255) * 5);\n\tconst gIndex = Math.round((g / 255) * 5);\n\tconst bIndex = Math.round((b / 255) * 5);\n\treturn 16 + 36 * rIndex + 6 * gIndex + bIndex;\n}\n\nfunction hexTo256(hex: string): number {\n\tconst { r, g, b } = hexToRgb(hex);\n\treturn rgbTo256(r, g, b);\n}\n\nfunction fgAnsi(color: string | number, mode: ColorMode): string {\n\tif (color === \"\") return \"\\x1b[39m\";\n\tif (typeof color === \"number\") return `\\x1b[38;5;${color}m`;\n\tif (color.startsWith(\"#\")) {\n\t\tif (mode === \"truecolor\") {\n\t\t\tconst { r, g, b } = hexToRgb(color);\n\t\t\treturn `\\x1b[38;2;${r};${g};${b}m`;\n\t\t} else {\n\t\t\tconst index = hexTo256(color);\n\t\t\treturn `\\x1b[38;5;${index}m`;\n\t\t}\n\t}\n\tthrow new Error(`Invalid color value: ${color}`);\n}\n\nfunction bgAnsi(color: string | number, mode: ColorMode): string {\n\tif (color === \"\") return \"\\x1b[49m\";\n\tif (typeof color === \"number\") return `\\x1b[48;5;${color}m`;\n\tif (color.startsWith(\"#\")) {\n\t\tif (mode === \"truecolor\") {\n\t\t\tconst { r, g, b } = hexToRgb(color);\n\t\t\treturn `\\x1b[48;2;${r};${g};${b}m`;\n\t\t} else {\n\t\t\tconst index = hexTo256(color);\n\t\t\treturn `\\x1b[48;5;${index}m`;\n\t\t}\n\t}\n\tthrow new Error(`Invalid color value: ${color}`);\n}\n\nfunction resolveVarRefs(\n\tvalue: ColorValue,\n\tvars: Record,\n\tvisited = new Set(),\n): string | number {\n\tif (typeof value === \"number\" || value === \"\" || value.startsWith(\"#\")) {\n\t\treturn value;\n\t}\n\tif (visited.has(value)) {\n\t\tthrow new Error(`Circular variable reference detected: ${value}`);\n\t}\n\tif (!(value in vars)) {\n\t\tthrow new Error(`Variable reference not found: ${value}`);\n\t}\n\tvisited.add(value);\n\treturn resolveVarRefs(vars[value], vars, visited);\n}\n\nfunction resolveThemeColors>(\n\tcolors: T,\n\tvars: Record = {},\n): Record {\n\tconst resolved: Record = {};\n\tfor (const [key, value] of Object.entries(colors)) {\n\t\tresolved[key] = resolveVarRefs(value, vars);\n\t}\n\treturn resolved as Record;\n}\n\n// ============================================================================\n// Theme Class\n// ============================================================================\n\nexport class Theme {\n\tprivate fgColors: Map;\n\tprivate bgColors: Map;\n\tprivate mode: ColorMode;\n\n\tconstructor(\n\t\tfgColors: Record,\n\t\tbgColors: Record,\n\t\tmode: ColorMode,\n\t) {\n\t\tthis.mode = mode;\n\t\tthis.fgColors = new Map();\n\t\tfor (const [key, value] of Object.entries(fgColors) as [ThemeColor, string | number][]) {\n\t\t\tthis.fgColors.set(key, fgAnsi(value, mode));\n\t\t}\n\t\tthis.bgColors = new Map();\n\t\tfor (const [key, value] of Object.entries(bgColors) as [ThemeBg, string | number][]) {\n\t\t\tthis.bgColors.set(key, bgAnsi(value, mode));\n\t\t}\n\t}\n\n\tfg(color: ThemeColor, text: string): string {\n\t\tconst ansi = this.fgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme color: ${color}`);\n\t\treturn `${ansi}${text}\\x1b[39m`; // Reset only foreground color\n\t}\n\n\tbg(color: ThemeBg, text: string): string {\n\t\tconst ansi = this.bgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme background color: ${color}`);\n\t\treturn `${ansi}${text}\\x1b[49m`; // Reset only background color\n\t}\n\n\tbold(text: string): string {\n\t\treturn chalk.bold(text);\n\t}\n\n\titalic(text: string): string {\n\t\treturn chalk.italic(text);\n\t}\n\n\tunderline(text: string): string {\n\t\treturn chalk.underline(text);\n\t}\n\n\tgetFgAnsi(color: ThemeColor): string {\n\t\tconst ansi = this.fgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme color: ${color}`);\n\t\treturn ansi;\n\t}\n\n\tgetBgAnsi(color: ThemeBg): string {\n\t\tconst ansi = this.bgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme background color: ${color}`);\n\t\treturn ansi;\n\t}\n\n\tgetColorMode(): ColorMode {\n\t\treturn this.mode;\n\t}\n}\n\n// ============================================================================\n// Theme Loading\n// ============================================================================\n\nlet BUILTIN_THEMES: Record | undefined;\n\nfunction getBuiltinThemes(): Record {\n\tif (!BUILTIN_THEMES) {\n\t\tconst darkPath = path.join(__dirname, \"dark.json\");\n\t\tconst lightPath = path.join(__dirname, \"light.json\");\n\t\tBUILTIN_THEMES = {\n\t\t\tdark: JSON.parse(fs.readFileSync(darkPath, \"utf-8\")) as ThemeJson,\n\t\t\tlight: JSON.parse(fs.readFileSync(lightPath, \"utf-8\")) as ThemeJson,\n\t\t};\n\t}\n\treturn BUILTIN_THEMES;\n}\n\nfunction getThemesDir(): string {\n\treturn path.join(os.homedir(), \".pi\", \"agent\", \"themes\");\n}\n\nexport function getAvailableThemes(): string[] {\n\tconst themes = new Set(Object.keys(getBuiltinThemes()));\n\tconst themesDir = getThemesDir();\n\tif (fs.existsSync(themesDir)) {\n\t\tconst files = fs.readdirSync(themesDir);\n\t\tfor (const file of files) {\n\t\t\tif (file.endsWith(\".json\")) {\n\t\t\t\tthemes.add(file.slice(0, -5));\n\t\t\t}\n\t\t}\n\t}\n\treturn Array.from(themes).sort();\n}\n\nfunction loadThemeJson(name: string): ThemeJson {\n\tconst builtinThemes = getBuiltinThemes();\n\tif (name in builtinThemes) {\n\t\treturn builtinThemes[name];\n\t}\n\tconst themesDir = getThemesDir();\n\tconst themePath = path.join(themesDir, `${name}.json`);\n\tif (!fs.existsSync(themePath)) {\n\t\tthrow new Error(`Theme not found: ${name}`);\n\t}\n\tconst content = fs.readFileSync(themePath, \"utf-8\");\n\tlet json: unknown;\n\ttry {\n\t\tjson = JSON.parse(content);\n\t} catch (error) {\n\t\tthrow new Error(`Failed to parse theme ${name}: ${error}`);\n\t}\n\tif (!validateThemeJson.Check(json)) {\n\t\tconst errors = Array.from(validateThemeJson.Errors(json));\n\t\tconst errorMessages = errors.map((e) => ` - ${e.path}: ${e.message}`).join(\"\\n\");\n\t\tthrow new Error(`Invalid theme ${name}:\\n${errorMessages}`);\n\t}\n\treturn json as ThemeJson;\n}\n\nfunction createTheme(themeJson: ThemeJson, mode?: ColorMode): Theme {\n\tconst colorMode = mode ?? detectColorMode();\n\tconst resolvedColors = resolveThemeColors(themeJson.colors, themeJson.vars);\n\tconst fgColors: Record = {} as Record;\n\tconst bgColors: Record = {} as Record;\n\tconst bgColorKeys: Set = new Set([\"userMessageBg\", \"toolPendingBg\", \"toolSuccessBg\", \"toolErrorBg\"]);\n\tfor (const [key, value] of Object.entries(resolvedColors)) {\n\t\tif (bgColorKeys.has(key)) {\n\t\t\tbgColors[key as ThemeBg] = value;\n\t\t} else {\n\t\t\tfgColors[key as ThemeColor] = value;\n\t\t}\n\t}\n\treturn new Theme(fgColors, bgColors, colorMode);\n}\n\nfunction loadTheme(name: string, mode?: ColorMode): Theme {\n\tconst themeJson = loadThemeJson(name);\n\treturn createTheme(themeJson, mode);\n}\n\nfunction detectTerminalBackground(): \"dark\" | \"light\" {\n\tconst colorfgbg = process.env.COLORFGBG || \"\";\n\tif (colorfgbg) {\n\t\tconst parts = colorfgbg.split(\";\");\n\t\tif (parts.length >= 2) {\n\t\t\tconst bg = parseInt(parts[1], 10);\n\t\t\tif (!Number.isNaN(bg)) {\n\t\t\t\treturn bg < 8 ? \"dark\" : \"light\";\n\t\t\t}\n\t\t}\n\t}\n\treturn \"dark\";\n}\n\nfunction getDefaultTheme(): string {\n\treturn detectTerminalBackground();\n}\n\n// ============================================================================\n// Global Theme Instance\n// ============================================================================\n\nexport let theme: Theme;\n\nexport function initTheme(themeName?: string): void {\n\tconst name = themeName ?? getDefaultTheme();\n\ttheme = loadTheme(name);\n}\n\nexport function setTheme(name: string): void {\n\ttheme = loadTheme(name);\n}\n\n// ============================================================================\n// TUI Helpers\n// ============================================================================\n\nexport function getMarkdownTheme(): MarkdownTheme {\n\treturn {\n\t\theading: (text: string) => theme.fg(\"mdHeading\", text),\n\t\tlink: (text: string) => theme.fg(\"mdLink\", text),\n\t\tcode: (text: string) => theme.fg(\"mdCode\", text),\n\t\tcodeBlock: (text: string) => theme.fg(\"mdCodeBlock\", text),\n\t\tcodeBlockBorder: (text: string) => theme.fg(\"mdCodeBlockBorder\", text),\n\t\tquote: (text: string) => theme.fg(\"mdQuote\", text),\n\t\tquoteBorder: (text: string) => theme.fg(\"mdQuoteBorder\", text),\n\t\thr: (text: string) => theme.fg(\"mdHr\", text),\n\t\tlistBullet: (text: string) => theme.fg(\"mdListBullet\", text),\n\t};\n}\n\nexport function getSelectListTheme(): SelectListTheme {\n\treturn {\n\t\tselectedPrefix: (text: string) => theme.fg(\"accent\", text),\n\t\tselectedText: (text: string) => theme.fg(\"accent\", text),\n\t\tdescription: (text: string) => theme.fg(\"muted\", text),\n\t\tscrollInfo: (text: string) => theme.fg(\"muted\", text),\n\t\tnoMatch: (text: string) => theme.fg(\"muted\", text),\n\t};\n}\n\nexport function getEditorTheme(): EditorTheme {\n\treturn {\n\t\tborderColor: (text: string) => theme.fg(\"borderMuted\", text),\n\t\tselectList: getSelectListTheme(),\n\t};\n}\n"}],"isError":false,"timestamp":1763681634577}} +{"type":"message","timestamp":"2025-11-20T23:33:54.580Z","message":{"role":"toolResult","toolCallId":"toolu_01FnVNKzWWm2s2SFJmJttiWh","toolName":"read","content":[{"type":"text","text":"import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { EditorTheme, MarkdownTheme, SelectListTheme } from \"@mariozechner/pi-tui\";\nimport { type Static, Type } from \"typebox\";\nimport { TypeCompiler } from \"typebox/compiler\";\nimport chalk from \"chalk\";\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\n// ============================================================================\n// Types & Schema\n// ============================================================================\n\nconst ColorValueSchema = Type.Union([\n\tType.String(), // hex \"#ff0000\", var ref \"primary\", or empty \"\"\n\tType.Integer({ minimum: 0, maximum: 255 }), // 256-color index\n]);\n\ntype ColorValue = Static;\n\nconst ThemeJsonSchema = Type.Object({\n\t$schema: Type.Optional(Type.String()),\n\tname: Type.String(),\n\tvars: Type.Optional(Type.Record(Type.String(), ColorValueSchema)),\n\tcolors: Type.Object({\n\t\t// Core UI (10 colors)\n\t\taccent: ColorValueSchema,\n\t\tborder: ColorValueSchema,\n\t\tborderAccent: ColorValueSchema,\n\t\tborderMuted: ColorValueSchema,\n\t\tsuccess: ColorValueSchema,\n\t\terror: ColorValueSchema,\n\t\twarning: ColorValueSchema,\n\t\tmuted: ColorValueSchema,\n\t\tdim: ColorValueSchema,\n\t\ttext: ColorValueSchema,\n\t\t// Backgrounds & Content Text (6 colors)\n\t\tuserMessageBg: ColorValueSchema,\n\t\tuserMessageText: ColorValueSchema,\n\t\ttoolPendingBg: ColorValueSchema,\n\t\ttoolSuccessBg: ColorValueSchema,\n\t\ttoolErrorBg: ColorValueSchema,\n\t\ttoolText: ColorValueSchema,\n\t\t// Markdown (9 colors)\n\t\tmdHeading: ColorValueSchema,\n\t\tmdLink: ColorValueSchema,\n\t\tmdCode: ColorValueSchema,\n\t\tmdCodeBlock: ColorValueSchema,\n\t\tmdCodeBlockBorder: ColorValueSchema,\n\t\tmdQuote: ColorValueSchema,\n\t\tmdQuoteBorder: ColorValueSchema,\n\t\tmdHr: ColorValueSchema,\n\t\tmdListBullet: ColorValueSchema,\n\t\t// Tool Diffs (3 colors)\n\t\ttoolDiffAdded: ColorValueSchema,\n\t\ttoolDiffRemoved: ColorValueSchema,\n\t\ttoolDiffContext: ColorValueSchema,\n\t\t// Syntax Highlighting (9 colors)\n\t\tsyntaxComment: ColorValueSchema,\n\t\tsyntaxKeyword: ColorValueSchema,\n\t\tsyntaxFunction: ColorValueSchema,\n\t\tsyntaxVariable: ColorValueSchema,\n\t\tsyntaxString: ColorValueSchema,\n\t\tsyntaxNumber: ColorValueSchema,\n\t\tsyntaxType: ColorValueSchema,\n\t\tsyntaxOperator: ColorValueSchema,\n\t\tsyntaxPunctuation: ColorValueSchema,\n\t}),\n});\n\ntype ThemeJson = Static;\n\nconst validateThemeJson = TypeCompiler.Compile(ThemeJsonSchema);\n\nexport type ThemeColor =\n\t| \"accent\"\n\t| \"border\"\n\t| \"borderAccent\"\n\t| \"borderMuted\"\n\t| \"success\"\n\t| \"error\"\n\t| \"warning\"\n\t| \"muted\"\n\t| \"dim\"\n\t| \"text\"\n\t| \"userMessageText\"\n\t| \"toolText\"\n\t| \"mdHeading\"\n\t| \"mdLink\"\n\t| \"mdCode\"\n\t| \"mdCodeBlock\"\n\t| \"mdCodeBlockBorder\"\n\t| \"mdQuote\"\n\t| \"mdQuoteBorder\"\n\t| \"mdHr\"\n\t| \"mdListBullet\"\n\t| \"toolDiffAdded\"\n\t| \"toolDiffRemoved\"\n\t| \"toolDiffContext\"\n\t| \"syntaxComment\"\n\t| \"syntaxKeyword\"\n\t| \"syntaxFunction\"\n\t| \"syntaxVariable\"\n\t| \"syntaxString\"\n\t| \"syntaxNumber\"\n\t| \"syntaxType\"\n\t| \"syntaxOperator\"\n\t| \"syntaxPunctuation\";\n\nexport type ThemeBg = \"userMessageBg\" | \"toolPendingBg\" | \"toolSuccessBg\" | \"toolErrorBg\";\n\ntype ColorMode = \"truecolor\" | \"256color\";\n\n// ============================================================================\n// Color Utilities\n// ============================================================================\n\nfunction detectColorMode(): ColorMode {\n\tconst colorterm = process.env.COLORTERM;\n\tif (colorterm === \"truecolor\" || colorterm === \"24bit\") {\n\t\treturn \"truecolor\";\n\t}\n\tconst term = process.env.TERM || \"\";\n\tif (term.includes(\"256color\")) {\n\t\treturn \"256color\";\n\t}\n\treturn \"256color\";\n}\n\nfunction hexToRgb(hex: string): { r: number; g: number; b: number } {\n\tconst cleaned = hex.replace(\"#\", \"\");\n\tif (cleaned.length !== 6) {\n\t\tthrow new Error(`Invalid hex color: ${hex}`);\n\t}\n\tconst r = parseInt(cleaned.substring(0, 2), 16);\n\tconst g = parseInt(cleaned.substring(2, 4), 16);\n\tconst b = parseInt(cleaned.substring(4, 6), 16);\n\tif (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) {\n\t\tthrow new Error(`Invalid hex color: ${hex}`);\n\t}\n\treturn { r, g, b };\n}\n\nfunction rgbTo256(r: number, g: number, b: number): number {\n\tconst rIndex = Math.round((r / 255) * 5);\n\tconst gIndex = Math.round((g / 255) * 5);\n\tconst bIndex = Math.round((b / 255) * 5);\n\treturn 16 + 36 * rIndex + 6 * gIndex + bIndex;\n}\n\nfunction hexTo256(hex: string): number {\n\tconst { r, g, b } = hexToRgb(hex);\n\treturn rgbTo256(r, g, b);\n}\n\nfunction fgAnsi(color: string | number, mode: ColorMode): string {\n\tif (color === \"\") return \"\\x1b[39m\";\n\tif (typeof color === \"number\") return `\\x1b[38;5;${color}m`;\n\tif (color.startsWith(\"#\")) {\n\t\tif (mode === \"truecolor\") {\n\t\t\tconst { r, g, b } = hexToRgb(color);\n\t\t\treturn `\\x1b[38;2;${r};${g};${b}m`;\n\t\t} else {\n\t\t\tconst index = hexTo256(color);\n\t\t\treturn `\\x1b[38;5;${index}m`;\n\t\t}\n\t}\n\tthrow new Error(`Invalid color value: ${color}`);\n}\n\nfunction bgAnsi(color: string | number, mode: ColorMode): string {\n\tif (color === \"\") return \"\\x1b[49m\";\n\tif (typeof color === \"number\") return `\\x1b[48;5;${color}m`;\n\tif (color.startsWith(\"#\")) {\n\t\tif (mode === \"truecolor\") {\n\t\t\tconst { r, g, b } = hexToRgb(color);\n\t\t\treturn `\\x1b[48;2;${r};${g};${b}m`;\n\t\t} else {\n\t\t\tconst index = hexTo256(color);\n\t\t\treturn `\\x1b[48;5;${index}m`;\n\t\t}\n\t}\n\tthrow new Error(`Invalid color value: ${color}`);\n}\n\nfunction resolveVarRefs(\n\tvalue: ColorValue,\n\tvars: Record,\n\tvisited = new Set(),\n): string | number {\n\tif (typeof value === \"number\" || value === \"\" || value.startsWith(\"#\")) {\n\t\treturn value;\n\t}\n\tif (visited.has(value)) {\n\t\tthrow new Error(`Circular variable reference detected: ${value}`);\n\t}\n\tif (!(value in vars)) {\n\t\tthrow new Error(`Variable reference not found: ${value}`);\n\t}\n\tvisited.add(value);\n\treturn resolveVarRefs(vars[value], vars, visited);\n}\n\nfunction resolveThemeColors>(\n\tcolors: T,\n\tvars: Record = {},\n): Record {\n\tconst resolved: Record = {};\n\tfor (const [key, value] of Object.entries(colors)) {\n\t\tresolved[key] = resolveVarRefs(value, vars);\n\t}\n\treturn resolved as Record;\n}\n\n// ============================================================================\n// Theme Class\n// ============================================================================\n\nexport class Theme {\n\tprivate fgColors: Map;\n\tprivate bgColors: Map;\n\tprivate mode: ColorMode;\n\n\tconstructor(\n\t\tfgColors: Record,\n\t\tbgColors: Record,\n\t\tmode: ColorMode,\n\t) {\n\t\tthis.mode = mode;\n\t\tthis.fgColors = new Map();\n\t\tfor (const [key, value] of Object.entries(fgColors) as [ThemeColor, string | number][]) {\n\t\t\tthis.fgColors.set(key, fgAnsi(value, mode));\n\t\t}\n\t\tthis.bgColors = new Map();\n\t\tfor (const [key, value] of Object.entries(bgColors) as [ThemeBg, string | number][]) {\n\t\t\tthis.bgColors.set(key, bgAnsi(value, mode));\n\t\t}\n\t}\n\n\tfg(color: ThemeColor, text: string): string {\n\t\tconst ansi = this.fgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme color: ${color}`);\n\t\treturn `${ansi}${text}\\x1b[39m`; // Reset only foreground color\n\t}\n\n\tbg(color: ThemeBg, text: string): string {\n\t\tconst ansi = this.bgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme background color: ${color}`);\n\t\treturn `${ansi}${text}\\x1b[49m`; // Reset only background color\n\t}\n\n\tbold(text: string): string {\n\t\treturn chalk.bold(text);\n\t}\n\n\titalic(text: string): string {\n\t\treturn chalk.italic(text);\n\t}\n\n\tunderline(text: string): string {\n\t\treturn chalk.underline(text);\n\t}\n\n\tgetFgAnsi(color: ThemeColor): string {\n\t\tconst ansi = this.fgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme color: ${color}`);\n\t\treturn ansi;\n\t}\n\n\tgetBgAnsi(color: ThemeBg): string {\n\t\tconst ansi = this.bgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme background color: ${color}`);\n\t\treturn ansi;\n\t}\n\n\tgetColorMode(): ColorMode {\n\t\treturn this.mode;\n\t}\n}\n\n// ============================================================================\n// Theme Loading\n// ============================================================================\n\nlet BUILTIN_THEMES: Record | undefined;\n\nfunction getBuiltinThemes(): Record {\n\tif (!BUILTIN_THEMES) {\n\t\tconst darkPath = path.join(__dirname, \"dark.json\");\n\t\tconst lightPath = path.join(__dirname, \"light.json\");\n\t\tBUILTIN_THEMES = {\n\t\t\tdark: JSON.parse(fs.readFileSync(darkPath, \"utf-8\")) as ThemeJson,\n\t\t\tlight: JSON.parse(fs.readFileSync(lightPath, \"utf-8\")) as ThemeJson,\n\t\t};\n\t}\n\treturn BUILTIN_THEMES;\n}\n\nfunction getThemesDir(): string {\n\treturn path.join(os.homedir(), \".pi\", \"agent\", \"themes\");\n}\n\nexport function getAvailableThemes(): string[] {\n\tconst themes = new Set(Object.keys(getBuiltinThemes()));\n\tconst themesDir = getThemesDir();\n\tif (fs.existsSync(themesDir)) {\n\t\tconst files = fs.readdirSync(themesDir);\n\t\tfor (const file of files) {\n\t\t\tif (file.endsWith(\".json\")) {\n\t\t\t\tthemes.add(file.slice(0, -5));\n\t\t\t}\n\t\t}\n\t}\n\treturn Array.from(themes).sort();\n}\n\nfunction loadThemeJson(name: string): ThemeJson {\n\tconst builtinThemes = getBuiltinThemes();\n\tif (name in builtinThemes) {\n\t\treturn builtinThemes[name];\n\t}\n\tconst themesDir = getThemesDir();\n\tconst themePath = path.join(themesDir, `${name}.json`);\n\tif (!fs.existsSync(themePath)) {\n\t\tthrow new Error(`Theme not found: ${name}`);\n\t}\n\tconst content = fs.readFileSync(themePath, \"utf-8\");\n\tlet json: unknown;\n\ttry {\n\t\tjson = JSON.parse(content);\n\t} catch (error) {\n\t\tthrow new Error(`Failed to parse theme ${name}: ${error}`);\n\t}\n\tif (!validateThemeJson.Check(json)) {\n\t\tconst errors = Array.from(validateThemeJson.Errors(json));\n\t\tconst errorMessages = errors.map((e) => ` - ${e.path}: ${e.message}`).join(\"\\n\");\n\t\tthrow new Error(`Invalid theme ${name}:\\n${errorMessages}`);\n\t}\n\treturn json as ThemeJson;\n}\n\nfunction createTheme(themeJson: ThemeJson, mode?: ColorMode): Theme {\n\tconst colorMode = mode ?? detectColorMode();\n\tconst resolvedColors = resolveThemeColors(themeJson.colors, themeJson.vars);\n\tconst fgColors: Record = {} as Record;\n\tconst bgColors: Record = {} as Record;\n\tconst bgColorKeys: Set = new Set([\"userMessageBg\", \"toolPendingBg\", \"toolSuccessBg\", \"toolErrorBg\"]);\n\tfor (const [key, value] of Object.entries(resolvedColors)) {\n\t\tif (bgColorKeys.has(key)) {\n\t\t\tbgColors[key as ThemeBg] = value;\n\t\t} else {\n\t\t\tfgColors[key as ThemeColor] = value;\n\t\t}\n\t}\n\treturn new Theme(fgColors, bgColors, colorMode);\n}\n\nfunction loadTheme(name: string, mode?: ColorMode): Theme {\n\tconst themeJson = loadThemeJson(name);\n\treturn createTheme(themeJson, mode);\n}\n\nfunction detectTerminalBackground(): \"dark\" | \"light\" {\n\tconst colorfgbg = process.env.COLORFGBG || \"\";\n\tif (colorfgbg) {\n\t\tconst parts = colorfgbg.split(\";\");\n\t\tif (parts.length >= 2) {\n\t\t\tconst bg = parseInt(parts[1], 10);\n\t\t\tif (!Number.isNaN(bg)) {\n\t\t\t\treturn bg < 8 ? \"dark\" : \"light\";\n\t\t\t}\n\t\t}\n\t}\n\treturn \"dark\";\n}\n\nfunction getDefaultTheme(): string {\n\treturn detectTerminalBackground();\n}\n\n// ============================================================================\n// Global Theme Instance\n// ============================================================================\n\nexport let theme: Theme;\n\nexport function initTheme(themeName?: string): void {\n\tconst name = themeName ?? getDefaultTheme();\n\ttheme = loadTheme(name);\n}\n\nexport function setTheme(name: string): void {\n\ttheme = loadTheme(name);\n}\n\n// ============================================================================\n// TUI Helpers\n// ============================================================================\n\nexport function getMarkdownTheme(): MarkdownTheme {\n\treturn {\n\t\theading: (text: string) => theme.fg(\"mdHeading\", text),\n\t\tlink: (text: string) => theme.fg(\"mdLink\", text),\n\t\tcode: (text: string) => theme.fg(\"mdCode\", text),\n\t\tcodeBlock: (text: string) => theme.fg(\"mdCodeBlock\", text),\n\t\tcodeBlockBorder: (text: string) => theme.fg(\"mdCodeBlockBorder\", text),\n\t\tquote: (text: string) => theme.fg(\"mdQuote\", text),\n\t\tquoteBorder: (text: string) => theme.fg(\"mdQuoteBorder\", text),\n\t\thr: (text: string) => theme.fg(\"mdHr\", text),\n\t\tlistBullet: (text: string) => theme.fg(\"mdListBullet\", text),\n\t};\n}\n\nexport function getSelectListTheme(): SelectListTheme {\n\treturn {\n\t\tselectedPrefix: (text: string) => theme.fg(\"accent\", text),\n\t\tselectedText: (text: string) => theme.fg(\"accent\", text),\n\t\tdescription: (text: string) => theme.fg(\"muted\", text),\n\t\tscrollInfo: (text: string) => theme.fg(\"muted\", text),\n\t\tnoMatch: (text: string) => theme.fg(\"muted\", text),\n\t};\n}\n\nexport function getEditorTheme(): EditorTheme {\n\treturn {\n\t\tborderColor: (text: string) => theme.fg(\"borderMuted\", text),\n\t\tselectList: getSelectListTheme(),\n\t};\n}\n"}],"isError":false,"timestamp":1763681634577}} {"type":"message","timestamp":"2025-11-20T23:33:54.592Z","message":{"role":"toolResult","toolCallId":"toolu_016aKHTkjrTJcMds3wsEou2R","toolName":"bash","content":[{"type":"text","text":"packages/coding-agent/src/tui/thinking-selector.ts\npackages/coding-agent/src/tui/theme-selector.ts\npackages/coding-agent/src/tui/oauth-selector.ts\npackages/coding-agent/src/tui/user-message-selector.ts\npackages/coding-agent/src/tui/queue-mode-selector.ts\npackages/coding-agent/src/tui/model-selector.ts\npackages/coding-agent/src/tui/session-selector.ts\n"}],"isError":false,"timestamp":1763681634589}} {"type":"message","timestamp":"2025-11-20T23:33:59.553Z","message":{"role":"assistant","content":[{"type":"text","text":"Now let me read a few of the selector files to understand the pattern:"},{"type":"toolCall","id":"toolu_01G6wBLUY7g5eyk4TJEcTUiT","name":"read","arguments":{"path":"packages/coding-agent/src/tui/oauth-selector.ts"}},{"type":"toolCall","id":"toolu_012U6SQ4AGg5JrNK6s715ATw","name":"read","arguments":{"path":"packages/coding-agent/src/tui/theme-selector.ts"}},{"type":"toolCall","id":"toolu_01TSY14a4g85DGSpjo9ao8Eu","name":"read","arguments":{"path":"packages/coding-agent/src/tui/model-selector.ts"}},{"type":"toolCall","id":"toolu_01Fo2ghr79kbj5bRxyVyFoQQ","name":"read","arguments":{"path":"packages/coding-agent/src/tui/user-message-selector.ts"}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-4-5","usage":{"input":7,"output":231,"cacheRead":1684,"cacheWrite":9518,"cost":{"input":0.000021000000000000002,"output":0.003465,"cacheRead":0.0005052,"cacheWrite":0.0356925,"total":0.0396837}},"stopReason":"toolUse","timestamp":1763681634589}} {"type":"message","timestamp":"2025-11-20T23:33:59.555Z","message":{"role":"toolResult","toolCallId":"toolu_01G6wBLUY7g5eyk4TJEcTUiT","toolName":"read","content":[{"type":"text","text":"import { Container, Spacer, Text } from \"@mariozechner/pi-tui\";\nimport { getOAuthProviders, type OAuthProviderInfo } from \"../oauth/index.js\";\nimport { theme } from \"../theme/theme.js\";\nimport { DynamicBorder } from \"./dynamic-border.js\";\n\n/**\n * Component that renders an OAuth provider selector\n */\nexport class OAuthSelectorComponent extends Container {\n\tprivate listContainer: Container;\n\tprivate allProviders: OAuthProviderInfo[] = [];\n\tprivate selectedIndex: number = 0;\n\tprivate mode: \"login\" | \"logout\";\n\tprivate onSelectCallback: (providerId: string) => void;\n\tprivate onCancelCallback: () => void;\n\n\tconstructor(mode: \"login\" | \"logout\", onSelect: (providerId: string) => void, onCancel: () => void) {\n\t\tsuper();\n\n\t\tthis.mode = mode;\n\t\tthis.onSelectCallback = onSelect;\n\t\tthis.onCancelCallback = onCancel;\n\n\t\t// Load all OAuth providers\n\t\tthis.loadProviders();\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add title\n\t\tconst title = mode === \"login\" ? \"Select provider to login:\" : \"Select provider to logout:\";\n\t\tthis.addChild(new Text(theme.bold(title), 0, 0));\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create list container\n\t\tthis.listContainer = new Container();\n\t\tthis.addChild(this.listContainer);\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Initial render\n\t\tthis.updateList();\n\t}\n\n\tprivate loadProviders(): void {\n\t\tthis.allProviders = getOAuthProviders();\n\t\tthis.allProviders = this.allProviders.filter((p) => p.available);\n\t}\n\n\tprivate updateList(): void {\n\t\tthis.listContainer.clear();\n\n\t\tfor (let i = 0; i < this.allProviders.length; i++) {\n\t\t\tconst provider = this.allProviders[i];\n\t\t\tif (!provider) continue;\n\n\t\t\tconst isSelected = i === this.selectedIndex;\n\t\t\tconst isAvailable = provider.available;\n\n\t\t\tlet line = \"\";\n\t\t\tif (isSelected) {\n\t\t\t\tconst prefix = theme.fg(\"accent\", \"→ \");\n\t\t\t\tconst text = isAvailable ? theme.fg(\"accent\", provider.name) : theme.fg(\"dim\", provider.name);\n\t\t\t\tline = prefix + text;\n\t\t\t} else {\n\t\t\t\tconst text = isAvailable ? ` ${provider.name}` : theme.fg(\"dim\", ` ${provider.name}`);\n\t\t\t\tline = text;\n\t\t\t}\n\n\t\t\tthis.listContainer.addChild(new Text(line, 0, 0));\n\t\t}\n\n\t\t// Show \"no providers\" if empty\n\t\tif (this.allProviders.length === 0) {\n\t\t\tconst message =\n\t\t\t\tthis.mode === \"login\" ? \"No OAuth providers available\" : \"No OAuth providers logged in. Use /login first.\";\n\t\t\tthis.listContainer.addChild(new Text(theme.fg(\"muted\", ` ${message}`), 0, 0));\n\t\t}\n\t}\n\n\thandleInput(keyData: string): void {\n\t\t// Up arrow\n\t\tif (keyData === \"\\x1b[A\") {\n\t\t\tthis.selectedIndex = Math.max(0, this.selectedIndex - 1);\n\t\t\tthis.updateList();\n\t\t}\n\t\t// Down arrow\n\t\telse if (keyData === \"\\x1b[B\") {\n\t\t\tthis.selectedIndex = Math.min(this.allProviders.length - 1, this.selectedIndex + 1);\n\t\t\tthis.updateList();\n\t\t}\n\t\t// Enter\n\t\telse if (keyData === \"\\r\") {\n\t\t\tconst selectedProvider = this.allProviders[this.selectedIndex];\n\t\t\tif (selectedProvider?.available) {\n\t\t\t\tthis.onSelectCallback(selectedProvider.id);\n\t\t\t}\n\t\t}\n\t\t// Escape\n\t\telse if (keyData === \"\\x1b\") {\n\t\t\tthis.onCancelCallback();\n\t\t}\n\t}\n}\n"}],"isError":false,"timestamp":1763681639554}} diff --git a/packages/mom/CHANGELOG.md b/packages/mom/CHANGELOG.md index ecb1ace2..5242e384 100644 --- a/packages/mom/CHANGELOG.md +++ b/packages/mom/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +### Breaking Changes + +- Migrated Mom's TypeBox-based tool examples and runtime dependency from `@sinclair/typebox` 0.34.x to `typebox` 1.x. Install and import from `typebox` instead of `@sinclair/typebox` when authoring Mom tools and integrations ([#3112](https://github.com/badlogic/pi-mono/issues/3112)) + ## [0.68.1] - 2026-04-22 ## [0.68.0] - 2026-04-20 diff --git a/packages/mom/docs/new.md b/packages/mom/docs/new.md index c8e51cb4..74957822 100644 --- a/packages/mom/docs/new.md +++ b/packages/mom/docs/new.md @@ -646,7 +646,7 @@ Mom runs bash commands inside a sandbox (Docker container), but sometimes you ne ```typescript // data/tools/gmail/index.ts import type { MomCustomTool, ToolAPI } from "@mariozechner/pi-mom"; -import { Type } from "@sinclair/typebox"; +import { Type } from "typebox"; import { StringEnum } from "@mariozechner/pi-ai"; const tool: MomCustomTool = { @@ -691,7 +691,7 @@ export default tool; ### MomCustomTool Type ```typescript -import type { TSchema, Static } from "@sinclair/typebox"; +import type { TSchema, Static } from "typebox"; export interface MomToolResult { content: Array<{ type: "text"; text: string } | { type: "image"; data: string; mimeType: string }>; @@ -798,7 +798,7 @@ async function loadCustomTools(dataDir: string): Promise { Mom has a single `invoke_tool` tool that dispatches to custom tools: ```typescript -import { Type } from "@sinclair/typebox"; +import { Type } from "typebox"; function createInvokeToolTool(loadedTools: LoadedTool[]): AgentTool { const toolMap = new Map(loadedTools.map(t => [t.tool.name, t.tool])); @@ -889,7 +889,7 @@ function schemaToSimpleJson(schema: TSchema): object { ```typescript // data/tools/gmail/index.ts import type { MomCustomTool, ToolAPI } from "@mariozechner/pi-mom"; -import { Type } from "@sinclair/typebox"; +import { Type } from "typebox"; import { StringEnum } from "@mariozechner/pi-ai"; import Imap from "imap"; import nodemailer from "nodemailer"; diff --git a/packages/tui/src/terminal.ts b/packages/tui/src/terminal.ts index e7a64dc8..8cedb73a 100644 --- a/packages/tui/src/terminal.ts +++ b/packages/tui/src/terminal.ts @@ -363,8 +363,8 @@ export class ProcessTerminal implements Terminal { setProgress(active: boolean): void { if (active) { - // OSC 9;4;1;0 - indeterminate progress - process.stdout.write("\x1b]9;4;1;0\x07"); + // OSC 9;4;3 - indeterminate progress + process.stdout.write("\x1b]9;4;3\x07"); } else { // OSC 9;4;0 - clear progress process.stdout.write("\x1b]9;4;0;\x07"); diff --git a/packages/web-ui/CHANGELOG.md b/packages/web-ui/CHANGELOG.md index c8d1b31a..74422f23 100644 --- a/packages/web-ui/CHANGELOG.md +++ b/packages/web-ui/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +### Breaking Changes + +- Migrated the web UI's TypeBox-based tool definitions and runtime dependency from `@sinclair/typebox` 0.34.x to `typebox` 1.x. Install and import from `typebox` instead of `@sinclair/typebox` when embedding or extending `@mariozechner/pi-web-ui` with shared TypeBox schemas ([#3112](https://github.com/badlogic/pi-mono/issues/3112)) + ### Fixed - Render SVG artifact previews through a blob-backed image instead of injecting untrusted SVG markup into the page DOM ([#3552](https://github.com/badlogic/pi-mono/issues/3552))