repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/goal/index.ts

Raw
File outline
import { complete, StringEnum } from "@earendil-works/pi-ai";
import type {
	ExtensionAPI,
	ExtensionContext,
	ThemeColor,
} from "@earendil-works/pi-coding-agent";
import {
	type AutocompleteItem,
	matchesKey,
	Text,
	truncateToWidth,
	visibleWidth,
} from "@earendil-works/pi-tui";
import { Type } from "typebox";

type GoalStatus = "active" | "paused" | "complete" | "blocked";
type ProbeMode = "direct" | "microtask" | "timeout";

type GoalSettings = {
	maxTurns: number;
	judgeModel?: string;
	tailBytes: number;
};

type GoalState = {
	id: string;
	objective: string;
	criteria: string[];
	status: GoalStatus;
	turnsUsed: number;
	maxTurns: number;
	lastReason?: string;
	sessionId?: string;
	createdAt: number;
	updatedAt: number;
};

type JudgeVerdict = {
	done: boolean;
	blocked: boolean;
	reason: string;
};

type ProbeState = {
	mode: ProbeMode;
	active: boolean;
	scheduled: boolean;
	dispatched: boolean;
};

type GoalSubcommand = {
	value: string;
	description: string;
};

const GOAL_STATE_ENTRY = "goal-state";
const GOAL_JUDGE_ENTRY = "goal-judge";
const PROBE_ENTRY = "goal-probe";
const PROBE_MESSAGE = "GOAL_PROBE_CONTINUATION";
const DEFAULT_MAX_TURNS = 20;
const DEFAULT_TAIL_BYTES = 4096;
const STATUS_KEY = "goal";
const WIDGET_KEY = "goal";
const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
const FOOTER_SEGMENT = { id: "goal", zone: "llm", order: 30 } as const;
const CONTINUATION_RETRY_MS = 250;
const CONTINUATION_MAX_ATTEMPTS = 20;
const JUDGE_ATTEMPTS = 2;
const ANSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]/g;
const CONTROL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g;
const GOAL_WIDGET_LABEL_WIDTH = 11;
const GOAL_WIDGET_MAX_WIDTH = 78;
const GOAL_WIDGET_LEFT_PADDING = 1;
const JUDGE_SYSTEM_PROMPT = `You are a strict /goal completion judge.
Return only JSON: {"done":boolean,"blocked":boolean,"reason":"one sentence"}.
Mark done only if the latest assistant response explicitly proves the objective and every criterion are complete.
Mark blocked only if the response shows a real impasse needing user input or external state.
Otherwise return done=false, blocked=false.`;
const GOAL_SUBCOMMANDS: GoalSubcommand[] = [
	{ value: "status", description: "Show current goal" },
	{ value: "pause", description: "Pause active goal" },
	{ value: "resume", description: "Resume/rebind goal" },
	{ value: "complete", description: "Mark goal complete" },
	{ value: "clear", description: "Clear goal" },
	{ value: "add", description: "Add criterion" },
	{ value: "remove", description: "Remove criterion by number" },
	{ value: "criteria", description: "List criteria" },
	{ value: "clear-criteria", description: "Clear all criteria" },
];

type GoalUiMode = "normal" | "judging";

type SettingsAPI = ExtensionAPI & {
	settingsManager?: { getSettings(): Record<string, unknown> | undefined };
};

function isRecord(value: unknown): value is Record<string, unknown> {
	return value !== null && typeof value === "object" && !Array.isArray(value);
}

function clampInt(
	value: unknown,
	fallback: number,
	min: number,
	max: number,
): number {
	const n = Number(value ?? fallback);
	if (!Number.isFinite(n)) return fallback;
	return Math.max(min, Math.min(max, Math.trunc(n)));
}

function loadSettings(pi: ExtensionAPI): GoalSettings {
	const all = (pi as SettingsAPI).settingsManager?.getSettings?.();
	const raw = isRecord(all?.goal) ? all.goal : {};
	return {
		maxTurns: clampInt(raw.maxTurns, DEFAULT_MAX_TURNS, 1, 10_000),
		judgeModel:
			typeof raw.judgeModel === "string" && raw.judgeModel.trim()
				? raw.judgeModel.trim()
				: undefined,
		tailBytes: clampInt(raw.tailBytes, DEFAULT_TAIL_BYTES, 512, 65_536),
	};
}

function textFromContent(content: unknown): string {
	if (typeof content === "string") return content;
	if (!Array.isArray(content)) return "";
	return content
		.map((part) => {
			if (!isRecord(part)) return "";
			return part.type === "text" && typeof part.text === "string"
				? part.text
				: "";
		})
		.filter(Boolean)
		.join("\n");
}

function extractStandingGoalObjective(prompt: string): string | undefined {
	if (!/standing goal/i.test(prompt)) return undefined;
	const match = prompt.match(/<objective>\s*([\s\S]*?)\s*<\/objective>/i);
	const objective = match?.[1]?.trim();
	return objective || undefined;
}

function isGoalStatus(value: unknown): value is GoalStatus {
	return (
		value === "active" ||
		value === "paused" ||
		value === "complete" ||
		value === "blocked"
	);
}

