repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ssh-tools/index.ts

Raw
File outline
/**
 * SSH tools for pi — toggle remote mode, use ssh_read/write/edit/bash.
 * Reads ~/.ssh/config for hosts. Toggle with /ssh, /ssh off, /ssh <host>[:/path].
 */
import { spawn } from "node:child_process";
import { existsSync, readFileSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { extname, join } from "node:path";
import {
	type BashOperations,
	createBashToolDefinition,
	createEditToolDefinition,
	createReadToolDefinition,
	createWriteToolDefinition,
	type EditOperations,
	type ExtensionAPI,
	type ReadOperations,
	type WriteOperations,
} from "@earendil-works/pi-coding-agent";
import { Text } from "@earendil-works/pi-tui";

const STATUS_KEY = "ssh-tools";
const TOOL_NAMES = ["ssh_read", "ssh_write", "ssh_edit", "ssh_bash"] as const;
const TOOL_SET = new Set(TOOL_NAMES);
const SSH_CONFIG = join(homedir(), ".ssh", "config");

// ── types ──────────────────────────────────────────────────────────────
interface Profile {
	name: string;
	remote: string;
	cwd?: string;
}
interface Target {
	name: string;
	remote: string;
	cwd: string;
}
interface ExecOptions {
	stdin?: string;
	signal?: AbortSignal;
	timeoutSeconds?: number;
	onStdout?: (b: Buffer) => void;
	onStderr?: (b: Buffer) => void;
}

// ── config cache ───────────────────────────────────────────────────────
let _configCache: { profiles: Profile[]; mtime: number } | null = null;

function parseSshConfig(): Profile[] {
	try {
		if (!existsSync(SSH_CONFIG)) return [];
		const mtime = statSync(SSH_CONFIG).mtimeMs;
		if (_configCache && _configCache.mtime === mtime)
			return _configCache.profiles;

		const profiles = new Map<string, Profile>();
		for (const line of readFileSync(SSH_CONFIG, "utf8").split("\n")) {
			const raw = line.replace(/\s+#.*$/, "").trim();
			if (!raw) continue;
			const m = raw.match(/^Host\s+(.+)$/i);
			if (!m) continue;
			for (const alias of m[1]
				.split(/\s+/)
				.filter(Boolean)
				.filter((a) => !a.includes("*") && !a.includes("?"))) {
				if (!profiles.has(alias))
					profiles.set(alias, { name: alias, remote: alias });
			}
		}
		_configCache = {
			profiles: Array.from(profiles.values()).sort((a, b) =>
				a.name.localeCompare(b.name),
			),
			mtime,
		};
		return _configCache.profiles;
	} catch {
		return [];
	}
}

// ── shell quoting ──────────────────────────────────────────────────────
function shellQuote(s: string): string {
	return `'${s.replaceAll("'", `'"'"'`)}'`;
}

// ── ssh exec ───────────────────────────────────────────────────────────
function sshExec(remote: string, cmd: string, opts: ExecOptions = {}) {
	return new Promise<{ out: Buffer; err: Buffer; code: number | null }>(
		(res, rej) => {
			const child = spawn("ssh", [remote, cmd], {
				stdio: ["pipe", "pipe", "pipe"],
			});
			const out: Buffer[] = [],
				err: Buffer[] = [];
			let timedOut = false;
			const timeout =
				opts.timeoutSeconds && opts.timeoutSeconds > 0
					? opts.timeoutSeconds
					: undefined;
			const timer = timeout
				? setTimeout(() => {
						timedOut = true;
						child.kill();
					}, timeout * 1000)
				: undefined;

			const cleanup = () => {
				if (timer) clearTimeout(timer);
			};
			const onAbort = () => child.kill();

			child.stdout.on("data", (d) => {
				out.push(d);
				opts.onStdout?.(d);
			});
			child.stderr.on("data", (d) => {
				err.push(d);
				opts.onStderr?.(d);
			});
			child.on("error", (e) => {
				cleanup();
				rej(e);
			});
			child.on("close", (code) => {
				cleanup();
				if (opts.signal?.aborted) {
					rej(new Error("aborted"));
					return;
				}
				if (timedOut) {
					rej(new Error(`timeout:${timeout}`));
					return;
				}
				res({ out: Buffer.concat(out), err: Buffer.concat(err), code });
			});

			if (opts.signal) {
				if (opts.signal.aborted) onAbort();
				else opts.signal.addEventListener("abort", onAbort, { once: true });
			}
			if (opts.stdin !== undefined) child.stdin!.write(opts.stdin);
			child.stdin!.end();
		},
	);
}

async function sshOk(
	remote: string,
	cmd: string,
	opts: ExecOptions = {},
): Promise<Buffer> {
	const { out, err, code } = await sshExec(remote, cmd, opts);
	if (code !== 0)
		throw new Error(
			`SSH ${code}: ${(err.toString() || out.toString()).trim()}`,
		);
	return out;
}

function normalizeTarget(arg: string, profiles: Profile[]): Profile {
	const t = arg.trim();
	const found = profiles.find((p) => p.name === t);
	if (found) return found;
	const i = t.indexOf(":");
	return i > 0
		? { name: t, remote: t.slice(0, i), cwd: t.slice(i + 1) }
		: { name: t, remote: t };
}

// ── remote ops ─────────────────────────────────────────────────────────
const IMAGE_MIMES: Record<string, string> = {
	".jpg": "image/jpeg",
	".jpeg": "image/jpeg",
	".png": "image/png",
	".gif": "image/gif",
	".webp": "image/webp",
};

function remoteMime(path: string): string | null {
	return IMAGE_MIMES[extname(path).toLowerCase()] ?? null;
}

function remoteRead(t: Target): ReadOperations {
	return {
		readFile: (p) => sshOk(t.remote, `cat ${shellQuote(p)}`),
		access: (p) => sshOk(t.remote, `test -r ${shellQuote(p)}`).then(() => {}),
		detectImageMimeType: remoteMime,
	};
}

function remoteWrite(t: Target): WriteOperations {
	return {
		writeFile: (p, c) =>
			sshOk(t.remote, `cat > ${shellQuote(p)}`, { stdin: c }),
		mkdir: (d) => sshOk(t.remote, `mkdir -p ${shellQuote(d)}`).then(() => {}),
	};
}

function remoteEdit(t: Target): EditOperations {
	return {
		...remoteRead(t),
		...remoteWrite(t),
		access: (p) =>
			sshOk(
				t.remote,
				`test -r ${shellQuote(p)} && test -w ${shellQuote(p)}`,
			).then(() => {}),
	};
}

function remoteBash(t: Target): BashOperations {
	return {
		exec: (script, cwd, { onData, signal, timeout }) =>
			sshExec(t.remote, `exec "\${SHELL:-/bin/sh}" -lc 'exec bash -se'`, {
				stdin: `cd ${shellQuote(cwd)}\n${script}\n`,
				signal,
				timeoutSeconds: timeout,
				onStdout: onData,
				onStderr: onData,
			}).then(({ code }) => ({ exitCode: code })),
	};
}

// ── helpers (function-scoped to access pi) ─────────────────────────────
function makeHelpers(pi: ExtensionAPI) {
	function assertTarget(): asserts target is Target {
		if (!target) throw new Error("SSH mode off. Use /ssh <host> first.");
	}
	function enableTools() {
		const next = new Set(pi.getActiveTools());
		for (const n of TOOL_NAMES) next.add(n);
		pi.setActiveTools(Array.from(next));
	}
	function disableTools() {
		pi.setActiveTools(pi.getActiveTools().filter((n) => !TOOL_SET.has(n)));
	}
	function renderCall(name: string, getPath: (args: unknown) => string) {
		return (args: unknown, theme: { fg: (c: string, s: string) => string }) =>
			new Text(
				`${theme.fg("toolTitle", theme.bold(name))} ${theme.fg("accent", getPath(args))} ${theme.fg("muted", `[${target?.name ?? "off"}]`)}`,
				0,
				0,
			);
	}
	return { assertTarget, enableTools, disableTools, renderCall };
}

// ── extension ───────────────────────────────────────────────────────────
let target: Target | null = null;

const readBase = createReadToolDefinition("/");
const writeBase = createWriteToolDefinition("/");
const editBase = createEditToolDefinition("/");
const bashBase = createBashToolDefinition("/");

export default function (pi: ExtensionAPI) {
	const { assertTarget, enableTools, disableTools, renderCall } =
		makeHelpers(pi);

	async function activate(profile: Profile) {
		const out = await sshOk(profile.remote, "pwd");
		target = {
			name: profile.name,
			remote: profile.remote,
			cwd: out.toString().trim(),
		};
		enableTools();
		pi.ui?.setStatus(
			STATUS_KEY,
			pi.ui.theme.fg("accent", `SSH ${target.name}:${target.cwd}`),
		);
		pi.ui?.notify(`SSH on: ${target.name} (${target.cwd})`, "info");
	}

	function deactivate(): boolean {
		if (!target) return false;
		target = null;
		disableTools();
		pi.ui?.setStatus(STATUS_KEY, undefined);
		pi.ui?.notify("SSH off", "info");
		return true;
	}

	// tools
	const toolDefs = [
		["ssh_read", remoteRead, createReadToolDefinition],
		["ssh_write", remoteWrite, createWriteToolDefinition],
		["ssh_edit", remoteEdit, createEditToolDefinition],
	] as const;
	for (const [name, ops, mkDef] of toolDefs) {
		const base = mkDef("/");
		pi.registerTool({
			name,
			label: name,
			description: `${name} on active SSH host.`,
			promptSnippet: `${name} on remote`,
			parameters: base.parameters,
			...(name === "ssh_edit"
				? { prepareArguments: editBase.prepareArguments }
				: {}),
			execute(id, params, signal, onUpdate) {
				assertTarget();
				return mkDef(target!.cwd, { operations: ops(target!) }).execute(
					id,
					params,
					signal,
					onUpdate,
				);
			},
			renderCall: renderCall(name, (a) => (a?.path as string) ?? "..."),
			renderResult: base.renderResult,
		});
	}

	// ssh_bash has special renderCall with command instead of path
	pi.registerTool({
		name: "ssh_bash",
		label: "ssh_bash",
		description: "Execute commands on active SSH host.",
		promptSnippet: "Run bash on remote SSH host",
		parameters: bashBase.parameters,
		execute(id, params, signal, onUpdate) {
			assertTarget();
			return createBashToolDefinition(target!.cwd, {
				operations: remoteBash(target!),
			}).execute(id, params, signal, onUpdate);
		},
		renderCall(args, theme, ctx) {
			const cmd = (args?.command as string) ?? "...";
			const text =
				(ctx.lastComponent as Text | undefined) ?? new Text("", 0, 0);
			text.setText(
				`${theme.fg("toolTitle", theme.bold("ssh_bash"))} ${theme.fg("accent", cmd)} ${theme.fg("muted", `[${target?.name ?? "off"}]`)}`,
			);
			return text;
		},
		renderResult: bashBase.renderResult,
	});

	// command
	pi.registerCommand("ssh", {
		description: "SSH mode: /ssh, /ssh off, /ssh status, /ssh <host>[:/path]",
		getArgumentCompletions(prefix) {
			return parseSshConfig()
				.filter((p) => p.name.startsWith(prefix))
				.map((p) => ({ value: p.name, label: p.name }));
		},
		handler: async (args, ctx) => {
			await ctx.waitForIdle();
			const input = args.trim();
			const profiles = parseSshConfig();

			if (input === "status") {
				ctx.ui.notify(
					target
						? `SSH: ${target.name} (${target.remote}:${target.cwd})`
						: "SSH off",
					"info",
				);
				return;
			}
			if (input === "off") {
				deactivate();
				return;
			}

			if (!input) {
				if (!profiles.length) {
					ctx.ui.notify("No hosts in ~/.ssh/config", "warning");
					return;
				}
				const picked = await ctx.ui.select("SSH target", [
					...(target ? ["off"] : []),
					...profiles.map((p) => p.name),
				]);
				if (!picked) return;
				if (picked === "off") {
					deactivate();
					return;
				}
				await activate(normalizeTarget(picked, profiles));
				return;
			}

			await activate(normalizeTarget(input, profiles));
		},
	});

	pi.on("session_start", (_e, ctx) => {
		target = null;
		disableTools();
		ctx.ui.setStatus(STATUS_KEY, undefined);
	});

	pi.on("before_agent_start", (e) => {
		if (!target) return;
		return {
			systemPrompt:
				e.systemPrompt +
				`\n\nSSH mode: ${target.remote} @ ${target.cwd}\nUse ssh_read/write/edit/bash for remote work.`,
		};
	});
}