diff --git a/package-lock.json b/package-lock.json index 24672c3853..65f7ff9748 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8779,7 +8779,7 @@ }, "pi-subagents": { "name": "billion-context-pi-subagents", - "version": "0.1.6", + "version": "0.2.0", "dev": true, "license": "MIT", "devDependencies": { diff --git a/pi-subagents/README.md b/pi-subagents/README.md index dcefea43d6..8cb2036d00 100644 --- a/pi-subagents/README.md +++ b/pi-subagents/README.md @@ -62,7 +62,8 @@ Read-only roles receive a restricted tool allowlist plus ACP context tools so th - **Print / JSON modes** (`pi -p`, SDK): `async:true` auto-downgrades to **synchronous** — the result returns as the tool result in the same turn. - **Failures are loud, never silent.** A failed run (nonzero exit, spawn error, watchdog timeout) injects a `FAILED ⚠️` notification carrying a short error excerpt. If a notification cannot be delivered at all, a recovery notice is attached to the next delegate notification or tool result. - **Result delivery**: the full delegate output is saved to `$TMPDIR/acp-delegate/.out`; the tool result and notification carry only the **task title + file path** (no preview) — use `read` for the details. -- **Live visibility (TUI)**: async runs show a status widget below the editor and a footer line with cumulative token/cost usage. `/acp-fleet` (or the `ctrl+alt+d` shortcut) opens the interactive fleet inspector: live list + transcript overlay. Disabled automatically in RPC/print/JSON. +- **Live visibility (TUI)**: async runs show a status widget below the editor and a footer line with cumulative token/cost usage; a running row appends `⚠ no activity Nm` when the child has been silent for over 2 minutes. `/acp-fleet` (or the `ctrl+alt+d` shortcut) opens the interactive fleet inspector: live list + transcript overlay. Disabled automatically in RPC/print/JSON. +- **Compact tool blocks (TUI)**: when the host supports custom tool rendering (pi-coding-agent ≥ 0.62; borderless self-shell since 0.67.3), `acp_delegate*` calls render as compact blocks — the call line shows agent + first task line, the result line shows a status icon, exit label, duration and up to 3 preview lines of the run's output (`Ctrl+O` expands to 40). The preview is screen-only: the model-facing text is unchanged (task title + file path). Older hosts ignore the renderers and show the default tool output. - **Resumable runs**: a run can be resumed from its saved session (`.session.jsonl` next to the result file) — earlier tool calls are restored instead of replayed. ## Configuration diff --git a/pi-subagents/README.zh-CN.md b/pi-subagents/README.zh-CN.md index d6a4a115c4..a512e41e5c 100644 --- a/pi-subagents/README.zh-CN.md +++ b/pi-subagents/README.zh-CN.md @@ -64,7 +64,8 @@ pi install npm:billion-context-pi-subagents - **Print / JSON 模式**(`pi -p`、SDK):`async:true` 自动降级为**同步** — 结果在同一轮次中作为工具结果返回。 - **失败必须显式可见,绝不静默。** 失败的运行(非零退出码、spawn 错误、看门狗超时)会注入一条携带简短错误摘要的 `FAILED ⚠️` 通知。如果通知完全无法送达,一条恢复提示会附加到下一条委派通知或工具结果上。 - **结果投递**:完整的委派输出保存到 `$TMPDIR/acp-delegate/.out`;工具结果和通知仅携带**任务标题 + 文件路径**(无预览)— 使用 `read` 查看详情。 -- **实时可见性(TUI)**:异步运行会在编辑器下方显示状态组件,并在底部栏显示累计 token/费用用量。`/acp-fleet`(或 `ctrl+alt+d` 快捷键)打开交互式集群检查器:实时列表 + 转录叠加层。在 RPC/print/JSON 模式下自动禁用。 +- **实时可见性(TUI)**:异步运行会在编辑器下方显示状态组件,并在底部栏显示累计 token/费用用量;子进程静默超过 2 分钟时,运行中的行会追加 `⚠ no activity Nm` 标记。`/acp-fleet`(或 `ctrl+alt+d` 快捷键)打开交互式集群检查器:实时列表 + 转录叠加层。在 RPC/print/JSON 模式下自动禁用。 +- **紧凑工具块(TUI)**:当宿主支持自定义工具渲染时(pi-coding-agent ≥ 0.62;无边框自渲染外壳自 0.67.3 起),`acp_delegate*` 调用以紧凑块呈现——调用行显示代理名 + 任务首行,结果行显示状态图标、退出码、耗时和最多 3 行输出预览(`Ctrl+O` 展开至 40 行)。预览仅用于屏幕显示:传给模型的文本不变(任务标题 + 文件路径)。更旧的宿主忽略这些渲染器,使用默认工具输出。 - **可恢复的运行**:运行可以从其保存的会话(结果文件旁的 `.session.jsonl`)中恢复 — 之前的工具调用会被还原而非重放。 ## 配置 diff --git a/pi-subagents/package.json b/pi-subagents/package.json index c1f1ee8c19..090a53850e 100644 --- a/pi-subagents/package.json +++ b/pi-subagents/package.json @@ -1,6 +1,6 @@ { "name": "billion-context-pi-subagents", - "version": "0.1.6", + "version": "0.2.0", "description": "acp_delegate sub-agent tools for the Pi coding agent — split out of billion-context-pi (#612); vendored in-repo (#2384).", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/pi-subagents/src/delegate-render.ts b/pi-subagents/src/delegate-render.ts new file mode 100644 index 0000000000..eb8cd2c2ea --- /dev/null +++ b/pi-subagents/src/delegate-render.ts @@ -0,0 +1,185 @@ +import { Text, truncateToWidth } from "@earendil-works/pi-tui"; +import type { Component } from "@earendil-works/pi-tui"; + +// Invariants: model-facing `content` text is untouched (previews live only in +// bounded `details` + the rendered screen); renderers never throw on bad input +// (they fall back to plain text; the host also try/catches renderer calls). +// Hosts < pi-coding-agent 0.62 ignore renderCall/renderResult and < 0.67.3 +// ignore renderShell — no runtime feature detection needed. + +// Method syntax keeps any host Theme (fg takes a narrower color union) assignable. +export interface RenderTheme { + fg(color: string, text: string): string; + bold(text: string): string; +} + +export type DelegateStatus = "queued" | "running" | "completed" | "failed" | "cancelled"; + +// Carried in tool-result `details`, which persists into the session +// transcript — keep payloads bounded (PREVIEW_MAX_CHARS). +export interface DelegateRenderMeta { + kind: "delegate"; + agent?: string; + runId?: string; + task?: string; + status?: DelegateStatus; + exitLabel?: string; + timedOut?: string; + file?: string; + durationMs?: number; + preview?: string; + previewTruncated?: boolean; + queuedAhead?: number; + resumedFrom?: string; +} + +const PREVIEW_MAX_CHARS = 4096; +const PREVIEW_LINE_WIDTH = 110; +const PREVIEW_LINES_COLLAPSED = 3; +const PREVIEW_LINES_EXPANDED = 40; +const CALL_TASK_WIDTH = 160; + +export function exitLabel(code: number | null, signal?: NodeJS.Signals | null): string { + if (code === null && signal) return `exit ${signal}`; + return `exit ${code ?? "?"}`; +} + +export function firstLine(s: string): string { + const i = s.indexOf("\n"); + return (i === -1 ? s : s.slice(0, i)).trim(); +} + +export function delegatePreview(body: string): { preview: string; truncated: boolean } { + if (!body) return { preview: "", truncated: false }; + const trimmed = body.replace(/\s+$/, ""); + if (trimmed.length <= PREVIEW_MAX_CHARS) return { preview: trimmed, truncated: false }; + const cut = trimmed.slice(0, PREVIEW_MAX_CHARS); + const nl = cut.lastIndexOf("\n"); + return { preview: (nl > 0 ? cut.slice(0, nl) : cut).replace(/\s+$/, ""), truncated: true }; +} + +// Structural subset of DelegateRun; kept here (not imported from +// delegate-tool.ts) to avoid a module cycle. +export interface MetaRunSource { + runId: string; + agent: string; + task: string; + status: DelegateStatus; + startedAt?: number; + finishedAt?: number; + exitCode?: number | null; + exitSignal?: NodeJS.Signals | null; + timedOut?: string | null; + result?: { file: string; body: string }; +} + +export function makeResultMeta(run: MetaRunSource): DelegateRenderMeta { + const terminal = run.status === "completed" || run.status === "failed" || run.status === "cancelled"; + const meta: DelegateRenderMeta = { + kind: "delegate", + agent: run.agent, + runId: run.runId, + task: firstLine(run.task), + status: run.status, + }; + if (!terminal) return meta; + if (run.startedAt != null && run.finishedAt != null && run.finishedAt >= run.startedAt) { + meta.durationMs = run.finishedAt - run.startedAt; + } + if (run.exitCode !== undefined || run.exitSignal !== undefined) { + meta.exitLabel = exitLabel(run.exitCode ?? null, run.exitSignal); + } + if (run.timedOut) meta.timedOut = String(run.timedOut); + if (run.result?.file) meta.file = run.result.file; + if (run.result?.body) { + const p = delegatePreview(run.result.body); + meta.preview = p.preview; + meta.previewTruncated = p.truncated; + } + return meta; +} + +function isRenderMeta(x: unknown): x is DelegateRenderMeta { + if (typeof x !== "object" || x === null) return false; + return (x as Record).kind === "delegate"; +} + +function plainTextOf(result: { content: { type: string; text?: string }[] }): string { + const first = result.content[0]; + return first && first.type === "text" ? first.text ?? "" : ""; +} + +function fmtDuration(ms: number): string { + const s = Math.round(ms / 1000); + if (s < 60) return `${s}s`; + const m = Math.floor(s / 60); + return `${m}m${s % 60 ? ` ${s % 60}s` : ""}`; +} + +export function renderDelegateCall( + args: { agent?: string; task?: string; resumeFrom?: string }, + theme: RenderTheme, +): Component { + const parts: string[] = [args.resumeFrom ? "↻" : "▸"]; + if (args.agent) parts.push(theme.fg("accent", theme.bold(args.agent))); + const taskLine = firstLine(args.task ?? ""); + if (taskLine) parts.push(theme.fg("muted", truncateToWidth(taskLine, CALL_TASK_WIDTH))); + if (args.resumeFrom) parts.push(theme.fg("dim", `(from ${args.resumeFrom})`)); + return new Text(parts.join(" "), 0, 0); +} + +export function renderDelegateResult( + result: { content: { type: string; text?: string }[]; details?: unknown }, + options: { expanded: boolean }, + theme: RenderTheme, + ctx: { isError: boolean }, +): Component { + const plain = plainTextOf(result); + const meta = isRenderMeta(result.details) ? result.details : undefined; + if (ctx.isError || !meta || !meta.status) return new Text(plain, 0, 0); + + const lines: string[] = []; + const label = meta.agent ?? "delegate"; + switch (meta.status) { + case "completed": + lines.push( + theme.fg("success", `✓ ${label}`) + + (meta.exitLabel ? ` · ${meta.exitLabel}` : "") + + (meta.durationMs != null ? theme.fg("muted", ` · ${fmtDuration(meta.durationMs)}`) : ""), + ); + break; + case "failed": + lines.push( + theme.fg("error", `✗ ${label} · FAILED ⚠️`) + + (meta.exitLabel ? ` · ${meta.exitLabel}` : "") + + (meta.timedOut ? theme.fg("warning", ` · timed out: ${truncateToWidth(meta.timedOut, PREVIEW_LINE_WIDTH)}`) : ""), + ); + break; + case "cancelled": + lines.push(theme.fg("warning", `◼ ${label} · cancelled`)); + break; + case "running": + lines.push(theme.fg("muted", `● ${label} · running in background${meta.runId ? ` · ${meta.runId}` : ""}`)); + break; + case "queued": + lines.push(theme.fg("muted", `○ ${label} · queued${meta.queuedAhead ? ` (${meta.queuedAhead} ahead)` : ""}`)); + break; + } + + const previewLines = (meta.preview ?? "").split("\n").map((l) => l.trimEnd()).filter((l) => l.trim().length > 0); + const maxLines = options.expanded ? PREVIEW_LINES_EXPANDED : PREVIEW_LINES_COLLAPSED; + let shown = 0; + for (const l of previewLines) { + if (shown >= maxLines) break; + lines.push(theme.fg("dim", ` ${truncateToWidth(l, PREVIEW_LINE_WIDTH)}`)); + shown++; + } + const hidden = previewLines.length - shown; + if (hidden > 0 && !options.expanded) lines.push(theme.fg("dim", ` … ${hidden} more line(s) — Ctrl+O expand`)); + + if (meta.file) lines.push(theme.fg("muted", `⎿ ${meta.file}`)); + else if (meta.status === "running") lines.push(theme.fg("muted", "⎿ notification injected on completion")); + else if (meta.status === "queued") lines.push(theme.fg("muted", "⎿ starts automatically when a slot frees")); + + return new Text(lines.join("\n"), 0, 0); +} diff --git a/pi-subagents/src/delegate-tool.ts b/pi-subagents/src/delegate-tool.ts index a746d1b9bc..b8134ad2f8 100644 --- a/pi-subagents/src/delegate-tool.ts +++ b/pi-subagents/src/delegate-tool.ts @@ -20,6 +20,16 @@ import { DEFAULT_DELEGATE_POLICY, type DelegatePolicy, type DelegateRoleConfig } import { attachWatchdogs } from "./delegate-watchdog.js"; import { parseEventLine, activityLines, newPortion, ThinkingCollector, type Usage } from "./delegate-events.js"; import { isPiHost } from "./host.js"; +import { + exitLabel, + firstLine, + delegatePreview, + makeResultMeta, + renderDelegateCall, + renderDelegateResult, + type DelegateRenderMeta, +} from "./delegate-render.js"; +export { exitLabel }; // public surface: tests/embedders import it from this module const EOF_GRACE_MS = 10_000; const SETTLED_GRACE_MS = 10_000; @@ -191,6 +201,8 @@ interface DelegateRun { cwd: string; startedAt: number; finishedAt?: number; + /** Last stdout-activity timestamp — the fleet widget warns when a running run goes silent. */ + lastActivityAt?: number; status: RunStatus; exitCode?: number | null; /** Exit signal when the child died by signal (exit code null), e.g. "SIGTERM". */ @@ -404,10 +416,10 @@ export function markDelegateRunReadByCommand(command: string): boolean { /** Snapshot of currently-running delegate runs, for the TUI status widget. */ -export function runningRunsSnapshot(): { runId: string; agent: string; task: string; startedAt: number }[] { - const out: { runId: string; agent: string; task: string; startedAt: number }[] = []; +export function runningRunsSnapshot(): { runId: string; agent: string; task: string; startedAt: number; lastActivityAt?: number }[] { + const out: { runId: string; agent: string; task: string; startedAt: number; lastActivityAt?: number }[] = []; for (const r of runs.values()) { - if (r.status === "running") out.push({ runId: r.runId, agent: r.agent, task: r.task, startedAt: r.startedAt }); + if (r.status === "running") out.push({ runId: r.runId, agent: r.agent, task: r.task, startedAt: r.startedAt, lastActivityAt: r.lastActivityAt }); } return out; } @@ -702,7 +714,7 @@ const agentListLine = (name: string): string => { return ` • ${name} - ${blurb[name]} [tools: ${def.tools}${def.restricted ? " + ACP context tools" : ""}]`; }; -export function makeDelegateTool(pi: ExtensionAPI): ToolDefinition { +export function makeDelegateTool(pi: ExtensionAPI): ToolDefinition { ensureHostNotificationHandlers(pi); const maxConcurrent = delegatePolicy.maxConcurrent; const concurrencyNote = Number.isFinite(maxConcurrent) @@ -737,14 +749,19 @@ The delegate runs in its own clean pi process — it does NOT see this conversat "A FAILED notification (⚠️) means that task produced no usable result — read the excerpt and the output files, then decide whether to re-dispatch it before wrapping up.", "A failed/cancelled run keeps its output files and can be resumed with resumeFrom: \"\" — prefer resuming over re-dispatching when the earlier work is worth keeping.", "For changes you must apply yourself, delegate read-only investigation (reviewer/researcher/oracle) and keep the main context as the sole writer.", + "Route by task kind: review/audit code → reviewer (never use worker to review), explore unfamiliar code → researcher, plan multi-step work → planner, questions/advice → oracle, making changes → worker.", + "A delegate's findings live in its result file — read that file instead of re-running exploration a child already did.", ], parameters: DelegateParams, - async execute(toolCallId, params, signal, _onUpdate, ctx): Promise> { + renderShell: "self", + renderCall: (args, theme) => renderDelegateCall(args, theme), + renderResult: (result, options, theme, ctx) => renderDelegateResult(result, options, theme, ctx), + async execute(toolCallId, params, signal, _onUpdate, ctx): Promise> { const args = params as DelegateArgs; - let outcome = await runDelegate(pi, args, ctx, signal); + const { text, meta } = await runDelegate(pi, args, ctx, signal); const notice = undeliveredNotice(); - if (notice) outcome = `${notice}\n\n${outcome}`; - return { details: undefined, content: [{ type: "text", text: outcome }] }; + const outcome = notice ? `${notice}\n\n${text}` : text; + return { details: meta, content: [{ type: "text", text: outcome }] }; }, }; } @@ -759,13 +776,6 @@ export function formatRunResult(run: DelegateRun): string { return formatPayload(header, run.result?.file ?? "", run.task, run.result?.body, run.status === "failed" ? run.activityFile : undefined); } -/** "exit 0" / "exit 1" / "exit SIGTERM" (signal shown when the child was - * killed and has no exit code) / "exit ?" (unknown). */ -export function exitLabel(code: number | null, signal?: NodeJS.Signals | null): string { - if (code === null && signal) return `exit ${signal}`; - return `exit ${code ?? "?"}`; -} - /** Shared note for cancelled runs: their files are retained, so point the * model at the partial output and offer a resume. */ export function cancelledFileNote(runId: string, file: string): string { @@ -1165,7 +1175,7 @@ function buildBatchTrailer(batch: DelegateRun[], anyFailed: boolean, mode: "merg /** Attach the recovery notice (if any) to a delegate tool result, so a lost * notification resurfaces at the next delegate interaction. */ -function withUndeliveredNotice(result: AgentToolResult): AgentToolResult { +function withUndeliveredNotice(result: AgentToolResult): AgentToolResult { const notice = undeliveredNotice(); const first = result.content[0]; if (notice && first && first.type === "text") first.text = `${notice}\n\n${first.text}`; @@ -1201,13 +1211,13 @@ export function buildWaitResult( content: string, mode: "merged" | "separate" = "separate", contentType = "text" as const, -): { details: undefined; content: { type: "text"; text: string }[]; usage?: AgentToolResult["usage"] } { +): { details: DelegateRenderMeta; content: { type: "text"; text: string }[]; usage?: AgentToolResult["usage"] } { if (run.usage && !run.usageReported) { run.usageReported = true; if (mode === "merged") { const cost = safeCost(run.usage); return { - details: undefined, + details: makeResultMeta(run), content: [{ type: contentType, text: content }], usage: { ...run.usage, cost: cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } as AgentToolResult["usage"], }; @@ -1215,7 +1225,7 @@ export function buildWaitResult( addDelegateUsage(run.usage); } } - return { details: undefined, content: [{ type: contentType, text: content }] }; + return { details: makeResultMeta(run), content: [{ type: contentType, text: content }] }; } /** Build usage-aware result for cancel tool. */ @@ -1223,13 +1233,13 @@ export function buildCancelResult( run: DelegateRun, content: string, mode: "merged" | "separate" = "separate", -): { details: undefined; content: { type: "text"; text: string }[]; usage?: AgentToolResult["usage"] } { +): { details: DelegateRenderMeta; content: { type: "text"; text: string }[]; usage?: AgentToolResult["usage"] } { if (run.usage && !run.usageReported) { run.usageReported = true; if (mode === "merged") { const cost = safeCost(run.usage); return { - details: undefined, + details: makeResultMeta(run), content: [{ type: "text", text: content }], usage: { ...run.usage, cost: cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } as AgentToolResult["usage"], }; @@ -1237,14 +1247,14 @@ export function buildCancelResult( addDelegateUsage(run.usage); } } - return { details: undefined, content: [{ type: "text", text: content }] }; + return { details: makeResultMeta(run), content: [{ type: "text", text: content }] }; } -export function makeDelegateWaitTool(pi: ExtensionAPI): ToolDefinition { - const exec = async (args: { runId: string; timeout?: number }, signal?: AbortSignal): Promise> => { +export function makeDelegateWaitTool(pi: ExtensionAPI): ToolDefinition { + const exec = async (args: { runId: string; timeout?: number }, signal?: AbortSignal): Promise> => { const run = runs.get(args.runId); if (!run) { - return { details: undefined, content: [{ type: "text" as const, text: `No delegate run with runId \`${args.runId}\`. It may have already been reported or never existed.` }] }; + return { details: { kind: "delegate" }, content: [{ type: "text" as const, text: `No delegate run with runId \`${args.runId}\`. It may have already been reported or never existed.` }] }; } // Already finished (e.g. the model calls wait after the injected // notification, or the run was cancelled). @@ -1280,14 +1290,14 @@ export function makeDelegateWaitTool(pi: ExtensionAPI): ToolDefinition { let settled = false; let timer: ReturnType | undefined; - const finish = (result: { details: undefined; content: { type: "text"; text: string }[]; usage?: AgentToolResult["usage"] }) => { + const finish = (result: { details: DelegateRenderMeta; content: { type: "text"; text: string }[]; usage?: AgentToolResult["usage"] }) => { if (settled) return; settled = true; run.waiter = undefined; @@ -1296,7 +1306,7 @@ export function makeDelegateWaitTool(pi: ExtensionAPI): ToolDefinition { - finish({ details: undefined, content: [{ type: "text", text: `Aborted; delegate \`${args.runId}\` is still running in the background. A notification will be injected when it finishes.` }] }); + finish({ details: makeResultMeta(run), content: [{ type: "text", text: `Aborted; delegate \`${args.runId}\` is still running in the background. A notification will be injected when it finishes.` }] }); }; run.waiter = () => { run.consumed = true; // we own the result; suppress injection @@ -1318,7 +1328,7 @@ export function makeDelegateWaitTool(pi: ExtensionAPI): ToolDefinition finish({ details: undefined, content: [{ type: "text", text: `Failed: delegate \`${args.runId}\` result not ready after ${Math.round(timeoutMs / 1000)}s. Do NOT keep waiting or retry — go do other work now. The run continues in the background and a completion notification (with the result file path) will be injected into the chat when it finishes.` }] }), + () => finish({ details: makeResultMeta(run), content: [{ type: "text", text: `Failed: delegate \`${args.runId}\` result not ready after ${Math.round(timeoutMs / 1000)}s. Do NOT keep waiting or retry — go do other work now. The run continues in the background and a completion notification (with the result file path) will be injected into the chat when it finishes.` }] }), timeoutMs, ); }); @@ -1334,18 +1344,21 @@ export function makeDelegateWaitTool(pi: ExtensionAPI): ToolDefinition> { + renderShell: "self", + renderCall: (args, theme) => renderDelegateCall({ task: args.runId }, theme), + renderResult: (result, options, theme, ctx) => renderDelegateResult(result, options, theme, ctx), + async execute(_toolCallId, params, signal): Promise> { return withUndeliveredNotice(await exec(params as { runId: string; timeout?: number }, signal)); }, }; } -export function makeDelegateCancelTool(pi: ExtensionAPI): ToolDefinition { - const exec = async (params: Static): Promise> => { +export function makeDelegateCancelTool(pi: ExtensionAPI): ToolDefinition { + const exec = async (params: Static): Promise> => { const { runId } = params; const run = runs.get(runId); if (!run) { - return { details: undefined, content: [{ type: "text", text: `Unknown runId "${runId}".` }] }; + return { details: { kind: "delegate" }, content: [{ type: "text", text: `Unknown runId "${runId}".` }] }; } if (run.status !== "running" && run.status !== "queued") { return buildCancelResult(run, `Run ${runId} already ${run.status} (no action).`); @@ -1381,7 +1394,10 @@ export function makeDelegateCancelTool(pi: ExtensionAPI): ToolDefinition> { + renderShell: "self", + renderCall: (args, theme) => renderDelegateCall({ task: args.runId }, theme), + renderResult: (result, options, theme, ctx) => renderDelegateResult(result, options, theme, ctx), + async execute(toolCallId, params): Promise> { return withUndeliveredNotice(await exec(params as Static)); }, }; @@ -1414,33 +1430,34 @@ async function runDelegate( args: DelegateArgs, ctx: ExtensionContext, signal: AbortSignal | undefined, -): Promise { +): Promise<{ text: string; meta: DelegateRenderMeta }> { + const errorResult = (text: string): { text: string; meta: DelegateRenderMeta } => ({ text, meta: { kind: "delegate", agent: args.agent } }); const agent = AGENTS[args.agent]; if (!agent) { - return `Unknown agent "${args.agent}". Choose one of: ${AGENT_NAMES.join(", ")}.`; + return errorResult(`Unknown agent "${args.agent}". Choose one of: ${AGENT_NAMES.join(", ")}.`); } const parentDepth = Number(process.env.PI_ACP_DELEGATE_DEPTH ?? "0"); const maxDepth = delegatePolicy.maxDepth; if (Number.isNaN(parentDepth) || parentDepth >= maxDepth) { - return `Delegate nesting limit reached (depth ${parentDepth}, max ${maxDepth}). The delegate cannot spawn further delegates.`; + return errorResult(`Delegate nesting limit reached (depth ${parentDepth}, max ${maxDepth}). The delegate cannot spawn further delegates.`); } if (!args.task || !args.task.trim()) { if (!args.resumeFrom) { - return `Task must be a non-empty string. Got: ${JSON.stringify(args.task).slice(0, 60)}`; + return errorResult(`Task must be a non-empty string. Got: ${JSON.stringify(args.task).slice(0, 60)}`); } } let prevSession: string | null = null; if (args.resumeFrom) { if (!isPiHost(ctx.sessionManager)) { - return `resumeFrom is only supported on pi hosts (this host has no pi session files to restore). Re-dispatch the task fresh instead.`; + return errorResult(`resumeFrom is only supported on pi hosts (this host has no pi session files to restore). Re-dispatch the task fresh instead.`); } const prev = runs.get(args.resumeFrom); if (prev && (prev.status === "running" || prev.status === "queued")) { - return `Cannot resume from run \`${args.resumeFrom}\`: it has not finished yet (${prev.status}). Wait for it to finish first, then resume from its final session.`; + return errorResult(`Cannot resume from run \`${args.resumeFrom}\`: it has not finished yet (${prev.status}). Wait for it to finish first, then resume from its final session.`); } prevSession = join(OUT_DIR, `${args.resumeFrom}${SESSION_EXT}`); if (!existsSync(prevSession)) { - return `Cannot resume ${args.resumeFrom}: no session file at ${prevSession} (the run produced no assistant output, or the file was cleaned up). Re-dispatch the task fresh instead.`; + return errorResult(`Cannot resume ${args.resumeFrom}: no session file at ${prevSession} (the run produced no assistant output, or the file was cleaned up). Re-dispatch the task fresh instead.`); } } const taskText = args.task?.trim() || (args.resumeFrom ? "(resumed — the original task is in the session history)" : ""); @@ -1500,6 +1517,7 @@ async function runDelegate( if (run.status === "cancelled") return; run.status = "running"; run.startedAt = Date.now(); + run.lastActivityAt = Date.now(); run.activityFile = useJsonStream ? activityFile : undefined; const child = spawnDelegateChild({ cwd, @@ -1559,6 +1577,7 @@ async function runDelegate( ); child.stdout?.on("data", (c: Buffer) => { watchdog.poke(); + run.lastActivityAt = Date.now(); if (useJsonStream) { stdoutBuf += c.toString("utf8"); let nl: number; @@ -1738,32 +1757,48 @@ async function runDelegate( }; const startedNow = delegateGate.launchOrQueue(runId, launch); + const launchMeta: DelegateRenderMeta = { + kind: "delegate", + agent: args.agent, + runId, + task: firstLine(taskText), + status: run.status, + resumedFrom: args.resumeFrom, + }; + if (!startedNow) launchMeta.queuedAhead = Math.max(0, delegateGate.queuedCount - 1); if (startedNow) { - return [ + return { + text: [ + args.resumeFrom + ? `Resuming **${args.agent}** from run \`${args.resumeFrom}\` (new runId \`${runId}\`).` + : `Delegated to **${args.agent}** (runId \`${runId}\`).`, + `Task: ${truncate(taskText, 160)}`, + `Running in the background at \`${cwd}\`.`, + useJsonStream + ? `Live activity is streaming to \`${activityFile}\` — read it anytime to watch the delegate work (tool calls and their output${args.showThinking ? ", plus thinking" : ""}).` + : `The reply is streaming to \`${replyFile}\` — read it anytime to see partial output (this host has no json event mode, so tool activity is not visible).`, + asyncWatchdogDescription(effectiveAsyncMs), + ``, + `Call acp_delegate_wait({ runId: "${runId}" }) to block for the result (default 10s timeout). If the wait times out, or you skip it, a completion notification (with the result file path) is still injected here automatically when the delegate finishes — so you may also just continue other work now and let the result find you.`, + ].join("\n"), + meta: launchMeta, + }; + } + return { + text: [ args.resumeFrom ? `Resuming **${args.agent}** from run \`${args.resumeFrom}\` (new runId \`${runId}\`).` : `Delegated to **${args.agent}** (runId \`${runId}\`).`, `Task: ${truncate(taskText, 160)}`, - `Running in the background at \`${cwd}\`.`, - useJsonStream - ? `Live activity is streaming to \`${activityFile}\` — read it anytime to watch the delegate work (tool calls and their output${args.showThinking ? ", plus thinking" : ""}).` - : `The reply is streaming to \`${replyFile}\` — read it anytime to see partial output (this host has no json event mode, so tool activity is not visible).`, - asyncWatchdogDescription(effectiveAsyncMs), - ``, - `Call acp_delegate_wait({ runId: "${runId}" }) to block for the result (default 10s timeout). If the wait times out, or you skip it, a completion notification (with the result file path) is still injected here automatically when the delegate finishes — so you may also just continue other work now and let the result find you.`, - ].join("\n"); - } - return [ - args.resumeFrom - ? `Resuming **${args.agent}** from run \`${args.resumeFrom}\` (new runId \`${runId}\`).` - : `Delegated to **${args.agent}** (runId \`${runId}\`).`, - `Task: ${truncate(taskText, 160)}`, - `QUEUED — at most ${delegatePolicy.maxConcurrent} background delegate(s) run concurrently; ${Math.max(0, delegateGate.queuedCount - 1)} ahead of it. It starts automatically when a slot frees.`, - `Call acp_delegate_wait({ runId: "${runId}" }) to block for the result; a completion notification is injected when it finishes (unless you already read the result file after it finished — then it's skipped).`, - ].join("\n"); + `QUEUED — at most ${delegatePolicy.maxConcurrent} background delegate(s) run concurrently; ${Math.max(0, delegateGate.queuedCount - 1)} ahead of it. It starts automatically when a slot frees.`, + `Call acp_delegate_wait({ runId: "${runId}" }) to block for the result; a completion notification is injected when it finishes (unless you already read the result file after it finished — then it's skipped).`, + ].join("\n"), + meta: launchMeta, + }; } // Sync: block until the child finishes (bounded by the configured timeout). + const syncStart = Date.now(); const child = spawnDelegateChild({ cwd, env: childEnv, @@ -1786,7 +1821,22 @@ async function runDelegate( body = result.stdout; } const file = await persistResult(runId, body); - return formatSyncResult(args.agent, runId, taskText, result, file); + const preview = delegatePreview(body); + const syncMeta: DelegateRenderMeta = { + kind: "delegate", + agent: args.agent, + runId, + task: firstLine(taskText), + status: result.timedOut ? "failed" : result.code === 0 && !syncNoOutput ? "completed" : "failed", + exitLabel: exitLabel(result.code, result.signal), + durationMs: Date.now() - syncStart, + file, + preview: preview.preview, + previewTruncated: preview.truncated, + resumedFrom: args.resumeFrom, + }; + if (result.timedOut) syncMeta.timedOut = String(result.timedOut); + return { text: formatSyncResult(args.agent, runId, taskText, result, file), meta: syncMeta }; } export async function buildChildArgs( diff --git a/pi-subagents/src/fleet-widget.ts b/pi-subagents/src/fleet-widget.ts index 48d08df196..fc2e6d1fc1 100644 --- a/pi-subagents/src/fleet-widget.ts +++ b/pi-subagents/src/fleet-widget.ts @@ -4,12 +4,16 @@ import { initFooterStatus, updateFooterStatus, disposeFooterStatus } from "./foo const DELEGATE_WIDGET_KEY = "billion-context-pi-delegates"; const REFRESH_MS = 500; const MAX_TASK_LEN = 48; +// Silence this long on a running run warrants a warning before the idle +// watchdog (default 5 min) kills it. +const STALL_WARN_MS = 120_000; interface WidgetRun { runId: string; agent: string; task: string; startedAt: number; + lastActivityAt?: number; } type RunsSnapshot = () => WidgetRun[]; @@ -48,7 +52,12 @@ function renderLines(runs: WidgetRun[]): string[] | undefined { : `acp_delegate · ${runs.length} running`; const rows = runs.map((r) => { const elapsed = Math.max(0, Math.round((now - r.startedAt) / 1000)); - return ` ● ${r.agent} (${elapsed}s) — ${truncateTask(r.task)}`; + let row = ` ● ${r.agent} (${elapsed}s) — ${truncateTask(r.task)}`; + if (r.lastActivityAt !== undefined && now - r.lastActivityAt >= STALL_WARN_MS) { + const mins = Math.max(1, Math.floor((now - r.lastActivityAt) / 60_000)); + row += ` ⚠ no activity ${mins}m`; + } + return row; }); const hint = fleetShortcut ? ` /acp-fleet · ${formatShortcutLabel(fleetShortcut)} — inspect` diff --git a/pi-subagents/tests/delegate-render.test.ts b/pi-subagents/tests/delegate-render.test.ts new file mode 100644 index 0000000000..8d2f886f28 --- /dev/null +++ b/pi-subagents/tests/delegate-render.test.ts @@ -0,0 +1,317 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + delegatePreview, + firstLine, + exitLabel, + makeResultMeta, + renderDelegateCall, + renderDelegateResult, + type DelegateRenderMeta, + type MetaRunSource, + type RenderTheme, +} from "../src/delegate-render.js"; +import { makeDelegateTool, makeDelegateWaitTool, makeDelegateCancelTool } from "../src/delegate-tool.js"; +import { delegateStatusWidget } from "../src/fleet-widget.js"; +import type { Component } from "@earendil-works/pi-tui"; +import { visibleWidth } from "@earendil-works/pi-tui"; +import type { ExtensionContext } from "@earendil-works/pi-coding-agent"; + +// #3047 tier-1 beautification: the render layer is screen-only — model-facing +// content text stays untouched, previews live in bounded `details`, and every +// renderer must degrade to plain text on bad input instead of throwing. + +type CallFn = (args: Record, theme: RenderTheme) => Component; +type ResultFn = ( + result: { content: { type: string; text?: string }[]; details?: unknown }, + options: { expanded: boolean }, + theme: RenderTheme, + ctx: { isError: boolean }, +) => Component; + +function fakeTheme(): { theme: RenderTheme; colors: string[] } { + const colors: string[] = []; + return { + colors, + theme: { + fg: (color: string, text: string) => { + colors.push(color); + return text; + }, + bold: (text: string) => text, + }, + }; +} + +// Text.render pads every row out to the terminal width, so assertions work +// on right-trimmed rows. +function rendered(comp: Component, width = 500): string[] { + return comp.render(width).map((l) => l.trimEnd()); +} + +test("firstLine takes the first line and trims", () => { + assert.equal(firstLine("single"), "single"); + assert.equal(firstLine("first\nsecond\nthird"), "first"); + assert.equal(firstLine(" padded \nnext"), "padded"); + assert.equal(firstLine(""), ""); +}); + +test("exitLabel covers code, signal, and unknown exits", () => { + assert.equal(exitLabel(0), "exit 0"); + assert.equal(exitLabel(1), "exit 1"); + assert.equal(exitLabel(null, "SIGTERM"), "exit SIGTERM"); + assert.equal(exitLabel(null, null), "exit ?"); + assert.equal(exitLabel(null, undefined), "exit ?"); +}); + +test("delegatePreview passes short bodies through untouched (minus trailing whitespace)", () => { + assert.deepEqual(delegatePreview(""), { preview: "", truncated: false }); + assert.deepEqual(delegatePreview("abc"), { preview: "abc", truncated: false }); + assert.deepEqual(delegatePreview("abc\n\n "), { preview: "abc", truncated: false }); +}); + +test("delegatePreview caps at PREVIEW_MAX_CHARS exactly without truncating", () => { + const body = "x".repeat(4096); + const r = delegatePreview(body); + assert.equal(r.truncated, false); + assert.equal(r.preview.length, 4096); +}); + +test("delegatePreview truncates oversized bodies on a line boundary", () => { + const body = Array.from({ length: 500 }, (_, i) => `line-${i}-${"x".repeat(16)}`).join("\n"); + const { preview, truncated } = delegatePreview(body); + assert.equal(truncated, true); + assert.ok(preview.length <= 4096); + // Cut must land on a newline so no partial line leaks into persisted details. + assert.equal(body.slice(preview.length, preview.length + 1), "\n"); + assert.equal(preview, preview.trimEnd()); +}); + +test("delegatePreview truncates even when there is no newline in budget", () => { + const body = "y".repeat(5000); + const { preview, truncated } = delegatePreview(body); + assert.equal(truncated, true); + assert.equal(preview.length, 4096); +}); + +const COMPLETED_RUN: MetaRunSource = { + runId: "run-1", + agent: "worker", + task: "do X\nand more", + status: "completed", + startedAt: 1000, + finishedAt: 43_000, + exitCode: 0, + result: { file: "/tmp/out.txt", body: "l1\nl2\nl3\nl4\nl5" }, +}; + +test("makeResultMeta fills terminal extras only for terminal states", () => { + const meta = makeResultMeta(COMPLETED_RUN); + assert.equal(meta.kind, "delegate"); + assert.equal(meta.agent, "worker"); + assert.equal(meta.runId, "run-1"); + assert.equal(meta.task, "do X"); + assert.equal(meta.status, "completed"); + assert.equal(meta.durationMs, 42_000); + assert.equal(meta.exitLabel, "exit 0"); + assert.equal(meta.file, "/tmp/out.txt"); + assert.equal(meta.preview, "l1\nl2\nl3\nl4\nl5"); + assert.equal(meta.previewTruncated, false); + + const running = makeResultMeta({ runId: "r2", agent: "researcher", task: "scan", status: "running" }); + assert.equal(running.durationMs, undefined); + assert.equal(running.exitLabel, undefined); + assert.equal(running.file, undefined); + assert.equal(running.preview, undefined); +}); + +test("makeResultMeta carries timeout and signal info for failed runs", () => { + const meta = makeResultMeta({ + runId: "r3", + agent: "oracle", + task: "think", + status: "failed", + exitCode: null, + exitSignal: "SIGTERM", + timedOut: "idle timeout", + result: { file: "/tmp/f.txt", body: "" }, + }); + assert.equal(meta.exitLabel, "exit SIGTERM"); + assert.equal(meta.timedOut, "idle timeout"); + assert.equal(meta.file, "/tmp/f.txt"); + assert.equal(meta.preview, undefined); +}); + +test("renderDelegateCall renders one compact line", () => { + const { theme } = fakeTheme(); + const lines = rendered(renderDelegateCall({ agent: "worker", task: "Review auth module" }, theme)); + assert.equal(lines.length, 1); + assert.ok(lines[0].includes("▸")); + assert.ok(lines[0].includes("worker")); + assert.ok(lines[0].includes("Review auth module")); +}); + +test("renderDelegateCall marks resume calls and tolerates missing agent", () => { + const { theme } = fakeTheme(); + const resume = rendered(renderDelegateCall({ agent: "worker", task: "t", resumeFrom: "abc123" }, theme)); + assert.equal(resume.length, 1); + assert.ok(resume[0].includes("↻")); + assert.ok(resume[0].includes("(from abc123)")); + + const noAgent = rendered(renderDelegateCall({ task: "del_xxx" }, theme)); + assert.equal(noAgent.length, 1); + assert.ok(noAgent[0].startsWith("▸ ")); + assert.ok(noAgent[0].includes("del_xxx")); +}); + +test("renderDelegateCall truncates long tasks", () => { + const { theme } = fakeTheme(); + const longTask = "a".repeat(300); + const lines = rendered(renderDelegateCall({ agent: "worker", task: longTask }, theme)); + assert.equal(lines.length, 1); + // "▸ worker " prefix (9 cells) + task truncated to CALL_TASK_WIDTH (160). + assert.ok(visibleWidth(lines[0]) <= 169, `call line too wide: ${visibleWidth(lines[0])}`); + assert.ok(!lines[0].includes("a".repeat(180))); +}); + +function completedMeta(): DelegateRenderMeta { + return makeResultMeta(COMPLETED_RUN); +} + +test("renderDelegateResult falls back to plain text on error, missing, or statusless meta", () => { + const { theme } = fakeTheme(); + const plain = { content: [{ type: "text", text: "boom" }] }; + assert.deepEqual(rendered(renderDelegateResult(plain, { expanded: false }, theme, { isError: true })), ["boom"]); + assert.deepEqual(rendered(renderDelegateResult(plain, { expanded: false }, theme, { isError: false })), ["boom"]); + const statusless = { content: [{ type: "text", text: "queued note" }], details: { kind: "delegate" } }; + assert.deepEqual(rendered(renderDelegateResult(statusless, { expanded: false }, theme, { isError: false })), ["queued note"]); +}); + +test("renderDelegateResult completed collapsed shows 3 preview lines plus expand hint and file trailer", () => { + const { theme, colors } = fakeTheme(); + const lines = rendered(renderDelegateResult({ content: [{ type: "text", text: "irrelevant for screen" }], details: completedMeta() }, { expanded: false }, theme, { isError: false })); + assert.ok(lines[0].includes("✓ worker")); + assert.ok(lines[0].includes("exit 0")); + assert.ok(lines[0].includes("42s")); + assert.deepEqual(colors[0], "success"); + // 1 header + 3 preview lines + 1 expand hint + 1 file trailer + assert.equal(lines.length, 6); + assert.ok(lines[1].includes("l1")); + assert.ok(lines[3].includes("l3")); + assert.ok(lines[4].includes("… 2 more line(s) — Ctrl+O expand")); + assert.ok(lines[5].includes("⎿ /tmp/out.txt")); +}); + +test("renderDelegateResult completed expanded shows all preview lines without the hint", () => { + const { theme } = fakeTheme(); + const lines = rendered(renderDelegateResult({ content: [{ type: "text", text: "" }], details: completedMeta() }, { expanded: true }, theme, { isError: false })); + // 1 header + 5 preview lines + 1 file trailer + assert.equal(lines.length, 7); + assert.ok(!lines.some((l) => l.includes("more line(s)"))); + assert.ok(lines[5].includes("l5")); + assert.ok(lines[6].includes("⎿ /tmp/out.txt")); +}); + +test("renderDelegateResult failed shows failure label, exit, and timeout reason", () => { + const { theme, colors } = fakeTheme(); + const meta = makeResultMeta({ + runId: "r4", + agent: "worker", + task: "build", + status: "failed", + exitCode: 1, + timedOut: "sync timeout", + startedAt: 0, + finishedAt: 5000, + }); + const lines = rendered(renderDelegateResult({ content: [], details: meta }, { expanded: false }, theme, { isError: false })); + assert.ok(lines[0].includes("✗ worker")); + assert.ok(lines[0].includes("FAILED ⚠️")); + assert.ok(lines[0].includes("exit 1")); + assert.ok(lines[0].includes("timed out: sync timeout")); + assert.ok(colors.includes("error")); +}); + +test("renderDelegateResult cancelled/running/queued each get their own shape", () => { + const { theme } = fakeTheme(); + const cancel = rendered(renderDelegateResult({ content: [], details: { kind: "delegate", agent: "worker", status: "cancelled" } }, { expanded: false }, theme, { isError: false })); + assert.ok(cancel[0].includes("◼ worker · cancelled")); + + const running = rendered(renderDelegateResult({ content: [], details: { kind: "delegate", agent: "oracle", runId: "r9", status: "running" } }, { expanded: false }, theme, { isError: false })); + assert.ok(running[0].includes("● oracle · running in background · r9")); + assert.ok(running[1].includes("⎿ notification injected on completion")); + + const queued = rendered(renderDelegateResult({ content: [], details: { kind: "delegate", agent: "worker", status: "queued", queuedAhead: 2 } }, { expanded: false }, theme, { isError: false })); + assert.ok(queued[0].includes("○ worker · queued (2 ahead)")); + assert.ok(queued[1].includes("⎿ starts automatically when a slot frees")); +}); + +test("renderDelegateResult keeps preview lines within the width budget", () => { + const { theme } = fakeTheme(); + const meta = makeResultMeta({ + runId: "r5", + agent: "worker", + task: "t", + status: "completed", + exitCode: 0, + result: { file: "/tmp/w.txt", body: Array.from({ length: 5 }, (_, i) => `${i}:${"z".repeat(300)}`).join("\n") }, + }); + const lines = rendered(renderDelegateResult({ content: [], details: meta }, { expanded: true }, theme, { isError: false })); + for (const l of lines) { + // 2-space indent + PREVIEW_LINE_WIDTH (110) for preview rows; header and + // trailer stay well under that. + assert.ok(visibleWidth(l) <= 112, `line too wide (${visibleWidth(l)}): ${l.slice(0, 40)}`); + } +}); + +test("all three delegate tools expose self-shell rendering hooks", () => { + const pi = {} as unknown as Parameters[0]; + const tools = [makeDelegateTool(pi), makeDelegateWaitTool(pi), makeDelegateCancelTool(pi)]; + for (const tool of tools) { + assert.equal(tool.renderShell, "self"); + assert.equal(typeof tool.renderCall, "function"); + assert.equal(typeof tool.renderResult, "function"); + } + const { theme } = fakeTheme(); + const callFn = tools[0].renderCall as unknown as CallFn; + const callLines = rendered(callFn({ agent: "worker", task: "t" }, theme)); + assert.equal(callLines.length, 1); + const resultFn = tools[0].renderResult as unknown as ResultFn; + const resultLines = rendered(resultFn({ content: [{ type: "text", text: "" }], details: completedMeta() }, { expanded: false }, theme, { isError: false })); + assert.ok(resultLines[0].includes("✓ worker")); +}); + +test("fleet widget flags stalled runs with a no-activity warning", () => { + const calls: Array<{ key: string; lines: string[] | undefined }> = []; + const ui = { + setWidget(key: string, lines: string[] | undefined): void { + calls.push({ key, lines }); + }, + setStatus(): void {}, + }; + const ctx = { + mode: "tui", + hasUI: true, + cwd: process.cwd(), + ui, + model: { provider: "test", id: "test-model" }, + sessionManager: { buildContextEntries: () => [] }, + } as unknown as ExtensionContext; + const now = Date.now(); + const snapshot = (): Array<{ runId: string; agent: string; task: string; startedAt: number; lastActivityAt?: number }> => [ + { runId: "stale", agent: "worker", task: "long task", startedAt: now - 5_000, lastActivityAt: now - 130_000 }, + { runId: "fresh", agent: "oracle", task: "quick task", startedAt: now - 5_000, lastActivityAt: now - 1_000 }, + ]; + + delegateStatusWidget.setContext(ctx, snapshot); + try { + assert.ok(calls.length >= 1); + const lines = calls[calls.length - 1]?.lines ?? []; + const staleRow = lines.find((l) => l.includes("worker")) ?? ""; + const freshRow = lines.find((l) => l.includes("oracle")) ?? ""; + assert.ok(staleRow.includes("⚠ no activity 2m"), `stale row missing marker: ${staleRow}`); + assert.ok(!freshRow.includes("⚠"), `fresh row should not warn: ${freshRow}`); + } finally { + delegateStatusWidget.dispose(); + } +});