function isGoalState(value: unknown): value is GoalState {
	if (!isRecord(value)) return false;
	return (
		typeof value.id === "string" &&
		typeof value.objective === "string" &&
		Array.isArray(value.criteria) &&
		value.criteria.every((criterion) => typeof criterion === "string") &&
		isGoalStatus(value.status) &&
		Number.isInteger(value.turnsUsed) &&
		Number.isInteger(value.maxTurns) &&
		(value.sessionId === undefined || typeof value.sessionId === "string") &&
		typeof value.createdAt === "number" &&
		typeof value.updatedAt === "number"
	);
}

function latestGoalState(ctx: ExtensionContext): GoalState | undefined {
	const entries = ctx.sessionManager.getEntries() as Array<{
		type: string;
		customType?: string;
		data?: unknown;
	}>;
	// Session entries are append-only: newest valid goal-state/tombstone decides replay.
	// Scan backward to avoid O(full transcript) work after long sessions.
	for (let i = entries.length - 1; i >= 0; i--) {
		const entry = entries[i];
		if (
			entry.type !== "custom" ||
			entry.customType !== GOAL_STATE_ENTRY ||
			!isRecord(entry.data)
		)
			continue;
		if (entry.data.cleared === true) return undefined;
		if (isGoalState(entry.data)) return entry.data;
	}
	return undefined;
}

function appendGoal(pi: ExtensionAPI, state: GoalState): void {
	pi.appendEntry(GOAL_STATE_ENTRY, state);
}

function updateGoal(
	pi: ExtensionAPI,
	current: GoalState,
	patch: Partial<GoalState>,
): GoalState {
	const next = { ...current, ...patch, updatedAt: Date.now() };
	appendGoal(pi, next);
	return next;
}

function showsTurnBudget(state: GoalState): boolean {
	return state.status === "active" || state.status === "paused";
}

function showsPersistentStatus(state: GoalState): boolean {
	return state.status !== "complete";
}

function shortText(text: string, max = 72): string {
	const oneLine = text.replace(/\s+/g, " ").trim();
	return oneLine.length <= max ? oneLine : `${oneLine.slice(0, max - 1)}…`;
}

function sanitizeGoalText(text: string, max = 160): string {
	return shortText(
		text.replace(ANSI_RE, "").replace(CONTROL_RE, " ").replace(/\s+/g, " "),
		max,
	);
}

function judgeDisplayReason(reason: string): string {
	return sanitizeGoalText(reason, 160);
}

function judgeVerdictLabel(
	verdict: JudgeVerdict,
): "done" | "blocked" | "continue" {
	if (verdict.done) return "done";
	if (verdict.blocked) return "blocked";
	return "continue";
}

function isJudgeFailure(verdict: JudgeVerdict): boolean {
	return verdict.reason.startsWith("judge failed:");
}

function judgeRunningText(state: GoalState): string {
	const criteria =
		state.criteria.length === 0 ? "" : ` · ${state.criteria.length} criteria`;
	return `Goal judge running: turn ${state.turnsUsed + 1}/${state.maxTurns}${criteria} · ${shortText(state.objective)}`;
}

function statusLine(state: GoalState, currentSessionId?: string): string {
	const turns = showsTurnBudget(state)
		? ` · ${state.turnsUsed}/${state.maxTurns} turns`
		: "";
	const criteria =
		state.criteria.length === 0 ? "" : ` · ${state.criteria.length} criteria`;
	const reason = state.lastReason ? ` · ${state.lastReason}` : "";
	const owner =
		state.sessionId && currentSessionId && state.sessionId !== currentSessionId
			? " · owned by another session"
			: "";
	return `${state.status}${turns}${criteria}${owner}${reason}\n${state.objective}`;
}

function statusText(state: GoalState | undefined): string | undefined {
	if (!state || !showsPersistentStatus(state)) return undefined;
	if (!showsTurnBudget(state)) return `goal ${state.status}`;
	const criteria =
		state.criteria.length === 0 ? "" : ` · ${state.criteria.length}c`;
	return `goal ${state.status} ${state.turnsUsed}/${state.maxTurns}${criteria}`;
}

function judgeStatusText(state: GoalState): string {
	const criteria =
		state.criteria.length === 0 ? "" : ` · ${state.criteria.length}c`;
	return `goal judging ${state.turnsUsed + 1}/${state.maxTurns}${criteria}`;
}

function hasFooter(): boolean {
	const footer = (globalThis as any)[FOOTER_KEY];
	return footer?.loaded === true && (footer.version ?? 0) >= 1;
}

function clearFooter(pi: ExtensionAPI): void {
	pi.events.emit("footer:segment", { id: FOOTER_SEGMENT.id, text: undefined });
}

function goalTone(state: GoalState, mode: GoalUiMode): ThemeColor {
	if (mode === "judging") return "warning";
	if (state.status === "complete") return "success";
	if (state.status === "blocked") return "warning";
	if (state.status === "paused") return "muted";
	return "accent";
}

