Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/ephemlets/index.ts

Raw
import type {
	ExtensionAPI,
	ToolDefinition,
} from "@earendil-works/pi-coding-agent";
import { type TSchema, Type } from "typebox";
import { EphemletRuntime } from "./runtime.ts";
import { closeDebug, dbg } from "./src/debug.ts";
import { ICON_SETS, type IconSet } from "./src/look.ts";
import {
	defineChoiceSetting,
	resolveSetting,
	type SettingDeclaration,
} from "./src/pi-ext-settings.ts";
import { ephemletRenderers } from "./src/tool-renderer.ts";

export const ICONS_SETTING: SettingDeclaration<IconSet> = defineChoiceSetting({
	key: "ephemlets.icons",
	label: "Icons",
	description:
		"Glyphs for checkboxes, receipts and panel controls: Nerd Font icons, or plain Unicode for fonts without them.",
	choices: ICON_SETS,
	default: "nerd",
	env: "PI_EPHEMLETS_ICONS",
});

export default function registerEphemlets(pi: ExtensionAPI): void {
	let runtime: EphemletRuntime | undefined;
	let activeBeforeHide = false;
	let icons: IconSet = ICONS_SETTING.default;
	const get = () => (runtime ??= new EphemletRuntime(pi, dbg, () => icons));
	pi.on("session_start", (_event, ctx) => {
		const active = pi.getActiveTools();
		tool.exposure = ctx.mode === "tui" ? "model-only" : "hidden";
		pi.registerTool(tool);
		if (ctx.mode === "tui" && activeBeforeHide && !active.includes("ephemlet"))
			pi.setActiveTools([...active, "ephemlet"]);
		if (ctx.mode !== "tui") {
			activeBeforeHide ||= active.includes("ephemlet");
			if (active.includes("ephemlet"))
				pi.setActiveTools(active.filter((name) => name !== "ephemlet"));
			runtime?.dispose();
			return;
		}
		activeBeforeHide = false;
		dbg?.("session.start");
		const hasEphemlets = ctx.sessionManager
			.getBranch()
			.some(
				(entry) => entry.type === "custom" && entry.customType === "ephemlets",
			);
		const iconSetting = resolveSetting(pi, ctx, ICONS_SETTING);
		if (!iconSetting.ok) ctx.ui.notify(iconSetting.error, "warning");
		icons = iconSetting.ok ? iconSetting.value : ICONS_SETTING.default;
		if (runtime || hasEphemlets) {
			try {
				get().restore(ctx);
			} catch (error) {
				ctx.ui.notify(`Ephemlet restore failed: ${String(error)}`, "error");
			}
		}
	});
	pi.on("session_tree", (_event, ctx) => {
		if (ctx.mode === "tui") runtime?.restore(ctx);
	});
	pi.on("context", (event, ctx) => {
		if (ctx.mode === "tui") runtime?.markRead(event.messages);
	});
	pi.on("before_agent_start", (_event, ctx) => {
		if (ctx.mode !== "tui" || !runtime) return undefined;
		runtime.setContext(ctx);
		const message = runtime.takeHeld();
		return message ? { message } : undefined;
	});
	pi.on("session_shutdown", () => {
		runtime?.dispose();
		dbg?.("session.shutdown");
		closeDebug();
	});
	pi.registerShortcut("alt+e", {
		description: "Expand/collapse ephemlets",
		handler: (ctx) => {
			if (ctx.mode === "tui") get().toggle(ctx);
		},
	});
	pi.registerShortcut("ctrl+alt+e", {
		description: "Open and focus ephemlets",
		handler: (ctx) => {
			if (ctx.mode === "tui") get().show(ctx);
		},
	});
	pi.registerCommand("ephemlets", {
		description: "Toggle compact/expanded ephemlets, or show/hide/focus panel",
		getArgumentCompletions(prefix) {
			return ["show", "hide", "focus"]
				.filter((value) => value.startsWith(prefix))
				.map((value) => ({ value, label: value }));
		},
		handler: async (args, ctx) => {
			if (ctx.mode !== "tui") {
				ctx.ui.notify("Ephemlets require interactive TUI mode", "warning");
				return;
			}
			const host = get();
			if (args === "show" || args === "focus") host.show(ctx);
			else if (args === "hide") host.hide(ctx);
			else if (!args) host.toggle(ctx);
			else ctx.ui.notify("Use /ephemlets [show|hide|focus]", "warning");
		},
	});
	const tool: ToolDefinition<ReturnType<typeof parameters>, unknown> = {
		name: "ephemlet",
		annotations: { readOnlyHint: false },
		exposure: "model-only",
		label: "Ephemlet",
		description:
			"Session-persistent Markdown task reports in a panel beside the conversation. Optional checklist, choice, confirm and text fields let the human steer without interrupting you; wait blocks only your tool call until a needed answer arrives. Creation omits id and returns a server-assigned id and revision; updates pass id plus that latest revision as expectedRevision. Get returns metadata unless include requests source, last rendered view text (not a screenshot) or answers. Interactive TUI only.",
		promptSnippet:
			"Persistent task reports the human can steer without interrupting you",
		promptGuidelines: [
			"Create an ephemlet only when the user asks, or for multi-turn work they will want to watch or steer while you continue (plan to veto, deferrable decision, status to check later). Otherwise answer in chat; a single question you must have answered before continuing belongs in a direct question, not a panel; deliverables belong in files.",
			"One ephemlet per task: use the id and revision returned by put/get for updates; list only when you need to rediscover an existing ephemlet. Update at milestones, not every step; when the task ends, put a final state.",
			"Keep it high-level: progress, decisions, blockers; what and why, not implementation details. Do not repeat it in chat.",
			"Fields steer without interrupting: checklist to veto/tick plan items (checked is your default; the human's toggles win), choice to pick, confirm for go/no-go, text for short free answers. Questions must stand alone; use few options and stable ids so answers survive updates.",
			'Delivery: checklist answers wait until you read include: ["answers"] (list/get show unseen: true); choice and text arrive before your next model call while you work, otherwise with the next prompt; confirm also starts a turn when you are idle. If you end your turn while a choice or text question is open, say so in chat. With several ephemlet-answer messages, only the highest revision counts.',
			"wait only for a question already in a panel that you cannot proceed without; it blocks just your tool call and returns all answers with timedOut.",
			"You cannot see the panel. Never show or focus it unless asked.",
		],
		executionMode: "sequential",
		constrainedSampling: { type: "json_schema", strict: "prefer" },
		parameters: parameters(),
		outputSchema: outputSchema(),
		...ephemletRenderers,
		async execute(_id, params, _signal, _onUpdate, ctx) {
			if (ctx.mode !== "tui")
				throw new Error("Ephemlets require interactive TUI mode");
			return get().execute(params, ctx, _signal);
		},
	};
	pi.registerTool(tool);
}

