Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/autopsy/details.ts

Raw
import { setImmediate } from "node:timers/promises";
import type { EntryDetailEvent } from "./src/types.ts";

const CHUNK = 8 * 1024;
const IMAGE_DATA = "[image data: available on demand]";

type RecordValue = Record<string, unknown>;

function object(value: unknown): RecordValue | undefined {
	return value !== null && typeof value === "object"
		? (value as RecordValue)
		: undefined;
}

// Stored JSON has data properties only. Never execute accessors or toJSON.
function property(value: RecordValue, key: string): unknown {
	const descriptor = Object.getOwnPropertyDescriptor(value, key);
	if (!descriptor) return undefined;
	if (!("value" in descriptor)) throw new Error("Unsupported accessor");
	return descriptor.value;
}

function* segments(value: string): Generator<string> {
	for (let start = 0; start < value.length; ) {
		let end = Math.min(start + CHUNK, value.length);
		const last = value.charCodeAt(end - 1);
		if (end < value.length && last >= 0xd800 && last <= 0xdbff) end--;
		yield value.slice(start, end);
		start = end;
	}
}

function* quoted(value: string): Generator<string> {
	yield '"';
	for (const part of segments(value)) yield JSON.stringify(part).slice(1, -1);
	yield '"';
}

function* members(value: RecordValue): Generator<[string, unknown]> {
	for (const key in value) {
		if (!Object.hasOwn(value, key)) continue;
		const item = property(value, key);
		if (item !== undefined) yield [key, item];
	}
}

type Frame =
	| { type: "value"; value: unknown; depth: number }
	| { type: "tokens"; tokens: Generator<string> }
	| {
			type: "container";
			value: RecordValue;
			iterator: Generator<[string, unknown]>;
			array: boolean;
			first: boolean;
			depth: number;
	  };

function* elements(value: unknown[]): Generator<[string, unknown]> {
	for (let index = 0; index < value.length; index++) {
		yield [
			String(index),
			property(value as unknown as RecordValue, String(index)) ?? null,
		];
	}
}

// Iterative traversal permits arbitrary stored depth without a JS call-stack limit.
function* jsonTokens(root: unknown): Generator<string> {
	const active = new WeakSet<object>();
	const stack: Frame[] = [{ type: "value", value: root, depth: 0 }];
	const indent = (depth: number): string => "  ".repeat(Math.min(depth, 32));
	while (stack.length) {
		const frame = stack.pop();
		if (!frame) break;
		if (frame.type === "tokens") {
			const next = frame.tokens.next();
			if (!next.done) {
				stack.push(frame);
				yield next.value;
			}
			continue;
		}
		if (frame.type === "container") {
			const next = frame.iterator.next();
			if (next.done) {
				active.delete(frame.value);
				if (!frame.first) yield `\n${indent(frame.depth)}`;
				yield frame.array ? "]" : "}";
				continue;
			}
			if (!frame.first) yield ",";
			yield `\n${indent(frame.depth + 1)}`;
			frame.first = false;
			const [key, value] = next.value;
			stack.push(frame);
			stack.push({
				type: "value",
				depth: frame.depth + 1,
				value:
					!frame.array &&
					key === "data" &&
					property(frame.value, "type") === "image"
						? IMAGE_DATA
						: value,
			});
			if (!frame.array) {
				stack.push({
					type: "tokens",
					tokens: (function* () {
						yield* quoted(key);
						yield ": ";
					})(),
				});
			}
			continue;
		}
		const value = frame.value;
		if (typeof value === "string") {
			stack.push({ type: "tokens", tokens: quoted(value) });
		} else if (value === null || typeof value === "boolean") {
			yield String(value);
		} else if (typeof value === "number") {
			yield Number.isFinite(value) ? String(value) : "null";
		} else if (object(value)) {
			const record = value as RecordValue;
			if (active.has(record)) throw new Error("Cyclic entry");
			const array = Array.isArray(value);
			const prototype = Object.getPrototypeOf(value);
			if (!array && prototype !== Object.prototype && prototype !== null)
				throw new Error("Unsupported object");
			active.add(record);
			stack.push({
				type: "container",
				value: record,
				iterator: array ? elements(value) : members(record),
				array,
				first: true,
				depth: frame.depth,
			});
			yield array ? "[" : "{";
		} else {
			throw new Error("Unsupported value");
		}
	}
}

