Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/nushell/diagnostic-help.ts

Raw
import { execFile } from "node:child_process";
import { promisify, stripVTControlCharacters } from "node:util";
import { truncateHead } from "@earendil-works/pi-coding-agent";

const execute = promisify(execFile);
// Parse a string, just like `nu -c`: no temporary filename changes import resolution.
// `ast` does not execute the source or merge its local declarations into this scope.
const ANALYZE =
	"ast --json --minify $env.PI_NU_HELP_SOURCE | insert commands { scope commands | select decl_id name } | to json -r";

type Span = { start: number; end: number };
export type DiagnosticHelp = {
	command: string;
	text: string;
	truncated: boolean;
};

function isRecord(value: unknown): value is Record<string, unknown> {
	return value !== null && typeof value === "object" && !Array.isArray(value);
}

function isSpan(value: unknown): value is Span {
	return (
		isRecord(value) &&
		typeof value["start"] === "number" &&
		typeof value["end"] === "number" &&
		Number.isSafeInteger(value["start"]) &&
		Number.isSafeInteger(value["end"]) &&
		value["start"] >= 0 &&
		value["start"] < value["end"]
	);
}

function contains(outer: Span, inner: Span): boolean {
	return outer.start <= inner.start && outer.end >= inner.end;
}

// Nested blocks are represented by IDs, not their bodies. Do not assign an
// error inside an argument expression to its enclosing command instead.
function insideExpression(
	values: unknown[],
	span: Span,
	extra: boolean,
): boolean {
	const pending = [...values];
	let visited = 0;
	while (pending.length) {
		if (++visited > 4096) return true;
		const value: unknown = pending.pop();
		if (Array.isArray(value)) pending.push(...value);
		else if (isRecord(value)) {
			if (
				"expr" in value &&
				isSpan(value["span"]) &&
				contains(value["span"], span) &&
				!(
					extra &&
					value["expr"] === "Garbage" &&
					value["span"].start === span.start &&
					value["span"].end === span.end
				)
			)
				return true;
			pending.push(...Object.values(value));
		}
	}
	return false;
}

/** Bounded native-parser analysis; original runtime statements are not replayed. */
export async function diagnosticHelp(
	binary: string,
	command: string,
	cwd: string,
	signal?: AbortSignal,
	timeoutMs = 1000,
): Promise<DiagnosticHelp | undefined> {
	try {
		if (
			signal?.aborted ||
			!Number.isFinite(timeoutMs) ||
			timeoutMs <= 0 ||
			command.length > 16_384 ||
			Buffer.byteLength(command) > 16_384
		)
			return;
		const deadline = AbortSignal.timeout(Math.ceil(Math.min(timeoutMs, 1000)));
		const combined = signal ? AbortSignal.any([signal, deadline]) : deadline;
		const run = async (source: string, env: NodeJS.ProcessEnv) =>
			(
				await execute(
					binary,
					["--no-config-file", "--no-history", "-c", source],
					{
						cwd,
						env,
						signal: combined,
						encoding: "utf8",
						maxBuffer: 128 * 1024,
						windowsHide: true,
					},
				)
			).stdout;
		const analysis = await run(ANALYZE, {
			...process.env,
			PI_NU_HELP_SOURCE: command,
		});
		combined.throwIfAborted();
		const parsed: unknown = JSON.parse(analysis);
		if (
			!isRecord(parsed) ||
			typeof parsed["block"] !== "string" ||
			typeof parsed["error"] !== "string" ||
			!parsed["error"].trim()
		)
			return;
		const block: unknown = JSON.parse(parsed["block"]);
		const error: unknown = JSON.parse(parsed["error"]);
		if (
			!isRecord(block) ||
			!isSpan(block["span"]) ||
			block["span"].end - block["span"].start !== Buffer.byteLength(command) ||
			!isRecord(error) ||
			Object.keys(error).length !== 1
		)
			return;
		const extra = "ExtraPositional" in error;
		const details = extra ? error["ExtraPositional"] : error["UnknownFlag"];
		if (!Array.isArray(details) || typeof details[0] !== "string") return;
		const span = details[extra ? 1 : 2];
		if (!isSpan(span) || !contains(block["span"], span)) return;
		const pipelines = block["pipelines"];
		const commands = parsed["commands"];
		if (
			!Array.isArray(pipelines) ||
			pipelines.length > 1024 ||
			!Array.isArray(commands) ||
			commands.length > 1024
		)
			return;
		const targets: string[] = [];
		for (const pipeline of pipelines) {
			if (
				!isRecord(pipeline) ||
				!Array.isArray(pipeline["elements"]) ||
				pipeline["elements"].length > 1024
			)
				return;
			for (const element of pipeline["elements"]) {
				if (!isRecord(element)) continue;
				const expression = element["expr"];
				if (
					!isRecord(expression) ||
					!isSpan(expression["span"]) ||
					!contains(expression["span"], span)
				)
					continue;
				const expr = expression["expr"];
				const call = isRecord(expr) ? expr["Call"] : undefined;
				if (
					!isRecord(call) ||
					!isSpan(call["head"]) ||
					!contains(expression["span"], call["head"]) ||
					span.start < call["head"].end ||
					typeof call["decl_id"] !== "number" ||
					!Array.isArray(call["arguments"]) ||
					insideExpression(call["arguments"], span, extra)
				)
					continue;
				// Redirection targets are sibling expressions, not call arguments.
				// Their errors must never use the direct-argument Garbage exception.
				if (insideExpression([element["redirection"]], span, false)) continue;
				// IDs refer to this same Nu process. New custom/shadowing declarations
				// are absent from the permanent catalog; aliases retain their target ID.
				const declaration: unknown = commands.find(
					(value) => isRecord(value) && value["decl_id"] === call["decl_id"],
				);
				if (
					isRecord(declaration) &&
					typeof declaration["name"] === "string" &&
					(extra || declaration["name"] === details[0])
				)
					targets.push(declaration["name"]);
			}
		}
		if (targets.length !== 1) return;
		const target = targets[0];
		if (!target) return;
		combined.throwIfAborted();
		const help = await run("help $env.PI_NU_HELP_TARGET", {
			...process.env,
			PI_NU_HELP_TARGET: target,
		});
		const truncated = truncateHead(stripVTControlCharacters(help), {
			maxBytes: 8192,
			maxLines: 200,
		});
		if (combined.aborted || !truncated.content.trim()) return;
		return {
			command: target,
			text: truncated.content,
			truncated: truncated.truncated,
		};
	} catch {
		// Parser/version/lookup failures must not replace the original command result.
		return;
	}
}