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 docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ Uncertain dispatches do not change the window; they already block all dispatch.

Lifecycle callbacks CAS loop revision, owner runtime/generation, work ID, dispatch ID, attempt, and agent ID. Normal terminal evidence is bounded and persisted with `provider_owned` completion status; pi-loop does not call `subagents:rpc:consume`, so the provider retains its native completion surface. Protocol-v2 stop replies and `stopped`/`aborted` lifecycle statuses acknowledge cancellation, not quiescence. They become non-retryable, non-consumable `uncertain` dispatches before stop RPCs run. A late spawn reply may attach its exact cleanup identity without restoring execution. Proved failures retry only within `maxAttempts`; a spawn timeout is ambiguous without upstream status/list or idempotent dispatch keys, so it becomes `uncertain` and is never retried automatically.

Completion bursts refill capacity without a pi-loop parent wake. When every terminal dispatch is provider-owned, pi-loop pauses the controller and acknowledges its aggregate wake internally so only the provider's native completion path runs. Uncertain dispatches and failures without a provider-owned terminal result retain the durable hidden wake until `pi.sendMessage` succeeds, unless cancelled or retired by expiry; a crash before acknowledgement may duplicate that delivery. Completed/attention controllers pause for `OrchestrationGet` inspection and explicit deletion. Presentation labels controller status as `active`, `needs attention`, `complete`, or `cancelled` while preserving reducer vocabulary in persisted state. Progress separates local `reserved` capacity from pending work and last-reported dispatch observations (`starting`, `queued`, `reported running`); none proves current worker liveness. An active controller shows the reservation count against its current capacity as `N/W in flight` (the aimd window, or the fixed concurrency); a controller that is no longer dispatching shows `N reserved`. "Swarm" is the user-facing keyword for this surface: the tool description and its prompt guidelines route a swarm, fan-out, or parallel subagents over a finite list of independent items here; send one delegation, a chain whose steps need earlier results, or foreground work to the provider's own tool; forbid sending the same items through both; name `WorkflowCreate` and `TaskCreate` for other shapes; and explain `verify`. A batch created while its session holds a live claim on exactly one active workflow records that workflow, execution and state as its `phase`, and the create result names it. With no claim, an expired claim, a paused workflow, or more than one claim, the batch is unlinked. The link groups the batch under that phase in progress views and has no effect on dispatch, workflow admission, or transitions. A listing row for a work item ends with the evidence held for it: `verify ok` or `verify failed (exit N)`, the reported duration, and the reported token total; a field is omitted when nothing was reported. The progress panel lists up to five work items under each orchestration. When an aimd batch is larger than its unverified ceiling, the create result says the window is capped and that declaring `verify` on every item lifts it. When a fixed batch of several items is held to one worker, the create result says it is serial and that omitting `concurrency` lifts that. The status line and progress panel count an orchestration only while it is `active` or `needs attention`; a `complete` or `cancelled` batch leaves both at once and stays stored for `OrchestrationGet`, `LoopList` and `/loop` until deleted or expired. Provider-native `SubagentWorkflow` UI and execution remain a separate provider-owned surface.
Completion bursts refill capacity without a pi-loop parent wake. When every terminal dispatch is provider-owned, pi-loop pauses the controller and acknowledges its aggregate wake internally so only the provider's native completion path runs. Uncertain dispatches and failures without a provider-owned terminal result retain the durable hidden wake until `pi.sendMessage` succeeds, unless cancelled or retired by expiry; a crash before acknowledgement may duplicate that delivery. Completed/attention controllers pause for `OrchestrationGet` inspection and explicit deletion. Presentation labels controller status as `active`, `needs attention`, `complete`, or `cancelled` while preserving reducer vocabulary in persisted state. Progress separates local `reserved` capacity from pending work and last-reported dispatch observations (`starting`, `queued`, `reported running`); none proves current worker liveness. An active controller shows the reservation count against its current capacity as `N/W in flight` (the aimd window, or the fixed concurrency); a controller that is no longer dispatching shows `N reserved`. "Swarm" is the user-facing keyword for this surface: the tool description and its prompt guidelines route a swarm, fan-out, or parallel subagents over a finite list of independent items here; send one delegation, a chain whose steps need earlier results, or foreground work to the provider's own tool; forbid sending the same items through both; say that `WorkflowCreate` owns ordered phases and rework while a phase's state may run its swarm here, and name `TaskCreate` for an unrequested backlog; and explain `verify`. A batch created while its session holds a live claim on exactly one active workflow records that workflow, execution and state as its `phase`, and the create result names it. With no claim, an expired claim, a paused workflow, or more than one claim, the batch is unlinked. The link groups the batch under that phase in progress views and has no effect on dispatch, workflow admission, or transitions. A listing row for a work item ends with the evidence held for it: `verify ok` or `verify failed (exit N)`, the reported duration, and the reported token total; a field is omitted when nothing was reported. The progress panel lists up to five work items under each orchestration. When an aimd batch is larger than its unverified ceiling, the create result says the window is capped and that declaring `verify` on every item lifts it. When a fixed batch of several items is held to one worker, the create result says it is serial and that omitting `concurrency` lifts that. The status line and progress panel count an orchestration only while it is `active` or `needs attention`; a `complete` or `cancelled` batch leaves both at once and stays stored for `OrchestrationGet`, `LoopList` and `/loop` until deleted or expired. Provider-native `SubagentWorkflow` UI and execution remain a separate provider-owned surface.