function* textEvents(text: string): Generator<EntryDetailEvent> {
	for (const part of segments(text)) yield { type: "text", text: part };
}

function* jsonEvents(value: unknown): Generator<EntryDetailEvent> {
	for (const token of jsonTokens(value)) yield* textEvents(token);
}

function* sectionEvents(message: RecordValue): Generator<EntryDetailEvent> {
	const sections = object(property(message, "sections"));
	if (!sections) return;
	for (const [name, value] of members(sections)) {
		yield* textEvents("\n\n[Section ");
		yield* textEvents(name);
		yield* textEvents("]\n");
		if (typeof value === "string") yield* textEvents(value);
		else if (value === null) yield* textEvents("[removed]");
		else yield* jsonEvents(value);
	}
}

function* readable(entry: unknown): Generator<EntryDetailEvent> {
	const record = object(entry);
	if (!record) return yield* jsonEvents(entry);
	const message = object(property(record, "message")) ?? record;
	const content = property(message, "content");
	if (typeof content === "string") {
		yield* textEvents(content);
		yield* sectionEvents(message);
		return;
	}
	if (Array.isArray(content)) {
		for (let index = 0; index < content.length; index++) {
			if (index) yield* textEvents("\n\n");
			const part = property(content as unknown as RecordValue, String(index));
			const block = object(part);
			const type = block && property(block, "type");
			if (block && type === "image") {
				const mime = property(block, "mimeType");
				yield {
					type: "image",
					index,
					mimeType:
						typeof mime === "string"
							? mime.slice(0, 256)
							: "application/octet-stream",
				};
			} else if (block && (type === "text" || type === "thinking")) {
				const text = property(block, type === "text" ? "text" : "thinking");
				if (type === "thinking") yield* textEvents("[Thinking]\n");
				if (typeof text === "string") yield* textEvents(text);
				else if (type === "thinking") yield* textEvents("[redacted]");
			} else if (block && (type === "toolCall" || type === "tool_call")) {
				yield* textEvents("[Tool: ");
				const name = property(block, "name");
				if (typeof name === "string") yield* textEvents(name);
				yield* textEvents("]\n");
				yield* jsonEvents(property(block, "arguments"));
			} else yield* jsonEvents(part);
		}
		yield* sectionEvents(message);
		return;
	}
	const command = property(message, "command");
	if (typeof command === "string") {
		yield* textEvents(command);
		yield* textEvents("\n");
		const output = property(message, "output");
		if (typeof output === "string") yield* textEvents(output);
		return;
	}
	const summary = property(record, "summary");
	if (typeof summary === "string") yield* textEvents(summary);
	else yield* jsonEvents(entry);
}

export async function* entryDetailEvents(
	entry: unknown,
	view: "text" | "json",
): AsyncGenerator<EntryDetailEvent> {
	try {
		let work = 0;
		let pending: string[] = [];
		let length = 0;
		for (const event of view === "json" ? jsonEvents(entry) : readable(entry)) {
			if (event.type === "text") {
				if (length && length + event.text.length > CHUNK) {
					yield { type: "text", text: pending.join("") };
					pending = [];
					length = 0;
				}
				pending.push(event.text);
				length += event.text.length;
			} else {
				if (length) yield { type: "text", text: pending.join("") };
				pending = [];
				length = 0;
				yield event;
			}
			if (++work % 64 === 0) await setImmediate();
		}
		if (length) yield { type: "text", text: pending.join("") };
		yield { type: "end" };
	} catch {
		yield { type: "error", message: "Could not read complete entry content." };
	}
}