function goalProgress(state: GoalState): number {
	return state.maxTurns <= 0
		? 0
		: Math.max(
				0,
				Math.min(100, Math.round((state.turnsUsed / state.maxTurns) * 100)),
			);
}

function goalBar(state: GoalState, width = 10): string {
	const filled = Math.max(
		0,
		Math.min(width, Math.round((goalProgress(state) / 100) * width)),
	);
	return "━".repeat(filled) + "─".repeat(width - filled);
}

function padVisible(text: string, width: number): string {
	return text + " ".repeat(Math.max(0, width - visibleWidth(text)));
}

function fitVisible(text: string, width: number): string {
	return padVisible(truncateToWidth(text, width, "…"), width);
}

function goalWidgetRow(
	label: string,
	value: string,
	innerWidth: number,
): string {
	const labelText = fitVisible(label, GOAL_WIDGET_LABEL_WIDTH);
	const valueWidth = Math.max(0, innerWidth - GOAL_WIDGET_LABEL_WIDTH);
	return `│ ${labelText}${fitVisible(value, valueWidth)} │`;
}

function insetWidgetLine(line: string, width: number): string {
	if (width <= 0) return "";
	return ` ${truncateToWidth(line, Math.max(0, width - GOAL_WIDGET_LEFT_PADDING), "…")}`;
}

function goalJudgeMessageLine(content: string): string {
	return ` ◇ ${content}`;
}

function goalWidgetLines(
	state: GoalState,
	mode: GoalUiMode,
	width = GOAL_WIDGET_MAX_WIDTH,
): string[] {
	const boxWidth = Math.max(
		28,
		Math.min(GOAL_WIDGET_MAX_WIDTH, Math.max(0, width)),
	);
	const innerWidth = boxWidth - 4;
	const criteria =
		state.criteria.length === 0 ? "" : ` · ${state.criteria.length}c`;
	const title = truncateToWidth(
		` goal ${goalPhaseText(state, mode)}${criteria} `,
		boxWidth - 2,
		"…",
	);
	const top = `╭${title}${"─".repeat(Math.max(0, boxWidth - visibleWidth(title) - 2))}╮`;
	const lines = [
		top,
		goalWidgetRow(
			"objective",
			sanitizeGoalText(state.objective, 120),
			innerWidth,
		),
	];
	if (mode === "judging") {
		lines.push(
			goalWidgetRow(
				"turn",
				`${state.turnsUsed + 1}/${state.maxTurns}`,
				innerWidth,
			),
		);
	} else if (showsTurnBudget(state)) {
		lines.push(
			goalWidgetRow(
				"turns",
				`${state.turnsUsed}/${state.maxTurns}  ${goalBar(state)}  ${goalProgress(state)}%`,
				innerWidth,
			),
		);
	}
	if (state.lastReason)
		lines.push(
			goalWidgetRow("judge", judgeDisplayReason(state.lastReason), innerWidth),
		);
	lines.push(`╰${"─".repeat(boxWidth - 2)}╯`);
	return lines;
}

function goalPhaseText(state: GoalState, mode: GoalUiMode): string {
	if (mode === "judging")
		return `judging ${state.turnsUsed + 1}/${state.maxTurns}`;
	if (!showsTurnBudget(state)) return state.status;
	return `${state.status} ${state.turnsUsed}/${state.maxTurns}`;
}

function widgetState(state: GoalState | undefined): GoalState | undefined {
	if (!state || state.status === "complete") return undefined;
	return state;
}

function updateWidget(
	ctx: ExtensionContext,
	state: GoalState | undefined,
	mode: GoalUiMode,
): void {
	const shown = widgetState(state);
	if (!shown) {
		ctx.ui.setWidget(WIDGET_KEY, undefined);
		return;
	}
	ctx.ui.setWidget(
		WIDGET_KEY,
		(_tui, theme) => ({
			invalidate() {},
			render(width: number): string[] {
				const tone = goalTone(shown, mode);
				const lines = goalWidgetLines(
					shown,
					mode,
					Math.max(0, width - GOAL_WIDGET_LEFT_PADDING),
				);
				return lines.map((rawLine) =>
					theme.fg(tone, insetWidgetLine(rawLine, width)),
				);
			},
		}),
		{ placement: "aboveEditor" },
	);
}

function updateFooter(
	pi: ExtensionAPI,
	ctx: ExtensionContext,
	state: GoalState | undefined,
	mode: GoalUiMode,
): void {
	if (!hasFooter()) {
		clearFooter(pi);
		ctx.ui.setStatus(
			STATUS_KEY,
			mode === "judging" && state ? judgeStatusText(state) : statusText(state),
		);
		return;
	}
	ctx.ui.setStatus(STATUS_KEY, undefined);
	const shown = widgetState(state);
	if (!shown) return clearFooter(pi);
	const phase = goalPhaseText(shown, mode);
	const criteria =
		shown.criteria.length === 0 ? "" : ` · ${shown.criteria.length}c`;
	const reason = shown.lastReason
		? ` · ${shortText(shown.lastReason, 36)}`
		: "";
	pi.events.emit("footer:segment", {
		...FOOTER_SEGMENT,
		text: `${phase}${criteria}${reason}`,
		variants: [phase, shown.status],
		color: goalTone(shown, mode),
	});
}