Session shutdown/switch invalidates lifecycle callbacks, persists unresolved work as uncertain, and best-effort requests cancellation before store rebinding. Any unresolved dispatch history prevents controller deletion under the Store lock; cancelled batches stay paused and inspectable. Late completion events do not clear this safety latch. Protocol v2 provides no safe automatic clearance or deletion route. Legacy `stopped`/`interrupted` records normalize to non-consumable uncertainty; previously launched retries or consumed evidence cannot be undone, and missing historical stop provenance cannot be reconstructed. A new runtime cannot adopt an unexpired foreign owner lease; after expiry it marks active dispatches uncertain rather than risking duplicates. Project scope, dynamic work addition, dependency graphs, cross-session election, and exact-once dispatch are not implemented.

Expand Down
2 changes: 1 addition & 1 deletion docs/USAGE_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,6 @@ The TUI status line summarizes ordinary loops, workflows, orchestrations, runnin

Workflow tool cards, `LoopList`, and `TaskList` stay at two lines while collapsed: the summary, then one dense preview such as `✓plan ▸ [implement] ▸ review ▸ done │ CLAIMED 4m │ try 1/3 │ » pass|retry`. It shows the state trail (visited states marked, the current state bracketed), derived activity using the same status word as the summary, attempt, and available outcomes; idle work without a live lease is flagged `(unclaimed)`. Several workflows or tasks share a one-line roster. The preview is display metadata only and never changes model-facing tool text. Colors come from the active pi theme, so custom themes apply. The default glyphs are box-drawing, basic shapes, and Latin-1 characters that effectively every monospace font draws. A terminal cannot report its font and a missing icon renders blank, so Nerd Font icons are opt-in (`PI_LOOP_GLYPHS=nerd` or `NERD_FONT=1`) and are accents only: brackets and separators stay portable. A non-UTF-8 locale or `TERM=linux|dumb` selects ASCII. `/loop glyphs [nerd|unicode|ascii]` switches the set and prints a sample; it applies to cards created afterwards.

