import type { AssistantMessage } from "@earendil-works/pi-ai"; import { getMarkdownTheme, keyHint as legacyKeyHint, type Theme, } from "@earendil-works/pi-coding-agent"; import { type Component, Container, Markdown, sliceByColumn, stripTerminalSequences, Text, truncateToWidth, } from "@earendil-works/pi-tui"; import type { Progress, TaskRequest, TaskResult } from "./runtime.ts"; export function safe(value: string, limit = 12000): string { return stripTerminalSequences(value) .replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/gu, "") .slice(0, limit); } export function renderTaskCall( args: Partial, expanded: boolean, theme: Theme, ): Component { const title = theme.fg("toolTitle", theme.bold("π²")) + theme.fg("muted", ` · ${safe(args.agent ?? "child", 120).split("\n")[0]}`); if (expanded) return new SafeText( title + "\n" + theme.fg("muted", safe(args.prompt ?? "", Number.MAX_SAFE_INTEGER)), 0, 0, ); const text = stripTerminalSequences(title) + " · " + safe((args.prompt ?? "").split("\n")[0] ?? "", Number.MAX_SAFE_INTEGER); return { render(width) { if (width <= 0) return []; // Native truncation inserts full resets; style only after clipping plain text. const clipped = stripTerminalSequences(truncateToWidth(text, width, "…")); return [ theme.fg("toolTitle", theme.bold(clipped.slice(0, 2))) + theme.fg("muted", clipped.slice(2)), ]; }, invalidate() {}, }; } export interface KeyHints { keyHint?: typeof legacyKeyHint; } export function collapsedPreview( lines: string[], width: number, hints?: KeyHints, ): string[] { if (width <= 0) return []; return [ lines[0] ?? "", lines[1] ?? "", (hints?.keyHint ?? legacyKeyHint)("app.tools.expand", "to expand"), ].map((line) => sliceByColumn(line, 0, width, true)); } export function renderTask( result: TaskResult | undefined, expanded: boolean, theme: Theme, progress?: Progress, hints?: KeyHints, ): Container { const view = new SafeContainer(); const compact = (text: string) => { const content = new SafeText(text, 0, 0); view.addChild({ render: (width) => collapsedPreview(content.render(width), width, hints), invalidate: () => content.invalidate(), }); }; if (!result) { const status = progress?.tool ? `tool: ${safe(progress.tool.name, 120)}` : safe( progress?.phase === "running" ? "" : progress?.phase || "Starting child task…", 120, ); const detail = progress?.tool?.args || progress?.preview; const isError = progress?.phase === "error"; const color = isError ? "error" : "muted"; if (!expanded) compact(theme.fg(color, status)); else { view.addChild(new SafeText(theme.fg(color, status), 0, 0)); if (detail) { const text = safe(detail, isError ? 12000 : 6000); view.addChild( new SafeText(isError ? theme.fg("error", text) : text, 0, 0), ); } } return view; } const role = result.outcome === "completed" ? "success" : result.outcome === "aborted" ? "warning" : "error"; const costSource = result.usage.cost.totalFromProvider === true ? "billed" : "estimated"; const cost = `$${result.usage.cost.total.toFixed(4)} ${costSource}`; const title = theme.fg(role, result.outcome) + theme.fg( "dim", ` · ${result.turns} turns · ${(result.durationMs / 1000).toFixed(1)}s · ${result.usage.totalTokens} tokens · ${cost}`, ); if (!expanded) { compact(title); return view; } view.addChild(new SafeText(title, 0, 0)); const section = (title: string, text: string, markdown = false) => { view.addChild( new SafeText("\n" + theme.fg("muted", theme.bold(title)), 0, 0), ); view.addChild( markdown ? new Markdown( safe(text, Number.MAX_SAFE_INTEGER), 0, 0, getMarkdownTheme(), ) : new SafeText(safe(text, Number.MAX_SAFE_INTEGER), 0, 0), ); }; const assistant = result.outputMode === "message" && result.output ? (result.output as unknown as AssistantMessage) : null; const output = assistant ? assistant.content .filter((part) => part.type === "text") .map((part) => part.text) .join("\n") : typeof result.output === "string" ? result.output : "```json\n" + JSON.stringify(result.output, null, 2) + "\n```"; const config = result.effective; section( "Config", [ `Model: ${config.model ?? "none"} · thinking ${config.thinkingLevel}`, `Workspace: ${config.cwd}`, `Tools: ${config.tools.join(", ") || "none"}`, ...(config.excludedTools?.length ? [ `Inherited tools excluded: ${config.excludedTools.map((name) => `${name} (hidden)`).join(", ")}`, ] : []), ...( ["extensions", "skills", "prompts", "flagNames", "sections"] as const ).flatMap((key) => { const values = config[key] ?? []; return values.length ? [ `${key === "flagNames" ? "Flags" : key[0]?.toUpperCase() + key.slice(1)}:`, ...values.map((value) => " " + value), ] : []; }), ].join("\n"), ); const overrides = Object.entries(result.requested); if (overrides.length) section( "Call config", overrides .map( ([key, value]) => `${key}: ${typeof value === "string" ? value : JSON.stringify(value, null, 2)}`, ) .join("\n"), ); section("Result", output || "No text output.", true); const errorMessage = (assistant ?? result.assistantMessage)?.errorMessage; if (errorMessage) section("Error", errorMessage); section( "Session", `${result.sessionId}\n${result.sessionFile ?? "not persisted"}`, ); if (result.diagnostics.length) section("Diagnostics", result.diagnostics.join("\n")); return view; } /** Native wrapping can exceed one-cell widths for wide graphemes. */ export class SafeText extends Text { override render(width: number): string[] { if (width <= 0) return []; return super.render(width).map((line) => truncateToWidth(line, width)); } } class SafeContainer extends Container { override render(width: number): string[] { if (width <= 0) return []; return super.render(width).map((line) => truncateToWidth(line, width)); } }