repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ctx/index.ts

Raw
File outline
const DEFAULT_THRESHOLD = 20_000;

function limit(): number {
	const n = Number(
		process.env.PI_CTX_COMPACT_THRESHOLD ??
			process.env.PI_CTX_READ_OUTPUT_THRESHOLD,
	);
	return Number.isFinite(n) && n >= 0 ? n : DEFAULT_THRESHOLD;
}

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

export function compactRead(text: string): string {
	const lines = text.split(/\r?\n/);
	return [
		lines.slice(0, 8).join("\n"),
		`[ctx compacted read: ${Math.max(0, lines.length - 40)} lines omitted]`,
		"Use grep or read offset/limit for hidden target text before editing.",
		lines.slice(-32).join("\n"),
	].join("\n");
}

export function handleToolResult(event: any) {
	if (
		event?.toolName !== "read" ||
		event.isError ||
		event.input?.limit !== undefined ||
		event.input?.l !== undefined
	)
		return;
	const text = textOf(event.content);
	if (Buffer.byteLength(text, "utf8") <= limit()) return;
	return {
		content: [{ type: "text", text: compactRead(text) }],
		details: { ...(event.details ?? {}), ctxCompactedRead: true },
		isError: false,
	};
}

export const __test = { compactRead, handleToolResult };
export default (pi: any) => pi.on("tool_result", handleToolResult);