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.file) ?? 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];
}

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 dropLines(result: WorkflowResult): string[] {
	const lines: string[] = [];
	for (const [phase, slots] of Object.entries(result.phaseResults)) {
		slots.forEach((slot, i) => {
			if (!slot.ok) lines.push(`- ${phase}#${i}: ${slot.reason ?? "dropped"}`);
		});
	}
	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}`;
}

export function formatUltraResultMarkdown(
	result: WorkflowResult,
	expanded = false,
): string {
	const finalItems = 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("");

	if (finalItems.length > 0) {
		lines.push("## Final results", ...finalItems.map(itemLine), "");
	} else {
		lines.push(
			"## No final results",
			"No items survived the workflow return selector.",
			"",
		);
	}

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

	const drops = dropLines(result);
	if (drops.length > 0) lines.push("## Drops", ...drops, "");

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

export function formatWorkflowResultMessage(result: WorkflowResult): string {
	const empty = Array.isArray(result.result) && result.result.length === 0;
	return [
		`ultra workflow "${result.workflow}" result${result.steered ? " (steered)" : ""}:`,
		empty
			? "\nResult is empty: no items survived the workflow return selector."
			: "",
		"```json",
		JSON.stringify(result, null, 2),
		"```",
	]
		.filter(Boolean)
		.join("\n");
}

export function formatBackgroundAcceptedMessage(
	runId: string,
	workflowName: string,
): string {
	return `ultra background run "${workflowName}" started: ${runId}`;
}

export function formatBackgroundResultMessage(
	runId: string,
	result: WorkflowResult,
): string {
	return [
		`ultra background run "${result.workflow}" complete: ${runId}`,
		formatWorkflowResultMessage(result),
	].join("\n\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.dropped ? `, ${state.dropped} dropped` : ""}`;
}

/**
 * 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;
	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.
			state = reduceProgress(state, { ...event, controls: undefined });
			onUpdate({
				content: [{ type: "text", text: summarize(state) }],
				details: 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;
}

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

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

/**
 * Parse a raw `/ultra <name> [args]` command line: 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 the `/ultra` command 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 <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 <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".',
	);
}