repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ultra/wire.ts

Raw
File outline
// ultra — wiring helpers (Task 9, offline-testable half).
//
// The pieces of the extension surface that carry real logic but no SDK
// coupling: the tool-surface progress sink (folds engine events with the shared
// reducer and pushes them through `onUpdate`), the `getArgumentCompletions`
// filter, and name-vs-inline spec resolution. `index.ts` is the thin SDK glue
// that wires these to the real `pi.registerTool` / `pi.registerCommand` / `ctx`.

import type { PhaseSlotResult, WorkflowResult } from "./engine.ts";
import {
	initialReducerState,
	type ProgressMeta,
	type ReducerState,
	reduceProgress,
	type UltraProgressEvent,
} from "./progress.ts";
import {
	type DiscoveredWorkflow,
	parseWorkflow,
	type WorkflowSpec,
} from "./spec.ts";

// ---------------------------------------------------------------------------
// Result message formatting
// ---------------------------------------------------------------------------

function record(value: unknown): Record<string, unknown> | undefined {
	return typeof value === "object" && value !== null && !Array.isArray(value)
		? (value as Record<string, unknown>)
		: undefined;
}

function text(value: unknown): string | undefined {
	return typeof value === "string" && value.length > 0 ? value : undefined;
}

function itemLine(value: unknown): string {
	const r = record(value);
	if (!r) return `- ${JSON.stringify(value)}`;
	const title =
		text(r.title) ??
		text(r.summary) ??
		text(r.group) ??
		text(r.name) ??
		text(r.file) ??
		text(r.status) ??
		JSON.stringify(value);
	const file = text(r.file);
	const why = text(r.why) ?? text(r.reason) ?? text(r.detail);
	return `- **${title}**${file && file !== title ? ` — \`${file}\`` : ""}${why ? `\n  ${why}` : ""}`;
}

function resultItems(value: unknown): unknown[] {
	if (Array.isArray(value)) return value;
	return value === undefined || value === null ? [] : [value];
}

interface ReviewReport {
	analysis: string;
	findings: unknown[];
	recommendations: string[];
}

interface ResearchReport {
	answerStatus: string;
	executiveSummary: string;
	analysis: string;
	findings: unknown[];
	contradictions: string[];
	gaps: string[];
	recommendations: string[];
	sources: unknown[];
}

function stringArray(value: unknown): string[] {
	return Array.isArray(value)
		? value.filter(
				(item): item is string => typeof item === "string" && item.length > 0,
			)
		: [];
}

function reviewReport(result: WorkflowResult): ReviewReport | undefined {
	if (result.workflow !== "review") return undefined;
	const items = resultItems(result.result);
	if (items.length !== 1) return undefined;
	const value = record(items[0]);
	const analysis = text(value?.analysis);
	if (!analysis || !Array.isArray(value?.findings)) return undefined;
	const recommendations = Array.isArray(value.recommendations)
		? value.recommendations.filter(
				(recommendation): recommendation is string =>
					typeof recommendation === "string" && recommendation.length > 0,
			)
		: [];
	return { analysis, findings: value.findings, recommendations };
}

function researchReport(result: WorkflowResult): ResearchReport | undefined {
	if (result.workflow !== "research") return undefined;
	const items = resultItems(result.result);
	if (items.length !== 1) return undefined;
	const value = record(items[0]);
	const answerStatus = text(value?.answer_status);
	const executiveSummary = text(value?.executive_summary);
	const analysis = text(value?.analysis);
	if (
		!answerStatus ||
		!executiveSummary ||
		!analysis ||
		!Array.isArray(value?.findings) ||
		!Array.isArray(value.sources)
	)
		return undefined;
	return {
		answerStatus,
		executiveSummary,
		analysis,
		findings: value.findings,
		contradictions: stringArray(value.contradictions),
		gaps: stringArray(value.gaps),
		recommendations: stringArray(value.recommendations),
		sources: value.sources,
	};
}

function researchFindingLine(value: unknown): string {
	const finding = record(value);
	if (!finding) return itemLine(value);
	const claim = text(finding.claim) ?? JSON.stringify(value);
	const evidence = text(finding.evidence);
	const confidence = text(finding.confidence);
	const citations = stringArray(finding.citations);
	return [
		`- **${claim}**${confidence ? ` [${confidence}]` : ""}`,
		...(evidence ? [`  ${evidence}`] : []),
		...(citations.length > 0 ? [`  Sources: ${citations.join(", ")}`] : []),
	].join("\n");
}

function researchSourceLine(value: unknown): string {
	const source = record(value);
	if (!source) return itemLine(value);
	const title = text(source.title) ?? "Untitled source";
	const url = text(source.url);
	const sourceType = text(source.source_type);
	const publishedAt = text(source.published_at);
	const metadata = [sourceType, publishedAt].filter(Boolean).join(" · ");
	return `- **${title}**${metadata ? ` (${metadata})` : ""}${url ? ` — ${url}` : ""}`;
}

function refutedSlots(result: WorkflowResult): PhaseSlotResult[] {
	return Object.values(result.phaseResults)
		.flat()
		.filter((slot) => {
			const v = record(slot.value);
			return slot.ok && v?.real === false;
		});
}

function compactFailureMessage(message: string): string {
	return message.length > 160 ? `${message.slice(0, 159)}…` : message;
}

function dropLines(result: WorkflowResult, expanded: boolean): string[] {
	const lines: string[] = [];
	for (const failures of Object.values(result.phaseFailures)) {
		for (const failure of failures) {
			const message = expanded
				? failure.message
				: compactFailureMessage(failure.message);
			lines.push(`- ${failure.agentId} [${failure.code}]: ${message}`);
			if (!expanded) continue;
			lines.push(
				`  retryable: ${failure.retryable ? "yes" : "no"}`,
				`  attempts: ${failure.attempts}`,
			);
			if (failure.model) lines.push(`  model: ${failure.model}`);
			if (failure.thinkingLevel)
				lines.push(`  thinking: ${failure.thinkingLevel}`);
			if (failure.item !== undefined)
				lines.push(`  item: ${JSON.stringify(failure.item)}`);
			if (failure.transcriptTail)
				lines.push(
					`  transcript tail: ${JSON.stringify(failure.transcriptTail)}`,
				);
		}
	}
	return lines;
}

function usageLine(result: WorkflowResult): string | undefined {
	const usage = result.tokenUsage;
	if (!usage || usage.total === 0) return undefined;
	const cost = usage.cost > 0 ? ` · $${usage.cost.toFixed(4)}` : "";
	return `Usage: ${usage.total} tokens (${usage.input} in, ${usage.output} out)${cost}`;
}

function plural(count: number, singular: string): string {
	return `${count} ${singular}${count === 1 ? "" : "s"}`;
}

function summaryLine(
	result: WorkflowResult,
	finalCount: number,
	refutedCount: number,
	droppedCount: number,
): string {
	const incomplete =
		droppedCount > 0
			? ` Review incomplete: ${plural(droppedCount, "step")} dropped.`
			: "";
	if (result.workflow === "review") {
		const findings =
			finalCount === 0
				? "No verified findings."
				: `${plural(finalCount, "verified finding")}.`;
		const refuted =
			refutedCount > 0
				? ` ${plural(refutedCount, "candidate finding")} refuted.`
				: "";
		return `${findings}${refuted}${incomplete}`;
	}
	return `${plural(finalCount, "final result")}.${incomplete}`;
}

function recommendationLines(
	result: WorkflowResult,
	finalCount: number,
	droppedCount: number,
): string[] {
	if (result.workflow === "review") {
		if (droppedCount > 0)
			return [
				"- Inspect dropped steps and rerun review before relying on the result.",
			];
		if (finalCount > 0)
			return ["- Address verified findings, then rerun review."];
		return [
			"- No code changes recommended from this review.",
			"- Continue normal project validation.",
		];
	}
	if (droppedCount > 0)
		return ["- Inspect dropped steps and rerun the workflow."];
	if (finalCount > 0) return ["- Continue with the final results above."];
	return ["- No follow-up action indicated."];
}

export function formatUltraResultMarkdown(
	result: WorkflowResult,
	expanded = false,
): string {
	const report = reviewReport(result);
	const research = researchReport(result);
	const finalItems =
		report?.findings ?? research?.findings ?? resultItems(result.result);
	const lines = [
		`# ultra ${result.workflow}${result.steered ? " (steered)" : ""}`,
	];
	lines.push("");
	lines.push(
		result.phases
			.map((p) => `${p.id}: ${p.ok}/${p.ran} ok, ${p.dropped} dropped`)
			.join(" · ") || "No phases.",
	);
	const usage = usageLine(result);
	if (usage) lines.push(usage);
	lines.push("");

	const refuted = refutedSlots(result);
	const droppedCount = result.phases.reduce(
		(total, phase) => total + phase.dropped,
		0,
	);
	if (report) lines.push("## Analysis", report.analysis, "");
	else if (research)
		lines.push(
			"## Answer",
			research.executiveSummary,
			`Status: ${research.answerStatus}`,
			"",
			"## Analysis",
			research.analysis,
			"",
		);
	else
		lines.push(
			"## Summary",
			summaryLine(result, finalItems.length, refuted.length, droppedCount),
			"",
		);

	if (finalItems.length > 0) {
		lines.push(
			result.workflow === "review"
				? "## Verified findings"
				: research
					? "## Findings"
					: "## Final results",
			...(research
				? finalItems.map(researchFindingLine)
				: finalItems.map(itemLine)),
			"",
		);
	}

	if (refuted.length > 0) {
		lines.push(
			"## Refuted findings",
			...refuted.map((s) => itemLine(s.value)),
			"",
		);
	}

	if (research?.contradictions.length)
		lines.push(
			"## Contradictions",
			...research.contradictions.map((item) => `- ${item}`),
			"",
		);
	if (research?.gaps.length)
		lines.push(
			"## Research gaps",
			...research.gaps.map((item) => `- ${item}`),
			"",
		);

	const drops = dropLines(result, expanded);
	if (drops.length > 0) lines.push("## Drops", ...drops, "");
	lines.push(
		"## Recommendations",
		...(report?.recommendations.length
			? report.recommendations.map((recommendation) => `- ${recommendation}`)
			: research?.recommendations.length
				? research.recommendations.map(
						(recommendation) => `- ${recommendation}`,
					)
				: recommendationLines(result, finalItems.length, droppedCount)),
		"",
	);
	if (research?.sources.length)
		lines.push("## Sources", ...research.sources.map(researchSourceLine), "");

	if (expanded)
		lines.push(
			"## Raw JSON",
			"```json",
			JSON.stringify(result, null, 2),
			"```",
		);
	return lines.join("\n").trimEnd();
}

