import { execFile } from "node:child_process"; import { createBashToolDefinition, type ExtensionAPI, type ExtensionContext, type ThemeColor, } from "@earendil-works/pi-coding-agent"; import { Text } from "@earendil-works/pi-tui"; import { Type } from "typebox"; import { diagnosticHelp } from "./diagnostic-help.ts"; import { findNu, freshOperations } from "./runtime.ts"; import { closeDebug, dbg } from "./src/debug.ts"; import { parseBooleanSetting, registerSettingFlag, resolveSetting, type SettingDeclaration, } from "./src/pi-ext-settings.ts"; // Precedence: --nushell, PI_NUSHELL_ENABLE, trusted project, user, false. const ENABLE_SETTING: SettingDeclaration = { key: "nushell.enable", parse: parseBooleanSetting, default: false, flag: { name: "nushell", type: "boolean", description: "Enable Nushell tools at startup instead of bash and powershell", }, env: "PI_NUSHELL_ENABLE", }; const DISPLACED_SHELLS = new Set(["bash", "powershell"]); const STATE_ENTRY = "nushell-tools"; type NushellState = { enabled: boolean; displaced: string[]; }; const NU_COLORS: Record = { 32: "syntaxString", 33: "syntaxOperator", 34: "syntaxPunctuation", 35: "syntaxVariable", 36: "syntaxFunction", 90: "syntaxVariable", 96: "syntaxKeyword", }; // Translate Nu's fixed ANSI palette into the active Pi theme at render time. function themeNuHighlight( ansi: string, theme: Parameters< NonNullable["renderCall"]> >[1], ): string { let output = ""; let start = 0; let color: ThemeColor = "toolOutput"; for (const match of ansi.matchAll(/\x1b\[([0-9;]*)m/g)) { output += theme.fg(color, ansi.slice(start, match.index)); const codes = match[1]?.split(";").map(Number) ?? []; const foreground = codes.findLast( (code) => (code >= 30 && code <= 37) || (code >= 90 && code <= 97), ); color = foreground === 35 && codes.includes(1) ? "syntaxPunctuation" : (NU_COLORS[foreground ?? -1] ?? "toolOutput"); start = match.index + match[0].length; } return output + theme.fg(color, ansi.slice(start)); } // Nu highlighting parses source too; only the command heading is highlighted. const highlightCache = new WeakMap(); function renderNuCall( args: { command: string; timeout?: number }, theme: Parameters< NonNullable["renderCall"]> >[1], context: Parameters< NonNullable["renderCall"]> >[2], ) { const state = context.state; if (context.executionStarted && state.startedAt === undefined) { state.startedAt = Date.now(); state.endedAt = undefined; } const command = typeof args?.command === "string" ? args.command : ""; let cached = highlightCache.get(state); if (context.argsComplete && cached?.command !== command) { const entry = { command, text: command }; cached = entry; highlightCache.set(state, entry); const binary = command && command.length <= 16_000 ? findNu() : undefined; if (binary) { execFile( binary, [ "--no-config-file", "--no-history", "-c", "$env.PI_NU_HIGHLIGHT_INPUT | nu-highlight", ], { env: { ...process.env, PI_NU_HIGHLIGHT_INPUT: command }, encoding: "utf8", timeout: 1000, maxBuffer: 128 * 1024, windowsHide: true, }, (error, stdout) => { if (error || highlightCache.get(state) !== entry) return; entry.text = stdout.trimEnd(); context.invalidate(); }, ); } } const highlighted = cached?.command === command ? cached.text : command; const text = context.lastComponent instanceof Text ? context.lastComponent : new Text("", 0, 0); text.setText( `${theme.fg("toolTitle", theme.bold(" nu>"))} ${themeNuHighlight(highlighted || "...", theme)}${args?.timeout ? theme.fg("muted", ` (timeout ${args.timeout}s)`) : ""}`, ); return text; } export default function nushellExtension(pi: ExtensionAPI): void { let enabled = false; let displaced: string[] = []; registerSettingFlag(pi, ENABLE_SETTING); function persist(): void { pi.appendEntry(STATE_ENTRY, { enabled, displaced }); } function restore(ctx: ExtensionContext): void { enabled = false; displaced = []; for (const entry of ctx.sessionManager.getBranch()) { if (entry.type !== "custom" || entry.customType !== STATE_ENTRY) continue; const state = entry.data; if ( typeof state !== "object" || state === null || !("enabled" in state) || !("displaced" in state) || typeof state.enabled !== "boolean" || !Array.isArray(state.displaced) || state.displaced.length > DISPLACED_SHELLS.size || (!state.enabled && state.displaced.length !== 0) || state.displaced.some( (shell) => typeof shell !== "string" || !DISPLACED_SHELLS.has(shell), ) || new Set(state.displaced).size !== state.displaced.length ) continue; enabled = state.enabled; displaced = state.displaced; } // Native CLI selection wins; saved provenance never activates tools. if (!pi.getActiveTools().includes("nu")) { enabled = false; displaced = []; } } function deactivate(): void { if (!enabled) return; const active = pi.getActiveTools().filter((tool) => tool !== "nu"); pi.setActiveTools([ ...active, ...displaced.filter((tool) => !active.includes(tool)), ]); dbg?.("tools.disabled", { count: displaced.length }); displaced = []; enabled = false; persist(); } function activate(ctx: ExtensionContext, quiet = false): void { if (enabled && pi.getActiveTools().includes("nu")) { // Another extension may re-add a shell on top of a resumed loadout. const active = pi.getActiveTools(); const returned = active.filter((tool) => DISPLACED_SHELLS.has(tool)); if (!returned.length) return; displaced = [...new Set([...displaced, ...returned])]; pi.setActiveTools(active.filter((tool) => !DISPLACED_SHELLS.has(tool))); persist(); dbg?.("tools.enabled", { count: returned.length }); return; } if (!findNu()) { ctx.ui.notify( "Nushell executable not found on PATH; tools unchanged", "warning", ); dbg?.("tools.enable.error", { kind: "nu_not_found" }); return; } const available = new Set(pi.getAllTools().map((tool) => tool.name)); const missing = ["nu"].filter((name) => !available.has(name)); if (missing.length) { ctx.ui.notify( `Nushell tools excluded by tool allowlist: ${missing.join(", ")}; tools unchanged`, "warning", ); dbg?.("tools.enable.error", { kind: "tools_excluded", count: missing.length, }); return; } const active = pi.getActiveTools(); displaced = active.filter((tool) => DISPLACED_SHELLS.has(tool)); pi.setActiveTools([ ...active.filter((tool) => !DISPLACED_SHELLS.has(tool)), "nu", ]); enabled = true; persist(); dbg?.("tools.enabled", { count: displaced.length }); if (!quiet) ctx.ui.notify("Nushell tools on: nu (fresh)", "info"); } const freshTool = createBashToolDefinition(process.cwd(), { operations: { exec: (command, cwd, options) => { const binary = findNu(); if (!binary) throw new Error("Nushell executable not found on PATH"); return freshOperations(binary).exec(command, cwd, options); }, }, }); pi.registerTool({ ...freshTool, name: "nu", outputSchema: Type.Intersect([ freshTool.outputSchema ?? Type.Object({}), Type.Object({ diagnostic_help: Type.Optional( Type.Object({ command: Type.String(), text: Type.String(), truncated: Type.Boolean(), }), ), }), ]), async execute(id, params, signal, onUpdate, ctx) { const started = performance.now(); const result = await freshTool.execute(id, params, signal, onUpdate, ctx); const output = result.structuredContent; if ( !output || typeof output !== "object" || Array.isArray(output) || !("exit_code" in output) || typeof output["exit_code"] !== "number" || output["exit_code"] === 0 || signal?.aborted ) return result; const binary = findNu(); if (!binary) return result; const budget = params.timeout === undefined ? 1000 : Math.min( 1000, params.timeout * 1000 - (performance.now() - started), ); const help = await diagnosticHelp( binary, params.command, ctx.cwd, signal, budget, ); if (!help || signal?.aborted) return result; return { ...result, content: [ ...result.content, { type: "text", text: `Installed Nushell help (${help.command}):\n${help.text}${help.truncated ? "\n[Help truncated]" : ""}`, }, ], structuredContent: { ...output, diagnostic_help: help }, }; }, annotations: { readOnlyHint: false }, defaultActive: false, label: " nu", description: "Execute Nushell source directly in a fresh process in Pi's cwd. State does not persist between calls. Streams output; timeout in seconds is optional.", promptSnippet: "Execute independent Nushell commands with nu; each call starts fresh", promptGuidelines: [ "Ordinary calls need no nu -c wrapper. Nu commands may share names with Unix commands but differ in flags and output types. Pipelines carry structured values; use ^name to explicitly invoke an external executable.", "Before using unfamiliar Nushell commands or flags, consult installed help rather than guessing Bash/GNU equivalents. Use help for exact syntax (multiword example: help str join), help --find for discovery. Language reference: help operators, help pipe-and-redirect, help escapes. After syntax/type errors, consult relevant help before retrying. Familiar commands do not require a help call.", ], renderCall: renderNuCall, }); pi.registerCommand("nushell", { description: "Toggle fresh Nushell tools and replace active bash/powershell", getArgumentCompletions: (prefix) => { const matches = ["on", "off"].filter((value) => value.startsWith(prefix)); return matches.length ? matches.map((value) => ({ value, label: value })) : null; }, async handler(arg, ctx) { const action = arg.trim() || (enabled ? "off" : "on"); if (action === "on") { activate(ctx); return; } if (action === "off") { if (!enabled) return; deactivate(); ctx.ui.notify("Nushell tools off", "info"); return; } ctx.ui.notify("Usage: /nushell [on|off]", "warning"); }, }); pi.on("session_start", async (_event, ctx) => { dbg?.("session.start"); restore(ctx); const setting = resolveSetting(pi, ctx, ENABLE_SETTING); if (!setting.ok) { ctx.ui.notify(`${setting.error}; tools unchanged`, "warning"); dbg?.("settings.invalid", { source: setting.source }); } else if (setting.value) activate(ctx, true); }); pi.on("session_tree", async (_event, ctx) => { restore(ctx); }); pi.on("session_shutdown", async () => { dbg?.("session.shutdown"); closeDebug(); }); }