@ashx-j/lunr 0.2.4 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"ashxj-thinking.d.ts","sourceRoot":"","sources":["../../src/builtin-extensions/ashxj-thinking.ts"],"names":[],"mappings":"AAIA;;;;;;;;;;;;;;;;;GAiBG;AAUH,qEAAqE;AAErE,KAAK,aAAa,GAAG,KAAK,GAAG,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,CAAC;AAErF,iEAAiE;AACjE,UAAU,gBAAgB;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,wEAAsE;AACtE,UAAU,SAAS;IAClB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC;CACjD;AAED,8EAA4E;AAC5E,UAAU,oBAAoB;IAC7B,IAAI,EAAE,KAAK,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,CAAC;IACvC,KAAK,EAAE,SAAS,GAAG,SAAS,CAAC;IAC7B,EAAE,EAAE;QACH,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,GAAG,IAAI,CAAC;QACnE,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,IAAI,CAAC,EAAE;YAAE,MAAM,CAAC,EAAE,WAAW,CAAC;YAAC,OAAO,CAAC,EAAE,MAAM,CAAA;SAAE,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;KACzH,CAAC;CACF;AAED,qFAAmF;AACnF,UAAU,2BAA4B,SAAQ,oBAAoB;IACjE,gBAAgB,IAAI,aAAa,CAAC;IAClC;;;kFAG4E;IAC5E,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED,oEAAkE;AAClE,UAAU,YAAY;IACrB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE;QACtC,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,sBAAsB,CAAC,CAAC,MAAM,EAAE,MAAM,GAAG,gBAAgB,EAAE,GAAG,IAAI,GAAG,OAAO,CAAC,gBAAgB,EAAE,GAAG,IAAI,CAAC,CAAC;QACxG,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,2BAA2B,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;KAC9E,GAAG,IAAI,CAAC;IACT,gBAAgB,IAAI,aAAa,CAAC;IAClC,gBAAgB,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI,CAAC;CAC7C;AAsLD,MAAM,CAAC,OAAO,WAAW,EAAE,EAAE,YAAY,GAAG,IAAI,CA2H/C","sourcesContent":["// @ts-nocheck\n// Vendored from https://github.com/ashx-j/ashxj-thinking @ 0330a34\n// (\"Remove custom footer — keep only /thinking command\"), single-file ashxj\n// convention. lunR patches are marked `// lunr:`.\n/**\n * batxj-thinking extension\n *\n * `/thinking [level]` slash command to view or set the reasoning level,\n * plus `/thinking show|hide|toggle` for thinking-block visibility.\n * `/effort` and `/reasoning` are full-parity aliases.\n *\n * Loaded by pi via jiti — no build step, plain TypeScript.\n *\n * NOTE on type imports: this file deliberately declares structural types\n * rather than importing from `@ashx-j/lunr` (or\n * `@ashx-j/lunr-tui`). pi-coding-agent's `index.d.ts` re-exports\n * from internal `.d.ts` files that contain subpath imports like\n * `@ashx-j/lunr-ai/compat`, which fail to resolve under the default\n * `tsc` settings when a file argument is passed (the spec'd\n * `tsc --noEmit index.ts` script). Declaring the types we use inline\n * keeps the typecheck self-contained.\n */\n\nimport { readFileSync, writeFileSync, existsSync, renameSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\n// ---------------------------------------------------------------------------\n// Minimal structural types (see file header for why these are inline)\n// ---------------------------------------------------------------------------\n\n/** Mirrored from `@ashx-j/lunr-agent` `ThinkingLevel`. */\n// lunr: added \"max\" — lunR's ThinkingLevel union includes it.\ntype ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/** Mirrored from `@ashx-j/lunr-tui` `AutocompleteItem`. */\ninterface AutocompleteItem {\n\tvalue: string;\n\tlabel: string;\n\tdescription?: string;\n}\n\n/** A trimmed view of a `Model` — only the fields the picker reads. */\ninterface ModelLike {\n\tid?: string;\n\treasoning?: boolean;\n\tthinkingLevelMap?: Record<string, string | null>;\n}\n\n/** A trimmed view of `ExtensionContext` — only the methods/props we use. */\ninterface ExtensionContextLike {\n\tmode: \"tui\" | \"rpc\" | \"json\" | \"print\";\n\tmodel: ModelLike | undefined;\n\tui: {\n\t\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n\t\tselect(title: string, options: string[], opts?: { signal?: AbortSignal; timeout?: number }): Promise<string | undefined>;\n\t};\n}\n\n/** A trimmed view of `ExtensionCommandContext` — only the methods/props we use. */\ninterface ExtensionCommandContextLike extends ExtensionContextLike {\n\tgetThinkingLevel(): ThinkingLevel;\n\t/** Reload extensions, skills, prompts, and themes. Re-reads settings.json\n\t * from disk (session.reload() → settingsManager.reload()), so persisted\n\t * runtime settings like `hideThinkingBlock` are live-applied. The captured\n\t * `ctx`/`pi` are stale after this resolves — do not use them afterward. */\n\treload(): Promise<void>;\n}\n\n/** A trimmed view of `ExtensionAPI` — only the methods we use. */\ninterface ExtensionAPI {\n\tregisterCommand(name: string, options: {\n\t\tdescription?: string;\n\t\tgetArgumentCompletions?(prefix: string): AutocompleteItem[] | null | Promise<AutocompleteItem[] | null>;\n\t\thandler(args: string, ctx: ExtensionCommandContextLike): Promise<void> | void;\n\t}): void;\n\tgetThinkingLevel(): ThinkingLevel;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n}\n\n// ---------------------------------------------------------------------------\n// Thinking level config\n// ---------------------------------------------------------------------------\n\n/** All known levels, in display order. */\n// lunr: \"max\" appended (lunR supports it; filtered per-model below when unsupported).\nconst ALL_LEVELS_7: readonly ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n/** Default 5 — used when the active model is undefined (we don't know whether `xhigh`/`max` are supported). */\nconst ALL_LEVELS_5: readonly ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\"];\n\n/** Per-level descriptions. Mirrored from `THINKING_DESCRIPTIONS` in settings-selector.ts. */\nconst THINKING_DESCRIPTIONS: Record<ThinkingLevel, string> = {\n\toff: \"No reasoning\",\n\tminimal: \"Very brief reasoning\",\n\tlow: \"Light reasoning\",\n\tmedium: \"Moderate reasoning\",\n\thigh: \"Deep reasoning\",\n\txhigh: \"Extra-high reasoning\",\n\t// lunr: added — mirrors settings-selector.ts.\n\tmax: \"Maximum reasoning\",\n};\n\n/** Returns the levels valid for the given model, in display order. */\nfunction availableLevelsFor(model: ModelLike | undefined): readonly ThinkingLevel[] {\n\tif (!model) return ALL_LEVELS_5;\n\tif (model.reasoning === false) return [\"off\" as const];\n\t// Filter out levels the model marks as unsupported (null entry).\n\treturn ALL_LEVELS_7.filter((lvl) => {\n\t\tconst m = model.thinkingLevelMap;\n\t\tif (m && Object.prototype.hasOwnProperty.call(m, lvl) && (m as Record<string, string | null>)[lvl] === null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t});\n}\n\n/** Builds the inline `<padded level> — <description>` label for a level. */\nfunction formatLevelLabel(level: ThinkingLevel): string {\n\treturn `${level.padEnd(8)} \\u2014 ${THINKING_DESCRIPTIONS[level]}`;\n}\n\n// ---------------------------------------------------------------------------\n// Persisted thinking-block visibility (hideThinkingBlock)\n//\n// pi has no public extension API to toggle thinking-block visibility live.\n// The live in-session toggle is `app.thinking.toggle` (default Ctrl+T) wired to\n// `toggleThinkingBlockVisibility()` in interactive-mode.js, which calls\n// `SettingsManager.setHideThinkingBlock()` + rebuilds the chat. That method is\n// not exposed on ExtensionContext / ExtensionCommandContext / ExtensionAPI.\n//\n// What extensions CAN do is persist the `hideThinkingBlock` boolean to the\n// global agent settings file (`~/.lunr/agent/settings.json`); the\n// `SettingsManager` reads it on startup. And because `ctx.reload()` drives\n// `session.reload()` → `settingsManager.reload()` (re-reads disk) →\n// `restoreChatBeforeSessionStart()` copies the new value into\n// `this.hideThinkingBlock` and calls `rebuildChatFromMessages()` (which\n// reconstructs every AssistantMessageComponent with the new hide flag), the\n// persisted value IS live-applied within the session by `await ctx.reload()`\n// (verified against pi 0.80.3). In non-TUI modes `ctx.reload()` is a no-op,\n// so the setting simply applies on next start.\n//\n// The instant keybinding path (Ctrl+T) still works and is the lowest-latency\n// toggle; the command is the discoverable, persistable, completions-friendly\n// equivalent.\n// ---------------------------------------------------------------------------\n\n/** Returns the path to lunR's global agent settings file.\n * lunr: lunR's agent dir is `~/.lunr/agent` (upstream hardcoded `~/.pi/agent`).\n * Honors the `PI_CODING_AGENT_DIR` env override like core config.ts does;\n * a custom agent dir is not exposed to extensions, so this is the only\n * location we can write to be picked up by\n * `SettingsManager.tryLoadFromStorage(\"global\")`. */\nfunction agentSettingsPath(): string {\n\tconst envDir = process.env.PI_CODING_AGENT_DIR;\n\tif (envDir) {\n\t\t// Match core normalizePath(): expand a leading ~ (~/ and, on win32, ~\\).\n\t\tconst home = homedir();\n\t\tconst expanded =\n\t\t\tenvDir === \"~\"\n\t\t\t\t? home\n\t\t\t\t: envDir.startsWith(\"~/\") || (process.platform === \"win32\" && envDir.startsWith(\"~\\\\\"))\n\t\t\t\t\t? join(home, envDir.slice(2))\n\t\t\t\t\t: envDir;\n\t\treturn join(expanded, \"settings.json\");\n\t}\n\treturn join(homedir(), \".lunr\", \"agent\", \"settings.json\");\n}\n\n// ---------------------------------------------------------------------------\n// lunR customize bridge for persisted thinking-block visibility.\n// When the bridge is present (TUI / gateway sessions), reads/writes go through\n// SettingsManager (lockfile + merge). Falls back to direct file I/O when the\n// extension loads in a context without the bridge (e.g. upstream pi).\n// ---------------------------------------------------------------------------\ninterface CustomizeBridge {\n\tgetHideThinkingBlock(): boolean;\n\tsetHideThinkingBlock(hide: boolean): void;\n}\n\nfunction getCustomizeBridge(): CustomizeBridge | undefined {\n\treturn (globalThis as Record<symbol, unknown>)[Symbol.for(\"@lunr/customize\")] as CustomizeBridge | undefined;\n}\n\n/** Returns the persisted `hideThinkingBlock` value (default false, matching\n * `getHideThinkingBlock()` which returns `this.settings.hideThinkingBlock ?? false`).\n * Never throws — on any error (missing file, bad JSON) returns false. */\nfunction readHideThinkingBlock(): boolean {\n\tconst bridge = getCustomizeBridge();\n\tif (bridge) return bridge.getHideThinkingBlock();\n\ttry {\n\t\tconst p = agentSettingsPath();\n\t\tif (!existsSync(p)) return false;\n\t\tconst cfg = JSON.parse(readFileSync(p, \"utf8\")) as { hideThinkingBlock?: boolean };\n\t\treturn cfg.hideThinkingBlock === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Persist `hideThinkingBlock` to the global agent settings file (safe merge).\n *\n * - Preserves all other keys (merge, never overwrite the whole file).\n * - Matches pi's 2-space indentation + trailing newline.\n * - On invalid JSON in the existing file, backs it up to `settings.json.bak`\n * before writing a fresh file, so a corrupted file is never written back.\n * - Never throws; on any error `ok` is false and the caller notifies the user.\n *\n * `createdFresh` is true when the file didn't exist (or was corrupt and backed\n * up) before this write — the handler uses it to warn that a global settings\n * file was created here.\n */\nfunction writeHideThinkingBlock(hide: boolean): {\n\tok: boolean;\n\tcreatedFresh: boolean;\n} {\n\tconst bridge = getCustomizeBridge();\n\tif (bridge) {\n\t\ttry {\n\t\t\tbridge.setHideThinkingBlock(hide);\n\t\t\treturn { ok: true, createdFresh: false };\n\t\t} catch {\n\t\t\treturn { ok: false, createdFresh: false };\n\t\t}\n\t}\n\ttry {\n\t\tconst p = agentSettingsPath();\n\t\tlet cfg: Record<string, unknown> = {};\n\t\tlet createdFresh = false;\n\t\tif (existsSync(p)) {\n\t\t\ttry {\n\t\t\t\tcfg = JSON.parse(readFileSync(p, \"utf8\")) as Record<string, unknown>;\n\t\t\t} catch {\n\t\t\t\t// Existing file is corrupt — back it up, then start fresh.\n\t\t\t\ttry {\n\t\t\t\t\trenameSync(p, `${p}.bak`);\n\t\t\t\t} catch {\n\t\t\t\t\t// If backup fails, still proceed to overwrite (best effort).\n\t\t\t\t}\n\t\t\t\tcfg = {};\n\t\t\t\tcreatedFresh = true;\n\t\t\t}\n\t\t} else {\n\t\t\tcreatedFresh = true;\n\t\t}\n\t\tcfg.hideThinkingBlock = hide;\n\t\twriteFileSync(p, JSON.stringify(cfg, null, 2) + \"\\n\", \"utf8\");\n\t\treturn { ok: true, createdFresh };\n\t} catch {\n\t\treturn { ok: false, createdFresh: false };\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Extension entry point\n// ---------------------------------------------------------------------------\n\nconst THINKING_COMMAND_DESCRIPTION =\n\t\"View or set the reasoning level for the current model, or toggle thinking-block visibility with show/hide/toggle\";\n\nexport default function (pi: ExtensionAPI): void {\n\tconst thinkingSpec = {\n\t\tdescription: THINKING_COMMAND_DESCRIPTION,\n\t\tgetArgumentCompletions(prefix: string): AutocompleteItem[] {\n\t\t\tconst lower = prefix.toLowerCase();\n\t\t\t// Visibility sub-options first, filtered by prefix, alongside the levels.\n\t\t\tconst visibility: AutocompleteItem[] = [\n\t\t\t\t{ value: \"show\", label: \"show\", description: \"Show thinking blocks (persisted to settings.json)\" },\n\t\t\t\t{ value: \"hide\", label: \"hide\", description: \"Hide thinking blocks (persisted to settings.json)\" },\n\t\t\t\t{ value: \"toggle\", label: \"toggle\", description: \"Toggle thinking blocks (persisted to settings.json)\" },\n\t\t\t];\n\t\t\tconst levels = availableLevelsFor(currentModel(pi));\n\t\t\tconst levelItems = levels\n\t\t\t\t.filter((lvl) => lvl.startsWith(lower))\n\t\t\t\t.map((lvl) => ({ value: lvl, label: lvl, description: THINKING_DESCRIPTIONS[lvl] }));\n\t\t\treturn [\n\t\t\t\t...visibility.filter((v) => v.value.startsWith(lower)),\n\t\t\t\t...levelItems,\n\t\t\t];\n\t\t},\n\t\thandler: async (args: string, ctx: ExtensionCommandContextLike) => {\n\t\t\tconst trimmed = args.trim();\n\t\t\tconst lower = trimmed.toLowerCase();\n\n\t\t\t// ---- Visibility sub-options: /thinking show | hide | toggle ----\n\t\t\t// Caught first so `hide`/`show`/`toggle` are never parsed as levels.\n\t\t\t// Works in every mode: only uses ctx.ui.notify + file I/O + ctx.reload().\n\t\t\tif (lower === \"show\" || lower === \"hide\" || lower === \"toggle\") {\n\t\t\t\tconst current = readHideThinkingBlock();\n\t\t\t\tconst next = lower === \"toggle\" ? !current : lower === \"hide\";\n\t\t\t\tif (next === current) {\n\t\t\t\t\tctx.ui.notify(`Thinking blocks already ${current ? \"hidden\" : \"shown\"}.`, \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst result = writeHideThinkingBlock(next);\n\t\t\t\tif (!result.ok) {\n\t\t\t\t\t// lunr: settings path is lunR's (see agentSettingsPath).\n\t\t\t\t\tctx.ui.notify(`Failed to update ${agentSettingsPath()}`, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// The notify MUST run before `await ctx.reload()`: after reload the\n\t\t\t\t// loader invalidates this `ctx`/`pi` as stale. ctx.reload() live-\n\t\t\t\t// applies the setting (verified against pi 0.80.3: it drives\n\t\t\t\t// session.reload() → settingsManager.reload() re-reads disk →\n\t\t\t\t// restoreChatBeforeSessionStart copies the new value into\n\t\t\t\t// this.hideThinkingBlock → rebuildChatFromMessages() rebuilds every\n\t\t\t\t// AssistantMessageComponent with the new hide flag). In non-TUI\n\t\t\t\t// modes ctx.reload() is a no-op; the setting then applies on next\n\t\t\t\t// start. The instant keybinding path (Ctrl+T) also still works.\n\t\t\t\tconst verb = next ? \"hidden\" : \"shown\";\n\t\t\t\tconst note = result.createdFresh\n\t\t\t\t\t? `Thinking blocks ${verb}. (Created ${agentSettingsPath()} with this setting.)`\n\t\t\t\t\t: `Thinking blocks ${verb}.`;\n\t\t\t\tctx.ui.notify(note, \"info\");\n\t\t\t\tawait ctx.reload();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst levels = availableLevelsFor(ctx.model);\n\t\t\tconst currentLevel: ThinkingLevel = pi.getThinkingLevel();\n\t\t\tconst validSet = new Set<ThinkingLevel>(levels);\n\n\t\t\t// No-arg form → open a picker. Skip in non-TUI modes — same pattern\n\t\t\t// as batxj-animations per AGENTS.md §5.\n\t\t\tif (trimmed === \"\") {\n\t\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\t\tctx.ui.notify(`Thinking level: ${currentLevel}`, \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (levels.length === 0) {\n\t\t\t\t\tctx.ui.notify(\"No thinking levels available for this model.\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst options = levels.map((lvl) =>\n\t\t\t\t\t(lvl === currentLevel ? \"\\u25CF \" : \" \") + formatLevelLabel(lvl),\n\t\t\t\t);\n\t\t\t\tconst chosen = await ctx.ui.select(\n\t\t\t\t\t`Thinking level (current: ${currentLevel})`,\n\t\t\t\t\toptions,\n\t\t\t\t);\n\t\t\t\tif (chosen === undefined) return;\n\t\t\t\t// Chosen string starts with the current-marker (\"● \") or two-space\n\t\t\t\t// gutter; strip the prefix and extract the first token (the level).\n\t\t\t\tconst stripped = chosen.replace(/^[\\u25CF ]\\s?/, \"\").trimStart();\n\t\t\t\tconst level = stripped.split(/\\s+/)[0] as ThinkingLevel;\n\t\t\t\tif (!validSet.has(level)) {\n\t\t\t\t\tctx.ui.notify(`Unsupported thinking level: ${level}`, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (level === currentLevel) return; // no-op\n\t\t\t\tpi.setThinkingLevel(level);\n\t\t\t\tctx.ui.notify(`Thinking level: ${level}`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Direct-set form: `/thinking <level>`\n\t\t\tconst requested = trimmed.toLowerCase() as ThinkingLevel;\n\t\t\tif (!validSet.has(requested)) {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t`Invalid thinking level: \"${trimmed}\". Valid: ${levels.join(\", \")}`,\n\t\t\t\t\t\"error\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (requested === currentLevel) {\n\t\t\t\tctx.ui.notify(`Thinking level: ${requested} (unchanged)`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpi.setThinkingLevel(requested);\n\t\t\tctx.ui.notify(`Thinking level: ${requested}`, \"info\");\n\t\t},\n\t};\n\n\tpi.registerCommand(\"thinking\", thinkingSpec);\n\t// lunr: /effort and /reasoning are full-parity aliases (same handler + completions).\n\tpi.registerCommand(\"effort\", {\n\t\t...thinkingSpec,\n\t\tdescription: `${THINKING_COMMAND_DESCRIPTION} (alias of /thinking)`,\n\t});\n\tpi.registerCommand(\"reasoning\", {\n\t\t...thinkingSpec,\n\t\tdescription: `${THINKING_COMMAND_DESCRIPTION} (alias of /thinking)`,\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Read the current model from the ExtensionAPI runtime. The spec mentions\n * `pi.getModel()`; pi doesn't expose that name on the API object itself, but\n * the bound `ExtensionContextActions` (which the runtime decorates onto\n * events) does include `getModel()`. We duck-type against the loader so this\n * file stays decoupled from non-public internals. When unavailable (e.g.\n * during autocomplete, before any session has bound), returns undefined and\n * the caller falls back to the default 5-level set.\n */\nfunction currentModel(pi: ExtensionAPI): ModelLike | undefined {\n\tconst fn = (pi as unknown as { getModel?: () => unknown }).getModel;\n\tif (typeof fn === \"function\") {\n\t\treturn fn.call(pi) as ModelLike | undefined;\n\t}\n\treturn undefined;\n}\n"]}
1
+ {"version":3,"file":"ashxj-thinking.d.ts","sourceRoot":"","sources":["../../src/builtin-extensions/ashxj-thinking.ts"],"names":[],"mappings":"AAIA;;;;;;;;;;;;;;;;;GAiBG;AAUH,qEAAqE;AAErE,KAAK,aAAa,GAAG,KAAK,GAAG,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,CAAC;AAErF,iEAAiE;AACjE,UAAU,gBAAgB;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,wEAAsE;AACtE,UAAU,SAAS;IAClB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC;CACjD;AAED,8EAA4E;AAC5E,UAAU,oBAAoB;IAC7B,IAAI,EAAE,KAAK,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,CAAC;IACvC,KAAK,EAAE,SAAS,GAAG,SAAS,CAAC;IAC7B,EAAE,EAAE;QACH,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,GAAG,IAAI,CAAC;QACnE,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,IAAI,CAAC,EAAE;YAAE,MAAM,CAAC,EAAE,WAAW,CAAC;YAAC,OAAO,CAAC,EAAE,MAAM,CAAA;SAAE,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;KACzH,CAAC;CACF;AAED,qFAAmF;AACnF,UAAU,2BAA4B,SAAQ,oBAAoB;IACjE,gBAAgB,IAAI,aAAa,CAAC;IAClC;;;kFAG4E;IAC5E,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED,oEAAkE;AAClE,UAAU,YAAY;IACrB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE;QACtC,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,sBAAsB,CAAC,CAAC,MAAM,EAAE,MAAM,GAAG,gBAAgB,EAAE,GAAG,IAAI,GAAG,OAAO,CAAC,gBAAgB,EAAE,GAAG,IAAI,CAAC,CAAC;QACxG,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,2BAA2B,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;KAC9E,GAAG,IAAI,CAAC;IACT,gBAAgB,IAAI,aAAa,CAAC;IAClC,gBAAgB,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI,CAAC;CAC7C;AAqLD,MAAM,CAAC,OAAO,WAAW,EAAE,EAAE,YAAY,GAAG,IAAI,CA2H/C","sourcesContent":["// @ts-nocheck\n// Vendored from https://github.com/ashx-j/ashxj-thinking @ 0330a34\n// (\"Remove custom footer — keep only /thinking command\"), single-file ashxj\n// convention. lunR patches are marked `// lunr:`.\n/**\n * batxj-thinking extension\n *\n * `/thinking [level]` slash command to view or set the reasoning level,\n * plus `/thinking show|hide|toggle` for thinking-block visibility.\n * `/effort` and `/reasoning` are full-parity aliases.\n *\n * Loaded by pi via jiti — no build step, plain TypeScript.\n *\n * NOTE on type imports: this file deliberately declares structural types\n * rather than importing from `@ashx-j/lunr` (or\n * `@ashx-j/lunr-tui`). pi-coding-agent's `index.d.ts` re-exports\n * from internal `.d.ts` files that contain subpath imports like\n * `@ashx-j/lunr-ai/compat`, which fail to resolve under the default\n * `tsc` settings when a file argument is passed (the spec'd\n * `tsc --noEmit index.ts` script). Declaring the types we use inline\n * keeps the typecheck self-contained.\n */\n\nimport { readFileSync, writeFileSync, existsSync, renameSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\n// ---------------------------------------------------------------------------\n// Minimal structural types (see file header for why these are inline)\n// ---------------------------------------------------------------------------\n\n/** Mirrored from `@ashx-j/lunr-agent` `ThinkingLevel`. */\n// lunr: added \"max\" — lunR's ThinkingLevel union includes it.\ntype ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/** Mirrored from `@ashx-j/lunr-tui` `AutocompleteItem`. */\ninterface AutocompleteItem {\n\tvalue: string;\n\tlabel: string;\n\tdescription?: string;\n}\n\n/** A trimmed view of a `Model` — only the fields the picker reads. */\ninterface ModelLike {\n\tid?: string;\n\treasoning?: boolean;\n\tthinkingLevelMap?: Record<string, string | null>;\n}\n\n/** A trimmed view of `ExtensionContext` — only the methods/props we use. */\ninterface ExtensionContextLike {\n\tmode: \"tui\" | \"rpc\" | \"json\" | \"print\";\n\tmodel: ModelLike | undefined;\n\tui: {\n\t\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n\t\tselect(title: string, options: string[], opts?: { signal?: AbortSignal; timeout?: number }): Promise<string | undefined>;\n\t};\n}\n\n/** A trimmed view of `ExtensionCommandContext` — only the methods/props we use. */\ninterface ExtensionCommandContextLike extends ExtensionContextLike {\n\tgetThinkingLevel(): ThinkingLevel;\n\t/** Reload extensions, skills, prompts, and themes. Re-reads settings.json\n\t * from disk (session.reload() → settingsManager.reload()), so persisted\n\t * runtime settings like `hideThinkingBlock` are live-applied. The captured\n\t * `ctx`/`pi` are stale after this resolves — do not use them afterward. */\n\treload(): Promise<void>;\n}\n\n/** A trimmed view of `ExtensionAPI` — only the methods we use. */\ninterface ExtensionAPI {\n\tregisterCommand(name: string, options: {\n\t\tdescription?: string;\n\t\tgetArgumentCompletions?(prefix: string): AutocompleteItem[] | null | Promise<AutocompleteItem[] | null>;\n\t\thandler(args: string, ctx: ExtensionCommandContextLike): Promise<void> | void;\n\t}): void;\n\tgetThinkingLevel(): ThinkingLevel;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n}\n\n// ---------------------------------------------------------------------------\n// Thinking level config\n// ---------------------------------------------------------------------------\n\n/** All known levels, in display order. Mirrors `EXTENDED_THINKING_LEVELS` in pi-ai. */\nconst ALL_LEVELS: readonly ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n/** Default 5 — used when the active model is undefined (we don't know whether `xhigh`/`max` are supported). */\nconst ALL_LEVELS_5: readonly ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\"];\n\n/** Per-level descriptions. Mirrored from `THINKING_DESCRIPTIONS` in settings-selector.ts. */\nconst THINKING_DESCRIPTIONS: Record<ThinkingLevel, string> = {\n\toff: \"No reasoning\",\n\tminimal: \"Very brief reasoning\",\n\tlow: \"Light reasoning\",\n\tmedium: \"Moderate reasoning\",\n\thigh: \"Deep reasoning\",\n\txhigh: \"Extra-high reasoning\",\n\t// lunr: added — mirrors settings-selector.ts.\n\tmax: \"Maximum reasoning\",\n};\n\n/** Returns the levels valid for the given model, in display order.\n * Mirrors `getSupportedThinkingLevels` in pi-ai: `xhigh`/`max` are opt-in\n * (non-null map entry); other levels drop only on an explicit null. */\nfunction availableLevelsFor(model: ModelLike | undefined): readonly ThinkingLevel[] {\n\tif (!model) return ALL_LEVELS_5;\n\tif (model.reasoning === false) return [\"off\" as const];\n\treturn ALL_LEVELS.filter((level) => {\n\t\tconst mapped = model.thinkingLevelMap?.[level];\n\t\tif (mapped === null) return false;\n\t\tif (level === \"xhigh\" || level === \"max\") return mapped !== undefined;\n\t\treturn true;\n\t});\n}\n\n/** Builds the inline `<padded level> — <description>` label for a level. */\nfunction formatLevelLabel(level: ThinkingLevel): string {\n\treturn `${level.padEnd(8)} \\u2014 ${THINKING_DESCRIPTIONS[level]}`;\n}\n\n// ---------------------------------------------------------------------------\n// Persisted thinking-block visibility (hideThinkingBlock)\n//\n// pi has no public extension API to toggle thinking-block visibility live.\n// The live in-session toggle is `app.thinking.toggle` (default Ctrl+T) wired to\n// `toggleThinkingBlockVisibility()` in interactive-mode.js, which calls\n// `SettingsManager.setHideThinkingBlock()` + rebuilds the chat. That method is\n// not exposed on ExtensionContext / ExtensionCommandContext / ExtensionAPI.\n//\n// What extensions CAN do is persist the `hideThinkingBlock` boolean to the\n// global agent settings file (`~/.lunr/agent/settings.json`); the\n// `SettingsManager` reads it on startup. And because `ctx.reload()` drives\n// `session.reload()` → `settingsManager.reload()` (re-reads disk) →\n// `restoreChatBeforeSessionStart()` copies the new value into\n// `this.hideThinkingBlock` and calls `rebuildChatFromMessages()` (which\n// reconstructs every AssistantMessageComponent with the new hide flag), the\n// persisted value IS live-applied within the session by `await ctx.reload()`\n// (verified against pi 0.80.3). In non-TUI modes `ctx.reload()` is a no-op,\n// so the setting simply applies on next start.\n//\n// The instant keybinding path (Ctrl+T) still works and is the lowest-latency\n// toggle; the command is the discoverable, persistable, completions-friendly\n// equivalent.\n// ---------------------------------------------------------------------------\n\n/** Returns the path to lunR's global agent settings file.\n * lunr: lunR's agent dir is `~/.lunr/agent` (upstream hardcoded `~/.pi/agent`).\n * Honors the `PI_CODING_AGENT_DIR` env override like core config.ts does;\n * a custom agent dir is not exposed to extensions, so this is the only\n * location we can write to be picked up by\n * `SettingsManager.tryLoadFromStorage(\"global\")`. */\nfunction agentSettingsPath(): string {\n\tconst envDir = process.env.PI_CODING_AGENT_DIR;\n\tif (envDir) {\n\t\t// Match core normalizePath(): expand a leading ~ (~/ and, on win32, ~\\).\n\t\tconst home = homedir();\n\t\tconst expanded =\n\t\t\tenvDir === \"~\"\n\t\t\t\t? home\n\t\t\t\t: envDir.startsWith(\"~/\") || (process.platform === \"win32\" && envDir.startsWith(\"~\\\\\"))\n\t\t\t\t\t? join(home, envDir.slice(2))\n\t\t\t\t\t: envDir;\n\t\treturn join(expanded, \"settings.json\");\n\t}\n\treturn join(homedir(), \".lunr\", \"agent\", \"settings.json\");\n}\n\n// ---------------------------------------------------------------------------\n// lunR customize bridge for persisted thinking-block visibility.\n// When the bridge is present (TUI / gateway sessions), reads/writes go through\n// SettingsManager (lockfile + merge). Falls back to direct file I/O when the\n// extension loads in a context without the bridge (e.g. upstream pi).\n// ---------------------------------------------------------------------------\ninterface CustomizeBridge {\n\tgetHideThinkingBlock(): boolean;\n\tsetHideThinkingBlock(hide: boolean): void;\n}\n\nfunction getCustomizeBridge(): CustomizeBridge | undefined {\n\treturn (globalThis as Record<symbol, unknown>)[Symbol.for(\"@lunr/customize\")] as CustomizeBridge | undefined;\n}\n\n/** Returns the persisted `hideThinkingBlock` value (default false, matching\n * `getHideThinkingBlock()` which returns `this.settings.hideThinkingBlock ?? false`).\n * Never throws — on any error (missing file, bad JSON) returns false. */\nfunction readHideThinkingBlock(): boolean {\n\tconst bridge = getCustomizeBridge();\n\tif (bridge) return bridge.getHideThinkingBlock();\n\ttry {\n\t\tconst p = agentSettingsPath();\n\t\tif (!existsSync(p)) return false;\n\t\tconst cfg = JSON.parse(readFileSync(p, \"utf8\")) as { hideThinkingBlock?: boolean };\n\t\treturn cfg.hideThinkingBlock === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Persist `hideThinkingBlock` to the global agent settings file (safe merge).\n *\n * - Preserves all other keys (merge, never overwrite the whole file).\n * - Matches pi's 2-space indentation + trailing newline.\n * - On invalid JSON in the existing file, backs it up to `settings.json.bak`\n * before writing a fresh file, so a corrupted file is never written back.\n * - Never throws; on any error `ok` is false and the caller notifies the user.\n *\n * `createdFresh` is true when the file didn't exist (or was corrupt and backed\n * up) before this write — the handler uses it to warn that a global settings\n * file was created here.\n */\nfunction writeHideThinkingBlock(hide: boolean): {\n\tok: boolean;\n\tcreatedFresh: boolean;\n} {\n\tconst bridge = getCustomizeBridge();\n\tif (bridge) {\n\t\ttry {\n\t\t\tbridge.setHideThinkingBlock(hide);\n\t\t\treturn { ok: true, createdFresh: false };\n\t\t} catch {\n\t\t\treturn { ok: false, createdFresh: false };\n\t\t}\n\t}\n\ttry {\n\t\tconst p = agentSettingsPath();\n\t\tlet cfg: Record<string, unknown> = {};\n\t\tlet createdFresh = false;\n\t\tif (existsSync(p)) {\n\t\t\ttry {\n\t\t\t\tcfg = JSON.parse(readFileSync(p, \"utf8\")) as Record<string, unknown>;\n\t\t\t} catch {\n\t\t\t\t// Existing file is corrupt — back it up, then start fresh.\n\t\t\t\ttry {\n\t\t\t\t\trenameSync(p, `${p}.bak`);\n\t\t\t\t} catch {\n\t\t\t\t\t// If backup fails, still proceed to overwrite (best effort).\n\t\t\t\t}\n\t\t\t\tcfg = {};\n\t\t\t\tcreatedFresh = true;\n\t\t\t}\n\t\t} else {\n\t\t\tcreatedFresh = true;\n\t\t}\n\t\tcfg.hideThinkingBlock = hide;\n\t\twriteFileSync(p, JSON.stringify(cfg, null, 2) + \"\\n\", \"utf8\");\n\t\treturn { ok: true, createdFresh };\n\t} catch {\n\t\treturn { ok: false, createdFresh: false };\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Extension entry point\n// ---------------------------------------------------------------------------\n\nconst THINKING_COMMAND_DESCRIPTION =\n\t\"View or set the reasoning level for the current model, or toggle thinking-block visibility with show/hide/toggle\";\n\nexport default function (pi: ExtensionAPI): void {\n\tconst thinkingSpec = {\n\t\tdescription: THINKING_COMMAND_DESCRIPTION,\n\t\tgetArgumentCompletions(prefix: string): AutocompleteItem[] {\n\t\t\tconst lower = prefix.toLowerCase();\n\t\t\t// Visibility sub-options first, filtered by prefix, alongside the levels.\n\t\t\tconst visibility: AutocompleteItem[] = [\n\t\t\t\t{ value: \"show\", label: \"show\", description: \"Show thinking blocks (persisted to settings.json)\" },\n\t\t\t\t{ value: \"hide\", label: \"hide\", description: \"Hide thinking blocks (persisted to settings.json)\" },\n\t\t\t\t{ value: \"toggle\", label: \"toggle\", description: \"Toggle thinking blocks (persisted to settings.json)\" },\n\t\t\t];\n\t\t\tconst levels = availableLevelsFor(currentModel(pi));\n\t\t\tconst levelItems = levels\n\t\t\t\t.filter((lvl) => lvl.startsWith(lower))\n\t\t\t\t.map((lvl) => ({ value: lvl, label: lvl, description: THINKING_DESCRIPTIONS[lvl] }));\n\t\t\treturn [\n\t\t\t\t...visibility.filter((v) => v.value.startsWith(lower)),\n\t\t\t\t...levelItems,\n\t\t\t];\n\t\t},\n\t\thandler: async (args: string, ctx: ExtensionCommandContextLike) => {\n\t\t\tconst trimmed = args.trim();\n\t\t\tconst lower = trimmed.toLowerCase();\n\n\t\t\t// ---- Visibility sub-options: /thinking show | hide | toggle ----\n\t\t\t// Caught first so `hide`/`show`/`toggle` are never parsed as levels.\n\t\t\t// Works in every mode: only uses ctx.ui.notify + file I/O + ctx.reload().\n\t\t\tif (lower === \"show\" || lower === \"hide\" || lower === \"toggle\") {\n\t\t\t\tconst current = readHideThinkingBlock();\n\t\t\t\tconst next = lower === \"toggle\" ? !current : lower === \"hide\";\n\t\t\t\tif (next === current) {\n\t\t\t\t\tctx.ui.notify(`Thinking blocks already ${current ? \"hidden\" : \"shown\"}.`, \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst result = writeHideThinkingBlock(next);\n\t\t\t\tif (!result.ok) {\n\t\t\t\t\t// lunr: settings path is lunR's (see agentSettingsPath).\n\t\t\t\t\tctx.ui.notify(`Failed to update ${agentSettingsPath()}`, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// The notify MUST run before `await ctx.reload()`: after reload the\n\t\t\t\t// loader invalidates this `ctx`/`pi` as stale. ctx.reload() live-\n\t\t\t\t// applies the setting (verified against pi 0.80.3: it drives\n\t\t\t\t// session.reload() → settingsManager.reload() re-reads disk →\n\t\t\t\t// restoreChatBeforeSessionStart copies the new value into\n\t\t\t\t// this.hideThinkingBlock → rebuildChatFromMessages() rebuilds every\n\t\t\t\t// AssistantMessageComponent with the new hide flag). In non-TUI\n\t\t\t\t// modes ctx.reload() is a no-op; the setting then applies on next\n\t\t\t\t// start. The instant keybinding path (Ctrl+T) also still works.\n\t\t\t\tconst verb = next ? \"hidden\" : \"shown\";\n\t\t\t\tconst note = result.createdFresh\n\t\t\t\t\t? `Thinking blocks ${verb}. (Created ${agentSettingsPath()} with this setting.)`\n\t\t\t\t\t: `Thinking blocks ${verb}.`;\n\t\t\t\tctx.ui.notify(note, \"info\");\n\t\t\t\tawait ctx.reload();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst levels = availableLevelsFor(ctx.model);\n\t\t\tconst currentLevel: ThinkingLevel = pi.getThinkingLevel();\n\t\t\tconst validSet = new Set<ThinkingLevel>(levels);\n\n\t\t\t// No-arg form → open a picker. Skip in non-TUI modes — same pattern\n\t\t\t// as batxj-animations per AGENTS.md §5.\n\t\t\tif (trimmed === \"\") {\n\t\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\t\tctx.ui.notify(`Thinking level: ${currentLevel}`, \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (levels.length === 0) {\n\t\t\t\t\tctx.ui.notify(\"No thinking levels available for this model.\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst options = levels.map((lvl) =>\n\t\t\t\t\t(lvl === currentLevel ? \"\\u25CF \" : \" \") + formatLevelLabel(lvl),\n\t\t\t\t);\n\t\t\t\tconst chosen = await ctx.ui.select(\n\t\t\t\t\t`Thinking level (current: ${currentLevel})`,\n\t\t\t\t\toptions,\n\t\t\t\t);\n\t\t\t\tif (chosen === undefined) return;\n\t\t\t\t// Chosen string starts with the current-marker (\"● \") or two-space\n\t\t\t\t// gutter; strip the prefix and extract the first token (the level).\n\t\t\t\tconst stripped = chosen.replace(/^[\\u25CF ]\\s?/, \"\").trimStart();\n\t\t\t\tconst level = stripped.split(/\\s+/)[0] as ThinkingLevel;\n\t\t\t\tif (!validSet.has(level)) {\n\t\t\t\t\tctx.ui.notify(`Unsupported thinking level: ${level}`, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (level === currentLevel) return; // no-op\n\t\t\t\tpi.setThinkingLevel(level);\n\t\t\t\tctx.ui.notify(`Thinking level: ${pi.getThinkingLevel()}`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Direct-set form: `/thinking <level>`\n\t\t\tconst requested = trimmed.toLowerCase() as ThinkingLevel;\n\t\t\tif (!validSet.has(requested)) {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t`Invalid thinking level: \"${trimmed}\". Valid: ${levels.join(\", \")}`,\n\t\t\t\t\t\"error\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (requested === currentLevel) {\n\t\t\t\tctx.ui.notify(`Thinking level: ${requested} (unchanged)`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpi.setThinkingLevel(requested);\n\t\t\tctx.ui.notify(`Thinking level: ${pi.getThinkingLevel()}`, \"info\");\n\t\t},\n\t};\n\n\tpi.registerCommand(\"thinking\", thinkingSpec);\n\t// lunr: /effort and /reasoning are full-parity aliases (same handler + completions).\n\tpi.registerCommand(\"effort\", {\n\t\t...thinkingSpec,\n\t\tdescription: `${THINKING_COMMAND_DESCRIPTION} (alias of /thinking)`,\n\t});\n\tpi.registerCommand(\"reasoning\", {\n\t\t...thinkingSpec,\n\t\tdescription: `${THINKING_COMMAND_DESCRIPTION} (alias of /thinking)`,\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Read the current model from the ExtensionAPI runtime. The spec mentions\n * `pi.getModel()`; pi doesn't expose that name on the API object itself, but\n * the bound `ExtensionContextActions` (which the runtime decorates onto\n * events) does include `getModel()`. We duck-type against the loader so this\n * file stays decoupled from non-public internals. When unavailable (e.g.\n * during autocomplete, before any session has bound), returns undefined and\n * the caller falls back to the default 5-level set.\n */\nfunction currentModel(pi: ExtensionAPI): ModelLike | undefined {\n\tconst fn = (pi as unknown as { getModel?: () => unknown }).getModel;\n\tif (typeof fn === \"function\") {\n\t\treturn fn.call(pi) as ModelLike | undefined;\n\t}\n\treturn undefined;\n}\n"]}
@@ -26,9 +26,8 @@ import { homedir } from "node:os";
26
26
  // ---------------------------------------------------------------------------