export function formatWorkflowResultMessage(result: WorkflowResult): string {
	if (result.workflow === "review" || result.workflow === "research")
		return formatUltraResultMarkdown(result);
	return [
		`ultra workflow "${result.workflow}" result${result.steered ? " (steered)" : ""}:`,
		"```json",
		JSON.stringify(result, null, 2),
		"```",
	].join("\n");
}

// ---------------------------------------------------------------------------
// Tool-surface progress sink
// ---------------------------------------------------------------------------

/** The minimal `AgentToolResult` shape `onUpdate` consumes; `renderResult`
 * reads `details` (validated P2). */
export interface ToolUpdate {
	content: { type: "text"; text: string }[];
	details: ReducerState;
}

/** One-line fallback summary (the live board is drawn from `details` by
 * `renderResult`; this `content` is just the textual fallback). */
function summarize(state: ReducerState): string {
	const phase = state.phase ? `${state.phase}: ` : "";
	return [
		`${phase}${state.done}/${state.total} done`,
		state.running ? `${state.running} active` : "",
		state.queued ? `${state.queued} queued` : "",
		state.later ? `${state.later} later` : "",
		state.dropped ? `${state.dropped} dropped` : "",
	]
		.filter(Boolean)
		.join(", ");
}

/**
 * Build the `workflow` tool's progress sink: each engine `onProgress` event is
 * folded with the shared reducer and pushed through `onUpdate` as the full
 * `AgentToolResult` shape (so `renderResult` can read fresh `details` every
 * tick). `getState` exposes the accumulated board for the final tool return.
 */
