repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/klaus/src/debug.ts

Raw
File outline
import { appendFileSync, mkdirSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { SettingsManager } from "@earendil-works/pi-coding-agent";

type Debug = (event: string, details?: Record<string, unknown>) => void;

const unsafeFields = new Set([
	"content",
	"detail",
	"error",
	"failure",
	"message",
	"reason",
	"text",
]);

function diagnostic(value: unknown): { kind: string; length: number } {
	const text = String(value);
	return {
		kind: /No message found with message\.uuid of:/i.test(text)
			? "missing-resume-uuid"
			: /OAuth access token has been revoked/i.test(text)
				? "revoked-oauth"
				: "redacted",
		length: text.length,
	};
}

const settings = SettingsManager.create(
	process.cwd(),
).getGlobalSettings() as Record<string, unknown>;
const klaus = settings.klaus;
const enabled =
	typeof klaus === "object" &&
	klaus !== null &&
	(klaus as { debugLog?: unknown }).debugLog === true;
const path =
	process.env.KLAUS_DEBUG_LOG ??
	(enabled
		? join(
				process.env.XDG_CACHE_HOME || join(homedir(), ".cache"),
				"pi-ext",
				"klaus",
				"debug.ndjson",
			)
		: undefined);

/** Metadata-only Klaus tracing, enabled through global settings or KLAUS_DEBUG_LOG. */
let directoryReady = false;
export const dbg: Debug | undefined = path
	? (event, details = {}) => {
			try {
				if (!directoryReady) {
					mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
					directoryReady = true;
				}
				appendFileSync(
					path,
					`${JSON.stringify({
						timestamp: new Date().toISOString(),
						pid: process.pid,
						event,
						...Object.fromEntries(
							Object.entries(details).map(([key, value]) => [
								key,
								unsafeFields.has(key) ? diagnostic(value) : value,
							]),
						),
					})}\n`,
					{ encoding: "utf8", mode: 0o600 },
				);
			} catch {
				// Debug logging must never write into Pi's terminal UI.
			}
		}
	: undefined;