repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/ctx/index.ts

Raw
File outline
import { spawn } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, isAbsolute, join, resolve } from "node:path";
import { Type } from "typebox";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";

const INTENT_SEARCH_THRESHOLD = 5_000;
const LARGE_OUTPUT_THRESHOLD = 102_400;
const MAX_RETURN_BYTES = 12_000;
const MAX_CHUNK_BYTES = 16_000;
const MAX_CHUNK_LINES = 200;
const ERROR_QUERY = "errors failures exceptions panic traceback assertion failed error";

type TextContent = { type: "text"; text: string };
type ToolPatch = { content: TextContent[]; details?: Record<string, unknown>; isError?: boolean };

export type CtxToolParams =
	| { op: "run-sh"; script: string; query?: string | string[]; timeoutMs?: number }
	| { op: "run-js"; code: string; query?: string | string[]; timeoutMs?: number }
	| { op: "run-py"; code: string; query?: string | string[]; timeoutMs?: number }
	| { op: "file-sh"; path: string; script: string; query?: string | string[]; timeoutMs?: number }
	| { op: "file-js"; path: string; code: string; query?: string | string[]; timeoutMs?: number }
	| { op: "file-py"; path: string; code: string; query?: string | string[]; timeoutMs?: number }
	| { op: "search"; query: string | string[]; source?: string; limit?: number };

interface SourceRow {
	id: number;
	kind: string;
	label: string;
	bytes: number;
	created_at: string;
}

interface SearchRow {
	source_id: number;
	title: string;
	text: string;
	label: string;
	kind: string;
	score: number;
}

interface RunResult {
	stdout: string;
	stderr: string;
	exitCode: number | null;
	timedOut: boolean;
}

function byteLen(text: string): number {
	return Buffer.byteLength(text, "utf8");
}

function truncateBytes(text: string, max = MAX_RETURN_BYTES): string {
	if (byteLen(text) <= max) return text;
	let out = "";
	let used = 0;
	for (const ch of text) {
		const n = byteLen(ch);
		if (used + n > max) break;
		out += ch;
		used += n;
	}
	return `${out}\n… truncated to ${max}B`;
}

function textOf(content: unknown): string {
	if (!Array.isArray(content)) return String(content ?? "");
	return content.map((c: any) => c?.type === "text" && typeof c.text === "string" ? c.text : "").join("\n");
}

function queryTerms(query: string): string[] {
	return [...query.matchAll(/[\p{L}\p{N}_]{2,}/gu)]
		.map(match => match[0].toLowerCase())
		.filter(term => !["and", "or", "not", "near"].includes(term));
}

function snippetForQuery(text: string, query: string, max = 2500): string {
	if (byteLen(text) <= max) return text.trim();
	const lower = text.toLowerCase();
	let pos = -1;
	for (const term of queryTerms(query)) {
		const next = lower.indexOf(term);
		if (next >= 0 && (pos < 0 || next < pos)) pos = next;
	}
	if (pos < 0) return truncateBytes(text.trim(), max);
	let start = Math.max(0, pos - Math.floor(max / 3));
	const newline = text.lastIndexOf("\n", pos);
	if (newline >= 0 && newline >= start - 500) start = newline + 1;
	let snippet = text.slice(start);
	if (start > 0) snippet = `…\n${snippet}`;
	return truncateBytes(snippet.trim(), max);
}

function shortHash(text: string): string {
	return createHash("sha256").update(text).digest("hex").slice(0, 8);
}

export function defaultDbPath(cwd = process.cwd(), ctx?: any): string {
	if (process.env.PI_CTX_DB_PATH) return process.env.PI_CTX_DB_PATH;
	const sessionFile = ctx?.sessionManager?.getSessionFile?.()
		?? ctx?.sessionManager?.sessionFile
		?? ctx?.sessionFile;
	const managerDir = ctx?.sessionManager?.getSessionDir?.()
		?? ctx?.sessionManager?.sessionDir;
	const sessionDir = typeof sessionFile === "string" && sessionFile
		? dirname(sessionFile)
		: typeof managerDir === "string" && managerDir
			? managerDir
			: process.env.PI_CODING_AGENT_SESSION_DIR;
	if (typeof sessionDir !== "string" || !sessionDir) {
		throw new Error("ctx requires a Pi session dir; use PI_CTX_DB_PATH for tests/no-session runs");
	}
	const base = join(sessionDir, "ctx");
	mkdirSync(base, { recursive: true });
	const hash = createHash("sha256").update(resolve(cwd)).digest("hex").slice(0, 16);
	return join(base, `${hash}.db`);
}

