repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

feat(nushell): add fresh and persistent Nu tools

efd87042e23a91f7f46dea67b6b642b650a8710d

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (12)

extensions/nushell/E2E.md

Added
new file mode 100644
1 +# Nushell JSON-mode evidence
3 +`//extensions/nushell:e2e-json` invokes real Pi with `--print --mode json --no-session --nushell`, an isolated cwd, explicit Nu tool allowlist, and opt-in JSONL diagnostics.
4 +Each case retains `invocation.json`, `events.jsonl`, `debug.jsonl`, `analysis.json`, `result.json`, `final.txt`, `stderr.txt`, and generated modules/fixtures under `.pi/tmp/nushell-json/<run>/`.
5 +The trace case also retains `validation.json`, which compares its generated Nu module against independent JS calculations over completed **real** debug logs.
6 +`--verify <run-directory>` repeats only trace validation for a retained run.
8 +## Observations
10 +The first restricted invocation at `.pi/tmp/nushell-json/2026-09-26T18-18-39-460Z/` exposed a Pi CLI allowlist conflict: `--tools bash,read,write,edit` excluded both Nu tools despite `--nushell`.
11 +Activation now checks Pi's configured registry before displacing shell tools and reports excluded tools instead of claiming success.
12 +An unrestricted pilot at `.pi/tmp/nushell-json/2026-09-26T18-19-45-271Z/` demonstrated a model invoking `^nu -c` inside `nu`, adding an avoidable second process.
13 +Tool guidance now directs agents to pass Nu source directly, avoid nested Nu processes, and prefer Nu builtins for suitable work.
15 +All five module exercises plus the session-state probe in `.pi/tmp/nushell-json/2026-09-26T18-43-52-847Z/` settled with Nu tool calls and no nested Nu invocations.
16 +That six-case run cost $0.4304 in projected API pricing and took 473 seconds; code-generation errors were corrected by agents before their final checks.
17 +The first generated `trace.nu` consumed an invented JSONL schema despite passing its own synthetic fixture, so these agent claims alone did **not** prove actual logger compatibility.
19 +Diagnostics now correlate interleaved calls by `callId`, pair early failures with terminal events, and preserve Pi's logger PID separately from Nu process PIDs.
20 +Tests cover overlapping fresh calls, preflight failures, worker startup failures, private file permissions, error-code redaction, session state, and abort/reset handling.
21 +The trace and state probes in `.pi/tmp/nushell-json/2026-09-26T19-02-22-798Z/` use real diagnostic fields and generated fixtures.
22 +The independent verifier initially failed because its stripped environment made Mise's already-configured file appear untrusted; `trace/validation-failed-mise.json` retains the exact failure.
23 +Restoring the existing Mise environment made verification run, then a harmless generated-result field naming difference caused a strict equality failure retained in `trace/validation-schema-diff.json`.
24 +Semantic normalization now compares the generated module's summaries with independent counts and nearest-rank percentiles over both completed real logs; `trace/validation.json` records two passes.
26 +`bench-current.txt` measured 36.25 ms cold, 36.72 ms fresh, and 822 µs warm, 25 runs each.
27 +Later correlated-logger samples were 10–20% slower, but `bench-load.txt` documents substantial concurrent compiler load; no causal performance claim follows from that comparison.
29 +## Limits
31 +These are bounded integration probes, not proof of zero bugs or universal agent optimality.
32 +The 110-second MCP deadline, detached external-process cleanup after cancellation, other operating systems, and diverse model behavior remain unverified live.
33 +Generated Nu modules are **prototypes in evidence workspaces**, not promoted packages.
34 +Do not read initial `trace.nu` prototypes as compatible with `PI_NUSHELL_DEBUG`; use the verified later trace fixture and module.

extensions/nushell/README.md

Added
new file mode 100644
1 +# nushell
3 +Opt-in Nushell tools for Pi.
5 +Loaded through the root pi-ext package; requires `nu` on `PATH`.
7 +`pi --nushell` enables both tools at session start and hides active `bash` and `powershell` from the model.
8 +`/nushell` toggles the same tools during a session.
9 +`/nushell on`, `/nushell off`, and `/nushell reset` are explicit alternatives.
10 +`/nushell reset` discards the persistent worker's state without changing active tools.
11 +Turning the tools off restores only the shell tools displaced by this toggle.
12 +Pi's `!` and `!!` remain owned by `nu-bang`.
14 +- `nu`: fresh `nu --no-config-file --no-history --error-style fancy --table-mode markdown -c` process per call, streaming output and optional timeout.
15 +- `nu_session`: persistent native Nu MCP worker, serialized calls, state scoped to the active Pi session, reset on session navigation, toggle-off, or shutdown.
17 +Use `nu` unless a later call requires variables, functions, imports, environment changes, or cwd set by an earlier `nu_session` call.
18 +Both tools use Nushell syntax, not Bash or PowerShell.
19 +Nu's native commands handle structured data; `^name` explicitly runs an external executable.
20 +Use `help <command>` for installed Nu guidance.
22 +MCP evaluates expressions and returns NUON with `output` and `history_index`.
23 +`print` writes to the worker's stderr, which also carries verbose Nu protocol diagnostics and is discarded; return an expression instead.
24 +MCP does not treat a nonzero external exit code as an evaluation error: use `^command | complete` and inspect `exit_code`.
25 +MCP collects output rather than streaming it, and replaces responses over its default 10 KB limit with a history reference.
26 +Each persistent request has a 110-second client deadline; interruption resets worker state, but detached external processes may continue running.
27 +Reset does not roll back filesystem changes.
29 +Set `nushell.enable` in Pi's `settings.json` to activate both tools at session start:
31 +```json
33 + "nushell": { "enable": true }
35 +```
37 +Disabled by default; project settings override user settings, and `--nushell` enables the tools regardless of settings.
38 +`/nushell off` still disables them for the current session.
40 +Set `PI_NUSHELL_DEBUG` to an existing directory's log-file path for opt-in JSONL diagnostics.
41 +The log records startup, tool selection, process/worker lifecycle, request duration, exit codes, output byte counts, and safe error classifications; it never records command text, output content, or environment values.
42 +`fresh.start`/`fresh.finish` and `session.request.start`/`session.request.finish`/`session.request.error` carry matching opaque `callId` values, including overlapping fresh calls.
43 +Terminal events carry `durationMs`; `fresh.finish` also records `outcome` and `exitCode`; session errors may carry an MCP `code` or allowlisted Nu `nuCode`.
44 +The envelope `pid` identifies the Pi logger process; `childPid` and `workerPid` identify Nu processes.
45 +New log files use owner-only permissions; preexisting group/world-readable files and symlinks are refused on Unix.
46 +Logging failures warn without writing to Pi's terminal output stream.
48 +`mise run //extensions/nushell:e2e-json` runs five isolated module exercises plus a persistent-state probe via Pi print JSON mode with `--no-session`; it retains prompts, JSON events, debug logs, outputs, and analyses under `.pi/tmp/nushell-json/`.
49 +`mise run //extensions/nushell:bench` reports fresh, cold persistent, and warm persistent end-to-end tool latency in benchstat format.
50 +It uses the real Pi extension harness and Nu binary, warms each path, and alternates fresh and warm call order each round.
51 +MCP schemas load with the first persistent worker rather than at inert extension startup.
52 +On Linux (Node 26.9.0, Pi 0.87.1, Nu 0.115.1), `//:extension-startup-bench` measured RPC readiness falling from 478 ms ±7% to 449 ms ±7% (25 runs each; benchstat p=0.003).
53 +The Nu call benchmark showed no significant fresh, cold-worker, or warm-worker latency changes (20 runs each); this preserves the warm-call advantage without eagerly loading MCP at startup.

extensions/nushell/__bench__/calls.bench.ts

