@ashx-j/lunr 0.2.3 → 0.2.4
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.
- package/dist/builtin-extensions/ashxj-thinking.d.ts +1 -0
- package/dist/builtin-extensions/ashxj-thinking.d.ts.map +1 -1
- package/dist/builtin-extensions/ashxj-thinking.js +19 -7
- package/dist/builtin-extensions/ashxj-thinking.js.map +1 -1
- package/dist/gateway/commands.d.ts.map +1 -1
- package/dist/gateway/commands.js +1 -0
- package/dist/gateway/commands.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +5 -5
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +5 -5
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/docs/keybindings.md +1 -1
- package/docs/quickstart.md +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +4 -4
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* `/thinking [level]` slash command to view or set the reasoning level,
|
|
5
5
|
* plus `/thinking show|hide|toggle` for thinking-block visibility.
|
|
6
|
+
* `/effort` and `/reasoning` are full-parity aliases.
|
|
6
7
|
*
|
|
7
8
|
* Loaded by pi via jiti — no build step, plain TypeScript.
|
|
8
9
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ashxj-thinking.d.ts","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B,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;AAmLD,MAAM,CAAC,OAAO,WAAW,EAAE,EAAE,YAAY,GAAG,IAAI,CAgH/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 *\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 (~1k tokens)\",\n\tlow: \"Light reasoning (~2k tokens)\",\n\tmedium: \"Moderate reasoning (~8k tokens)\",\n\thigh: \"Deep reasoning (~16k tokens)\",\n\txhigh: \"Extra-high reasoning (~32k tokens)\",\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\nexport default function (pi: ExtensionAPI): void {\n\tpi.registerCommand(\"thinking\", {\n\t\tdescription: \"View or set the reasoning level for the current model, or toggle thinking-block visibility with show/hide/toggle\",\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\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,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,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"]}
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
*
|
|
8
8
|
* `/thinking [level]` slash command to view or set the reasoning level,
|
|
9
9
|
* plus `/thinking show|hide|toggle` for thinking-block visibility.
|
|
10
|
+
* `/effort` and `/reasoning` are full-parity aliases.
|
|
10
11
|
*
|
|
11
12
|
* Loaded by pi via jiti — no build step, plain TypeScript.
|
|
12
13
|
*
|
|
@@ -33,11 +34,11 @@ const ALL_LEVELS_5 = ["off", "minimal", "low", "medium", "high"];
|
|
|
33
34
|
/** Per-level descriptions. Mirrored from `THINKING_DESCRIPTIONS` in settings-selector.ts. */
|
|
34
35
|
const THINKING_DESCRIPTIONS = {
|
|
35
36
|
off: "No reasoning",
|
|
36
|
-
minimal: "Very brief reasoning
|
|
37
|
-
low: "Light reasoning
|
|
38
|
-
medium: "Moderate reasoning
|
|
39
|
-
high: "Deep reasoning
|
|
40
|
-
xhigh: "Extra-high reasoning
|
|
37
|
+
minimal: "Very brief reasoning",
|
|
38
|
+
low: "Light reasoning",
|
|
39
|
+
medium: "Moderate reasoning",
|
|
40
|
+
high: "Deep reasoning",
|
|
41
|
+
xhigh: "Extra-high reasoning",
|
|
41
42
|
// lunr: added — mirrors settings-selector.ts.
|
|
42
43
|
max: "Maximum reasoning",
|
|
43
44
|
};
|
|
@@ -183,9 +184,10 @@ function writeHideThinkingBlock(hide) {
|
|
|
183
184
|
// ---------------------------------------------------------------------------
|
|
184
185
|
// Extension entry point
|
|
185
186
|
// ---------------------------------------------------------------------------
|
|
187
|
+
const THINKING_COMMAND_DESCRIPTION = "View or set the reasoning level for the current model, or toggle thinking-block visibility with show/hide/toggle";
|
|
186
188
|
export default function (pi) {
|
|
187
|
-
|
|
188
|
-
description:
|
|
189
|
+
const thinkingSpec = {
|
|
190
|
+
description: THINKING_COMMAND_DESCRIPTION,
|
|
189
191
|
getArgumentCompletions(prefix) {
|
|
190
192
|
const lower = prefix.toLowerCase();
|
|
191
193
|
// Visibility sub-options first, filtered by prefix, alongside the levels.
|
|
@@ -284,6 +286,16 @@ export default function (pi) {
|
|
|
284
286
|
pi.setThinkingLevel(requested);
|
|
285
287
|
ctx.ui.notify(`Thinking level: ${requested}`, "info");
|
|
286
288
|
},
|
|
289
|
+
};
|
|
290
|
+
pi.registerCommand("thinking", thinkingSpec);
|
|
291
|
+
// lunr: /effort and /reasoning are full-parity aliases (same handler + completions).
|
|
292
|
+
pi.registerCommand("effort", {
|
|
293
|
+
...thinkingSpec,
|
|
294
|
+
description: `${THINKING_COMMAND_DESCRIPTION} (alias of /thinking)`,
|
|
295
|
+
});
|
|
296
|
+
pi.registerCommand("reasoning", {
|
|
297
|
+
...thinkingSpec,
|
|
298
|
+
description: `${THINKING_COMMAND_DESCRIPTION} (alias of /thinking)`,
|
|
287
299
|
});
|
|
288
300
|
}
|
|
289
301
|
// ---------------------------------------------------------------------------
|
|
@@ -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;;;;;;;;;;;;;;;;GAgBG;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,mCAAmC;IAC5C,GAAG,EAAE,8BAA8B;IACnC,MAAM,EAAE,iCAAiC;IACzC,IAAI,EAAE,8BAA8B;IACpC,KAAK,EAAE,oCAAoC;IAC3C,gDAA8C;IAC9C,GAAG,EAAE,mBAAmB;CACxB,CAAC;AAEF,sEAAsE;AACtE,SAAS,kBAAkB,CAAC,KAA4B,EAA4B;IACnF,IAAI,CAAC,KAAK;QAAE,OAAO,YAAY,CAAC;IAChC,IAAI,KAAK,CAAC,SAAS,KAAK,KAAK;QAAE,OAAO,CAAC,KAAc,CAAC,CAAC;IACvD,iEAAiE;IACjE,OAAO,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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 *\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 (~1k tokens)\",\n\tlow: \"Light reasoning (~2k tokens)\",\n\tmedium: \"Moderate reasoning (~8k tokens)\",\n\thigh: \"Deep reasoning (~16k tokens)\",\n\txhigh: \"Extra-high reasoning (~32k tokens)\",\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\nexport default function (pi: ExtensionAPI): void {\n\tpi.registerCommand(\"thinking\", {\n\t\tdescription: \"View or set the reasoning level for the current model, or toggle thinking-block visibility with show/hide/toggle\",\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\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.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,IAAI,EAAE,gBAAgB;IACtB,KAAK,EAAE,sBAAsB;IAC7B,gDAA8C;IAC9C,GAAG,EAAE,mBAAmB;CACxB,CAAC;AAEF,sEAAsE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AAG,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commands.d.ts","sourceRoot":"","sources":["../../src/gateway/commands.ts"],"names":[],"mappings":"AAAA;;;;;;GA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sourcesContent":["/**\n * lunR: gateway chat command registry.\n *\n * Every command is a small headless handler over AgentSession. Router.ts keeps\n * platform gating/authorization and delegates to runChatCommand for busy/session\n * guards, error wrapping, and /help generation.\n */\n\nimport type { ThinkingLevel } from \"@ashx-j/lunr-agent\";\nimport type { Model } from \"@ashx-j/lunr-ai/compat\";\nimport { computeContextBreakdown } from \"../core/context-breakdown.ts\";\nimport type { ToolDefinition } from \"../core/extensions/types.ts\";\nimport { findExactModelReferenceMatch } from \"../core/model-resolver.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.ts\";\nimport type { SessionInfo } from \"../core/session-manager.ts\";\nimport { SessionManager } from \"../core/session-manager.ts\";\nimport { buildSwarmPrompt } from \"../core/swarm.ts\";\nimport type { BridgeSession } from \"./agent-bridge.ts\";\nimport { createPicker, type PickerItem } from \"./buttons.ts\";\nimport type { BridgeLike } from \"./router.ts\";\nimport type { MessageEvent, PlatformAdapter } from \"./types.ts\";\n\nconst MODEL_CACHE_TTL_MS = 5 * 60 * 1000;\nconst SESSIONS_CACHE_TTL_MS = 5 * 60 * 1000;\nconst MAX_MODEL_LIST_LINES = 15;\nconst PROVIDER_PER_PAGE = 10;\nconst _MODEL_PER_PAGE = 8;\nconst MAX_MODELS_PER_PROVIDER = 50;\nconst MODEL_ID_MAX = 38;\nconst MODEL_CACHE_CAP = 100;\nconst SESSIONS_CACHE_CAP = 100;\n\ninterface ModelCacheEntry {\n\tmodels: Model<any>[];\n\texpires: number;\n}\n\ninterface SessionsCacheEntry {\n\tsessions: SessionInfo[];\n\texpires: number;\n}\n\nconst modelCache = new Map<string, ModelCacheEntry>();\nconst sessionsCache = new Map<string, SessionsCacheEntry>();\n\nfunction evictLRU<K, V>(map: Map<K, V>, cap: number): void {\n\twhile (map.size > cap) {\n\t\tconst first = map.keys().next().value;\n\t\tif (first !== undefined) map.delete(first);\n\t}\n}\n\nfunction getCachedModels(key: string): Model<any>[] | undefined {\n\tconst cached = modelCache.get(key);\n\tif (!cached) return undefined;\n\tif (Date.now() > cached.expires) {\n\t\tmodelCache.delete(key);\n\t\treturn undefined;\n\t}\n\t// LRU refresh.\n\tmodelCache.delete(key);\n\tmodelCache.set(key, cached);\n\treturn cached.models;\n}\n\nfunction setCachedModels(key: string, models: Model<any>[]): void {\n\tmodelCache.set(key, { models, expires: Date.now() + MODEL_CACHE_TTL_MS });\n\tevictLRU(modelCache, MODEL_CACHE_CAP);\n}\n\nfunction getCachedSessions(key: string): SessionInfo[] | undefined {\n\tconst cached = sessionsCache.get(key);\n\tif (!cached) return undefined;\n\tif (Date.now() > cached.expires) {\n\t\tsessionsCache.delete(key);\n\t\treturn undefined;\n\t}\n\tsessionsCache.delete(key);\n\tsessionsCache.set(key, cached);\n\treturn cached.sessions;\n}\n\nfunction setCachedSessions(key: string, sessions: SessionInfo[]): void {\n\tsessionsCache.set(key, { sessions, expires: Date.now() + SESSIONS_CACHE_TTL_MS });\n\tevictLRU(sessionsCache, SESSIONS_CACHE_CAP);\n}\n\nexport interface ChatCommandContext {\n\tevent: MessageEvent;\n\tkey: string;\n\tadapter: PlatformAdapter;\n\tbridge: BridgeLike;\n\tsession?: BridgeSession;\n\treply(text: string): Promise<void>;\n\targs: string;\n}\n\nexport interface ChatCommand {\n\tname: string;\n\taliases?: string[];\n\tdescription: string;\n\tbypassBusy: boolean;\n\tneedsSession: boolean;\n\t// biome-ignore lint/suspicious/noConfusingVoidType: handlers may return nothing; runChatCommand treats undefined as consumed.\n\thandler(ctx: ChatCommandContext): Promise<boolean | void>;\n}\n\nfunction oneLine(text: string): string {\n\treturn text.replace(/\\s+/g, \" \").trim().slice(0, 200);\n}\n\nfunction prefixLines(text: string, prefix: string): string {\n\treturn text\n\t\t.split(\"\\n\")\n\t\t.map((line, index) => (index === 0 ? prefix : \" \") + line)\n\t\t.join(\"\\n\");\n}\n\nfunction truncate(text: string, max: number): string {\n\tif (text.length <= max) return text;\n\treturn `${text.slice(0, max - 1)}…`;\n}\n\nfunction formatRelativeTime(date: Date): string {\n\tconst seconds = Math.max(0, Math.floor((Date.now() - date.getTime()) / 1000));\n\tif (seconds < 60) return `${seconds}s ago`;\n\tconst minutes = Math.floor(seconds / 60);\n\tif (minutes < 60) return `${minutes}m ago`;\n\tconst hours = Math.floor(minutes / 60);\n\tif (hours < 24) return `${hours}h ago`;\n\tconst days = Math.floor(hours / 24);\n\treturn `${days}d ago`;\n}\n\nfunction formatModelList(models: Model<any>[], maxLines = MAX_MODEL_LIST_LINES): string[] {\n\tif (models.length === 0) return [\"No models available.\"];\n\tconst byProvider = new Map<string, Model<any>[]>();\n\tfor (const model of models) {\n\t\tconst list = byProvider.get(model.provider) ?? [];\n\t\tlist.push(model);\n\t\tbyProvider.set(model.provider, list);\n\t}\n\tconst providers = [...byProvider.keys()].sort();\n\tconst lines: string[] = [];\n\tlet index = 1;\n\tfor (const provider of providers) {\n\t\tconst list = (byProvider.get(provider) ?? []).sort((a, b) => a.id.localeCompare(b.id));\n\t\tfor (const model of list) {\n\t\t\tlines.push(`${index}) ${provider}/${model.id}`);\n\t\t\tindex++;\n\t\t}\n\t}\n\tif (lines.length <= maxLines) return lines;\n\treturn [\n\t\t`${models.length} models across ${providers.length} providers.`,\n\t\t\"Use /model <provider/id> or /model <query>.\",\n\t\t...providers.map((p) => `- ${p}`),\n\t];\n}\n\nfunction groupModelsByProvider(models: Model<any>[]): Map<string, Model<any>[]> {\n\tconst byProvider = new Map<string, Model<any>[]>();\n\tfor (const model of models) {\n\t\tconst list = byProvider.get(model.provider) ?? [];\n\t\tlist.push(model);\n\t\tbyProvider.set(model.provider, list);\n\t}\n\tfor (const list of byProvider.values()) {\n\t\tlist.sort((a, b) => a.id.localeCompare(b.id));\n\t}\n\treturn byProvider;\n}\n\nfunction truncateModelId(id: string): string {\n\tconst lastSlash = id.lastIndexOf(\"/\");\n\tconst name = lastSlash >= 0 ? id.slice(lastSlash + 1) : id;\n\treturn truncate(name, MODEL_ID_MAX);\n}\n\nasync function refreshAndCacheModels(session: BridgeSession, key: string): Promise<Model<any>[]> {\n\tconst runtime: ModelRuntime = session.modelRuntime;\n\tawait runtime.refresh();\n\tconst models = [...(await runtime.getAvailable())].sort(\n\t\t(a, b) => a.provider.localeCompare(b.provider) || a.id.localeCompare(b.id),\n\t);\n\tsetCachedModels(key, models);\n\treturn models;\n}\n\nasync function setModelAndReply(ctx: ChatCommandContext, model: Model<any>): Promise<void> {\n\tconst session = ctx.session!;\n\ttry {\n\t\tawait session.setModel(model);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tif (message.includes(\"No API key\")) {\n\t\t\tawait ctx.reply(`No API key for ${model.provider}.`);\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n\tawait ctx.reply(`Model → ${model.provider}/${model.id} (thinking level re-clamped to ${session.thinkingLevel})`);\n}\n\nconst newCommand: ChatCommand = {\n\tname: \"new\",\n\taliases: [\"reset\"],\n\tdescription: \"start a fresh session for this chat\",\n\tbypassBusy: false,\n\tneedsSession: false,\n\tasync handler(ctx) {\n\t\tawait ctx.bridge.reset(ctx.key);\n\t\tawait ctx.reply(\"Session reset — next message starts a fresh session.\");\n\t},\n};\n\nconst undoCommand: ChatCommand = {\n\tname: \"undo\",\n\tdescription: \"rewind the session tree before the last user turn\",\n\tbypassBusy: false,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst { userText } = await ctx.bridge.undo(ctx.key);\n\t\tconst text = userText ? ` \"${truncate(userText, 60)}\"` : \"\";\n\t\tawait ctx.reply(`Undone — rewound before${text}. /redo to restore.`);\n\t},\n};\n\nconst redoCommand: ChatCommand = {\n\tname: \"redo\",\n\tdescription: \"restore the last undone turn\",\n\tbypassBusy: false,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tawait ctx.bridge.redo(ctx.key);\n\t\tawait ctx.reply(\"Redone.\");\n\t},\n};\n\nconst stopCommand: ChatCommand = {\n\tname: \"stop\",\n\tdescription: \"abort the running turn\",\n\tbypassBusy: true,\n\tneedsSession: false,\n\tasync handler(ctx) {\n\t\tawait ctx.bridge.abort(ctx.key);\n\t\tawait ctx.reply(\"Stopped.\");\n\t},\n};\n\nconst statusCommand: ChatCommand = {\n\tname: \"status\",\n\tdescription: \"session status\",\n\tbypassBusy: true,\n\tneedsSession: false,\n\tasync handler(ctx) {\n\t\tconst status = ctx.bridge.getStatus(ctx.key);\n\t\tconst age = status.createdAt\n\t\t\t? `${Math.max(0, Math.round((Date.now() - Date.parse(status.createdAt)) / 1000))}s`\n\t\t\t: \"no session yet\";\n\t\tawait ctx.reply(\n\t\t\t`${ctx.event.source.platform} · session age ${age} · ${status.busy ? \"busy\" : \"idle\"} · queue ${status.queueDepth}`,\n\t\t);\n\t},\n};\n\nconst whoamiCommand: ChatCommand = {\n\tname: \"whoami\",\n\tdescription: \"your ids and session key\",\n\tbypassBusy: true,\n\tneedsSession: false,\n\tasync handler(ctx) {\n\t\tconst { userId, chatId } = ctx.event.source;\n\t\tawait ctx.reply(`userId: ${userId}\\nchatId: ${chatId}\\nkey: ${ctx.key}`);\n\t},\n};\n\nconst helpCommand: ChatCommand = {\n\tname: \"help\",\n\tdescription: \"this message\",\n\tbypassBusy: true,\n\tneedsSession: false,\n\tasync handler(ctx) {\n\t\tawait ctx.reply(formatHelpText());\n\t},\n};\n\nconst modelCommand: ChatCommand = {\n\tname: \"model\",\n\tdescription: \"list or switch models\",\n\tbypassBusy: false,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst session = ctx.session!;\n\t\tconst arg = ctx.args.trim();\n\t\tif (!arg) {\n\t\t\tconst cached = getCachedModels(ctx.key);\n\t\t\tconst models = cached ?? (await refreshAndCacheModels(session, ctx.key));\n\t\t\tconst byProvider = groupModelsByProvider(models);\n\t\t\tconst current = session.model;\n\t\t\tconst currentRef = current ? `${current.provider}/${current.id}` : \"\";\n\t\t\tconst providers = [...byProvider.keys()].sort();\n\t\t\tconst providerItems: PickerItem[] = providers.map((provider) => ({\n\t\t\t\tlabel: `${current?.provider === provider ? \"✓ \" : \"\"}${provider} (${byProvider.get(provider)?.length ?? 0})`,\n\t\t\t\tvalue: provider,\n\t\t\t}));\n\n\t\t\tconst pickerOpts = {\n\t\t\t\treplyTo: ctx.event.messageId,\n\t\t\t\tthreadId: ctx.event.source.threadId,\n\t\t\t};\n\t\t\tconst result = await createPicker(\n\t\t\t\tctx.adapter,\n\t\t\t\tctx.event.source,\n\t\t\t\t{\n\t\t\t\t\tkind: \"model\",\n\t\t\t\t\tsessionKey: ctx.key,\n\t\t\t\t\tinvokerId: ctx.event.source.userId,\n\t\t\t\t\titems: providerItems,\n\t\t\t\t\tperPage: PROVIDER_PER_PAGE,\n\t\t\t\t\ttitle: \"Pick a model provider\",\n\t\t\t\t\tasync resolve(item) {\n\t\t\t\t\t\tif (item.value === \"__back__\") {\n\t\t\t\t\t\t\treturn { done: false, items: providerItems, title: \"Pick a model provider\" };\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!item.value.includes(\"/\")) {\n\t\t\t\t\t\t\tconst provider = item.value;\n\t\t\t\t\t\t\tconst list = byProvider.get(provider) ?? [];\n\t\t\t\t\t\t\tconst capped = list.slice(0, MAX_MODELS_PER_PROVIDER);\n\t\t\t\t\t\t\tconst note =\n\t\t\t\t\t\t\t\tlist.length > MAX_MODELS_PER_PROVIDER\n\t\t\t\t\t\t\t\t\t? ` — ${list.length - MAX_MODELS_PER_PROVIDER} more available`\n\t\t\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\t\t\tconst modelItems: PickerItem[] = [];\n\t\t\t\t\t\t\tfor (const m of capped) {\n\t\t\t\t\t\t\t\tconst ref = `${provider}/${m.id}`;\n\t\t\t\t\t\t\t\tmodelItems.push({\n\t\t\t\t\t\t\t\t\tlabel: `${currentRef === ref ? \"✓ \" : \"\"}${truncateModelId(m.id)}`,\n\t\t\t\t\t\t\t\t\tvalue: ref,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tmodelItems.unshift({ label: \"◀ Back\", value: \"__back__\" });\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\t\t\titems: modelItems,\n\t\t\t\t\t\t\t\ttitle: `${provider} (${list.length})${note}`,\n\t\t\t\t\t\t\t\tbreadcrumbs: provider,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst exact = findExactModelReferenceMatch(item.value, models);\n\t\t\t\t\t\tif (!exact) {\n\t\t\t\t\t\t\treturn { done: true, text: \"That model is no longer available.\" };\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait session.setModel(exact);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\t\tif (message.includes(\"No API key\")) {\n\t\t\t\t\t\t\t\treturn { done: true, text: `No API key for ${exact.provider}.` };\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tdone: true,\n\t\t\t\t\t\t\ttext: `☾ Model → ${exact.provider}/${exact.id} (thinking level re-clamped to ${session.thinkingLevel})`,\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tpickerOpts,\n\t\t\t);\n\t\t\tif (!result.success) {\n\t\t\t\tconst currentText = `${current?.provider ?? \"none\"}/${current?.id ?? \"none\"}`;\n\t\t\t\tconst lines = formatModelList(models);\n\t\t\t\tawait ctx.reply([`Current: ${currentText}`, ...lines, \"Use /model <n> or /model <provider/id>\"].join(\"\\n\"));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tconst numeric = Number.parseInt(arg, 10);\n\t\tif (!Number.isNaN(numeric) && /^\\d+$/.test(arg)) {\n\t\t\tconst cached = getCachedModels(ctx.key);\n\t\t\tif (!cached || numeric < 1 || numeric > cached.length) {\n\t\t\t\tawait ctx.reply(\"Invalid selection — run /model to see the current list.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait setModelAndReply(ctx, cached[numeric - 1]);\n\t\t\treturn;\n\t\t}\n\n\t\tconst models = getCachedModels(ctx.key) ?? (await refreshAndCacheModels(session, ctx.key));\n\t\tconst exact = findExactModelReferenceMatch(arg, models);\n\t\tif (exact) {\n\t\t\tawait setModelAndReply(ctx, exact);\n\t\t\treturn;\n\t\t}\n\n\t\tconst query = arg.toLowerCase();\n\t\tconst matches = models.filter(\n\t\t\t(m) =>\n\t\t\t\tm.id.toLowerCase().includes(query) ||\n\t\t\t\t`${m.provider}/${m.id}`.toLowerCase().includes(query) ||\n\t\t\t\t(m.name?.toLowerCase().includes(query) ?? false),\n\t\t);\n\t\tif (matches.length === 0) {\n\t\t\tawait ctx.reply(`No model matches \"${arg}\".`);\n\t\t\treturn;\n\t\t}\n\t\tif (matches.length > 1) {\n\t\t\tawait ctx.reply(formatModelList(matches).join(\"\\n\"));\n\t\t\treturn;\n\t\t}\n\t\tawait setModelAndReply(ctx, matches[0]);\n\t},\n};\n\nconst sessionsCommand: ChatCommand = {\n\tname: \"sessions\",\n\tdescription: \"list or switch sessions\",\n\tbypassBusy: false,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst session = ctx.session!;\n\t\tconst arg = ctx.args.trim();\n\t\tconst currentFile = session.sessionManager?.getSessionFile();\n\n\t\tif (!arg) {\n\t\t\tconst all = await SessionManager.list(process.cwd());\n\t\t\tall.sort((a, b) => b.modified.getTime() - a.modified.getTime());\n\t\t\tconst sessions = all.slice(0, 10);\n\t\t\tsetCachedSessions(ctx.key, sessions);\n\t\t\tconst items: PickerItem[] = sessions.map((s) => ({\n\t\t\t\tlabel: `${s.path === currentFile ? \"☾ \" : \"\"}${s.name ? truncate(s.name, 30) : truncate(s.firstMessage, 30) || \"(empty)\"}`,\n\t\t\t\tvalue: s.path,\n\t\t\t}));\n\t\t\tconst result = await createPicker(\n\t\t\t\tctx.adapter,\n\t\t\t\tctx.event.source,\n\t\t\t\t{\n\t\t\t\t\tkind: \"sessions\",\n\t\t\t\t\tsessionKey: ctx.key,\n\t\t\t\t\tinvokerId: ctx.event.source.userId,\n\t\t\t\t\titems,\n\t\t\t\t\tperPage: 8,\n\t\t\t\t\ttitle: \"Pick a session\",\n\t\t\t\t\tasync resolve(item) {\n\t\t\t\t\t\tawait ctx.bridge.switchSession(ctx.key, item.value);\n\t\t\t\t\t\tconst switched = await ctx.bridge.getSession(ctx.key);\n\t\t\t\t\t\tconst name = switched?.sessionManager?.getSessionName() ?? \"unnamed\";\n\t\t\t\t\t\tconst count = switched?.sessionManager?.getEntries().length ?? 0;\n\t\t\t\t\t\treturn { done: true, text: `☾ Switched to \"${name}\" (${count} msgs). History continues here.` };\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ replyTo: ctx.event.messageId, threadId: ctx.event.source.threadId },\n\t\t\t);\n\t\t\tif (!result.success) {\n\t\t\t\tconst lines = sessions.map((s, i) => {\n\t\t\t\t\tconst marker = s.path === currentFile ? \" ☾\" : \"\";\n\t\t\t\t\tconst label = s.name ? truncate(s.name, 40) : truncate(s.firstMessage, 40) || \"(empty)\";\n\t\t\t\t\treturn `${i + 1}) ${label}${marker} · ${formatRelativeTime(s.modified)} · ${s.messageCount} msgs`;\n\t\t\t\t});\n\t\t\t\tawait ctx.reply(\n\t\t\t\t\t[`Sessions for ${process.cwd()}`, ...lines, \"Use /sessions <n> or /sessions <id-prefix>\"].join(\"\\n\"),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tlet path: string | undefined;\n\t\tconst numeric = Number.parseInt(arg, 10);\n\t\tconst cached = getCachedSessions(ctx.key);\n\t\tif (!Number.isNaN(numeric) && /^\\d+$/.test(arg)) {\n\t\t\tif (!cached || numeric < 1 || numeric > cached.length) {\n\t\t\t\tawait ctx.reply(\"Invalid selection — run /sessions to see the current list.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpath = cached[numeric - 1].path;\n\t\t} else {\n\t\t\tconst pool = cached ?? (await SessionManager.list(process.cwd()));\n\t\t\tconst matches = pool.filter((s) => s.id.startsWith(arg) || s.path.startsWith(arg));\n\t\t\tif (matches.length === 0) {\n\t\t\t\tawait ctx.reply(`No session matches \"${arg}\".`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (matches.length > 1) {\n\t\t\t\tawait ctx.reply(`Multiple sessions match \"${arg}\" — use a longer prefix.`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpath = matches[0].path;\n\t\t}\n\n\t\tif (!path) {\n\t\t\tawait ctx.reply(\"No session selected.\");\n\t\t\treturn;\n\t\t}\n\n\t\tawait ctx.bridge.switchSession(ctx.key, path);\n\t\tconst switched = await ctx.bridge.getSession(ctx.key);\n\t\tconst name = switched?.sessionManager?.getSessionName() ?? \"unnamed\";\n\t\tconst count = switched?.sessionManager?.getEntries().length ?? 0;\n\t\tawait ctx.reply(`Switched to \"${name}\" (${count} msgs). History continues here.`);\n\t},\n};\n\nconst titleCommand: ChatCommand = {\n\tname: \"title\",\n\taliases: [\"name\"],\n\tdescription: \"name the current session\",\n\tbypassBusy: true,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst session = ctx.session!;\n\t\tconst name = ctx.args.trim();\n\t\tif (!name) {\n\t\t\tconst current = session.sessionManager?.getSessionName();\n\t\t\tawait ctx.reply(current ? `Session title: ${current}` : \"(unnamed)\");\n\t\t\treturn;\n\t\t}\n\t\tsession.setSessionName(name);\n\t\tconst readBack = session.sessionManager?.getSessionName() ?? name;\n\t\tawait ctx.reply(`Session titled \"${readBack}\".`);\n\t},\n};\n\nconst contextCommand: ChatCommand = {\n\tname: \"context\",\n\tdescription: \"estimated context window breakdown\",\n\tbypassBusy: true,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst session = ctx.session!;\n\t\tconst model = session.model;\n\t\tif (!model) {\n\t\t\tawait ctx.reply(\"No model selected.\");\n\t\t\treturn;\n\t\t}\n\t\tconst contextWindow = model.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) {\n\t\t\tawait ctx.reply(\"Context window unknown for this model.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst tools: ToolDefinition[] = session\n\t\t\t.getActiveToolNames()\n\t\t\t.map((name) => session.getToolDefinition(name))\n\t\t\t.filter((d): d is ToolDefinition => d !== undefined);\n\n\t\tconst breakdown = computeContextBreakdown({\n\t\t\tsystemPrompt: session.systemPrompt,\n\t\t\ttools,\n\t\t\tmessages: session.messages,\n\t\t\tcontextWindow,\n\t\t});\n\n\t\tconst usage = session.getContextUsage();\n\t\tconst tokens = usage?.tokens ?? breakdown.total;\n\t\tconst percent = usage?.percent ?? (contextWindow > 0 ? (tokens / contextWindow) * 100 : 0);\n\n\t\tconst messageTokens =\n\t\t\tbreakdown.user +\n\t\t\tbreakdown.assistantText +\n\t\t\tbreakdown.thinking +\n\t\t\tbreakdown.toolCalls +\n\t\t\tbreakdown.toolResults +\n\t\t\tbreakdown.summaries;\n\n\t\tconst stats = session.getSessionStats();\n\t\tawait ctx.reply(\n\t\t\t[\n\t\t\t\t`Context: ${tokens.toLocaleString(\"en-US\")} / ${contextWindow.toLocaleString(\"en-US\")} tokens (${Math.round(percent)}%)`,\n\t\t\t\t` system ${breakdown.systemPrompt.toLocaleString(\"en-US\")} · tools ${breakdown.toolDefinitions.toLocaleString(\"en-US\")} · messages ${messageTokens.toLocaleString(\"en-US\")}`,\n\t\t\t\t`Session: ${stats.totalMessages} messages · ${stats.userMessages} turns · model ${model.provider}/${model.id}`,\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t},\n};\n\nconst swarmCommand: ChatCommand = {\n\tname: \"swarm\",\n\tdescription: \"decompose a task across parallel subagents\",\n\tbypassBusy: false,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst task = ctx.args.trim();\n\t\tif (!task) {\n\t\t\tawait ctx.reply(\"Usage: /swarm <task> — decomposes the task across parallel subagents.\");\n\t\t\treturn true;\n\t\t}\n\t\tctx.event.text = buildSwarmPrompt(task);\n\t\treturn false;\n\t},\n};\n\nconst compactCommand: ChatCommand = {\n\tname: \"compact\",\n\tdescription: \"summarize and compress session context\",\n\tbypassBusy: true,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst session = ctx.session!;\n\t\tconst instructions = ctx.args.trim() || undefined;\n\t\ttry {\n\t\t\tconst result = await session.compact(instructions);\n\t\t\tconst before = result.tokensBefore.toLocaleString(\"en-US\");\n\t\t\tconst after =\n\t\t\t\tresult.estimatedTokensAfter !== undefined\n\t\t\t\t\t? `~${result.estimatedTokensAfter.toLocaleString(\"en-US\")}`\n\t\t\t\t\t: \"~?\";\n\t\t\tawait ctx.reply(`Compacted: ${before} → ${after} tokens.`);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (\n\t\t\t\tmessage.includes(\"Nothing to compact\") ||\n\t\t\t\tmessage.includes(\"Already compacted\") ||\n\t\t\t\tmessage.includes(\"No model selected\")\n\t\t\t) {\n\t\t\t\tawait ctx.reply(message);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t},\n};\n\nconst thinkingCommand: ChatCommand = {\n\tname: \"thinking\",\n\tdescription: \"get or set the thinking level\",\n\tbypassBusy: false,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst session = ctx.session!;\n\t\tconst levels = session.getAvailableThinkingLevels();\n\t\tif (!session.supportsThinking()) {\n\t\t\tawait ctx.reply(\n\t\t\t\t`Model ${session.model?.provider ?? \"none\"}/${session.model?.id ?? \"none\"} doesn't support thinking.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst arg = ctx.args.trim().toLowerCase() as ThinkingLevel;\n\t\tif (!arg) {\n\t\t\tconst current = session.thinkingLevel;\n\t\t\tconst items: PickerItem[] = levels.map((level) => ({\n\t\t\t\tlabel: `${level === current ? \"✓ \" : \"\"}${level}`,\n\t\t\t\tvalue: level,\n\t\t\t}));\n\t\t\tconst result = await createPicker(\n\t\t\t\tctx.adapter,\n\t\t\t\tctx.event.source,\n\t\t\t\t{\n\t\t\t\t\tkind: \"thinking\",\n\t\t\t\t\tsessionKey: ctx.key,\n\t\t\t\t\tinvokerId: ctx.event.source.userId,\n\t\t\t\t\titems,\n\t\t\t\t\tperPage: levels.length,\n\t\t\t\t\ttitle: \"Pick a thinking level\",\n\t\t\t\t\tasync resolve(item) {\n\t\t\t\t\t\tconst level = item.value as ThinkingLevel;\n\t\t\t\t\t\tsession.setThinkingLevel(level);\n\t\t\t\t\t\treturn { done: true, text: `☾ Thinking → ${level}` };\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ replyTo: ctx.event.messageId, threadId: ctx.event.source.threadId },\n\t\t\t);\n\t\t\tif (!result.success) {\n\t\t\t\tawait ctx.reply(`Level: ${current} — available: ${levels.join(\", \")}`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (!levels.includes(arg)) {\n\t\t\tawait ctx.reply(`Invalid level. Available: ${levels.join(\", \")}`);\n\t\t\treturn;\n\t\t}\n\t\tsession.setThinkingLevel(arg);\n\t\tawait ctx.reply(`Thinking → ${arg}`);\n\t},\n};\n\nexport const CHAT_COMMANDS: ChatCommand[] = [\n\tnewCommand,\n\tundoCommand,\n\tredoCommand,\n\tstopCommand,\n\tstatusCommand,\n\twhoamiCommand,\n\thelpCommand,\n\tmodelCommand,\n\tsessionsCommand,\n\ttitleCommand,\n\tcontextCommand,\n\tswarmCommand,\n\tcompactCommand,\n\tthinkingCommand,\n];\n\n/** Platform menu specs (e.g. Telegram setMyCommands): canonical names only, aliases skipped. */\nexport function botCommandSpecs(): { name: string; description: string }[] {\n\treturn CHAT_COMMANDS.map((c) => ({ name: c.name, description: c.description }));\n}\n\nexport function formatHelpText(): string {\n\tconst lines = [\"lunR gateway commands:\"];\n\tfor (const cmd of CHAT_COMMANDS) {\n\t\tconst names = [cmd.name, ...(cmd.aliases ?? [])].map((a) => `/${a}`).join(\" | \");\n\t\tlines.push(`${names} — ${cmd.description}`);\n\t}\n\tlines.push(\"\");\n\tlines.push(\"Tap to pick: /model, /thinking, /sessions (run without args to see buttons).\");\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Run a chat command with busy/session guards and error → \"⚠ one-line\".\n * Returns true when the event was consumed by the command, false when the\n * router should continue (e.g. /swarm mutates the event and wants a normal turn).\n */\nexport async function runChatCommand(cmd: ChatCommand, ctx: ChatCommandContext): Promise<boolean> {\n\tif (!cmd.bypassBusy && ctx.bridge.getStatus(ctx.key).busy) {\n\t\tawait ctx.reply(\"⏳ busy — /stop first or wait\");\n\t\treturn true;\n\t}\n\tif (cmd.needsSession) {\n\t\tconst session = await ctx.bridge.getSession(ctx.key);\n\t\tif (!session) {\n\t\t\tawait ctx.reply(\"No session yet — send a message first.\");\n\t\t\treturn true;\n\t\t}\n\t\tctx.session = session;\n\t}\n\ttry {\n\t\tconst consumed = await cmd.handler(ctx);\n\t\treturn consumed ?? true;\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tawait ctx.adapter.send(ctx.event.source.chatId, `⚠ ${oneLine(message)}`, {\n\t\t\treplyTo: ctx.event.messageId,\n\t\t\tthreadId: ctx.event.source.threadId,\n\t\t});\n\t\treturn true;\n\t}\n}\n\n/** Reply helper used by the router to build the ChatCommandContext. */\nexport async function sendCommandReply(adapter: PlatformAdapter, event: MessageEvent, text: string): Promise<void> {\n\tawait adapter.send(event.source.chatId, prefixLines(text, \"☾ \"), {\n\t\treplyTo: event.messageId,\n\t\tthreadId: event.source.threadId,\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"commands.d.ts","sourceRoot":"","sources":["../../src/gateway/commands.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAWH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAEvD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAmEhE,MAAM,WAAW,kBAAkB;IAClC,KAAK,EAAE,YAAY,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,eAAe,CAAC;IACzB,MAAM,EAAE,UAAU,CAAC;IACnB,OAAO,CAAC,EAAE,aAAa,CAAC;IACxB,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACnC,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,WAAW;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,OAAO,CAAC;IACpB,YAAY,EAAE,OAAO,CAAC;IAEtB,OAAO,CAAC,GAAG,EAAE,kBAAkB,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;CAC1D;AA4jBD,eAAO,MAAM,aAAa,EAAE,WAAW,EAetC,CAAC;AAEF,gGAAgG;AAChG,wBAAgB,eAAe,IAAI;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,EAAE,CAEzE;AAED,wBAAgB,cAAc,IAAI,MAAM,CASvC;AAED;;;;GAIG;AACH,wBAAsB,cAAc,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,kBAAkB,GAAG,OAAO,CAAC,OAAO,CAAC,CAwBhG;AAED,uEAAuE;AACvE,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAKjH","sourcesContent":["/**\n * lunR: gateway chat command registry.\n *\n * Every command is a small headless handler over AgentSession. Router.ts keeps\n * platform gating/authorization and delegates to runChatCommand for busy/session\n * guards, error wrapping, and /help generation.\n */\n\nimport type { ThinkingLevel } from \"@ashx-j/lunr-agent\";\nimport type { Model } from \"@ashx-j/lunr-ai/compat\";\nimport { computeContextBreakdown } from \"../core/context-breakdown.ts\";\nimport type { ToolDefinition } from \"../core/extensions/types.ts\";\nimport { findExactModelReferenceMatch } from \"../core/model-resolver.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.ts\";\nimport type { SessionInfo } from \"../core/session-manager.ts\";\nimport { SessionManager } from \"../core/session-manager.ts\";\nimport { buildSwarmPrompt } from \"../core/swarm.ts\";\nimport type { BridgeSession } from \"./agent-bridge.ts\";\nimport { createPicker, type PickerItem } from \"./buttons.ts\";\nimport type { BridgeLike } from \"./router.ts\";\nimport type { MessageEvent, PlatformAdapter } from \"./types.ts\";\n\nconst MODEL_CACHE_TTL_MS = 5 * 60 * 1000;\nconst SESSIONS_CACHE_TTL_MS = 5 * 60 * 1000;\nconst MAX_MODEL_LIST_LINES = 15;\nconst PROVIDER_PER_PAGE = 10;\nconst _MODEL_PER_PAGE = 8;\nconst MAX_MODELS_PER_PROVIDER = 50;\nconst MODEL_ID_MAX = 38;\nconst MODEL_CACHE_CAP = 100;\nconst SESSIONS_CACHE_CAP = 100;\n\ninterface ModelCacheEntry {\n\tmodels: Model<any>[];\n\texpires: number;\n}\n\ninterface SessionsCacheEntry {\n\tsessions: SessionInfo[];\n\texpires: number;\n}\n\nconst modelCache = new Map<string, ModelCacheEntry>();\nconst sessionsCache = new Map<string, SessionsCacheEntry>();\n\nfunction evictLRU<K, V>(map: Map<K, V>, cap: number): void {\n\twhile (map.size > cap) {\n\t\tconst first = map.keys().next().value;\n\t\tif (first !== undefined) map.delete(first);\n\t}\n}\n\nfunction getCachedModels(key: string): Model<any>[] | undefined {\n\tconst cached = modelCache.get(key);\n\tif (!cached) return undefined;\n\tif (Date.now() > cached.expires) {\n\t\tmodelCache.delete(key);\n\t\treturn undefined;\n\t}\n\t// LRU refresh.\n\tmodelCache.delete(key);\n\tmodelCache.set(key, cached);\n\treturn cached.models;\n}\n\nfunction setCachedModels(key: string, models: Model<any>[]): void {\n\tmodelCache.set(key, { models, expires: Date.now() + MODEL_CACHE_TTL_MS });\n\tevictLRU(modelCache, MODEL_CACHE_CAP);\n}\n\nfunction getCachedSessions(key: string): SessionInfo[] | undefined {\n\tconst cached = sessionsCache.get(key);\n\tif (!cached) return undefined;\n\tif (Date.now() > cached.expires) {\n\t\tsessionsCache.delete(key);\n\t\treturn undefined;\n\t}\n\tsessionsCache.delete(key);\n\tsessionsCache.set(key, cached);\n\treturn cached.sessions;\n}\n\nfunction setCachedSessions(key: string, sessions: SessionInfo[]): void {\n\tsessionsCache.set(key, { sessions, expires: Date.now() + SESSIONS_CACHE_TTL_MS });\n\tevictLRU(sessionsCache, SESSIONS_CACHE_CAP);\n}\n\nexport interface ChatCommandContext {\n\tevent: MessageEvent;\n\tkey: string;\n\tadapter: PlatformAdapter;\n\tbridge: BridgeLike;\n\tsession?: BridgeSession;\n\treply(text: string): Promise<void>;\n\targs: string;\n}\n\nexport interface ChatCommand {\n\tname: string;\n\taliases?: string[];\n\tdescription: string;\n\tbypassBusy: boolean;\n\tneedsSession: boolean;\n\t// biome-ignore lint/suspicious/noConfusingVoidType: handlers may return nothing; runChatCommand treats undefined as consumed.\n\thandler(ctx: ChatCommandContext): Promise<boolean | void>;\n}\n\nfunction oneLine(text: string): string {\n\treturn text.replace(/\\s+/g, \" \").trim().slice(0, 200);\n}\n\nfunction prefixLines(text: string, prefix: string): string {\n\treturn text\n\t\t.split(\"\\n\")\n\t\t.map((line, index) => (index === 0 ? prefix : \" \") + line)\n\t\t.join(\"\\n\");\n}\n\nfunction truncate(text: string, max: number): string {\n\tif (text.length <= max) return text;\n\treturn `${text.slice(0, max - 1)}…`;\n}\n\nfunction formatRelativeTime(date: Date): string {\n\tconst seconds = Math.max(0, Math.floor((Date.now() - date.getTime()) / 1000));\n\tif (seconds < 60) return `${seconds}s ago`;\n\tconst minutes = Math.floor(seconds / 60);\n\tif (minutes < 60) return `${minutes}m ago`;\n\tconst hours = Math.floor(minutes / 60);\n\tif (hours < 24) return `${hours}h ago`;\n\tconst days = Math.floor(hours / 24);\n\treturn `${days}d ago`;\n}\n\nfunction formatModelList(models: Model<any>[], maxLines = MAX_MODEL_LIST_LINES): string[] {\n\tif (models.length === 0) return [\"No models available.\"];\n\tconst byProvider = new Map<string, Model<any>[]>();\n\tfor (const model of models) {\n\t\tconst list = byProvider.get(model.provider) ?? [];\n\t\tlist.push(model);\n\t\tbyProvider.set(model.provider, list);\n\t}\n\tconst providers = [...byProvider.keys()].sort();\n\tconst lines: string[] = [];\n\tlet index = 1;\n\tfor (const provider of providers) {\n\t\tconst list = (byProvider.get(provider) ?? []).sort((a, b) => a.id.localeCompare(b.id));\n\t\tfor (const model of list) {\n\t\t\tlines.push(`${index}) ${provider}/${model.id}`);\n\t\t\tindex++;\n\t\t}\n\t}\n\tif (lines.length <= maxLines) return lines;\n\treturn [\n\t\t`${models.length} models across ${providers.length} providers.`,\n\t\t\"Use /model <provider/id> or /model <query>.\",\n\t\t...providers.map((p) => `- ${p}`),\n\t];\n}\n\nfunction groupModelsByProvider(models: Model<any>[]): Map<string, Model<any>[]> {\n\tconst byProvider = new Map<string, Model<any>[]>();\n\tfor (const model of models) {\n\t\tconst list = byProvider.get(model.provider) ?? [];\n\t\tlist.push(model);\n\t\tbyProvider.set(model.provider, list);\n\t}\n\tfor (const list of byProvider.values()) {\n\t\tlist.sort((a, b) => a.id.localeCompare(b.id));\n\t}\n\treturn byProvider;\n}\n\nfunction truncateModelId(id: string): string {\n\tconst lastSlash = id.lastIndexOf(\"/\");\n\tconst name = lastSlash >= 0 ? id.slice(lastSlash + 1) : id;\n\treturn truncate(name, MODEL_ID_MAX);\n}\n\nasync function refreshAndCacheModels(session: BridgeSession, key: string): Promise<Model<any>[]> {\n\tconst runtime: ModelRuntime = session.modelRuntime;\n\tawait runtime.refresh();\n\tconst models = [...(await runtime.getAvailable())].sort(\n\t\t(a, b) => a.provider.localeCompare(b.provider) || a.id.localeCompare(b.id),\n\t);\n\tsetCachedModels(key, models);\n\treturn models;\n}\n\nasync function setModelAndReply(ctx: ChatCommandContext, model: Model<any>): Promise<void> {\n\tconst session = ctx.session!;\n\ttry {\n\t\tawait session.setModel(model);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tif (message.includes(\"No API key\")) {\n\t\t\tawait ctx.reply(`No API key for ${model.provider}.`);\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n\tawait ctx.reply(`Model → ${model.provider}/${model.id} (thinking level re-clamped to ${session.thinkingLevel})`);\n}\n\nconst newCommand: ChatCommand = {\n\tname: \"new\",\n\taliases: [\"reset\"],\n\tdescription: \"start a fresh session for this chat\",\n\tbypassBusy: false,\n\tneedsSession: false,\n\tasync handler(ctx) {\n\t\tawait ctx.bridge.reset(ctx.key);\n\t\tawait ctx.reply(\"Session reset — next message starts a fresh session.\");\n\t},\n};\n\nconst undoCommand: ChatCommand = {\n\tname: \"undo\",\n\tdescription: \"rewind the session tree before the last user turn\",\n\tbypassBusy: false,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst { userText } = await ctx.bridge.undo(ctx.key);\n\t\tconst text = userText ? ` \"${truncate(userText, 60)}\"` : \"\";\n\t\tawait ctx.reply(`Undone — rewound before${text}. /redo to restore.`);\n\t},\n};\n\nconst redoCommand: ChatCommand = {\n\tname: \"redo\",\n\tdescription: \"restore the last undone turn\",\n\tbypassBusy: false,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tawait ctx.bridge.redo(ctx.key);\n\t\tawait ctx.reply(\"Redone.\");\n\t},\n};\n\nconst stopCommand: ChatCommand = {\n\tname: \"stop\",\n\tdescription: \"abort the running turn\",\n\tbypassBusy: true,\n\tneedsSession: false,\n\tasync handler(ctx) {\n\t\tawait ctx.bridge.abort(ctx.key);\n\t\tawait ctx.reply(\"Stopped.\");\n\t},\n};\n\nconst statusCommand: ChatCommand = {\n\tname: \"status\",\n\tdescription: \"session status\",\n\tbypassBusy: true,\n\tneedsSession: false,\n\tasync handler(ctx) {\n\t\tconst status = ctx.bridge.getStatus(ctx.key);\n\t\tconst age = status.createdAt\n\t\t\t? `${Math.max(0, Math.round((Date.now() - Date.parse(status.createdAt)) / 1000))}s`\n\t\t\t: \"no session yet\";\n\t\tawait ctx.reply(\n\t\t\t`${ctx.event.source.platform} · session age ${age} · ${status.busy ? \"busy\" : \"idle\"} · queue ${status.queueDepth}`,\n\t\t);\n\t},\n};\n\nconst whoamiCommand: ChatCommand = {\n\tname: \"whoami\",\n\tdescription: \"your ids and session key\",\n\tbypassBusy: true,\n\tneedsSession: false,\n\tasync handler(ctx) {\n\t\tconst { userId, chatId } = ctx.event.source;\n\t\tawait ctx.reply(`userId: ${userId}\\nchatId: ${chatId}\\nkey: ${ctx.key}`);\n\t},\n};\n\nconst helpCommand: ChatCommand = {\n\tname: \"help\",\n\tdescription: \"this message\",\n\tbypassBusy: true,\n\tneedsSession: false,\n\tasync handler(ctx) {\n\t\tawait ctx.reply(formatHelpText());\n\t},\n};\n\nconst modelCommand: ChatCommand = {\n\tname: \"model\",\n\tdescription: \"list or switch models\",\n\tbypassBusy: false,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst session = ctx.session!;\n\t\tconst arg = ctx.args.trim();\n\t\tif (!arg) {\n\t\t\tconst cached = getCachedModels(ctx.key);\n\t\t\tconst models = cached ?? (await refreshAndCacheModels(session, ctx.key));\n\t\t\tconst byProvider = groupModelsByProvider(models);\n\t\t\tconst current = session.model;\n\t\t\tconst currentRef = current ? `${current.provider}/${current.id}` : \"\";\n\t\t\tconst providers = [...byProvider.keys()].sort();\n\t\t\tconst providerItems: PickerItem[] = providers.map((provider) => ({\n\t\t\t\tlabel: `${current?.provider === provider ? \"✓ \" : \"\"}${provider} (${byProvider.get(provider)?.length ?? 0})`,\n\t\t\t\tvalue: provider,\n\t\t\t}));\n\n\t\t\tconst pickerOpts = {\n\t\t\t\treplyTo: ctx.event.messageId,\n\t\t\t\tthreadId: ctx.event.source.threadId,\n\t\t\t};\n\t\t\tconst result = await createPicker(\n\t\t\t\tctx.adapter,\n\t\t\t\tctx.event.source,\n\t\t\t\t{\n\t\t\t\t\tkind: \"model\",\n\t\t\t\t\tsessionKey: ctx.key,\n\t\t\t\t\tinvokerId: ctx.event.source.userId,\n\t\t\t\t\titems: providerItems,\n\t\t\t\t\tperPage: PROVIDER_PER_PAGE,\n\t\t\t\t\ttitle: \"Pick a model provider\",\n\t\t\t\t\tasync resolve(item) {\n\t\t\t\t\t\tif (item.value === \"__back__\") {\n\t\t\t\t\t\t\treturn { done: false, items: providerItems, title: \"Pick a model provider\" };\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!item.value.includes(\"/\")) {\n\t\t\t\t\t\t\tconst provider = item.value;\n\t\t\t\t\t\t\tconst list = byProvider.get(provider) ?? [];\n\t\t\t\t\t\t\tconst capped = list.slice(0, MAX_MODELS_PER_PROVIDER);\n\t\t\t\t\t\t\tconst note =\n\t\t\t\t\t\t\t\tlist.length > MAX_MODELS_PER_PROVIDER\n\t\t\t\t\t\t\t\t\t? ` — ${list.length - MAX_MODELS_PER_PROVIDER} more available`\n\t\t\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\t\t\tconst modelItems: PickerItem[] = [];\n\t\t\t\t\t\t\tfor (const m of capped) {\n\t\t\t\t\t\t\t\tconst ref = `${provider}/${m.id}`;\n\t\t\t\t\t\t\t\tmodelItems.push({\n\t\t\t\t\t\t\t\t\tlabel: `${currentRef === ref ? \"✓ \" : \"\"}${truncateModelId(m.id)}`,\n\t\t\t\t\t\t\t\t\tvalue: ref,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tmodelItems.unshift({ label: \"◀ Back\", value: \"__back__\" });\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\t\t\titems: modelItems,\n\t\t\t\t\t\t\t\ttitle: `${provider} (${list.length})${note}`,\n\t\t\t\t\t\t\t\tbreadcrumbs: provider,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst exact = findExactModelReferenceMatch(item.value, models);\n\t\t\t\t\t\tif (!exact) {\n\t\t\t\t\t\t\treturn { done: true, text: \"That model is no longer available.\" };\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait session.setModel(exact);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\t\tif (message.includes(\"No API key\")) {\n\t\t\t\t\t\t\t\treturn { done: true, text: `No API key for ${exact.provider}.` };\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tdone: true,\n\t\t\t\t\t\t\ttext: `☾ Model → ${exact.provider}/${exact.id} (thinking level re-clamped to ${session.thinkingLevel})`,\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tpickerOpts,\n\t\t\t);\n\t\t\tif (!result.success) {\n\t\t\t\tconst currentText = `${current?.provider ?? \"none\"}/${current?.id ?? \"none\"}`;\n\t\t\t\tconst lines = formatModelList(models);\n\t\t\t\tawait ctx.reply([`Current: ${currentText}`, ...lines, \"Use /model <n> or /model <provider/id>\"].join(\"\\n\"));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tconst numeric = Number.parseInt(arg, 10);\n\t\tif (!Number.isNaN(numeric) && /^\\d+$/.test(arg)) {\n\t\t\tconst cached = getCachedModels(ctx.key);\n\t\t\tif (!cached || numeric < 1 || numeric > cached.length) {\n\t\t\t\tawait ctx.reply(\"Invalid selection — run /model to see the current list.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait setModelAndReply(ctx, cached[numeric - 1]);\n\t\t\treturn;\n\t\t}\n\n\t\tconst models = getCachedModels(ctx.key) ?? (await refreshAndCacheModels(session, ctx.key));\n\t\tconst exact = findExactModelReferenceMatch(arg, models);\n\t\tif (exact) {\n\t\t\tawait setModelAndReply(ctx, exact);\n\t\t\treturn;\n\t\t}\n\n\t\tconst query = arg.toLowerCase();\n\t\tconst matches = models.filter(\n\t\t\t(m) =>\n\t\t\t\tm.id.toLowerCase().includes(query) ||\n\t\t\t\t`${m.provider}/${m.id}`.toLowerCase().includes(query) ||\n\t\t\t\t(m.name?.toLowerCase().includes(query) ?? false),\n\t\t);\n\t\tif (matches.length === 0) {\n\t\t\tawait ctx.reply(`No model matches \"${arg}\".`);\n\t\t\treturn;\n\t\t}\n\t\tif (matches.length > 1) {\n\t\t\tawait ctx.reply(formatModelList(matches).join(\"\\n\"));\n\t\t\treturn;\n\t\t}\n\t\tawait setModelAndReply(ctx, matches[0]);\n\t},\n};\n\nconst sessionsCommand: ChatCommand = {\n\tname: \"sessions\",\n\tdescription: \"list or switch sessions\",\n\tbypassBusy: false,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst session = ctx.session!;\n\t\tconst arg = ctx.args.trim();\n\t\tconst currentFile = session.sessionManager?.getSessionFile();\n\n\t\tif (!arg) {\n\t\t\tconst all = await SessionManager.list(process.cwd());\n\t\t\tall.sort((a, b) => b.modified.getTime() - a.modified.getTime());\n\t\t\tconst sessions = all.slice(0, 10);\n\t\t\tsetCachedSessions(ctx.key, sessions);\n\t\t\tconst items: PickerItem[] = sessions.map((s) => ({\n\t\t\t\tlabel: `${s.path === currentFile ? \"☾ \" : \"\"}${s.name ? truncate(s.name, 30) : truncate(s.firstMessage, 30) || \"(empty)\"}`,\n\t\t\t\tvalue: s.path,\n\t\t\t}));\n\t\t\tconst result = await createPicker(\n\t\t\t\tctx.adapter,\n\t\t\t\tctx.event.source,\n\t\t\t\t{\n\t\t\t\t\tkind: \"sessions\",\n\t\t\t\t\tsessionKey: ctx.key,\n\t\t\t\t\tinvokerId: ctx.event.source.userId,\n\t\t\t\t\titems,\n\t\t\t\t\tperPage: 8,\n\t\t\t\t\ttitle: \"Pick a session\",\n\t\t\t\t\tasync resolve(item) {\n\t\t\t\t\t\tawait ctx.bridge.switchSession(ctx.key, item.value);\n\t\t\t\t\t\tconst switched = await ctx.bridge.getSession(ctx.key);\n\t\t\t\t\t\tconst name = switched?.sessionManager?.getSessionName() ?? \"unnamed\";\n\t\t\t\t\t\tconst count = switched?.sessionManager?.getEntries().length ?? 0;\n\t\t\t\t\t\treturn { done: true, text: `☾ Switched to \"${name}\" (${count} msgs). History continues here.` };\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ replyTo: ctx.event.messageId, threadId: ctx.event.source.threadId },\n\t\t\t);\n\t\t\tif (!result.success) {\n\t\t\t\tconst lines = sessions.map((s, i) => {\n\t\t\t\t\tconst marker = s.path === currentFile ? \" ☾\" : \"\";\n\t\t\t\t\tconst label = s.name ? truncate(s.name, 40) : truncate(s.firstMessage, 40) || \"(empty)\";\n\t\t\t\t\treturn `${i + 1}) ${label}${marker} · ${formatRelativeTime(s.modified)} · ${s.messageCount} msgs`;\n\t\t\t\t});\n\t\t\t\tawait ctx.reply(\n\t\t\t\t\t[`Sessions for ${process.cwd()}`, ...lines, \"Use /sessions <n> or /sessions <id-prefix>\"].join(\"\\n\"),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tlet path: string | undefined;\n\t\tconst numeric = Number.parseInt(arg, 10);\n\t\tconst cached = getCachedSessions(ctx.key);\n\t\tif (!Number.isNaN(numeric) && /^\\d+$/.test(arg)) {\n\t\t\tif (!cached || numeric < 1 || numeric > cached.length) {\n\t\t\t\tawait ctx.reply(\"Invalid selection — run /sessions to see the current list.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpath = cached[numeric - 1].path;\n\t\t} else {\n\t\t\tconst pool = cached ?? (await SessionManager.list(process.cwd()));\n\t\t\tconst matches = pool.filter((s) => s.id.startsWith(arg) || s.path.startsWith(arg));\n\t\t\tif (matches.length === 0) {\n\t\t\t\tawait ctx.reply(`No session matches \"${arg}\".`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (matches.length > 1) {\n\t\t\t\tawait ctx.reply(`Multiple sessions match \"${arg}\" — use a longer prefix.`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpath = matches[0].path;\n\t\t}\n\n\t\tif (!path) {\n\t\t\tawait ctx.reply(\"No session selected.\");\n\t\t\treturn;\n\t\t}\n\n\t\tawait ctx.bridge.switchSession(ctx.key, path);\n\t\tconst switched = await ctx.bridge.getSession(ctx.key);\n\t\tconst name = switched?.sessionManager?.getSessionName() ?? \"unnamed\";\n\t\tconst count = switched?.sessionManager?.getEntries().length ?? 0;\n\t\tawait ctx.reply(`Switched to \"${name}\" (${count} msgs). History continues here.`);\n\t},\n};\n\nconst titleCommand: ChatCommand = {\n\tname: \"title\",\n\taliases: [\"name\"],\n\tdescription: \"name the current session\",\n\tbypassBusy: true,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst session = ctx.session!;\n\t\tconst name = ctx.args.trim();\n\t\tif (!name) {\n\t\t\tconst current = session.sessionManager?.getSessionName();\n\t\t\tawait ctx.reply(current ? `Session title: ${current}` : \"(unnamed)\");\n\t\t\treturn;\n\t\t}\n\t\tsession.setSessionName(name);\n\t\tconst readBack = session.sessionManager?.getSessionName() ?? name;\n\t\tawait ctx.reply(`Session titled \"${readBack}\".`);\n\t},\n};\n\nconst contextCommand: ChatCommand = {\n\tname: \"context\",\n\tdescription: \"estimated context window breakdown\",\n\tbypassBusy: true,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst session = ctx.session!;\n\t\tconst model = session.model;\n\t\tif (!model) {\n\t\t\tawait ctx.reply(\"No model selected.\");\n\t\t\treturn;\n\t\t}\n\t\tconst contextWindow = model.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) {\n\t\t\tawait ctx.reply(\"Context window unknown for this model.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst tools: ToolDefinition[] = session\n\t\t\t.getActiveToolNames()\n\t\t\t.map((name) => session.getToolDefinition(name))\n\t\t\t.filter((d): d is ToolDefinition => d !== undefined);\n\n\t\tconst breakdown = computeContextBreakdown({\n\t\t\tsystemPrompt: session.systemPrompt,\n\t\t\ttools,\n\t\t\tmessages: session.messages,\n\t\t\tcontextWindow,\n\t\t});\n\n\t\tconst usage = session.getContextUsage();\n\t\tconst tokens = usage?.tokens ?? breakdown.total;\n\t\tconst percent = usage?.percent ?? (contextWindow > 0 ? (tokens / contextWindow) * 100 : 0);\n\n\t\tconst messageTokens =\n\t\t\tbreakdown.user +\n\t\t\tbreakdown.assistantText +\n\t\t\tbreakdown.thinking +\n\t\t\tbreakdown.toolCalls +\n\t\t\tbreakdown.toolResults +\n\t\t\tbreakdown.summaries;\n\n\t\tconst stats = session.getSessionStats();\n\t\tawait ctx.reply(\n\t\t\t[\n\t\t\t\t`Context: ${tokens.toLocaleString(\"en-US\")} / ${contextWindow.toLocaleString(\"en-US\")} tokens (${Math.round(percent)}%)`,\n\t\t\t\t` system ${breakdown.systemPrompt.toLocaleString(\"en-US\")} · tools ${breakdown.toolDefinitions.toLocaleString(\"en-US\")} · messages ${messageTokens.toLocaleString(\"en-US\")}`,\n\t\t\t\t`Session: ${stats.totalMessages} messages · ${stats.userMessages} turns · model ${model.provider}/${model.id}`,\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t},\n};\n\nconst swarmCommand: ChatCommand = {\n\tname: \"swarm\",\n\tdescription: \"decompose a task across parallel subagents\",\n\tbypassBusy: false,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst task = ctx.args.trim();\n\t\tif (!task) {\n\t\t\tawait ctx.reply(\"Usage: /swarm <task> — decomposes the task across parallel subagents.\");\n\t\t\treturn true;\n\t\t}\n\t\tctx.event.text = buildSwarmPrompt(task);\n\t\treturn false;\n\t},\n};\n\nconst compactCommand: ChatCommand = {\n\tname: \"compact\",\n\tdescription: \"summarize and compress session context\",\n\tbypassBusy: true,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst session = ctx.session!;\n\t\tconst instructions = ctx.args.trim() || undefined;\n\t\ttry {\n\t\t\tconst result = await session.compact(instructions);\n\t\t\tconst before = result.tokensBefore.toLocaleString(\"en-US\");\n\t\t\tconst after =\n\t\t\t\tresult.estimatedTokensAfter !== undefined\n\t\t\t\t\t? `~${result.estimatedTokensAfter.toLocaleString(\"en-US\")}`\n\t\t\t\t\t: \"~?\";\n\t\t\tawait ctx.reply(`Compacted: ${before} → ${after} tokens.`);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (\n\t\t\t\tmessage.includes(\"Nothing to compact\") ||\n\t\t\t\tmessage.includes(\"Already compacted\") ||\n\t\t\t\tmessage.includes(\"No model selected\")\n\t\t\t) {\n\t\t\t\tawait ctx.reply(message);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t},\n};\n\nconst thinkingCommand: ChatCommand = {\n\tname: \"thinking\",\n\taliases: [\"effort\", \"reasoning\"],\n\tdescription: \"get or set the thinking level\",\n\tbypassBusy: false,\n\tneedsSession: true,\n\tasync handler(ctx) {\n\t\tconst session = ctx.session!;\n\t\tconst levels = session.getAvailableThinkingLevels();\n\t\tif (!session.supportsThinking()) {\n\t\t\tawait ctx.reply(\n\t\t\t\t`Model ${session.model?.provider ?? \"none\"}/${session.model?.id ?? \"none\"} doesn't support thinking.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst arg = ctx.args.trim().toLowerCase() as ThinkingLevel;\n\t\tif (!arg) {\n\t\t\tconst current = session.thinkingLevel;\n\t\t\tconst items: PickerItem[] = levels.map((level) => ({\n\t\t\t\tlabel: `${level === current ? \"✓ \" : \"\"}${level}`,\n\t\t\t\tvalue: level,\n\t\t\t}));\n\t\t\tconst result = await createPicker(\n\t\t\t\tctx.adapter,\n\t\t\t\tctx.event.source,\n\t\t\t\t{\n\t\t\t\t\tkind: \"thinking\",\n\t\t\t\t\tsessionKey: ctx.key,\n\t\t\t\t\tinvokerId: ctx.event.source.userId,\n\t\t\t\t\titems,\n\t\t\t\t\tperPage: levels.length,\n\t\t\t\t\ttitle: \"Pick a thinking level\",\n\t\t\t\t\tasync resolve(item) {\n\t\t\t\t\t\tconst level = item.value as ThinkingLevel;\n\t\t\t\t\t\tsession.setThinkingLevel(level);\n\t\t\t\t\t\treturn { done: true, text: `☾ Thinking → ${level}` };\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ replyTo: ctx.event.messageId, threadId: ctx.event.source.threadId },\n\t\t\t);\n\t\t\tif (!result.success) {\n\t\t\t\tawait ctx.reply(`Level: ${current} — available: ${levels.join(\", \")}`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (!levels.includes(arg)) {\n\t\t\tawait ctx.reply(`Invalid level. Available: ${levels.join(\", \")}`);\n\t\t\treturn;\n\t\t}\n\t\tsession.setThinkingLevel(arg);\n\t\tawait ctx.reply(`Thinking → ${arg}`);\n\t},\n};\n\nexport const CHAT_COMMANDS: ChatCommand[] = [\n\tnewCommand,\n\tundoCommand,\n\tredoCommand,\n\tstopCommand,\n\tstatusCommand,\n\twhoamiCommand,\n\thelpCommand,\n\tmodelCommand,\n\tsessionsCommand,\n\ttitleCommand,\n\tcontextCommand,\n\tswarmCommand,\n\tcompactCommand,\n\tthinkingCommand,\n];\n\n/** Platform menu specs (e.g. Telegram setMyCommands): canonical names only, aliases skipped. */\nexport function botCommandSpecs(): { name: string; description: string }[] {\n\treturn CHAT_COMMANDS.map((c) => ({ name: c.name, description: c.description }));\n}\n\nexport function formatHelpText(): string {\n\tconst lines = [\"lunR gateway commands:\"];\n\tfor (const cmd of CHAT_COMMANDS) {\n\t\tconst names = [cmd.name, ...(cmd.aliases ?? [])].map((a) => `/${a}`).join(\" | \");\n\t\tlines.push(`${names} — ${cmd.description}`);\n\t}\n\tlines.push(\"\");\n\tlines.push(\"Tap to pick: /model, /thinking, /sessions (run without args to see buttons).\");\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Run a chat command with busy/session guards and error → \"⚠ one-line\".\n * Returns true when the event was consumed by the command, false when the\n * router should continue (e.g. /swarm mutates the event and wants a normal turn).\n */\nexport async function runChatCommand(cmd: ChatCommand, ctx: ChatCommandContext): Promise<boolean> {\n\tif (!cmd.bypassBusy && ctx.bridge.getStatus(ctx.key).busy) {\n\t\tawait ctx.reply(\"⏳ busy — /stop first or wait\");\n\t\treturn true;\n\t}\n\tif (cmd.needsSession) {\n\t\tconst session = await ctx.bridge.getSession(ctx.key);\n\t\tif (!session) {\n\t\t\tawait ctx.reply(\"No session yet — send a message first.\");\n\t\t\treturn true;\n\t\t}\n\t\tctx.session = session;\n\t}\n\ttry {\n\t\tconst consumed = await cmd.handler(ctx);\n\t\treturn consumed ?? true;\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tawait ctx.adapter.send(ctx.event.source.chatId, `⚠ ${oneLine(message)}`, {\n\t\t\treplyTo: ctx.event.messageId,\n\t\t\tthreadId: ctx.event.source.threadId,\n\t\t});\n\t\treturn true;\n\t}\n}\n\n/** Reply helper used by the router to build the ChatCommandContext. */\nexport async function sendCommandReply(adapter: PlatformAdapter, event: MessageEvent, text: string): Promise<void> {\n\tawait adapter.send(event.source.chatId, prefixLines(text, \"☾ \"), {\n\t\treplyTo: event.messageId,\n\t\tthreadId: event.source.threadId,\n\t});\n}\n"]}
|
package/dist/gateway/commands.js
CHANGED