function jsonText(value: unknown): string {
	try { return JSON.stringify(value); } catch { return String(value); }
}

function normalizeQueries(query: string | string[] | undefined): string[] {
	if (Array.isArray(query)) return query.map(q => q.trim()).filter(Boolean);
	if (typeof query === "string" && query.trim()) return [query.trim()];
	return [];
}

function sourceFilter(source: string | undefined): string | undefined {
	const s = source?.trim();
	return s ? `%${s}%` : undefined;
}

function chunkText(text: string): Array<{ title: string; text: string }> {
	const lines = text.split(/\r?\n/);
	const chunks: Array<{ title: string; text: string }> = [];
	let current: string[] = [];
	let currentBytes = 0;
	let start = 1;
	const flush = (end: number) => {
		if (current.length === 0) return;
		chunks.push({ title: `lines ${start}-${end}`, text: current.join("\n") });
		current = [];
		currentBytes = 0;
		start = end + 1;
	};
	for (let i = 0; i < lines.length; i++) {
		const line = lines[i] ?? "";
		const n = byteLen(line) + 1;
		if (current.length > 0 && (current.length >= MAX_CHUNK_LINES || currentBytes + n > MAX_CHUNK_BYTES)) {
			flush(i);
		}
		current.push(line);
		currentBytes += n;
	}
	flush(lines.length);
	return chunks.length ? chunks : [{ title: "output", text }];
}

export class CtxStore {
	#db: any;
	readonly dbPath: string;