Added
new file mode 100644
1 +import path from "node:path";
2 +import { createTestSession } from "@marcfargas/pi-test-harness";
3 +import { findNu } from "../runtime.ts";
5 +const rounds = Number(process.env.NUSHELL_BENCH_ROUNDS ?? 25);
6 +const warmups = Number(process.env.NUSHELL_BENCH_WARMUPS ?? 3);
7 +if (
8 + !Number.isSafeInteger(rounds) ||
9 + rounds < 1 ||
10 + !Number.isSafeInteger(warmups) ||
11 + warmups < 0
13 + throw new Error(
14 + "Benchmark rounds must be positive integers; warmups may be zero",
15 + );
16 +if (!findNu()) throw new Error("nu executable missing on PATH");
18 +const t = await createTestSession({
19 + cwd: process.cwd(),
20 + extensions: [path.resolve(import.meta.dirname, "../index.ts")],
21 +});
22 +try {
23 + const runner = t.session.extensionRunner;
24 + const ctx = runner.createCommandContext();
25 + const fresh = runner.extensions[0]?.tools.get("nu")?.definition;
26 + const persistent = runner.extensions[0]?.tools.get("nu_session")?.definition;
27 + if (!fresh || !persistent) throw new Error("Nushell tools not registered");
28 + const exec = async (tool: typeof fresh) => {
29 + const result = await tool.execute(
30 + "bench",
31 + { command: "1 + 2" },
32 + undefined,
33 + undefined,
34 + ctx,
35 + );
36 + if (
37 + !result.content.some(
38 + (part) => part.type === "text" && part.text.includes("3"),
39 + )
40 + )
41 + throw new Error("Incorrect benchmark output");
42 + };
43 + const measure = async (
44 + name: string,
45 + call: () => Promise<void>,
46 + record: boolean,
47 + ) => {
48 + const start = process.hrtime.bigint();
49 + await call();
50 + if (record)
51 + console.log(`${name}\t1\t${process.hrtime.bigint() - start} ns/op`);
52 + };
53 + console.log(`goos: ${process.platform}`);
54 + console.log(`goarch: ${process.arch}`);
55 + console.log("pkg: pi-ext/nushell");
56 + console.log(`node: ${process.version}`);
57 + for (let index = -warmups; index < rounds; index++) {
58 + const record = index >= 0;
59 + await runner.getCommand("nushell")?.handler("reset", ctx);
60 + await measure("BenchmarkNuSessionCold", () => exec(persistent), record);
61 + if (index % 2 === 0) {
62 + await measure("BenchmarkNuFresh", () => exec(fresh), record);
63 + await measure("BenchmarkNuSessionWarm", () => exec(persistent), record);
64 + } else {
65 + await measure("BenchmarkNuSessionWarm", () => exec(persistent), record);
66 + await measure("BenchmarkNuFresh", () => exec(fresh), record);
67 + }
68 + }
69 + await runner.getCommand("nushell")?.handler("reset", ctx);
70 +} finally {
71 + t.dispose();

extensions/nushell/__e2e__/json.ts

Added
new file mode 100644
1 +import { spawn, spawnSync } from "node:child_process";
2 +import {
3 + createWriteStream,
4 + existsSync,
5 + mkdirSync,
6 + readFileSync,
7 + statSync,
8 + writeFileSync,
9 +} from "node:fs";
10 +import { join, resolve } from "node:path";
11 +import { performance } from "node:perf_hooks";
12 +import { finished } from "node:stream/promises";
14 +const root = resolve(import.meta.dirname, "../../..");
15 +const cases: Record<string, string> = {
16 + proquint:
17 + "Implement a tiny reusable Nushell module proquint.nu with IPv4 dotted-quad ↔ proquint functions. Use the paper's alphabet bdfghjklmnprstvz / aiou and verify 127.0.0.1 ↔ lusab-babad, 0.0.0.0, 255.255.255.255, malformed input, and round trips. Use only your Nushell tools for shell work. Produce the module inside the current working directory; run positive and negative checks. No network, no writes outside cwd.",
18 + base32:
19 + "Implement a small reusable Nushell module crockford.nu for fixed-width unsigned 32-bit Crockford Base32 IDs, encoding and decoding with canonical uppercase alphabet and human aliases O/0 and I/L/1. Include explicit leading-zero width and reject overflow or invalid symbols. Use only your Nushell tools for shell work. Produce the module inside the current working directory; run positive and negative round-trip checks. No network, no writes outside cwd.",
20 + csv: "Implement a tiny reusable Nushell module csv-headers.nu reporting added, removed, and reordered CSV header columns between two files. Handle quoted commas in headers, empty files, and duplicate headers explicitly. Make two small fixture files in cwd and run positive and negative checks. Use only your Nushell tools for shell work. No network, no writes outside cwd.",
21 + manifest:
22 + "Implement a small reusable Nushell module manifest.nu which snapshots regular files in a given directory into records of relative path, size, and SHA-256; compare two snapshots to report added, removed, changed. Explicitly skip symlinks. Make small fixture directories in cwd and run positive and negative checks. Use only your Nushell tools for shell work. No network, no writes outside cwd.",
23 + trace:
24 + "Implement trace.nu: summarize PI_NUSHELL_DEBUG JSONL in actual logger format. A fixture.jsonl is already in cwd; inspect it, do not invent a different schema. Pair fresh.start/fresh.finish and session.request.start/session.request.finish or session.request.error by callId, including interleaved starts. Ignore session.connect.ready and orphan terminals. Use durationMs from terminal records; nearest-rank p50/p95 for each mode, empty group null. Report counts, nonzero fresh exitCode and session nuCode/code separately, unmatched start callIds, and malformed/truncated final-line count. For fixture expect fresh count 2, p50 10, p95 30; session count 2, p50 40, p95 60; unmatched [orphan]. Return fields fresh {count,p50,p95,nonzeroExitCodeCount}, session {count,p50,p95,nuCodeCount,nonzeroCodeCount}, unmatchedStartCallIds, malformedFinalLineCount. Run positive and negative assertions using the actual fixture. Do not read process env or actual live debug log. Use only Nushell tools; no network, no writes outside cwd.",
25 + state:
26 + "Exercise the persistent Nushell tool contract within this one Pi invocation. First nu_session call defines a uniquely named function pq-harness-encode and a variable pq_harness_alphabet; a separate later nu_session call must use both stored bindings and verify a value. Run a deliberate Nushell evaluation error, then verify a subsequent nu_session call still sees both bindings. Call the fresh nu tool once to check it does not inherit either binding. Finally report observed outputs and whether fresh and persistent state were isolated. No file writes, no network, do not run Nu inside Nu.",
27 +};
28 +function traceOracle(file: string) {
29 + const records = readFileSync(file, "utf8")
30 + .trim()
31 + .split("\n")
32 + .map(
33 + (line) =>
34 + JSON.parse(line) as {
35 + event: string;
36 + callId?: string;
37 + durationMs?: number;
38 + exitCode?: number;
39 + code?: number;
40 + nuCode?: string;
41 + },
42 + );
43 + const pending = new Map<string, "fresh" | "session">();
44 + const fresh: number[] = [];
45 + const session: number[] = [];
46 + let nonzeroExitCodeCount = 0;
47 + let nuCodeCount = 0;
48 + let nonzeroCodeCount = 0;
49 + for (const record of records) {
50 + const mode =
51 + record.event === "fresh.start"
52 + ? "fresh"
53 + : record.event === "session.request.start"
54 + ? "session"
55 + : undefined;
56 + if (mode && record.callId) pending.set(record.callId, mode);
57 + const endMode =
58 + record.event === "fresh.finish"
59 + ? "fresh"
60 + : ["session.request.finish", "session.request.error"].includes(
61 + record.event,
62 + )
63 + ? "session"
64 + : undefined;
65 + if (!endMode || !record.callId || pending.get(record.callId) !== endMode)
66 + continue;
67 + pending.delete(record.callId);
68 + if (typeof record.durationMs !== "number") continue;
69 + if (endMode === "fresh") {
70 + fresh.push(record.durationMs);
71 + if (typeof record.exitCode === "number" && record.exitCode !== 0)
72 + nonzeroExitCodeCount++;
73 + } else {
74 + session.push(record.durationMs);
75 + if (record.nuCode) nuCodeCount++;
76 + if (typeof record.code === "number" && record.code !== 0)
77 + nonzeroCodeCount++;
78 + }
79 + }
80 + const summary = (values: number[]) => {
81 + const ordered = values.toSorted((a, b) => a - b);
82 + return {
83 + count: ordered.length,
84 + p50: ordered[Math.ceil(ordered.length * 0.5) - 1] ?? null,
85 + p95: ordered[Math.ceil(ordered.length * 0.95) - 1] ?? null,
86 + };
87 + };
88 + return {
89 + fresh: { ...summary(fresh), nonzeroExitCodeCount },
90 + session: { ...summary(session), nuCodeCount, nonzeroCodeCount },
91 + unmatchedStartCallIds: [...pending.keys()],
92 + malformedFinalLineCount: 0,
93 + };
96 +const verifying = process.argv[2] === "--verify";
97 +const names = verifying ? [] : process.argv.slice(2);
98 +for (const name of names)
99 + if (!cases[name]) throw new Error(`Unknown case: ${name}`);
100 +const chosen = verifying ? [] : names.length ? names : Object.keys(cases);
101 +const evidenceRoot = join(root, ".pi", "tmp", "nushell-json");
102 +const runRoot = verifying
103 + ? resolve(process.argv[3] ?? "")
104 + : join(evidenceRoot, new Date().toISOString().replace(/[:.]/g, "-"));
105 +if (verifying && !runRoot.startsWith(`${evidenceRoot}/`))
106 + throw new Error(
107 + "Verification path must be a retained Nushell JSON evidence run",
108 + );
109 +const model = process.env.PI_NUSHELL_E2E_MODEL ?? "openai-codex/gpt-5.6-terra";
110 +const binary = resolve(root, "extensions/nushell/index.ts");
111 +const results: Record<string, unknown>[] = verifying
112 + ? JSON.parse(readFileSync(join(runRoot, "results.json"), "utf8"))
113 + : [];
114 +for (const name of chosen) {
115 + const directory = join(runRoot, name);
116 + const workspace = join(directory, "workspace");
117 + mkdirSync(workspace, { recursive: true, mode: 0o700 });
118 + if (name === "trace") {
119 + const fixture = [
120 + { event: "fresh.start", callId: "a", commandLength: 10 },
121 + { event: "fresh.start", callId: "b", commandLength: 20 },
123 + event: "fresh.finish",
124 + callId: "b",
125 + durationMs: 30,
126 + exitCode: 1,
127 + outcome: "nonzero",
128 + },
130 + event: "fresh.finish",
131 + callId: "a",
132 + durationMs: 10,
133 + exitCode: 0,
134 + outcome: "success",
135 + },
136 + { event: "session.request.start", callId: "c", commandLength: 5 },
137 + { event: "session.connect.ready", callId: "c", durationMs: 15 },
139 + event: "session.request.finish",
140 + callId: "c",
141 + durationMs: 40,
142 + outputBytes: 25,
143 + },
144 + { event: "session.request.start", callId: "d", commandLength: 5 },
146 + event: "session.request.error",
147 + callId: "d",
148 + durationMs: 60,
149 + nuCode: "nu::shell::error",
150 + },
151 + { event: "fresh.start", callId: "orphan", commandLength: 2 },
152 + { event: "fresh.finish", callId: "ghost", durationMs: 99, exitCode: 0 },
153 + ];
154 + writeFileSync(
155 + join(workspace, "fixture.jsonl"),
156 + `${fixture.map((record, index) => JSON.stringify({ timestamp: "2026-01-01T00:00:00.000Z", pid: 1234, sequence: index + 1, ...record })).join("\n")}\n{"event":"fresh.finish"`,
157 + );
159 + const prompt = `${cases[name]} Prefer nu for independent commands; use nu_session only if later calls need session variables/functions/cwd. Report what worked, failed, and which module checks passed.`;
160 + const args = [
161 + "--print",
162 + "--mode",
163 + "json",
164 + "--no-session",
165 + "--nushell",
166 + "--offline",
167 + "--no-approve",
168 + "--no-context-files",
169 + "--no-extensions",
170 + "--extension",
171 + binary,
172 + "--no-skills",
173 + "--no-prompt-templates",
174 + "--no-themes",
175 + "--model",
176 + model,
177 + "--thinking",
178 + "low",
179 + "--tools",
180 + process.env.PI_NUSHELL_E2E_TOOLS ?? "bash,read,write,edit,nu,nu_session",
181 + prompt,
182 + ];
183 + writeFileSync(
184 + join(directory, "invocation.json"),
185 + `${JSON.stringify({ cwd: workspace, command: "pi", args, timeoutMs: 180_000, debug: join(directory, "debug.jsonl") }, null, 2)}\n`,
186 + );
187 + const out = createWriteStream(join(directory, "events.jsonl"), {
188 + mode: 0o600,
189 + });
190 + const err = createWriteStream(join(directory, "stderr.txt"), { mode: 0o600 });
191 + const started = performance.now();
192 + const result = await new Promise<{
193 + exitCode: number | null;
194 + signal: string | null;
195 + timedOut: boolean;
196 + }>((done, reject) => {
197 + const child = spawn("pi", args, {
198 + cwd: workspace,
199 + env: { ...process.env, PI_NUSHELL_DEBUG: join(directory, "debug.jsonl") },
200 + stdio: ["ignore", "pipe", "pipe"],
201 + detached: process.platform !== "win32",
202 + });
203 + child.stdout.pipe(out);
204 + child.stderr.pipe(err);
205 + let timedOut = false;
206 + const timer = setTimeout(() => {
207 + timedOut = true;
208 + if (child.pid) {
209 + if (process.platform === "win32") child.kill("SIGKILL");
210 + else process.kill(-child.pid, "SIGKILL");
212 + }, 180_000);
213 + child.once("error", (error) => {
214 + clearTimeout(timer);
215 + reject(error);
216 + });
217 + child.once("close", (exitCode, signal) => {
218 + clearTimeout(timer);
219 + done({ exitCode, signal, timedOut });
220 + });
221 + });
222 + await Promise.all([finished(out), finished(err)]);
223 + const events = readFileSync(join(directory, "events.jsonl"), "utf8")
224 + .split("\n")
225 + .filter(Boolean)
226 + .map(
227 + (line) =>
228 + JSON.parse(line) as {
229 + type: string;
230 + toolName?: string;
231 + isError?: boolean;
232 + args?: { command?: string };
233 + message?: {
234 + role?: string;
235 + stopReason?: string;
236 + content?: { type: string; text?: string }[];
237 + usage?: { cost?: { total?: number } };
238 + };
239 + },
240 + );
241 + const calls = events.filter((event) => event.type === "tool_execution_start");
242 + const lastAssistant = events
243 + .filter(
244 + (event) =>
245 + event.type === "message_end" && event.message?.role === "assistant",
247 + .at(-1);
248 + const debugPath = join(directory, "debug.jsonl");
249 + const debugEvents = (
250 + existsSync(debugPath) ? readFileSync(debugPath, "utf8") : ""
252 + .split("\n")
253 + .filter(Boolean)
254 + .map(
255 + (line) =>
256 + JSON.parse(line) as {
257 + event: string;
258 + exitCode?: number;
259 + nuCode?: string;
260 + },
261 + );
262 + const finalText =
263 + lastAssistant?.message?.content
264 + ?.filter((part) => part.type === "text")
265 + .map((part) => part.text ?? "")
266 + .join("\n") ?? "";
267 + writeFileSync(join(directory, "final.txt"), `${finalText}\n`);
268 + const analysis = {
269 + settled: events.some((event) => event.type === "agent_settled"),
270 + stopReason: lastAssistant?.message?.stopReason,
271 + toolCalls: Object.fromEntries(
272 + [...new Set(calls.map((event) => event.toolName))].map((name) => [
273 + name,
274 + calls.filter((call) => call.toolName === name).length,
275 + ]),
276 + ),
277 + toolErrors: events.filter(
278 + (event) => event.type === "tool_execution_end" && event.isError,
279 + ).length,
280 + debugErrors: debugEvents
281 + .filter(
282 + (event) =>
283 + event.event.endsWith(".error") ||
284 + (event.event === "fresh.finish" && event.exitCode !== 0),
286 + .map((event) => ({ event: event.event, nuCode: event.nuCode })),
287 + stderrBytes: statSync(join(directory, "stderr.txt")).size,
288 + hasFinal: finalText.length > 0,
289 + nestedNu: calls.filter((event) =>
290 + /(?:\^?nu\s+-c\b)/.test(event.args?.command ?? ""),
291 + ).length,
292 + debugEnabled: debugEvents.some((event) => event.event === "tools.enabled"),
293 + projectedCostUSD: events
294 + .filter(
295 + (event) =>
296 + event.type === "message_end" && event.message?.role === "assistant",
298 + .reduce(
299 + (sum, event) => sum + (event.message?.usage?.cost?.total ?? 0),
300 + 0,
301 + ),
302 + };
303 + writeFileSync(
304 + join(directory, "analysis.json"),
305 + `${JSON.stringify(analysis, null, 2)}\n`,
306 + );
307 + const row = {
308 + name,
309 + ...result,
310 + ...analysis,
311 + durationMs: Math.round(performance.now() - started),
312 + directory,
313 + };
314 + results.push(row);
315 + writeFileSync(
316 + join(directory, "result.json"),
317 + `${JSON.stringify(row, null, 2)}\n`,
318 + );
319 + console.log(JSON.stringify(row));
321 +const trace = results.find((row) => row.name === "trace");
322 +if (trace) {
323 + const traceWorkspace = join(runRoot, "trace", "workspace");
324 + const validations = results.map((row) => {
325 + const file = join(String(row.directory), "debug.jsonl");
326 + const check = spawnSync(
327 + "nu",
329 + "--no-config-file",
330 + "--no-history",
331 + "-c",
332 + "use trace.nu *; summarize $env.PI_NUSHELL_TRACE_INPUT | to json -r",
333 + ],
335 + cwd: traceWorkspace,
336 + env: {
337 + PATH: process.env.PATH ?? "",
338 + HOME: process.env.HOME ?? traceWorkspace,
339 + XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,
340 + MISE_SHELL: process.env.MISE_SHELL,
341 + PI_NUSHELL_TRACE_INPUT: file,
342 + },
343 + encoding: "utf8",
344 + timeout: 15_000,
345 + maxBuffer: 1_000_000,
346 + },
347 + );
348 + const expected = traceOracle(file);
349 + let observed: unknown;
350 + try {
351 + observed = JSON.parse(check.stdout);
352 + } catch {
353 + observed = null;
355 + const value =
356 + observed && typeof observed === "object"
357 + ? (observed as Record<string, unknown>)
358 + : null;
359 + const session =
360 + value?.session && typeof value.session === "object"
361 + ? (value.session as Record<string, unknown>)
362 + : null;
363 + const normalized =
364 + value && session
365 + ? {
366 + fresh: value.fresh,
367 + session: {
368 + count: session.count,
369 + p50: session.p50,
370 + p95: session.p95,
371 + nuCodeCount: session.nuCodeCount ?? session.nonzeroNuCodeCount,
372 + nonzeroCodeCount: session.nonzeroCodeCount,
373 + },
374 + unmatchedStartCallIds: value.unmatchedStartCallIds,
375 + malformedFinalLineCount:
376 + value.malformedFinalLineCount ??
377 + value.malformedTruncatedFinalLineCount,
379 + : observed;
380 + return {
381 + name: row.name,
382 + passed:
383 + check.status === 0 &&
384 + JSON.stringify(normalized) === JSON.stringify(expected),
385 + expected,
386 + observed,
387 + normalized,
388 + error: check.status === 0 ? undefined : check.stderr.slice(0, 1000),
389 + };
390 + });
391 + trace.traceValidation = validations.every((item) => item.passed);
392 + writeFileSync(
393 + join(runRoot, "trace", "validation.json"),
394 + `${JSON.stringify(validations, null, 2)}\n`,
395 + );
396 + writeFileSync(
397 + join(runRoot, "trace", "result.json"),
398 + `${JSON.stringify(trace, null, 2)}\n`,
399 + );
400 + console.log(
401 + JSON.stringify({
402 + traceValidation: trace.traceValidation,
403 + cases: validations.map(({ name, passed }) => ({ name, passed })),
404 + }),
405 + );
407 +writeFileSync(
408 + join(runRoot, "results.json"),
409 + `${JSON.stringify(results, null, 2)}\n`,
411 +console.log(`Evidence: ${runRoot}`);
412 +if (
413 + results.some(
414 + (result) =>
415 + result.exitCode !== 0 ||
416 + result.timedOut ||
417 + result.stopReason !== "stop" ||
418 + !result.settled ||
419 + !result.debugEnabled ||
420 + result.traceValidation === false ||
421 + (!(result.toolCalls as Record<string, number>).nu &&
422 + !(result.toolCalls as Record<string, number>).nu_session),
425 + throw new Error(
426 + `One or more runs lacked a successful Nu-tool session; inspect ${runRoot}`,
427 + );

extensions/nushell/__tests__/debug.test.ts

Added
new file mode 100644
1 +import {
2 + mkdtempSync,
3 + readFileSync,
4 + rmSync,
5 + statSync,
6 + writeFileSync,
7 +} from "node:fs";
8 +import path from "node:path";
9 +import { afterEach, describe, expect, it } from "vitest";
10 +import { createTestSession, type TestSession } from "../../../test/harness";
11 +import { findNu, freshOperations, NuSession } from "../runtime.ts";
13 +const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
15 +describe("Nushell opt-in debug logging", () => {
16 + let t: TestSession | undefined;
17 + let root: string | undefined;
18 + afterEach(() => {
19 + t?.dispose();
20 + t = undefined;
21 + if (root) rmSync(root, { recursive: true, force: true });
22 + root = undefined;
23 + });
25 + it.runIf(Boolean(findNu()))(
26 + "writes private JSONL metadata for both tool paths without command text",
27 + async () => {
28 + root = mkdtempSync(path.join(process.cwd(), ".pi/tmp/nushell-log-"));
29 + const file = path.join(root, "trace.jsonl");
30 + t = await createTestSession({
31 + extensions: [extensionPath],
32 + env: { PI_NUSHELL_DEBUG: file },
33 + });
34 + const runner = t.session.extensionRunner;
35 + const ctx = runner.createCommandContext();
36 + await runner.getCommand("nushell")?.handler("on", ctx);
37 + const fresh = runner.extensions[0]?.tools.get("nu")?.definition;
38 + const persistent =
39 + runner.extensions[0]?.tools.get("nu_session")?.definition;
40 + await fresh?.execute(
41 + "fresh",
42 + { command: "print diagnostic-probe" },
43 + undefined,
44 + undefined,
45 + ctx,
46 + );
47 + await expect(
48 + persistent?.execute(
49 + "session",
50 + {
51 + command: 'error make {msg: "secret-probe nu::shell::secret_probe"}',
52 + },
53 + undefined,
54 + undefined,
55 + ctx,
56 + ),
57 + ).rejects.toThrow("secret-probe");
58 + await expect(
59 + persistent?.execute(
60 + "division",
61 + { command: "1 / 0" },
62 + undefined,
63 + undefined,
64 + ctx,
65 + ),
66 + ).rejects.toThrow("Division by zero");
67 + await runner.getCommand("nushell")?.handler("off", ctx);
68 + await runner.emit({ type: "session_shutdown", reason: "quit" });
69 + const text = readFileSync(file, "utf8");
70 + const records = text
71 + .trim()
72 + .split("\n")
73 + .map(
74 + (line) =>
75 + JSON.parse(line) as {
76 + event: string;
77 + sequence: number;
78 + [key: string]: unknown;
79 + },
80 + );
81 + expect(records.map((record) => record.event)).toEqual(
82 + expect.arrayContaining([
83 + "session.start",
84 + "tools.enabled",
85 + "fresh.start",
86 + "fresh.finish",
87 + "session.connect.ready",
88 + "session.request.error",
89 + "session.reset",
90 + "tools.disabled",
91 + "session.shutdown",
92 + ]),
93 + );
94 + expect(records.map((record) => record.sequence)).toEqual(
95 + records.map((_, index) => index + 1),
96 + );
97 + expect(records.every((record) => record.pid === process.pid)).toBe(true);
98 + const starts = records.filter(
99 + (record) =>
100 + record.event === "fresh.start" ||
101 + record.event === "session.request.start",
102 + );
103 + const terminals = records.filter(
104 + (record) =>
105 + record.event === "fresh.finish" ||
106 + record.event === "session.request.finish" ||
107 + record.event === "session.request.error",
108 + );
109 + expect(new Set(starts.map((record) => record.callId)).size).toBe(
110 + starts.length,
111 + );
112 + for (const start of starts) {
113 + expect(
114 + terminals.filter((terminal) => terminal.callId === start.callId),
115 + ).toHaveLength(1);
117 + expect(
118 + records.find((record) => record.event === "fresh.finish"),
119 + ).toMatchObject({ exitCode: 0, outcome: "success", pid: process.pid });
120 + expect(
121 + records.filter((record) => record.event === "session.request.error"),
122 + ).toEqual(
123 + expect.arrayContaining([
124 + expect.objectContaining({ nuCode: "nu::shell::division_by_zero" }),
125 + ]),
126 + );
127 + expect(text).not.toContain("diagnostic-probe");
128 + expect(text).not.toContain("secret-probe");
129 + expect(text).not.toContain("nu::shell::secret_probe");
130 + if (process.platform !== "win32")
131 + expect(statSync(file).mode & 0o777).toBe(0o600);
132 + },
133 + );
135 + it.runIf(Boolean(findNu()))(
136 + "pairs overlapping and preflight-failed fresh calls",
137 + async () => {
138 + const records: { event: string; callId?: unknown; outcome?: unknown }[] =
139 + [];
140 + const binary = findNu();
141 + if (!binary) throw new Error("nu missing");
142 + const operations = freshOperations(binary, (event, details) =>
143 + records.push({ event, ...details }),
144 + );
145 + const aborted = new AbortController();
146 + aborted.abort();
147 + await expect(
148 + operations.exec("1 + 2", process.cwd(), {
149 + onData: () => {},
150 + signal: aborted.signal,
151 + }),
152 + ).rejects.toThrow("aborted");
153 + await expect(
154 + operations.exec("1 + 2", process.cwd(), {
155 + onData: () => {},
156 + timeout: 0,
157 + }),
158 + ).rejects.toThrow("Invalid timeout");
159 + await Promise.all([
160 + operations.exec("sleep 50ms; 1", process.cwd(), { onData: () => {} }),
161 + operations.exec("sleep 50ms; 2", process.cwd(), { onData: () => {} }),
162 + ]);
163 + const starts = records.filter((record) => record.event === "fresh.start");
164 + const finishes = records.filter(
165 + (record) => record.event === "fresh.finish",
166 + );
167 + expect(starts).toHaveLength(4);
168 + expect(new Set(starts.map((record) => record.callId)).size).toBe(4);
169 + for (const start of starts)
170 + expect(
171 + finishes.filter((finish) => finish.callId === start.callId),
172 + ).toHaveLength(1);
173 + expect(finishes.map((finish) => finish.outcome)).toEqual(
174 + expect.arrayContaining(["aborted", "failed", "success", "success"]),
175 + );
176 + expect(records.slice(4, 6).map((record) => record.event)).toEqual([
177 + "fresh.start",
178 + "fresh.start",
179 + ]);
180 + },
181 + );
183 + it.runIf(Boolean(findNu()))(
184 + "pairs session failures before worker startup",
185 + async () => {
186 + const records: { event: string; callId?: unknown }[] = [];
187 + const session = new NuSession((event, details) =>
188 + records.push({ event, ...details }),
189 + );
190 + const binary = findNu();
191 + if (!binary) throw new Error("nu missing");
192 + const aborted = new AbortController();
193 + aborted.abort();
194 + await expect(
195 + session.evaluate(binary, process.cwd(), "1 + 2", aborted.signal),
196 + ).rejects.toThrow("aborted before execution");
197 + await expect(
198 + session.evaluate(
199 + path.join(process.cwd(), ".pi/tmp/missing-nu-executable"),
200 + process.cwd(),
201 + "1 + 2",
202 + ),
203 + ).rejects.toThrow();
204 + const starts = records.filter(
205 + (record) => record.event === "session.request.start",
206 + );
207 + const errors = records.filter(
208 + (record) => record.event === "session.request.error",
209 + );
210 + expect(starts).toHaveLength(2);
211 + expect(new Set(starts.map((record) => record.callId)).size).toBe(2);
212 + for (const start of starts)
213 + expect(
214 + errors.filter((error) => error.callId === start.callId),
215 + ).toHaveLength(1);
216 + await session.reset();
217 + },
218 + );
220 + it("refuses preexisting world-readable debug files", async () => {
221 + if (process.platform === "win32") return;
222 + root = mkdtempSync(path.join(process.cwd(), ".pi/tmp/nushell-log-"));
223 + const file = path.join(root, "trace.jsonl");
224 + writeFileSync(file, "existing\n", { mode: 0o644 });
225 + t = await createTestSession({
226 + extensions: [extensionPath],
227 + env: { PI_NUSHELL_DEBUG: file },
228 + });
229 + expect(readFileSync(file, "utf8")).toBe("existing\n");
230 + expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([
231 + expect.stringContaining("Nushell debug logging unavailable"),
232 + "warning",
233 + ]);
234 + expect(t.session.extensionRunner.getCommand("nushell")).toBeDefined();
235 + });
236 +});

extensions/nushell/__tests__/harness.test.ts

Added
new file mode 100644
1 +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2 +import path from "node:path";
3 +import { initTheme } from "@earendil-works/pi-coding-agent";
4 +import { afterEach, describe, expect, it, vi } from "vitest";
5 +import { createTestSession, type TestSession } from "../../../test/harness";
6 +import { findNu } from "../runtime.ts";
8 +const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
10 +describe("nushell pi-test-harness", () => {
11 + let t: TestSession | undefined;
12 + let root: string | undefined;
13 + afterEach(() => {
14 + t?.dispose();
15 + t = undefined;
16 + if (root) rmSync(root, { recursive: true, force: true });
17 + root = undefined;
18 + });
20 + it("registers inert tools and toggles without changing unrelated tools", async () => {
21 + t = await createTestSession({ extensions: [extensionPath] });
22 + const runner = t.session.extensionRunner;
23 + const command = runner.getCommand("nushell");
24 + const ctx = runner.createCommandContext();
25 + expect(runner.extensions[0]?.tools.has("nu")).toBe(true);
26 + expect(runner.extensions[0]?.tools.has("nu_session")).toBe(true);
27 + expect(t.session.getActiveToolNames()).not.toContain("nu");
28 + expect(command?.getArgumentCompletions?.("re")).toEqual([
29 + { value: "reset", label: "reset" },
30 + ]);
31 + const initial = t.session.getActiveToolNames();
32 + await command?.handler("on", ctx);
33 + const enabled = t.session.getActiveToolNames();
34 + if (!findNu()) {
35 + expect(enabled).toEqual(initial);
36 + return;
37 + }
38 + expect(enabled).toContain("nu");
39 + expect(enabled).toContain("nu_session");
40 + expect(enabled).not.toContain("bash");
41 + expect(enabled).not.toContain("powershell");
42 + for (const name of initial.filter(
43 + (name) => name !== "bash" && name !== "powershell",
44 + ))
45 + expect(enabled).toContain(name);
46 + await command?.handler("off", ctx);
47 + expect([...t.session.getActiveToolNames()].sort()).toEqual(
48 + [...initial].sort(),
49 + );
50 + });
52 + it.runIf(Boolean(findNu()))(
53 + "uses global nushell.enable with project override and CLI flag priority",
54 + async () => {
55 + root = mkdtempSync(path.join(process.cwd(), ".pi/tmp/nushell-settings-"));
56 + const agentDir = path.join(root, ".test-home/.pi/agent");
57 + mkdirSync(agentDir, { recursive: true });
58 + writeFileSync(
59 + path.join(agentDir, "settings.json"),
60 + JSON.stringify({ nushell: { enable: true } }),
61 + );
62 + t = await createTestSession({ cwd: root, extensions: [extensionPath] });
63 + await t.session.extensionRunner.emit({
64 + type: "session_start",
65 + reason: "startup",
66 + });
67 + expect(t.session.getActiveToolNames()).toContain("nu");
68 + expect(t.session.getActiveToolNames()).not.toContain("bash");
69 + t.dispose();
70 + t = undefined;
72 + const projectDir = path.join(root, ".pi");
73 + mkdirSync(projectDir, { recursive: true });
74 + writeFileSync(
75 + path.join(projectDir, "settings.json"),
76 + JSON.stringify({ nushell: { enable: false } }),
77 + );
78 + t = await createTestSession({ cwd: root, extensions: [extensionPath] });
79 + await t.session.extensionRunner.emit({
80 + type: "session_start",
81 + reason: "startup",
82 + });
83 + expect(t.session.getActiveToolNames()).not.toContain("nu");
84 + t.session.extensionRunner.setFlagValue("nushell", true);
85 + await t.session.extensionRunner.emit({
86 + type: "session_start",
87 + reason: "startup",
88 + });
89 + expect(t.session.getActiveToolNames()).toContain("nu");
90 + },
91 + );
93 + it("registers --nushell to enable both tools on session start", async () => {
94 + t = await createTestSession({ extensions: [extensionPath] });
95 + const runner = t.session.extensionRunner;
96 + expect(runner.getFlags().has("nushell")).toBe(true);
97 + runner.setFlagValue("nushell", true);
98 + await runner.emit({ type: "session_start", reason: "startup" });
99 + const active = t.session.getActiveToolNames();
100 + if (!findNu()) {
101 + expect(active).not.toContain("nu");
102 + return;
104 + expect(active).toContain("nu");
105 + expect(active).toContain("nu_session");
106 + expect(active).not.toContain("bash");
107 + expect(active).not.toContain("powershell");
108 + });
110 + it.runIf(Boolean(findNu()))(
111 + "does not claim activation when Nu tools are excluded",
112 + async () => {
113 + t = await createTestSession({ extensions: [extensionPath] });
114 + const runner = t.session.extensionRunner;
115 + const initial = t.session.getActiveToolNames();
116 + const tools = t.session.getAllTools();
117 + vi.spyOn(t.session, "getAllTools").mockReturnValue(
118 + tools.filter((tool) => tool.name !== "nu_session"),
119 + );
120 + runner.setFlagValue("nushell", true);
121 + await runner.emit({ type: "session_start", reason: "startup" });
122 + expect(t.session.getActiveToolNames()).toEqual(initial);
123 + expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([
124 + expect.stringContaining("nu_session"),
125 + "warning",
126 + ]);
127 + },
128 + );
130 + it.runIf(Boolean(findNu()))(
131 + "renders both Nu commands with syntax highlighting and shell-style results",
132 + async () => {
133 + t = await createTestSession({ extensions: [extensionPath] });
134 + initTheme("default", false);
135 + const tools = t.session.extensionRunner.extensions[0]?.tools;
136 + const theme = {
137 + fg: (color: string, value: string) =>
138 + value ? `<${color}>${value}</${color}>` : "",
139 + bold: (value: string) => value,
140 + } as never;
141 + for (const name of ["nu", "nu_session"]) {
142 + const tool = tools?.get(name)?.definition;
143 + const context = {
144 + state: {},
145 + executionStarted: false,
146 + argsComplete: false,
147 + invalidate: vi.fn(),
148 + } as never;
149 + const partial = tool?.renderCall?.(
150 + { command: "let value" },
151 + theme,
152 + context,
153 + );
154 + expect(partial?.render(1000).join("\n")).not.toContain(
155 + "<syntaxVariable>",
156 + );
157 + context.argsComplete = true;
158 + context.executionStarted = true;
159 + const command = 'let value = "safe"';
160 + const call = tool?.renderCall?.({ command }, theme, context);
161 + const lines = call?.render(1000).join("\n") ?? "";
162 + expect(lines.replace(/<\/?[a-zA-Z]+>/g, "")).toContain(command);
163 + expect(lines).not.toContain("<syntaxVariable>");
164 + await vi.waitFor(() =>
165 + expect(context.invalidate).toHaveBeenCalledTimes(1),
166 + );
167 + const highlighted =
168 + tool
169 + ?.renderCall?.({ command }, theme, context)
170 + .render(1000)
171 + .join("\n") ?? "";
172 + expect(highlighted).toContain("<syntaxVariable>value</syntaxVariable>");
173 + expect(highlighted).toContain('<syntaxString>"safe"</syntaxString>');
174 + expect(highlighted).not.toMatch(/\x1b\[/);
175 + const paletteCommand =
176 + 'if true { let value = "safe"; $value | str uppercase; 2 > 1 }';
177 + tool?.renderCall?.({ command: paletteCommand }, theme, context);
178 + await vi.waitFor(() =>
179 + expect(context.invalidate).toHaveBeenCalledTimes(2),
180 + );
181 + const palette =
182 + tool
183 + ?.renderCall?.({ command: paletteCommand }, theme, context)
184 + .render(2000)
185 + .join("\n") ?? "";
186 + for (const token of [
187 + "<syntaxFunction>if</syntaxFunction>",
188 + "<syntaxKeyword>true</syntaxKeyword>",
189 + "<syntaxPunctuation>{</syntaxPunctuation>",
190 + "<syntaxVariable>$value</syntaxVariable>",
191 + "<syntaxPunctuation>|</syntaxPunctuation>",
192 + "<syntaxOperator>></syntaxOperator>",
193 + '<syntaxString>"safe"</syntaxString>',
194 + ])
195 + expect(palette).toContain(token);
196 + expect(lines).toContain(name === "nu" ? "nu>" : "nu session>");
197 + const result = tool?.renderResult?.(
199 + content: [
200 + { type: "text", text: "one\ntwo\nthree\nfour\nfive\nsix" },
201 + ],
202 + details: undefined,
203 + },
204 + { expanded: false, isPartial: false },
205 + theme,
206 + { ...context, showImages: false, isError: false },
207 + );
208 + expect(result?.render(120).join("\n")).toContain("to expand");
210 + },
211 + );
213 + it.runIf(Boolean(findNu()))(
214 + "keeps session state across calls but isolates fresh calls",
215 + async () => {
216 + t = await createTestSession({ extensions: [extensionPath] });
217 + const runner = t.session.extensionRunner;
218 + const ctx = runner.createCommandContext();
219 + const tool = (name: string) =>
220 + runner.extensions[0]?.tools.get(name)?.definition;
221 + const run = (name: string, command: string) =>
222 + tool(name)?.execute("call", { command }, undefined, undefined, ctx);
223 + const fresh = await run("nu", "1 + 2");
224 + expect(fresh?.content[0]).toMatchObject({ type: "text", text: "3\n" });
225 + await run("nu_session", "let value = 41");
226 + const persistent = await run("nu_session", "$value + 1");
227 + expect(persistent?.content[0]).toMatchObject({
228 + type: "text",
229 + text: expect.stringContaining("output:42"),
230 + });
231 + await expect(run("nu", "$value + 1")).rejects.toThrow();
232 + await expect(run("nu_session", "1 / 0")).rejects.toThrow(
233 + "Division by zero",
234 + );
235 + await expect(
236 + run("nu_session", 'error make {msg: "timeout from user"}'),
237 + ).rejects.toThrow("timeout from user");
238 + const afterError = await run("nu_session", "$value");
239 + expect(afterError?.content[0]).toMatchObject({
240 + text: expect.stringContaining("output:41"),
241 + });
242 + const external = await run("nu_session", "^false");
243 + expect(external?.content[0]).toMatchObject({
244 + text: expect.stringContaining('output:""'),
245 + });
246 + await runner.getCommand("nushell")?.handler("reset", ctx);
247 + await expect(run("nu_session", "$value")).rejects.toThrow();
248 + await run("nu_session", "let value = 42");
249 + const controller = new AbortController();
250 + const pending = tool("nu_session")?.execute(
251 + "abort-call",
252 + { command: "sleep 2sec" },
253 + controller.signal,
254 + undefined,
255 + ctx,
256 + );
257 + const abortTimer = setTimeout(() => controller.abort(), 50);
258 + try {
259 + await expect(pending).rejects.toThrow("state reset");
260 + } finally {
261 + clearTimeout(abortTimer);
263 + await expect(run("nu_session", "$value")).rejects.toThrow();
264 + await runner.getCommand("nushell")?.handler("off", ctx);
265 + },
266 + );
267 +});

extensions/nushell/debug.ts

Added
new file mode 100644
1 +import { closeSync, constants, fstatSync, openSync, writeSync } from "node:fs";
3 +export type DebugLog = (
4 + event: string,
5 + details?: Record<string, unknown>,
6 +) => void;
8 +export function openDebugLog(
9 + path: string,
10 + onError: (message: string) => void,
11 +): {
12 + log: DebugLog;
13 + close: () => void;
14 +} {
15 + const fd = openSync(
16 + path,
17 + constants.O_WRONLY |
18 + constants.O_APPEND |
19 + constants.O_CREAT |
20 + (constants.O_NOFOLLOW ?? 0),
21 + 0o600,
22 + );
23 + const stat = fstatSync(fd);
24 + if (
25 + !stat.isFile() ||
26 + (process.platform !== "win32" && (stat.mode & 0o077) !== 0)
27 + ) {
28 + closeSync(fd);
29 + throw new Error(
30 + "Debug log must be a regular file accessible only to its owner",
31 + );
32 + }
33 + let open = true;
34 + let sequence = 0;
35 + const close = () => {
36 + if (!open) return;
37 + open = false;
38 + closeSync(fd);
39 + };
40 + return {
41 + log(event, details = {}) {
42 + if (!open) return;
43 + try {
44 + writeSync(
45 + fd,
46 + `${JSON.stringify({ ...details, timestamp: new Date().toISOString(), pid: process.pid, sequence: ++sequence, event })}\n`,
47 + );
48 + } catch (error) {
49 + close();
50 + onError(
51 + `Nushell debug logging stopped: ${error instanceof Error ? error.message : String(error)}`,
52 + );
53 + }
54 + },
55 + close,
56 + };

extensions/nushell/index.ts

Added
new file mode 100644
1 +import { execFile } from "node:child_process";
2 +import {
3 + createBashToolDefinition,
4 + type ExtensionAPI,
5 + type ExtensionContext,
6 + SettingsManager,
7 + type ThemeColor,
8 +} from "@earendil-works/pi-coding-agent";
9 +import { Text } from "@earendil-works/pi-tui";
10 +import { Type } from "typebox";
11 +import { type DebugLog, openDebugLog } from "./debug.ts";
12 +import { findNu, freshOperations, NuSession } from "./runtime.ts";
14 +const NU_COLORS: Record<number, ThemeColor> = {
15 + 32: "syntaxString",
16 + 33: "syntaxOperator",
17 + 34: "syntaxPunctuation",
18 + 35: "syntaxVariable",
19 + 36: "syntaxFunction",
20 + 90: "syntaxVariable",
21 + 96: "syntaxKeyword",
22 +};
24 +// Translate Nu's fixed ANSI palette into the active Pi theme at render time.
25 +function themeNuHighlight(
26 + ansi: string,
27 + theme: Parameters<
28 + NonNullable<ReturnType<typeof createBashToolDefinition>["renderCall"]>
29 + >[1],
30 +): string {
31 + let output = "";
32 + let start = 0;
33 + let color: ThemeColor = "toolOutput";
34 + for (const match of ansi.matchAll(/\x1b\[([0-9;]*)m/g)) {
35 + output += theme.fg(color, ansi.slice(start, match.index));
36 + const codes = match[1]?.split(";").map(Number) ?? [];
37 + const foreground = codes.findLast(
38 + (code) => (code >= 30 && code <= 37) || (code >= 90 && code <= 97),
39 + );
40 + color =
41 + foreground === 35 && codes.includes(1)
42 + ? "syntaxPunctuation"
43 + : (NU_COLORS[foreground ?? -1] ?? "toolOutput");
44 + start = match.index + match[0].length;
45 + }
46 + return output + theme.fg(color, ansi.slice(start));
49 +// Nu parses source without evaluating it; only the command heading is highlighted.
50 +const highlightCache = new WeakMap<object, { command: string; text: string }>();
51 +function renderNuCall(
52 + args: { command: string; timeout?: number },
53 + theme: Parameters<
54 + NonNullable<ReturnType<typeof createBashToolDefinition>["renderCall"]>
55 + >[1],
56 + context: Parameters<
57 + NonNullable<ReturnType<typeof createBashToolDefinition>["renderCall"]>
58 + >[2],
59 + label: string,
60 +) {
61 + const state = context.state;
62 + if (context.executionStarted && state.startedAt === undefined) {
63 + state.startedAt = Date.now();
64 + state.endedAt = undefined;
65 + }
66 + const command = typeof args?.command === "string" ? args.command : "";
67 + let cached = highlightCache.get(state);
68 + if (context.argsComplete && cached?.command !== command) {
69 + const entry = { command, text: command };
70 + cached = entry;
71 + highlightCache.set(state, entry);
72 + const binary = command && command.length <= 16_000 ? findNu() : undefined;
73 + if (binary) {
74 + execFile(
75 + binary,
76 + [
77 + "--no-config-file",
78 + "--no-history",
79 + "-c",
80 + "$env.PI_NU_HIGHLIGHT_INPUT | nu-highlight",
81 + ],
82 + {
83 + env: { ...process.env, PI_NU_HIGHLIGHT_INPUT: command },
84 + encoding: "utf8",
85 + timeout: 1000,
86 + maxBuffer: 128 * 1024,
87 + windowsHide: true,
88 + },
89 + (error, stdout) => {
90 + if (error || highlightCache.get(state) !== entry) return;
91 + entry.text = stdout.trimEnd();
92 + context.invalidate();
93 + },
94 + );
95 + }
96 + }
97 + const highlighted = cached?.command === command ? cached.text : command;
98 + const text =
99 + context.lastComponent instanceof Text
100 + ? context.lastComponent
101 + : new Text("", 0, 0);
102 + text.setText(
103 + `${theme.fg("toolTitle", theme.bold(label))} ${themeNuHighlight(highlighted || "...", theme)}${args?.timeout ? theme.fg("muted", ` (timeout ${args.timeout}s)`) : ""}`,
104 + );
105 + return text;
108 +function settingsEnabled(cwd: string): boolean {
109 + const settings = SettingsManager.create(cwd);
110 + const global = (
111 + settings.getGlobalSettings() as { nushell?: { enable?: unknown } }
112 + ).nushell?.enable;
113 + const project = (
114 + settings.getProjectSettings() as { nushell?: { enable?: unknown } }
115 + ).nushell?.enable;
116 + return typeof project === "boolean"
117 + ? project
118 + : typeof global === "boolean"
119 + ? global
120 + : false;
123 +export default function nushellExtension(pi: ExtensionAPI) {
124 + let log: DebugLog | undefined;
125 + let closeLog: (() => void) | undefined;
126 + const session = new NuSession();
127 + let enabled = false;
128 + let displaced: string[] = [];
130 + pi.registerFlag("nushell", {
131 + description:
132 + "Enable Nushell tools at startup instead of bash and powershell",
133 + type: "boolean",
134 + default: false,
135 + });
137 + function activate(ctx: ExtensionContext, quiet = false): void {
138 + if (enabled) return;
139 + if (!findNu()) {
140 + ctx.ui.notify(
141 + "Nushell executable not found on PATH; tools unchanged",
142 + "warning",
143 + );
144 + log?.("tools.enable.error", { reason: "nu_not_found" });
145 + return;
147 + const available = new Set(pi.getAllTools().map((tool) => tool.name));
148 + const missing = ["nu", "nu_session"].filter((name) => !available.has(name));
149 + if (missing.length) {
150 + ctx.ui.notify(
151 + `Nushell tools excluded by tool allowlist: ${missing.join(", ")}; tools unchanged`,
152 + "warning",
153 + );
154 + log?.("tools.enable.error", { reason: "tools_excluded", missing });
155 + return;
157 + const active = pi.getActiveTools();
158 + displaced = active.filter(
159 + (tool) => tool === "bash" || tool === "powershell",
160 + );
161 + pi.setActiveTools([
162 + ...active.filter((tool) => !displaced.includes(tool)),
163 + "nu",
164 + "nu_session",
165 + ]);
166 + enabled = true;
167 + log?.("tools.enabled", { displaced });
168 + if (!quiet)
169 + ctx.ui.notify(
170 + "Nushell tools on: nu (fresh), nu_session (persistent)",
171 + "info",
172 + );
175 + const freshTool = createBashToolDefinition(process.cwd(), {
176 + operations: {
177 + exec: (command, cwd, options) => {
178 + const binary = findNu();
179 + if (!binary) throw new Error("Nushell executable not found on PATH");
180 + return freshOperations(binary, log).exec(command, cwd, options);
181 + },
182 + },
183 + });
184 + pi.registerTool({
185 + ...freshTool,
186 + name: "nu",
187 + label: "nu",
188 + description:
189 + "Execute Nushell commands in a fresh process in Pi's cwd. Syntax is Nushell, not Bash or PowerShell. Each call has independent variables, functions, environment, and cwd. Streams output; timeout in seconds is optional.",
190 + promptSnippet:
191 + "Execute independent Nushell commands with nu; use nu_session only for state across calls",
192 + promptGuidelines: [
193 + "nu already runs Nushell. Pass source directly; never wrap it in nu -c or ^nu -c. Prefer native commands like ls, pwd, open, mkdir, save; use ^name only for necessary external executables. Nu flags differ from GNU flags: check help <command> before guessing options. Batch short independent checks when readable.",
194 + "Use Nushell syntax: structured pipelines, $env.NAME, (command), o> file or save. Use try/catch for expected command failures.",
195 + ],
196 + renderCall: (args, theme, context) =>
197 + renderNuCall(args, theme, context, "nu>"),
198 + });
200 + pi.registerTool({
201 + name: "nu_session",
202 + label: "nu session",
203 + description:
204 + "Evaluate Nushell in a persistent session. Variables, functions, environment, and cwd survive subsequent nu_session calls; nu calls stay independent. Prefer nu unless state must persist. MCP captures expression results as NUON; use ^command | complete and inspect exit_code for external status. Do not rely on print: MCP uses stderr for diagnostics.",
205 + promptSnippet:
206 + "Evaluate persistent Nushell state with nu_session when later calls depend on earlier state",
207 + promptGuidelines: [
208 + "Use nu by default; choose nu_session only for state shared across calls. Both tools already run Nu, so do not wrap commands in nu -c or ^nu -c. Nu session is sequential; /nushell reset clears its state. Cancelled commands can leave detached external processes running.",
209 + ],
210 + executionMode: "sequential",
211 + parameters: Type.Object({
212 + command: Type.String({
213 + description: "Nushell source to evaluate in the persistent session",
214 + }),
215 + }),
216 + async execute(_id, { command }, signal, _onUpdate, ctx) {
217 + const binary = findNu();
218 + if (!binary) throw new Error("Nushell executable not found on PATH");
219 + const text = await session.evaluate(binary, ctx.cwd, command, signal);
220 + return { content: [{ type: "text", text }], details: undefined };
221 + },
222 + renderCall: (args, theme, context) =>
223 + renderNuCall(args, theme, context, "nu session>"),
224 + renderResult: freshTool.renderResult,
225 + });
227 + pi.registerCommand("nushell", {
228 + description:
229 + "Toggle Nushell tools and replace active bash/powershell; /nushell reset clears persistent state",
230 + getArgumentCompletions: (prefix) => {
231 + const matches = ["on", "off", "reset"].filter((value) =>
232 + value.startsWith(prefix),
233 + );
234 + return matches.length
235 + ? matches.map((value) => ({ value, label: value }))
236 + : null;
237 + },
238 + async handler(arg, ctx) {
239 + const action = arg.trim() || (enabled ? "off" : "on");
240 + if (action === "reset") {
241 + await session.reset("explicit");
242 + ctx.ui.notify("Nushell session reset", "info");
243 + return;
245 + if (action === "on") {
246 + activate(ctx);
247 + return;
249 + if (action === "off") {
250 + if (!enabled) return;
251 + await session.reset("toggle_off");
252 + const active = pi
253 + .getActiveTools()
254 + .filter((tool) => tool !== "nu" && tool !== "nu_session");
255 + pi.setActiveTools([
256 + ...active,
257 + ...displaced.filter((tool) => !active.includes(tool)),
258 + ]);
259 + log?.("tools.disabled");
260 + displaced = [];
261 + enabled = false;
262 + ctx.ui.notify("Nushell tools off; persistent state cleared", "info");
263 + return;
265 + ctx.ui.notify("Usage: /nushell [on|off|reset]", "warning");
266 + },
267 + });
269 + pi.on("session_start", async (_event, ctx) => {
270 + await session.reset("session_start");
271 + closeLog?.();
272 + log = undefined;
273 + closeLog = undefined;
274 + session.setDebug(undefined);
275 + const debugPath = process.env.PI_NUSHELL_DEBUG;
276 + if (debugPath) {
277 + try {
278 + const debug = openDebugLog(debugPath, (message) =>
279 + ctx.ui.notify(message, "warning"),
280 + );
281 + log = debug.log;
282 + closeLog = debug.close;
283 + session.setDebug(log);
284 + log("session.start");
285 + } catch (error) {
286 + ctx.ui.notify(
287 + `Nushell debug logging unavailable: ${error instanceof Error ? error.message : String(error)}`,
288 + "warning",
289 + );
292 + enabled = false;
293 + displaced = [];
294 + pi.setActiveTools(
295 + pi
296 + .getActiveTools()
297 + .filter((name) => name !== "nu" && name !== "nu_session"),
298 + );
299 + if (pi.getFlag("nushell") === true || settingsEnabled(ctx.cwd))
300 + activate(ctx, true);
301 + });
302 + pi.on("session_tree", async () => {
303 + await session.reset("session_tree");
304 + });
305 + pi.on("session_shutdown", async () => {
306 + await session.reset("session_shutdown");
307 + log?.("session.shutdown");
308 + closeLog?.();
309 + session.setDebug(undefined);
310 + log = undefined;
311 + closeLog = undefined;
312 + });

extensions/nushell/mise.toml

Added
new file mode 100644
1 +[tasks.bench]
2 +description = "Benchmark fresh and persistent Nushell tool calls"
3 +depends = ["//:install"]
4 +run = "node --no-warnings --experimental-strip-types __bench__/calls.bench.ts"
6 +[tasks.e2e-json]
7 +description = "Run isolated Pi JSON-mode Nushell module exercises and retain evidence"
8 +depends = ["//:install"]
9 +run = "node --no-warnings --experimental-strip-types __e2e__/json.ts"
11 +[tasks.fmt]
12 +description = "Format nushell extension"
13 +depends = ["//:install"]
14 +run = [
15 + "biome check --write --config-path ../.. .",
16 + "rumdl fmt --config ../../.rumdl.toml .",
17 + "taplo format --config ../../.taplo.toml mise.toml",
20 +[tasks.lint]
21 +description = "Lint nushell extension"
22 +depends = ["//:install"]
23 +run = [
24 + "biome ci --config-path ../.. .",
25 + "rumdl check --config ../../.rumdl.toml .",
26 + "taplo format --check --config ../../.taplo.toml mise.toml",
29 +[tasks.test]
30 +description = "Test nushell extension"
31 +depends = ["//:install"]
32 +run = [
33 + { task = "//:test", args = ["extensions/nushell"] },
36 +[tasks.check]
37 +description = "Check nushell extension"
38 +depends = ["//:install"]
39 +run = [
40 + { task = "//:build", args = ["nushell"] },

extensions/nushell/package.json

Added
new file mode 100644
1 +{
2 + "name": "@bugabinga/pi-ext-nushell",
3 + "private": true,
4 + "type": "module",
5 + "main": "index.ts",
6 + "license": "MIT",
7 + "description": "Opt-in fresh and persistent Nushell tools for Pi.",
8 + "peerDependencies": {
9 + "@earendil-works/pi-coding-agent": "*",
10 + "@earendil-works/pi-tui": "*",
11 + "typebox": "*"
12 + },
13 + "dependencies": {
14 + "@modelcontextprotocol/sdk": "^1.29.0"
15 + },
16 + "devDependencies": {
17 + "@marcfargas/pi-test-harness": "^0.6.1",
18 + "vitest": "^4.1.9"
19 + },
20 + "pi": {
21 + "extensions": [
22 + "index.ts"
23 + ]
24 + }

extensions/nushell/runtime.ts

Added
new file mode 100644
1 +import { spawn } from "node:child_process";
2 +import { constants, existsSync } from "node:fs";
3 +import { access } from "node:fs/promises";
4 +import { delimiter, join } from "node:path";
5 +import type { BashOperations } from "@earendil-works/pi-coding-agent";
6 +import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
7 +import type { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
8 +import type { DebugLog } from "./debug.ts";
10 +const SAFE_NU_CODES = new Set([
11 + "nu::shell::error",
12 + "nu::shell::external_command",
13 + "nu::shell::division_by_zero",
14 +]);
16 +const FRESH_ARGS = [
17 + "--no-config-file",
18 + "--no-history",
19 + "--error-style",
20 + "fancy",
21 + "--table-mode",
22 + "markdown",
23 + "-c",
24 +];
26 +export function findNu(): string | undefined {
27 + const path = Object.entries(process.env).find(
28 + ([key]) => key.toLowerCase() === "path",
29 + )?.[1];
30 + const names = process.platform === "win32" ? ["nu.exe"] : ["nu"];
31 + for (const directory of (path ?? "").split(delimiter)) {
32 + if (!directory) continue;
33 + for (const name of names) {
34 + const candidate = join(directory, name);
35 + if (existsSync(candidate)) return candidate;
36 + }
37 + }
38 + return undefined;
41 +function stopProcess(pid: number | undefined): void {
42 + if (!pid) return;
43 + if (process.platform === "win32") {
44 + const root = process.env.SystemRoot ?? "C:\\Windows";
45 + spawn(
46 + join(root, "System32", "taskkill.exe"),
47 + ["/F", "/T", "/PID", String(pid)],
48 + {
49 + stdio: "ignore",
50 + windowsHide: true,
51 + },
52 + ).unref();
53 + } else {
54 + try {
55 + process.kill(-pid, "SIGKILL");
56 + } catch {
57 + try {
58 + process.kill(pid, "SIGKILL");
59 + } catch {
60 + /* already exited */
61 + }
62 + }
63 + }
66 +export function freshOperations(
67 + binary: string,
68 + debug?: DebugLog,
69 +): BashOperations {
70 + return {
71 + async exec(command, cwd, { onData, signal, timeout, env }) {
72 + const started = debug ? performance.now() : 0;
73 + const callId = debug ? globalThis.crypto.randomUUID() : undefined;
74 + debug?.("fresh.start", {
75 + callId,
76 + commandLength: command.length,
77 + timeout,
78 + });
79 + let childPid: number | undefined;
80 + let exitCode: number | null = null;
81 + let timedOut = false;
82 + let stdoutBytes = 0;
83 + let stderrBytes = 0;
84 + try {
85 + if (signal?.aborted) throw new Error("aborted");
86 + if (
87 + timeout !== undefined &&
88 + (!Number.isFinite(timeout) ||
89 + timeout <= 0 ||
90 + timeout * 1000 > 2_147_483_647)
91 + )
92 + throw new Error(
93 + "Invalid timeout: must be a positive number of seconds within the timer range",
94 + );
95 + await access(cwd, constants.F_OK);
96 + const child = spawn(binary, [...FRESH_ARGS, command], {
97 + cwd,
98 + env,
99 + detached: process.platform !== "win32",
100 + stdio: ["ignore", "pipe", "pipe"],
101 + windowsHide: true,
102 + });
103 + childPid = child.pid;
104 + const onAbort = () => stopProcess(child.pid);
105 + const timer =
106 + timeout === undefined
107 + ? undefined
108 + : setTimeout(() => {
109 + timedOut = true;
110 + onAbort();
111 + }, timeout * 1000);
112 + signal?.addEventListener("abort", onAbort, { once: true });
113 + if (signal?.aborted) onAbort();
114 + if (debug) {
115 + child.stdout.on("data", (chunk: Buffer) => {
116 + stdoutBytes += chunk.length;
117 + onData(chunk);
118 + });
119 + child.stderr.on("data", (chunk: Buffer) => {
120 + stderrBytes += chunk.length;
121 + onData(chunk);
122 + });
123 + } else {
124 + child.stdout.on("data", onData);
125 + child.stderr.on("data", onData);
127 + try {
128 + exitCode = await new Promise<number | null>((resolve, reject) => {
129 + child.once("error", reject);
130 + child.once("exit", resolve);
131 + });
132 + if (signal?.aborted) throw new Error("aborted");
133 + if (timedOut) throw new Error(`timeout:${timeout}`);
134 + return { exitCode: exitCode ?? (child.signalCode ? 1 : null) };
135 + } finally {
136 + if (timer) clearTimeout(timer);
137 + signal?.removeEventListener("abort", onAbort);
139 + } finally {
140 + debug?.("fresh.finish", {
141 + callId,
142 + childPid,
143 + durationMs: performance.now() - started,
144 + exitCode,
145 + outcome: signal?.aborted
146 + ? "aborted"
147 + : timedOut
148 + ? "timeout"
149 + : exitCode === 0
150 + ? "success"
151 + : exitCode === null
152 + ? "failed"
153 + : "nonzero",
154 + stdoutBytes,
155 + stderrBytes,
156 + });
158 + },
159 + };
162 +type Worker = {
163 + client: Client;
164 + transport: StdioClientTransport;
165 + types: typeof import("@modelcontextprotocol/sdk/types.js");
168 +export class NuSession {
169 + private worker: Worker | undefined;
170 + private debug?: DebugLog;
171 + constructor(debug?: DebugLog) {
172 + this.debug = debug;
174 + setDebug(debug?: DebugLog): void {
175 + this.debug = debug;
177 + private pending: Promise<unknown> = Promise.resolve();
178 + private generation = 0;
180 + private async start(
181 + binary: string,
182 + cwd: string,
183 + debug?: DebugLog,
184 + callId?: string,
185 + ): Promise<Worker> {
186 + const started = debug ? performance.now() : 0;
187 + debug?.("session.connect.start", { callId });
188 + const { Client } = await import(
189 + "@modelcontextprotocol/sdk/client/index.js"
190 + );
191 + const { StdioClientTransport } = await import(
192 + "@modelcontextprotocol/sdk/client/stdio.js"
193 + );
194 + // Load MCP schemas with the first worker, not during inert Pi startup.
195 + const types = await import("@modelcontextprotocol/sdk/types.js");
196 + const client = new Client({ name: "pi-ext-nushell", version: "1" });
197 + const transport = new StdioClientTransport({
198 + command: binary,
199 + args: [
200 + "--no-config-file",
201 + "--no-history",
202 + "--mcp",
203 + "--mcp-transport",
204 + "stdio",
205 + ],
206 + cwd,
207 + env: Object.fromEntries(
208 + Object.entries(process.env).filter(
209 + (entry): entry is [string, string] => entry[1] !== undefined,
210 + ),
211 + ),
212 + stderr: "pipe",
213 + });
214 + // Nu MCP logs requests and responses to stderr, including command text.
215 + // Drain it; never print it into Pi's TUI or JSON mode.
216 + transport.stderr?.on("data", () => {});
217 + try {
218 + await client.connect(transport);
219 + } catch (error) {
220 + debug?.("session.connect.error", {
221 + callId,
222 + durationMs: performance.now() - started,
223 + errorType: error instanceof Error ? error.name : typeof error,
224 + });
225 + await client.close();
226 + throw error;
228 + debug?.("session.connect.ready", {
229 + callId,
230 + workerPid: transport.pid,
231 + durationMs: performance.now() - started,
232 + });
233 + return { client, transport, types };
236 + async evaluate(
237 + binary: string,
238 + cwd: string,
239 + command: string,
240 + signal?: AbortSignal,
241 + ): Promise<string> {
242 + const work = async () => {
243 + const debug = this.debug;
244 + const started = debug ? performance.now() : 0;
245 + const callId = debug ? globalThis.crypto.randomUUID() : undefined;
246 + debug?.("session.request.start", {
247 + callId,
248 + commandLength: command.length,
249 + });
250 + let worker: Worker | undefined;
251 + let startedCall = false;
252 + try {
253 + if (signal?.aborted)
254 + throw new Error("Nu session request aborted before execution");
255 + const generation = this.generation;
256 + worker = this.worker ?? (await this.start(binary, cwd, debug, callId));
257 + if (generation !== this.generation || signal?.aborted) {
258 + if (worker !== this.worker) await worker.client.close();
259 + throw new Error("Nu session reset before execution");
261 + this.worker = worker;
262 + startedCall = true;
263 + const { CallToolResultSchema } = worker.types;
264 + const result = CallToolResultSchema.parse(
265 + await worker.client.callTool(
266 + { name: "evaluate", arguments: { input: command } },
267 + CallToolResultSchema,
268 + { signal, timeout: 110_000 },
269 + ),
270 + );
271 + const text = result.content
272 + .filter((part) => part.type === "text")
273 + .map((part) => part.text)
274 + .join("\n");
275 + if (result.isError)
276 + throw new Error(text || "Nushell evaluation failed");
277 + debug?.("session.request.finish", {
278 + callId,
279 + workerPid: worker.transport.pid,
280 + durationMs: performance.now() - started,
281 + outputBytes: Buffer.byteLength(text),
282 + });
283 + return text || "(no output)";
284 + } catch (error) {
285 + const rawCode =
286 + debug && error instanceof Error
287 + ? /\bnu::[a-z_]+::[a-z_]+\b/.exec(error.message)?.[0]
288 + : undefined;
289 + debug?.("session.request.error", {
290 + callId,
291 + workerPid: worker?.transport.pid,
292 + durationMs: performance.now() - started,
293 + aborted: signal?.aborted ?? false,
294 + errorType: error instanceof Error ? error.name : typeof error,
295 + code:
296 + worker && error instanceof worker.types.McpError
297 + ? error.code
298 + : undefined,
299 + nuCode: rawCode && SAFE_NU_CODES.has(rawCode) ? rawCode : undefined,
300 + });
301 + if (startedCall && worker) {
302 + const { McpError, ErrorCode } = worker.types;
303 + if (
304 + signal?.aborted ||
305 + (error instanceof McpError &&
306 + (error.code === ErrorCode.RequestTimeout ||
307 + (error.code === ErrorCode.InternalError &&
308 + error.message.includes(
309 + "Operation promoted to background job (id:",
310 + ))))
311 + ) {
312 + await this.reset("interrupted");
313 + throw new Error(
314 + "Nu session interrupted; state reset. Detached external commands may still be running; inspect before retrying.",
315 + );
317 + if (worker.transport.pid === null) await this.reset("worker_exit");
319 + throw error;
321 + };
322 + const next = this.pending.then(work, work);
323 + this.pending = next.catch(() => {});
324 + return next;
327 + async reset(reason = "requested"): Promise<void> {
328 + this.generation++;
329 + const worker = this.worker;
330 + this.worker = undefined;
331 + this.debug?.("session.reset", {
332 + reason,
333 + workerPid: worker?.transport.pid ?? null,
334 + });
335 + if (worker) await worker.client.close();

package-lock.json

Modified
288 288 "@earendil-works/pi-tui": "*"
291 + "extensions/nushell": {
292 + "name": "@bugabinga/pi-ext-nushell",
293 + "license": "MIT",
294 + "dependencies": {
295 + "@modelcontextprotocol/sdk": "^1.29.0"
296 + },
297 + "devDependencies": {
298 + "@marcfargas/pi-test-harness": "^0.6.1",
299 + "vitest": "^4.1.9"
300 + },
301 + "peerDependencies": {
302 + "@earendil-works/pi-coding-agent": "*",
303 + "@earendil-works/pi-tui": "*",
304 + "typebox": "*"
306 + },
291 307 "extensions/open": {
292 308 "name": "@bugabinga/pi-ext-open",
293 309 "license": "MIT",
1364 1380 "resolved": "extensions/nu-bang",
1365 1381 "link": true
1383 + "node_modules/@bugabinga/pi-ext-nushell": {
1384 + "resolved": "extensions/nushell",
1385 + "link": true
1386 + },
1367 1387 "node_modules/@bugabinga/pi-ext-open": {
1368 1388 "resolved": "extensions/open",
1369 1389 "link": true