On terminals at least 110 columns wide, a narrow progress panel docks at the top-right while a workflow, orchestration, running monitor, or native task is in progress. It never takes keyboard focus and disappears when nothing is in progress. Each workflow is a vertical state trail (`✓` visited, `▶` current with derived activity and attempt, `○` not yet entered) followed by its available outcomes; workflows that are paused or unclaimed are listed first. Each orchestration (at most two) is a header with its progress and in-flight count, followed by up to five work items named by `label` or prompt: `●` in flight with its last reported dispatch state, elapsed time and attempt; `✗` failed; `?` uncertain; `○` pending; `✓` complete with duration and token count when the provider reported them; `–` cancelled. In-flight items are listed first and finished ones last, and a final `… N more` line counts the items not shown. The reported state is the last one received, not proof a worker is running. Running monitors (at most three, oldest first) show id, elapsed time, description or command, and their last output line, with a `quiet` flag after five minutes without output; monitor state is process-local, so nothing is shown for monitors from a previous pi process. Native tasks show `done/total`, in-progress work first, and flag a claim whose lease has expired. The panel is presentation only: it reads the same LoopStore and TaskStore snapshots as the status line and never claims work, resumes a controller, or schedules a wake. Task rows come only from standalone tasks, monitor rows only from this process's MonitorManager, and workflow rows only from LoopStore. Monitor output is untrusted and stripped of control bytes before display. Durations refresh on state changes and the existing 30-second heartbeat, and every minute while a monitor runs. Because it overlays the transcript's right edge, hide it with `/loop panel off` (or `/loop panel` to toggle), or start pi with `PI_LOOP_PANEL=off`.
On terminals at least 110 columns wide, a narrow progress panel docks at the top-right while a workflow, orchestration, running monitor, or native task is in progress. It never takes keyboard focus and disappears when nothing is in progress. Each workflow is a vertical state trail (`✓` visited, `▶` current with derived activity and attempt, `○` not yet entered) followed by its available outcomes; workflows that are paused or unclaimed are listed first. A swarm started from a workflow phase is listed under that phase's row instead of on its own; a finished phase shows its latest swarm's `done/total`, and a `∑` line under the workflow title totals agents and reported tokens across its swarms. A swarm whose workflow is gone, or whose phase row is not on screen, is listed on its own. Each orchestration (at most two) is a header with its progress and in-flight count, followed by up to five work items named by `label` or prompt: `●` in flight with its last reported dispatch state, elapsed time and attempt; `✗` failed; `?` uncertain; `○` pending; `✓` complete with duration and token count when the provider reported them; `–` cancelled. In-flight items are listed first and finished ones last, and a final `… N more` line counts the items not shown. The reported state is the last one received, not proof a worker is running. Running monitors (at most three, oldest first) show id, elapsed time, description or command, and their last output line, with a `quiet` flag after five minutes without output; monitor state is process-local, so nothing is shown for monitors from a previous pi process. Native tasks show `done/total`, in-progress work first, and flag a claim whose lease has expired. The panel is presentation only: it reads the same LoopStore and TaskStore snapshots as the status line and never claims work, resumes a controller, or schedules a wake. Task rows come only from standalone tasks, monitor rows only from this process's MonitorManager, and workflow rows only from LoopStore. Monitor output is untrusted and stripped of control bytes before display. Durations refresh on state changes and the existing 30-second heartbeat, and every minute while a monitor runs. Because it overlays the transcript's right edge, hide it with `/loop panel off` (or `/loop panel` to toggle), or start pi with `PI_LOOP_PANEL=off`.