function updateUI(
	pi: ExtensionAPI,
	ctx: ExtensionContext,
	state: GoalState | undefined,
	mode: GoalUiMode = "normal",
): void {
	if (!ctx.hasUI) return;
	updateWidget(ctx, state, mode);
	updateFooter(pi, ctx, state, mode);
}

function canUseUpdateGoal(state: GoalState | undefined): state is GoalState {
	return !!state && state.status === "active" && state.turnsUsed > 0;
}

function setToolActive(pi: ExtensionAPI, name: string, active: boolean): void {
	const names = pi.getActiveTools();
	const has = names.includes(name);
	if (active === has) return;
	pi.setActiveTools(
		active ? [...names, name] : names.filter((tool) => tool !== name),
	);
}

function currentSessionId(ctx: ExtensionContext): string | undefined {
	return ctx.sessionManager.getSessionId?.();
}

function ownsGoal(ctx: ExtensionContext, state: GoalState): boolean {
	return !state.sessionId || state.sessionId === currentSessionId(ctx);
}

function ownedGoalOrNotify(
	ctx: ExtensionContext,
	state: GoalState | undefined,
): state is GoalState {
	if (!state) {
		ctx.ui.notify("No goal.", "warning");
		return false;
	}
	if (ownsGoal(ctx, state)) return true;
	ctx.ui.notify(
		"Goal belongs to another session — run /goal resume first.",
		"warning",
	);
	return false;
}

function criteriaText(state: GoalState): string {
	if (state.criteria.length === 0) return "No goal criteria.";
	return state.criteria
		.map((criterion, index) => `${index + 1}. ${criterion}`)
		.join("\n");
}

function goalArgumentCompletions(
	argumentPrefix: string,
	state: GoalState | undefined,
): AutocompleteItem[] | null {
	const input = argumentPrefix.trimStart();
	const firstSpace = input.search(/\s/);
	const cmd = firstSpace === -1 ? input : input.slice(0, firstSpace);
	const rest = firstSpace === -1 ? "" : input.slice(firstSpace + 1).trim();
	if (firstSpace === -1) {
		const matches = GOAL_SUBCOMMANDS.filter((subcommand) =>
			subcommand.value.startsWith(cmd),
		).map((subcommand) => ({
			value: subcommand.value,
			label: subcommand.value,
			description: subcommand.description,
		}));
		return matches.length === 0 ? null : matches;
	}
	if (cmd !== "remove" || !state || state.criteria.length === 0) return null;
	const matches = state.criteria
		.map((criterion, index) => ({ n: String(index + 1), criterion }))
		.filter((item) => item.n.startsWith(rest))
		.map((item) => ({
			value: `remove ${item.n}`,
			label: item.n,
			description: item.criterion,
		}));
	return matches.length === 0 ? null : matches;
}

function activeGoalPrompt(state: GoalState): string {
	const criteria =
		state.criteria.length === 0
			? "none"
			: state.criteria
					.map((criterion, index) => `${index + 1}. ${criterion}`)
					.join("\n");
	return `\n\nActive /goal:\n<objective>\n${state.objective}\n</objective>\n\nCriteria:\n${criteria}\n\nKeep working toward this standing goal. Do not redefine success smaller. Before claiming completion, verify current files, commands, tests, or deliverables. Use update_goal only after judge review and only when complete or genuinely blocked.`;
}

function continuationPrompt(state: GoalState): string {
	const criteria =
		state.criteria.length === 0
			? "none"
			: state.criteria
					.map((criterion, index) => `${index + 1}. ${criterion}`)
					.join("\n");
	return `Continue working toward this standing goal.\n\n<objective>\n${state.objective}\n</objective>\n\nCriteria:\n${criteria}\n\nDo not redefine success smaller. Inspect current state before claiming completion. If incomplete, make concrete progress. If complete or blocked after judge review, call update_goal.`;
}

function kickoffPrompt(state: GoalState): string {
	return `Start working toward this standing goal.\n\n<objective>\n${state.objective}\n</objective>\n\nDo not stop just because one turn ends. Keep making concrete progress until the goal is complete, blocked, paused, cleared, or the turn budget is exhausted.`;
}

function latestAssistantTail(ctx: ExtensionContext, tailBytes: number): string {
	const entries = ctx.sessionManager.getEntries() as Array<{
		type: string;
		message?: { role?: string; content?: unknown };
	}>;
	for (let i = entries.length - 1; i >= 0; i--) {
		const entry = entries[i];
		if (entry?.type !== "message" || entry.message?.role !== "assistant")
			continue;
		const text = textFromContent(entry.message.content).trim();
		if (!text) continue;
		return Buffer.from(text).subarray(-tailBytes).toString();
	}
	return "";
}

function parseModelRef(ref: string): { provider: string; model: string } {
	const i = ref.indexOf("/");
	if (i <= 0 || i === ref.length - 1)
		throw new Error(`Invalid model ref "${ref}". Use "provider/model".`);
	return { provider: ref.slice(0, i), model: ref.slice(i + 1) };
}