27
27
  // Thinking level config
28
28
  // ---------------------------------------------------------------------------
29
- /** All known levels, in display order. */
30
- // lunr: "max" appended (lunR supports it; filtered per-model below when unsupported).
31
- const ALL_LEVELS_7 = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
29
+ /** All known levels, in display order. Mirrors `EXTENDED_THINKING_LEVELS` in pi-ai. */
30
+ const ALL_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
32
31
  /** Default 5 — used when the active model is undefined (we don't know whether `xhigh`/`max` are supported). */
33
32
  const ALL_LEVELS_5 = ["off", "minimal", "low", "medium", "high"];
34
33
  /** Per-level descriptions. Mirrored from `THINKING_DESCRIPTIONS` in settings-selector.ts. */
@@ -42,18 +41,20 @@ const THINKING_DESCRIPTIONS = {
42
41
  // lunr: added — mirrors settings-selector.ts.
43
42
  max: "Maximum reasoning",
44
43
  };
45
- /** Returns the levels valid for the given model, in display order. */
44
+ /** Returns the levels valid for the given model, in display order.
45
+ * Mirrors `getSupportedThinkingLevels` in pi-ai: `xhigh`/`max` are opt-in
46
+ * (non-null map entry); other levels drop only on an explicit null. */
46
47
  function availableLevelsFor(model) {
47
48
  if (!model)
48
49
  return ALL_LEVELS_5;
49
50
  if (model.reasoning === false)
50
51
  return ["off"];
51
- // Filter out levels the model marks as unsupported (null entry).
52
- return ALL_LEVELS_7.filter((lvl) => {
53
- const m = model.thinkingLevelMap;
54
- if (m && Object.prototype.hasOwnProperty.call(m, lvl) && m[lvl] === null) {
52
+ return ALL_LEVELS.filter((level) => {
53
+ const mapped = model.thinkingLevelMap?.[level];
54
+ if (mapped === null)
55
55
  return false;
56
- }
56
+ if (level === "xhigh" || level === "max")
57
+ return mapped !== undefined;
57
58
  return true;
58
59
  });
59
60
  }
@@ -270,7 +271,7 @@ export default function (pi) {
270
271
  if (level === currentLevel)
271
272
  return; // no-op
272
273
  pi.setThinkingLevel(level);
273
- ctx.ui.notify(`Thinking level: ${level}`, "info");
274
+ ctx.ui.notify(`Thinking level: ${pi.getThinkingLevel()}`, "info");
274
275
  return;
275
276
  }
276
277
  // Direct-set form: `/thinking <level>`
@@ -284,7 +285,7 @@ export default function (pi) {
284
285
  return;
285
286
  }
286
287
  pi.setThinkingLevel(requested);
287
- ctx.ui.notify(`Thinking level: ${requested}`, "info");
288
+ ctx.ui.notify(`Thinking level: ${pi.getThinkingLevel()}`, "info");
288
289
  },
289
290
  };