function parameters() {
	return Type.Object({
		action: Type.Union(
			(["put", "list", "get", "delete", "show", "hide", "wait"] as const).map(
				(value) => Type.Literal(value),
			),
			{
				description:
					"Operation; creation omits id, updates require expectedRevision, and get reads metadata by default.",
			},
		),
		id: Type.Optional(
			Type.String({
				minLength: 1,
				maxLength: 80,
				description: "Server-assigned ID; required for get/delete and updates.",
			}),
		),
		expectedRevision: Type.Optional(
			Type.Integer({
				minimum: 1,
				description: "Latest revision from put or get; required for updates.",
			}),
		),
		title: Type.Optional(
			Type.String({
				minLength: 1,
				maxLength: 256,
				description: "Required on creation.",
			}),
		),
		purpose: Type.Optional(
			Type.String({
				maxLength: 4096,
				description: "Why the report exists; defaults to title on creation.",
			}),
		),
		source: Type.Optional(
			Type.String({
				maxLength: 131072,
				description:
					"Markdown; required on creation, omitted on update reuses prior source.",
			}),
		),
		fields: Type.Optional(
			Type.Array(
				Type.Union([
					fieldSchema("checklist", {
						label: optionalLabel(),
						items: Type.Array(
							Type.Object({
								id: idSchema(),
								label: labelSchema(),
								checked: Type.Optional(
									Type.Boolean({
										description: "Agent default; human toggles win.",
									}),
								),
							}),
							{ minItems: 1, maxItems: 64 },
						),
					}),
					fieldSchema("choice", {
						label: optionalLabel(),
						options: Type.Array(
							Type.Object({ id: idSchema(), label: labelSchema() }),
							{ minItems: 1, maxItems: 32 },
						),
						multiple: Type.Optional(Type.Boolean()),
					}),
					fieldSchema("confirm", {
						label: Type.String({
							minLength: 1,
							maxLength: 256,
							description: "The yes/no question.",
						}),
					}),
					fieldSchema("text", {
						label: Type.String({
							minLength: 1,
							maxLength: 256,
							description: "The question the human answers in free text.",
						}),
						placeholder: Type.Optional(Type.String({ maxLength: 256 })),
					}),
				]),
				{
					maxItems: 8,
					description:
						"Interactive fields rendered below the Markdown. Omitted on update keeps prior fields; [] removes them. Human answers survive for unchanged field and option IDs.",
				},
			),
		),
		include: Type.Optional(
			Type.Array(
				Type.Union([
					Type.Literal("source"),
					Type.Literal("view"),
					Type.Literal("answers"),
				]),
				{
					maxItems: 3,
					uniqueItems: true,
					description:
						"Get only: include source, bounded last-rendered view text (not a screenshot), and/or field answers; reading answers marks them seen for the human.",
				},
			),
		),
		waitFor: Type.Optional(
			Type.Array(idSchema(), {
				minItems: 1,
				maxItems: 8,
				uniqueItems: true,
				description:
					"Wait only: field IDs whose answer you need; default every open question.",
			}),
		),
		timeoutMs: Type.Optional(
			Type.Integer({
				minimum: 1,
				maximum: 1_800_000,
				description: "Wait only: give up after this long; default 5 minutes.",
			}),
		),
	});
}

