repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(ultra): expand agent metadata rows

df437242cb67c43669de2693b6a7d86da6d98426

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (7)

+218 / −17 text lines

Diff layout

extensions/ultra/README.md

Modified

+3 / −0 text lines

6565If a run is aborted, the next run of the same workflow name, cwd, and args reuses completed matching steps and runs the missing/changed steps.
6666A completed run marks its journal complete, so later runs start fresh.
68Expanded workflow tool output renders each sub-agent as a multiline block: identity/status, resolved model metadata, elapsed time and reported tokens, then latest action.
69Configured tiers are shown as `tier → provider/model`; collapsed output remains summary-only.
6871Workflow results include aggregate token and cost usage from completed sub-agent turns when the provider reports it.
6972The final JSON contains `tokenUsage` with `input`, `output`, `total`, `cacheRead`, `cacheWrite`, and `cost`.

extensions/ultra/__tests__/progress.test.ts

Modified

+32 / −0 text lines

267267 expect(s.phase).toBe("verify");
268268 });
270 it("retains model, timing, and usage metadata across later events", () => {
271 const usage = {
272 input: 100,
273 output: 20,
274 total: 120,
275 cacheRead: 10,
276 cacheWrite: 0,
277 cost: 0.1,
278 };
279 const s = fold([
280 pe({
281 agentId: "a",
282 phase: "p1",
283 kind: "start",
284 tier: "small",
285 model: "openai/gpt-5-mini",
286 thinkingLevel: "low",
287 startedAt: 1000,
288 }),
289 pe({ agentId: "a", phase: "p1", kind: "delta", text: "x" }),
290 pe({ agentId: "a", phase: "p1", kind: "end", status: "done", usage }),
291 ]);
293 expect(s.rows[0]).toMatchObject({
294 tier: "small",
295 model: "openai/gpt-5-mini",
296 thinkingLevel: "low",
297 startedAt: 1000,
298 usage,
299 });
300 });
270302 it("binds per-agent controls from the event onto the row", () => {
271303 const controls: AgentControls = { steer: vi.fn(), abort: vi.fn() };
272304 const s = fold([

extensions/ultra/__tests__/runner.test.ts

Modified

+25 / −4 text lines

417417 expect(result.reason).toBe("completion failed: socket hang up");
418418 });
420 it("emits coarse start/end with no-op controls", async () => {
420 it("emits coarse start/end with model metadata, usage, and no-op controls", async () => {
421 const usage = {
422 input: 10,
423 output: 5,
424 totalTokens: 15,
425 cacheRead: 0,
426 cacheWrite: 0,
427 cost: { total: 0.1 },
428 };
421429 const completeFn = vi.fn(
422 async (): Promise<CompleteResponse> => ({ text: '{ "verdict": "ok" }' }),
430 async (): Promise<CompleteResponse> => ({
431 text: '{ "verdict": "ok" }',
432 usage,
433 }),
423434 );
424435 const drivers = makeDrivers({ completeFn });
425436 const events: UltraProgressEvent[] = [];
427438 const result = await runStep(
428 toollessStep,
439 { ...toollessStep, model: "small" },
429440 makeCtx(),
430441 drivers,
431 baseOpts({ onProgress: (e) => events.push(e) }),
442 baseOpts({
443 modelTiers: { small: "openai/gpt-5-mini:low" },
444 onProgress: (e) => events.push(e),
445 }),
432446 );
434448 expect(result.ok).toBe(true);
435449 expect(events.map((e) => e.kind)).toEqual(["start", "end"]);
450 expect(events[0]).toMatchObject({
451 tier: "small",
452 model: "openai/gpt-5-mini",
453 thinkingLevel: "low",
454 startedAt: expect.any(Number),
455 });
456 expect(events[1].usage).toEqual(result.usage);
436457 for (const e of events) {
437458 expect(e.agentId).toBe("review#0");
438459 expect(e.phase).toBe("review");

extensions/ultra/__tests__/ui.test.ts

Modified

+45 / −0 text lines

173173 expect(out).not.toContain("SECRET-TRANSCRIPT-BODY");
174174 });
176 it("expanded: renders each agent as identity plus model, usage, and action lines", () => {
177 const s = stateFrom([
178 pe({
179 agentId: "plan#0",
180 phase: "plan",
181 kind: "start",
182 tier: "small",
183 model: "openai/gpt-5-mini",
184 thinkingLevel: "low",
185 startedAt: Date.now() - 18_000,
186 }),
187 pe({
188 agentId: "plan#0",
189 phase: "plan",
190 kind: "action",
191 toolName: "read",
192 text: "docs/phase-1.html",
193 }),
194 pe({
195 agentId: "plan#0",
196 phase: "plan",
197 kind: "end",
198 status: "done",
199 usage: {
200 input: 1800,
201 output: 300,
202 total: 2100,
203 cacheRead: 0,
204 cacheWrite: 0,
205 cost: 0,
206 },
207 }),
208 ]);
209 const lines = renderTool(s, { expanded: true, isPartial: false }, 100);
210 const out = lines.join("\n");
212 expect(out).toContain("plan#0 · done");
213 expect(out).toContain("├ model");
214 expect(out).toContain("small → openai/gpt-5-mini · low");
215 expect(out).toContain("├ usage");
216 expect(out).toContain("2.1k tokens");
217 expect(out).toContain("└ action");
218 expect(out).toContain("read docs/phase-1.html");
219 });
176221 it("never emits bodies when expanded=false (sentinels absent collapsed, present expanded)", () => {
177222 const collapsed = toolText(scripted, { expanded: false, isPartial: false });
178223 const expanded = toolText(scripted, { expanded: true, isPartial: false });

extensions/ultra/progress.ts

Modified

+19 / −0 text lines

1111// terminating tool's structured payload is on `tool_execution_end.result.details`.
1313import type { AgentSessionEvent } from "@earendil-works/pi-coding-agent";
14import type { TokenUsage } from "./runner.ts";
15import type { ThinkingLevel } from "./spec.ts";
1517// ---------------------------------------------------------------------------
1618// Event types (the `deps.onProgress` contract — design line 242)
5456 text?: string;
5557 /** Terminal/error marker: `end` carries the run outcome; `action` may carry `"error"`. */
5658 status?: string;
59 /** Requested model tier before resolution. */
60 tier?: string;
61 /** Resolved provider/model label. */
62 model?: string;
63 thinkingLevel?: ThinkingLevel;
64 startedAt?: number;
65 usage?: TokenUsage;
5766 /** Per-agent live controls (runner-bound; absent on the tool surface). */
5867 controls?: AgentControls;
222231 status: AgentStatus;
223232 /** Latest coarse action ("read a.ts", "grep …") — never the streamed body. */
224233 action: string;
234 tier?: string;
235 model?: string;
236 thinkingLevel?: ThinkingLevel;
237 startedAt?: number;
238 usage?: TokenUsage;
225239 /** Live controls (command overlay only); absent on tool-less / tool-surface rows. */
226240 controls?: AgentControls;
371385 phase: event.phase,
372386 status,
373387 action,
388 tier: event.tier ?? base.tier,
389 model: event.model ?? base.model,
390 thinkingLevel: event.thinkingLevel ?? base.thinkingLevel,
391 startedAt: event.startedAt ?? base.startedAt,
392 usage: event.usage ?? base.usage,
374393 controls: event.controls ?? base.controls,
375394 };

extensions/ultra/runner.ts

Modified

+52 / −5 text lines

251251 return { model: match[1], thinkingLevel: match[2] as ThinkingLevel };
254function requestedTier(step: Step): string | undefined {
255 return step.model && isModelTierName(step.model) ? step.model : undefined;
256}
258function modelLabel(
259 model: unknown,
260 fallback: string | undefined,
261): string | undefined {
262 if (model && typeof model === "object") {
263 const value = model as { provider?: unknown; id?: unknown };
264 if (typeof value.provider === "string" && typeof value.id === "string")
265 return `${value.provider}/${value.id}`;
266 if (typeof value.id === "string") return fallback ?? value.id;
267 }
268 return fallback;
269}
254271function resolveModelTier(step: Step, tiers: ModelTiers | undefined): Step {
255272 if (!step.model || !isModelTierName(step.model)) return step;
256273 const tier = tiers?.[step.model];
410427 drivers: StepDrivers,
411428 opts: RunStepOptions,
412429): Promise<RunStepResult> {
430 const tier = requestedTier(step);
413431 const resolvedStep = resolveModelTier(step, opts.modelTiers);
414432 const schemaObj = resolveStepSchema(resolvedStep, opts);
415433 const validator = schemaObj
428446 schemaObj,
429447 validator,
430448 timeoutMs,
449 tier,
431450 )
432 : runCompleteStep(resolvedStep, drivers, opts, validator, timeoutMs);
451 : runCompleteStep(resolvedStep, drivers, opts, validator, timeoutMs, tier);
435454// ---- tool-less path -------------------------------------------------------
440459 opts: RunStepOptions,
441460 validator: CompiledValidator | undefined,
442461 timeoutMs: number,
462 tier: string | undefined,
443463): Promise<RunStepResult> {
444 emitCompleteStart(opts);
464 const startedAt = Date.now();
446465 const model = drivers.resolveModel(step.model);
466 emitCompleteStart(opts, {
467 tier,
468 model: modelLabel(model, step.model),
469 thinkingLevel: step.thinkingLevel,
470 startedAt,
471 });
447472 const auth = await drivers.resolveAuth(model);
448473 if (!auth.ok) {
449474 return finishComplete(opts, {
478503 return finishComplete(opts, { ok: false, value: null, reason: lastReason });
481function emitCompleteStart(opts: RunStepOptions): void {
506function emitCompleteStart(
507 opts: RunStepOptions,
508 meta: Pick<
509 UltraProgressEvent,
510 "tier" | "model" | "thinkingLevel" | "startedAt"
511 >,
512): void {
482513 opts.onProgress?.({
483514 agentId: opts.agentId,
484515 phase: opts.phase,
485516 kind: "start",
517 ...meta,
486518 controls: NOOP_CONTROLS,
487519 });
498530 kind: "end",
499531 status: result.ok ? "done" : "dropped",
500532 text: result.ok ? undefined : result.reason,
533 usage: result.usage,
501534 controls: NOOP_CONTROLS,
502535 });
503536 return result;
622655 schemaObj: object | undefined,
623656 validator: CompiledValidator | undefined,
624657 timeoutMs: number,
658 tier: string | undefined,
625659): Promise<RunStepResult> {
626660 const { agentId, phase, onProgress } = opts;
661 const startedAt = Date.now();
627662 const model = drivers.resolveModel(step.model);
663 const meta = {
664 tier,
665 model: modelLabel(model, step.model),
666 thinkingLevel: step.thinkingLevel,
667 startedAt,
668 };
629670 // The terminating StructuredOutput tool: validates the model's call against
630671 // the step schema, captures the validated payload as the step result, and
683724 usage = lastAssistantUsage((event as { messages?: unknown }).messages);
684725 }
685726 const mapped = mapSessionEvent(event, agentId, phase);
686 if (mapped) onProgress?.({ ...mapped, controls });
727 if (mapped)
728 onProgress?.({
729 ...mapped,
730 ...meta,
731 usage: mapped.kind === "end" ? usage : undefined,
732 controls,
733 });
687734 });
689736 const guarded = await raceGuards(

extensions/ultra/ui.ts

Modified

+42 / −8 text lines

8787 return state.workflowDescription;
90function compactTokens(tokens: number): string {
91 if (tokens < 1000) return String(tokens);
92 const value = tokens / 1000;
93 return `${value >= 10 ? Math.round(value) : value.toFixed(1).replace(/\.0$/, "")}k`;
94}
96function elapsed(startedAt: number): string {
97 const seconds = Math.max(0, Math.floor((Date.now() - startedAt) / 1000));
98 if (seconds < 60) return `${seconds}s`;
99 return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
100}
102function agentDetailLines(row: ReducerState["rows"][number]): string[] {
103 const details: { label: string; value: string }[] = [];
104 const model = row.tier
105 ? `${row.tier}${row.model ? ` → ${row.model}` : ""}`
106 : row.model;
107 const modelValue = [model, row.thinkingLevel].filter(Boolean).join(" · ");
108 if (modelValue) details.push({ label: "model", value: modelValue });
109 const usageValue = [
110 row.startedAt === undefined ? undefined : elapsed(row.startedAt),
111 row.usage ? `${compactTokens(row.usage.total)} tokens` : undefined,
112 ]
113 .filter(Boolean)
114 .join(" · ");
115 if (usageValue) details.push({ label: "usage", value: usageValue });
116 if (row.action) details.push({ label: "action", value: row.action });
117 return details.map(
118 (detail, index) =>
119 `${index === details.length - 1 ? "└" : "├"} ${detail.label.padEnd(6)} ${detail.value}`,
120 );
121}
90123function divider(label: string, width: number): string {
91124 const w = Math.max(1, width);
92125 const text = ` ${label} `;
112145/**
113146 * Pure board renderer for the tool surface. Collapsed = aggregate counts +
114147 * one-line summary + the expand hint (NEVER any per-agent line or transcript
115 * body). Expanded = per-agent `status · latest action`, with dropped agents
116 * surfaced. The drill-in transcript is the OVERLAY's job, never the tool sink's,
148 * body). Expanded = multiline per-agent identity, model/usage metadata, and latest
149 * action, with dropped agents surfaced. The drill-in transcript is the OVERLAY's job, never the tool sink's,
117150 * so `state.transcripts` is intentionally never read here.
118151 */
119152function renderToolBoard(
136169 return lines.map((l) => fitLine(l, w));
137170 }
139 // Expanded: one line per agent (status · latest action). Dropped agents are
140 // surfaced by their ✗ icon + last action (the raw drop reason is not retained
141 // by the reducer, so the last action stands in as context).
172 // Expanded: identity first, then an indented metadata/action tree.
142173 for (const row of state.rows) {
143174 const icon = STATUS_ICON[row.status];
144 let line = `${icon} ${row.agentId} · ${row.status}`;
145 if (row.action) line += ` · ${row.action}`;
146 lines.push(theme.fg("dim", fitLine(line, w)));
175 lines.push(
176 theme.fg("dim", fitLine(`${icon} ${row.agentId} · ${row.status}`, w)),
177 );
178 for (const detail of agentDetailLines(row)) {
179 lines.push(theme.fg("muted", fitLine(` ${detail}`, w)));
180 }
147181 }
149183 return lines.map((l) => fitLine(l, w));