Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion pi-subagents/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<runId>.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
Expand Down
3 changes: 2 additions & 1 deletion pi-subagents/README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ pi install npm:billion-context-pi-subagents
- **Print / JSON 模式**(`pi -p`、SDK):`async:true` 自动降级为**同步** — 结果在同一轮次中作为工具结果返回。
- **失败必须显式可见,绝不静默。** 失败的运行(非零退出码、spawn 错误、看门狗超时)会注入一条携带简短错误摘要的 `FAILED ⚠️` 通知。如果通知完全无法送达,一条恢复提示会附加到下一条委派通知或工具结果上。
- **结果投递**:完整的委派输出保存到 `$TMPDIR/acp-delegate/<runId>.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`)中恢复 — 之前的工具调用会被还原而非重放。

## 配置
Expand Down
2 changes: 1 addition & 1 deletion pi-subagents/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
185 changes: 185 additions & 0 deletions pi-subagents/src/delegate-render.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>).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);
}
Loading
Loading