function resolveJudgeModel(ctx: ExtensionContext, settings: GoalSettings) {
	if (!settings.judgeModel) return ctx.model;
	const { provider, model } = parseModelRef(settings.judgeModel);
	const found = ctx.modelRegistry.find(provider, model);
	if (!found)
		throw new Error(`Goal judge model not found: ${settings.judgeModel}`);
	return found;
}

function parseJudge(raw: string): JudgeVerdict {
	const trimmed = raw.trim();
	if (!trimmed) throw new Error("judge returned empty response");
	const json = trimmed.match(/\{[\s\S]*\}/)?.[0] ?? trimmed;
	const parsed = JSON.parse(json);
	if (!isRecord(parsed)) throw new Error("judge returned non-object JSON");
	return {
		done: parsed.done === true,
		blocked: parsed.blocked === true,
		reason:
			typeof parsed.reason === "string" && parsed.reason.trim()
				? parsed.reason.trim()
				: "no reason",
	};
}

function appendJudge(
	pi: ExtensionAPI,
	event: "start" | "verdict",
	state: GoalState,
	verdict?: JudgeVerdict,
): void {
	const data = {
		event,
		goalId: state.id,
		objective: state.objective,
		turn: state.turnsUsed + 1,
		maxTurns: state.maxTurns,
		verdict,
		timestamp: Date.now(),
	};
	pi.appendEntry(GOAL_JUDGE_ENTRY, data);
	setTimeout(() => {
		try {
			pi.sendMessage(
				{
					customType: GOAL_JUDGE_ENTRY,
					content: verdict
						? `goal judge ${judgeVerdictLabel(verdict)} · turn ${data.turn}/${data.maxTurns} · ${judgeDisplayReason(verdict.reason)}`
						: `goal judge running · turn ${data.turn}/${data.maxTurns}`,
					display: true,
					details: data,
				},
				{ triggerTurn: false },
			);
		} catch (error) {
			if (!isStaleContextError(error)) throw error;
		}
	}, 0);
}

async function judgeGoal(
	ctx: ExtensionContext,
	state: GoalState,
	settings: GoalSettings,
): Promise<JudgeVerdict> {
	const model = resolveJudgeModel(ctx, settings);
	if (!model) return { done: false, blocked: false, reason: "no judge model" };
	const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
	if (!auth.ok || !auth.apiKey)
		return {
			done: false,
			blocked: false,
			reason: auth.ok ? "no judge api key" : auth.error,
		};
	const judgeContext = {
		systemPrompt: JUDGE_SYSTEM_PROMPT,
		messages: [
			{
				role: "user" as const,
				content: [
					{
						type: "text" as const,
						text: JSON.stringify(
							{
								objective: state.objective,
								criteria: state.criteria,
								latestAssistantResponse: latestAssistantTail(
									ctx,
									settings.tailBytes,
								),
							},
							null,
							2,
						),
					},
				],
				timestamp: Date.now(),
			},
		],
	};
	let lastError: unknown;
	for (let attempt = 0; attempt < JUDGE_ATTEMPTS; attempt++) {
		try {
			const response = await complete(model, judgeContext, {
				apiKey: auth.apiKey,
				headers: auth.headers,
				signal: ctx.signal,
				reasoning: "off",
				cacheRetention: "none",
			});
			if (response.stopReason === "error" || response.stopReason === "aborted")
				throw new Error(
					response.errorMessage || `judge ${response.stopReason}`,
				);
			const raw = response.content
				.filter(
					(part): part is { type: "text"; text: string } =>
						part.type === "text",
				)
				.map((part) => part.text)
				.join("\n");
			return parseJudge(raw);
		} catch (error) {
			lastError = error;
		}
	}
	throw lastError;
}

function isStaleContextError(error: unknown): boolean {
	return (
		error instanceof Error && error.message.includes("extension ctx is stale")
	);
}

function cancelGoalRun(
	pi: ExtensionAPI,
	ctx: ExtensionContext,
	state: GoalState | undefined,
): GoalState | undefined {
	if (!state || state.status !== "active" || !ownsGoal(ctx, state))
		return state;
	const next = updateGoal(pi, state, {
		status: "paused",
		lastReason: "cancelled by user",
	});
	updateUI(pi, ctx, next);
	setToolActive(pi, "update_goal", false);
	if (ctx.hasUI) ctx.ui.notify("Goal cancelled", "warning");
	return next;
}

function sendWhenIdle(
	pi: ExtensionAPI,
	ctx: ExtensionContext,
	state: GoalState,
	scheduled: { value: boolean },
	attempt = 0,
) {
	setTimeout(
		() => {
			let latest: GoalState | undefined;
			try {
				latest = latestGoalState(ctx);
			} catch (error) {
				if (isStaleContextError(error)) {
					scheduled.value = false;
					return;
				}
				throw error;
			}
			if (
				!latest ||
				latest.id !== state.id ||
				latest.status !== "active" ||
				!ownsGoal(ctx, latest)
			) {
				scheduled.value = false;
				return;
			}
			if (!ctx.isIdle() || ctx.hasPendingMessages()) {
				if (attempt >= CONTINUATION_MAX_ATTEMPTS) {
					scheduled.value = false;
					return;
				}
				return sendWhenIdle(pi, ctx, latest, scheduled, attempt + 1);
			}
			scheduled.value = false;
			pi.sendUserMessage(continuationPrompt(latest));
		},
		attempt === 0 ? 0 : CONTINUATION_RETRY_MS,
	);
}