export function makeToolProgressSink(
	onUpdate: (update: ToolUpdate) => void,
	meta: ProgressMeta = {},
): {
	sink: (event: UltraProgressEvent) => void;
	finish: (result: WorkflowResult) => ReducerState;
	getState: () => ReducerState;
} {
	let state = initialReducerState(meta);
	return {
		sink: (event) => {
			// Strip `controls` before folding: the tool surface ignores them, and
			// Pi STRUCTURED-CLONES the `details` it receives (both per-tick via
			// `onUpdate` and the final tool result). `controls` are functions —
			// incl. the runner's `NOOP_CONTROLS` on the tool-less `complete()`
			// path — so leaving them in throws "The object can not be cloned.",
			// which propagates back into every step that emitted an event and
			// fails the whole run. Only the command overlay (never serialized)
			// keeps controls.
			const safe =
				"agentId" in event
					? { ...event, controls: undefined, prompt: undefined }
					: event;
			state = reduceProgress(state, safe);
			onUpdate({
				content: [{ type: "text", text: summarize(state) }],
				details: state,
			});
		},
		finish: (result) => {
			state = { ...state, workflowResult: result };
			return state;
		},
		getState: () => state,
	};
}

// ---------------------------------------------------------------------------
// Argument completions
// ---------------------------------------------------------------------------