	constructor(dbPath = defaultDbPath()) {
		this.dbPath = dbPath;
		mkdirSync(dirname(dbPath), { recursive: true });
		const { Database } = require("bun:sqlite") as typeof import("bun:sqlite");
		this.#db = new Database(dbPath);
		this.#db.exec("PRAGMA journal_mode=WAL");
		this.#db.exec("PRAGMA busy_timeout=30000");
		this.#db.exec(`
			CREATE TABLE IF NOT EXISTS sources (
				id INTEGER PRIMARY KEY AUTOINCREMENT,
				kind TEXT NOT NULL,
				label TEXT NOT NULL,
				bytes INTEGER NOT NULL,
				metadata TEXT,
				created_at TEXT NOT NULL DEFAULT (datetime('now'))
			);
			CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
				source_id UNINDEXED,
				title,
				text,
				label UNINDEXED,
				kind UNINDEXED,
				tokenize='porter unicode61'
			);
		`);
	}

	indexText(input: { kind: string; label: string; text: string; metadata?: unknown }): { sourceId: number; chunkCount: number; bytes: number; label: string } {
		const bytes = byteLen(input.text);
		const source = this.#db.prepare("INSERT INTO sources(kind, label, bytes, metadata) VALUES (?, ?, ?, ?)")
			.run(input.kind, input.label, bytes, input.metadata === undefined ? null : jsonText(input.metadata));
		const sourceId = Number(source.lastInsertRowid);
		const insert = this.#db.prepare("INSERT INTO chunks_fts(source_id, title, text, label, kind) VALUES (?, ?, ?, ?, ?)");
		const chunks = chunkText(input.text);
		const tx = this.#db.transaction(() => {
			for (const chunk of chunks) insert.run(sourceId, chunk.title, chunk.text, input.label, input.kind);
		});
		tx();
		return { sourceId, chunkCount: chunks.length, bytes, label: input.label };
	}

	search(queries: string[], opts: { source?: string; limit?: number } = {}): string {
		const clean = queries.map(q => q.trim()).filter(Boolean);
		if (clean.length === 0) return "ctx: empty query";
		const limit = Math.max(1, Math.min(opts.limit ?? 3, 10));
		const src = sourceFilter(opts.source);
		const lines: string[] = [];
		for (const q of clean) {
			const rows = src
				? this.#db.prepare("SELECT source_id, title, text, label, kind, bm25(chunks_fts) AS score FROM chunks_fts WHERE chunks_fts MATCH ? AND label LIKE ? ORDER BY score LIMIT ?").all(q, src, limit) as SearchRow[]
				: this.#db.prepare("SELECT source_id, title, text, label, kind, bm25(chunks_fts) AS score FROM chunks_fts WHERE chunks_fts MATCH ? ORDER BY score LIMIT ?").all(q, limit) as SearchRow[];
			lines.push(`## ${q}`);
			if (rows.length === 0) {
				lines.push("no matches");
				continue;
			}
			for (const row of rows) {
				lines.push(`### ${row.label} · ${row.title}`);
				lines.push(snippetForQuery(row.text, q, 2500));
			}
		}
		return lines.join("\n");
	}

	intentSearch(indexed: { sourceId: number; chunkCount: number; bytes: number; label: string }, query: string, maxResults = 5): string {
		const rows = this.#db.prepare("SELECT source_id, title, text, label, kind, bm25(chunks_fts) AS score FROM chunks_fts WHERE chunks_fts MATCH ? AND source_id = ? ORDER BY score LIMIT ?")
			.all(query, indexed.sourceId, maxResults) as SearchRow[];
		const kb = (indexed.bytes / 1024).toFixed(1);
		if (rows.length === 0) {
			return [
				`ctx:stored ${indexed.label} (${kb}KB, ${indexed.chunkCount} chunks).`,
				`No sections matched "${query}".`,
				`Use ctx search with source "${indexed.label}".`,
			].join("\n");
		}
		const lines = [
			`ctx:stored ${indexed.label} (${kb}KB, ${indexed.chunkCount} chunks).`,
			`${rows.length} sections matched "${query}":`,
			"",
		];
		for (const row of rows) {
			const preview = row.text.split(/\r?\n/).find(Boolean)?.slice(0, 160) ?? "";
			lines.push(`- ${row.title}: ${preview}`);
		}
		lines.push("");
		lines.push(`Use ctx search with source "${indexed.label}" for details.`);
		return lines.join("\n");
	}

	pointer(indexed: { chunkCount: number; bytes: number; label: string }): string {
		const kb = (indexed.bytes / 1024).toFixed(1);
		return `ctx:stored ${indexed.label} (${kb}KB, ${indexed.chunkCount} chunks).\nUse ctx search with source "${indexed.label}".`;
	}

	stats(): { sources: number; bytes: number; recent: SourceRow[] } {
		const row = this.#db.prepare("SELECT COUNT(*) AS sources, COALESCE(SUM(bytes), 0) AS bytes FROM sources").get() as { sources: number; bytes: number };
		const recent = this.#db.prepare("SELECT id, kind, label, bytes, created_at FROM sources ORDER BY id DESC LIMIT 8").all() as SourceRow[];
		return { sources: Number(row.sources), bytes: Number(row.bytes), recent };
	}

	formatStats(): string {
		const stats = this.stats();
		const lines = [`ctx: ${stats.sources} sources, ${(stats.bytes / 1024).toFixed(1)}KB stored`];
		if (stats.recent.length) {
			lines.push("recent:");
			for (const s of stats.recent) lines.push(`- ${s.label} ${s.kind} ${(s.bytes / 1024).toFixed(1)}KB`);
		}
		lines.push("usage: /ctx <query> | /ctx --purge");
		return lines.join("\n");
	}

	purge(): void {
		this.#db.exec("DELETE FROM chunks_fts; DELETE FROM sources;");
	}

	close(): void {
		this.#db.close();
	}
}

