repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ultra/progress.ts

Raw
File outline
// ultra — live progress: pure event types, session-event mapping, and a shared
// board/transcript reducer (Task 7a). NO SDK *session* is ever constructed
// here; only the `AgentSessionEvent` *type* is imported. Both `runner.ts`
// (emits these events + binds `controls`) and `ui.ts` (folds them with the
// reducer and renders) import from this module, so the names are the contract.
//
// Field paths read from `AgentSessionEvent` are the ones validated against a
// real Pi + MiniMax run (prototypes P1/P4): streaming text arrives on
// `event.assistantMessageEvent` as `{ type: "text_delta", delta }` during
// `message_update` (NOT `event.message.content`, which is empty mid-stream); a
// terminating tool's structured payload is on `tool_execution_end.result.details`.

import type { AgentSessionEvent } from "@earendil-works/pi-coding-agent";
import type { TokenUsage } from "./runner.ts";
import type { ThinkingLevel } from "./spec.ts";

// ---------------------------------------------------------------------------
// Event types (the `deps.onProgress` contract — design line 242)
// ---------------------------------------------------------------------------

/** Lifecycle stage of a single mapped progress event. */
export type ProgressKind = "start" | "action" | "delta" | "end";

/**
 * Live control surface for one running sub-agent. Bound by the runner (which
 * owns the session); no-ops for tool-less `complete()` steps. Only the command
 * overlay acts on these — the tool surface ignores `controls`. The methods may
 * be sync or async (`session.steer`/`session.abort` return promises that the
 * runner must `await`/`.catch()` to avoid floating rejections).
 */
export interface AgentControls {
	steer(text: string): Promise<void> | void;
	abort(): Promise<void> | void;
}

/**
 * A single progress event forwarded through `deps.onProgress`. Produced by
 * `mapSessionEvent` (for tool-using steps' session events) or constructed
 * directly by the runner/engine (coarse start/end, dropped items). `controls`
 * is attached by the runner, never by `mapSessionEvent`.
 */
export interface UltraProgressEvent {
	agentId: string;
	phase: string;
	kind: ProgressKind;
	/** Tool name for `action` events (tool start/end). */
	toolName?: string;
	/** Tool call id for native tool rendering. */
	toolCallId?: string;
	/** Raw tool args for native tool rendering. */
	args?: unknown;
	/** Raw tool result for native tool rendering. */
	result?: unknown;
	isError?: boolean;
	/** Streamed delta text, a tool action/result preview, or a coarse status line. */
	text?: string;
	/** Terminal/error marker: `end` carries the run outcome; `action` may carry `"error"`. */
	status?: string;
	/** Requested model tier before resolution. */
	tier?: string;
	/** Resolved provider/model label. */
	model?: string;
	thinkingLevel?: ThinkingLevel;
	startedAt?: number;
	usage?: TokenUsage;
	/** Per-agent live controls (runner-bound; absent on the tool surface). */
	controls?: AgentControls;
}

// ---------------------------------------------------------------------------
// mapSessionEvent — pure AgentSessionEvent -> UltraProgressEvent
// ---------------------------------------------------------------------------

const MAX_PREVIEW = 120;

function stringify(value: unknown): string {
	if (typeof value === "string") return value;
	try {
		return JSON.stringify(value) ?? String(value);
	} catch {
		return String(value);
	}
}

function cap(text: string): string {
	return text.length > MAX_PREVIEW ? `${text.slice(0, MAX_PREVIEW)}…` : text;
}

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

/** Short preview of a tool call's args for the board/transcript. */
function previewArgs(args: unknown): string {
	if (args === undefined || args === null) return "";
	return cap(stringify(args));
}

function firstLine(value: unknown): string | undefined {
	return typeof value === "string" ? value.split("\n")[0]?.trim() : undefined;
}

function conciseArgs(toolName: string | undefined, args: unknown): string {
	if (!toolName || !isRecord(args)) return previewArgs(args);
	switch (toolName) {
		case "bash": {
			const command = firstLine(args.command);
			return command ? `$ ${cap(command)}` : previewArgs(args);
		}
		case "read":
		case "ls":
			return firstLine(args.path) ?? previewArgs(args);
		case "grep": {
			const pattern = firstLine(args.pattern);
			const path = firstLine(args.path);
			if (pattern && path) return `${pattern} in ${path}`;
			return pattern ?? path ?? previewArgs(args);
		}
		case "find": {
			const pattern = firstLine(args.pattern);
			const path = firstLine(args.path);
			if (pattern && path) return `${pattern} in ${path}`;
			return pattern ?? path ?? previewArgs(args);
		}
		case "structured_output":
			return structuredOutputSummary(args);
		default:
			return previewArgs(args);
	}
}

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

