repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/dbg.ts

Raw
File outline
/**
 * Debug mode extension for pi.
 *
 * Registers:
 *   --dbg flag   — enable debug mode from CLI
 *   /dbg command — toggle debug mode, open/clear logs
 *
 * Logs are written as JSONL to ~/.pi/agent/logs/dbg.log.
 * Rotation: 64MB primary → zstd compressed archive (single .zst file).
 *
 * Usage:
 *   pi --dbg              # start with debug on
 *   /dbg                  # toggle on/off
 *   /dbg on|off           # enable/disable
 *   /dbg open             # open log file in $EDITOR
 *   /dbg status           # show current state
 *   /dbg clear            # truncate log + archive
 */

import type { ExtensionAPI, AutocompleteItem } from "@mariozechner/pi-coding-agent";
import {
	isDbgEnabled,
	setDbgSink,
	setDbgEnabled,
	dbg,
	type DbgLogEntry,
} from "../lib/dbg.ts";
import {
	updateSettings,
	type DbgSettings,
} from "../lib/settings.ts";
import {
	existsSync,
	openSync,
	writeSync,
	closeSync,
	statSync,
	unlinkSync,
	readFileSync,
	appendFileSync,
	mkdirSync,
	renameSync,
} from "node:fs";
import { join } from "node:path";
import { getAgentDir } from "@mariozechner/pi-coding-agent";
import { execSync } from "node:child_process";

// ── Constants ────────────────────────────────────────────────────────────

const MAX_LOG_BYTES = 64 * 1024 * 1024; // 64 MiB

// ── Log file management ──────────────────────────────────────────────────

let _logDir: string;
let _logPath: string;
let _archivePath: string;
let _fd: number | null = null;
let _rotating = false;

function ensureLogDir(): void {
	_logDir = join(getAgentDir(), "logs");
	_logPath = join(_logDir, "dbg.log");
	_archivePath = join(_logDir, "dbg.log.zst");
	mkdirSync(_logDir, { recursive: true });
}

function openLogFile(): void {
	try {
		_fd = openSync(_logPath, "a");
	} catch {
		_fd = null;
	}
}

function closeLogFile(): void {
	if (_fd !== null) {
		try { closeSync(_fd); } catch {}
		_fd = null;
	}
}

function writeEntry(entry: DbgLogEntry): void {
	if (_fd === null) return;
	try {
		const line = JSON.stringify(entry) + "\n";
		writeSync(_fd, line, "utf-8");
	} catch {
		try { closeSync(_fd!); } catch {}
		_fd = null;
		return;
	}

	if (!_rotating && _fd !== null) {
		try {
			if (statSync(_logPath).size >= MAX_LOG_BYTES) {
				rotateLog();
			}
		} catch {}
	}
}

function rotateLog(): void {
	_rotating = true;
	closeLogFile();
	const tmpCompressed = _archivePath + ".rotating";

	try {
		execSync(`zstd -f --quiet "${_logPath}" -o "${tmpCompressed}"`, {
			stdio: "ignore",
			timeout: 30_000,
		});

		if (existsSync(_archivePath)) {
			const newFrame = readFileSync(tmpCompressed);
			appendFileSync(_archivePath, newFrame);
			unlinkSync(tmpCompressed);
		} else {
			renameSync(tmpCompressed, _archivePath);
		}

		_fd = openSync(_logPath, "w");
		closeSync(_fd);
		_fd = openSync(_logPath, "a");
	} catch {
		try { unlinkSync(tmpCompressed); } catch {}
		openLogFile();
	}

	_rotating = false;
}

function clearLogs(): void {
	closeLogFile();
	try { unlinkSync(_logPath); } catch {}
	try { unlinkSync(_archivePath); } catch {}
	if (isDbgEnabled()) openLogFile();
}

function openInEditor(ctx: { ui: { notify: (msg: string, severity: string) => void } }): void {
	const editor = process.env.VISUAL;
	if (!editor) {
		ctx.ui.notify("Set $VISUAL to your editor, then /dbg open", "warning");
		return;
	}
	execSync(`${editor} "${_logPath}"`, { stdio: "inherit" });
}

// ── Settings ─────────────────────────────────────────────────────────────

function apply(enabled: boolean): void {
	updateSettings<DbgSettings>("dbg", { enabled });
	setDbgEnabled(enabled);
	if (enabled && !_fd) openLogFile();
	if (!enabled) closeLogFile();
}

// ── Extension ────────────────────────────────────────────────────────────

export default function (pi: ExtensionAPI) {

	pi.registerFlag("dbg", {
		description: "Enable debug mode for extensions",
		type: "boolean",
		default: false,
	});

	ensureLogDir();

	if (pi.getFlag("dbg") || process.env.PI_DBG === "1") {
		apply(true);
	}

	setDbgSink((entry) => {
		if (_fd === null && isDbgEnabled()) openLogFile();
		writeEntry(entry);
	});

	pi.on("session_start", () => {
		if (isDbgEnabled()) {
			if (!_fd) openLogFile();
			dbg("debug session started");
		}
	});

	pi.on("session_shutdown", () => {
		closeLogFile();
	});

	pi.registerCommand("dbg", {
		description: "Debug mode: /dbg on|off|status|open|clear",
		getArgumentCompletions(text: string): AutocompleteItem[] {
			const opts = ["on", "off", "status", "open", "clear"];
			return opts.filter(o => o.startsWith(text)).map(o => ({ value: o, label: o }));
		},
		handler: async (args, ctx) => {
			const arg = args.trim().toLowerCase();
			const current = isDbgEnabled();

			switch (arg) {
				case "":
				case "toggle": {
					apply(!current);
					ctx.ui.notify(`Debug ${!current ? "ON" : "OFF"}`, !current ? "warning" : "info");
					break;
				}

				case "on": {
					if (current) {
						ctx.ui.notify("Debug already ON", "info");
						return;
					}
					apply(true);
					ctx.ui.notify("Debug ON", "warning");
					break;
				}

				case "off": {
					if (!current) {
						ctx.ui.notify("Debug already OFF", "info");
						return;
					}
					apply(false);
					ctx.ui.notify("Debug OFF", "info");
					break;
				}

				case "status": {
					let msg = `Debug: ${current ? "ON" : "OFF"}`;
					try {
						if (existsSync(_logPath)) {
							msg += ` | Log: ${(statSync(_logPath).size / 1024).toFixed(1)}KB`;
						}
						if (existsSync(_archivePath)) {
							msg += ` | Archive: ${(statSync(_archivePath).size / 1024).toFixed(1)}KB`;
						}
					} catch {}
					ctx.ui.notify(msg, current ? "warning" : "info");
					break;
				}

				case "open": {
					if (!existsSync(_logPath)) {
						ctx.ui.notify("No log file yet", "info");
						return;
					}
					openInEditor(ctx);
					break;
				}

				case "clear": {
					clearLogs();
					ctx.ui.notify("Debug logs cleared", "info");
					break;
				}

				default: {
					ctx.ui.notify(`Unknown: "${arg}". Use: on, off, status, open, clear`, "warning");
					break;
				}
			}
		},
	});
}