Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/bak/tool.ts

Raw
import { keyHint, type ToolDefinition } from "@earendil-works/pi-coding-agent";
import { Text } from "@earendil-works/pi-tui";
import {
	type Static,
	type TArray,
	type TBoolean,
	type TInteger,
	type TLiteral,
	type TNull,
	type TObject,
	type TOptional,
	type TString,
	type TUnion,
	Type,
} from "typebox";

const UUID = Type.String({
	pattern:
		"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$",
	minLength: 36,
	maxLength: 36,
});
const Limit = Type.Optional(
	Type.Integer({
		minimum: 1,
		maximum: 100,
		default: 20,
		description:
			"Maximum sessions or transcript fragments on this page; byte limit may return fewer.",
	}),
);
const Cursor = Type.String({ minLength: 1, maxLength: 512 });
const NullableText = Type.Union([Type.String({ maxLength: 512 }), Type.Null()]);

const RawRead: TObject<{
	action: TLiteral<"read">;
	view: TLiteral<"raw-jsonl">;
	hostId: TString;
	sessionId: TString;
	byteOffset: TOptional<TInteger>;
}> = Type.Object(
	{
		action: Type.Literal("read"),
		view: Type.Literal("raw-jsonl", {
			description:
				"All archived fields, including header, details, custom state, reasoning, tool arguments and media. Byte-paged JSONL text, not independently parseable entries; configured credentials are masked.",
		}),
		hostId: UUID,
		sessionId: UUID,
		byteOffset: Type.Optional(
			Type.Integer({
				minimum: 0,
				maximum: Number.MAX_SAFE_INTEGER - 128 * 1024,
				description:
					"Original-object UTF-8 byte offset; default 0. Use returned cursors to continue a pinned object version.",
			}),
		),
	},
	{ additionalProperties: false },
);

export const BakParameters: TUnion<
	[
		TObject<{
			action: TLiteral<"list">;
			hostId: TOptional<TString>;
			limit: TOptional<TInteger>;
		}>,
		TObject<{
			action: TLiteral<"search">;
			query: TString;
			hostId: TOptional<TString>;
			limit: TOptional<TInteger>;
		}>,
		TObject<{
			action: TLiteral<"read">;
			hostId: TString;
			sessionId: TString;
			limit: TOptional<TInteger>;
		}>,
		typeof RawRead,
		TObject<{
			action: TUnion<[TLiteral<"list">, TLiteral<"search">, TLiteral<"read">]>;
			cursor: TString;
			limit: TOptional<TInteger>;
		}>,
	]
> = Type.Union([
	Type.Object(
		{
			action: Type.Literal("list"),
			hostId: Type.Optional(UUID),
			limit: Limit,
		},
		{ additionalProperties: false },
	),
	Type.Object(
		{
			action: Type.Literal("search"),
			query: Type.String({
				minLength: 1,
				maxLength: 256,
				description:
					"Literal, case-insensitive substring of session name, cwd, session ID, host alias or host ID; not transcript search.",
			}),
			hostId: Type.Optional(UUID),
			limit: Limit,
		},
		{ additionalProperties: false },
	),
	Type.Object(
		{
			action: Type.Literal("read"),
			hostId: UUID,
			sessionId: UUID,
			limit: Limit,
		},
		{ additionalProperties: false },
	),
	RawRead,
	Type.Object(
		{
			action: Type.Union([
				Type.Literal("list"),
				Type.Literal("search"),
				Type.Literal("read"),
			]),
			cursor: Cursor,
			limit: Limit,
		},
		{ additionalProperties: false },
	),
]);
export type BakParams = Static<typeof BakParameters>;

const Session: TObject<{
	hostId: TString;
	hostAlias: TString;
	sessionId: TString;
	name: TUnion<[TString, TNull]>;
	cwd: TString;
	created: TString;
	metadataTruncated: TBoolean;
}> = Type.Object(
	{
		hostId: UUID,
		hostAlias: Type.String({ maxLength: 64 }),
		sessionId: UUID,
		name: NullableText,
		cwd: Type.String({ maxLength: 512 }),
		created: Type.String({ maxLength: 64 }),
		metadataTruncated: Type.Boolean(),
	},
	{ additionalProperties: false },
);
export type BakSession = Static<typeof Session>;

const Omitted: TObject<
	Record<
		| "thinking"
		| "images"
		| "system"
		| "customState"
		| "toolArguments"
		| "other",
		TInteger
	>
> = Type.Object(
	{
		thinking: Type.Integer({ minimum: 0 }),
		images: Type.Integer({ minimum: 0 }),
		system: Type.Integer({ minimum: 0 }),
		customState: Type.Integer({ minimum: 0 }),
		toolArguments: Type.Integer({ minimum: 0 }),
		other: Type.Integer({ minimum: 0 }),
	},
	{ additionalProperties: false },
);
export type BakOmitted = Static<typeof Omitted>;