async function runProcess(command: string, args: string[], opts: { cwd: string; input?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number; signal?: AbortSignal }): Promise<RunResult> {
	return await new Promise((resolve) => {
		let stdout = "";
		let stderr = "";
		let settled = false;
		const child = spawn(command, args, {
			cwd: opts.cwd,
			env: opts.env ?? process.env,
			stdio: [opts.input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
			signal: opts.signal,
		});
		const finish = (result: RunResult) => {
			if (settled) return;
			settled = true;
			if (timer) clearTimeout(timer);
			resolve(result);
		};
		const timer = opts.timeoutMs && opts.timeoutMs > 0 ? setTimeout(() => {
			try { child.kill("SIGTERM"); } catch { /* noop */ }
			finish({ stdout, stderr, exitCode: null, timedOut: true });
		}, opts.timeoutMs) : undefined;
		child.stdout?.setEncoding("utf8");
		child.stderr?.setEncoding("utf8");
		child.stdout?.on("data", (chunk: string) => { stdout += chunk; });
		child.stderr?.on("data", (chunk: string) => { stderr += chunk; });
		child.on("error", (err) => finish({ stdout, stderr: stderr + String(err), exitCode: 1, timedOut: false }));
		child.on("close", (code) => finish({ stdout, stderr, exitCode: code, timedOut: false }));
		if (opts.input !== undefined && child.stdin) {
			child.stdin.end(opts.input);
		}
	});
}

async function withTempFile<T>(prefix: string, suffix: string, content: string, fn: (path: string) => Promise<T>): Promise<T> {
	const dir = await mkdtemp(join(tmpdir(), prefix));
	try {
		const file = join(dir, `script${suffix}`);
		await writeFile(file, content, "utf8");
		return await fn(file);
	} finally {
		await rm(dir, { recursive: true, force: true }).catch(() => {});
	}
}

function resultText(result: RunResult): { text: string; isError: boolean } {
	const isError = result.timedOut || (result.exitCode !== 0 && result.exitCode !== null);
	let text = result.stdout;
	if (result.stderr) text += (text ? "\n" : "") + result.stderr;
	if (result.timedOut) text += `\n(timed out)`;
	if (!text) text = "(no output)";
	return { text, isError };
}

function finalizeOutput(store: CtxStore, source: { kind: string; label: string; metadata?: unknown }, text: string, isError: boolean, query?: string | string[]): ToolPatch {
	const bytes = byteLen(text);
	const queries = normalizeQueries(query);
	if (queries.length && bytes > INTENT_SEARCH_THRESHOLD) {
		const indexed = store.indexText({ ...source, text });
		return { content: [{ type: "text", text: store.intentSearch(indexed, queries.join(" ")) }], isError };
	}
	if (isError && bytes > INTENT_SEARCH_THRESHOLD) {
		const indexed = store.indexText({ ...source, text });
		return { content: [{ type: "text", text: store.intentSearch(indexed, ERROR_QUERY) }], isError };
	}
	if (bytes > LARGE_OUTPUT_THRESHOLD) {
		const indexed = store.indexText({ ...source, text });
		return { content: [{ type: "text", text: store.pointer(indexed) }], isError };
	}
	return { content: [{ type: "text", text: truncateBytes(text) }], isError };
}

export async function executeCtxOperation(store: CtxStore, params: CtxToolParams, cwd: string, signal?: AbortSignal): Promise<ToolPatch> {
	const timeoutMs = "timeoutMs" in params ? params.timeoutMs : undefined;
	const query = "query" in params ? params.query : undefined;
	switch (params.op) {
		case "search": {
			return { content: [{ type: "text", text: store.search(normalizeQueries(params.query), { source: params.source, limit: params.limit }) }] };
		}
		case "run-sh": {
			const r = await runProcess("/bin/sh", ["-c", params.script], { cwd, timeoutMs, signal });
			const { text, isError } = resultText(r);
			return finalizeOutput(store, { kind: "run-sh", label: `run-sh:${shortHash(params.script)}`, metadata: { script: params.script } }, text, isError, query);
		}
		case "run-js": {
			return await withTempFile("pi-ctx-js-", ".js", params.code, async (file) => {
				const r = await runProcess("bun", [file], { cwd, timeoutMs, signal });
				const { text, isError } = resultText(r);
				return finalizeOutput(store, { kind: "run-js", label: `run-js:${shortHash(params.code)}`, metadata: { code: params.code } }, text, isError, query);
			});
		}
		case "run-py": {
			return await withTempFile("pi-ctx-py-", ".py", params.code, async (file) => {
				const r = await runProcess("python3", [file], { cwd, timeoutMs, signal });
				const { text, isError } = resultText(r);
				return finalizeOutput(store, { kind: "run-py", label: `run-py:${shortHash(params.code)}`, metadata: { code: params.code } }, text, isError, query);
			});
		}
		case "file-sh": {
			const path = isAbsolute(params.path) ? params.path : resolve(cwd, params.path);
			const r = await runProcess("/bin/sh", ["-c", params.script], { cwd, timeoutMs, signal, env: { ...process.env, CTX_FILE: path } });
			const { text, isError } = resultText(r);
			return finalizeOutput(store, { kind: "file-sh", label: `file-sh:${params.path}`, metadata: { path: params.path, script: params.script } }, text, isError, query);
		}
		case "file-js": {
			const path = isAbsolute(params.path) ? params.path : resolve(cwd, params.path);
			const wrapper = `const path = ${JSON.stringify(path)};\nconst text = await Bun.file(path).text();\n${params.code}\n`;
			return await withTempFile("pi-ctx-file-js-", ".js", wrapper, async (file) => {
				const r = await runProcess("bun", [file], { cwd, timeoutMs, signal });
				const { text, isError } = resultText(r);
				return finalizeOutput(store, { kind: "file-js", label: `file-js:${params.path}`, metadata: { path: params.path, code: params.code } }, text, isError, query);
			});
		}
		case "file-py": {
			const path = isAbsolute(params.path) ? params.path : resolve(cwd, params.path);
			const wrapper = `path = ${JSON.stringify(path)}\ntext = open(path, 'r', encoding='utf-8', errors='replace').read()\n${params.code}\n`;
			return await withTempFile("pi-ctx-file-py-", ".py", wrapper, async (file) => {
				const r = await runProcess("python3", [file], { cwd, timeoutMs, signal });
				const { text, isError } = resultText(r);
				return finalizeOutput(store, { kind: "file-py", label: `file-py:${params.path}`, metadata: { path: params.path, code: params.code } }, text, isError, query);
			});
		}
	}
}

export function handleBashToolResult(store: CtxStore, event: any): ToolPatch | undefined {
	if (event?.toolName !== "bash") return undefined;
	const visible = textOf(event.content);
	const fullPath = event.details?.fullOutputPath;
	let full = visible;
	if (typeof fullPath === "string") {
		try {
			if (existsSync(fullPath)) full = readFileSync(fullPath, "utf8");
		} catch (err) {
			return {
				content: [{ type: "text", text: `ctx:suppressed bash output; failed to read fullOutputPath (${err instanceof Error ? err.message : String(err)})` }],
				details: { ...(event.details ?? {}), ctxSuppressed: true },
				isError: event.isError,
			};
		}
	}
	const bytes = byteLen(full);
	if (!event.isError && bytes <= LARGE_OUTPUT_THRESHOLD) return undefined;
	if (event.isError && bytes <= INTENT_SEARCH_THRESHOLD) return undefined;
	try {
		const command = String(event.input?.command ?? "bash");
		const label = `${event.isError ? "bash-error" : "bash"}:${shortHash(command)}`;
		const indexed = store.indexText({ kind: event.isError ? "bash-error" : "bash", label, text: full, metadata: { command } });
		const text = event.isError ? store.intentSearch(indexed, ERROR_QUERY) : store.pointer(indexed);
		return {
			content: [{ type: "text", text }],
			details: { ...(event.details ?? {}), ctxStored: true, ctxSource: label },
			isError: event.isError,
		};
	} catch (err) {
		return {
			content: [{ type: "text", text: `ctx:suppressed ${bytes}B bash output; storage failed (${err instanceof Error ? err.message : String(err)})` }],
			details: { ...(event.details ?? {}), ctxSuppressed: true },
			isError: event.isError,
		};
	}
}

function makeStore(ctx?: any): CtxStore {
	const cwd = ctx?.cwd ?? process.cwd();
	return new CtxStore(defaultDbPath(cwd, ctx));
}

const Params = Type.Object({
	op: Type.Union([
		Type.Literal("run-sh"), Type.Literal("run-js"), Type.Literal("run-py"),
		Type.Literal("file-sh"), Type.Literal("file-js"), Type.Literal("file-py"), Type.Literal("search"),
	], { description: "Operation" }),
	script: Type.Optional(Type.String({ description: "Shell script for run-sh/file-sh" })),
	code: Type.Optional(Type.String({ description: "JS/Python code for run-js/run-py/file-js/file-py" })),
	path: Type.Optional(Type.String({ description: "File path for file-* ops" })),
	query: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())], { description: "Search query / intent" })),
	source: Type.Optional(Type.String({ description: "Source label substring for search" })),
	limit: Type.Optional(Type.Number({ description: "Search results per query" })),
	timeoutMs: Type.Optional(Type.Number({ description: "Timeout in ms" })),
});