function appendProbe(
	pi: ExtensionAPI,
	event: string,
	data: Record<string, unknown> = {},
) {
	pi.appendEntry(PROBE_ENTRY, { event, ...data, timestamp: Date.now() });
}

function sendProbeContinuation(
	pi: ExtensionAPI,
	ctx: ExtensionContext,
	state: ProbeState,
) {
	if (!state.active || state.dispatched) return;
	if (!ctx.isIdle()) {
		appendProbe(pi, "dispatch-skipped-busy", { mode: state.mode });
		return;
	}
	if (ctx.hasPendingMessages()) {
		appendProbe(pi, "dispatch-skipped-pending", { mode: state.mode });
		return;
	}
	state.dispatched = true;
	appendProbe(pi, "dispatch", { mode: state.mode });
	pi.sendUserMessage(PROBE_MESSAGE);
}

function scheduleProbeContinuation(
	pi: ExtensionAPI,
	ctx: ExtensionContext,
	state: ProbeState,
) {
	if (!state.active || state.scheduled) return;
	state.scheduled = true;
	appendProbe(pi, "persisted-before-schedule", { mode: state.mode });
	if (state.mode === "direct") return sendProbeContinuation(pi, ctx, state);
	if (state.mode === "microtask")
		return queueMicrotask(() => sendProbeContinuation(pi, ctx, state));
	setTimeout(() => sendProbeContinuation(pi, ctx, state), 0);
}

function parseProbeMode(args: string): ProbeMode | undefined {
	const mode = args.trim();
	if (mode === "direct" || mode === "microtask" || mode === "timeout")
		return mode;
	return undefined;
}

