Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/pipi/index.ts

Raw
import { isAbsolute } from "node:path";
import {
	DEFAULT_MAX_BYTES,
	DEFAULT_MAX_LINES,
	defineTool,
	type ExtensionAPI,
	getAgentDir,
	truncateHead,
} from "@earendil-works/pi-coding-agent";
import type { TUI } from "@earendil-works/pi-tui";
import { Type } from "typebox";
import {
	ConfigSchema,
	callDeadline,
	discover,
	settings,
	tierGuidance,
} from "./config.ts";
import { LiveTaskPreview } from "./live.ts";
import { renderTask, renderTaskCall } from "./render.ts";
import {
	type Inheritance,
	json,
	type Progress,
	runTask,
	snapshotPrompt,
	type TaskRequest,
	type TaskResult,
} from "./runtime.ts";
import { closeDebug, dbg } from "./src/debug.ts";

export default function pipi(pi: ExtensionAPI): void {
	let host: TUI | undefined;
	const liveTasks = new Map<string, LiveTaskPreview>();
	pi.on("session_start", (_event, ctx) => {
		if (ctx.mode !== "tui") return;
		// Native tool components require Pi's real TUI; this widget adds no visible rows.
		ctx.ui.setWidget(
			"pipi-native-preview-host",
			(tui) => {
				host = tui;
				return {
					render: () => [],
					invalidate() {},
					dispose() {
						if (host === tui) host = undefined;
					},
				};
			},
			{ placement: "belowEditor" },
		);
	});
	let inheritedPrompt: Inheritance["prompt"] = {};
	pi.on("before_agent_start", async (event, ctx) => {
		const options = event.systemPromptOptions;
		inheritedPrompt = options;
		options.sections["pipi_tiers"] = tierGuidance(
			settings(pi, ctx),
			ctx.model?.provider,
		);
		const catalog = await discover(getAgentDir());
		const root = getAgentDir() + "/pipi";
		options.sections["pipi_library"] = [
			`Reusable agent library (prefer a fitting preset before ad-hoc delegation): ${root}/agents/<name>/config.json (description required), optional instructions.md. Agent name is folder name; lowercase ASCII recommended. Read instructions only when needed. Prefer improving or simplifying an existing agent over creating near-duplicates. Ordinary file tools manage this library; changes affect future calls, including continuation.`,
			...catalog.agents.map((agent) => `- ${agent.name}: ${agent.description}`),
			`Dynamic extension root: ${root}/dynamic. Ordinary Pi extensions, initially one index.ts; grow only when needed. Load explicitly using extensions paths. No extra publication or validation step.`,
			...catalog.dynamic.map((name) => `- ${name}/index.ts`),
			...catalog.diagnostics,
		].join("\n");
	});
	pi.on("session_shutdown", () => {
		for (const preview of liveTasks.values()) preview.dispose();
		liveTasks.clear();
		host = undefined;
		dbg?.("session.shutdown");
		closeDebug();
	});
	pi.registerTool(
		defineTool({
			name: "pipi",
			label: "π²",
			description:
				"Run one blocking child Pi task. Fresh session by default; use sessionId to continue or fork:true for a native fork. Child and descendants stop when this call is cancelled or at the deadline (pipi.timeoutMs, default 4 hours; per-call timeoutMs overrides, null opts out). Optional agent preset; explicit call config overrides it. Calls may run concurrently. Result contains output, outcome, native session locator, new-work usage and effective config.",
			promptSnippet: "Delegate one task to a child Pi session.",
			executionMode: "parallel",
			parameters: Type.Unsafe<TaskRequest>(
				Type.Object(
					{
						...ConfigSchema.properties,
						prompt: Type.String(),
						images: Type.Optional(
							Type.Array(
								Type.Object({
									type: Type.Literal("image"),
									data: Type.String(),
									mimeType: Type.String(),
								}),
							),
						),
						agent: Type.Optional(Type.String()),
						cwd: Type.Optional(Type.String()),
						sessionId: Type.Optional(Type.String()),
						fork: Type.Optional(Type.Boolean()),
					},
					{ additionalProperties: false },
				),
			),
			outputSchema: Type.Object({
				outputMode: Type.Union([
					Type.Literal("message"),
					Type.Literal("structured"),
				]),
				outcome: Type.Union(
					["completed", "aborted", "error", "failed"].map((value) =>
						Type.Literal(value),
					),
				),
				output: Type.Unknown(),
				assistantMessage: Type.Unknown(),
				sessionId: Type.String(),
				sessionFile: Type.Union([Type.String(), Type.Null()]),
				durationMs: Type.Number(),
				turns: Type.Number(),
				usage: Type.Unknown(),
				requested: Type.Unknown(),
				effective: Type.Unknown(),
				diagnostics: Type.Array(Type.String()),
			}),
			async execute(_id, request, signal, onUpdate, ctx) {
				const extensions = [
					...new Set(
						pi
							.getAllTools()
							.filter(
								(tool) =>
									tool.sourceInfo.source !== "builtin" &&
									!tool.sourceInfo.path.startsWith("builtin:"),
							)
							.map((tool) => tool.sourceInfo.path)
							.filter(isAbsolute),
					),
				];
				const live =
					ctx.mode === "tui"
						? new LiveTaskPreview(
								() => host,
								() => pi.getSettings().hideThinkingBlock ?? false,
							)
						: undefined;
				if (live) liveTasks.set(_id, live);
				let result: TaskResult;
				try {
					result = await runTask(
						ctx,
						request,
						{
							tools: pi
								.getActiveTools()
								.filter((name) => name !== "pipi_output"),
							availableTools: pi
								.getAllTools()
								.map((tool) => tool.name)
								.filter((name) => name !== "pipi_output"),
							extensions,
							prompt: snapshotPrompt(inheritedPrompt),
						},
						settings(pi, ctx),
						callDeadline(pi, ctx),
						signal,
						(value) => {
							onUpdate?.({ content: [], details: { progress: value } });
						},
						live
							? (event, child) => {
									try {
										if (live.update(event, child))
											onUpdate?.({ content: [], details: {} });
									} catch {
										// Presentation failures must not fail child execution.
										live.dispose();
									}
								}
							: undefined,
					);
				} finally {
					live?.dispose();
					liveTasks.delete(_id);
				}
				const rendered = truncateHead(JSON.stringify(result), {
					maxBytes: DEFAULT_MAX_BYTES,
					maxLines: DEFAULT_MAX_LINES,
				});
				const content =
					rendered.content +
					(rendered.truncated
						? `\n[Truncated model-facing result; complete native transcript: ${result.sessionFile ?? result.sessionId}. Structured result remains complete.]`
						: "");
				return {
					content: [{ type: "text", text: content }],
					structuredContent: json(result),
					details: { result },
					// A persisted child session is its own usage ledger; reporting it here
					// too would count it twice for anyone aggregating sessions.
					...(result.sessionFile === null ? { usage: result.usage } : {}),
					isError: result.outcome !== "completed",
				};
			},
			renderCall(args, theme, context) {
				return renderTaskCall(args, context.expanded, theme);
			},
			renderResult(result, options, theme, context) {
				const details = result.details as
					| { result?: TaskResult; progress?: Progress }
					| undefined;
				if (context.isError && !details?.result)
					return renderTask(
						undefined,
						options.expanded,
						theme,
						{
							phase: "error",
							preview: result.content
								.filter((part) => part.type === "text")
								.map((part) => part.text)
								.join("\n"),
						},
						context,
					);
				const live = liveTasks.get(context.toolCallId);
				if (!details?.result && live)
					return live.configure(options.expanded, theme, context);
				return renderTask(
					details?.result,
					options.expanded,
					theme,
					details?.progress,
					context,
				);
			},
		}),
	);
}