The runtime allows at most 25 active loops and 25 running monitors. Each orchestration batch allows up to 32 work items, 8 local workers under fixed pacing (under `aimd`, the batch size when every item declares `verify`, otherwise 8), and 3 attempts per item, plus up to 3 overload re-sends per item that do not count as attempts.
2 changes: 1 addition & 1 deletion src/tools/subagent-orchestration-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ export function registerSubagentOrchestrationTools(options: OrchestrationToolsOp
"A swarm, fan-out, or parallel subagents over a finite list of independent items means OrchestrationCreate: it persists the batch, paces workers from feedback, retries proved failures, and survives restart.",
"Use the provider's own subagent tool for one delegation, a chain whose steps need earlier results, or foreground work to watch; never send the same items through both.",
"Give each item `verify`, a shell command that exits 0 only when that item is done, whenever one exists: only a fully verified batch may grow past 8 workers. Omit `concurrency` unless a fixed worker count was requested.",
"Not for ordered phases or rework (WorkflowCreate) or a backlog nobody was asked to run (TaskCreate).",
"Ordered phases or rework: WorkflowCreate owns them, and a phase's state runs its swarm here. A backlog nobody asked to run: TaskCreate.",
],
parameters: Type.Object({
goal: Type.String({ description: "Shared batch goal", maxLength: MAX_GOAL_CHARS }),
Expand Down
49 changes: 45 additions & 4 deletions src/ui/progress-panel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,46 @@ export function trailStateNames(workflow: NonNullable<LoopEntry["workflow"]>): s
return names.includes(workflow.currentState) ? names : [workflow.currentState, ...names];
}

function workflowLines(entry: LoopEntry, now: number): PanelLine[] {
/** Stored swarms started from one of this workflow's phases, oldest first. */
function phaseSwarms(workflowId: string, loops: readonly LoopEntry[]): LoopEntry[] {
return loops
.filter((loop) => loop.orchestration?.phase?.workflowId === workflowId && (loop.status === "active" || loop.status === "paused"))
.sort((a, b) => Number(a.id) - Number(b.id));
}

/** Agents finished out of all agents across a workflow's swarms, with the tokens they reported. */
function swarmTotalsLine(swarms: readonly LoopEntry[]): PanelLine {
let done = 0;
let total = 0;
let tokens = 0;
for (const swarm of swarms) {
for (const item of swarm.orchestration?.work ?? []) {
total++;
if (item.status === "completed") done++;
for (const dispatch of item.dispatches) tokens += dispatch.usage?.tokens?.total ?? 0;
}
}
return [seg(" ∑ ", "dim"), seg(`${done}/${total} agents`, "muted"), seg(tokens > 0 ? ` · ${compactTokens(tokens)} tok` : "", "dim")];
}

/**
* A workflow's state trail. A swarm started from a phase is listed under that phase's row, and
* `nested` receives its id so the caller does not list it a second time on its own.
*/
function workflowLines(entry: LoopEntry, now: number, loops: readonly LoopEntry[] = [], nested: Set<string> = new Set()): PanelLine[] {
const workflow = entry.workflow;
if (!workflow) return [];
const activity = deriveWorkflowActivity(entry, now);
const lines: PanelLine[] = [[seg("◆ ", "accent"), seg(`#${entry.id} `, "dim"), seg(plainPanelText(entry.prompt))]];
const swarms = phaseSwarms(entry.id, loops);
if (swarms.length > 0) lines.push(swarmTotalsLine(swarms));
const pushRunning = (name: string) => {
for (const swarm of swarms) {
if (swarm.orchestration?.phase?.state !== name || !isOrchestrationInProgress(swarm)) continue;
nested.add(swarm.id);
for (const line of orchestrationLines(swarm, now)) lines.push([seg(" "), ...line.map((part, index) => index === 0 ? { ...part, text: part.text.trimStart() } : part)]);
}
};
const window = stateWindow(trailStateNames(workflow), workflow.currentState);
if (window.before > 0) lines.push([seg(` ⋮ ${window.before} earlier`, "dim")]);
for (const name of window.names) {
Expand All @@ -151,10 +186,14 @@ function workflowLines(entry: LoopEntry, now: number): PanelLine[] {
ACTIVITY_TONE[activity.status],
)]);
} else if ((workflow.attemptsByState[name] ?? 0) > 0) {
lines.push([seg(" ✓ ", "success"), seg(label, "dim")]);
// A phase re-entered on rework is counted by its latest swarm.
const latest = swarms.filter((swarm) => swarm.orchestration?.phase?.state === name).at(-1)?.orchestration;
const counts = latest ? ` ${getOrchestrationCounts(latest).completed}/${latest.work.length}` : "";
lines.push([seg(" ✓ ", "success"), seg(label, "dim"), seg(counts, "muted")]);
} else {
lines.push([seg(" ○ ", "dim"), seg(label, "muted")]);
}
pushRunning(name);
}
if (window.after > 0) lines.push([seg(` ⋮ ${window.after} later`, "dim")]);
const outcomes = getWorkflowOutcomeAvailability(workflow).available;
Expand Down Expand Up @@ -303,12 +342,14 @@ export function layoutProgressPanel(input: ProgressPanelInput, width: number, ma
};
return rank(a) - rank(b) || Number(a.id) - Number(b.id);
});
for (const entry of workflows.slice(0, MAX_DETAILED_WORKFLOWS)) lines.push(...workflowLines(entry, now));
const nested = new Set<string>();
for (const entry of workflows.slice(0, MAX_DETAILED_WORKFLOWS)) lines.push(...workflowLines(entry, now, input.loops, nested));
if (workflows.length > MAX_DETAILED_WORKFLOWS) {
lines.push([seg(`◆ … ${workflows.length - MAX_DETAILED_WORKFLOWS} more workflows`, "dim")]);
}

const orchestrations = input.loops.filter(isPanelOrchestration);
// A swarm listed under its workflow phase is not listed again on its own.
const orchestrations = input.loops.filter((entry) => isPanelOrchestration(entry) && !nested.has(entry.id));
for (const entry of orchestrations.slice(0, MAX_ORCHESTRATION_ROWS)) lines.push(...orchestrationLines(entry, now));
if (orchestrations.length > MAX_ORCHESTRATION_ROWS) {
lines.push([seg(`◇ … ${orchestrations.length - MAX_ORCHESTRATION_ROWS} more`, "dim")]);
Expand Down
3 changes: 3 additions & 0 deletions test/orchestration-guidance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ describe("orchestration routing guidance", () => {
// One controller per job.
expect(guidance).toContain("WorkflowCreate");
expect(guidance).toContain("TaskCreate");
// Phased fan-out: the workflow owns the phases and a phase runs its swarm here; a swarm is not refused for being a phase.
expect(guidance).toMatch(/Ordered phases or rework: WorkflowCreate owns them, and a phase's state runs its swarm here/);
expect(guidance).not.toMatch(/Not for ordered phases/);
// What verify buys, and that a worker count is not the default.
expect(guidance).toMatch(/`verify`, a shell command that exits 0 only when that item is done/);
expect(guidance).toMatch(/only a fully verified batch may grow past 8 workers/);
Expand Down
Loading
Loading