290
291
  pi.registerCommand("thinking", thinkingSpec);
@@ -1 +1 @@
1
- {"version":3,"file":"ashxj-thinking.js","sourceRoot":"","sources":["../../src/builtin-extensions/ashxj-thinking.ts"],"names":[],"mappings":"AAAA,cAAc;AACd,mEAAmE;AACnE,8EAA4E;AAC5E,kDAAkD;AAClD;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAC9E,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAuDlC,8EAA8E;AAC9E,wBAAwB;AACxB,8EAA8E;AAE9E,0CAA0C;AAC1C,sFAAsF;AACtF,MAAM,YAAY,GAA6B,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC3G,iHAA+G;AAC/G,MAAM,YAAY,GAA6B,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AAE3F,6FAA6F;AAC7F,MAAM,qBAAqB,GAAkC;IAC5D,GAAG,EAAE,cAAc;IACnB,OAAO,EAAE,sBAAsB;IAC/B,GAAG,EAAE,iBAAiB;IACtB,MAAM,EAAE,oBAAoB;IAC5B,I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AAC,eAAe,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;IAC7C,qFAAqF;IACrF,EAAE,CAAC,eAAe,CAAC,QAAQ,EAAE;QAC5B,GAAG,YAAY;QACf,WAAW,EAAE,GAAG,4BAA4B,uBAAuB;KACnE,CAAC,CAAC;IACH,EAAE,CAAC,eAAe,CAAC,WAAW,EAAE;QAC/B,GAAG,YAAY;QACf,WAAW,EAAE,GAAG,4BAA4B,uBAAuB;KACnE,CAAC,CAAC;AAAA,CACH;AAED,8EAA8E;AAC9E,UAAU;AACV,8EAA8E;AAE9E;;;;;;;;GAQG;AACH,SAAS,YAAY,CAAC,EAAgB,EAAyB;IAC9D,MAAM,EAAE,GAAI,EAA8C,CAAC,QAAQ,CAAC;IACpE,IAAI,OAAO,EAAE,KAAK,UAAU,EAAE,CAAC;QAC9B,OAAO,EAAE,CAAC,IAAI,CAAC,EAAE,CAA0B,CAAC;IAC7C,CAAC;IACD,OAAO,SAAS,CAAC;AAAA,CACjB","sourcesContent":["// @ts-nocheck\n// Vendored from https://github.com/ashx-j/ashxj-thinking @ 0330a34\n// (\"Remove custom footer — keep only /thinking command\"), single-file ashxj\n// convention. lunR patches are marked `// lunr:`.\n/**\n * batxj-thinking extension\n *\n * `/thinking [level]` slash command to view or set the reasoning level,\n * plus `/thinking show|hide|toggle` for thinking-block visibility.\n * `/effort` and `/reasoning` are full-parity aliases.\n *\n * Loaded by pi via jiti — no build step, plain TypeScript.\n *\n * NOTE on type imports: this file deliberately declares structural types\n * rather than importing from `@ashx-j/lunr` (or\n * `@ashx-j/lunr-tui`). pi-coding-agent's `index.d.ts` re-exports\n * from internal `.d.ts` files that contain subpath imports like\n * `@ashx-j/lunr-ai/compat`, which fail to resolve under the default\n * `tsc` settings when a file argument is passed (the spec'd\n * `tsc --noEmit index.ts` script). Declaring the types we use inline\n * keeps the typecheck self-contained.\n */\n\nimport { readFileSync, writeFileSync, existsSync, renameSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\n// ---------------------------------------------------------------------------\n// Minimal structural types (see file header for why these are inline)\n// ---------------------------------------------------------------------------\n\n/** Mirrored from `@ashx-j/lunr-agent` `ThinkingLevel`. */\n// lunr: added \"max\" — lunR's ThinkingLevel union includes it.\ntype ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/** Mirrored from `@ashx-j/lunr-tui` `AutocompleteItem`. */\ninterface AutocompleteItem {\n\tvalue: string;\n\tlabel: string;\n\tdescription?: string;\n}\n\n/** A trimmed view of a `Model` — only the fields the picker reads. */\ninterface ModelLike {\n\tid?: string;\n\treasoning?: boolean;\n\tthinkingLevelMap?: Record<string, string | null>;\n}\n\n/** A trimmed view of `ExtensionContext` — only the methods/props we use. */\ninterface ExtensionContextLike {\n\tmode: \"tui\" | \"rpc\" | \"json\" | \"print\";\n\tmodel: ModelLike | undefined;\n\tui: {\n\t\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n\t\tselect(title: string, options: string[], opts?: { signal?: AbortSignal; timeout?: number }): Promise<string | undefined>;\n\t};\n}\n\n/** A trimmed view of `ExtensionCommandContext` — only the methods/props we use. */\ninterface ExtensionCommandContextLike extends ExtensionContextLike {\n\tgetThinkingLevel(): ThinkingLevel;\n\t/** Reload extensions, skills, prompts, and themes. Re-reads settings.json\n\t * from disk (session.reload() → settingsManager.reload()), so persisted\n\t * runtime settings like `hideThinkingBlock` are live-applied. The captured\n\t * `ctx`/`pi` are stale after this resolves — do not use them afterward. */\n\treload(): Promise<void>;\n}\n\n/** A trimmed view of `ExtensionAPI` — only the methods we use. */\ninterface ExtensionAPI {\n\tregisterCommand(name: string, options: {\n\t\tdescription?: string;\n\t\tgetArgumentCompletions?(prefix: string): AutocompleteItem[] | null | Promise<AutocompleteItem[] | null>;\n\t\thandler(args: string, ctx: ExtensionCommandContextLike): Promise<void> | void;\n\t}): void;\n\tgetThinkingLevel(): ThinkingLevel;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n}\n\n// ---------------------------------------------------------------------------\n// Thinking level config\n// ---------------------------------------------------------------------------\n\n/** All known levels, in display order. */\n// lunr: \"max\" appended (lunR supports it; filtered per-model below when unsupported).\nconst ALL_LEVELS_7: readonly ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n/** Default 5 — used when the active model is undefined (we don't know whether `xhigh`/`max` are supported). */\nconst ALL_LEVELS_5: readonly ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\"];\n\n/** Per-level descriptions. Mirrored from `THINKING_DESCRIPTIONS` in settings-selector.ts. */\nconst THINKING_DESCRIPTIONS: Record<ThinkingLevel, string> = {\n\toff: \"No reasoning\",\n\tminimal: \"Very brief reasoning\",\n\tlow: \"Light reasoning\",\n\tmedium: \"Moderate reasoning\",\n\thigh: \"Deep reasoning\",\n\txhigh: \"Extra-high reasoning\",\n\t// lunr: added — mirrors settings-selector.ts.\n\tmax: \"Maximum reasoning\",\n};\n\n/** Returns the levels valid for the given model, in display order. */\nfunction availableLevelsFor(model: ModelLike | undefined): readonly ThinkingLevel[] {\n\tif (!model) return ALL_LEVELS_5;\n\tif (model.reasoning === false) return [\"off\" as const];\n\t// Filter out levels the model marks as unsupported (null entry).\n\treturn ALL_LEVELS_7.filter((lvl) => {\n\t\tconst m = model.thinkingLevelMap;\n\t\tif (m && Object.prototype.hasOwnProperty.call(m, lvl) && (m as Record<string, string | null>)[lvl] === null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t});\n}\n\n/** Builds the inline `<padded level> — <description>` label for a level. */\nfunction formatLevelLabel(level: ThinkingLevel): string {\n\treturn `${level.padEnd(8)} \\u2014 ${THINKING_DESCRIPTIONS[level]}`;\n}\n\n// ---------------------------------------------------------------------------\n// Persisted thinking-block visibility (hideThinkingBlock)\n//\n// pi has no public extension API to toggle thinking-block visibility live.\n// The live in-session toggle is `app.thinking.toggle` (default Ctrl+T) wired to\n// `toggleThinkingBlockVisibility()` in interactive-mode.js, which calls\n// `SettingsManager.setHideThinkingBlock()` + rebuilds the chat. That method is\n// not exposed on ExtensionContext / ExtensionCommandContext / ExtensionAPI.\n//\n// What extensions CAN do is persist the `hideThinkingBlock` boolean to the\n// global agent settings file (`~/.lunr/agent/settings.json`); the\n// `SettingsManager` reads it on startup. And because `ctx.reload()` drives\n// `session.reload()` → `settingsManager.reload()` (re-reads disk) →\n// `restoreChatBeforeSessionStart()` copies the new value into\n// `this.hideThinkingBlock` and calls `rebuildChatFromMessages()` (which\n// reconstructs every AssistantMessageComponent with the new hide flag), the\n// persisted value IS live-applied within the session by `await ctx.reload()`\n// (verified against pi 0.80.3). In non-TUI modes `ctx.reload()` is a no-op,\n// so the setting simply applies on next start.\n//\n// The instant keybinding path (Ctrl+T) still works and is the lowest-latency\n// toggle; the command is the discoverable, persistable, completions-friendly\n// equivalent.\n// ---------------------------------------------------------------------------\n\n/** Returns the path to lunR's global agent settings file.\n * lunr: lunR's agent dir is `~/.lunr/agent` (upstream hardcoded `~/.pi/agent`).\n * Honors the `PI_CODING_AGENT_DIR` env override like core config.ts does;\n * a custom agent dir is not exposed to extensions, so this is the only\n * location we can write to be picked up by\n * `SettingsManager.tryLoadFromStorage(\"global\")`. */\nfunction agentSettingsPath(): string {\n\tconst envDir = process.env.PI_CODING_AGENT_DIR;\n\tif (envDir) {\n\t\t// Match core normalizePath(): expand a leading ~ (~/ and, on win32, ~\\).\n\t\tconst home = homedir();\n\t\tconst expanded =\n\t\t\tenvDir === \"~\"\n\t\t\t\t? home\n\t\t\t\t: envDir.startsWith(\"~/\") || (process.platform === \"win32\" && envDir.startsWith(\"~\\\\\"))\n\t\t\t\t\t? join(home, envDir.slice(2))\n\t\t\t\t\t: envDir;\n\t\treturn join(expanded, \"settings.json\");\n\t}\n\treturn join(homedir(), \".lunr\", \"agent\", \"settings.json\");\n}\n\n// ---------------------------------------------------------------------------\n// lunR customize bridge for persisted thinking-block visibility.\n// When the bridge is present (TUI / gateway sessions), reads/writes go through\n// SettingsManager (lockfile + merge). Falls back to direct file I/O when the\n// extension loads in a context without the bridge (e.g. upstream pi).\n// ---------------------------------------------------------------------------\ninterface CustomizeBridge {\n\tgetHideThinkingBlock(): boolean;\n\tsetHideThinkingBlock(hide: boolean): void;\n}\n\nfunction getCustomizeBridge(): CustomizeBridge | undefined {\n\treturn (globalThis as Record<symbol, unknown>)[Symbol.for(\"@lunr/customize\")] as CustomizeBridge | undefined;\n}\n\n/** Returns the persisted `hideThinkingBlock` value (default false, matching\n * `getHideThinkingBlock()` which returns `this.settings.hideThinkingBlock ?? false`).\n * Never throws — on any error (missing file, bad JSON) returns false. */\nfunction readHideThinkingBlock(): boolean {\n\tconst bridge = getCustomizeBridge();\n\tif (bridge) return bridge.getHideThinkingBlock();\n\ttry {\n\t\tconst p = agentSettingsPath();\n\t\tif (!existsSync(p)) return false;\n\t\tconst cfg = JSON.parse(readFileSync(p, \"utf8\")) as { hideThinkingBlock?: boolean };\n\t\treturn cfg.hideThinkingBlock === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Persist `hideThinkingBlock` to the global agent settings file (safe merge).\n *\n * - Preserves all other keys (merge, never overwrite the whole file).\n * - Matches pi's 2-space indentation + trailing newline.\n * - On invalid JSON in the existing file, backs it up to `settings.json.bak`\n * before writing a fresh file, so a corrupted file is never written back.\n * - Never throws; on any error `ok` is false and the caller notifies the user.\n *\n * `createdFresh` is true when the file didn't exist (or was corrupt and backed\n * up) before this write — the handler uses it to warn that a global settings\n * file was created here.\n */\nfunction writeHideThinkingBlock(hide: boolean): {\n\tok: boolean;\n\tcreatedFresh: boolean;\n} {\n\tconst bridge = getCustomizeBridge();\n\tif (bridge) {\n\t\ttry {\n\t\t\tbridge.setHideThinkingBlock(hide);\n\t\t\treturn { ok: true, createdFresh: false };\n\t\t} catch {\n\t\t\treturn { ok: false, createdFresh: false };\n\t\t}\n\t}\n\ttry {\n\t\tconst p = agentSettingsPath();\n\t\tlet cfg: Record<string, unknown> = {};\n\t\tlet createdFresh = false;\n\t\tif (existsSync(p)) {\n\t\t\ttry {\n\t\t\t\tcfg = JSON.parse(readFileSync(p, \"utf8\")) as Record<string, unknown>;\n\t\t\t} catch {\n\t\t\t\t// Existing file is corrupt — back it up, then start fresh.\n\t\t\t\ttry {\n\t\t\t\t\trenameSync(p, `${p}.bak`);\n\t\t\t\t} catch {\n\t\t\t\t\t// If backup fails, still proceed to overwrite (best effort).\n\t\t\t\t}\n\t\t\t\tcfg = {};\n\t\t\t\tcreatedFresh = true;\n\t\t\t}\n\t\t} else {\n\t\t\tcreatedFresh = true;\n\t\t}\n\t\tcfg.hideThinkingBlock = hide;\n\t\twriteFileSync(p, JSON.stringify(cfg, null, 2) + \"\\n\", \"utf8\");\n\t\treturn { ok: true, createdFresh };\n\t} catch {\n\t\treturn { ok: false, createdFresh: false };\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Extension entry point\n// ---------------------------------------------------------------------------\n\nconst THINKING_COMMAND_DESCRIPTION =\n\t\"View or set the reasoning level for the current model, or toggle thinking-block visibility with show/hide/toggle\";\n\nexport default function (pi: ExtensionAPI): void {\n\tconst thinkingSpec = {\n\t\tdescription: THINKING_COMMAND_DESCRIPTION,\n\t\tgetArgumentCompletions(prefix: string): AutocompleteItem[] {\n\t\t\tconst lower = prefix.toLowerCase();\n\t\t\t// Visibility sub-options first, filtered by prefix, alongside the levels.\n\t\t\tconst visibility: AutocompleteItem[] = [\n\t\t\t\t{ value: \"show\", label: \"show\", description: \"Show thinking blocks (persisted to settings.json)\" },\n\t\t\t\t{ value: \"hide\", label: \"hide\", description: \"Hide thinking blocks (persisted to settings.json)\" },\n\t\t\t\t{ value: \"toggle\", label: \"toggle\", description: \"Toggle thinking blocks (persisted to settings.json)\" },\n\t\t\t];\n\t\t\tconst levels = availableLevelsFor(currentModel(pi));\n\t\t\tconst levelItems = levels\n\t\t\t\t.filter((lvl) => lvl.startsWith(lower))\n\t\t\t\t.map((lvl) => ({ value: lvl, label: lvl, description: THINKING_DESCRIPTIONS[lvl] }));\n\t\t\treturn [\n\t\t\t\t...visibility.filter((v) => v.value.startsWith(lower)),\n\t\t\t\t...levelItems,\n\t\t\t];\n\t\t},\n\t\thandler: async (args: string, ctx: ExtensionCommandContextLike) => {\n\t\t\tconst trimmed = args.trim();\n\t\t\tconst lower = trimmed.toLowerCase();\n\n\t\t\t// ---- Visibility sub-options: /thinking show | hide | toggle ----\n\t\t\t// Caught first so `hide`/`show`/`toggle` are never parsed as levels.\n\t\t\t// Works in every mode: only uses ctx.ui.notify + file I/O + ctx.reload().\n\t\t\tif (lower === \"show\" || lower === \"hide\" || lower === \"toggle\") {\n\t\t\t\tconst current = readHideThinkingBlock();\n\t\t\t\tconst next = lower === \"toggle\" ? !current : lower === \"hide\";\n\t\t\t\tif (next === current) {\n\t\t\t\t\tctx.ui.notify(`Thinking blocks already ${current ? \"hidden\" : \"shown\"}.`, \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst result = writeHideThinkingBlock(next);\n\t\t\t\tif (!result.ok) {\n\t\t\t\t\t// lunr: settings path is lunR's (see agentSettingsPath).\n\t\t\t\t\tctx.ui.notify(`Failed to update ${agentSettingsPath()}`, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// The notify MUST run before `await ctx.reload()`: after reload the\n\t\t\t\t// loader invalidates this `ctx`/`pi` as stale. ctx.reload() live-\n\t\t\t\t// applies the setting (verified against pi 0.80.3: it drives\n\t\t\t\t// session.reload() → settingsManager.reload() re-reads disk →\n\t\t\t\t// restoreChatBeforeSessionStart copies the new value into\n\t\t\t\t// this.hideThinkingBlock → rebuildChatFromMessages() rebuilds every\n\t\t\t\t// AssistantMessageComponent with the new hide flag). In non-TUI\n\t\t\t\t// modes ctx.reload() is a no-op; the setting then applies on next\n\t\t\t\t// start. The instant keybinding path (Ctrl+T) also still works.\n\t\t\t\tconst verb = next ? \"hidden\" : \"shown\";\n\t\t\t\tconst note = result.createdFresh\n\t\t\t\t\t? `Thinking blocks ${verb}. (Created ${agentSettingsPath()} with this setting.)`\n\t\t\t\t\t: `Thinking blocks ${verb}.`;\n\t\t\t\tctx.ui.notify(note, \"info\");\n\t\t\t\tawait ctx.reload();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst levels = availableLevelsFor(ctx.model);\n\t\t\tconst currentLevel: ThinkingLevel = pi.getThinkingLevel();\n\t\t\tconst validSet = new Set<ThinkingLevel>(levels);\n\n\t\t\t// No-arg form → open a picker. Skip in non-TUI modes — same pattern\n\t\t\t// as batxj-animations per AGENTS.md §5.\n\t\t\tif (trimmed === \"\") {\n\t\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\t\tctx.ui.notify(`Thinking level: ${currentLevel}`, \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (levels.length === 0) {\n\t\t\t\t\tctx.ui.notify(\"No thinking levels available for this model.\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst options = levels.map((lvl) =>\n\t\t\t\t\t(lvl === currentLevel ? \"\\u25CF \" : \" \") + formatLevelLabel(lvl),\n\t\t\t\t);\n\t\t\t\tconst chosen = await ctx.ui.select(\n\t\t\t\t\t`Thinking level (current: ${currentLevel})`,\n\t\t\t\t\toptions,\n\t\t\t\t);\n\t\t\t\tif (chosen === undefined) return;\n\t\t\t\t// Chosen string starts with the current-marker (\"● \") or two-space\n\t\t\t\t// gutter; strip the prefix and extract the first token (the level).\n\t\t\t\tconst stripped = chosen.replace(/^[\\u25CF ]\\s?/, \"\").trimStart();\n\t\t\t\tconst level = stripped.split(/\\s+/)[0] as ThinkingLevel;\n\t\t\t\tif (!validSet.has(level)) {\n\t\t\t\t\tctx.ui.notify(`Unsupported thinking level: ${level}`, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (level === currentLevel) return; // no-op\n\t\t\t\tpi.setThinkingLevel(level);\n\t\t\t\tctx.ui.notify(`Thinking level: ${level}`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Direct-set form: `/thinking <level>`\n\t\t\tconst requested = trimmed.toLowerCase() as ThinkingLevel;\n\t\t\tif (!validSet.has(requested)) {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t`Invalid thinking level: \"${trimmed}\". Valid: ${levels.join(\", \")}`,\n\t\t\t\t\t\"error\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (requested === currentLevel) {\n\t\t\t\tctx.ui.notify(`Thinking level: ${requested} (unchanged)`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpi.setThinkingLevel(requested);\n\t\t\tctx.ui.notify(`Thinking level: ${requested}`, \"info\");\n\t\t},\n\t};\n\n\tpi.registerCommand(\"thinking\", thinkingSpec);\n\t// lunr: /effort and /reasoning are full-parity aliases (same handler + completions).\n\tpi.registerCommand(\"effort\", {\n\t\t...thinkingSpec,\n\t\tdescription: `${THINKING_COMMAND_DESCRIPTION} (alias of /thinking)`,\n\t});\n\tpi.registerCommand(\"reasoning\", {\n\t\t...thinkingSpec,\n\t\tdescription: `${THINKING_COMMAND_DESCRIPTION} (alias of /thinking)`,\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Read the current model from the ExtensionAPI runtime. The spec mentions\n * `pi.getModel()`; pi doesn't expose that name on the API object itself, but\n * the bound `ExtensionContextActions` (which the runtime decorates onto\n * events) does include `getModel()`. We duck-type against the loader so this\n * file stays decoupled from non-public internals. When unavailable (e.g.\n * during autocomplete, before any session has bound), returns undefined and\n * the caller falls back to the default 5-level set.\n */\nfunction currentModel(pi: ExtensionAPI): ModelLike | undefined {\n\tconst fn = (pi as unknown as { getModel?: () => unknown }).getModel;\n\tif (typeof fn === \"function\") {\n\t\treturn fn.call(pi) as ModelLike | undefined;\n\t}\n\treturn undefined;\n}\n"]}
1
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yB;IAC9D,MAAM,EAAE,GAAI,EAA8C,CAAC,QAAQ,CAAC;IACpE,IAAI,OAAO,EAAE,KAAK,UAAU,EAAE,CAAC;QAC9B,OAAO,EAAE,CAAC,IAAI,CAAC,EAAE,CAA0B,CAAC;IAC7C,CAAC;IACD,OAAO,SAAS,CAAC;AAAA,CACjB","sourcesContent":["// @ts-nocheck\n// Vendored from https://github.com/ashx-j/ashxj-thinking @ 0330a34\n// (\"Remove custom footer — keep only /thinking command\"), single-file ashxj\n// convention. lunR patches are marked `// lunr:`.\n/**\n * batxj-thinking extension\n *\n * `/thinking [level]` slash command to view or set the reasoning level,\n * plus `/thinking show|hide|toggle` for thinking-block visibility.\n * `/effort` and `/reasoning` are full-parity aliases.\n *\n * Loaded by pi via jiti — no build step, plain TypeScript.\n *\n * NOTE on type imports: this file deliberately declares structural types\n * rather than importing from `@ashx-j/lunr` (or\n * `@ashx-j/lunr-tui`). pi-coding-agent's `index.d.ts` re-exports\n * from internal `.d.ts` files that contain subpath imports like\n * `@ashx-j/lunr-ai/compat`, which fail to resolve under the default\n * `tsc` settings when a file argument is passed (the spec'd\n * `tsc --noEmit index.ts` script). Declaring the types we use inline\n * keeps the typecheck self-contained.\n */\n\nimport { readFileSync, writeFileSync, existsSync, renameSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\n// ---------------------------------------------------------------------------\n// Minimal structural types (see file header for why these are inline)\n// ---------------------------------------------------------------------------\n\n/** Mirrored from `@ashx-j/lunr-agent` `ThinkingLevel`. */\n// lunr: added \"max\" — lunR's ThinkingLevel union includes it.\ntype ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/** Mirrored from `@ashx-j/lunr-tui` `AutocompleteItem`. */\ninterface AutocompleteItem {\n\tvalue: string;\n\tlabel: string;\n\tdescription?: string;\n}\n\n/** A trimmed view of a `Model` — only the fields the picker reads. */\ninterface ModelLike {\n\tid?: string;\n\treasoning?: boolean;\n\tthinkingLevelMap?: Record<string, string | null>;\n}\n\n/** A trimmed view of `ExtensionContext` — only the methods/props we use. */\ninterface ExtensionContextLike {\n\tmode: \"tui\" | \"rpc\" | \"json\" | \"print\";\n\tmodel: ModelLike | undefined;\n\tui: {\n\t\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n\t\tselect(title: string, options: string[], opts?: { signal?: AbortSignal; timeout?: number }): Promise<string | undefined>;\n\t};\n}\n\n/** A trimmed view of `ExtensionCommandContext` — only the methods/props we use. */\ninterface ExtensionCommandContextLike extends ExtensionContextLike {\n\tgetThinkingLevel(): ThinkingLevel;\n\t/** Reload extensions, skills, prompts, and themes. Re-reads settings.json\n\t * from disk (session.reload() → settingsManager.reload()), so persisted\n\t * runtime settings like `hideThinkingBlock` are live-applied. The captured\n\t * `ctx`/`pi` are stale after this resolves — do not use them afterward. */\n\treload(): Promise<void>;\n}\n\n/** A trimmed view of `ExtensionAPI` — only the methods we use. */\ninterface ExtensionAPI {\n\tregisterCommand(name: string, options: {\n\t\tdescription?: string;\n\t\tgetArgumentCompletions?(prefix: string): AutocompleteItem[] | null | Promise<AutocompleteItem[] | null>;\n\t\thandler(args: string, ctx: ExtensionCommandContextLike): Promise<void> | void;\n\t}): void;\n\tgetThinkingLevel(): ThinkingLevel;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n}\n\n// ---------------------------------------------------------------------------\n// Thinking level config\n// ---------------------------------------------------------------------------\n\n/** All known levels, in display order. Mirrors `EXTENDED_THINKING_LEVELS` in pi-ai. */\nconst ALL_LEVELS: readonly ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n/** Default 5 — used when the active model is undefined (we don't know whether `xhigh`/`max` are supported). */\nconst ALL_LEVELS_5: readonly ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\"];\n\n/** Per-level descriptions. Mirrored from `THINKING_DESCRIPTIONS` in settings-selector.ts. */\nconst THINKING_DESCRIPTIONS: Record<ThinkingLevel, string> = {\n\toff: \"No reasoning\",\n\tminimal: \"Very brief reasoning\",\n\tlow: \"Light reasoning\",\n\tmedium: \"Moderate reasoning\",\n\thigh: \"Deep reasoning\",\n\txhigh: \"Extra-high reasoning\",\n\t// lunr: added — mirrors settings-selector.ts.\n\tmax: \"Maximum reasoning\",\n};\n\n/** Returns the levels valid for the given model, in display order.\n * Mirrors `getSupportedThinkingLevels` in pi-ai: `xhigh`/`max` are opt-in\n * (non-null map entry); other levels drop only on an explicit null. */\nfunction availableLevelsFor(model: ModelLike | undefined): readonly ThinkingLevel[] {\n\tif (!model) return ALL_LEVELS_5;\n\tif (model.reasoning === false) return [\"off\" as const];\n\treturn ALL_LEVELS.filter((level) => {\n\t\tconst mapped = model.thinkingLevelMap?.[level];\n\t\tif (mapped === null) return false;\n\t\tif (level === \"xhigh\" || level === \"max\") return mapped !== undefined;\n\t\treturn true;\n\t});\n}\n\n/** Builds the inline `<padded level> — <description>` label for a level. */\nfunction formatLevelLabel(level: ThinkingLevel): string {\n\treturn `${level.padEnd(8)} \\u2014 ${THINKING_DESCRIPTIONS[level]}`;\n}\n\n// ---------------------------------------------------------------------------\n// Persisted thinking-block visibility (hideThinkingBlock)\n//\n// pi has no public extension API to toggle thinking-block visibility live.\n// The live in-session toggle is `app.thinking.toggle` (default Ctrl+T) wired to\n// `toggleThinkingBlockVisibility()` in interactive-mode.js, which calls\n// `SettingsManager.setHideThinkingBlock()` + rebuilds the chat. That method is\n// not exposed on ExtensionContext / ExtensionCommandContext / ExtensionAPI.\n//\n// What extensions CAN do is persist the `hideThinkingBlock` boolean to the\n// global agent settings file (`~/.lunr/agent/settings.json`); the\n// `SettingsManager` reads it on startup. And because `ctx.reload()` drives\n// `session.reload()` → `settingsManager.reload()` (re-reads disk) →\n// `restoreChatBeforeSessionStart()` copies the new value into\n// `this.hideThinkingBlock` and calls `rebuildChatFromMessages()` (which\n// reconstructs every AssistantMessageComponent with the new hide flag), the\n// persisted value IS live-applied within the session by `await ctx.reload()`\n// (verified against pi 0.80.3). In non-TUI modes `ctx.reload()` is a no-op,\n// so the setting simply applies on next start.\n//\n// The instant keybinding path (Ctrl+T) still works and is the lowest-latency\n// toggle; the command is the discoverable, persistable, completions-friendly\n// equivalent.\n// ---------------------------------------------------------------------------\n\n/** Returns the path to lunR's global agent settings file.\n * lunr: lunR's agent dir is `~/.lunr/agent` (upstream hardcoded `~/.pi/agent`).\n * Honors the `PI_CODING_AGENT_DIR` env override like core config.ts does;\n * a custom agent dir is not exposed to extensions, so this is the only\n * location we can write to be picked up by\n * `SettingsManager.tryLoadFromStorage(\"global\")`. */\nfunction agentSettingsPath(): string {\n\tconst envDir = process.env.PI_CODING_AGENT_DIR;\n\tif (envDir) {\n\t\t// Match core normalizePath(): expand a leading ~ (~/ and, on win32, ~\\).\n\t\tconst home = homedir();\n\t\tconst expanded =\n\t\t\tenvDir === \"~\"\n\t\t\t\t? home\n\t\t\t\t: envDir.startsWith(\"~/\") || (process.platform === \"win32\" && envDir.startsWith(\"~\\\\\"))\n\t\t\t\t\t? join(home, envDir.slice(2))\n\t\t\t\t\t: envDir;\n\t\treturn join(expanded, \"settings.json\");\n\t}\n\treturn join(homedir(), \".lunr\", \"agent\", \"settings.json\");\n}\n\n// ---------------------------------------------------------------------------\n// lunR customize bridge for persisted thinking-block visibility.\n// When the bridge is present (TUI / gateway sessions), reads/writes go through\n// SettingsManager (lockfile + merge). Falls back to direct file I/O when the\n// extension loads in a context without the bridge (e.g. upstream pi).\n// ---------------------------------------------------------------------------\ninterface CustomizeBridge {\n\tgetHideThinkingBlock(): boolean;\n\tsetHideThinkingBlock(hide: boolean): void;\n}\n\nfunction getCustomizeBridge(): CustomizeBridge | undefined {\n\treturn (globalThis as Record<symbol, unknown>)[Symbol.for(\"@lunr/customize\")] as CustomizeBridge | undefined;\n}\n\n/** Returns the persisted `hideThinkingBlock` value (default false, matching\n * `getHideThinkingBlock()` which returns `this.settings.hideThinkingBlock ?? false`).\n * Never throws — on any error (missing file, bad JSON) returns false. */\nfunction readHideThinkingBlock(): boolean {\n\tconst bridge = getCustomizeBridge();\n\tif (bridge) return bridge.getHideThinkingBlock();\n\ttry {\n\t\tconst p = agentSettingsPath();\n\t\tif (!existsSync(p)) return false;\n\t\tconst cfg = JSON.parse(readFileSync(p, \"utf8\")) as { hideThinkingBlock?: boolean };\n\t\treturn cfg.hideThinkingBlock === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Persist `hideThinkingBlock` to the global agent settings file (safe merge).\n *\n * - Preserves all other keys (merge, never overwrite the whole file).\n * - Matches pi's 2-space indentation + trailing newline.\n * - On invalid JSON in the existing file, backs it up to `settings.json.bak`\n * before writing a fresh file, so a corrupted file is never written back.\n * - Never throws; on any error `ok` is false and the caller notifies the user.\n *\n * `createdFresh` is true when the file didn't exist (or was corrupt and backed\n * up) before this write — the handler uses it to warn that a global settings\n * file was created here.\n */\nfunction writeHideThinkingBlock(hide: boolean): {\n\tok: boolean;\n\tcreatedFresh: boolean;\n} {\n\tconst bridge = getCustomizeBridge();\n\tif (bridge) {\n\t\ttry {\n\t\t\tbridge.setHideThinkingBlock(hide);\n\t\t\treturn { ok: true, createdFresh: false };\n\t\t} catch {\n\t\t\treturn { ok: false, createdFresh: false };\n\t\t}\n\t}\n\ttry {\n\t\tconst p = agentSettingsPath();\n\t\tlet cfg: Record<string, unknown> = {};\n\t\tlet createdFresh = false;\n\t\tif (existsSync(p)) {\n\t\t\ttry {\n\t\t\t\tcfg = JSON.parse(readFileSync(p, \"utf8\")) as Record<string, unknown>;\n\t\t\t} catch {\n\t\t\t\t// Existing file is corrupt — back it up, then start fresh.\n\t\t\t\ttry {\n\t\t\t\t\trenameSync(p, `${p}.bak`);\n\t\t\t\t} catch {\n\t\t\t\t\t// If backup fails, still proceed to overwrite (best effort).\n\t\t\t\t}\n\t\t\t\tcfg = {};\n\t\t\t\tcreatedFresh = true;\n\t\t\t}\n\t\t} else {\n\t\t\tcreatedFresh = true;\n\t\t}\n\t\tcfg.hideThinkingBlock = hide;\n\t\twriteFileSync(p, JSON.stringify(cfg, null, 2) + \"\\n\", \"utf8\");\n\t\treturn { ok: true, createdFresh };\n\t} catch {\n\t\treturn { ok: false, createdFresh: false };\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Extension entry point\n// ---------------------------------------------------------------------------\n\nconst THINKING_COMMAND_DESCRIPTION =\n\t\"View or set the reasoning level for the current model, or toggle thinking-block visibility with show/hide/toggle\";\n\nexport default function (pi: ExtensionAPI): void {\n\tconst thinkingSpec = {\n\t\tdescription: THINKING_COMMAND_DESCRIPTION,\n\t\tgetArgumentCompletions(prefix: string): AutocompleteItem[] {\n\t\t\tconst lower = prefix.toLowerCase();\n\t\t\t// Visibility sub-options first, filtered by prefix, alongside the levels.\n\t\t\tconst visibility: AutocompleteItem[] = [\n\t\t\t\t{ value: \"show\", label: \"show\", description: \"Show thinking blocks (persisted to settings.json)\" },\n\t\t\t\t{ value: \"hide\", label: \"hide\", description: \"Hide thinking blocks (persisted to settings.json)\" },\n\t\t\t\t{ value: \"toggle\", label: \"toggle\", description: \"Toggle thinking blocks (persisted to settings.json)\" },\n\t\t\t];\n\t\t\tconst levels = availableLevelsFor(currentModel(pi));\n\t\t\tconst levelItems = levels\n\t\t\t\t.filter((lvl) => lvl.startsWith(lower))\n\t\t\t\t.map((lvl) => ({ value: lvl, label: lvl, description: THINKING_DESCRIPTIONS[lvl] }));\n\t\t\treturn [\n\t\t\t\t...visibility.filter((v) => v.value.startsWith(lower)),\n\t\t\t\t...levelItems,\n\t\t\t];\n\t\t},\n\t\thandler: async (args: string, ctx: ExtensionCommandContextLike) => {\n\t\t\tconst trimmed = args.trim();\n\t\t\tconst lower = trimmed.toLowerCase();\n\n\t\t\t// ---- Visibility sub-options: /thinking show | hide | toggle ----\n\t\t\t// Caught first so `hide`/`show`/`toggle` are never parsed as levels.\n\t\t\t// Works in every mode: only uses ctx.ui.notify + file I/O + ctx.reload().\n\t\t\tif (lower === \"show\" || lower === \"hide\" || lower === \"toggle\") {\n\t\t\t\tconst current = readHideThinkingBlock();\n\t\t\t\tconst next = lower === \"toggle\" ? !current : lower === \"hide\";\n\t\t\t\tif (next === current) {\n\t\t\t\t\tctx.ui.notify(`Thinking blocks already ${current ? \"hidden\" : \"shown\"}.`, \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst result = writeHideThinkingBlock(next);\n\t\t\t\tif (!result.ok) {\n\t\t\t\t\t// lunr: settings path is lunR's (see agentSettingsPath).\n\t\t\t\t\tctx.ui.notify(`Failed to update ${agentSettingsPath()}`, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// The notify MUST run before `await ctx.reload()`: after reload the\n\t\t\t\t// loader invalidates this `ctx`/`pi` as stale. ctx.reload() live-\n\t\t\t\t// applies the setting (verified against pi 0.80.3: it drives\n\t\t\t\t// session.reload() → settingsManager.reload() re-reads disk →\n\t\t\t\t// restoreChatBeforeSessionStart copies the new value into\n\t\t\t\t// this.hideThinkingBlock → rebuildChatFromMessages() rebuilds every\n\t\t\t\t// AssistantMessageComponent with the new hide flag). In non-TUI\n\t\t\t\t// modes ctx.reload() is a no-op; the setting then applies on next\n\t\t\t\t// start. The instant keybinding path (Ctrl+T) also still works.\n\t\t\t\tconst verb = next ? \"hidden\" : \"shown\";\n\t\t\t\tconst note = result.createdFresh\n\t\t\t\t\t? `Thinking blocks ${verb}. (Created ${agentSettingsPath()} with this setting.)`\n\t\t\t\t\t: `Thinking blocks ${verb}.`;\n\t\t\t\tctx.ui.notify(note, \"info\");\n\t\t\t\tawait ctx.reload();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst levels = availableLevelsFor(ctx.model);\n\t\t\tconst currentLevel: ThinkingLevel = pi.getThinkingLevel();\n\t\t\tconst validSet = new Set<ThinkingLevel>(levels);\n\n\t\t\t// No-arg form → open a picker. Skip in non-TUI modes — same pattern\n\t\t\t// as batxj-animations per AGENTS.md §5.\n\t\t\tif (trimmed === \"\") {\n\t\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\t\tctx.ui.notify(`Thinking level: ${currentLevel}`, \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (levels.length === 0) {\n\t\t\t\t\tctx.ui.notify(\"No thinking levels available for this model.\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst options = levels.map((lvl) =>\n\t\t\t\t\t(lvl === currentLevel ? \"\\u25CF \" : \" \") + formatLevelLabel(lvl),\n\t\t\t\t);\n\t\t\t\tconst chosen = await ctx.ui.select(\n\t\t\t\t\t`Thinking level (current: ${currentLevel})`,\n\t\t\t\t\toptions,\n\t\t\t\t);\n\t\t\t\tif (chosen === undefined) return;\n\t\t\t\t// Chosen string starts with the current-marker (\"● \") or two-space\n\t\t\t\t// gutter; strip the prefix and extract the first token (the level).\n\t\t\t\tconst stripped = chosen.replace(/^[\\u25CF ]\\s?/, \"\").trimStart();\n\t\t\t\tconst level = stripped.split(/\\s+/)[0] as ThinkingLevel;\n\t\t\t\tif (!validSet.has(level)) {\n\t\t\t\t\tctx.ui.notify(`Unsupported thinking level: ${level}`, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (level === currentLevel) return; // no-op\n\t\t\t\tpi.setThinkingLevel(level);\n\t\t\t\tctx.ui.notify(`Thinking level: ${pi.getThinkingLevel()}`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Direct-set form: `/thinking <level>`\n\t\t\tconst requested = trimmed.toLowerCase() as ThinkingLevel;\n\t\t\tif (!validSet.has(requested)) {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t`Invalid thinking level: \"${trimmed}\". Valid: ${levels.join(\", \")}`,\n\t\t\t\t\t\"error\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (requested === currentLevel) {\n\t\t\t\tctx.ui.notify(`Thinking level: ${requested} (unchanged)`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpi.setThinkingLevel(requested);\n\t\t\tctx.ui.notify(`Thinking level: ${pi.getThinkingLevel()}`, \"info\");\n\t\t},\n\t};\n\n\tpi.registerCommand(\"thinking\", thinkingSpec);\n\t// lunr: /effort and /reasoning are full-parity aliases (same handler + completions).\n\tpi.registerCommand(\"effort\", {\n\t\t...thinkingSpec,\n\t\tdescription: `${THINKING_COMMAND_DESCRIPTION} (alias of /thinking)`,\n\t});\n\tpi.registerCommand(\"reasoning\", {\n\t\t...thinkingSpec,\n\t\tdescription: `${THINKING_COMMAND_DESCRIPTION} (alias of /thinking)`,\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Read the current model from the ExtensionAPI runtime. The spec mentions\n * `pi.getModel()`; pi doesn't expose that name on the API object itself, but\n * the bound `ExtensionContextActions` (which the runtime decorates onto\n * events) does include `getModel()`. We duck-type against the loader so this\n * file stays decoupled from non-public internals. When unavailable (e.g.\n * during autocomplete, before any session has bound), returns undefined and\n * the caller falls back to the default 5-level set.\n */\nfunction currentModel(pi: ExtensionAPI): ModelLike | undefined {\n\tconst fn = (pi as unknown as { getModel?: () => unknown }).getModel;\n\tif (typeof fn === \"function\") {\n\t\treturn fn.call(pi) as ModelLike | undefined;\n\t}\n\treturn undefined;\n}\n"]}
@@ -31,6 +31,10 @@
31
31
  * under vite-node (`Class extends value undefined`).