const Fragment: TObject<{
	entryId: TUnion<[TString, TNull]>;
	parentId: TUnion<[TString, TNull]>;
	timestamp: TUnion<[TString, TNull]>;
	line: TInteger;
	kind: TUnion<
		[
			TLiteral<"user">,
			TLiteral<"assistant">,
			TLiteral<"toolResult">,
			TLiteral<"bashExecution">,
			TLiteral<"custom_message">,
			TLiteral<"compaction">,
			TLiteral<"branch_summary">,
		]
	>;
	toolName: TUnion<[TString, TNull]>;
	isError: TUnion<[TBoolean, TNull]>;
	part: TInteger;
	parts: TInteger;
	text: TString;
}> = Type.Object(
	{
		entryId: NullableText,
		parentId: NullableText,
		timestamp: Type.Union([Type.String({ maxLength: 64 }), Type.Null()]),
		line: Type.Integer({ minimum: 2 }),
		kind: Type.Union([
			Type.Literal("user"),
			Type.Literal("assistant"),
			Type.Literal("toolResult"),
			Type.Literal("bashExecution"),
			Type.Literal("custom_message"),
			Type.Literal("compaction"),
			Type.Literal("branch_summary"),
		]),
		toolName: NullableText,
		isError: Type.Union([Type.Boolean(), Type.Null()]),
		part: Type.Integer({ minimum: 1 }),
		parts: Type.Integer({ minimum: 1 }),
		text: Type.String({ maxLength: 4096 }),
	},
	{ additionalProperties: false },
);
export type BakFragment = Static<typeof Fragment>;

type PageShape = {
	fetchedAt: TString;
	trust: TLiteral<"untrusted-history">;
	totalItems: TInteger;
	nextCursor: TUnion<[TString, TNull]>;
};
const PageFields = {
	fetchedAt: Type.String({ maxLength: 64 }),
	trust: Type.Literal("untrusted-history"),
	totalItems: Type.Integer({ minimum: 0 }),
	nextCursor: Type.Union([Cursor, Type.Null()]),
};
const RawOutput: TObject<{
	fetchedAt: TString;
	trust: TLiteral<"untrusted-history">;
	nextCursor: TUnion<[TString, TNull]>;
	action: TLiteral<"read">;
	view: TLiteral<"raw-jsonl">;
	session: typeof Session;
	startByte: TInteger;
	endByteExclusive: TInteger;
	totalBytes: TInteger;
	redaction: TLiteral<"configured-credentials">;
	text: TString;
}> = Type.Object(
	{
		fetchedAt: PageFields.fetchedAt,
		trust: PageFields.trust,
		nextCursor: PageFields.nextCursor,
		action: Type.Literal("read"),
		view: Type.Literal("raw-jsonl"),
		session: Session,
		startByte: Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }),
		endByteExclusive: Type.Integer({
			minimum: 0,
			maximum: Number.MAX_SAFE_INTEGER,
		}),
		totalBytes: Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }),
		redaction: Type.Literal("configured-credentials"),
		text: Type.String({ maxLength: 16 * 1024 }),
	},
	{ additionalProperties: false },
);
export type BakRawResult = Static<typeof RawOutput>;

export const BakOutput: TUnion<
	[
		TObject<
			PageShape & {
				action: TUnion<[TLiteral<"list">, TLiteral<"search">]>;
				scope: TLiteral<"indexed-sessions">;
				sessions: TArray<typeof Session>;
			}
		>,
		TObject<
			PageShape & {
				action: TLiteral<"read">;
				view: TLiteral<"archive-history">;
				order: TLiteral<"append">;
				branches: TLiteral<"all">;
				session: typeof Session;
				omitted: typeof Omitted;
				fragments: TArray<typeof Fragment>;
			}
		>,
		typeof RawOutput,
	]
> = Type.Union([
	Type.Object(
		{
			...PageFields,
			action: Type.Union([Type.Literal("list"), Type.Literal("search")]),
			scope: Type.Literal("indexed-sessions"),
			sessions: Type.Array(Session, { maxItems: 100 }),
		},
		{ additionalProperties: false },
	),
	Type.Object(
		{
			...PageFields,
			action: Type.Literal("read"),
			view: Type.Literal("archive-history"),
			order: Type.Literal("append"),
			branches: Type.Literal("all"),
			session: Session,
			omitted: Omitted,
			fragments: Type.Array(Fragment, { maxItems: 100 }),
		},
		{ additionalProperties: false },
	),
	RawOutput,
]);
export type BakResult = Static<typeof BakOutput>;
export interface BakToolDetails {
	action: "list" | "search" | "read" | "raw-jsonl";
	count: number;
	total: number;
}

type Definition = ToolDefinition<typeof BakParameters, BakToolDetails>;
export const renderBakCall: NonNullable<Definition["renderCall"]> = (
	args,
	theme,
) => {
	const action =
		args.action === "list" || args.action === "search" || args.action === "read"
			? args.action
			: "query";
	return new Text(
		`${theme.fg("toolTitle", theme.bold("bak"))} ${action}`,
		0,
		0,
	);
};

export const renderBakResult: NonNullable<Definition["renderResult"]> = (
	result,
	{ expanded, isPartial },
	theme,
	context,
) => {
	const text = result.content
		.filter((item) => item.type === "text")
		.map((item) => item.text)
		.join("\n");
	if (isPartial) return new Text(theme.fg("muted", "Reading archive…"), 0, 0);
	if (context.isError)
		return new Text(theme.fg("error", text.slice(0, 240)), 0, 0);
	if (expanded) return new Text(text, 0, 0);
	const details = result.details;
	const summary =
		details && Number.isFinite(details.count) && Number.isFinite(details.total)
			? `${details.count}/${details.total} ${details.action === "raw-jsonl" ? "bytes" : details.action === "read" ? "fragments" : "sessions"}`
			: "Archive result";
	return new Text(
		`${theme.fg("muted", summary)} ${context.keyHint?.("app.tools.expand", "to expand") ?? keyHint("app.tools.expand", "to expand")}`,
		0,
		0,
	);
};