export default function goalExtension(pi: ExtensionAPI) {
	pi.registerMessageRenderer(GOAL_JUDGE_ENTRY, (message, _options, theme) => {
		const data = isRecord(message.details) ? message.details : {};
		const verdict = isRecord(data.verdict)
			? (data.verdict as JudgeVerdict)
			: undefined;
		const color: ThemeColor = verdict?.done
			? "success"
			: verdict?.blocked
				? "warning"
				: "accent";
		return new Text(
			theme.fg(color, goalJudgeMessageLine(message.content)),
			0,
			0,
		);
	});

	let state: GoalState | undefined;
	const continuationScheduled = { value: false };
	let removeTerminalInput: (() => void) | undefined;
	let probe: ProbeState | undefined;
	const syncUpdateGoalTool = () =>
		setToolActive(pi, "update_goal", canUseUpdateGoal(state));

	pi.on("session_start", (_event, ctx) => {
		state = latestGoalState(ctx);
		removeTerminalInput?.();
		removeTerminalInput = ctx.hasUI
			? ctx.ui.onTerminalInput((data) => {
					if (matchesKey(data, "escape")) {
						state = cancelGoalRun(pi, ctx, state);
						continuationScheduled.value = false;
					}
					return undefined;
				})
			: undefined;
		updateUI(pi, ctx, state);
		syncUpdateGoalTool();
	});

	pi.on("before_agent_start", (event, ctx) => {
		if (!state) {
			const objective = extractStandingGoalObjective(event.prompt);
			if (objective) {
				const settings = loadSettings(pi);
				const now = Date.now();
				state = {
					id: crypto.randomUUID(),
					objective,
					criteria: [],
					status: "active",
					turnsUsed: 0,
					maxTurns: settings.maxTurns,
					sessionId: currentSessionId(ctx),
					createdAt: now,
					updatedAt: now,
				};
				appendGoal(pi, state);
				updateUI(pi, ctx, state);
				syncUpdateGoalTool();
			}
		}
		if (!state || state.status !== "active" || !ownsGoal(ctx, state)) return;
		return { systemPrompt: event.systemPrompt + activeGoalPrompt(state) };
	});

	pi.on("agent_start", (_event, _ctx) => {
		if (probe?.active) appendProbe(pi, "agent-start", { mode: probe.mode });
	});

	pi.on("session_shutdown", (_event, ctx) => {
		removeTerminalInput?.();
		removeTerminalInput = undefined;
		updateUI(pi, ctx, undefined);
		setToolActive(pi, "update_goal", false);
	});

	pi.on("agent_end", async (_event, ctx) => {
		if (probe?.active) {
			appendProbe(pi, "agent-end", { mode: probe.mode });
			if (probe.dispatched) {
				probe.active = false;
				appendProbe(pi, "done", { mode: probe.mode });
			} else {
				scheduleProbeContinuation(pi, ctx, probe);
			}
		}

		updateUI(pi, ctx, state);
		syncUpdateGoalTool();
		if (
			!state ||
			state.status !== "active" ||
			!ownsGoal(ctx, state) ||
			continuationScheduled.value
		)
			return;
		const judged = state;
		appendJudge(pi, "start", judged);
		updateUI(pi, ctx, judged, "judging");
		let verdict: JudgeVerdict;
		try {
			verdict = await judgeGoal(ctx, judged, loadSettings(pi));
		} catch (err) {
			verdict = {
				done: false,
				blocked: false,
				reason: `judge failed: ${(err as Error).message}`,
			};
		}
		if (state !== judged || state.status !== "active") return;
		appendJudge(pi, "verdict", judged, verdict);
		if (isJudgeFailure(verdict)) {
			state = updateGoal(pi, judged, {
				status: "paused",
				lastReason: verdict.reason,
			});
			updateUI(pi, ctx, state);
			syncUpdateGoalTool();
			if (ctx.hasUI)
				ctx.ui.notify(`Goal paused — ${verdict.reason}`, "warning");
			return;
		}
		if (verdict.done) {
			state = updateGoal(pi, judged, {
				status: "complete",
				lastReason: verdict.reason,
			});
			updateUI(pi, ctx, state);
			syncUpdateGoalTool();
			if (ctx.hasUI)
				ctx.ui.notify(`✓ Goal complete: ${verdict.reason}`, "info");
			return;
		}
		if (verdict.blocked) {
			state = updateGoal(pi, judged, {
				status: "blocked",
				lastReason: verdict.reason,
			});
			updateUI(pi, ctx, state);
			syncUpdateGoalTool();
			if (ctx.hasUI)
				ctx.ui.notify(`Goal blocked: ${verdict.reason}`, "warning");
			return;
		}
		const turnsUsed = judged.turnsUsed + 1;
		if (turnsUsed >= judged.maxTurns) {
			state = updateGoal(pi, judged, {
				status: "paused",
				turnsUsed,
				lastReason: `turn budget exhausted: ${verdict.reason}`,
			});
			updateUI(pi, ctx, state);
			syncUpdateGoalTool();
			if (ctx.hasUI)
				ctx.ui.notify(
					`Goal paused — ${turnsUsed}/${judged.maxTurns} turns used`,
					"warning",
				);
			return;
		}
		state = updateGoal(pi, judged, { turnsUsed, lastReason: verdict.reason });
		updateUI(pi, ctx, state);
		syncUpdateGoalTool();
		continuationScheduled.value = true;
		sendWhenIdle(pi, ctx, state, continuationScheduled);
	});

	pi.registerTool({
		name: "update_goal",
		label: "Update Goal",
		description: "Mark the active /goal complete or blocked.",
		promptSnippet:
			"Mark the active /goal complete or blocked after judge review.",
		promptGuidelines: [
			"Use update_goal only after a judge review has run and the active /goal is actually complete or genuinely blocked.",
			"Before update_goal complete, verify the objective and all criteria against current files, tests, commands, or deliverables.",
		],
		parameters: Type.Object({
			status: StringEnum(["complete", "blocked"] as const),
			reason: Type.String(),
		}),
		async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
			if (!state || state.status !== "active")
				throw new Error("No active goal.");
			if (!ownsGoal(ctx, state))
				throw new Error("Goal belongs to another session.");
			if (!canUseUpdateGoal(state))
				throw new Error("Goal has not been judged yet.");
			state = updateGoal(pi, state, {
				status: params.status,
				lastReason: params.reason,
			});
			updateUI(pi, ctx, state);
			syncUpdateGoalTool();
			return {
				content: [
					{
						type: "text",
						text: `Goal marked ${params.status}: ${params.reason}`,
					},
				],
				details: { goal: state },
			};
		},
	});

	pi.registerCommand("goal", {
		description: "Persistent goal loop. Usage: /goal <objective>",
		getArgumentCompletions: (argumentPrefix) =>
			goalArgumentCompletions(argumentPrefix, state),
		handler: (args, ctx) => {
			const input = args.trim();
			const firstSpace = input.search(/\s/);
			const cmd = firstSpace === -1 ? input : input.slice(0, firstSpace);
			const rest = firstSpace === -1 ? "" : input.slice(firstSpace).trim();
			if (!input || cmd === "status") {
				ctx.ui.notify(
					state ? statusLine(state, currentSessionId(ctx)) : "No active goal.",
					state ? "info" : "warning",
				);
				updateUI(pi, ctx, state);
				return;
			}
			if (cmd === "pause") {
				if (!ownedGoalOrNotify(ctx, state)) return;
				if (state.status !== "active")
					return ctx.ui.notify("Goal is not active.", "warning");
				state = updateGoal(pi, state, { status: "paused" });
				updateUI(pi, ctx, state);
				syncUpdateGoalTool();
				ctx.ui.notify("Goal paused", "info");
				return;
			}
			if (cmd === "resume") {
				if (!state) return ctx.ui.notify("No goal to resume.", "warning");
				const rebinding =
					state.sessionId && state.sessionId !== currentSessionId(ctx);
				state = updateGoal(pi, state, {
					status: "active",
					turnsUsed: 0,
					sessionId: currentSessionId(ctx),
				});
				updateUI(pi, ctx, state);
				syncUpdateGoalTool();
				ctx.ui.notify(
					rebinding ? "Goal resumed in this session" : "Goal resumed",
					rebinding ? "warning" : "info",
				);
				continuationScheduled.value = true;
				sendWhenIdle(pi, ctx, state, continuationScheduled);
				return;
			}
			if (cmd === "complete") {
				if (!ownedGoalOrNotify(ctx, state)) return;
				const reason = rest.trim() || "marked complete by user";
				state = updateGoal(pi, state, {
					status: "complete",
					lastReason: reason,
				});
				updateUI(pi, ctx, state);
				syncUpdateGoalTool();
				ctx.ui.notify("Goal complete", "info");
				return;
			}
			if (cmd === "clear") {
				if (!ownedGoalOrNotify(ctx, state)) return;
				state = updateGoal(pi, state, {
					status: "paused",
					lastReason: "cleared",
				});
				state = undefined;
				pi.appendEntry(GOAL_STATE_ENTRY, {
					cleared: true,
					updatedAt: Date.now(),
				});
				updateUI(pi, ctx, state);
				syncUpdateGoalTool();
				ctx.ui.notify("Goal cleared", "info");
				return;
			}
			if (cmd === "add") {
				if (!ownedGoalOrNotify(ctx, state)) return;
				if (!rest.trim())
					return ctx.ui.notify("Usage: /goal add <criterion>", "error");
				state = updateGoal(pi, state, {
					criteria: [...state.criteria, rest.trim()],
				});
				updateUI(pi, ctx, state);
				syncUpdateGoalTool();
				ctx.ui.notify("Goal criterion added", "info");
				return;
			}
			if (cmd === "remove") {
				if (!ownedGoalOrNotify(ctx, state)) return;
				const index = Number(rest.trim()) - 1;
				if (
					!Number.isInteger(index) ||
					index < 0 ||
					index >= state.criteria.length
				)
					return ctx.ui.notify("Usage: /goal remove <n>", "error");
				state = updateGoal(pi, state, {
					criteria: state.criteria.filter((_, i) => i !== index),
				});
				updateUI(pi, ctx, state);
				syncUpdateGoalTool();
				ctx.ui.notify("Goal criterion removed", "info");
				return;
			}
			if (cmd === "criteria") {
				ctx.ui.notify(
					state ? criteriaText(state) : "No active goal.",
					state ? "info" : "warning",
				);
				return;
			}
			if (cmd === "clear-criteria") {
				if (!ownedGoalOrNotify(ctx, state)) return;
				state = updateGoal(pi, state, { criteria: [] });
				updateUI(pi, ctx, state);
				syncUpdateGoalTool();
				ctx.ui.notify("Goal criteria cleared", "info");
				return;
			}
			if (!ctx.isIdle())
				return ctx.ui.notify(
					"Agent is running — use /goal status, pause, resume, complete, clear, add, remove, criteria, or clear-criteria.",
					"warning",
				);
			const settings = loadSettings(pi);
			state = {
				id: crypto.randomUUID(),
				objective: input,
				criteria: [],
				status: "active",
				turnsUsed: 0,
				maxTurns: settings.maxTurns,
				sessionId: currentSessionId(ctx),
				createdAt: Date.now(),
				updatedAt: Date.now(),
			};
			appendGoal(pi, state);
			updateUI(pi, ctx, state);
			syncUpdateGoalTool();
			ctx.ui.notify(`Goal set (${state.maxTurns}-turn budget)`, "info");
			pi.sendUserMessage(kickoffPrompt(state));
		},
	});

	if (process.env.PI_GOAL_PROBE === "1") {
		pi.registerCommand("goal-probe", {
			description: "Internal /goal continuation scheduling probe",
			handler: (args, ctx) => {
				const mode = parseProbeMode(args);
				if (!mode)
					return ctx.ui.notify(
						"Usage: /goal-probe direct|microtask|timeout",
						"error",
					);
				probe = { mode, active: true, scheduled: false, dispatched: false };
				appendProbe(pi, "start", { mode });
				ctx.ui.notify(`goal probe armed: ${mode}`, "info");
			},
		});
	}
}

export const GOAL_PROBE_MESSAGE = PROBE_MESSAGE;
export const GOAL_STATE_CUSTOM_TYPE = GOAL_STATE_ENTRY;
export const __goalTest = {
	activeGoalPrompt,
	continuationPrompt,
	criteriaText,
	goalArgumentCompletions,
	goalBar,
	goalJudgeMessageLine,
	goalWidgetLines,
	insetWidgetLine,
	kickoffPrompt,
	latestAssistantTail,
	latestGoalState,
	cancelGoalRun,
	loadSettings,
	judgeRunningText,
	judgeDisplayReason,
	isJudgeFailure,
	parseJudge,
	parseModelRef,
	extractStandingGoalObjective,
	statusLine,
	statusText,
	textFromContent,
};