repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/ultra/progress.ts
RawFile outline
- ProgressKind line 20
- AgentControls line 29
- steer line 30
- abort line 31
- UltraProgressEvent line 40
- agentId line 41
- phase line 42
- kind line 43
- toolName line 45
- text line 47
- status line 49
- controls line 51
- MAX_PREVIEW line 58
- stringify line 60
- cap line 69
- previewArgs line 74
- previewResult line 84
- content line 87
- details line 87
- mapSessionEvent line 103
- AgentStatus line 152
- AgentRow line 155
- agentId line 156
- phase line 157
- status line 158
- action line 160
- controls line 162
- ProgressMeta line 172
- workflowName line 173
- workflowDescription line 174
- ReducerState line 177
- rows line 178
- transcripts line 180
- phases line 182
- phase line 184
- total line 186
- done line 188
- dropped line 190
- initialReducerState line 194
- DROP_STATUSES line 210
- classifyEnd line 218
- actionLabel line 223
- transcriptText line 231
- nextRow line 244
- reduceProgress line 286
// 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";
// ---------------------------------------------------------------------------
// 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;
/** 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;
/** 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;
}
/** 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));
}
/**
* 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,
text: previewArgs(event.args),
};
case "tool_execution_end":
return {
...base,
kind: "action",
toolName: event.toolName,
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;
/** 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 interface ReducerState extends ProgressMeta {
rows: readonly AgentRow[];
/** agentId -> accumulated transcript (text/thinking deltas + tool action lines). */
transcripts: Readonly<Record<string, string>>;
/** 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: {},
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.text ?? "";
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 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":
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,
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 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,
phases,
phase: event.phase,
total: rows.length,
done,
dropped,
};
}