/** Mirrors the SDK `AutocompleteItem` (angel/index.ts:791). */
export interface AutocompleteItem {
	value: string;
	label: string;
	description?: string;
}

/** Filter discovered workflow names by a (case-insensitive) prefix; `null` when
 * nothing matches (the SDK convention for "no completions"). */
export function completeWorkflowNames(
	discovered: readonly DiscoveredWorkflow[],
	prefix: string,
): AutocompleteItem[] | null {
	const p = prefix.toLowerCase();
	const items = discovered
		.filter((w) => w.name.toLowerCase().startsWith(p))
		.map((w) => ({ value: w.name, label: w.name, description: w.source }));
	return items.length > 0 ? items : null;
}

const ULTRA_SUBCOMMANDS: AutocompleteItem[] = [
	{
		value: "exec",
		label: "exec",
		description: "execute instructions through an authored workflow",
	},
	{
		value: "run",
		label: "run",
		description: "run a saved workflow",
	},
];

export function completeUltraCommand(
	discovered: readonly DiscoveredWorkflow[],
	prefix: string,
): AutocompleteItem[] | null {
	const input = prefix.trimStart();
	if (!/\s/.test(input)) {
		const p = input.toLowerCase();
		const items = ULTRA_SUBCOMMANDS.filter((item) => item.value.startsWith(p));
		return items.length > 0 ? items : null;
	}
	const match = input.match(/^run\s+(.*)$/i);
	if (!match) return null;
	const workflows = completeWorkflowNames(discovered, match[1]);
	return (
		workflows?.map((item) => ({
			...item,
			value: `run ${item.value}`,
		})) ?? null
	);
}

export type UltraCommand =
	| { subcommand: "activate" }
	| { subcommand: "exec"; instructions: string }
	| { subcommand: "run"; invocation: string }
	| { subcommand: "invalid" };

export function parseUltraCommand(raw: string): UltraCommand {
	const input = raw.trim();
	if (!input) return { subcommand: "activate" };
	const space = input.search(/\s/);
	const subcommand = space === -1 ? input : input.slice(0, space);
	const rest = space === -1 ? "" : input.slice(space + 1).trim();
	if (subcommand === "exec" && rest)
		return { subcommand: "exec", instructions: rest };
	if (subcommand === "run" && rest)
		return { subcommand: "run", invocation: rest };
	return { subcommand: "invalid" };
}

// ---------------------------------------------------------------------------
// Spec resolution
// ---------------------------------------------------------------------------

/** The `workflow` tool / `/ultra run` command input. */
export interface WorkflowInput {
	name?: string;
	spec?: unknown;
	args?: Record<string, unknown>;
}

