repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

fix(nu-bang): harden shell bridge

9da82fdf7f1d9d59ab2693ce00a6417abb03ff08

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (4)

+785 / −38 text lines

Diff layout

pi/agent/extensions/nu-bang/README.md

Modified

+14 / −1 text lines

33Nushell bang-command bridge for Pi.
5Runs Pi ! and !! shell input through Nushell with completions.
5Runs Pi `!` and `!!` shell input through Nushell with completions. Requires `nu` in `PATH`.
6
7## Install / load
8
9Install or copy this package into a Pi extension location, then `/reload`.
11Canonical loading options: [Pi extension locations](https://github.com/earendil-works/pi-coding-agent/blob/main/docs/extensions.md#extension-locations).
13## Commands / tools / settings
15- Commands: none
16- Tools: none
17- Hooks: `user_bash`, autocomplete provider
18- Settings: none
720## Demo

pi/agent/extensions/nu-bang/__tests__/nu-bang.test.ts

Modified

+138 / −0 text lines

11import { describe, expect, test } from "bun:test";
2import { join } from "node:path";
23import { completionPrefix, cursorOffset, parseCompletionsOutput, stripBangPrefix, wrapNuAutocompleteProvider } from "../index.js";
45describe("nu-bang helpers", () => {
1920 expect(completionPrefix("ls | wh", 7)).toBe("wh");
2021 expect(completionPrefix("$env.PA", 7)).toBe("PA");
2122 expect(completionPrefix("$env.", 5)).toBe("");
23 expect(completionPrefix("open people.j", 13)).toBe("people.j");
24 expect(completionPrefix("open .e", 7)).toBe(".e");
25 expect(completionPrefix("open my\\ f", 10)).toBe("my\\ f");
26 expect(completionPrefix('open "my f', 10)).toBe('"my f');
27 expect(completionPrefix("open 'my f", 10)).toBe("'my f");
28 expect(completionPrefix("open `my f", 10)).toBe("`my f");
2229 });
2431 test("salvages malformed completion JSON", () => {
4552 });
4653 });
55 test("applies dotted path completions without duplicating prefix", () => {
56 const provider = wrapNuAutocompleteProvider({
57 async getSuggestions() {
58 return null;
59 },
60 applyCompletion() {
61 throw new Error("not used");
62 },
63 }, process.cwd());
65 const prefix = completionPrefix("open people.j", 13);
67 expect(provider.applyCompletion(["!open people.j"], 0, 14, { value: "people.json", label: "people.json" }, prefix)).toEqual({
68 lines: ["!open people.json"],
69 cursorLine: 0,
70 cursorCol: 17,
71 });
72 });
74 test("applies quoted path completions without leaving stale quotes", () => {
75 const provider = wrapNuAutocompleteProvider({
76 async getSuggestions() {
77 return null;
78 },
79 applyCompletion() {
80 throw new Error("not used");
81 },
82 }, process.cwd());
83 const prefix = completionPrefix('open "my f', 10);
85 expect(provider.applyCompletion(['!open "my f'], 0, 11, { value: '`my file.txt`', label: '`my file.txt`' }, prefix)).toEqual({
86 lines: ['!open `my file.txt`'],
87 cursorLine: 0,
88 cursorCol: 19,
89 });
90 });
92 test("removes existing closing quote when applying quoted path completions", () => {
93 const provider = wrapNuAutocompleteProvider({
94 async getSuggestions() {
95 return null;
96 },
97 applyCompletion() {
98 throw new Error("not used");
99 },
100 }, process.cwd());
102 expect(provider.applyCompletion(['!open "my f"'], 0, 11, { value: '`my file.txt`', label: '`my file.txt`' }, completionPrefix('open "my f', 10))).toEqual({
103 lines: ['!open `my file.txt`'],
104 cursorLine: 0,
105 cursorCol: 19,
106 });
107 expect(provider.applyCompletion(["!open 'my f'"], 0, 11, { value: '`my file.txt`', label: '`my file.txt`' }, completionPrefix("open 'my f", 10))).toEqual({
108 lines: ['!open `my file.txt`'],
109 cursorLine: 0,
110 cursorCol: 19,
111 });
112 expect(provider.applyCompletion(['!open `my f`'], 0, 11, { value: '`my file.txt`', label: '`my file.txt`' }, completionPrefix('open `my f', 10))).toEqual({
113 lines: ['!open `my file.txt`'],
114 cursorLine: 0,
115 cursorCol: 19,
116 });
117 });
119 test("applies escaped-space path completions without duplicating prefix", () => {
120 const provider = wrapNuAutocompleteProvider({
121 async getSuggestions() {
122 return null;
123 },
124 applyCompletion() {
125 throw new Error("not used");
126 },
127 }, process.cwd());
128 const prefix = completionPrefix("open my\\ f", 10);
130 expect(provider.applyCompletion(["!open my\\ f"], 0, 11, { value: "`my file.txt`", label: "`my file.txt`" }, prefix)).toEqual({
131 lines: ["!open `my file.txt`"],
132 cursorLine: 0,
133 cursorCol: 19,
134 });
135 });
48137 test("delegates non-bang completion application", () => {
49138 const provider = wrapNuAutocompleteProvider({
50139 async getSuggestions() {
67156 });
68157 });
159 test("delegates fallback-origin bang completion application", async () => {
160 let applyCalls = 0;
161 const fallbackItem = { value: "/reload", label: "reload" };
162 const provider = wrapNuAutocompleteProvider({
163 async getSuggestions(lines, cursorLine, cursorCol) {
164 expect(lines).toEqual(["!bad"]);
165 expect(cursorLine).toBe(0);
166 expect(cursorCol).toBe(4);
167 return { prefix: "/re", items: [fallbackItem] };
168 },
169 applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
170 applyCalls++;
171 expect(lines).toEqual(["!bad"]);
172 expect(cursorLine).toBe(0);
173 expect(cursorCol).toBe(4);
174 expect(item).toBe(fallbackItem);
175 expect(prefix).toBe("/re");
176 return { lines: ["!/reload"], cursorLine: 0, cursorCol: 8 };
177 },
178 }, join(process.cwd(), "missing-nu-bang-cwd"));
180 const suggestions = await provider.getSuggestions(["!bad"], 0, 4, { signal: new AbortController().signal });
181 expect(suggestions?.items[0]).toBe(fallbackItem);
182 expect(provider.applyCompletion(["!bad"], 0, 4, fallbackItem, suggestions?.prefix ?? "")).toEqual({
183 lines: ["!/reload"],
184 cursorLine: 0,
185 cursorCol: 8,
186 });
187 expect(applyCalls).toBe(1);
188 });
190 test("does not invoke fallback suggestions for already-aborted bang completion failures", async () => {
191 let fallbackCalls = 0;
192 const controller = new AbortController();
193 controller.abort();
194 const provider = wrapNuAutocompleteProvider({
195 async getSuggestions() {
196 fallbackCalls++;
197 return { prefix: "x", items: [{ value: "fallback", label: "fallback" }] };
198 },
199 applyCompletion() {
200 throw new Error("not used");
201 },
202 }, join(process.cwd(), "missing-nu-bang-cwd"));
204 await expect(provider.getSuggestions(["!bad"], 0, 4, { signal: controller.signal })).resolves.toBeNull();
205 expect(fallbackCalls).toBe(0);
206 });
70208 test("allows tab completion for bang input", () => {
71209 const provider = wrapNuAutocompleteProvider({
72210 async getSuggestions() {

pi/agent/extensions/nu-bang/__tests__/real-world.test.ts

Modified

+275 / −3 text lines

11import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
33import { readdirSync } from "node:fs";
44import { tmpdir } from "node:os";
55import { join } from "node:path";
6import { executeNu, nuCompletions } from "../index.js";
6import { createNuBashOperations, executeNu, nuCompletions, wrapNuAutocompleteProvider } from "../index.js";
88let dir = "";
1717 await writeFile(join(dir, "config.nuon"), "{host: localhost, ports: [8080, 8081], enabled: true}", "utf8");
1818 await writeFile(join(dir, "alpha.nu"), "export def greet [name: string] { $'hello ($name)' }", "utf8");
1919 await writeFile(join(dir, "beta.txt"), "hello\nworld\n", "utf8");
20 await writeFile(join(dir, "my file.txt"), "space path\n", "utf8");
21 await writeFile(join(dir, "hash#file.txt"), "hash path\n", "utf8");
22 await writeFile(join(dir, "semi;file.txt"), "semi path\n", "utf8");
23 await writeFile(join(dir, "paren(file).txt"), "paren path\n", "utf8");
24 await writeFile(join(dir, "brack[file].txt"), "brack path\n", "utf8");
25 await mkdir(join(dir, "my dir"));
26 await mkdir(join(dir, "src"));
2027 await writeFile(join(dir, "script.nu"), "let x = 1\n$x + 1\n", "utf8");
143150 expect(result.output).toContain("err");
144151 });
153 test("preserves interleaved stdout and stderr", async () => {
154 const result = await run('^bash -lc "printf out1; sleep 0.05; printf err1 >&2; sleep 0.05; printf out2; sleep 0.05; printf err2 >&2"');
155 expect(result.exitCode).toBe(0);
156 expect(result.output).toBe("out1err1out2err2");
157 });
159 test("cancels long-running external commands", async () => {
160 const controller = new AbortController();
161 const started = Date.now();
162 setTimeout(() => controller.abort(), 50);
163 const result = await executeNu('^bash -lc "sleep 5"', dir, controller.signal);
164 expect(Date.now() - started).toBeLessThan(1000);
165 expect(result.cancelled).toBe(true);
166 });
168 test("streams output through bash operations before command exit", async () => {
169 const controller = new AbortController();
170 const operations = createNuBashOperations('^bash -lc "echo first; sleep 5; echo second"');
171 let done = false;
172 let seen = "";
173 let resolveFirst: () => void = () => {};
174 const firstChunk = new Promise<void>((resolve) => { resolveFirst = resolve; });
175 const timeout = new Promise<never>((_, reject) => setTimeout(() => reject(new Error("timed out waiting for streamed output")), 1000));
177 const exec = operations.exec("ignored", dir, {
178 onData(chunk) {
179 seen += chunk.toString("utf8");
180 if (seen.includes("first")) resolveFirst();
181 },
182 signal: controller.signal,
183 }).finally(() => { done = true; });
185 await Promise.race([firstChunk, timeout]);
186 expect(seen).toContain("first");
187 expect(done).toBe(false);
189 controller.abort();
190 await exec;
191 });
193 test("does not wait for background children that inherit stdio", async () => {
194 const started = Date.now();
195 const result = await run('^bash -lc "sleep 1.2 & echo done"');
196 expect(Date.now() - started).toBeLessThan(1000);
197 expect(result.exitCode).toBe(0);
198 expect(result.output).toBe("done\n");
199 });
146201 test("supports save side effects in cwd", async () => {
147202 const result = await run('"created" | save generated.txt --force');
148203 expect(result.exitCode).toBe(0);
174229 expect(result.output).not.toContain("\u001b[");
175230 });
232 test("strips terminal control sequences from returned output", async () => {
233 const result = await run(String.raw`^bash -lc "printf $'plain\\033[31mred\\033[0m\\nosc\\033]0;title\\007done\\nctrl\\001x\\n'"`);
234 expect(result.exitCode).toBe(0);
235 expect(result.output).toContain("plainred");
236 expect(result.output).toContain("oscdone");
237 expect(result.output).toContain("ctrlx");
238 expect(result.output).not.toContain("\u001b");
239 expect(result.output).not.toContain("\u0007");
240 expect(result.output).not.toContain("\u0001");
241 expect(result.output).not.toContain("]0;title");
242 });
244 test("strips carriage returns and C1 terminal controls from returned output", async () => {
245 const result = await run(String.raw`^bash -lc 'printf "cr\rkeep\nc1\302\23331mred\302\2330m\n"'`);
246 expect(result.exitCode).toBe(0);
247 expect(result.output).toContain("crkeep");
248 expect(result.output).toContain("c1red");
249 expect(result.output).not.toContain("\r");
250 expect(result.output).not.toContain("\u009b");
251 expect(result.output).not.toContain("31m");
252 expect(result.output).not.toContain("0m");
253 });
255 test("strips unterminated terminal string controls from returned output", async () => {
256 const result = await run(String.raw`^bash -lc 'printf "ok\n\033]0;title\nvisible\n\033Psecret\nnext\n\302\235c1title\nlast\n"'`);
257 expect(result.exitCode).toBe(0);
258 expect(result.output).toContain("ok\n");
259 expect(result.output).toContain("visible\n");
260 expect(result.output).toContain("next\n");
261 expect(result.output).toContain("last\n");
262 expect(result.output).not.toContain("title");
263 expect(result.output).not.toContain("secret");
264 expect(result.output).not.toContain("\u001b");
265 expect(result.output).not.toContain("\u009d");
266 });
268 test("strips terminated DCS controls without dropping following text", async () => {
269 const result = await run(String.raw`^python3 -c 'import sys; sys.stdout.buffer.write(b"before\x1bPsecret\x1b\\after\n")'`);
270 expect(result.exitCode).toBe(0);
271 expect(result.output).toBe("beforeafter\n");
272 expect(result.output).not.toContain("secret");
273 expect(result.output).not.toContain("\u001b");
274 });
177276 test("shows nu's native parser diagnostics", async () => {
178277 const result = await run("ls | where");
179278 expect(result.exitCode).toBe(1);
187286 expect(result.output).toContain("Unexpected end of code");
188287 });
289 test("reports a missing working directory clearly", async () => {
290 const missing = join(dir, "missing-cwd");
291 const result = await executeNu("pwd", missing);
293 expect(result.exitCode).toBe(1);
294 expect(result.output).toContain("Working directory does not exist");
295 expect(result.output).toContain(missing);
296 expect(result.output).not.toContain("posix_spawn");
297 expect(result.output).not.toContain("spawn nu");
298 });
300 test("escapes controls in execute working directory errors", async () => {
301 const unsafeMissing = join(dir, "missing-\u001b[31mred");
302 const missingResult = await executeNu("pwd", unsafeMissing);
303 expect(missingResult.output).toContain("Working directory does not exist");
304 expect(missingResult.output).toContain("missing-\\u001b[31mred");
305 expect(missingResult.output).not.toContain("\u001b");
307 const unsafeFile = join(dir, "file-\u001b[32mgreen");
308 await writeFile(unsafeFile, "not a directory", "utf8");
309 const fileResult = await executeNu("pwd", unsafeFile);
310 expect(fileResult.output).toContain("Working directory is not a directory");
311 expect(fileResult.output).toContain("file-\\u001b[32mgreen");
312 expect(fileResult.output).not.toContain("\u001b");
313 });
190315 test("does not leave pi-nu-bang temp dirs after execution", async () => {
191316 const before = tmpBangDirs();
192317 await run("ls | first 1");
194319 expect(after.sort()).toEqual(before.sort());
195320 });
197 test("truncates huge output", async () => {
322 test("truncates huge output and exposes readable full output", async () => {
198323 const result = await run("1..2500 | each {|n| $'line-($n)' } | str join (char nl)");
199324 expect(result.truncated).toBe(true);
200325 expect(result.output).toContain("truncated");
201326 expect(result.output).toContain("line-2500");
327 expect(typeof result.fullOutputPath).toBe("string");
329 try {
330 const fullOutputStat = await stat(result.fullOutputPath!);
331 expect(fullOutputStat.mode & 0o777).toBe(0o600);
332 const fullOutput = await readFile(result.fullOutputPath!, "utf8");
333 expect(fullOutput).toContain("line-1");
334 expect(fullOutput).toContain("line-2500");
335 expect(fullOutput.length).toBeGreaterThan(result.output.length);
336 } finally {
337 await rm(result.fullOutputPath!, { force: true });
338 }
202339 });
203340});
215352 expect(completions).toContain("logs.csv");
216353 });
355 test("does not expose terminal controls in path completions", async () => {
356 await writeFile(join(dir, "unsafe-\u001b[31mred\u0007.txt"), "unsafe", "utf8");
358 const completions = await nuCompletions("open unsafe-", 12, dir);
359 const unsafeCompletion = completions.find((completion) => completion.includes("unsafe-"));
361 expect(unsafeCompletion).toBeString();
362 expect(unsafeCompletion).toContain("unsafe-\\u001b[31mred\\u0007.txt");
363 expect(unsafeCompletion).not.toContain("\u001b");
364 expect(unsafeCompletion).not.toContain("\u0007");
365 });
367 test("filters escaped-space path suggestions to the typed prefix", async () => {
368 const provider = wrapNuAutocompleteProvider({
369 async getSuggestions() {
370 return null;
371 },
372 applyCompletion() {
373 throw new Error("not used");
374 },
375 }, dir);
377 const broadSuggestions = await provider.getSuggestions(["!open my\\ "], 0, 10, { signal: new AbortController().signal, force: true });
378 expect(broadSuggestions?.prefix).toBe("my\\ ");
379 expect(broadSuggestions?.items.map((item) => item.value)).toEqual(["`my dir/`", "`my file.txt`"]);
381 const suggestions = await provider.getSuggestions(["!open my\\ f"], 0, 11, { signal: new AbortController().signal, force: true });
382 expect(suggestions?.prefix).toBe("my\\ f");
383 expect(suggestions?.items.map((item) => item.value)).toEqual(["`my file.txt`"]);
385 const directorySuggestions = await provider.getSuggestions(["!open my\\ d"], 0, 11, { signal: new AbortController().signal, force: true });
386 expect(directorySuggestions?.prefix).toBe("my\\ d");
387 expect(directorySuggestions?.items.map((item) => item.value)).toEqual(["`my dir/`"]);
388 });
390 test("completes escaped metacharacter paths instead of command suggestions", async () => {
391 const provider = wrapNuAutocompleteProvider({
392 async getSuggestions() {
393 return null;
394 },
395 applyCompletion() {
396 throw new Error("not used");
397 },
398 }, dir);
400 const cases = [
401 ["!open hash\\#", "hash\\#", "`hash#file.txt`"],
402 ["!open semi\\;", "semi\\;", "`semi;file.txt`"],
403 ["!open paren\\(", "paren\\(", "`paren(file).txt`"],
404 ["!open brack\\[", "brack\\[", "'brack[file].txt'"],
405 ] as const;
407 for (const [line, prefix, value] of cases) {
408 const suggestions = await provider.getSuggestions([line], 0, line.length, { signal: new AbortController().signal, force: true });
409 expect(suggestions?.prefix).toBe(prefix);
410 expect(suggestions?.items.map((item) => item.value)).toEqual([value]);
411 }
412 });
218414 test("completes env record cells", async () => {
219415 const completions = await nuCompletions("$env.", 5, dir);
220416 expect(completions).toContain("PATH");
225421 expect(completions.some((c) => c.includes("help") || c.includes("long"))).toBe(true);
226422 });
424 test("reports missing completion working directory clearly", async () => {
425 const missing = join(dir, "missing-completion-cwd");
427 await expect(nuCompletions("open ", 5, missing)).rejects.toThrow(`Working directory does not exist: ${missing}`);
428 });
430 test("escapes controls in completion working directory errors", async () => {
431 const unsafeMissing = join(dir, "missing-\u001b]0;title\u0007-cwd");
432 try {
433 await nuCompletions("open ", 5, unsafeMissing);
434 throw new Error("expected nuCompletions to reject");
435 } catch (error) {
436 const message = error instanceof Error ? error.message : String(error);
437 expect(message).toContain("Working directory does not exist");
438 expect(message).toContain("missing-\\u001b]0;title\\u0007-cwd");
439 expect(message).not.toContain("\u001b");
440 expect(message).not.toContain("\u0007");
441 }
443 const unsafeFile = join(dir, "file-\u001b[33myellow");
444 await writeFile(unsafeFile, "not a directory", "utf8");
445 try {
446 await nuCompletions("open ", 5, unsafeFile);
447 throw new Error("expected nuCompletions to reject");
448 } catch (error) {
449 const message = error instanceof Error ? error.message : String(error);
450 expect(message).toContain("Working directory is not a directory");
451 expect(message).toContain("file-\\u001b[33myellow");
452 expect(message).not.toContain("\u001b");
453 }
455 const unsafeParent = join(dir, "parent-\u001b[36mcyan");
456 const unsafeChild = join(unsafeParent, "child-\u001b]0;title\u0007-cwd");
457 await writeFile(unsafeParent, "not a directory", "utf8");
458 try {
459 await nuCompletions("open ", 5, unsafeChild);
460 throw new Error("expected nuCompletions to reject");
461 } catch (error) {
462 const message = error instanceof Error ? error.message : String(error);
463 expect(message).toContain("Working directory cannot be checked");
464 expect(message).toContain("parent-\\u001b[36mcyan");
465 expect(message).toContain("child-\\u001b]0;title\\u0007-cwd");
466 expect(message).not.toContain("\u001b");
467 expect(message).not.toContain("\u0007");
468 }
469 });
471 test("reports inaccessible working directories clearly", async () => {
472 const unsafeDir = join(dir, "deny-\u001b[35msecret");
473 await mkdir(unsafeDir);
474 await chmod(unsafeDir, 0o000);
476 try {
477 const result = await executeNu("pwd", unsafeDir);
478 expect(result.output).toContain("Working directory is not accessible");
479 expect(result.output).toContain("deny-\\u001b[35msecret");
480 expect(result.output).not.toContain("posix_spawn");
481 expect(result.output).not.toContain("spawn nu");
482 expect(result.output).not.toContain("\u001b");
484 try {
485 await nuCompletions("open ", 5, unsafeDir);
486 throw new Error("expected nuCompletions to reject");
487 } catch (error) {
488 const message = error instanceof Error ? error.message : String(error);
489 expect(message).toContain("Working directory is not accessible");
490 expect(message).toContain("deny-\\u001b[35msecret");
491 expect(message).not.toContain("posix_spawn");
492 expect(message).not.toContain("spawn nu");
493 expect(message).not.toContain("\u001b");
494 }
495 } finally {
496 await chmod(unsafeDir, 0o700).catch(() => {});
497 }
498 });
228500 test("completion temp dirs are cleaned", async () => {
229501 const before = tmpBangDirs();
230502 await nuCompletions("open ", 5, dir);

pi/agent/extensions/nu-bang/index.ts

Modified

+358 / −34 text lines

1import { spawn } from "node:child_process";
2import { mkdtemp, rm, writeFile } from "node:fs/promises";
1import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2import { randomBytes } from "node:crypto";
3import { constants } from "node:fs";
4import { access, mkdtemp, rm, stat, writeFile } from "node:fs/promises";
35import { tmpdir } from "node:os";
46import { join } from "node:path";
5import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6import { truncateTail } from "@earendil-works/pi-coding-agent";
7import { truncateTail, type BashOperations, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
78import type { AutocompleteItem, AutocompleteProvider } from "@earendil-works/pi-tui";
910interface ProcessResult {
1011 stdout: string;
1112 stderr: string;
13 output: string;
1214 code: number | undefined;
1315 signal: NodeJS.Signals | null;
2325 exitCode: number | undefined;
2426 cancelled: boolean;
2527 truncated: boolean;
28 fullOutputPath?: string;
2831const NU_BIN = "nu";
3033const NU_TABLE_MODE = "none";
3134const TEMP_PREFIX = "pi-nu-bang-";
3235const TEMP_FILE_NAME = "command.nu";
36const FULL_OUTPUT_PREFIX = "pi-nu-bang-output-";
37const EXIT_STDIO_GRACE_MS = 100;
3439const tempDirs = new Set<string>();
4146 return [...nuBaseArgs(), "--table-mode", NU_TABLE_MODE, "-c", command];
49function fullOutputPath(): string {
50 return join(tmpdir(), `${FULL_OUTPUT_PREFIX}${randomBytes(8).toString("hex")}.log`);
51}
53async function persistFullOutput(output: string): Promise<string> {
54 const path = fullOutputPath();
55 await writeFile(path, output, { encoding: "utf8", mode: 0o600 });
56 return path;
57}
59function escapeControlChars(text: string): string {
60 return text.replace(/[\x00-\x1F\x7F-\x9F]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
61}
63function stripTerminalControls(output: string): string {
64 return output
65 .replace(/\x1B\][\s\S]*?(?:\x07|\x1B\\|\u009C)/g, "")
66 .replace(/\u009D[\s\S]*?(?:\x07|\x1B\\|\u009C)/g, "")
67 .replace(/\x1B[PX^_][\s\S]*?(?:\x1B\\|\u009C)/g, "")
68 .replace(/[\u0090\u0098\u009E\u009F][\s\S]*?(?:\x1B\\|\u009C)/g, "")
69 .replace(/\x1B[PX^_][^\r\n]*(?=\r?\n|$)/g, "")
70 .replace(/\x1B\][^\r\n]*(?=\r?\n|$)/g, "")
71 .replace(/[\u0090\u0098\u009D\u009E\u009F][^\r\n]*(?=\r?\n|$)/g, "")
72 .replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
73 .replace(/\u009B[0-?]*[ -/]*[@-~]/g, "")
74 .replace(/\x1B[@-Z\\-_]/g, "")
75 .replace(/[\x00-\x08\x0B-\x0D\x0E-\x1F\x7F-\x9F]/g, "");
76}
4478function truncateOutput(output: string): { output: string; truncated: boolean } {
4579 const truncated = truncateTail(output);
4680 if (!truncated.truncated) return { output: truncated.content, truncated: false };
5488 };
91function nodeErrorCode(error: unknown): string | undefined {
92 return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : undefined;
93}
95async function workingDirectoryError(cwd: string): Promise<string | undefined> {
96 const safeCwd = escapeControlChars(cwd);
97 try {
98 const info = await stat(cwd);
99 if (!info.isDirectory()) return `Working directory is not a directory: ${safeCwd}`;
100 try {
101 await access(cwd, constants.X_OK);
102 return undefined;
103 } catch (error) {
104 const code = nodeErrorCode(error);
105 if (code === "EACCES") {
106 return `Working directory is not accessible: ${safeCwd}`;
107 }
108 if (code) return `Working directory cannot be checked: ${safeCwd} (${escapeControlChars(code)})`;
109 throw error;
110 }
111 } catch (error) {
112 const code = nodeErrorCode(error);
113 if (code === "ENOENT") {
114 return `Working directory does not exist: ${safeCwd}`;
115 }
116 if (code) return `Working directory cannot be checked: ${safeCwd} (${escapeControlChars(code)})`;
117 throw error;
118 }
119}
121function waitForForegroundProcess(child: ChildProcessWithoutNullStreams): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {
122 return new Promise((resolve, reject) => {
123 let settled = false;
124 let exited = false;
125 let exitCode: number | null = null;
126 let exitSignal: NodeJS.Signals | null = null;
127 let postExitTimer: ReturnType<typeof setTimeout> | undefined;
128 let stdoutEnded = false;
129 let stderrEnded = false;
131 function cleanup(): void {
132 if (postExitTimer) clearTimeout(postExitTimer);
133 child.removeListener("error", onError);
134 child.removeListener("exit", onExit);
135 child.removeListener("close", onClose);
136 child.stdout.removeListener("end", onStdoutEnd);
137 child.stderr.removeListener("end", onStderrEnd);
138 }
140 function finalize(code: number | null, processSignal: NodeJS.Signals | null): void {
141 if (settled) return;
142 settled = true;
143 cleanup();
144 child.stdout.destroy();
145 child.stderr.destroy();
146 resolve({ code, signal: processSignal });
147 }
149 function maybeFinalizeAfterExit(): void {
150 if (exited && stdoutEnded && stderrEnded) finalize(exitCode, exitSignal);
151 }
153 function onStdoutEnd(): void {
154 stdoutEnded = true;
155 maybeFinalizeAfterExit();
156 }
158 function onStderrEnd(): void {
159 stderrEnded = true;
160 maybeFinalizeAfterExit();
161 }
163 function onError(error: Error): void {
164 if (settled) return;
165 settled = true;
166 cleanup();
167 reject(error);
168 }
170 function onExit(code: number | null, processSignal: NodeJS.Signals | null): void {
171 exited = true;
172 exitCode = code;
173 exitSignal = processSignal;
174 maybeFinalizeAfterExit();
175 if (!settled) postExitTimer ??= setTimeout(() => finalize(code, processSignal), EXIT_STDIO_GRACE_MS);
176 }
178 function onClose(code: number | null, processSignal: NodeJS.Signals | null): void {
179 finalize(code, processSignal);
180 }
182 child.stdout.once("end", onStdoutEnd);
183 child.stderr.once("end", onStderrEnd);
184 child.once("error", onError);
185 child.once("exit", onExit);
186 child.once("close", onClose);
187 });
188}
57190function runProcess(args: string[], cwd: string, signal?: AbortSignal): Promise<ProcessResult> {
58191 return new Promise((resolve, reject) => {
59192 let stdout = "";
60193 let stderr = "";
194 let output = "";
196 runStreamingProcess(args, cwd, {
197 onStdout(chunk) {
198 const text = chunk.toString("utf8");
199 stdout += text;
200 output += text;
201 },
202 onStderr(chunk) {
203 const text = chunk.toString("utf8");
204 stderr += text;
205 output += text;
206 },
207 signal,
208 })
209 .then((result) => resolve({ stdout, stderr, output, code: result.exitCode ?? undefined, signal: result.signal }))
210 .catch(reject);
211 });
212}
214function runStreamingProcess(
215 args: string[],
216 cwd: string,
217 options: {
218 onStdout?: (chunk: Buffer) => void;
219 onStderr?: (chunk: Buffer) => void;
220 signal?: AbortSignal;
221 timeout?: number;
222 env?: NodeJS.ProcessEnv;
223 },
224): Promise<{ exitCode: number | null; signal: NodeJS.Signals | null }> {
225 return new Promise((resolve, reject) => {
226 let aborted = options.signal?.aborted ?? false;
227 let timedOut = false;
228 let forceKillTimer: ReturnType<typeof setTimeout> | undefined;
229 let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
230 const detached = process.platform !== "win32";
61231 const child = spawn(NU_BIN, args, {
62232 cwd,
63 env: process.env,
233 detached,
234 env: options.env ?? process.env,
64235 stdio: ["ignore", "pipe", "pipe"],
65 signal,
66236 });
68 child.stdout.setEncoding("utf8");
69 child.stderr.setEncoding("utf8");
70 child.stdout.on("data", (chunk: string) => { stdout += chunk; });
71 child.stderr.on("data", (chunk: string) => { stderr += chunk; });
72 child.on("error", (error) => {
73 if ((error as NodeJS.ErrnoException).name === "AbortError") {
74 resolve({ stdout, stderr, code: undefined, signal: "SIGTERM" });
75 return;
238 function killProcessGroup(kind: NodeJS.Signals): void {
239 if (child.pid === undefined) return;
240 try {
241 if (detached) process.kill(-child.pid, kind);
242 else child.kill(kind);
243 } catch {
244 try { child.kill(kind); } catch {}
76245 }
77 reject(error);
78 });
79 child.on("close", (code, processSignal) => {
80 resolve({ stdout, stderr, code: code ?? undefined, signal: processSignal });
81 });
246 }
248 function abortProcess(): void {
249 aborted = true;
250 killProcessGroup("SIGTERM");
251 forceKillTimer ??= setTimeout(() => killProcessGroup("SIGKILL"), 250);
252 }
254 function cleanup(): void {
255 if (forceKillTimer) clearTimeout(forceKillTimer);
256 if (timeoutTimer) clearTimeout(timeoutTimer);
257 options.signal?.removeEventListener("abort", abortProcess);
258 }
260 if (options.timeout !== undefined && options.timeout > 0) {
261 timeoutTimer = setTimeout(() => {
262 timedOut = true;
263 killProcessGroup("SIGTERM");
264 forceKillTimer ??= setTimeout(() => killProcessGroup("SIGKILL"), 250);
265 }, options.timeout * 1000);
266 }
268 child.stdout.on("data", (chunk: Buffer) => options.onStdout?.(chunk));
269 child.stderr.on("data", (chunk: Buffer) => options.onStderr?.(chunk));
271 waitForForegroundProcess(child)
272 .then((result) => {
273 cleanup();
274 if (timedOut) {
275 reject(new Error(`timeout:${options.timeout}`));
276 return;
277 }
278 resolve({ exitCode: result.code, signal: aborted ? "SIGTERM" : result.signal });
279 })
280 .catch((error: unknown) => {
281 cleanup();
282 if (aborted) {
283 resolve({ exitCode: null, signal: "SIGTERM" });
284 return;
285 }
286 reject(error);
287 });
289 if (options.signal) {
290 options.signal.addEventListener("abort", abortProcess, { once: true });
291 if (options.signal.aborted) abortProcess();
292 }
82293 });
109320 return Math.max(0, offset - prefixLength);
323function completionToken(before: string): string {
324 let tokenStart = 0;
325 let quote: string | undefined;
326 let escaped = false;
328 for (let i = 0; i < before.length; i++) {
329 const char = before[i] ?? "";
330 if (quote) {
331 if (escaped) {
332 escaped = false;
333 continue;
334 }
335 if (char === "\\" && quote !== "`") {
336 escaped = true;
337 continue;
338 }
339 if (char === quote) quote = undefined;
340 continue;
341 }
343 if (escaped) {
344 escaped = false;
345 continue;
346 }
347 if (char === "\\") {
348 escaped = true;
349 continue;
350 }
351 if (char === "\"" || char === "'" || char === "`") {
352 quote = char;
353 continue;
354 }
355 if (/[\s|;(){}\[\]]/.test(char)) tokenStart = i + 1;
356 }
358 return before.slice(tokenStart);
359}
112361export function completionPrefix(code: string, offset: number): string {
113 const before = code.slice(0, offset);
114 const token = before.match(/[^\s|;(){}\[\]"'`]*$/)?.[0] ?? "";
362 const token = completionToken(code.slice(0, offset));
115363 const dot = token.lastIndexOf(".");
116 return dot >= 0 ? token.slice(dot + 1) : token;
364 const isVariableCellPath = /^\$[^\s|;(){}\[\]"'`]*$/.test(token);
365 return isVariableCellPath && dot >= 0 ? token.slice(dot + 1) : token;
366}
368function unescapeBackslashToken(value: string): string {
369 return value.replace(/\\(.)/g, "$1");
370}
372function escapedPathCompletionInput(code: string, offset: number, prefix: string): { code: string; offset: number } | undefined {
373 if (!/\\./.test(prefix)) return undefined;
374 const start = offset - prefix.length;
375 if (start < 0) return undefined;
377 const quotedPrefix = "`" + unescapeBackslashToken(prefix);
378 return {
379 code: `${code.slice(0, start)}${quotedPrefix}${code.slice(offset)}`,
380 offset: start + quotedPrefix.length,
381 };
382}
384function unquoteCompletionValue(value: string): string {
385 const quote = value[0];
386 return (quote === "`" || quote === "'" || quote === "\"") && value.endsWith(quote)
387 ? value.slice(1, -1)
388 : value;
389}
391function filterEscapedPathCompletions(values: string[], prefix: string): string[] {
392 const unescapedPrefix = unescapeBackslashToken(prefix);
393 return values.filter((value) => unescapeBackslashToken(unquoteCompletionValue(value)).startsWith(unescapedPrefix));
119396function stringArray(value: unknown): string[] {
188465export function parseCompletionsOutput(stdout: string): string[] {
189466 const text = stdout.trim();
190467 if (!text) return [];
191 return parseCompletionJson(text) ?? parseMalformedCompletionList(text);
468 return (parseCompletionJson(text) ?? parseMalformedCompletionList(text)).map(escapeControlChars);
194471export async function nuCompletions(code: string, offset: number, cwd: string, signal?: AbortSignal): Promise<string[]> {
472 const cwdProblem = await workingDirectoryError(cwd);
473 if (cwdProblem) throw new Error(cwdProblem);
195475 return withTempNuFile(code, async (file) => {
196476 const result = await runProcess([...nuBaseArgs(), "-I", cwd, "--ide-complete", String(offset), file], cwd, signal);
197477 return parseCompletionsOutput(result.stdout);
198478 });
201export async function executeNu(command: string, cwd: string): Promise<NuExecutionResult> {
481export function createNuBashOperations(fixedCommand?: string): BashOperations {
482 return {
483 async exec(command, cwd, options) {
484 const cwdProblem = await workingDirectoryError(cwd);
485 if (cwdProblem) throw new Error(cwdProblem);
487 const result = await runStreamingProcess(nuExecArgs(fixedCommand ?? command), cwd, {
488 onStdout: options.onData,
489 onStderr: options.onData,
490 signal: options.signal,
491 timeout: options.timeout,
492 env: options.env,
493 });
495 return { exitCode: result.exitCode };
496 },
497 };
498}
500export async function executeNu(command: string, cwd: string, signal?: AbortSignal): Promise<NuExecutionResult> {
202501 try {
203 const result = await runProcess(nuExecArgs(command), cwd);
204 const truncated = truncateOutput(`${result.stdout}${result.stderr}`);
502 const cwdProblem = await workingDirectoryError(cwd);
503 if (cwdProblem) throw new Error(cwdProblem);
505 const result = await runProcess(nuExecArgs(command), cwd, signal);
506 const output = stripTerminalControls(result.output);
507 const truncated = truncateOutput(output);
205508 return {
206509 output: truncated.output,
207510 exitCode: result.code,
208511 cancelled: result.signal !== null,
209512 truncated: truncated.truncated,
513 fullOutputPath: truncated.truncated ? await persistFullOutput(output) : undefined,
210514 };
211515 } catch (error) {
516 const message = error instanceof Error ? error.message : String(error);
212517 return {
213 output: `Nu execution failed: ${error instanceof Error ? error.message : String(error)}`,
518 output: `Nu execution failed: ${escapeControlChars(message)}`,
214519 exitCode: 1,
215520 cancelled: false,
216521 truncated: false,
226531 return values.map((value) => ({ value, label: value }));
534function matchingClosingQuote(prefix: string): string | undefined {
535 const quote = prefix[0];
536 return quote === "\"" || quote === "'" || quote === "`" ? quote : undefined;
537}
229539function replacePrefix(lines: string[], cursorLine: number, cursorCol: number, prefix: string, value: string) {
230540 const next = [...lines];
231541 const line = next[cursorLine] ?? "";
232542 const before = line.slice(0, cursorCol);
233543 const after = line.slice(cursorCol);
234 next[cursorLine] = before.slice(0, before.length - prefix.length) + value + after;
544 const closingQuote = matchingClosingQuote(prefix);
545 const adjustedAfter = closingQuote && after.startsWith(closingQuote) ? after.slice(1) : after;
546 next[cursorLine] = before.slice(0, before.length - prefix.length) + value + adjustedAfter;
235547 return { lines: next, cursorLine, cursorCol: cursorCol - prefix.length + value.length };
238550export function wrapNuAutocompleteProvider(current: AutocompleteProvider, cwd: string): AutocompleteProvider {
551 const fallbackItems = new WeakSet<AutocompleteItem>();
239553 return {
240554 async getSuggestions(lines, cursorLine, cursorCol, options) {
241555 const bang = stripBangPrefix(fullText(lines));
245559 if (offset === undefined) return null;
247561 try {
248 const items = completionItems(await nuCompletions(bang.command, offset, cwd, options.signal));
249 return items.length === 0 ? null : { prefix: completionPrefix(bang.command, offset), items };
562 const prefix = completionPrefix(bang.command, offset);
563 const retry = escapedPathCompletionInput(bang.command, offset, prefix);
564 let completions = await nuCompletions(bang.command, offset, cwd, options.signal);
565 if (retry) {
566 const retryCompletions = await nuCompletions(retry.code, retry.offset, cwd, options.signal);
567 completions = filterEscapedPathCompletions(retryCompletions.length > 0 ? retryCompletions : completions, prefix);
568 }
569 const items = completionItems(completions);
570 return items.length === 0 ? null : { prefix, items };
250571 } catch {
251 return current.getSuggestions(lines, cursorLine, cursorCol, options);
572 if (options.signal.aborted) return null;
573 const fallback = await current.getSuggestions(lines, cursorLine, cursorCol, options);
574 for (const item of fallback?.items ?? []) fallbackItems.add(item);
575 return fallback;
252576 }
253577 },
254578 applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
255 if (!stripBangPrefix(fullText(lines))) return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
579 if (!stripBangPrefix(fullText(lines)) || fallbackItems.has(item)) return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
256580 return replacePrefix(lines, cursorLine, cursorCol, prefix, item.value);
257581 },
258582 shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
276600 ctx.ui.addAutocompleteProvider((current) => wrapNuAutocompleteProvider(current, ctx.cwd));
277601 });
279 pi.on("user_bash", async (event) => {
280 return { result: await executeNu(event.command, event.cwd) };
603 pi.on("user_bash", (event) => {
604 return { operations: createNuBashOperations(event.command) };
281605 });