function structuredOutputSummary(value: Record<string, unknown>): string {
	if (Array.isArray(value.findings))
		return plural(value.findings.length, "finding");
	if (typeof value.real === "boolean") {
		const title = firstLine(value.title);
		return title ? `real=${value.real} · ${cap(title)}` : `real=${value.real}`;
	}
	const keys = Object.keys(value);
	return keys.length > 0 ? `returned ${keys.join(", ")}` : "returned output";
}

/**
 * Short preview of a tool result. Prefers `result.details` — the validated
 * structured-output payload path (P1) — falling back to `result.content`, then
 * the whole result.
 */
function previewResult(result: unknown): string {
	if (result === undefined || result === null) return "";
	if (typeof result === "object") {
		const r = result as { details?: unknown; content?: unknown };
		if (r.details !== undefined && r.details !== null)
			return cap(stringify(r.details));
		if (r.content !== undefined && r.content !== null)
			return cap(stringify(r.content));
	}
	return cap(stringify(result));
}

/**
 * Map one Pi `AgentSessionEvent` to an `UltraProgressEvent`, stamping it with
 * the owning agent id + phase. Returns `null` for events outside the live-board
 * vocabulary (turn boundaries, message start/end, compaction, queue, etc.).
 * Pure: reads only the validated field paths; never constructs a session and
 * never attaches `controls`.
 */
export function mapSessionEvent(
	event: AgentSessionEvent,
	agentId: string,
	phase: string,
): UltraProgressEvent | null {
	const base = { agentId, phase } as const;

	switch (event.type) {
		case "agent_start":
			return { ...base, kind: "start" };

		case "tool_execution_start":
			return {
				...base,
				kind: "action",
				toolName: event.toolName,
				toolCallId: event.toolCallId,
				args: event.args,
				text: previewArgs(event.args),
			};

		case "tool_execution_end":
			return {
				...base,
				kind: "action",
				toolName: event.toolName,
				toolCallId: event.toolCallId,
				result: event.result,
				isError: event.isError,
				text: previewResult(event.result),
				status: event.isError ? "error" : undefined,
			};

		case "message_update": {
			const inner = event.assistantMessageEvent;
			if (inner.type === "text_delta" || inner.type === "thinking_delta") {
				return { ...base, kind: "delta", text: inner.delta };
			}
			return null;
		}

		case "agent_end":
			return { ...base, kind: "end", status: "done" };

		default:
			return null;
	}
}

// ---------------------------------------------------------------------------
// Reducer — folds an UltraProgressEvent stream into board + transcript state
// ---------------------------------------------------------------------------

/** Terminal classification of a board row. */
export type AgentStatus = "running" | "done" | "dropped";

/** One live board row: an agent's status + its latest action. */
export interface AgentRow {
	agentId: string;
	phase: string;
	status: AgentStatus;
	/** Latest coarse action ("read a.ts", "grep …") — never the streamed body. */
	action: string;
	tier?: string;
	model?: string;
	thinkingLevel?: ThinkingLevel;
	startedAt?: number;
	usage?: TokenUsage;
	/** Live controls (command overlay only); absent on tool-less / tool-surface rows. */
	controls?: AgentControls;
}

/**
 * Folded view of a run, consumed by both `ui.ts` sinks.
 *
 * `total` is agents-*seen* (rows grow as agents launch), not the fanout width —
 * the width is not derivable from a pure event stream, so a freshly-queued
 * agent is not yet counted until its first event arrives.
 */
export interface ProgressMeta {
	workflowName?: string;
	workflowDescription?: string;
}

export type TranscriptItem =
	| { kind: "text"; text: string }
	| {
			kind: "tool";
			toolName: string;
			toolCallId?: string;
			args?: unknown;
			result?: unknown;
			isError?: boolean;
			fallback: string;
	  };

export interface ReducerState extends ProgressMeta {
	rows: readonly AgentRow[];
	/** agentId -> accumulated transcript (text/thinking deltas + tool action lines). */
	transcripts: Readonly<Record<string, string>>;
	transcriptItems: Readonly<Record<string, readonly TranscriptItem[]>>;
	/** Distinct phase ids in arrival order — the phase counter (`phase N/len`). */
	phases: readonly string[];
	/** Current (latest-seen) phase id. */
	phase: string | undefined;
	/** Agents seen so far. */
	total: number;
	/** Agents that ended successfully. */
	done: number;
	/** Agents that ended dropped/failed. */
	dropped: number;
}