32
32
  */
33
33
  type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
34
+ /** Theme token for the chatbox thinking-level border / effort chip. */
35
+ export declare function thinkingThemeToken(level: ThinkingLevel): string;
36
+ /** Chip effort label — identity, locked so xhigh/max are never mapped down to high. */
37
+ export declare function formatChipEffort(level: ThinkingLevel): string;
34
38
  /** Trimmed view of pi's `Theme` — only the methods we use. */
35
39
  interface Theme {
36
40
  fg(token: string, text: string): string;
@@ -1 +1 @@
1
- {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C;IAC5C,EAAE,EAAE,sBAAsB,CAAC;CAC3B;AAED,sCAAsC;AACtC,UAAU,YAAY;IACrB,gBAAgB,IAAI,aAAa,CAAC;IAClC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,oBAAoB,KAAK,IAAI,GAAG,IAAI,CAAC;CACtF;AAED,0CAA0C;AAC1C,KAAK,iBAAiB,GAAG,CACxB,GAAG,EAAE,SAAS,EACd,KAAK,EAAE,eAAe,EACtB,WAAW,EAAE,eAAe,KACxB,mBAAmB,CAAC;AAEzB,UAAU,mBAAmB;IAC5B,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAChC,OAAO,IAAI,MAAM,CAAC;IAClB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,UAAU,IAAI,IAAI,CAAC;IACnB,WAAW,CAAC,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;CACjC;AAED,iCAAiC;AACjC,KAAK,iBAAiB,GAAG,CACxB,GAAG,EAAE,SAAS,EACd,KAAK,EAAE,KAAK,EACZ,UAAU,EAAE,0BAA0B,KAClC,mBAAmB,CAAC;AAEzB,UAAU,mBAAmB;IAC5B,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAChC,OAAO,CAAC,IAAI,IAAI,CAAC;IACjB,UAAU,CAAC,IAAI,IAAI,CAAC;CACpB;AA4eD,MAAM,CAAC,OAAO,WAAW,EAAE,EAAE,YAAY,GAAG,IAAI,CA+C/C","sourcesContent":["/**\n * ashxj-tui — a custom slim chatbox for pi.\n *\n * Replaces pi-zentui's prompt box + statusline with:\n * - A rounded prompt box that auto-expands as the typed message wraps to\n * multiple rows (the sides extend; height grows with content).\n * - A right-aligned chip on the box's BOTTOM border:\n * model · provider · effort (e.g. `glm-5.2 · Ollama Cloud · xhigh`)\n * - A slim stats line (extension statuses · context% · ↑↓; each segment\n * toggle-gated via the lunr customize bridge) BELOW the box, not wrapped\n * around the input.\n * - No session-mode indicator anywhere (pi has no such concept).\n *\n * Loaded by pi via jiti — no build step, plain TypeScript.\n *\n * NOTE on type imports (see `ashxj-thinking`/`simple-memory` for the convention):\n * This file declares structural types inline rather than importing them from\n * `@ashx-j/lunr` / `@ashx-j/lunr-tui`.\n * pi-coding-agent's `index.d.ts` re-exports from internal `.d.ts` files that\n * contain subpath imports like `@ashx-j/lunr-ai/compat`, which do not\n * resolve under `tsc` with a file argument. We keep the typecheck\n * self-contained with inline types and verify via the included `tsconfig.json`\n * (`moduleResolution: \"Bundler\"` + `skipLibCheck: true`).\n *\n * The ONE exception is `CustomEditor`, imported as a RUNTIME VALUE directly\n * from its defining module (`modes/interactive/components/custom-editor.ts`).\n * We must `extends` it to inherit pi's app keybindings (escape, ctrl+d, model\n * switching, extension shortcuts) — wrapping would lose those. It is imported\n * from the concrete module, NOT the package barrel, because the barrel\n * re-exports main.ts which imports this file — a circular import that crashes\n * under vite-node (`Class extends value undefined`).\n */\n\nimport { CustomEditor } from \"../modes/interactive/components/custom-editor.js\";\n\n// lunr: customize bridge — read the prompt-symbol toggle (bridgeless → no symbol).\nconst PROMPT_SYMBOL_BRIDGE = Symbol.for(\"@lunr/customize\");\nconst PERMISSION_MODE_BRIDGE = Symbol.for(\"@lunr/permission-mode\");\ninterface CustomizeBridgeForPrompt {\n\tgetPromptSymbol(): boolean;\n\t// lunr: footer element toggles (added to the same bridge).\n\tgetFooterMcp?(): boolean;\n\tgetFooterLsp?(): boolean;\n\tgetFooterContext?(): boolean;\n\tgetFooterTokens?(): boolean;\n\tgetFooterStatuses?(): boolean;\n}\ninterface PermissionModeBridgeForFooter {\n\tgetMode(): string | undefined;\n}\nfunction lunrCustomizeBridge(): CustomizeBridgeForPrompt | undefined {\n\treturn (globalThis as Record<symbol, unknown>)[PROMPT_SYMBOL_BRIDGE] as CustomizeBridgeForPrompt | undefined;\n}\nfunction lunrPermissionModeBridge(): PermissionModeBridgeForFooter | undefined {\n\treturn (globalThis as Record<symbol, unknown>)[PERMISSION_MODE_BRIDGE] as PermissionModeBridgeForFooter | undefined;\n}\nfunction lunrPromptSymbolEnabled(): boolean {\n\treturn lunrCustomizeBridge()?.getPromptSymbol() ?? false;\n}\n// lunr: footer toggles, read at render time. Bridgeless / missing-getter fallback\n// matches the settings-manager defaults: MCP on, LSP off, everything else on.\nfunction lunrFooterToggles(): { mcp: boolean; lsp: boolean; context: boolean; tokens: boolean; statuses: boolean } {\n\tconst bridge = lunrCustomizeBridge();\n\treturn {\n\t\tmcp: bridge?.getFooterMcp?.() ?? true,\n\t\tlsp: bridge?.getFooterLsp?.() ?? false,\n\t\tcontext: bridge?.getFooterContext?.() ?? true,\n\t\ttokens: bridge?.getFooterTokens?.() ?? true,\n\t\tstatuses: bridge?.getFooterStatuses?.() ?? true,\n\t};\n}\n// lunr: permission mode for the footer safety indicator (always shown).\nfunction lunrPermissionMode(): string | undefined {\n\treturn lunrPermissionModeBridge()?.getMode();\n}\n// lunr: prompt glyph comes from the theme tokens `glyphs.promptMoon` /\n// `glyphs.promptArrow` (defaults below match moon.json). An empty token hides\n// that part; both empty = no glyph at all.\nfunction lunrPromptGlyph(theme: Theme | undefined): string {\n\tconst moon = theme?.glyph?.(\"promptMoon\") ?? \"☾\";\n\tconst arrow = theme?.glyph?.(\"promptArrow\") ?? \">\";\n\tconst parts = [moon, arrow].filter((s) => s !== \"\");\n\treturn parts.length > 0 ? `${parts.join(\" \")} ` : \"\";\n}\n\n// ---------------------------------------------------------------------------\n// Minimal structural types (inline — see file header)\n// ---------------------------------------------------------------------------\n\ntype ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/** Trimmed view of pi's `Theme` — only the methods we use. */\ninterface Theme {\n\tfg(token: string, text: string): string;\n\t/** lunr: prompt glyph tokens (optional for forward/backward compat). */\n\tglyph?(name: \"promptMoon\" | \"promptArrow\"): string;\n}\n\n/** Trimmed view of `pi-tui`'s `TUI` — only the method we use. */\ninterface TUIHandle {\n\trequestRender(force?: boolean): void;\n}\n\n/** Trimmed view of `pi-tui`'s `EditorTheme`. */\ninterface EditorThemeLike {\n\tborderColor: (str: string) => string;\n\tselectList: unknown;\n}\n\n/** Opaque keybindings manager. */\ninterface KeybindingsLike {\n\treadonly _?: unknown;\n}\n\n/** Trimmed view of an autocomplete list (the editor's private `autocompleteList`). */\ninterface AutocompleteListLike {\n\trender(width: number): string[];\n}\n\n/** Trimmed view of pi's `ReadonlyFooterDataProvider`. */\ninterface ReadonlyFooterDataProvider {\n\tgetGitBranch(): string | null;\n\tgetExtensionStatuses(): ReadonlyMap<string, string>;\n\tgetAvailableProviderCount(): number;\n\tonBranchChange(callback: () => void): () => void;\n}\n\n/** Trimmed view of the `getContextUsage` return value. */\ninterface ContextUsage {\n\ttokens: number | null;\n\tcontextWindow: number;\n\tpercent: number | null;\n}\n\n/** Trimmed view of an assistant message's usage — the bits we render. */\ninterface AssistantUsage {\n\tinput: number;\n\toutput: number;\n\tcost: { total: number };\n}\n\n/** Trimmed view of an assistant message. */\ninterface AssistantMessageLike {\n\trole: \"assistant\";\n\tusage: AssistantUsage;\n}\n\n/** Trimmed view of a session entry — only what we iterate over. */\ntype SessionEntry =\n\t| { type: \"message\"; message: AssistantMessageLike }\n\t| { type: string; message?: unknown };\n\n/** Trimmed view of a `ReadonlySessionManager`. */\ninterface ReadonlySessionManagerLike {\n\tgetEntries(): readonly SessionEntry[];\n\tgetBranch?(): readonly SessionEntry[];\n}\n\n/** Trimmed view of a `Model`. */\ninterface ModelLike {\n\tid?: string;\n\tprovider?: string;\n\tcontextWindow?: number;\n\treasoning?: boolean;\n\tthinkingLevelMap?: Record<string, string | null>;\n}\n\ninterface ExtensionUIContextLike {\n\tsetEditorComponent(factory: EditorFactoryLike | undefined): void;\n\tsetFooter(factory: FooterFactoryLike | undefined): void;\n\treadonly theme?: Theme;\n}\n\n/** Trimmed view of `ExtensionContext`. */\ninterface ExtensionContextLike {\n\tmode: \"tui\" | \"rpc\" | \"json\" | \"print\";\n\thasUI: boolean;\n\tmodel: ModelLike | undefined;\n\tsessionManager: ReadonlySessionManagerLike;\n\tgetContextUsage(): ContextUsage | undefined;\n\tui: ExtensionUIContextLike;\n}\n\n/** Trimmed view of `ExtensionAPI`. */\ninterface ExtensionAPI {\n\tgetThinkingLevel(): ThinkingLevel;\n\ton(event: string, handler: (event: unknown, ctx: ExtensionContextLike) => void): void;\n}\n\n/** `setEditorComponent` factory shape. */\ntype EditorFactoryLike = (\n\ttui: TUIHandle,\n\ttheme: EditorThemeLike,\n\tkeybindings: KeybindingsLike,\n) => EditorComponentLike;\n\ninterface EditorComponentLike {\n\trender(width: number): string[];\n\tgetText(): string;\n\tsetText(text: string): void;\n\tinvalidate(): void;\n\thandleInput?(data: string): void;\n}\n\n/** `setFooter` factory shape. */\ntype FooterFactoryLike = (\n\ttui: TUIHandle,\n\ttheme: Theme,\n\tfooterData: ReadonlyFooterDataProvider,\n) => FooterComponentLike;\n\ninterface FooterComponentLike {\n\trender(width: number): string[];\n\tdispose?(): void;\n\tinvalidate?(): void;\n}\n\n// ---------------------------------------------------------------------------\n// Display-width helpers (ANSI-aware; CJK-aware)\n//\n// The editor (`Editor.render`) word-wraps to the given width using grapheme\n// width, so each returned line is ≤ that many visual columns. To right-pad a\n// line for our box we need a width model that matches closely enough: skip ALL\n// escape sequences (SGR color, OSC/DCS/APC/PM/SOS string sequences such as\n// pi-tui's `CURSOR_MARKER` `ESC _pi:c BEL`, and two-char escapes), count common\n// East-Asian wide ranges as 2, combining marks and variation selectors as 0.\n// Handling the string sequences as 0-width is what keeps the right `│` rail\n// aligned on the focused (cursor) line — the base editor embeds the marker and\n// the TUI strips it at flush time, so we must not count it here.\n// ---------------------------------------------------------------------------\n\nfunction skipAnsi(str: string, pos: number): number {\n\tif (str.charCodeAt(pos) !== 0x1b) return 0;\n\tconst next = str.charCodeAt(pos + 1);\n\t// CSI: ESC [ ... <final 0x40-0x7e>\n\tif (next === 0x5b /* [ */) {\n\t\tlet j = pos + 2;\n\t\twhile (j < str.length) {\n\t\t\tconst c = str.charCodeAt(j);\n\t\t\tif (c >= 0x40 && c <= 0x7e) return j + 1 - pos;\n\t\t\tj++;\n\t\t}\n\t\treturn str.length - pos; // unterminated; consume the rest\n\t}\n\t// String sequences — OSC (]), DCS (P), APC (_), PM (^), SOS (X) — terminated\n\t// by BEL (0x07) or ST (ESC \\). pi-tui's CURSOR_MARKER `ESC _pi:c BEL` is APC;\n\t// OSC color queries are OSC. All are zero visual width.\n\tif (\n\t\tnext === 0x5d /* ] */ ||\n\t\tnext === 0x50 /* P */ ||\n\t\tnext === 0x5f /* _ */ ||\n\t\tnext === 0x5e /* ^ */ ||\n\t\tnext === 0x58 /* X */\n\t) {\n\t\tlet j = pos + 2;\n\t\twhile (j < str.length) {\n\t\t\tconst c = str.charCodeAt(j);\n\t\t\tif (c === 0x07 /* BEL */) return j + 1 - pos;\n\t\t\tif (c === 0x1b && str.charCodeAt(j + 1) === 0x5c /* \\ */) return j + 2 - pos;\n\t\t\tj++;\n\t\t}\n\t\treturn str.length - pos; // unterminated; consume the rest\n\t}\n\t// Any other ESC sequence: consume ESC + one final byte (e.g. ESC c, ESC \\,\n\t// ESC ( B). A lone trailing ESC with no following byte is 0 width too.\n\treturn Number.isNaN(next) ? 1 : 2;\n}\n\nfunction isWide(cp: number): boolean {\n\treturn (\n\t\t(cp >= 0x1100 && cp <= 0x115f) ||\n\t\t(cp >= 0x2e80 && cp <= 0x303e) ||\n\t\t(cp >= 0x3041 && cp <= 0x33ff) ||\n\t\t(cp >= 0x3400 && cp <= 0x4dbf) ||\n\t\t(cp >= 0x4e00 && cp <= 0x9fff) ||\n\t\t(cp >= 0xa000 && cp <= 0xa4cf) ||\n\t\t(cp >= 0xac00 && cp <= 0xd7a3) ||\n\t\t(cp >= 0xf900 && cp <= 0xfaff) ||\n\t\t(cp >= 0xfe30 && cp <= 0xfe4f) ||\n\t\t(cp >= 0xff00 && cp <= 0xff60) ||\n\t\t(cp >= 0xffe0 && cp <= 0xffe6) ||\n\t\t(cp >= 0x1f300 && cp <= 0x1faff) ||\n\t\t(cp >= 0x20000 && cp <= 0x3fffd)\n\t);\n}\n\nfunction charWidth(cp: number): number {\n\tif (cp >= 0x20 && cp < 0x7f) return 1;\n\tif ((cp >= 0x0300 && cp <= 0x036f) || (cp >= 0xfe00 && cp <= 0xfe0f) || cp === 0x200d) return 0;\n\treturn isWide(cp) ? 2 : 1;\n}\n\n/** Visible width of a string, ignoring SGR color codes. */\nfunction displayWidth(str: string): number {\n\tlet w = 0;\n\tlet i = 0;\n\twhile (i < str.length) {\n\t\tconst skip = skipAnsi(str, i);\n\t\tif (skip > 0) {\n\t\t\ti += skip;\n\t\t\tcontinue;\n\t\t}\n\t\tconst cp = str.codePointAt(i) ?? 0;\n\t\tw += charWidth(cp);\n\t\ti += cp > 0xffff ? 2 : 1;\n\t}\n\treturn w;\n}\n\n/** Right-pad a (possibly colored) line to `width` visible columns. */\nfunction padRight(line: string, width: number): string {\n\tconst w = displayWidth(line);\n\tif (w >= width) return line;\n\treturn line + \" \".repeat(width - w);\n}\n\n/** Truncate a plain (non-ANSI) string to `maxWidth` visible columns. */\nfunction truncatePlain(text: string, maxWidth: number): string {\n\tif (maxWidth <= 0) return \"\";\n\tif (displayWidth(text) <= maxWidth) return text;\n\tlet out = \"\";\n\tlet w = 0;\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tconst code = text.codePointAt(i) ?? 0;\n\t\tconst cw = charWidth(code);\n\t\tif (w + cw > maxWidth) break;\n\t\tout += String.fromCodePoint(code);\n\t\tw += cw;\n\t\ti += code > 0xffff ? 2 : 1;\n\t}\n\treturn out;\n}\n\n/** Truncate a (possibly ANSI-colored) string to `maxWidth` visible columns,\n * re-emitting an SGR reset at the cut so styling doesn't bleed. */\nfunction truncateToWidth(text: string, maxWidth: number, ellipsis = \"\"): string {\n\tif (maxWidth <= 0) return \"\";\n\tif (displayWidth(text) <= maxWidth) return text;\n\tconst target = Math.max(0, maxWidth - displayWidth(ellipsis));\n\tlet out = \"\";\n\tlet w = 0;\n\tlet i = 0;\n\twhile (i < text.length && w < target) {\n\t\tconst skip = skipAnsi(text, i);\n\t\tif (skip > 0) {\n\t\t\tout += text.slice(i, i + skip);\n\t\t\ti += skip;\n\t\t\tcontinue;\n\t\t}\n\t\tconst code = text.codePointAt(i) ?? 0;\n\t\tconst cw = charWidth(code);\n\t\tif (w + cw > target) break;\n\t\tout += String.fromCodePoint(code);\n\t\tw += cw;\n\t\ti += code > 0xffff ? 2 : 1;\n\t}\n\tout += \"\\x1b[0m\";\n\treturn out + ellipsis;\n}\n\n/** Clamp each rendered line to `width` visible columns (fallback path). */\nfunction clampLines(lines: string[], width: number): string[] {\n\treturn lines.map((l) => (displayWidth(l) > width ? truncateToWidth(l, width, \"\") : l));\n}\n\n/** Apply a theme `fg` token safely; falls back to plain text. */\nfunction color(theme: Theme | undefined, token: string, text: string): string {\n\ttry {\n\t\treturn theme?.fg?.(token, text) ?? text;\n\t} catch {\n\t\treturn text;\n\t}\n}\n\n// lunr: strip ANSI escape sequences so footer statuses can be re-colored uniformly.\nfunction stripAnsi(s: string): string {\n\treturn s.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n}\n\n// ---------------------------------------------------------------------------\n// Stats formatting\n// ---------------------------------------------------------------------------\n\n/** Compact token-count formatter: `999`, `1.2k`, `15k`, `1.2M`, `15M`.\n * Matches pi's FooterComponent / the captured zentui examples\n * (`↑9.0M ↓112k`, `20%/1.0M`). */\nfunction formatCount(count: number): string {\n\tif (count < 1000) return count.toString();\n\tif (count < 10000) return `${(count / 1000).toFixed(1)}k`;\n\tif (count < 1000000) return `${Math.round(count / 1000)}k`;\n\tif (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;\n\treturn `${Math.round(count / 1000000)}M`;\n}\n\n/** Sum input/output tokens across assistant messages in the session. */\nfunction getUsageTotals(ctx: ExtensionContextLike): { input: number; output: number } {\n\tlet input = 0;\n\tlet output = 0;\n\tconst entries = ctx.sessionManager.getEntries?.() ?? ctx.sessionManager.getBranch?.() ?? [];\n\tfor (const entry of entries as readonly SessionEntry[]) {\n\t\tif (entry.type !== \"message\") continue;\n\t\tconst m = entry.message as AssistantMessageLike | undefined;\n\t\tif (!m || m.role !== \"assistant\") continue;\n\t\tconst u = m.usage;\n\t\tif (!u) continue;\n\t\tinput += u.input ?? 0;\n\t\toutput += u.output ?? 0;\n\t}\n\treturn { input, output };\n}\n\n// ---------------------------------------------------------------------------\n// Provider display label\n//\n// `ctx.model.provider` is a ProviderId string (e.g. `\"ollama-cloud\"`), NOT the\n// human label. `BUILT_IN_PROVIDER_DISPLAY_NAMES` exists in pi core but is not\n// re-exported to extensions, so we derive the label (mirrors zentui's\n// `formatProviderLabel`, with an explicit `ollama-cloud` entry).\n// ---------------------------------------------------------------------------\n\nfunction formatProviderLabel(provider: string | undefined): string {\n\tif (!provider) return \"Unknown\";\n\tconst known: Record<string, string> = {\n\t\tanthropic: \"Anthropic\",\n\t\tgemini: \"Google\",\n\t\tgoogle: \"Google\",\n\t\tollama: \"Ollama\",\n\t\t\"ollama-cloud\": \"Ollama Cloud\",\n\t\topenai: \"OpenAI\",\n\t\t\"openai-codex\": \"OpenAI\",\n\t\tmistral: \"Mistral\",\n\t};\n\treturn (\n\t\tknown[provider] ??\n\t\tprovider.replace(/[-_]/g, \" \").replace(/\\b\\w/g, (c) => c.toUpperCase())\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// The chip: `model · provider · effort`\n// ---------------------------------------------------------------------------\n\nfunction buildChip(ctx: ExtensionContextLike, pi: ExtensionAPI): string {\n\tconst modelId = ctx.model?.id ?? \"no-model\";\n\tconst providerLabel = formatProviderLabel(ctx.model?.provider);\n\tconst effort = pi.getThinkingLevel();\n\treturn `${modelId} \\u00b7 ${providerLabel} \\u00b7 ${effort}`;\n}\n\n// ---------------------------------------------------------------------------\n// The prompt box — `ChatboxEditor extends CustomEditor`\n// ---------------------------------------------------------------------------\n\nclass ChatboxEditor extends CustomEditor {\n\tprivate readonly ctx: ExtensionContextLike;\n\tprivate readonly pi: ExtensionAPI;\n\n\tconstructor(\n\t\ttui: TUIHandle,\n\t\ttheme: EditorThemeLike,\n\t\tkeybindings: KeybindingsLike,\n\t\tctx: ExtensionContextLike,\n\t\tpi: ExtensionAPI,\n\t) {\n\t\t// CustomEditor ctor: (tui, theme, keybindings, options?: EditorOptions).\n\t\t// Casts keep the inline types from leaking into the real base signature.\n\t\tsuper(tui as unknown as never, theme as unknown as never, keybindings as unknown as never, {\n\t\t\tpaddingX: 0,\n\t\t});\n\t\tthis.ctx = ctx;\n\t\tthis.pi = pi;\n\t\t// `borderColor` is used internally by the base editor; route it through our\n\t\t// theme so any internal use stays consistent with the frame.\n\t\tthis.borderColor = (s: string) => this.color(\"border\", s);\n\t}\n\n\tprivate color(token: string, text: string): string {\n\t\treturn color(this.ctx.ui?.theme, token, text);\n\t}\n\n\toverride render(width: number): string[] {\n\t\t// Too narrow to draw a box — defer to the base editor, clamped.\n\t\tif (width <= 4) {\n\t\t\treturn clampLines(super.render(width), width);\n\t\t}\n\n\t\t// Rails: `│ ` (left) + ` │` (right) => 4 columns of chrome.\n\t\tconst promptSymbol = lunrPromptSymbolEnabled();\n\t\tconst glyph = lunrPromptGlyph(this.ctx.ui?.theme);\n\t\tconst glyphW = promptSymbol ? displayWidth(glyph) : 0;\n\t\tconst innerWidth = Math.max(1, width - 4 - glyphW);\n\t\tconst base = super.render(innerWidth);\n\n\t\t// The base editor appends the autocomplete menu lines (if any) to the END\n\t\t// of its render output. Split them off so the body sits inside the box and\n\t\t// the autocomplete renders BELOW the bottom border (preserves slash\n\t\t// commands). Mirrors zentui's `renderPolishedFrame`.\n\t\tconst showing = this.isShowingAutocomplete();\n\t\tconst acList = (this as unknown as { autocompleteList?: AutocompleteListLike }).autocompleteList;\n\t\tlet acCount = 0;\n\t\tif (showing && acList && typeof acList.render === \"function\") {\n\t\t\ttry {\n\t\t\t\tacCount = acList.render(innerWidth).length;\n\t\t\t} catch {\n\t\t\t\tacCount = 0;\n\t\t\t}\n\t\t}\n\n\t\t// `super.render` returns [base top ─ border, ...wrapped text lines, base\n\t\t// bottom ─ border, ...autocomplete lines] — the base editor draws its OWN\n\t\t// straight borders and (when active) appends the autocomplete menu. Split the\n\t\t// autocomplete off the end, then STRIP the base's first/last lines (its own\n\t\t// borders) so we don't render them a second time inside our rounded frame.\n\t\t// Mirrors zentui's `editorFrame.slice(1, -1)` (renderPolishedFrame).\n\t\tlet frame = base;\n\t\tlet acLines: string[] = [];\n\t\tif (acCount > 0 && acCount < frame.length) {\n\t\t\tacLines = frame.slice(frame.length - acCount);\n\t\t\tframe = frame.slice(0, frame.length - acCount);\n\t\t}\n\t\tconst inner = frame.length >= 2 ? frame.slice(1, frame.length - 1) : frame;\n\t\tconst body = inner.length > 0 ? inner : [\"\"];\n\n\t\tconst border = (s: string): string => this.color(\"border\", s);\n\n\t\t// Top border: ╭─…─╮\n\t\tconst top = border(\"\\u256d\" + \"\\u2500\".repeat(width - 2) + \"\\u256e\");\n\n\t\t// Body: │ <padded line> │ (auto-grows with the number of wrapped lines)\n\t\t// lunr: prefix the first body line with the dim theme prompt glyph (☾ > by\n\t\t// default); a same-width blank gutter keeps subsequent lines aligned.\n\t\tconst gutter = glyphW > 0 ? \" \".repeat(glyphW) : \"\";\n\t\tconst bodyLines = body.map((ln: string, i: number) => {\n\t\t\tconst prefix = i === 0 && glyphW > 0 ? this.color(\"dim\", glyph) : gutter;\n\t\t\treturn border(\"\\u2502 \") + prefix + padRight(ln, innerWidth) + border(\" \\u2502\");\n\t\t});\n\n\t\t// Bottom border with the right-aligned chip: ╰─…─ <chip> ─╯\n\t\tconst bottom = this.renderBottomBorder(width);\n\n\t\treturn [top, ...bodyLines, bottom, ...acLines];\n\t}\n\n\tprivate renderBottomBorder(width: number): string {\n\t\tconst border = (s: string): string => this.color(\"border\", s);\n\t\tlet chip = buildChip(this.ctx, this.pi);\n\t\tlet chipW = displayWidth(chip);\n\n\t\t// Overhead with zero dashes: ╰ + \" \" + chip + \" \" + ╯ => 4 columns.\n\t\tconst overhead = 4;\n\t\tif (chipW > width - overhead) {\n\t\t\tchip = truncatePlain(chip, Math.max(0, width - overhead));\n\t\t\tchipW = displayWidth(chip);\n\t\t}\n\t\tconst dashTotal = Math.max(0, width - overhead - chipW);\n\t\t// Right-align the chip: a single trailing dash before the corner, the\n\t\t// rest lead (right-aligns the chip near the corner).\n\t\tconst rightDashes = Math.min(dashTotal, 1);\n\t\tconst leftDashes = dashTotal - rightDashes;\n\n\t\tconst left = \"\\u2570\" + \"\\u2500\".repeat(leftDashes) + \" \";\n\t\tconst right = \" \" + \"\\u2500\".repeat(rightDashes) + \"\\u256f\";\n\t\treturn border(left) + this.color(\"white\", chip) + border(right); // lunr: theme-polish — model/provider/thinking chip white (was dim)\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// The stats line (footer) — slim, single line, BELOW the box\n// ---------------------------------------------------------------------------\n\nfunction renderStatsLine(\n\twidth: number,\n\tctx: ExtensionContextLike,\n\ttheme: Theme,\n\tfooterData: ReadonlyFooterDataProvider,\n): string[] {\n\tconst sep = color(theme, \"accent2\", \" | \"); // lunr: theme-polish — separator uses subtle accent2 blue (was bright-black plain fallback)\n\tconst parts: string[] = [];\n\n\t// lunr: mode zone — permission mode + agent-mode statuses (plan/goal/swarm/research)\n\t// render as ONE segment (dim middot-separated), not scattered across piped sections.\n\tconst modeZone: string[] = [];\n\n\t// lunr: permission mode safety indicator — always shown (not toggle-gated).\n\tconst mode = lunrPermissionMode();\n\tif (mode === \"yolo\" || mode === \"auto\") modeZone.push(color(theme, \"warning\", mode));\n\telse if (mode === \"manual\" || mode === \"plan\") modeZone.push(color(theme, \"white\", mode)); // lunr: theme-polish — manual/plan read white (was dim)\n\n\t// lunr: footer element toggles from the customize bridge (read at render time).\n\tconst footerToggles = lunrFooterToggles();\n\n\t// 1) Extension statuses published by other extensions (rendered as-is,\n\t// already styled): LSP (`pi-lsp-extension`), MCP (`pi-mcp-adapter`),\n\t// throughput/tokens (`pi-tps-was-taken`). These are NOT on `ctx` directly.\n\tconst statuses = footerData.getExtensionStatuses?.();\n\tif (statuses && statuses.size > 0) {\n\t\t// lunr: status segments are toggle-gated via the customize bridge:\n\t\t// footerStatuses gates plan/goal/swarm/research/tps, footerMcp gates\n\t\t// mcp/mcp-auth, footerLsp gates lsp. Publishers keep calling\n\t\t// ctx.ui.setStatus harmlessly when their segment is hidden.\n\t\t// lunr: plan/goal/swarm/research join the mode zone; tps/mcp/lsp stay piped.\n\t\tconst modeKeys: string[] = footerToggles.statuses ? [\"plan\", \"goal\", \"swarm\", \"research\"] : [];\n\t\tfor (const key of modeKeys) {\n\t\t\tconst v = statuses.get(key);\n\t\t\tif (v) modeZone.push(color(theme, \"white\", stripAnsi(v)));\n\t\t}\n\t\tconst pipedKeys: string[] = [];\n\t\tif (footerToggles.statuses) pipedKeys.push(\"tps\");\n\t\tif (footerToggles.mcp) pipedKeys.push(\"mcp\", \"mcp-auth\");\n\t\tif (footerToggles.lsp) pipedKeys.push(\"lsp\");\n\t\tfor (const key of pipedKeys) {\n\t\t\tconst v = statuses.get(key);\n\t\t\t// lunr: unify footer status colors (white, was dim) so the whole stats line reads as one tone.\n\t\t\tif (v) parts.push(color(theme, \"white\", stripAnsi(v))); // lunr: theme-polish — status segments white (was dim)\n\t\t}\n\t}\n\tif (modeZone.length > 0) {\n\t\tparts.unshift(modeZone.join(color(theme, \"dim\", \" · \")));\n\t}\n\n\t// 2) Context usage: `pct/window` (lunr: gated on footerContext).\n\tif (footerToggles.context) {\n\t\tconst usage = ctx.getContextUsage();\n\t\tconst win = ctx.model?.contextWindow ?? usage?.contextWindow ?? 0;\n\t\tconst pct = usage?.percent == null ? \"?\" : `${Math.round(usage.percent)}%`;\n\t\tconst ctxSeg = `${pct}/${formatCount(win)}`;\n\t\tconst pv = usage?.percent ?? 0;\n\t\tif (pv > 90) parts.push(color(theme, \"error\", ctxSeg));\n\t\telse if (pv > 70) parts.push(color(theme, \"warning\", ctxSeg));\n\t\telse parts.push(color(theme, \"white\", ctxSeg)); // lunr: theme-polish — normal context % white (was dim)\n\t}\n\n\t// 3) Token totals: ↑in ↓out (lunr: gated on footerTokens).\n\tif (footerToggles.tokens) {\n\t\tconst totals = getUsageTotals(ctx);\n\t\tparts.push(color(theme, \"white\", `\\u2191${formatCount(totals.input)} \\u2193${formatCount(totals.output)}`)); // lunr: theme-polish — token totals white (was dim)\n\t}\n\n\t// lunr: cost/usage counter segment removed entirely (both the $x.xxx dollar\n\t// counter for API-key providers and the plan-usage limit bar for OAuth/subscription\n\t// providers). Segments 1-3 (statuses, context, tokens) remain.\n\n\tlet line = parts.join(sep);\n\tif (displayWidth(line) > width) {\n\t\tline = truncateToWidth(line, width, \"\");\n\t}\n\treturn [line];\n}\n\n// ---------------------------------------------------------------------------\n// Install / teardown\n// ---------------------------------------------------------------------------\n\nfunction installEditor(\n\tctx: ExtensionContextLike,\n\tpi: ExtensionAPI,\n\tsetRequestor: (r: () => void) => void,\n): void {\n\tif (typeof ctx.ui.setEditorComponent !== \"function\") return;\n\tconst factory: EditorFactoryLike = (tui, _theme, _keybindings) => {\n\t\tsetRequestor(() => {\n\t\t\ttry {\n\t\t\t\ttui.requestRender();\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t});\n\t\treturn new ChatboxEditor(tui, _theme, _keybindings, ctx, pi);\n\t};\n\tctx.ui.setEditorComponent(factory);\n}\n\nfunction installFooter(\n\tctx: ExtensionContextLike,\n\tsetRequestor: (r: () => void) => void,\n): void {\n\tif (typeof ctx.ui.setFooter !== \"function\") return;\n\tlet disposed = false;\n\tconst factory: FooterFactoryLike = (tui, _theme, _footerData) => {\n\t\tsetRequestor(() => {\n\t\t\ttry {\n\t\t\t\ttui.requestRender();\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t});\n\t\treturn {\n\t\t\tinvalidate(): void {\n\t\t\t\t// render is pure\n\t\t\t},\n\t\t\tdispose(): void {\n\t\t\t\tdisposed = true;\n\t\t\t},\n\t\t\trender(width: number): string[] {\n\t\t\t\tif (disposed) return [];\n\t\t\t\treturn renderStatsLine(width, ctx, _theme, _footerData);\n\t\t\t},\n\t\t};\n\t};\n\tctx.ui.setFooter(factory);\n}\n\n// ---------------------------------------------------------------------------\n// Extension entry point\n// ---------------------------------------------------------------------------\n\nexport default function (pi: ExtensionAPI): void {\n\tlet renderRequestor: (() => void) | undefined = undefined;\n\tconst requestRender = (): void => {\n\t\ttry {\n\t\t\trenderRequestor?.();\n\t\t} catch {\n\t\t\t/* ignore */\n\t\t}\n\t};\n\n\tpi.on(\"session_start\", (_event, ctx) => {\n\t\tif (!ctx.hasUI || ctx.mode !== \"tui\") return;\n\t\tinstallEditor(ctx, pi, (r) => {\n\t\t\trenderRequestor = r;\n\t\t});\n\t\tinstallFooter(ctx, (r) => {\n\t\t\tif (!renderRequestor) renderRequestor = r;\n\t\t});\n\t});\n\n\tpi.on(\"session_shutdown\", (_event, ctx) => {\n\t\ttry {\n\t\t\tif (typeof ctx.ui?.setEditorComponent === \"function\") ctx.ui.setEditorComponent(undefined);\n\t\t} catch {\n\t\t\t/* ignore */\n\t\t}\n\t\ttry {\n\t\t\tif (typeof ctx.ui?.setFooter === \"function\") ctx.ui.setFooter(undefined);\n\t\t} catch {\n\t\t\t/* ignore */\n\t\t}\n\t\trenderRequestor = undefined;\n\t});\n\n\t// Re-render triggers: model/provider + effort (chip), and token/cost/context\n\t// (stats line). Event names match those zentui wires.\n\tconst reRenderEvents = [\n\t\t\"model_select\",\n\t\t\"thinking_level_select\",\n\t\t\"agent_end\",\n\t\t\"message_end\",\n\t\t\"tool_execution_end\",\n\t\t\"session_compact\",\n\t];\n\tfor (const ev of reRenderEvents) {\n\t\tpi.on(ev, () => requestRender());\n\t}\n}"]}
1
+ {"version":3,"file":"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\n * - A rounded prompt box that auto-expands as the typed message wraps to\n * multiple rows (the sides extend; height grows with content).\n * - A right-aligned chip on the box's BOTTOM border:\n * model · provider · effort (e.g. `glm-5.2 · Ollama Cloud · xhigh`)\n * - A slim stats line (extension statuses · context% · ↑↓; each segment\n * toggle-gated via the lunr customize bridge) BELOW the box, not wrapped\n * around the input.\n * - No session-mode indicator anywhere (pi has no such concept).\n *\n * Loaded by pi via jiti — no build step, plain TypeScript.\n *\n * NOTE on type imports (see `ashxj-thinking`/`simple-memory` for the convention):\n * This file declares structural types inline rather than importing them from\n * `@ashx-j/lunr` / `@ashx-j/lunr-tui`.\n * pi-coding-agent's `index.d.ts` re-exports from internal `.d.ts` files that\n * contain subpath imports like `@ashx-j/lunr-ai/compat`, which do not\n * resolve under `tsc` with a file argument. We keep the typecheck\n * self-contained with inline types and verify via the included `tsconfig.json`\n * (`moduleResolution: \"Bundler\"` + `skipLibCheck: true`).\n *\n * The ONE exception is `CustomEditor`, imported as a RUNTIME VALUE directly\n * from its defining module (`modes/interactive/components/custom-editor.ts`).\n * We must `extends` it to inherit pi's app keybindings (escape, ctrl+d, model\n * switching, extension shortcuts) — wrapping would lose those. It is imported\n * from the concrete module, NOT the package barrel, because the barrel\n * re-exports main.ts which imports this file — a circular import that crashes\n * under vite-node (`Class extends value undefined`).\n */\n\nimport { CustomEditor } from \"../modes/interactive/components/custom-editor.js\";\n\n// lunr: customize bridge — read the prompt-symbol toggle (bridgeless → no symbol).\nconst PROMPT_SYMBOL_BRIDGE = Symbol.for(\"@lunr/customize\");\nconst PERMISSION_MODE_BRIDGE = Symbol.for(\"@lunr/permission-mode\");\ninterface CustomizeBridgeForPrompt {\n\tgetPromptSymbol(): boolean;\n\t// lunr: footer element toggles (added to the same bridge).\n\tgetFooterMcp?(): boolean;\n\tgetFooterLsp?(): boolean;\n\tgetFooterContext?(): boolean;\n\tgetFooterTokens?(): boolean;\n\tgetFooterStatuses?(): boolean;\n}\ninterface PermissionModeBridgeForFooter {\n\tgetMode(): string | undefined;\n}\nfunction lunrCustomizeBridge(): CustomizeBridgeForPrompt | undefined {\n\treturn (globalThis as Record<symbol, unknown>)[PROMPT_SYMBOL_BRIDGE] as CustomizeBridgeForPrompt | undefined;\n}\nfunction lunrPermissionModeBridge(): PermissionModeBridgeForFooter | undefined {\n\treturn (globalThis as Record<symbol, unknown>)[PERMISSION_MODE_BRIDGE] as PermissionModeBridgeForFooter | undefined;\n}\nfunction lunrPromptSymbolEnabled(): boolean {\n\treturn lunrCustomizeBridge()?.getPromptSymbol() ?? false;\n}\n// lunr: footer toggles, read at render time. Bridgeless / missing-getter fallback\n// matches the settings-manager defaults: MCP on, LSP off, everything else on.\nfunction lunrFooterToggles(): { mcp: boolean; lsp: boolean; context: boolean; tokens: boolean; statuses: boolean } {\n\tconst bridge = lunrCustomizeBridge();\n\treturn {\n\t\tmcp: bridge?.getFooterMcp?.() ?? true,\n\t\tlsp: bridge?.getFooterLsp?.() ?? false,\n\t\tcontext: bridge?.getFooterContext?.() ?? true,\n\t\ttokens: bridge?.getFooterTokens?.() ?? true,\n\t\tstatuses: bridge?.getFooterStatuses?.() ?? true,\n\t};\n}\n// lunr: permission mode for the footer safety indicator (always shown).\nfunction lunrPermissionMode(): string | undefined {\n\treturn lunrPermissionModeBridge()?.getMode();\n}\n// lunr: prompt glyph comes from the theme tokens `glyphs.promptMoon` /\n// `glyphs.promptArrow` (defaults below match moon.json). An empty token hides\n// that part; both empty = no glyph at all.\nfunction lunrPromptGlyph(theme: Theme | undefined): string {\n\tconst moon = theme?.glyph?.(\"promptMoon\") ?? \"☾\";\n\tconst arrow = theme?.glyph?.(\"promptArrow\") ?? \">\";\n\tconst parts = [moon, arrow].filter((s) => s !== \"\");\n\treturn parts.length > 0 ? `${parts.join(\" \")} ` : \"\";\n}\n\n// ---------------------------------------------------------------------------\n// Minimal structural types (inline — see file header)\n// ---------------------------------------------------------------------------\n\ntype ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/** Theme token for the chatbox thinking-level border / effort chip. */\nexport function thinkingThemeToken(level: ThinkingLevel): string {\n\tswitch (level) {\n\t\tcase \"off\":\n\t\t\treturn \"thinkingOff\";\n\t\tcase \"minimal\":\n\t\t\treturn \"thinkingMinimal\";\n\t\tcase \"low\":\n\t\t\treturn \"thinkingLow\";\n\t\tcase \"medium\":\n\t\t\treturn \"thinkingMedium\";\n\t\tcase \"high\":\n\t\t\treturn \"thinkingHigh\";\n\t\tcase \"xhigh\":\n\t\t\treturn \"thinkingXhigh\";\n\t\tcase \"max\":\n\t\t\treturn \"thinkingMax\";\n\t\tdefault:\n\t\t\treturn \"thinkingOff\";\n\t}\n}\n\n/** Chip effort label — identity, locked so xhigh/max are never mapped down to high. */\nexport function formatChipEffort(level: ThinkingLevel): string {\n\treturn level;\n}\n\n/** Trimmed view of pi's `Theme` — only the methods we use. */\ninterface Theme {\n\tfg(token: string, text: string): string;\n\t/** lunr: prompt glyph tokens (optional for forward/backward compat). */\n\tglyph?(name: \"promptMoon\" | \"promptArrow\"): string;\n}\n\n/** Trimmed view of `pi-tui`'s `TUI` — only the method we use. */\ninterface TUIHandle {\n\trequestRender(force?: boolean): void;\n}\n\n/** Trimmed view of `pi-tui`'s `EditorTheme`. */\ninterface EditorThemeLike {\n\tborderColor: (str: string) => string;\n\tselectList: unknown;\n}\n\n/** Opaque keybindings manager. */\ninterface KeybindingsLike {\n\treadonly _?: unknown;\n}\n\n/** Trimmed view of an autocomplete list (the editor's private `autocompleteList`). */\ninterface AutocompleteListLike {\n\trender(width: number): string[];\n}\n\n/** Trimmed view of pi's `ReadonlyFooterDataProvider`. */\ninterface ReadonlyFooterDataProvider {\n\tgetGitBranch(): string | null;\n\tgetExtensionStatuses(): ReadonlyMap<string, string>;\n\tgetAvailableProviderCount(): number;\n\tonBranchChange(callback: () => void): () => void;\n}\n\n/** Trimmed view of the `getContextUsage` return value. */\ninterface ContextUsage {\n\ttokens: number | null;\n\tcontextWindow: number;\n\tpercent: number | null;\n}\n\n/** Trimmed view of an assistant message's usage — the bits we render. */\ninterface AssistantUsage {\n\tinput: number;\n\toutput: number;\n\tcost: { total: number };\n}\n\n/** Trimmed view of an assistant message. */\ninterface AssistantMessageLike {\n\trole: \"assistant\";\n\tusage: AssistantUsage;\n}\n\n/** Trimmed view of a session entry — only what we iterate over. */\ntype SessionEntry =\n\t| { type: \"message\"; message: AssistantMessageLike }\n\t| { type: string; message?: unknown };\n\n/** Trimmed view of a `ReadonlySessionManager`. */\ninterface ReadonlySessionManagerLike {\n\tgetEntries(): readonly SessionEntry[];\n\tgetBranch?(): readonly SessionEntry[];\n}\n\n/** Trimmed view of a `Model`. */\ninterface ModelLike {\n\tid?: string;\n\tprovider?: string;\n\tcontextWindow?: number;\n\treasoning?: boolean;\n\tthinkingLevelMap?: Record<string, string | null>;\n}\n\ninterface ExtensionUIContextLike {\n\tsetEditorComponent(factory: EditorFactoryLike | undefined): void;\n\tsetFooter(factory: FooterFactoryLike | undefined): void;\n\treadonly theme?: Theme;\n}\n\n/** Trimmed view of `ExtensionContext`. */\ninterface ExtensionContextLike {\n\tmode: \"tui\" | \"rpc\" | \"json\" | \"print\";\n\thasUI: boolean;\n\tmodel: ModelLike | undefined;\n\tsessionManager: ReadonlySessionManagerLike;\n\tgetContextUsage(): ContextUsage | undefined;\n\tui: ExtensionUIContextLike;\n}\n\n/** Trimmed view of `ExtensionAPI`. */\ninterface ExtensionAPI {\n\tgetThinkingLevel(): ThinkingLevel;\n\ton(event: string, handler: (event: unknown, ctx: ExtensionContextLike) => void): void;\n}\n\n/** `setEditorComponent` factory shape. */\ntype EditorFactoryLike = (\n\ttui: TUIHandle,\n\ttheme: EditorThemeLike,\n\tkeybindings: KeybindingsLike,\n) => EditorComponentLike;\n\ninterface EditorComponentLike {\n\trender(width: number): string[];\n\tgetText(): string;\n\tsetText(text: string): void;\n\tinvalidate(): void;\n\thandleInput?(data: string): void;\n}\n\n/** `setFooter` factory shape. */\ntype FooterFactoryLike = (\n\ttui: TUIHandle,\n\ttheme: Theme,\n\tfooterData: ReadonlyFooterDataProvider,\n) => FooterComponentLike;\n\ninterface FooterComponentLike {\n\trender(width: number): string[];\n\tdispose?(): void;\n\tinvalidate?(): void;\n}\n\n// ---------------------------------------------------------------------------\n// Display-width helpers (ANSI-aware; CJK-aware)\n//\n// The editor (`Editor.render`) word-wraps to the given width using grapheme\n// width, so each returned line is ≤ that many visual columns. To right-pad a\n// line for our box we need a width model that matches closely enough: skip ALL\n// escape sequences (SGR color, OSC/DCS/APC/PM/SOS string sequences such as\n// pi-tui's `CURSOR_MARKER` `ESC _pi:c BEL`, and two-char escapes), count common\n// East-Asian wide ranges as 2, combining marks and variation selectors as 0.\n// Handling the string sequences as 0-width is what keeps the right `│` rail\n// aligned on the focused (cursor) line — the base editor embeds the marker and\n// the TUI strips it at flush time, so we must not count it here.\n// ---------------------------------------------------------------------------\n\nfunction skipAnsi(str: string, pos: number): number {\n\tif (str.charCodeAt(pos) !== 0x1b) return 0;\n\tconst next = str.charCodeAt(pos + 1);\n\t// CSI: ESC [ ... <final 0x40-0x7e>\n\tif (next === 0x5b /* [ */) {\n\t\tlet j = pos + 2;\n\t\twhile (j < str.length) {\n\t\t\tconst c = str.charCodeAt(j);\n\t\t\tif (c >= 0x40 && c <= 0x7e) return j + 1 - pos;\n\t\t\tj++;\n\t\t}\n\t\treturn str.length - pos; // unterminated; consume the rest\n\t}\n\t// String sequences — OSC (]), DCS (P), APC (_), PM (^), SOS (X) — terminated\n\t// by BEL (0x07) or ST (ESC \\). pi-tui's CURSOR_MARKER `ESC _pi:c BEL` is APC;\n\t// OSC color queries are OSC. All are zero visual width.\n\tif (\n\t\tnext === 0x5d /* ] */ ||\n\t\tnext === 0x50 /* P */ ||\n\t\tnext === 0x5f /* _ */ ||\n\t\tnext === 0x5e /* ^ */ ||\n\t\tnext === 0x58 /* X */\n\t) {\n\t\tlet j = pos + 2;\n\t\twhile (j < str.length) {\n\t\t\tconst c = str.charCodeAt(j);\n\t\t\tif (c === 0x07 /* BEL */) return j + 1 - pos;\n\t\t\tif (c === 0x1b && str.charCodeAt(j + 1) === 0x5c /* \\ */) return j + 2 - pos;\n\t\t\tj++;\n\t\t}\n\t\treturn str.length - pos; // unterminated; consume the rest\n\t}\n\t// Any other ESC sequence: consume ESC + one final byte (e.g. ESC c, ESC \\,\n\t// ESC ( B). A lone trailing ESC with no following byte is 0 width too.\n\treturn Number.isNaN(next) ? 1 : 2;\n}\n\nfunction isWide(cp: number): boolean {\n\treturn (\n\t\t(cp >= 0x1100 && cp <= 0x115f) ||\n\t\t(cp >= 0x2e80 && cp <= 0x303e) ||\n\t\t(cp >= 0x3041 && cp <= 0x33ff) ||\n\t\t(cp >= 0x3400 && cp <= 0x4dbf) ||\n\t\t(cp >= 0x4e00 && cp <= 0x9fff) ||\n\t\t(cp >= 0xa000 && cp <= 0xa4cf) ||\n\t\t(cp >= 0xac00 && cp <= 0xd7a3) ||\n\t\t(cp >= 0xf900 && cp <= 0xfaff) ||\n\t\t(cp >= 0xfe30 && cp <= 0xfe4f) ||\n\t\t(cp >= 0xff00 && cp <= 0xff60) ||\n\t\t(cp >= 0xffe0 && cp <= 0xffe6) ||\n\t\t(cp >= 0x1f300 && cp <= 0x1faff) ||\n\t\t(cp >= 0x20000 && cp <= 0x3fffd)\n\t);\n}\n\nfunction charWidth(cp: number): number {\n\tif (cp >= 0x20 && cp < 0x7f) return 1;\n\tif ((cp >= 0x0300 && cp <= 0x036f) || (cp >= 0xfe00 && cp <= 0xfe0f) || cp === 0x200d) return 0;\n\treturn isWide(cp) ? 2 : 1;\n}\n\n/** Visible width of a string, ignoring SGR color codes. */\nfunction displayWidth(str: string): number {\n\tlet w = 0;\n\tlet i = 0;\n\twhile (i < str.length) {\n\t\tconst skip = skipAnsi(str, i);\n\t\tif (skip > 0) {\n\t\t\ti += skip;\n\t\t\tcontinue;\n\t\t}\n\t\tconst cp = str.codePointAt(i) ?? 0;\n\t\tw += charWidth(cp);\n\t\ti += cp > 0xffff ? 2 : 1;\n\t}\n\treturn w;\n}\n\n/** Right-pad a (possibly colored) line to `width` visible columns. */\nfunction padRight(line: string, width: number): string {\n\tconst w = displayWidth(line);\n\tif (w >= width) return line;\n\treturn line + \" \".repeat(width - w);\n}\n\n/** Truncate a plain (non-ANSI) string to `maxWidth` visible columns. */\nfunction truncatePlain(text: string, maxWidth: number): string {\n\tif (maxWidth <= 0) return \"\";\n\tif (displayWidth(text) <= maxWidth) return text;\n\tlet out = \"\";\n\tlet w = 0;\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tconst code = text.codePointAt(i) ?? 0;\n\t\tconst cw = charWidth(code);\n\t\tif (w + cw > maxWidth) break;\n\t\tout += String.fromCodePoint(code);\n\t\tw += cw;\n\t\ti += code > 0xffff ? 2 : 1;\n\t}\n\treturn out;\n}\n\n/** Truncate a (possibly ANSI-colored) string to `maxWidth` visible columns,\n * re-emitting an SGR reset at the cut so styling doesn't bleed. */\nfunction truncateToWidth(text: string, maxWidth: number, ellipsis = \"\"): string {\n\tif (maxWidth <= 0) return \"\";\n\tif (displayWidth(text) <= maxWidth) return text;\n\tconst target = Math.max(0, maxWidth - displayWidth(ellipsis));\n\tlet out = \"\";\n\tlet w = 0;\n\tlet i = 0;\n\twhile (i < text.length && w < target) {\n\t\tconst skip = skipAnsi(text, i);\n\t\tif (skip > 0) {\n\t\t\tout += text.slice(i, i + skip);\n\t\t\ti += skip;\n\t\t\tcontinue;\n\t\t}\n\t\tconst code = text.codePointAt(i) ?? 0;\n\t\tconst cw = charWidth(code);\n\t\tif (w + cw > target) break;\n\t\tout += String.fromCodePoint(code);\n\t\tw += cw;\n\t\ti += code > 0xffff ? 2 : 1;\n\t}\n\tout += \"\\x1b[0m\";\n\treturn out + ellipsis;\n}\n\n/** Clamp each rendered line to `width` visible columns (fallback path). */\nfunction clampLines(lines: string[], width: number): string[] {\n\treturn lines.map((l) => (displayWidth(l) > width ? truncateToWidth(l, width, \"\") : l));\n}\n\n/** Apply a theme `fg` token safely; falls back to plain text. */\nfunction color(theme: Theme | undefined, token: string, text: string): string {\n\ttry {\n\t\treturn theme?.fg?.(token, text) ?? text;\n\t} catch {\n\t\treturn text;\n\t}\n}\n\n// lunr: strip ANSI escape sequences so footer statuses can be re-colored uniformly.\nfunction stripAnsi(s: string): string {\n\treturn s.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n}\n\n// ---------------------------------------------------------------------------\n// Stats formatting\n// ---------------------------------------------------------------------------\n\n/** Compact token-count formatter: `999`, `1.2k`, `15k`, `1.2M`, `15M`.\n * Matches pi's FooterComponent / the captured zentui examples\n * (`↑9.0M ↓112k`, `20%/1.0M`). */\nfunction formatCount(count: number): string {\n\tif (count < 1000) return count.toString();\n\tif (count < 10000) return `${(count / 1000).toFixed(1)}k`;\n\tif (count < 1000000) return `${Math.round(count / 1000)}k`;\n\tif (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;\n\treturn `${Math.round(count / 1000000)}M`;\n}\n\n/** Sum input/output tokens across assistant messages in the session. */\nfunction getUsageTotals(ctx: ExtensionContextLike): { input: number; output: number } {\n\tlet input = 0;\n\tlet output = 0;\n\tconst entries = ctx.sessionManager.getEntries?.() ?? ctx.sessionManager.getBranch?.() ?? [];\n\tfor (const entry of entries as readonly SessionEntry[]) {\n\t\tif (entry.type !== \"message\") continue;\n\t\tconst m = entry.message as AssistantMessageLike | undefined;\n\t\tif (!m || m.role !== \"assistant\") continue;\n\t\tconst u = m.usage;\n\t\tif (!u) continue;\n\t\tinput += u.input ?? 0;\n\t\toutput += u.output ?? 0;\n\t}\n\treturn { input, output };\n}\n\n// ---------------------------------------------------------------------------\n// Provider display label\n//\n// `ctx.model.provider` is a ProviderId string (e.g. `\"ollama-cloud\"`), NOT the\n// human label. `BUILT_IN_PROVIDER_DISPLAY_NAMES` exists in pi core but is not\n// re-exported to extensions, so we derive the label (mirrors zentui's\n// `formatProviderLabel`, with an explicit `ollama-cloud` entry).\n// ---------------------------------------------------------------------------\n\nfunction formatProviderLabel(provider: string | undefined): string {\n\tif (!provider) return \"Unknown\";\n\tconst known: Record<string, string> = {\n\t\tanthropic: \"Anthropic\",\n\t\tgemini: \"Google\",\n\t\tgoogle: \"Google\",\n\t\tollama: \"Ollama\",\n\t\t\"ollama-cloud\": \"Ollama Cloud\",\n\t\topenai: \"OpenAI\",\n\t\t\"openai-codex\": \"OpenAI\",\n\t\tmistral: \"Mistral\",\n\t};\n\treturn (\n\t\tknown[provider] ??\n\t\tprovider.replace(/[-_]/g, \" \").replace(/\\b\\w/g, (c) => c.toUpperCase())\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// The chip: `model · provider · effort`\n// ---------------------------------------------------------------------------\n\nfunction colorEffort(theme: Theme | undefined, level: ThinkingLevel, text: string): string {\n\tconst token = thinkingThemeToken(level);\n\tconst painted = color(theme, token, text);\n\tif (token === \"thinkingMax\" && painted === text) {\n\t\treturn color(theme, \"thinkingXhigh\", text);\n\t}\n\treturn painted;\n}\n\nfunction buildChip(ctx: ExtensionContextLike, pi: ExtensionAPI): { left: string; effort: string; level: ThinkingLevel } {\n\tconst modelId = ctx.model?.id ?? \"no-model\";\n\tconst providerLabel = formatProviderLabel(ctx.model?.provider);\n\tconst level = pi.getThinkingLevel();\n\tconst effort = formatChipEffort(level);\n\treturn { left: `${modelId} \\u00b7 ${providerLabel} \\u00b7 `, effort, level };\n}\n\n// ---------------------------------------------------------------------------\n// The prompt box — `ChatboxEditor extends CustomEditor`\n// ---------------------------------------------------------------------------\n\nclass ChatboxEditor extends CustomEditor {\n\tprivate readonly ctx: ExtensionContextLike;\n\tprivate readonly pi: ExtensionAPI;\n\n\tconstructor(\n\t\ttui: TUIHandle,\n\t\ttheme: EditorThemeLike,\n\t\tkeybindings: KeybindingsLike,\n\t\tctx: ExtensionContextLike,\n\t\tpi: ExtensionAPI,\n\t) {\n\t\t// CustomEditor ctor: (tui, theme, keybindings, options?: EditorOptions).\n\t\t// Casts keep the inline types from leaking into the real base signature.\n\t\tsuper(tui as unknown as never, theme as unknown as never, keybindings as unknown as never, {\n\t\t\tpaddingX: 0,\n\t\t});\n\t\tthis.ctx = ctx;\n\t\tthis.pi = pi;\n\t\t// lunr: do not clobber borderColor — InteractiveMode.updateEditorBorderColor()\n\t\t// owns it (thinkingOff…thinkingMax, or bashMode).\n\t}\n\n\tprivate color(token: string, text: string): string {\n\t\treturn color(this.ctx.ui?.theme, token, text);\n\t}\n\n\toverride render(width: number): string[] {\n\t\t// Too narrow to draw a box — defer to the base editor, clamped.\n\t\tif (width <= 4) {\n\t\t\treturn clampLines(super.render(width), width);\n\t\t}\n\n\t\t// Rails: `│ ` (left) + ` │` (right) => 4 columns of chrome.\n\t\tconst promptSymbol = lunrPromptSymbolEnabled();\n\t\tconst glyph = lunrPromptGlyph(this.ctx.ui?.theme);\n\t\tconst glyphW = promptSymbol ? displayWidth(glyph) : 0;\n\t\tconst innerWidth = Math.max(1, width - 4 - glyphW);\n\t\tconst base = super.render(innerWidth);\n\n\t\t// The base editor appends the autocomplete menu lines (if any) to the END\n\t\t// of its render output. Split them off so the body sits inside the box and\n\t\t// the autocomplete renders BELOW the bottom border (preserves slash\n\t\t// commands). Mirrors zentui's `renderPolishedFrame`.\n\t\tconst showing = this.isShowingAutocomplete();\n\t\tconst acList = (this as unknown as { autocompleteList?: AutocompleteListLike }).autocompleteList;\n\t\tlet acCount = 0;\n\t\tif (showing && acList && typeof acList.render === \"function\") {\n\t\t\ttry {\n\t\t\t\tacCount = acList.render(innerWidth).length;\n\t\t\t} catch {\n\t\t\t\tacCount = 0;\n\t\t\t}\n\t\t}\n\n\t\t// `super.render` returns [base top ─ border, ...wrapped text lines, base\n\t\t// bottom ─ border, ...autocomplete lines] — the base editor draws its OWN\n\t\t// straight borders and (when active) appends the autocomplete menu. Split the\n\t\t// autocomplete off the end, then STRIP the base's first/last lines (its own\n\t\t// borders) so we don't render them a second time inside our rounded frame.\n\t\t// Mirrors zentui's `editorFrame.slice(1, -1)` (renderPolishedFrame).\n\t\tlet frame = base;\n\t\tlet acLines: string[] = [];\n\t\tif (acCount > 0 && acCount < frame.length) {\n\t\t\tacLines = frame.slice(frame.length - acCount);\n\t\t\tframe = frame.slice(0, frame.length - acCount);\n\t\t}\n\t\tconst inner = frame.length >= 2 ? frame.slice(1, frame.length - 1) : frame;\n\t\tconst body = inner.length > 0 ? inner : [\"\"];\n\n\t\tconst border = (s: string): string => this.borderColor(s);\n\n\t\t// Top border: ╭─…─╮\n\t\tconst top = border(\"\\u256d\" + \"\\u2500\".repeat(width - 2) + \"\\u256e\");\n\n\t\t// Body: │ <padded line> │ (auto-grows with the number of wrapped lines)\n\t\t// lunr: prefix the first body line with the dim theme prompt glyph (☾ > by\n\t\t// default); a same-width blank gutter keeps subsequent lines aligned.\n\t\tconst gutter = glyphW > 0 ? \" \".repeat(glyphW) : \"\";\n\t\tconst bodyLines = body.map((ln: string, i: number) => {\n\t\t\tconst prefix = i === 0 && glyphW > 0 ? this.color(\"dim\", glyph) : gutter;\n\t\t\treturn border(\"\\u2502 \") + prefix + padRight(ln, innerWidth) + border(\" \\u2502\");\n\t\t});\n\n\t\t// Bottom border with the right-aligned chip: ╰─…─ <chip> ─╯\n\t\tconst bottom = this.renderBottomBorder(width);\n\n\t\treturn [top, ...bodyLines, bottom, ...acLines];\n\t}\n\n\tprivate renderBottomBorder(width: number): string {\n\t\tconst border = (s: string): string => this.borderColor(s);\n\t\tconst parts = buildChip(this.ctx, this.pi);\n\t\tconst plain = parts.left + parts.effort;\n\t\tconst overhead = 4;\n\t\tconst maxChip = Math.max(0, width - overhead);\n\t\tconst truncated = displayWidth(plain) > maxChip;\n\t\tconst chipPlain = truncated ? truncatePlain(plain, maxChip) : plain;\n\t\tconst chipW = displayWidth(chipPlain);\n\t\tconst dashTotal = Math.max(0, width - overhead - chipW);\n\t\t// Right-align the chip: a single trailing dash before the corner, the\n\t\t// rest lead (right-aligns the chip near the corner).\n\t\tconst rightDashes = Math.min(dashTotal, 1);\n\t\tconst leftDashes = dashTotal - rightDashes;\n\n\t\tconst left = \"\\u2570\" + \"\\u2500\".repeat(leftDashes) + \" \";\n\t\tconst right = \" \" + \"\\u2500\".repeat(rightDashes) + \"\\u256f\";\n\t\tconst theme = this.ctx.ui?.theme;\n\t\t// Truncated chips may have lost the effort token — paint all white.\n\t\t// Otherwise model/provider stay white and the effort uses the thinking token.\n\t\tconst chip = truncated\n\t\t\t? this.color(\"white\", chipPlain)\n\t\t\t: this.color(\"white\", parts.left) + colorEffort(theme, parts.level, parts.effort);\n\t\treturn border(left) + chip + border(right);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// The stats line (footer) — slim, single line, BELOW the box\n// ---------------------------------------------------------------------------\n\nfunction renderStatsLine(\n\twidth: number,\n\tctx: ExtensionContextLike,\n\ttheme: Theme,\n\tfooterData: ReadonlyFooterDataProvider,\n): string[] {\n\tconst sep = color(theme, \"accent2\", \" | \"); // lunr: theme-polish — separator uses subtle accent2 blue (was bright-black plain fallback)\n\tconst parts: string[] = [];\n\n\t// lunr: mode zone — permission mode + agent-mode statuses (plan/goal/swarm/research)\n\t// render as ONE segment (dim middot-separated), not scattered across piped sections.\n\tconst modeZone: string[] = [];\n\n\t// lunr: permission mode safety indicator — always shown (not toggle-gated).\n\tconst mode = lunrPermissionMode();\n\tif (mode === \"yolo\" || mode === \"auto\") modeZone.push(color(theme, \"warning\", mode));\n\telse if (mode === \"manual\" || mode === \"plan\") modeZone.push(color(theme, \"white\", mode)); // lunr: theme-polish — manual/plan read white (was dim)\n\n\t// lunr: footer element toggles from the customize bridge (read at render time).\n\tconst footerToggles = lunrFooterToggles();\n\n\t// 1) Extension statuses published by other extensions (rendered as-is,\n\t// already styled): LSP (`pi-lsp-extension`), MCP (`pi-mcp-adapter`),\n\t// throughput/tokens (`pi-tps-was-taken`). These are NOT on `ctx` directly.\n\tconst statuses = footerData.getExtensionStatuses?.();\n\tif (statuses && statuses.size > 0) {\n\t\t// lunr: status segments are toggle-gated via the customize bridge:\n\t\t// footerStatuses gates plan/goal/swarm/research/tps, footerMcp gates\n\t\t// mcp/mcp-auth, footerLsp gates lsp. Publishers keep calling\n\t\t// ctx.ui.setStatus harmlessly when their segment is hidden.\n\t\t// lunr: plan/goal/swarm/research join the mode zone; tps/mcp/lsp stay piped.\n\t\tconst modeKeys: string[] = footerToggles.statuses ? [\"plan\", \"goal\", \"swarm\", \"research\"] : [];\n\t\tfor (const key of modeKeys) {\n\t\t\tconst v = statuses.get(key);\n\t\t\tif (v) modeZone.push(color(theme, \"white\", stripAnsi(v)));\n\t\t}\n\t\tconst pipedKeys: string[] = [];\n\t\tif (footerToggles.statuses) pipedKeys.push(\"tps\");\n\t\tif (footerToggles.mcp) pipedKeys.push(\"mcp\", \"mcp-auth\");\n\t\tif (footerToggles.lsp) pipedKeys.push(\"lsp\");\n\t\tfor (const key of pipedKeys) {\n\t\t\tconst v = statuses.get(key);\n\t\t\t// lunr: unify footer status colors (white, was dim) so the whole stats line reads as one tone.\n\t\t\tif (v) parts.push(color(theme, \"white\", stripAnsi(v))); // lunr: theme-polish — status segments white (was dim)\n\t\t}\n\t}\n\tif (modeZone.length > 0) {\n\t\tparts.unshift(modeZone.join(color(theme, \"dim\", \" · \")));\n\t}\n\n\t// 2) Context usage: `pct/window` (lunr: gated on footerContext).\n\tif (footerToggles.context) {\n\t\tconst usage = ctx.getContextUsage();\n\t\tconst win = ctx.model?.contextWindow ?? usage?.contextWindow ?? 0;\n\t\tconst pct = usage?.percent == null ? \"?\" : `${Math.round(usage.percent)}%`;\n\t\tconst ctxSeg = `${pct}/${formatCount(win)}`;\n\t\tconst pv = usage?.percent ?? 0;\n\t\tif (pv > 90) parts.push(color(theme, \"error\", ctxSeg));\n\t\telse if (pv > 70) parts.push(color(theme, \"warning\", ctxSeg));\n\t\telse parts.push(color(theme, \"white\", ctxSeg)); // lunr: theme-polish — normal context % white (was dim)\n\t}\n\n\t// 3) Token totals: ↑in ↓out (lunr: gated on footerTokens).\n\tif (footerToggles.tokens) {\n\t\tconst totals = getUsageTotals(ctx);\n\t\tparts.push(color(theme, \"white\", `\\u2191${formatCount(totals.input)} \\u2193${formatCount(totals.output)}`)); // lunr: theme-polish — token totals white (was dim)\n\t}\n\n\t// lunr: cost/usage counter segment removed entirely (both the $x.xxx dollar\n\t// counter for API-key providers and the plan-usage limit bar for OAuth/subscription\n\t// providers). Segments 1-3 (statuses, context, tokens) remain.\n\n\tlet line = parts.join(sep);\n\tif (displayWidth(line) > width) {\n\t\tline = truncateToWidth(line, width, \"\");\n\t}\n\treturn [line];\n}\n\n// ---------------------------------------------------------------------------\n// Install / teardown\n// ---------------------------------------------------------------------------\n\nfunction installEditor(\n\tctx: ExtensionContextLike,\n\tpi: ExtensionAPI,\n\tsetRequestor: (r: () => void) => void,\n): void {\n\tif (typeof ctx.ui.setEditorComponent !== \"function\") return;\n\tconst factory: EditorFactoryLike = (tui, _theme, _keybindings) => {\n\t\tsetRequestor(() => {\n\t\t\ttry {\n\t\t\t\ttui.requestRender();\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t});\n\t\treturn new ChatboxEditor(tui, _theme, _keybindings, ctx, pi);\n\t};\n\tctx.ui.setEditorComponent(factory);\n}\n\nfunction installFooter(\n\tctx: ExtensionContextLike,\n\tsetRequestor: (r: () => void) => void,\n): void {\n\tif (typeof ctx.ui.setFooter !== \"function\") return;\n\tlet disposed = false;\n\tconst factory: FooterFactoryLike = (tui, _theme, _footerData) => {\n\t\tsetRequestor(() => {\n\t\t\ttry {\n\t\t\t\ttui.requestRender();\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t});\n\t\treturn {\n\t\t\tinvalidate(): void {\n\t\t\t\t// render is pure\n\t\t\t},\n\t\t\tdispose(): void {\n\t\t\t\tdisposed = true;\n\t\t\t},\n\t\t\trender(width: number): string[] {\n\t\t\t\tif (disposed) return [];\n\t\t\t\treturn renderStatsLine(width, ctx, _theme, _footerData);\n\t\t\t},\n\t\t};\n\t};\n\tctx.ui.setFooter(factory);\n}\n\n// ---------------------------------------------------------------------------\n// Extension entry point\n// ---------------------------------------------------------------------------\n\nexport default function (pi: ExtensionAPI): void {\n\tlet renderRequestor: (() => void) | undefined = undefined;\n\tconst requestRender = (): void => {\n\t\ttry {\n\t\t\trenderRequestor?.();\n\t\t} catch {\n\t\t\t/* ignore */\n\t\t}\n\t};\n\n\tpi.on(\"session_start\", (_event, ctx) => {\n\t\tif (!ctx.hasUI || ctx.mode !== \"tui\") return;\n\t\tinstallEditor(ctx, pi, (r) => {\n\t\t\trenderRequestor = r;\n\t\t});\n\t\tinstallFooter(ctx, (r) => {\n\t\t\tif (!renderRequestor) renderRequestor = r;\n\t\t});\n\t});\n\n\tpi.on(\"session_shutdown\", (_event, ctx) => {\n\t\ttry {\n\t\t\tif (typeof ctx.ui?.setEditorComponent === \"function\") ctx.ui.setEditorComponent(undefined);\n\t\t} catch {\n\t\t\t/* ignore */\n\t\t}\n\t\ttry {\n\t\t\tif (typeof ctx.ui?.setFooter === \"function\") ctx.ui.setFooter(undefined);\n\t\t} catch {\n\t\t\t/* ignore */\n\t\t}\n\t\trenderRequestor = undefined;\n\t});\n\n\t// Re-render triggers: model/provider + effort (chip), and token/cost/context\n\t// (stats line). Event names match those zentui wires.\n\tconst reRenderEvents = [\n\t\t\"model_select\",\n\t\t\"thinking_level_select\",\n\t\t\"agent_end\",\n\t\t\"message_end\",\n\t\t\"tool_execution_end\",\n\t\t\"session_compact\",\n\t];\n\tfor (const ev of reRenderEvents) {\n\t\tpi.on(ev, () => requestRender());\n\t}\n}"]}
@@ -68,6 +68,31 @@ function lunrPromptGlyph(theme) {
68
68
  const parts = [moon, arrow].filter((s) => s !== "");
69
69
  return parts.length > 0 ? `${parts.join(" ")} ` : "";
70
70
  }