/**
 * Parse a raw `/ultra run <name> [args]` invocation: the first whitespace token is
 * the workflow name; the remainder is either a trailing JSON object (used as the
 * run args directly) or bare text returned verbatim as `rest` for positional
 * mapping against the spec's declared `args.params` (see `mapPositionalArgs`).
 * The name always resolves regardless of the remainder's shape.
 */
export function parseCommandLine(raw: string): {
	name?: string;
	args?: Record<string, unknown>;
	rest?: string;
} {
	const trimmed = raw.trim();
	if (!trimmed) return {};
	const space = trimmed.search(/\s/);
	if (space === -1) return { name: trimmed };
	const name = trimmed.slice(0, space);
	const rest = trimmed.slice(space + 1).trim();
	if (!rest) return { name };
	try {
		const parsed = JSON.parse(rest);
		if (
			parsed !== null &&
			typeof parsed === "object" &&
			!Array.isArray(parsed)
		) {
			return { name, args: parsed as Record<string, unknown>, rest };
		}
	} catch {
		// non-JSON trailing text → kept as `rest` for positional mapping
	}
	return { name, rest };
}

/**
 * Map a bare command-line remainder to named args using a workflow's declared
 * positional `params`: whitespace-split tokens fill `params` in order, and the
 * last declared param soaks any remaining tokens so a trailing free-text arg
 * (e.g. a feature description) survives intact. Returns `undefined` when nothing
 * maps (empty remainder or no declared params). Only `/ultra run` uses
 * this — the `workflow` tool passes a structured `args` object directly.
 */
export function mapPositionalArgs(
	rest: string,
	params: readonly string[],
): Record<string, unknown> | undefined {
	const tokens = rest.trim().split(/\s+/).filter(Boolean);
	if (tokens.length === 0 || params.length === 0) return undefined;
	const out: Record<string, unknown> = {};
	params.forEach((name, i) => {
		if (i >= tokens.length) return;
		// The last declared param soaks the remaining tokens so a trailing
		// free-text arg (e.g. a feature description) survives intact; earlier
		// params take exactly one token each.
		out[name] = i === params.length - 1 ? tokens.slice(i).join(" ") : tokens[i];
	});
	return Object.keys(out).length > 0 ? out : undefined;
}

/** Resolved run input: a validated spec + its run args. */
export interface ResolvedWorkflow {
	spec: WorkflowSpec;
	args?: Record<string, unknown>;
}

/**
 * Resolve a run request to a validated spec. An inline `spec` (ephemeral mode)
 * wins and is parsed/validated; otherwise a `name` (persisted mode) is looked up
 * among discovered workflows. Throws on an unknown name, a malformed inline
 * spec, or neither being supplied.
 */
export function resolveWorkflowInput(
	input: WorkflowInput,
	discovered: readonly DiscoveredWorkflow[],
	rest?: string,
): ResolvedWorkflow {
	if (input.spec !== undefined) {
		return { spec: parseWorkflow(input.spec), args: input.args };
	}
	if (input.name) {
		const found = discovered.find((w) => w.name === input.name);
		if (!found) {
			const known = discovered.map((w) => w.name).join(", ") || "(none)";
			throw new Error(
				`ultra: unknown workflow "${input.name}". Available: ${known}.`,
			);
		}
		// Validate the discovered spec at resolve time (not at discovery, so a
		// malformed file still lists in the picker) — `/ultra run <name>` then fails
		// fast with parseWorkflow's TypeBox path error instead of crashing the
		// engine mid-run on a raw, unvalidated object.
		const spec = parseWorkflow(found.spec);
		let args = input.args;
		// Positional fallback: a bare `/ultra run <name> <tok...>` line (no JSON args
		// object) maps to the spec's declared `args.params` in order.
		if (args === undefined && rest && spec.args?.params?.length) {
			args = mapPositionalArgs(rest, spec.args.params);
		}
		return { spec, args };
	}
	throw new Error(
		'ultra: provide either a workflow "name" or an inline "spec".',
	);
}