function normalizeParams(raw: any): CtxToolParams {
	if (!raw || typeof raw !== "object") throw new Error("ctx params object required");
	switch (raw.op) {
		case "run-sh": if (typeof raw.script === "string") return raw; break;
		case "run-js": if (typeof raw.code === "string") return raw; break;
		case "run-py": if (typeof raw.code === "string") return raw; break;
		case "file-sh": if (typeof raw.path === "string" && typeof raw.script === "string") return raw; break;
		case "file-js": if (typeof raw.path === "string" && typeof raw.code === "string") return raw; break;
		case "file-py": if (typeof raw.path === "string" && typeof raw.code === "string") return raw; break;
		case "search": if (typeof raw.query === "string" || Array.isArray(raw.query)) return raw; break;
	}
	throw new Error("invalid ctx params for op");
}

export function registerCtxExtension(pi: Pick<ExtensionAPI, "registerTool" | "registerCommand" | "on">): void {
	pi.on("tool_result", (event: any, ctx: any) => {
		let store: CtxStore | undefined;
		try {
			store = makeStore(ctx);
			return handleBashToolResult(store, event);
		} catch (err) {
			const text = textOf(event?.content);
			const maybeLarge = event?.toolName === "bash" && (event?.details?.fullOutputPath || byteLen(text) > LARGE_OUTPUT_THRESHOLD);
			if (!maybeLarge) return undefined;
			return {
				content: [{ type: "text", text: `ctx:suppressed bash output; store unavailable (${err instanceof Error ? err.message : String(err)})` }],
				details: { ...(event.details ?? {}), ctxSuppressed: true },
				isError: event.isError,
			};
		} finally {
			store?.close();
		}
	});

	pi.registerTool({
		name: "ctx",
		label: "ctx",
		description: "Run JS/Py/sh analysis off-context; search stored large bash output.",
		promptSnippet: "Run JS/Py/sh analysis off-context; search stored large bash output.",
		promptGuidelines: [
			"Use ctx run-* for large-output analysis; print only findings.",
			"Use ctx file-* for large file analysis without reading whole files into context.",
			"Use ctx search when bash output was stored as ctx:stored.",
		],
		parameters: Params,
		async execute(_toolCallId: string, raw: unknown, signal?: AbortSignal, _onUpdate?: unknown, ctx?: any) {
			const store = makeStore(ctx);
			try {
				const params = normalizeParams(raw);
				return await executeCtxOperation(store, params, ctx?.cwd ?? process.cwd(), signal);
			} catch (err) {
				return { content: [{ type: "text", text: `ctx error: ${err instanceof Error ? err.message : String(err)}` }], details: {}, isError: true };
			} finally {
				store.close();
			}
		},
	});

	pi.registerCommand("ctx", {
		description: "ctx stats/search/purge",
		handler: async (args: unknown, ctx: any) => {
			const q = String(args ?? "").trim();
			const store = makeStore(ctx);
			try {
				if (q === "--purge") {
					if (ctx?.hasUI) {
						const ok = await ctx.ui.confirm("ctx purge", "Delete ctx index for this project?");
						if (!ok) return { text: "ctx purge cancelled" };
					}
					store.purge();
					return { text: "ctx purged" };
				}
				if (!q) return { text: store.formatStats() };
				return { text: store.search([q], { limit: 5 }) };
			} finally {
				store.close();
			}
		},
	});
}

export default function (pi: ExtensionAPI): void {
	registerCtxExtension(pi);
}