71
+ /** Theme token for the chatbox thinking-level border / effort chip. */
72
+ export function thinkingThemeToken(level) {
73
+ switch (level) {
74
+ case "off":
75
+ return "thinkingOff";
76
+ case "minimal":
77
+ return "thinkingMinimal";
78
+ case "low":
79
+ return "thinkingLow";
80
+ case "medium":
81
+ return "thinkingMedium";
82
+ case "high":
83
+ return "thinkingHigh";
84
+ case "xhigh":
85
+ return "thinkingXhigh";
86
+ case "max":
87
+ return "thinkingMax";
88
+ default:
89
+ return "thinkingOff";
90
+ }
91
+ }
92
+ /** Chip effort label — identity, locked so xhigh/max are never mapped down to high. */
93
+ export function formatChipEffort(level) {
94
+ return level;
95
+ }
71
96
  // ---------------------------------------------------------------------------
72
97
  // Display-width helpers (ANSI-aware; CJK-aware)
73
98
  //
@@ -293,11 +318,20 @@ function formatProviderLabel(provider) {
293
318
  // ---------------------------------------------------------------------------
294
319
  // The chip: `model · provider · effort`
295
320
  // ---------------------------------------------------------------------------
321
+ function colorEffort(theme, level, text) {
322
+ const token = thinkingThemeToken(level);
323
+ const painted = color(theme, token, text);
324
+ if (token === "thinkingMax" && painted === text) {
325
+ return color(theme, "thinkingXhigh", text);
326
+ }
327
+ return painted;
328
+ }
296
329
  function buildChip(ctx, pi) {
297
330
  const modelId = ctx.model?.id ?? "no-model";
298
331
  const providerLabel = formatProviderLabel(ctx.model?.provider);
299
- const effort = pi.getThinkingLevel();
300
- return `${modelId} \u00b7 ${providerLabel} \u00b7 ${effort}`;
332
+ const level = pi.getThinkingLevel();
333
+ const effort = formatChipEffort(level);
334
+ return { left: `${modelId} \u00b7 ${providerLabel} \u00b7 `, effort, level };
301
335
  }
302
336
  // ---------------------------------------------------------------------------
303
337
  // The prompt box — `ChatboxEditor extends CustomEditor`
@@ -313,9 +347,8 @@ class ChatboxEditor extends CustomEditor {
313
347
  });