/** A fresh, empty reducer state. */
export function initialReducerState(meta: ProgressMeta = {}): ReducerState {
	return {
		workflowName: meta.workflowName,
		workflowDescription: meta.workflowDescription,
		rows: [],
		transcripts: {},
		transcriptItems: {},
		phases: [],
		phase: undefined,
		total: 0,
		done: 0,
		dropped: 0,
	};
}

// Statuses on an `end` event that mean the agent did not produce a usable
// result. Anything else (incl. "done"/undefined on an `end`) counts as done.
const DROP_STATUSES = new Set([
	"dropped",
	"error",
	"aborted",
	"timeout",
	"failed",
]);

function classifyEnd(status: string | undefined): AgentStatus {
	return status !== undefined && DROP_STATUSES.has(status) ? "dropped" : "done";
}

/** The coarse board label for an `action` event. */
function actionLabel(event: UltraProgressEvent): string {
	const text =
		event.args !== undefined
			? conciseArgs(event.toolName, event.args)
			: (event.text ?? "");
	if (event.toolName === "structured_output")
		return text ? `structured output · ${text}` : "structured output";
	if (event.toolName)
		return text ? `${event.toolName} ${text}` : event.toolName;
	return text;
}

/** Text contributed to the per-agent transcript by this event (may be empty). */
function transcriptText(event: UltraProgressEvent): string {
	switch (event.kind) {
		case "delta":
			return event.text ?? "";
		case "action": {
			const label = actionLabel(event);
			return label ? `\n\n> ${label}\n\n` : "";
		}
		default:
			return event.text ?? "";
	}
}

function transcriptItem(event: UltraProgressEvent): TranscriptItem | undefined {
	if (event.kind === "delta") return { kind: "text", text: event.text ?? "" };
	if (event.kind !== "action" || !event.toolName) return undefined;
	const fallback = actionLabel(event);
	return {
		kind: "tool",
		toolName: event.toolName,
		toolCallId: event.toolCallId,
		args: event.args,
		result: event.result,
		isError: event.isError,
		fallback,
	};
}

function nextRow(
	prev: AgentRow | undefined,
	event: UltraProgressEvent,
): AgentRow {
	const base: AgentRow = prev ?? {
		agentId: event.agentId,
		phase: event.phase,
		status: "running",
		action: "",
	};
	let status = base.status;
	let action = base.action;
	switch (event.kind) {
		case "start":
			status = "running";
			break;
		case "action":
			if (event.result === undefined || event.isError)
				action = actionLabel(event) || action;
			break;
		case "delta":
			// Token deltas feed the transcript, not the board's latest-action line.
			break;
		case "end":
			status = classifyEnd(event.status);
			break;
	}
	return {
		agentId: event.agentId,
		phase: event.phase,
		status,
		action,
		tier: event.tier ?? base.tier,
		model: event.model ?? base.model,
		thinkingLevel: event.thinkingLevel ?? base.thinkingLevel,
		startedAt: event.startedAt ?? base.startedAt,
		usage: event.usage ?? base.usage,
		controls: event.controls ?? base.controls,
	};
}

/**
 * Pure reducer: fold one `UltraProgressEvent` into the board/transcript state,
 * returning a NEW state. Rows are upserted by `agentId` (idempotent — a later
 * event updates the row in place, never appends); unchanged rows keep their
 * reference identity so `ui.ts` can memoize. Tallies are recomputed from row
 * statuses, so re-applying an event can never double-count.
 */
export function reduceProgress(
	state: ReducerState,
	event: UltraProgressEvent,
): ReducerState {
	const idx = state.rows.findIndex((r) => r.agentId === event.agentId);
	const prev = idx >= 0 ? state.rows[idx] : undefined;
	const row = nextRow(prev, event);
	const rows =
		idx >= 0
			? state.rows.map((r, i) => (i === idx ? row : r))
			: [...state.rows, row];

	const added = transcriptText(event);
	const transcripts = added
		? {
				...state.transcripts,
				[event.agentId]: (state.transcripts[event.agentId] ?? "") + added,
			}
		: state.transcripts;

	const item = transcriptItem(event);
	const transcriptItems = item
		? {
				...state.transcriptItems,
				[event.agentId]: [
					...(state.transcriptItems[event.agentId] ?? []),
					item,
				],
			}
		: state.transcriptItems;

	const phases = state.phases.includes(event.phase)
		? state.phases
		: [...state.phases, event.phase];

	let done = 0;
	let dropped = 0;
	for (const r of rows) {
		if (r.status === "done") done++;
		else if (r.status === "dropped") dropped++;
	}

	return {
		workflowName: state.workflowName,
		workflowDescription: state.workflowDescription,
		rows,
		transcripts,
		transcriptItems,
		phases,
		phase: event.phase,
		total: rows.length,
		done,
		dropped,
	};
}