function idSchema() {
	return Type.String({ pattern: "^[a-zA-Z0-9_-]{1,64}$" });
}
function optionalLabel() {
	return Type.Optional(Type.String({ maxLength: 256 }));
}
function labelSchema() {
	return Type.String({ minLength: 1, maxLength: 256 });
}
function fieldSchema<T extends string, P extends Record<string, TSchema>>(
	type: T,
	properties: P,
) {
	return Type.Object({
		id: idSchema(),
		type: Type.Literal(type),
		delivery: Type.Optional(
			Type.Union(
				[Type.Literal("ambient"), Type.Literal("next"), Type.Literal("now")],
				{ description: "How answers reach you; see guidelines for defaults." },
			),
		),
		...properties,
	});
}

function outputSchema() {
	const ephemlet = Type.Object({
		id: Type.String(),
		title: Type.String(),
		purpose: Type.String(),
		revision: Type.Integer({ minimum: 1 }),
		unseen: Type.Optional(Type.Literal(true)),
		droppedAnswers: Type.Optional(Type.Array(Type.String())),
		timedOut: Type.Optional(Type.Boolean()),
		fields: Type.Optional(
			Type.Array(
				Type.Object({
					id: Type.String(),
					type: Type.Union([
						Type.Literal("checklist"),
						Type.Literal("choice"),
						Type.Literal("confirm"),
						Type.Literal("text"),
					]),
					label: Type.Optional(Type.String()),
					text: Type.Optional(Type.Union([Type.String(), Type.Null()])),
					items: Type.Array(
						Type.Object({
							id: Type.String(),
							label: Type.String(),
							checked: Type.Boolean(),
							by: Type.Union([Type.Literal("agent"), Type.Literal("user")]),
						}),
					),
				}),
			),
		),
		source: Type.Optional(Type.String()),
		view: Type.Optional(
			Type.Union([
				Type.Object({
					available: Type.Literal(true),
					plainText: Type.String(),
					width: Type.Integer({ minimum: 0, maximum: 200 }),
					height: Type.Integer({ minimum: 0, maximum: 40 }),
					revision: Type.Integer({ minimum: 1 }),
					stale: Type.Boolean(),
					truncated: Type.Boolean(),
				}),
				Type.Object({ available: Type.Literal(false), reason: Type.String() }),
			]),
		),
	});
	return Type.Union([
		ephemlet,
		Type.Object({ ephemlets: Type.Array(ephemlet) }),
		Type.Object({
			visible: Type.Boolean(),
			selected: Type.Union([Type.String(), Type.Null()]),
		}),
		Type.Object({ deleted: Type.String() }),
	]);
}