314
348
  this.ctx = ctx;
315
349
  this.pi = pi;
316
- // `borderColor` is used internally by the base editor; route it through our
317
- // theme so any internal use stays consistent with the frame.
318
- this.borderColor = (s) => this.color("border", s);
350
+ // lunr: do not clobber borderColor InteractiveMode.updateEditorBorderColor()
351
+ // owns it (thinkingOff…thinkingMax, or bashMode).
319
352
  }
320
353
  color(token, text) {
321
354
  return color(this.ctx.ui?.theme, token, text);
@@ -360,7 +393,7 @@ class ChatboxEditor extends CustomEditor {
360
393
  }
361
394
  const inner = frame.length >= 2 ? frame.slice(1, frame.length - 1) : frame;
362
395
  const body = inner.length > 0 ? inner : [""];
363
- const border = (s) => this.color("border", s);
396
+ const border = (s) => this.borderColor(s);
364
397
  // Top border: ╭─…─╮
365
398
  const top = border("\u256d" + "\u2500".repeat(width - 2) + "\u256e");
366
399
  // Body: │ <padded line> │ (auto-grows with the number of wrapped lines)
@@ -376,15 +409,14 @@ class ChatboxEditor extends CustomEditor {
376
409
  return [top, ...bodyLines, bottom, ...acLines];
377
410
  }
378
411
  renderBottomBorder(width) {
379
- const border = (s) => this.color("border", s);
380
- let chip = buildChip(this.ctx, this.pi);
381
- let chipW = displayWidth(chip);
382
- // Overhead with zero dashes: ╰ + " " + chip + " " + ╯ => 4 columns.
412
+ const border = (s) => this.borderColor(s);
413
+ const parts = buildChip(this.ctx, this.pi);
414
+ const plain = parts.left + parts.effort;
383
415
  const overhead = 4;
384
- if (chipW > width - overhead) {
385
- chip = truncatePlain(chip, Math.max(0, width - overhead));
386
- chipW = displayWidth(chip);
387
- }
416
+ const maxChip = Math.max(0, width - overhead);
417
+ const truncated = displayWidth(plain) > maxChip;
418
+ const chipPlain = truncated ? truncatePlain(plain, maxChip) : plain;
419
+ const chipW = displayWidth(chipPlain);
388
420
  const dashTotal = Math.max(0, width - overhead - chipW);
389
421
  // Right-align the chip: a single trailing dash before the corner, the
390
422
  // rest lead (right-aligns the chip near the corner).
@@ -392,7 +424,13 @@ class ChatboxEditor extends CustomEditor {
392
424
  const leftDashes = dashTotal - rightDashes;
393
425
  const left = "\u2570" + "\u2500".repeat(leftDashes) + " ";
394
426
  const right = " " + "\u2500".repeat(rightDashes) + "\u256f";
395
- return border(left) + this.color("white", chip) + border(right); // lunr: theme-polish — model/provider/thinking chip white (was dim)
427
+ const theme = this.ctx.ui?.theme;
428
+ // Truncated chips may have lost the effort token — paint all white.
429
+ // Otherwise model/provider stay white and the effort uses the thinking token.
430
+ const chip = truncated
431
+ ? this.color("white", chipPlain)
432
+ : this.color("white", parts.left) + colorEffort(theme, parts.level, parts.effort);
433
+ return border(left) + chip + border(right);
396
434
  }
397
435
  }
398
436
  // ---------------------------------------------------------------------------