Added nono profiles & orca integration - Added some extensions to start working on
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* The unified backend interface: one `SubagentBackend` per agent runtime
|
||||
* (pi, Claude Code, Codex), all producing the same `SubagentSession` shape.
|
||||
*
|
||||
* Planned real implementations (currently stubbed in ./backends/):
|
||||
* - pi: in-process `createAgentSession()` via the pi SDK.
|
||||
* - claude: `@anthropic-ai/claude-agent-sdk` `query()` in streaming-input mode.
|
||||
* - codex: `codex app-server` child process speaking JSON-RPC over stdio.
|
||||
*/
|
||||
|
||||
import type { Effect, Scope, Stream } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type {
|
||||
BackendName,
|
||||
SendError,
|
||||
SpawnError,
|
||||
SpawnTask,
|
||||
SubagentEvent,
|
||||
SubagentMeta,
|
||||
} from "./domain.ts";
|
||||
|
||||
export interface BackendCapabilities {
|
||||
/** Can send() steer a live run (vs. only starting a fresh run when idle). */
|
||||
readonly steering: boolean;
|
||||
readonly modelSelection: boolean;
|
||||
readonly reasoningEffort: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A live subagent session. The manager is the single consumer of `events`;
|
||||
* it folds them into the `SubagentSnapshot` everything else reads.
|
||||
*/
|
||||
export interface SubagentSession {
|
||||
/** Current metadata snapshot. Updates also arrive as MetaChanged events. */
|
||||
readonly meta: Effect.Effect<SubagentMeta>;
|
||||
/**
|
||||
* All activity, normalized. Ends when the session's scope closes. Every
|
||||
* run started within the session terminates with a RunSettled event.
|
||||
*/
|
||||
readonly events: Stream.Stream<SubagentEvent>;
|
||||
/**
|
||||
* Steer the active run, or start a fresh run when idle (v1 `manager.send`
|
||||
* semantics — the "is a run active" decision is backend-native state).
|
||||
*/
|
||||
send(text: string): Effect.Effect<void, SendError>;
|
||||
/**
|
||||
* Interrupt the active run. Resolves once the backend acknowledges; the
|
||||
* corresponding RunSettled(Interrupted) arrives on `events`. Callers bound
|
||||
* this with a timeout and fall back to closing the session scope.
|
||||
*/
|
||||
readonly interrupt: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface SubagentBackend {
|
||||
readonly name: BackendName;
|
||||
readonly capabilities: BackendCapabilities;
|
||||
/** Probe availability (binary on PATH, SDK importable, credentials). */
|
||||
readonly available: Effect.Effect<boolean>;
|
||||
/**
|
||||
* Spawn a session. Scoped: closing the scope interrupts/kills the
|
||||
* underlying session or process and ends `events`. Fire-and-forget
|
||||
* semantics (background fibers, result delivery) live in the manager.
|
||||
*/
|
||||
spawn(
|
||||
task: SpawnTask,
|
||||
): Effect.Effect<SubagentSession, SpawnError, Scope.Scope>;
|
||||
}
|
||||
|
||||
/** Registry of all wired backends, keyed by name. */
|
||||
export class BackendRegistry extends Context.Service<
|
||||
BackendRegistry,
|
||||
ReadonlyMap<BackendName, SubagentBackend>
|
||||
>()("subagents/BackendRegistry") {}
|
||||
@@ -0,0 +1,701 @@
|
||||
/**
|
||||
* Claude Code backend — real implementation over the Claude Agent SDK.
|
||||
*
|
||||
* One SDK `query()` and one streaming-input bridge live for the whole scoped
|
||||
* session. User sends are pushed into that bridge, while the query iterator is
|
||||
* pumped in the background and translated to normalized SubagentEvents. The
|
||||
* CLI therefore owns conversation continuity, tool execution, and persisted
|
||||
* `~/.claude/projects` transcripts; this file only owns lifecycle guarantees
|
||||
* and the normalized view consumed by the manager.
|
||||
*/
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import {
|
||||
query,
|
||||
type SDKAssistantMessage,
|
||||
type SDKMessage,
|
||||
type SDKResultMessage,
|
||||
type SDKUserMessage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import type { Cause, Scope } from "effect";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
import type { SubagentBackend, SubagentSession } from "../backend.ts";
|
||||
import type {
|
||||
QueuedMessage,
|
||||
ReasoningEffort,
|
||||
RunOutcome,
|
||||
SpawnTask,
|
||||
SubagentEvent,
|
||||
SubagentMeta,
|
||||
TranscriptPart,
|
||||
} from "../domain.ts";
|
||||
import { SendError, SpawnError } from "../domain.ts";
|
||||
|
||||
const CLAUDE_CONTEXT_WINDOW = 200_000;
|
||||
const INTERRUPT_TIMEOUT_MS = 2_000;
|
||||
const PREVIEW_MAX_LENGTH = 4_096;
|
||||
|
||||
// --- Binary resolution --------------------------------------------------------
|
||||
|
||||
let cachedClaudeBinary: string | null | undefined;
|
||||
|
||||
function executable(file: string) {
|
||||
try {
|
||||
fs.accessSync(file, fs.constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the Claude Code CLI once from PATH. The SDK can also run without
|
||||
* this (it bundles a CLI), but pointing it at the user's installed binary
|
||||
* keeps versions, settings, and login state consistent with their terminal.
|
||||
*/
|
||||
function resolveClaudeBinary() {
|
||||
if (cachedClaudeBinary !== undefined) return cachedClaudeBinary ?? undefined;
|
||||
const names =
|
||||
process.platform === "win32"
|
||||
? ["claude.exe", "claude.cmd", "claude"]
|
||||
: ["claude"];
|
||||
for (const directory of (process.env.PATH ?? "").split(path.delimiter)) {
|
||||
if (!directory) continue;
|
||||
for (const name of names) {
|
||||
const candidate = path.join(directory, name);
|
||||
if (executable(candidate)) {
|
||||
cachedClaudeBinary = candidate;
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
cachedClaudeBinary = null;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// --- Streaming input ---------------------------------------------------------
|
||||
|
||||
/** A single-consumer push queue adapted to the SDK's AsyncIterable input. */
|
||||
class ClaudeInput implements AsyncIterable<SDKUserMessage> {
|
||||
private pending: SDKUserMessage[] = [];
|
||||
private waiter:
|
||||
((result: IteratorResult<SDKUserMessage>) => void) | undefined;
|
||||
private closed = false;
|
||||
|
||||
push(text: string) {
|
||||
if (this.closed) return undefined;
|
||||
const message: SDKUserMessage = {
|
||||
type: "user",
|
||||
message: { role: "user", content: text },
|
||||
parent_tool_use_id: null,
|
||||
// Stamped UUIDs make queued messages visible in interrupt receipts.
|
||||
uuid: randomUUID(),
|
||||
};
|
||||
const waiter = this.waiter;
|
||||
if (waiter) {
|
||||
this.waiter = undefined;
|
||||
waiter({ value: message, done: false });
|
||||
} else {
|
||||
this.pending.push(message);
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
clear() {
|
||||
return this.pending.splice(0);
|
||||
}
|
||||
|
||||
end() {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
const waiter = this.waiter;
|
||||
this.waiter = undefined;
|
||||
waiter?.({ value: undefined, done: true });
|
||||
}
|
||||
|
||||
async *[Symbol.asyncIterator]() {
|
||||
while (true) {
|
||||
const message = this.pending.shift();
|
||||
if (message) {
|
||||
yield message;
|
||||
continue;
|
||||
}
|
||||
if (this.closed) return;
|
||||
const next = await new Promise<IteratorResult<SDKUserMessage>>(
|
||||
(resolve) => {
|
||||
this.waiter = resolve;
|
||||
},
|
||||
);
|
||||
if (next.done) return;
|
||||
yield next.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Model, effort, and transcript helpers ----------------------------------
|
||||
|
||||
/**
|
||||
* Claude's deprecated-but-supported maxThinkingTokens is the closest match to
|
||||
* the shared numeric scale requested by this extension. Zero explicitly
|
||||
* disables extended thinking in SDK 0.3.207; an omitted effort leaves the CLI
|
||||
* default untouched.
|
||||
*/
|
||||
const THINKING_BUDGETS = {
|
||||
off: 0,
|
||||
minimal: 1_024,
|
||||
low: 4_096,
|
||||
medium: 10_000,
|
||||
high: 16_000,
|
||||
xhigh: 32_000,
|
||||
max: 63_999,
|
||||
} satisfies Record<ReasoningEffort, number>;
|
||||
|
||||
function boundedError(error: unknown) {
|
||||
return (error instanceof Error ? error.message : String(error)).slice(
|
||||
0,
|
||||
4_096,
|
||||
);
|
||||
}
|
||||
|
||||
function singleLine(text: string) {
|
||||
const flattened = text.replace(/\s+/g, " ").trim();
|
||||
return flattened ? flattened.slice(0, PREVIEW_MAX_LENGTH) : undefined;
|
||||
}
|
||||
|
||||
function safeJson(value: unknown) {
|
||||
try {
|
||||
const text = JSON.stringify(value);
|
||||
if (!text || text === "{}") return undefined;
|
||||
return singleLine(text);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function outputPreview(value: unknown): string | undefined {
|
||||
if (typeof value === "string") return singleLine(value);
|
||||
if (Array.isArray(value)) {
|
||||
const text = value
|
||||
.flatMap((part) => {
|
||||
if (!part || typeof part !== "object") return [];
|
||||
const record = part as { type?: unknown; text?: unknown };
|
||||
return record.type === "text" && typeof record.text === "string"
|
||||
? [record.text]
|
||||
: [];
|
||||
})
|
||||
.join(" ");
|
||||
return singleLine(text) ?? safeJson(value);
|
||||
}
|
||||
return safeJson(value);
|
||||
}
|
||||
|
||||
function assistantParts(message: SDKAssistantMessage): TranscriptPart[] {
|
||||
const parts: TranscriptPart[] = [];
|
||||
for (const block of message.message.content) {
|
||||
if (block.type === "text") {
|
||||
parts.push({ type: "text", text: block.text });
|
||||
} else if (block.type === "thinking") {
|
||||
parts.push({ type: "thinking", text: block.thinking });
|
||||
} else if (block.type === "redacted_thinking") {
|
||||
parts.push({ type: "thinking", text: "", redacted: true });
|
||||
} else if (block.type === "tool_use") {
|
||||
parts.push({
|
||||
type: "toolCall",
|
||||
toolId: block.id,
|
||||
name: block.name,
|
||||
argsPreview: safeJson(block.input),
|
||||
});
|
||||
}
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
/** Claude Code's project-directory escaping, verified against CLI 2.1.207. */
|
||||
function sessionFilePath(cwd: string, sessionId: string) {
|
||||
const projectDirectory = cwd.replace(/[/.]/g, "-");
|
||||
return path.join(
|
||||
os.homedir(),
|
||||
".claude",
|
||||
"projects",
|
||||
projectDirectory,
|
||||
`${sessionId}.jsonl`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Context occupancy after one API request. An assistant message's `usage`
|
||||
* describes only that request: the full prompt (fresh + cache-read +
|
||||
* cache-written input) plus this response's output — exactly what now sits
|
||||
* in the context window. The result message's `usage` instead sums these
|
||||
* per-request counts across the whole run, so a multi-request turn
|
||||
* re-counts cached context once per request and quickly exceeds the real
|
||||
* window; it must never be treated as occupancy.
|
||||
*/
|
||||
export function contextOccupancyTokens(
|
||||
usage:
|
||||
| {
|
||||
input_tokens?: number | null;
|
||||
cache_read_input_tokens?: number | null;
|
||||
cache_creation_input_tokens?: number | null;
|
||||
output_tokens?: number | null;
|
||||
}
|
||||
| null
|
||||
| undefined,
|
||||
) {
|
||||
if (!usage || typeof usage.input_tokens !== "number") return undefined;
|
||||
const count = (value: number | null | undefined) =>
|
||||
typeof value === "number" && Number.isFinite(value) ? value : 0;
|
||||
return (
|
||||
count(usage.input_tokens) +
|
||||
count(usage.cache_read_input_tokens) +
|
||||
count(usage.cache_creation_input_tokens) +
|
||||
count(usage.output_tokens)
|
||||
);
|
||||
}
|
||||
|
||||
function resultContextWindow(result: SDKResultMessage) {
|
||||
return Object.values(result.modelUsage)[0]?.contextWindow;
|
||||
}
|
||||
|
||||
function waitBounded(operation: Promise<unknown>, timeoutMs: number) {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeout = new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, timeoutMs);
|
||||
});
|
||||
return Promise.race([
|
||||
operation.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
),
|
||||
timeout,
|
||||
]).finally(() => {
|
||||
if (timer) clearTimeout(timer);
|
||||
});
|
||||
}
|
||||
|
||||
// --- The session -------------------------------------------------------------
|
||||
|
||||
interface NativeQueuedMessage extends QueuedMessage {
|
||||
readonly uuid: string;
|
||||
/** Raw response sequence after which this steer can be consumed. */
|
||||
readonly afterResponse: number;
|
||||
}
|
||||
|
||||
const makeClaudeSession = (
|
||||
task: SpawnTask,
|
||||
): Effect.Effect<SubagentSession, SpawnError, Scope.Scope> =>
|
||||
Effect.gen(function* () {
|
||||
const input = new ClaudeInput();
|
||||
const abortController = new AbortController();
|
||||
const events = yield* Queue.make<SubagentEvent, Cause.Done>();
|
||||
const emit = (event: SubagentEvent) => {
|
||||
Queue.offerUnsafe(events, event);
|
||||
};
|
||||
|
||||
const state = {
|
||||
closed: false,
|
||||
activeRun: false,
|
||||
interruptRequested: false,
|
||||
runVersion: 0,
|
||||
lastSettledVersion: 0,
|
||||
responseSequence: 0,
|
||||
queued: [] as NativeQueuedMessage[],
|
||||
submittedUuids: new Set<string>(),
|
||||
currentText: "",
|
||||
liveText: "",
|
||||
tools: new Map<string, string>(),
|
||||
settleWaiters: new Set<() => void>(),
|
||||
meta: {
|
||||
backend: "claude",
|
||||
modelLabel: task.model,
|
||||
// Claude models used by this backend currently expose 200k context;
|
||||
// result.modelUsage replaces this fallback when the CLI knows better.
|
||||
contextWindow: CLAUDE_CONTEXT_WINDOW,
|
||||
} satisfies SubagentMeta as SubagentMeta,
|
||||
};
|
||||
|
||||
const thinkingBudget = task.reasoningEffort
|
||||
? THINKING_BUDGETS[task.reasoningEffort]
|
||||
: undefined;
|
||||
const claudeBinary = resolveClaudeBinary();
|
||||
const nativeQuery = yield* Effect.try({
|
||||
try: () =>
|
||||
query({
|
||||
prompt: input,
|
||||
options: {
|
||||
cwd: task.cwd,
|
||||
// Headless children cannot answer approval prompts. The caller
|
||||
// already chose to launch an autonomous subagent, so let it use
|
||||
// its tools without interactive permission checks.
|
||||
permissionMode: "bypassPermissions",
|
||||
allowDangerouslySkipPermissions: true,
|
||||
// Keep child orchestration inside this extension's global manager
|
||||
// and concurrency cap rather than Claude Code's native subagents.
|
||||
disallowedTools: ["Agent", "Task"],
|
||||
// For cwds pi marked untrusted, restrict to user-level settings so
|
||||
// an untrusted project's config cannot reconfigure the child.
|
||||
...(task.parent.projectTrusted
|
||||
? {}
|
||||
: { settingSources: ["user" as const] }),
|
||||
includePartialMessages: true,
|
||||
abortController,
|
||||
...(claudeBinary
|
||||
? { pathToClaudeCodeExecutable: claudeBinary }
|
||||
: {}),
|
||||
...(task.model ? { model: task.model } : {}),
|
||||
...(thinkingBudget !== undefined
|
||||
? { maxThinkingTokens: thinkingBudget }
|
||||
: {}),
|
||||
},
|
||||
}),
|
||||
catch: (error) => new SpawnError({ message: boundedError(error) }),
|
||||
});
|
||||
|
||||
let resolvePumpDone: (() => void) | undefined;
|
||||
const pumpDone = new Promise<void>((resolve) => {
|
||||
resolvePumpDone = resolve;
|
||||
});
|
||||
|
||||
const queuedView = (): ReadonlyArray<QueuedMessage> =>
|
||||
state.queued.map(({ text, kind }) => ({ text, kind }));
|
||||
|
||||
const notifySettled = () => {
|
||||
for (const waiter of state.settleWaiters) waiter();
|
||||
state.settleWaiters.clear();
|
||||
};
|
||||
|
||||
const partialText = () => state.liveText || state.currentText || undefined;
|
||||
|
||||
const settle = (outcome: RunOutcome) => {
|
||||
if (!state.activeRun) return;
|
||||
emit({ _tag: "RunSettled", outcome });
|
||||
state.activeRun = false;
|
||||
state.lastSettledVersion = state.runVersion;
|
||||
state.interruptRequested = false;
|
||||
state.liveText = "";
|
||||
notifySettled();
|
||||
};
|
||||
|
||||
const updateMeta = (patch: Partial<SubagentMeta>) => {
|
||||
state.meta = { ...state.meta, ...patch };
|
||||
emit({ _tag: "MetaChanged", meta: patch });
|
||||
};
|
||||
|
||||
const beginQueuedRunIfNeeded = () => {
|
||||
if (state.activeRun || state.queued.length === 0) return;
|
||||
// A steer arriving too late for the prior turn becomes a fresh queued
|
||||
// turn. The repeated init is the first reliable signal that it started.
|
||||
state.activeRun = true;
|
||||
state.runVersion++;
|
||||
state.currentText = "";
|
||||
state.liveText = "";
|
||||
emit({ _tag: "RunStarted" });
|
||||
};
|
||||
|
||||
const clearConsumedSteers = () => {
|
||||
const remaining = state.queued.filter(
|
||||
(message) => message.afterResponse >= state.responseSequence,
|
||||
);
|
||||
if (remaining.length === state.queued.length) return;
|
||||
state.queued = remaining;
|
||||
emit({ _tag: "QueueChanged", queued: queuedView() });
|
||||
};
|
||||
|
||||
const handleAssistant = (message: SDKAssistantMessage) => {
|
||||
const parts = assistantParts(message);
|
||||
if (parts.length > 0) emit({ _tag: "AssistantMessage", parts });
|
||||
|
||||
// Top-level messages only: subagent (sidechain) requests have their own
|
||||
// context and must not overwrite this conversation's occupancy.
|
||||
if (message.parent_tool_use_id == null) {
|
||||
const tokens = contextOccupancyTokens(message.message.usage);
|
||||
if (tokens !== undefined) emit({ _tag: "UsageChanged", tokens });
|
||||
}
|
||||
|
||||
const text = message.message.content
|
||||
.filter((block) => block.type === "text")
|
||||
.map((block) => block.text)
|
||||
.join("\n")
|
||||
.trim();
|
||||
if (text) state.currentText = text;
|
||||
state.liveText = "";
|
||||
|
||||
if (message.message.model !== state.meta.modelLabel) {
|
||||
updateMeta({ modelLabel: message.message.model });
|
||||
}
|
||||
for (const block of message.message.content) {
|
||||
if (block.type !== "tool_use") continue;
|
||||
state.tools.set(block.id, block.name);
|
||||
emit({
|
||||
_tag: "ToolStart",
|
||||
toolId: block.id,
|
||||
name: block.name,
|
||||
argsPreview: safeJson(block.input),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleUser = (message: SDKUserMessage) => {
|
||||
const content = message.message.content;
|
||||
if (!Array.isArray(content)) return;
|
||||
for (const block of content) {
|
||||
if (block.type !== "tool_result") continue;
|
||||
const name = state.tools.get(block.tool_use_id) ?? "Tool";
|
||||
state.tools.delete(block.tool_use_id);
|
||||
emit({
|
||||
_tag: "ToolEnd",
|
||||
toolId: block.tool_use_id,
|
||||
name,
|
||||
isError: block.is_error ?? false,
|
||||
outputPreview: outputPreview(block.content),
|
||||
});
|
||||
}
|
||||
// External prompts are emitted synchronously by submit(); ignoring text
|
||||
// here prevents a future CLI echo from duplicating the transcript row.
|
||||
};
|
||||
|
||||
const handleResult = (result: SDKResultMessage) => {
|
||||
// result.usage is a whole-run aggregate, not occupancy (see
|
||||
// contextOccupancyTokens); only the capacity is trustworthy here. The
|
||||
// occupancy itself was already emitted by the last assistant message.
|
||||
const contextWindow = resultContextWindow(result);
|
||||
emit({
|
||||
_tag: "UsageChanged",
|
||||
contextWindow: contextWindow ?? state.meta.contextWindow,
|
||||
});
|
||||
if (
|
||||
contextWindow !== undefined &&
|
||||
contextWindow !== state.meta.contextWindow
|
||||
) {
|
||||
updateMeta({ contextWindow });
|
||||
}
|
||||
|
||||
if (state.interruptRequested) {
|
||||
settle({ _tag: "Interrupted", partialText: partialText() });
|
||||
} else if (result.subtype === "success") {
|
||||
settle({
|
||||
_tag: "Completed",
|
||||
finalText: result.result.trim() || state.currentText,
|
||||
});
|
||||
} else {
|
||||
const details =
|
||||
result.errors.filter((error) => error.trim()).join("\n") ||
|
||||
result.stop_reason ||
|
||||
`Claude Code ended with ${result.subtype}`;
|
||||
settle({
|
||||
_tag: "Failed",
|
||||
errorText: boundedError(details),
|
||||
partialText: partialText(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleMessage = (message: SDKMessage) => {
|
||||
if (state.closed) return;
|
||||
// A queued steer's turn normally announces itself with a repeated
|
||||
// system/init, but any turn activity is an equally valid begin signal —
|
||||
// without this, a missed init would stream events into a "done" run
|
||||
// that could then never settle.
|
||||
if (
|
||||
message.type === "stream_event" ||
|
||||
message.type === "assistant" ||
|
||||
message.type === "result"
|
||||
) {
|
||||
beginQueuedRunIfNeeded();
|
||||
}
|
||||
if (message.type === "system" && message.subtype === "init") {
|
||||
beginQueuedRunIfNeeded();
|
||||
updateMeta({
|
||||
modelLabel: message.model,
|
||||
nativeSessionId: message.session_id,
|
||||
sessionFilePath: sessionFilePath(message.cwd, message.session_id),
|
||||
contextWindow: CLAUDE_CONTEXT_WINDOW,
|
||||
});
|
||||
} else if (message.type === "stream_event") {
|
||||
if (message.parent_tool_use_id !== null) return;
|
||||
if (message.event.type === "message_start") {
|
||||
state.responseSequence++;
|
||||
clearConsumedSteers();
|
||||
} else if (message.event.type === "content_block_delta") {
|
||||
const delta = message.event.delta;
|
||||
if (delta.type === "text_delta") {
|
||||
state.liveText += delta.text;
|
||||
emit({ _tag: "AssistantDelta", kind: "text", delta: delta.text });
|
||||
} else if (delta.type === "thinking_delta") {
|
||||
emit({
|
||||
_tag: "AssistantDelta",
|
||||
kind: "thinking",
|
||||
delta: delta.thinking,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (message.type === "assistant") {
|
||||
handleAssistant(message);
|
||||
} else if (message.type === "user") {
|
||||
handleUser(message);
|
||||
} else if (message.type === "result") {
|
||||
handleResult(message);
|
||||
}
|
||||
};
|
||||
|
||||
const pump = async () => {
|
||||
let failure: string | undefined;
|
||||
try {
|
||||
for await (const message of nativeQuery) handleMessage(message);
|
||||
} catch (error) {
|
||||
if (!state.closed && !abortController.signal.aborted) {
|
||||
failure = boundedError(error);
|
||||
}
|
||||
} finally {
|
||||
if (!state.closed) {
|
||||
if (state.activeRun) {
|
||||
settle(
|
||||
state.interruptRequested
|
||||
? { _tag: "Interrupted", partialText: partialText() }
|
||||
: {
|
||||
_tag: "Failed",
|
||||
errorText:
|
||||
failure ?? "Claude Code query ended unexpectedly",
|
||||
partialText: partialText(),
|
||||
},
|
||||
);
|
||||
} else if (failure) {
|
||||
emit({ _tag: "BackendError", message: failure });
|
||||
}
|
||||
state.closed = true;
|
||||
Queue.endUnsafe(events);
|
||||
}
|
||||
resolvePumpDone?.();
|
||||
}
|
||||
};
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.promise(async () => {
|
||||
// Settle before marking closed: the pump's finally skips settlement
|
||||
// once closed, and every run must end in a RunSettled even when the
|
||||
// scope closes mid-run.
|
||||
if (state.activeRun) {
|
||||
settle({ _tag: "Interrupted", partialText: partialText() });
|
||||
}
|
||||
state.closed = true;
|
||||
input.end();
|
||||
abortController.abort();
|
||||
nativeQuery.close();
|
||||
await waitBounded(pumpDone, INTERRUPT_TIMEOUT_MS);
|
||||
Queue.endUnsafe(events);
|
||||
}),
|
||||
);
|
||||
|
||||
void pump();
|
||||
|
||||
const submit = (text: string) => {
|
||||
const wasActive = state.activeRun;
|
||||
const message = input.push(text);
|
||||
if (!message) return false;
|
||||
if (!wasActive) {
|
||||
state.activeRun = true;
|
||||
state.runVersion++;
|
||||
state.currentText = "";
|
||||
state.liveText = "";
|
||||
}
|
||||
state.submittedUuids.add(message.uuid ?? "");
|
||||
// Idle restarts flip status synchronously (like pi's startRun); a steer
|
||||
// into an active run must NOT re-emit RunStarted — its own turn begins
|
||||
// later via beginQueuedRunIfNeeded.
|
||||
if (!wasActive) emit({ _tag: "RunStarted" });
|
||||
emit({ _tag: "UserMessage", text });
|
||||
if (wasActive) {
|
||||
state.queued.push({
|
||||
text,
|
||||
kind: "steer",
|
||||
uuid: message.uuid ?? "",
|
||||
afterResponse: state.responseSequence,
|
||||
});
|
||||
emit({ _tag: "QueueChanged", queued: queuedView() });
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const waitForVersion = (version: number) => {
|
||||
if (state.lastSettledVersion >= version) return Promise.resolve();
|
||||
return new Promise<void>((resolve) => {
|
||||
const waiter = () => {
|
||||
if (state.lastSettledVersion < version && !state.closed) return;
|
||||
state.settleWaiters.delete(waiter);
|
||||
resolve();
|
||||
};
|
||||
state.settleWaiters.add(waiter);
|
||||
});
|
||||
};
|
||||
|
||||
emit({ _tag: "MetaChanged", meta: state.meta });
|
||||
submit(task.prompt);
|
||||
|
||||
return {
|
||||
meta: Effect.sync(() => state.meta),
|
||||
events: Stream.fromQueue(events),
|
||||
send: (text) =>
|
||||
Effect.suspend((): Effect.Effect<void, SendError> => {
|
||||
if (state.closed) {
|
||||
return new SendError({ message: "Subagent session is closed." });
|
||||
}
|
||||
return submit(text)
|
||||
? Effect.void
|
||||
: new SendError({ message: "Subagent session is closed." });
|
||||
}),
|
||||
interrupt: Effect.promise(async () => {
|
||||
if (state.closed || !state.activeRun) return;
|
||||
const version = state.runVersion;
|
||||
state.interruptRequested = true;
|
||||
input.clear();
|
||||
state.queued = [];
|
||||
emit({ _tag: "QueueChanged", queued: [] });
|
||||
|
||||
const interruptAndSettle = (async () => {
|
||||
try {
|
||||
const receipt = await nativeQuery.interrupt();
|
||||
const hasOwnQueuedMessage = receipt?.still_queued?.some((uuid) =>
|
||||
state.submittedUuids.has(uuid),
|
||||
);
|
||||
if (hasOwnQueuedMessage) {
|
||||
// 0.3.207 exposes cancellation receipts but no public per-message
|
||||
// cancel method. Closing is the only way to prevent a cancelled
|
||||
// queued prompt from immediately starting another turn.
|
||||
input.end();
|
||||
nativeQuery.close();
|
||||
}
|
||||
} catch (error) {
|
||||
if (!state.closed) {
|
||||
emit({ _tag: "BackendError", message: boundedError(error) });
|
||||
}
|
||||
}
|
||||
await waitForVersion(version);
|
||||
})();
|
||||
|
||||
await waitBounded(interruptAndSettle, INTERRUPT_TIMEOUT_MS);
|
||||
if (!state.closed && state.activeRun && state.runVersion === version) {
|
||||
// Covers pre-init/pending races and SDK versions that acknowledge an
|
||||
// interrupt without delivering a result. Force-close after settling
|
||||
// so a late native result cannot resurrect or re-settle this run.
|
||||
settle({ _tag: "Interrupted", partialText: partialText() });
|
||||
state.closed = true;
|
||||
input.end();
|
||||
abortController.abort();
|
||||
nativeQuery.close();
|
||||
Queue.endUnsafe(events);
|
||||
}
|
||||
}),
|
||||
} satisfies SubagentSession;
|
||||
});
|
||||
|
||||
// --- Backend -----------------------------------------------------------------
|
||||
|
||||
export const claudeBackend: SubagentBackend = {
|
||||
name: "claude",
|
||||
capabilities: { steering: true, modelSelection: true, reasoningEffort: true },
|
||||
available: Effect.sync(() => resolveClaudeBinary() !== undefined),
|
||||
spawn: makeClaudeSession,
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,575 @@
|
||||
/**
|
||||
* pi backend — real implementation over the pi SDK.
|
||||
*
|
||||
* Each subagent is an in-process `AgentSession` (a port of v1
|
||||
* subagents/manager.ts + shared/child-session.ts):
|
||||
* - real session files visible in /resume, child resources loaded per-cwd
|
||||
* with trust gating, and the child tool denylist;
|
||||
* - `session.subscribe()` events translated to normalized SubagentEvents;
|
||||
* - send() steers a streaming run or starts a fresh prompt() when idle;
|
||||
* - interrupt clears the queue and aborts; closing the session scope emits
|
||||
* the child session_shutdown hook and disposes the session.
|
||||
*/
|
||||
|
||||
import type { AssistantMessage, Message, Model } from "@earendil-works/pi-ai";
|
||||
import type {
|
||||
AgentSession,
|
||||
AgentSessionEvent,
|
||||
ModelRegistry,
|
||||
} from "@earendil-works/pi-coding-agent";
|
||||
import {
|
||||
createAgentSession,
|
||||
DefaultResourceLoader,
|
||||
getAgentDir,
|
||||
SessionManager,
|
||||
SettingsManager,
|
||||
} from "@earendil-works/pi-coding-agent";
|
||||
import type { Cause, Scope } from "effect";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
import type { SubagentBackend, SubagentSession } from "../backend.ts";
|
||||
import type {
|
||||
SpawnTask,
|
||||
SubagentEvent,
|
||||
SubagentMeta,
|
||||
TranscriptPart,
|
||||
} from "../domain.ts";
|
||||
import { SendError, SpawnError } from "../domain.ts";
|
||||
import { createToolCallTimeoutGuard } from "../../../shared/tool-call-timeout.ts";
|
||||
|
||||
const CHILD_SHUTDOWN_TIMEOUT_MS = 5_000;
|
||||
|
||||
/** Tools that headless children must not receive. Everything else stays enabled. */
|
||||
const CHILD_EXCLUDED_TOOL_NAMES = [
|
||||
"subagent_spawn",
|
||||
"subagent_wait",
|
||||
"subagent_cancel",
|
||||
"subagent_check",
|
||||
"subagent_list",
|
||||
"workflow",
|
||||
"ask_user",
|
||||
] as const;
|
||||
|
||||
// --- Model + effort resolution -----------------------------------------------
|
||||
|
||||
type ThinkingLevel = NonNullable<
|
||||
NonNullable<Parameters<typeof createAgentSession>[0]>["thinkingLevel"]
|
||||
>;
|
||||
|
||||
/**
|
||||
* Resolve the generic model hint against the parent registry (v1 semantics):
|
||||
* "provider/model-id" is exact; a bare id prefers the inherited provider,
|
||||
* then must be unambiguous across providers. No hint inherits the parent
|
||||
* model; with nothing to inherit, the SDK default applies.
|
||||
*/
|
||||
function resolvePiModel(
|
||||
registry: ModelRegistry,
|
||||
hint: string | undefined,
|
||||
inherited: { provider: string; id: string } | undefined,
|
||||
): Model<any> | undefined {
|
||||
if (!hint) {
|
||||
if (!inherited) return undefined;
|
||||
return registry.find(inherited.provider, inherited.id) ?? undefined;
|
||||
}
|
||||
const slash = hint.indexOf("/");
|
||||
if (slash > 0) {
|
||||
const provider = hint.slice(0, slash);
|
||||
const id = hint.slice(slash + 1);
|
||||
const found = registry.find(provider, id);
|
||||
if (found) return found;
|
||||
throw new Error(`Unknown model "${hint}".`);
|
||||
}
|
||||
if (inherited) {
|
||||
const found = registry.find(inherited.provider, hint);
|
||||
if (found) return found;
|
||||
}
|
||||
const matches = registry.getAll().filter((m) => m.id === hint);
|
||||
if (matches.length === 1) return matches[0];
|
||||
if (matches.length > 1) {
|
||||
throw new Error(
|
||||
`Model "${hint}" exists in multiple providers (${matches.map((m) => m.provider).join(", ")}). Use "provider/${hint}".`,
|
||||
);
|
||||
}
|
||||
throw new Error(`Unknown model "${hint}".`);
|
||||
}
|
||||
|
||||
// --- Child session helpers (ported from v1 shared/child-session.ts) -----------
|
||||
|
||||
/** Load normal global/package resources and trust-gated project resources. */
|
||||
async function createChildResources(cwd: string, projectTrusted: boolean) {
|
||||
const agentDir = getAgentDir();
|
||||
const settingsManager = SettingsManager.create(cwd, agentDir, {
|
||||
projectTrusted,
|
||||
});
|
||||
const loader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });
|
||||
await loader.reload();
|
||||
return { loader, settingsManager };
|
||||
}
|
||||
|
||||
function waitBounded(operation: Promise<unknown>, timeoutMs: number) {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeout = new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, timeoutMs);
|
||||
});
|
||||
return Promise.race([
|
||||
operation.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
),
|
||||
timeout,
|
||||
])
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
if (timer) clearTimeout(timer);
|
||||
});
|
||||
}
|
||||
|
||||
/** Emit child session_shutdown (bounded), then dispose. Never throws. */
|
||||
async function shutdownAndDisposeChildSession(session: AgentSession) {
|
||||
try {
|
||||
if (session.extensionRunner.hasHandlers("session_shutdown")) {
|
||||
await waitBounded(
|
||||
session.extensionRunner.emit({
|
||||
type: "session_shutdown",
|
||||
reason: "quit",
|
||||
}),
|
||||
CHILD_SHUTDOWN_TIMEOUT_MS,
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// Extension runner inspection/emission is best-effort during teardown.
|
||||
} finally {
|
||||
try {
|
||||
session.dispose();
|
||||
} catch {
|
||||
// Disposal is terminal and must remain idempotent for callers.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Event translation ----------------------------------------------------------
|
||||
|
||||
function messageRole(msg: unknown): Message["role"] | undefined {
|
||||
const role = (msg as { role?: string } | undefined)?.role;
|
||||
if (role === "user" || role === "assistant" || role === "toolResult")
|
||||
return role;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function lastAssistantMessage(
|
||||
session: AgentSession,
|
||||
): AssistantMessage | undefined {
|
||||
const messages = session.messages;
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const msg = messages[i];
|
||||
if (messageRole(msg) === "assistant") return msg as AssistantMessage;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Final assistant text output (last assistant message with text), v1 semantics. */
|
||||
function finalOutput(session: AgentSession): string {
|
||||
const messages = session.messages;
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const msg = messages[i];
|
||||
if (messageRole(msg) !== "assistant") continue;
|
||||
const text = (msg as AssistantMessage).content
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => part.text)
|
||||
.join("\n")
|
||||
.trim();
|
||||
if (text) return text;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function safeJson(value: unknown): string | undefined {
|
||||
try {
|
||||
const text = JSON.stringify(value);
|
||||
return text === "{}" ? undefined : text.slice(0, 4_096);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** First non-empty line of a tool result-ish value (v1 liveToolPreview). */
|
||||
function toolPreview(value: unknown): string | undefined {
|
||||
if (typeof value === "string") {
|
||||
return value
|
||||
.split("\n")
|
||||
.find((line) => line.trim())
|
||||
?.trim();
|
||||
}
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
const content = (value as { content?: unknown }).content;
|
||||
if (!Array.isArray(content)) return undefined;
|
||||
for (const part of content) {
|
||||
if (!part || typeof part !== "object") continue;
|
||||
const record = part as { type?: unknown; text?: unknown };
|
||||
if (record.type !== "text" || typeof record.text !== "string") continue;
|
||||
const firstLine = record.text.split("\n").find((line) => line.trim());
|
||||
if (firstLine) return firstLine.trim();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function assistantParts(msg: AssistantMessage): TranscriptPart[] {
|
||||
const parts: TranscriptPart[] = [];
|
||||
for (const part of msg.content) {
|
||||
if (part.type === "text") {
|
||||
parts.push({ type: "text", text: part.text });
|
||||
} else if (part.type === "thinking") {
|
||||
parts.push({
|
||||
type: "thinking",
|
||||
text: part.redacted ? "" : part.thinking,
|
||||
redacted: part.redacted,
|
||||
});
|
||||
} else if (part.type === "toolCall") {
|
||||
parts.push({
|
||||
type: "toolCall",
|
||||
toolId: part.id,
|
||||
name: part.name,
|
||||
argsPreview: safeJson(part.arguments),
|
||||
});
|
||||
}
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
function userText(msg: Message): string {
|
||||
const content = (msg as { content: unknown }).content;
|
||||
if (typeof content === "string") return content;
|
||||
if (!Array.isArray(content)) return "";
|
||||
return content
|
||||
.filter(
|
||||
(part): part is { type: "text"; text: string } =>
|
||||
!!part &&
|
||||
typeof part === "object" &&
|
||||
(part as { type?: unknown }).type === "text",
|
||||
)
|
||||
.map((part) => part.text)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
// --- The session ------------------------------------------------------------------
|
||||
|
||||
function boundedError(error: unknown) {
|
||||
return (error instanceof Error ? error.message : String(error)).slice(
|
||||
0,
|
||||
4096,
|
||||
);
|
||||
}
|
||||
|
||||
const makePiSession = (
|
||||
task: SpawnTask,
|
||||
): Effect.Effect<SubagentSession, SpawnError, Scope.Scope> =>
|
||||
Effect.gen(function* () {
|
||||
const registry = task.parent.modelRegistry;
|
||||
if (!registry) {
|
||||
return yield* new SpawnError({
|
||||
message: "pi backend requires the parent session's model registry.",
|
||||
});
|
||||
}
|
||||
|
||||
const model = yield* Effect.try({
|
||||
try: () =>
|
||||
resolvePiModel(registry, task.model, task.parent.inheritedModel),
|
||||
catch: (error) => new SpawnError({ message: boundedError(error) }),
|
||||
});
|
||||
// pi's thinking levels ARE the shared reasoning-effort scale.
|
||||
const thinkingLevel = (task.reasoningEffort ??
|
||||
task.parent.inheritedThinkingLevel) as ThinkingLevel | undefined;
|
||||
|
||||
const session = yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const { loader, settingsManager } = await createChildResources(
|
||||
task.cwd,
|
||||
task.parent.projectTrusted,
|
||||
);
|
||||
const { session } = await createAgentSession({
|
||||
cwd: task.cwd,
|
||||
sessionManager: SessionManager.create(task.cwd),
|
||||
settingsManager,
|
||||
resourceLoader: loader,
|
||||
model,
|
||||
thinkingLevel,
|
||||
excludeTools: [...CHILD_EXCLUDED_TOOL_NAMES],
|
||||
});
|
||||
// Start child extension session hooks/resources in headless mode.
|
||||
// A rejection here would otherwise leak the freshly created session:
|
||||
// the scope finalizer that owns cleanup is only registered later.
|
||||
try {
|
||||
await session.bindExtensions({ mode: "print" });
|
||||
} catch (error) {
|
||||
await shutdownAndDisposeChildSession(session);
|
||||
throw error;
|
||||
}
|
||||
return session;
|
||||
},
|
||||
catch: (error) => new SpawnError({ message: boundedError(error) }),
|
||||
});
|
||||
|
||||
const state = {
|
||||
closed: false,
|
||||
/** prompt() rejection for the active run; folded into RunSettled. */
|
||||
runError: undefined as string | undefined,
|
||||
/** One terminal event per run: lifecycle, prompt-rejection, and abort
|
||||
* fallbacks can all race to settle; the first wins. */
|
||||
settled: false,
|
||||
};
|
||||
|
||||
const events = yield* Queue.make<SubagentEvent, Cause.Done>();
|
||||
const emit = (event: SubagentEvent) => {
|
||||
Queue.offerUnsafe(events, event);
|
||||
};
|
||||
|
||||
const toolTimeout = createToolCallTimeoutGuard();
|
||||
toolTimeout.apply(session);
|
||||
|
||||
const activeModel = (): Model<any> | undefined => {
|
||||
const sessionModel = session.model;
|
||||
const last = lastAssistantMessage(session);
|
||||
if (!last) return sessionModel;
|
||||
if (
|
||||
sessionModel &&
|
||||
(last.provider !== sessionModel.provider ||
|
||||
last.model !== sessionModel.id)
|
||||
) {
|
||||
// The session changed models after this assistant response.
|
||||
return sessionModel;
|
||||
}
|
||||
return (
|
||||
registry.find(last.provider, last.responseModel ?? last.model) ??
|
||||
sessionModel
|
||||
);
|
||||
};
|
||||
|
||||
const currentMeta = (): SubagentMeta => {
|
||||
const m = activeModel();
|
||||
return {
|
||||
backend: "pi",
|
||||
modelLabel: m ? `${m.provider}/${m.id}` : undefined,
|
||||
contextWindow: m?.contextWindow,
|
||||
sessionFilePath: session.sessionFile,
|
||||
};
|
||||
};
|
||||
|
||||
const emitUsage = () => {
|
||||
const usage = session.getContextUsage();
|
||||
emit({
|
||||
_tag: "UsageChanged",
|
||||
tokens: usage?.tokens ?? undefined,
|
||||
contextWindow: activeModel()?.contextWindow ?? usage?.contextWindow,
|
||||
});
|
||||
};
|
||||
|
||||
const settle = () => {
|
||||
if (state.settled) return;
|
||||
state.settled = true;
|
||||
const last = lastAssistantMessage(session);
|
||||
const partialText = finalOutput(session) || undefined;
|
||||
if (last?.stopReason === "aborted") {
|
||||
emit({
|
||||
_tag: "RunSettled",
|
||||
outcome: { _tag: "Interrupted", partialText },
|
||||
});
|
||||
return;
|
||||
}
|
||||
const errorText =
|
||||
state.runError ??
|
||||
(last?.stopReason === "error"
|
||||
? (last.errorMessage ?? "Run failed")
|
||||
: undefined);
|
||||
if (errorText !== undefined) {
|
||||
emit({
|
||||
_tag: "RunSettled",
|
||||
outcome: {
|
||||
_tag: "Failed",
|
||||
errorText: boundedError(errorText),
|
||||
partialText,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
emit({
|
||||
_tag: "RunSettled",
|
||||
outcome: { _tag: "Completed", finalText: finalOutput(session) },
|
||||
});
|
||||
};
|
||||
|
||||
const handleEvent = (event: AgentSessionEvent) => {
|
||||
if (state.closed) return;
|
||||
switch (event.type) {
|
||||
case "agent_start":
|
||||
// Extensions may register tools between runs; guard new ones too.
|
||||
toolTimeout.apply(session);
|
||||
state.settled = false;
|
||||
emit({ _tag: "RunStarted" });
|
||||
break;
|
||||
case "message_update": {
|
||||
const streamEvent = event.assistantMessageEvent;
|
||||
if (streamEvent.type === "text_delta") {
|
||||
emit({
|
||||
_tag: "AssistantDelta",
|
||||
kind: "text",
|
||||
delta: streamEvent.delta,
|
||||
});
|
||||
} else if (streamEvent.type === "thinking_delta") {
|
||||
emit({
|
||||
_tag: "AssistantDelta",
|
||||
kind: "thinking",
|
||||
delta: streamEvent.delta,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "message_end": {
|
||||
const role = messageRole(event.message);
|
||||
if (role === "user") {
|
||||
const text = userText(event.message as Message);
|
||||
if (text.trim()) emit({ _tag: "UserMessage", text });
|
||||
} else if (role === "assistant") {
|
||||
emit({
|
||||
_tag: "AssistantMessage",
|
||||
parts: assistantParts(event.message as AssistantMessage),
|
||||
});
|
||||
emitUsage();
|
||||
emit({ _tag: "MetaChanged", meta: currentMeta() });
|
||||
}
|
||||
// toolResult messages are covered by tool_execution_end.
|
||||
break;
|
||||
}
|
||||
case "tool_execution_start":
|
||||
emit({
|
||||
_tag: "ToolStart",
|
||||
toolId: event.toolCallId,
|
||||
name: event.toolName,
|
||||
argsPreview: safeJson(event.args),
|
||||
});
|
||||
break;
|
||||
case "tool_execution_update":
|
||||
emit({
|
||||
_tag: "ToolUpdate",
|
||||
toolId: event.toolCallId,
|
||||
outputPreview: toolPreview(event.partialResult),
|
||||
});
|
||||
break;
|
||||
case "tool_execution_end":
|
||||
emit({
|
||||
_tag: "ToolEnd",
|
||||
toolId: event.toolCallId,
|
||||
name: event.toolName,
|
||||
isError: event.isError,
|
||||
outputPreview: toolPreview(event.result),
|
||||
});
|
||||
break;
|
||||
case "queue_update":
|
||||
emit({
|
||||
_tag: "QueueChanged",
|
||||
queued: [
|
||||
...event.steering.map((text) => ({
|
||||
text,
|
||||
kind: "steer" as const,
|
||||
})),
|
||||
...event.followUp.map((text) => ({
|
||||
text,
|
||||
kind: "follow-up" as const,
|
||||
})),
|
||||
],
|
||||
});
|
||||
break;
|
||||
case "agent_settled":
|
||||
settle();
|
||||
break;
|
||||
}
|
||||
};
|
||||
const unsubscribe = session.subscribe(handleEvent);
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.promise(async () => {
|
||||
state.closed = true;
|
||||
unsubscribe();
|
||||
try {
|
||||
session.clearQueue();
|
||||
} catch {
|
||||
// Continue with abort/dispose.
|
||||
}
|
||||
await waitBounded(session.abort(), CHILD_SHUTDOWN_TIMEOUT_MS);
|
||||
await shutdownAndDisposeChildSession(session);
|
||||
Queue.endUnsafe(events);
|
||||
}),
|
||||
);
|
||||
|
||||
/** Start a fresh run (v1 manager.run): fire-and-forget, errors -> events. */
|
||||
const startRun = (text: string) => {
|
||||
state.runError = undefined;
|
||||
state.settled = false;
|
||||
emit({ _tag: "RunStarted" });
|
||||
void session.prompt(text).catch((error) => {
|
||||
state.runError = boundedError(error);
|
||||
// Preflight failures may never start the agent lifecycle, so no
|
||||
// agent_settled will arrive for them.
|
||||
if (!session.isStreaming) settle();
|
||||
});
|
||||
};
|
||||
|
||||
// Session naming is best-effort.
|
||||
yield* Effect.try(() =>
|
||||
session.sessionManager.appendSessionInfo(
|
||||
`${task.origin === "btw" ? "btw" : "subagent"}: ${task.title}`,
|
||||
),
|
||||
).pipe(Effect.ignore);
|
||||
|
||||
emit({ _tag: "MetaChanged", meta: currentMeta() });
|
||||
startRun(task.prompt);
|
||||
|
||||
return {
|
||||
meta: Effect.sync(currentMeta),
|
||||
events: Stream.fromQueue(events),
|
||||
send: (text) =>
|
||||
Effect.suspend((): Effect.Effect<void, SendError> => {
|
||||
if (state.closed) {
|
||||
return new SendError({ message: "Subagent session is closed." });
|
||||
}
|
||||
if (session.isStreaming) {
|
||||
// Steer the active run via the SDK's queue; queue_update events
|
||||
// render it, message_end(user) lands it in the transcript. A
|
||||
// rejected steer is a real send failure, not a diagnostic.
|
||||
return Effect.tryPromise({
|
||||
try: () => session.steer(text),
|
||||
catch: (error) => new SendError({ message: boundedError(error) }),
|
||||
}).pipe(Effect.asVoid);
|
||||
}
|
||||
return Effect.sync(() => startRun(text));
|
||||
}),
|
||||
interrupt: Effect.promise(async () => {
|
||||
if (state.closed) return;
|
||||
try {
|
||||
session.clearQueue();
|
||||
} catch {
|
||||
// Abort regardless.
|
||||
}
|
||||
await session.abort().catch(() => undefined);
|
||||
// Only resolve once streaming has actually stopped: reporting the
|
||||
// interrupt as complete while the run keeps working would let the
|
||||
// manager settle a run that is still mutating the workspace. The
|
||||
// manager bounds this effect at 5s and force-disposes on timeout.
|
||||
while (!state.closed && session.isStreaming) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
// No streaming run means no agent_settled will arrive; emit the
|
||||
// terminal event (once) so the run cannot look running forever.
|
||||
if (!state.closed && !state.settled) {
|
||||
state.settled = true;
|
||||
emit({ _tag: "RunSettled", outcome: { _tag: "Interrupted" } });
|
||||
}
|
||||
}),
|
||||
} satisfies SubagentSession;
|
||||
});
|
||||
|
||||
export const piBackend: SubagentBackend = {
|
||||
name: "pi",
|
||||
capabilities: { steering: true, modelSelection: true, reasoningEffort: true },
|
||||
// In-process SDK: always available.
|
||||
available: Effect.succeed(true),
|
||||
spawn: makePiSession,
|
||||
};
|
||||
@@ -0,0 +1,300 @@
|
||||
/**
|
||||
* Scripted stub sessions shared by all three backend implementations while
|
||||
* the real integrations are pending. A stub session:
|
||||
*
|
||||
* - streams a plausible turn (thinking deltas, one fake tool cycle, text
|
||||
* deltas, usage ramp, a final assistant message, RunSettled) over a few
|
||||
* seconds so streaming UI, wait, and the footer counters are observable;
|
||||
* - supports send() while running (queued-steer rendering) and while idle
|
||||
* (fresh run);
|
||||
* - supports interrupt (RunSettled Interrupted -> status "error", matching v1);
|
||||
* - fails the run when the prompt starts with "FAIL:" (error-path testing);
|
||||
* - appends every event to a JSONL "session file" in tmpdir so the
|
||||
* "full transcript in session file" pointers resolve.
|
||||
*/
|
||||
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import type { Cause, Scope } from "effect";
|
||||
import { Duration, Effect, Fiber, Queue, Ref, Stream } from "effect";
|
||||
import type { SubagentBackend, SubagentSession } from "../backend.ts";
|
||||
import type {
|
||||
BackendName,
|
||||
QueuedMessage,
|
||||
SpawnTask,
|
||||
SubagentEvent,
|
||||
SubagentMeta,
|
||||
} from "../domain.ts";
|
||||
import { SendError } from "../domain.ts";
|
||||
|
||||
export interface StubProfile {
|
||||
readonly backend: BackendName;
|
||||
readonly defaultModelLabel: string;
|
||||
readonly contextWindow: number;
|
||||
readonly toolName: string;
|
||||
/** Delay between scripted events; varies per backend so streams differ. */
|
||||
readonly cadenceMs: number;
|
||||
}
|
||||
|
||||
const STUB_DIR = path.join(os.tmpdir(), "subagents-stub");
|
||||
let sessionCounter = 0;
|
||||
|
||||
export function makeStubBackend(profile: StubProfile): SubagentBackend {
|
||||
return {
|
||||
name: profile.backend,
|
||||
capabilities: {
|
||||
steering: true,
|
||||
modelSelection: true,
|
||||
reasoningEffort: true,
|
||||
},
|
||||
// Real impls probe binary-on-PATH / SDK import / credentials here.
|
||||
available: Effect.succeed(true),
|
||||
spawn: (task) => makeStubSession(profile, task),
|
||||
};
|
||||
}
|
||||
|
||||
function firstLine(text: string): string {
|
||||
return (
|
||||
text
|
||||
.split("\n")
|
||||
.find((line) => line.trim())
|
||||
?.trim() ?? ""
|
||||
);
|
||||
}
|
||||
|
||||
function chunked(text: string, size: number): string[] {
|
||||
const chunks: string[] = [];
|
||||
for (let i = 0; i < text.length; i += size)
|
||||
chunks.push(text.slice(i, i + size));
|
||||
return chunks;
|
||||
}
|
||||
|
||||
const makeStubSession = (
|
||||
profile: StubProfile,
|
||||
task: SpawnTask,
|
||||
): Effect.Effect<SubagentSession, never, Scope.Scope> =>
|
||||
Effect.gen(function* () {
|
||||
const sessionId = `stub-${profile.backend}-${++sessionCounter}`;
|
||||
const sessionFile = path.join(STUB_DIR, `${sessionId}.jsonl`);
|
||||
|
||||
const state = {
|
||||
meta: {
|
||||
backend: profile.backend,
|
||||
modelLabel: task.model ?? profile.defaultModelLabel,
|
||||
contextWindow: profile.contextWindow,
|
||||
sessionFilePath: sessionFile,
|
||||
nativeSessionId: sessionId,
|
||||
} satisfies SubagentMeta as SubagentMeta,
|
||||
pending: [] as string[],
|
||||
turnCount: 0,
|
||||
closed: false,
|
||||
/** True between the driver dequeuing a prompt and registering its turn fiber. */
|
||||
dispatching: false,
|
||||
};
|
||||
|
||||
const events = yield* Queue.make<SubagentEvent, Cause.Done>();
|
||||
const inbox = yield* Queue.make<string, Cause.Done>();
|
||||
const activeTurn = yield* Ref.make<Fiber.Fiber<void> | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
const emit = (event: SubagentEvent) =>
|
||||
Effect.suspend(() => {
|
||||
try {
|
||||
fs.appendFileSync(sessionFile, `${JSON.stringify(event)}\n`);
|
||||
} catch {
|
||||
// The fake session file is best-effort.
|
||||
}
|
||||
if (event._tag === "MetaChanged") {
|
||||
state.meta = { ...state.meta, ...event.meta };
|
||||
}
|
||||
return Queue.offer(events, event);
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const pause = Effect.sleep(Duration.millis(profile.cadenceMs));
|
||||
|
||||
const runTurn = (userText: string, turn: number) =>
|
||||
Effect.gen(function* () {
|
||||
yield* emit({ _tag: "RunStarted" });
|
||||
const failing = userText.trimStart().startsWith("FAIL:");
|
||||
|
||||
const thinking = "Looking at the task and planning an approach...";
|
||||
for (const delta of chunked(thinking, 16)) {
|
||||
yield* emit({ _tag: "AssistantDelta", kind: "thinking", delta });
|
||||
yield* pause;
|
||||
}
|
||||
|
||||
const toolId = `${sessionId}-tool-${turn}`;
|
||||
const argsPreview = `{"command":"ls ${task.cwd}"}`;
|
||||
yield* emit({
|
||||
_tag: "AssistantMessage",
|
||||
parts: [
|
||||
{ type: "thinking", text: thinking },
|
||||
{
|
||||
type: "text",
|
||||
text: `I'll run ${profile.toolName} to look around first.`,
|
||||
},
|
||||
{ type: "toolCall", toolId, name: profile.toolName, argsPreview },
|
||||
],
|
||||
});
|
||||
yield* emit({
|
||||
_tag: "ToolStart",
|
||||
toolId,
|
||||
name: profile.toolName,
|
||||
argsPreview,
|
||||
});
|
||||
yield* pause;
|
||||
yield* emit({
|
||||
_tag: "ToolUpdate",
|
||||
toolId,
|
||||
outputPreview: "src docs package.json",
|
||||
});
|
||||
yield* pause;
|
||||
yield* emit({
|
||||
_tag: "ToolEnd",
|
||||
toolId,
|
||||
name: profile.toolName,
|
||||
isError: false,
|
||||
outputPreview: "src docs package.json",
|
||||
});
|
||||
yield* emit({
|
||||
_tag: "UsageChanged",
|
||||
tokens: Math.min(profile.contextWindow, 2400 * (turn + 1)),
|
||||
contextWindow: profile.contextWindow,
|
||||
});
|
||||
|
||||
if (failing) {
|
||||
yield* pause;
|
||||
yield* emit({
|
||||
_tag: "RunSettled",
|
||||
outcome: {
|
||||
_tag: "Failed",
|
||||
errorText: `[stub:${profile.backend}] task failed as requested by FAIL: prefix`,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const finalText =
|
||||
`[stub:${profile.backend}] completed: ${firstLine(userText).slice(0, 200)}\n\n` +
|
||||
`This is a stubbed ${profile.backend} subagent turn ${turn + 1}. ` +
|
||||
`The real backend integration will replace this scripted output.`;
|
||||
for (const delta of chunked(finalText, 24)) {
|
||||
yield* emit({ _tag: "AssistantDelta", kind: "text", delta });
|
||||
yield* pause;
|
||||
}
|
||||
yield* emit({
|
||||
_tag: "AssistantMessage",
|
||||
parts: [{ type: "text", text: finalText }],
|
||||
});
|
||||
yield* emit({
|
||||
_tag: "UsageChanged",
|
||||
tokens: Math.min(profile.contextWindow, 2400 * (turn + 1) + 900),
|
||||
contextWindow: profile.contextWindow,
|
||||
});
|
||||
yield* emit({
|
||||
_tag: "RunSettled",
|
||||
outcome: { _tag: "Completed", finalText },
|
||||
});
|
||||
});
|
||||
|
||||
const queuedView = (): ReadonlyArray<QueuedMessage> =>
|
||||
state.pending.map((text) => ({ text, kind: "steer" as const }));
|
||||
|
||||
// Driver: one turn at a time, in submission order. Turns run as child
|
||||
// fibers so interrupt() stops the turn without killing the driver.
|
||||
const driver = Effect.gen(function* () {
|
||||
while (true) {
|
||||
const text = yield* Queue.take(inbox);
|
||||
state.dispatching = true;
|
||||
state.pending.shift();
|
||||
yield* emit({ _tag: "QueueChanged", queued: queuedView() });
|
||||
yield* emit({ _tag: "UserMessage", text });
|
||||
const turn = state.turnCount++;
|
||||
const fiber = yield* Effect.forkChild(
|
||||
runTurn(text, turn).pipe(
|
||||
Effect.onInterrupt(() =>
|
||||
emit({
|
||||
_tag: "RunSettled",
|
||||
outcome: { _tag: "Interrupted" },
|
||||
}).pipe(Effect.ignore),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* Ref.set(activeTurn, fiber);
|
||||
state.dispatching = false;
|
||||
yield* Fiber.await(fiber);
|
||||
yield* Ref.set(activeTurn, undefined);
|
||||
}
|
||||
});
|
||||
yield* Effect.forkScoped(driver.pipe(Effect.ignore));
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.gen(function* () {
|
||||
state.closed = true;
|
||||
yield* Queue.end(inbox).pipe(Effect.ignore);
|
||||
yield* Queue.end(events).pipe(Effect.ignore);
|
||||
}),
|
||||
);
|
||||
|
||||
const submit = (text: string) =>
|
||||
Effect.gen(function* () {
|
||||
if (state.closed) {
|
||||
return yield* new SendError({
|
||||
message: "Subagent session is closed.",
|
||||
});
|
||||
}
|
||||
state.pending.push(text);
|
||||
const busy = (yield* Ref.get(activeTurn)) !== undefined;
|
||||
if (busy) {
|
||||
// Show the queued steer line until the driver picks it up.
|
||||
yield* emit({ _tag: "QueueChanged", queued: queuedView() });
|
||||
}
|
||||
yield* Queue.offer(inbox, text);
|
||||
});
|
||||
|
||||
// Announce metadata, then kick off the initial run.
|
||||
yield* Effect.try(() => fs.mkdirSync(STUB_DIR, { recursive: true })).pipe(
|
||||
Effect.ignore, // The fake session file directory is best-effort.
|
||||
);
|
||||
yield* emit({ _tag: "MetaChanged", meta: state.meta });
|
||||
// The session cannot be closed yet, so the initial submit cannot fail.
|
||||
yield* submit(task.prompt).pipe(Effect.orDie);
|
||||
|
||||
return {
|
||||
meta: Effect.sync(() => state.meta),
|
||||
events: Stream.fromQueue(events),
|
||||
send: submit,
|
||||
interrupt: Effect.gen(function* () {
|
||||
// Drop queued prompts so interrupting cannot immediately start
|
||||
// another turn, then stop the active turn. A prompt may be mid-flight
|
||||
// between the driver dequeuing it and registering its fiber, so wait
|
||||
// that window out instead of silently missing the turn.
|
||||
const cleared = yield* Queue.clear(inbox).pipe(
|
||||
Effect.orElseSucceed(() => []),
|
||||
);
|
||||
state.pending = [];
|
||||
yield* emit({ _tag: "QueueChanged", queued: [] });
|
||||
while (true) {
|
||||
const fiber = yield* Ref.get(activeTurn);
|
||||
if (fiber) {
|
||||
yield* Fiber.interrupt(fiber);
|
||||
return;
|
||||
}
|
||||
if (!state.dispatching) {
|
||||
// No turn ever started. If we cancelled queued prompts, the run
|
||||
// still needs a terminal event or it would look running forever.
|
||||
if (cleared.length > 0) {
|
||||
yield* emit({
|
||||
_tag: "RunSettled",
|
||||
outcome: { _tag: "Interrupted" },
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
yield* Effect.sleep(Duration.millis(5));
|
||||
}
|
||||
}),
|
||||
} satisfies SubagentSession;
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { SubagentOrigin } from "./domain.ts";
|
||||
|
||||
export const BTW_TITLE_MAX_LENGTH = 60;
|
||||
|
||||
/** Build a compact dashboard title from the first non-empty prompt line. */
|
||||
export function deriveBtwTitle(prompt: string) {
|
||||
const firstLine = prompt
|
||||
.split("\n")
|
||||
.find((line) => line.trim())
|
||||
?.trim();
|
||||
const title = firstLine?.replace(/\s+/g, " ") ?? "";
|
||||
if (!title) return "by the way";
|
||||
const codePoints = Array.from(title);
|
||||
if (codePoints.length <= BTW_TITLE_MAX_LENGTH) return title;
|
||||
return `${codePoints.slice(0, BTW_TITLE_MAX_LENGTH - 1).join("")}…`;
|
||||
}
|
||||
|
||||
/** User asides remain visible in the dashboard but hidden from model tools. */
|
||||
export function isModelVisible(snap: { readonly origin: SubagentOrigin }) {
|
||||
return snap.origin === "model";
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* Domain model for subagents.
|
||||
*
|
||||
* Everything downstream of a backend (manager, tools, UI) speaks only these
|
||||
* types. Backends translate their native streams (pi session events, Claude
|
||||
* Agent SDK messages, Codex app-server JSON-RPC notifications) into the
|
||||
* normalized `SubagentEvent` union.
|
||||
*/
|
||||
|
||||
import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
|
||||
import { Data } from "effect";
|
||||
|
||||
export const BACKEND_NAMES = ["pi", "claude", "codex"] as const;
|
||||
export type BackendName = (typeof BACKEND_NAMES)[number];
|
||||
|
||||
/** Who initiated the session. User asides stay out of model-facing tooling. */
|
||||
export type SubagentOrigin = "model" | "btw";
|
||||
|
||||
/**
|
||||
* Shared reasoning-effort scale (pi's thinking levels). Each backend maps a
|
||||
* value to its nearest native equivalent: pi uses it directly, codex
|
||||
* translates to its reasoning-effort slugs, claude translates to thinking
|
||||
* budgets. Omitted = backend default (pi inherits the parent level).
|
||||
*/
|
||||
export const REASONING_EFFORTS = [
|
||||
"off",
|
||||
"minimal",
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
] as const;
|
||||
export type ReasoningEffort = (typeof REASONING_EFFORTS)[number];
|
||||
|
||||
export type SubagentStatus = "running" | "done" | "error";
|
||||
|
||||
/** Parent-session context resolved by the tool layer and passed opaquely. */
|
||||
export interface ParentContext {
|
||||
readonly parentCwd: string;
|
||||
readonly projectTrusted: boolean;
|
||||
/** Parent pi model, for the pi backend's "inherit" default. */
|
||||
readonly inheritedModel?: { readonly provider: string; readonly id: string };
|
||||
readonly inheritedThinkingLevel?: string;
|
||||
/** Parent model registry; required by the pi backend to resolve models. */
|
||||
readonly modelRegistry?: ModelRegistry;
|
||||
}
|
||||
|
||||
export interface SpawnTask {
|
||||
/** Omitted for normal tool-driven spawns. */
|
||||
readonly origin?: SubagentOrigin;
|
||||
readonly prompt: string;
|
||||
readonly title: string;
|
||||
readonly cwd: string;
|
||||
/**
|
||||
* Generic model hint, interpreted per backend:
|
||||
* pi: "provider/model-id" or bare model id; claude: model alias;
|
||||
* codex: model slug. Omitted = backend default / inherit.
|
||||
*/
|
||||
readonly model?: string;
|
||||
/** Shared effort scale; each backend maps it to its native equivalent. */
|
||||
readonly reasoningEffort?: ReasoningEffort;
|
||||
readonly parent: ParentContext;
|
||||
}
|
||||
|
||||
export interface SubagentMeta {
|
||||
readonly backend: BackendName;
|
||||
/** Display label, e.g. "anthropic/claude-opus-4-5" or "gpt-5-codex". */
|
||||
readonly modelLabel?: string;
|
||||
/** Context window capacity for utilization display, when known. */
|
||||
readonly contextWindow?: number;
|
||||
/** pi session file / Claude projects JSONL / Codex rollout path. */
|
||||
readonly sessionFilePath?: string;
|
||||
/** Claude session id / Codex conversation id. */
|
||||
readonly nativeSessionId?: string;
|
||||
}
|
||||
|
||||
// --- Transcript ------------------------------------------------------------
|
||||
|
||||
export type TranscriptPart =
|
||||
| { readonly type: "text"; readonly text: string }
|
||||
| {
|
||||
readonly type: "thinking";
|
||||
readonly text: string;
|
||||
readonly redacted?: boolean;
|
||||
}
|
||||
| {
|
||||
readonly type: "toolCall";
|
||||
readonly toolId: string;
|
||||
readonly name: string;
|
||||
readonly argsPreview?: string;
|
||||
};
|
||||
|
||||
export type TranscriptItem =
|
||||
| { readonly kind: "user"; readonly text: string }
|
||||
| {
|
||||
readonly kind: "assistant";
|
||||
readonly parts: ReadonlyArray<TranscriptPart>;
|
||||
}
|
||||
| {
|
||||
readonly kind: "toolResult";
|
||||
readonly toolId: string;
|
||||
readonly name: string;
|
||||
readonly isError: boolean;
|
||||
readonly outputPreview?: string;
|
||||
};
|
||||
|
||||
export interface LiveToolState {
|
||||
readonly toolId: string;
|
||||
readonly name: string;
|
||||
readonly argsPreview?: string;
|
||||
readonly outputPreview?: string;
|
||||
readonly done?: boolean;
|
||||
readonly isError?: boolean;
|
||||
}
|
||||
|
||||
export interface QueuedMessage {
|
||||
readonly text: string;
|
||||
readonly kind: "steer" | "follow-up";
|
||||
}
|
||||
|
||||
// --- Events ------------------------------------------------------------------
|
||||
|
||||
export type RunOutcome =
|
||||
| { readonly _tag: "Completed"; readonly finalText: string }
|
||||
| {
|
||||
readonly _tag: "Failed";
|
||||
readonly errorText: string;
|
||||
readonly partialText?: string;
|
||||
}
|
||||
| { readonly _tag: "Interrupted"; readonly partialText?: string };
|
||||
|
||||
/**
|
||||
* Normalized activity stream. Previews (`argsPreview`, `outputPreview`) are
|
||||
* pre-flattened single-line strings because the UI only ever renders one
|
||||
* sanitized line, which keeps three different native tool-result shapes out
|
||||
* of the interface.
|
||||
*/
|
||||
export type SubagentEvent =
|
||||
// lifecycle (a session can run multiple turns via send())
|
||||
| { readonly _tag: "RunStarted" }
|
||||
| { readonly _tag: "RunSettled"; readonly outcome: RunOutcome }
|
||||
// transcript building blocks
|
||||
| { readonly _tag: "UserMessage"; readonly text: string }
|
||||
| {
|
||||
readonly _tag: "AssistantDelta";
|
||||
readonly kind: "text" | "thinking";
|
||||
readonly delta: string;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "AssistantMessage";
|
||||
readonly parts: ReadonlyArray<TranscriptPart>;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "ToolStart";
|
||||
readonly toolId: string;
|
||||
readonly name: string;
|
||||
readonly argsPreview?: string;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "ToolUpdate";
|
||||
readonly toolId: string;
|
||||
readonly outputPreview?: string;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "ToolEnd";
|
||||
readonly toolId: string;
|
||||
readonly name: string;
|
||||
readonly isError: boolean;
|
||||
readonly outputPreview?: string;
|
||||
}
|
||||
// bookkeeping
|
||||
| {
|
||||
readonly _tag: "QueueChanged";
|
||||
readonly queued: ReadonlyArray<QueuedMessage>;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "UsageChanged";
|
||||
readonly tokens?: number;
|
||||
readonly contextWindow?: number;
|
||||
}
|
||||
| { readonly _tag: "MetaChanged"; readonly meta: Partial<SubagentMeta> }
|
||||
/** Non-fatal diagnostics. Fatal failures arrive as a RunSettled outcome. */
|
||||
| { readonly _tag: "BackendError"; readonly message: string };
|
||||
|
||||
// --- Snapshot ---------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The manager folds `SubagentEvent`s into one snapshot per subagent. This is
|
||||
* everything the tools, footer status, and both TUI views read.
|
||||
*/
|
||||
export interface SubagentSnapshot {
|
||||
readonly id: string;
|
||||
readonly origin: SubagentOrigin;
|
||||
readonly backend: BackendName;
|
||||
readonly title: string;
|
||||
readonly prompt: string;
|
||||
readonly cwd: string;
|
||||
readonly status: SubagentStatus;
|
||||
readonly createdAt: number;
|
||||
readonly settledAt?: number;
|
||||
readonly errorText?: string;
|
||||
readonly meta: SubagentMeta;
|
||||
readonly usage: { readonly tokens?: number; readonly contextWindow?: number };
|
||||
readonly transcript: ReadonlyArray<TranscriptItem>;
|
||||
/** Streaming assistant buffers, cleared when the finalized message lands. */
|
||||
readonly liveAssistant?: { readonly text: string; readonly thinking: string };
|
||||
readonly liveTools: ReadonlyArray<LiveToolState>;
|
||||
readonly queued: ReadonlyArray<QueuedMessage>;
|
||||
/** Final text of the most recent completed run (v1 `finalOutput`). */
|
||||
readonly finalText: string;
|
||||
/** Count of finalized assistant messages (for subagent_check). */
|
||||
readonly turns: number;
|
||||
}
|
||||
|
||||
/** Final text, or the live streaming buffer while a run is active (v1 `latestOutput`). */
|
||||
export function latestText(snap: SubagentSnapshot) {
|
||||
const live = snap.liveAssistant?.text.trim();
|
||||
if (live) return live;
|
||||
return snap.finalText;
|
||||
}
|
||||
|
||||
export function formatElapsed(snap: SubagentSnapshot) {
|
||||
const end = snap.settledAt ?? Date.now();
|
||||
const totalSeconds = Math.max(0, Math.round((end - snap.createdAt) / 1000));
|
||||
const minutes = Math.floor(totalSeconds / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
return minutes > 0
|
||||
? `${minutes}m${seconds.toString().padStart(2, "0")}s`
|
||||
: `${seconds}s`;
|
||||
}
|
||||
|
||||
// --- Errors -------------------------------------------------------------------
|
||||
|
||||
export class SpawnError extends Data.TaggedError("SpawnError")<{
|
||||
readonly message: string;
|
||||
}> {}
|
||||
|
||||
export class BackendUnavailableError extends Data.TaggedError(
|
||||
"BackendUnavailableError",
|
||||
)<{
|
||||
readonly message: string;
|
||||
}> {}
|
||||
|
||||
export class ConcurrencyLimitError extends Data.TaggedError(
|
||||
"ConcurrencyLimitError",
|
||||
)<{
|
||||
readonly message: string;
|
||||
}> {}
|
||||
|
||||
export class SendError extends Data.TaggedError("SendError")<{
|
||||
readonly message: string;
|
||||
}> {}
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Formatting helpers (self-contained copies of the v1 shared helpers:
|
||||
* context-utilization + activity-status).
|
||||
*/
|
||||
|
||||
import type { Theme } from "@earendil-works/pi-coding-agent";
|
||||
|
||||
export interface ContextUtilization {
|
||||
/** Current conversation context occupancy; undefined while unknown. */
|
||||
tokens?: number | null;
|
||||
/** Capacity of the model currently serving the conversation. */
|
||||
contextWindow?: number | null;
|
||||
}
|
||||
|
||||
function usableTokens(value: number | null | undefined) {
|
||||
return typeof value === "number" && Number.isFinite(value) && value >= 0
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function usableCapacity(value: number | null | undefined) {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function contextPercent(usage: ContextUtilization) {
|
||||
const tokens = usableTokens(usage.tokens);
|
||||
const capacity = usableCapacity(usage.contextWindow);
|
||||
if (tokens === undefined || capacity === undefined) return undefined;
|
||||
return Math.round(Math.min(100, Math.max(0, (tokens / capacity) * 100)));
|
||||
}
|
||||
|
||||
export function formatCompactTokens(count: number) {
|
||||
if (count < 1000) return Math.round(count).toString();
|
||||
if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
|
||||
if (count < 1000000) return `${Math.round(count / 1000)}k`;
|
||||
return `${(count / 1000000).toFixed(1)}M`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render `%/capacity`. If occupancy is unknown, retain the useful capacity
|
||||
* as `?%/capacity`; with no valid capacity, omit the statistic entirely.
|
||||
*/
|
||||
export function formatContextUtilization(usage: ContextUtilization) {
|
||||
const capacity = usableCapacity(usage.contextWindow);
|
||||
if (capacity === undefined) return "";
|
||||
const percent = contextPercent(usage);
|
||||
return `${percent === undefined ? "?" : percent}%/${formatCompactTokens(capacity)}`;
|
||||
}
|
||||
|
||||
interface ActivityCounts {
|
||||
running: number;
|
||||
done: number;
|
||||
failed: number;
|
||||
}
|
||||
|
||||
const SQUARE = "■";
|
||||
|
||||
export function formatActivityStatus(theme: Theme, counts: ActivityCounts) {
|
||||
const parts: string[] = [];
|
||||
if (counts.running > 0) {
|
||||
parts.push(theme.fg("warning", `${SQUARE} ${counts.running} running`));
|
||||
}
|
||||
if (counts.done > 0) {
|
||||
parts.push(theme.fg("success", `${SQUARE} ${counts.done} done`));
|
||||
}
|
||||
if (counts.failed > 0) {
|
||||
parts.push(theme.fg("error", `${SQUARE} ${counts.failed} failed`));
|
||||
}
|
||||
parts.push(theme.fg("accent", "/subagents") + theme.fg("dim", " to view"));
|
||||
|
||||
return `${theme.fg("muted", "subagents:")} ${parts.join(theme.fg("dim", " · "))}`;
|
||||
}
|
||||
@@ -0,0 +1,736 @@
|
||||
/**
|
||||
* SubagentManager — owns the registry of running/finished subagents.
|
||||
*
|
||||
* Each subagent is a scoped `SubagentSession` from a `SubagentBackend` plus a
|
||||
* pump fiber that folds its normalized event stream into a mutable
|
||||
* `SubagentSnapshot`. Closing a subagent's scope kills the underlying
|
||||
* session/process and stops the pump.
|
||||
*
|
||||
* The manager also exposes a synchronous `SubagentReadModel` so the
|
||||
* imperative TUI components (which render synchronously) can read snapshots
|
||||
* and issue fire-and-forget commands without touching the Effect runtime.
|
||||
*/
|
||||
|
||||
import {
|
||||
Context,
|
||||
Effect,
|
||||
Exit,
|
||||
Fiber,
|
||||
Layer,
|
||||
Result,
|
||||
Scope,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import type { SubagentBackend, SubagentSession } from "./backend.ts";
|
||||
import { BackendRegistry } from "./backend.ts";
|
||||
import type {
|
||||
BackendName,
|
||||
LiveToolState,
|
||||
RunOutcome,
|
||||
SpawnTask,
|
||||
SubagentEvent,
|
||||
SubagentOrigin,
|
||||
SubagentMeta,
|
||||
SubagentSnapshot,
|
||||
SubagentStatus,
|
||||
TranscriptItem,
|
||||
} from "./domain.ts";
|
||||
import {
|
||||
BackendUnavailableError,
|
||||
ConcurrencyLimitError,
|
||||
SendError,
|
||||
SpawnError,
|
||||
} from "./domain.ts";
|
||||
|
||||
export const MAX_RUNNING = 4;
|
||||
export const MAX_TRACKED = 64;
|
||||
const STOP_TIMEOUT_MS = 5_000;
|
||||
const ERROR_TEXT_MAX_LENGTH = 4_096;
|
||||
const TRANSCRIPT_TEXT_MAX_LENGTH = 64 * 1_024;
|
||||
const LIVE_ASSISTANT_MAX_LENGTH = 128 * 1_024;
|
||||
const FINAL_TEXT_MAX_LENGTH = 1_024 * 1_024;
|
||||
const MAX_TRANSCRIPT_ITEMS = 512;
|
||||
|
||||
function bounded(text: string) {
|
||||
return text.slice(0, ERROR_TEXT_MAX_LENGTH);
|
||||
}
|
||||
|
||||
function boundedTranscriptText(text: string) {
|
||||
return text.slice(0, TRANSCRIPT_TEXT_MAX_LENGTH);
|
||||
}
|
||||
|
||||
function appendTranscript(snapshot: MutableSnapshot, item: TranscriptItem) {
|
||||
snapshot.transcript.push(item);
|
||||
if (snapshot.transcript.length > MAX_TRANSCRIPT_ITEMS) {
|
||||
snapshot.transcript.splice(
|
||||
0,
|
||||
snapshot.transcript.length - MAX_TRANSCRIPT_ITEMS,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Internal state -----------------------------------------------------------
|
||||
|
||||
/** Mutable snapshot; exposed to readers via the readonly SubagentSnapshot type. */
|
||||
interface MutableSnapshot {
|
||||
id: string;
|
||||
origin: SubagentOrigin;
|
||||
backend: BackendName;
|
||||
title: string;
|
||||
prompt: string;
|
||||
cwd: string;
|
||||
status: SubagentStatus;
|
||||
createdAt: number;
|
||||
settledAt?: number;
|
||||
errorText?: string;
|
||||
meta: SubagentMeta;
|
||||
usage: { tokens?: number; contextWindow?: number };
|
||||
transcript: TranscriptItem[];
|
||||
liveAssistant?: { text: string; thinking: string };
|
||||
liveTools: LiveToolState[];
|
||||
queued: SubagentSnapshot["queued"];
|
||||
finalText: string;
|
||||
turns: number;
|
||||
}
|
||||
|
||||
interface Entry {
|
||||
snapshot: MutableSnapshot;
|
||||
session: SubagentSession;
|
||||
scope: Scope.Closeable;
|
||||
pump?: Fiber.Fiber<void>;
|
||||
liveToolMap: Map<string, LiveToolState>;
|
||||
/** Idle restart dispatched but RunStarted not folded yet; counts as running
|
||||
* so concurrent restarts cannot race past the cap. */
|
||||
restarting?: boolean;
|
||||
}
|
||||
|
||||
// --- Read model ----------------------------------------------------------------
|
||||
|
||||
/** Synchronous bridge for the TUI. Snapshots are live objects; do not mutate. */
|
||||
export interface SubagentReadModel {
|
||||
list(): ReadonlyArray<SubagentSnapshot>;
|
||||
get(id: string): SubagentSnapshot | undefined;
|
||||
size(): number;
|
||||
/** Any-change notification (footer status, dashboard). */
|
||||
subscribe(listener: () => void): () => void;
|
||||
/** Per-subagent notification (takeover view). */
|
||||
subscribeTo(id: string, listener: () => void): () => void;
|
||||
/** Fire-and-forget: steer/continue a subagent (takeover input). */
|
||||
requestSend(id: string, text: string): void;
|
||||
/** Fire-and-forget: abort a running subagent (dashboard `x`, takeover). */
|
||||
requestAbort(id: string): void;
|
||||
/**
|
||||
* Register the settle hook. `consumed` is true when an active
|
||||
* subagent_wait/cancel is collecting the result (so it must not also be
|
||||
* delivered as a follow-up message).
|
||||
*/
|
||||
setOnSettled(
|
||||
hook: ((snap: SubagentSnapshot, consumed: boolean) => void) | undefined,
|
||||
): void;
|
||||
}
|
||||
|
||||
// --- Service --------------------------------------------------------------------
|
||||
|
||||
export interface CancelResult {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly status: SubagentStatus;
|
||||
readonly cancelled: boolean;
|
||||
}
|
||||
|
||||
export interface SubagentManagerShape {
|
||||
spawn(
|
||||
backend: BackendName,
|
||||
task: SpawnTask,
|
||||
): Effect.Effect<
|
||||
SubagentSnapshot,
|
||||
SpawnError | ConcurrencyLimitError | BackendUnavailableError
|
||||
>;
|
||||
/**
|
||||
* Wait until all listed subagents are settled. Unknown ids are treated as
|
||||
* settled (the tool layer validates ids first). While waiting, settles for
|
||||
* these ids are marked "consumed". Interruption (tool abort) releases the
|
||||
* interest and leaves the subagents running.
|
||||
*/
|
||||
waitFor(
|
||||
ids: ReadonlyArray<string>,
|
||||
onPending?: (pending: string[]) => void,
|
||||
): Effect.Effect<void>;
|
||||
/** Cancel running subagents; resolves when they have settled. */
|
||||
cancel(
|
||||
ids: ReadonlyArray<string>,
|
||||
): Effect.Effect<ReadonlyArray<CancelResult>>;
|
||||
send(id: string, text: string): Effect.Effect<void, SendError>;
|
||||
get(id: string): Effect.Effect<SubagentSnapshot | undefined>;
|
||||
readonly list: Effect.Effect<ReadonlyArray<SubagentSnapshot>>;
|
||||
readonly disposeAll: Effect.Effect<void>;
|
||||
readonly view: SubagentReadModel;
|
||||
}
|
||||
|
||||
export class SubagentManager extends Context.Service<
|
||||
SubagentManager,
|
||||
SubagentManagerShape
|
||||
>()("subagents/SubagentManager") {}
|
||||
|
||||
// --- Implementation --------------------------------------------------------------
|
||||
|
||||
const makeManager = Effect.gen(function* () {
|
||||
const registry = yield* BackendRegistry;
|
||||
// Detached forker for sync contexts (read-model commands, pruning) that
|
||||
// preserves the manager's services instead of using the global runtime.
|
||||
const runDetached = Effect.runForkWith(yield* Effect.context());
|
||||
|
||||
const entries = new Map<string, Entry>();
|
||||
const waitInterest = new Map<string, number>();
|
||||
const listeners = new Set<() => void>();
|
||||
/** One-shot nextChange waiters, swapped out before invocation so waiters
|
||||
* re-registering during notification are not visited in the same sweep. */
|
||||
let changeWaiters: Array<() => void> = [];
|
||||
const idListeners = new Map<string, Set<() => void>>();
|
||||
const cleanups = new Set<Fiber.Fiber<unknown>>();
|
||||
let modelCounter = 0;
|
||||
let btwCounter = 0;
|
||||
let reserved = 0;
|
||||
let disposed = false;
|
||||
let onSettled:
|
||||
((snap: SubagentSnapshot, consumed: boolean) => void) | undefined;
|
||||
|
||||
const notify = (id?: string) => {
|
||||
const waiters = changeWaiters;
|
||||
changeWaiters = [];
|
||||
for (const waiter of waiters) waiter();
|
||||
for (const listener of [...listeners]) {
|
||||
try {
|
||||
listener();
|
||||
} catch {
|
||||
// A failed status/render listener must not corrupt lifecycle state.
|
||||
}
|
||||
}
|
||||
if (id) {
|
||||
for (const listener of idListeners.get(id) ?? []) {
|
||||
try {
|
||||
listener();
|
||||
} catch {
|
||||
// Same.
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** Resolves on the next state change. Interruption unregisters the waiter. */
|
||||
const nextChange = Effect.callback<void>((resume) => {
|
||||
const waiter = () => resume(Effect.void);
|
||||
changeWaiters.push(waiter);
|
||||
return Effect.sync(() => {
|
||||
const index = changeWaiters.indexOf(waiter);
|
||||
if (index >= 0) changeWaiters.splice(index, 1);
|
||||
});
|
||||
});
|
||||
|
||||
const runningCount = () =>
|
||||
[...entries.values()].filter(
|
||||
(e) => e.snapshot.status === "running" || e.restarting === true,
|
||||
).length;
|
||||
|
||||
const addInterest = (ids: ReadonlyArray<string>) => {
|
||||
for (const id of ids) waitInterest.set(id, (waitInterest.get(id) ?? 0) + 1);
|
||||
};
|
||||
const releaseInterest = (ids: ReadonlyArray<string>) => {
|
||||
for (const id of ids) {
|
||||
const count = (waitInterest.get(id) ?? 1) - 1;
|
||||
if (count <= 0) waitInterest.delete(id);
|
||||
else waitInterest.set(id, count);
|
||||
}
|
||||
};
|
||||
|
||||
const closeEntryScope = (entry: Entry) =>
|
||||
Scope.close(entry.scope, Exit.void).pipe(Effect.ignore);
|
||||
|
||||
const pruneSettled = () => {
|
||||
if (entries.size <= MAX_TRACKED) return;
|
||||
const candidates = [...entries.values()]
|
||||
.filter(
|
||||
(e) =>
|
||||
e.snapshot.status !== "running" && !waitInterest.has(e.snapshot.id),
|
||||
)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
(a.snapshot.settledAt ?? a.snapshot.createdAt) -
|
||||
(b.snapshot.settledAt ?? b.snapshot.createdAt),
|
||||
);
|
||||
for (const entry of candidates) {
|
||||
if (entries.size <= MAX_TRACKED) break;
|
||||
entries.delete(entry.snapshot.id);
|
||||
const fiber = runDetached(closeEntryScope(entry));
|
||||
cleanups.add(fiber);
|
||||
fiber.addObserver(() => cleanups.delete(fiber));
|
||||
}
|
||||
};
|
||||
|
||||
const settle = (entry: Entry, outcome: RunOutcome) => {
|
||||
const s = entry.snapshot;
|
||||
entry.restarting = false;
|
||||
if (s.status !== "running") return;
|
||||
s.settledAt = Date.now();
|
||||
switch (outcome._tag) {
|
||||
case "Completed":
|
||||
s.status = "done";
|
||||
s.errorText = undefined;
|
||||
s.finalText = outcome.finalText.slice(0, FINAL_TEXT_MAX_LENGTH);
|
||||
break;
|
||||
case "Failed":
|
||||
s.status = "error";
|
||||
s.errorText = bounded(outcome.errorText);
|
||||
// Never let a failed run report the previous run's successful output.
|
||||
s.finalText = (outcome.partialText ?? "").slice(
|
||||
0,
|
||||
FINAL_TEXT_MAX_LENGTH,
|
||||
);
|
||||
break;
|
||||
case "Interrupted":
|
||||
s.status = "error";
|
||||
s.errorText = "Run was aborted";
|
||||
s.finalText = (outcome.partialText ?? "").slice(
|
||||
0,
|
||||
FINAL_TEXT_MAX_LENGTH,
|
||||
);
|
||||
break;
|
||||
}
|
||||
s.liveAssistant = undefined;
|
||||
entry.liveToolMap.clear();
|
||||
s.liveTools = [];
|
||||
s.queued = [];
|
||||
const consumed = (waitInterest.get(s.id) ?? 0) > 0;
|
||||
notify(s.id);
|
||||
try {
|
||||
// During teardown, don't queue results into a shutting-down session.
|
||||
if (!disposed) onSettled?.(s, consumed);
|
||||
} catch {
|
||||
// The parent session may be unavailable; settlement stays final.
|
||||
}
|
||||
pruneSettled();
|
||||
};
|
||||
|
||||
const foldEvent = (entry: Entry, event: SubagentEvent) => {
|
||||
const s = entry.snapshot;
|
||||
switch (event._tag) {
|
||||
case "RunStarted":
|
||||
entry.restarting = false;
|
||||
s.status = "running";
|
||||
s.settledAt = undefined;
|
||||
s.errorText = undefined;
|
||||
break;
|
||||
case "RunSettled":
|
||||
settle(entry, event.outcome);
|
||||
return; // settle() already notified
|
||||
case "UserMessage":
|
||||
appendTranscript(s, {
|
||||
kind: "user",
|
||||
text: boundedTranscriptText(event.text),
|
||||
});
|
||||
break;
|
||||
case "AssistantDelta": {
|
||||
const live = s.liveAssistant ?? { text: "", thinking: "" };
|
||||
s.liveAssistant =
|
||||
event.kind === "text"
|
||||
? {
|
||||
...live,
|
||||
text: (live.text + event.delta).slice(
|
||||
-LIVE_ASSISTANT_MAX_LENGTH,
|
||||
),
|
||||
}
|
||||
: {
|
||||
...live,
|
||||
thinking: (live.thinking + event.delta).slice(
|
||||
-LIVE_ASSISTANT_MAX_LENGTH,
|
||||
),
|
||||
};
|
||||
break;
|
||||
}
|
||||
case "AssistantMessage":
|
||||
appendTranscript(s, {
|
||||
kind: "assistant",
|
||||
parts: event.parts.map((part) =>
|
||||
part.type === "toolCall"
|
||||
? {
|
||||
...part,
|
||||
argsPreview: part.argsPreview
|
||||
? boundedTranscriptText(part.argsPreview)
|
||||
: undefined,
|
||||
}
|
||||
: { ...part, text: boundedTranscriptText(part.text) },
|
||||
),
|
||||
});
|
||||
s.liveAssistant = undefined;
|
||||
s.turns++;
|
||||
break;
|
||||
case "ToolStart":
|
||||
entry.liveToolMap.set(event.toolId, {
|
||||
toolId: event.toolId,
|
||||
name: event.name,
|
||||
argsPreview: event.argsPreview
|
||||
? boundedTranscriptText(event.argsPreview)
|
||||
: undefined,
|
||||
});
|
||||
s.liveTools = [...entry.liveToolMap.values()];
|
||||
break;
|
||||
case "ToolUpdate": {
|
||||
const current = entry.liveToolMap.get(event.toolId);
|
||||
if (current) {
|
||||
entry.liveToolMap.set(event.toolId, {
|
||||
...current,
|
||||
outputPreview: event.outputPreview
|
||||
? boundedTranscriptText(event.outputPreview)
|
||||
: current.outputPreview,
|
||||
});
|
||||
s.liveTools = [...entry.liveToolMap.values()];
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "ToolEnd":
|
||||
entry.liveToolMap.delete(event.toolId);
|
||||
s.liveTools = [...entry.liveToolMap.values()];
|
||||
appendTranscript(s, {
|
||||
kind: "toolResult",
|
||||
toolId: event.toolId,
|
||||
name: event.name,
|
||||
isError: event.isError,
|
||||
outputPreview: event.outputPreview
|
||||
? boundedTranscriptText(event.outputPreview)
|
||||
: undefined,
|
||||
});
|
||||
break;
|
||||
case "QueueChanged":
|
||||
s.queued = event.queued;
|
||||
break;
|
||||
case "UsageChanged":
|
||||
s.usage = {
|
||||
tokens: event.tokens ?? s.usage.tokens,
|
||||
contextWindow: event.contextWindow ?? s.usage.contextWindow,
|
||||
};
|
||||
break;
|
||||
case "MetaChanged":
|
||||
s.meta = { ...s.meta, ...event.meta };
|
||||
break;
|
||||
case "BackendError":
|
||||
s.errorText = bounded(event.message);
|
||||
break;
|
||||
}
|
||||
notify(s.id);
|
||||
};
|
||||
|
||||
const spawn = (backendName: BackendName, task: SpawnTask) =>
|
||||
Effect.gen(function* () {
|
||||
// Reserve synchronously (before the first yield inside doSpawn) so
|
||||
// parallel tool calls cannot race past the global cap.
|
||||
yield* Effect.suspend(
|
||||
(): Effect.Effect<void, SpawnError | ConcurrencyLimitError> => {
|
||||
if (disposed) {
|
||||
return new SpawnError({
|
||||
message: "Subagent manager is shutting down.",
|
||||
});
|
||||
}
|
||||
if (runningCount() + reserved >= MAX_RUNNING) {
|
||||
return new ConcurrencyLimitError({
|
||||
message: `Max ${MAX_RUNNING} subagents can run concurrently. Wait for one to finish before spawning another.`,
|
||||
});
|
||||
}
|
||||
reserved++;
|
||||
return Effect.void;
|
||||
},
|
||||
);
|
||||
|
||||
const doSpawn = Effect.gen(function* () {
|
||||
const backend: SubagentBackend | undefined = registry.get(backendName);
|
||||
if (!backend) {
|
||||
return yield* new BackendUnavailableError({
|
||||
message: `Unknown backend "${backendName}".`,
|
||||
});
|
||||
}
|
||||
const available = yield* backend.available;
|
||||
if (!available) {
|
||||
return yield* new BackendUnavailableError({
|
||||
message: `Backend "${backendName}" is not available on this machine (binary/SDK/credentials missing).`,
|
||||
});
|
||||
}
|
||||
|
||||
const scope = yield* Scope.make();
|
||||
const session = yield* Scope.provide(backend.spawn(task), scope).pipe(
|
||||
Effect.onError(() => Scope.close(scope, Exit.void)),
|
||||
);
|
||||
if (disposed) {
|
||||
yield* Scope.close(scope, Exit.void);
|
||||
return yield* new SpawnError({
|
||||
message: "Subagent manager shut down while spawning.",
|
||||
});
|
||||
}
|
||||
|
||||
const origin = task.origin ?? "model";
|
||||
const id =
|
||||
origin === "btw" ? `btw-${++btwCounter}` : `sa-${++modelCounter}`;
|
||||
const meta = yield* session.meta;
|
||||
const entry: Entry = {
|
||||
snapshot: {
|
||||
id,
|
||||
origin,
|
||||
backend: backendName,
|
||||
title: task.title,
|
||||
prompt: task.prompt,
|
||||
cwd: task.cwd,
|
||||
status: "running",
|
||||
createdAt: Date.now(),
|
||||
meta,
|
||||
usage: { contextWindow: meta.contextWindow },
|
||||
transcript: [],
|
||||
liveTools: [],
|
||||
queued: [],
|
||||
finalText: "",
|
||||
turns: 0,
|
||||
},
|
||||
session,
|
||||
scope,
|
||||
liveToolMap: new Map(),
|
||||
};
|
||||
entries.set(id, entry);
|
||||
|
||||
// Pump: fold the event stream into the snapshot. Tied to the entry
|
||||
// scope, so closing the scope stops it. If the stream ends while the
|
||||
// subagent still looks running, the backend died out from under us.
|
||||
const pump = Stream.runForEach(session.events, (event) =>
|
||||
Effect.sync(() => foldEvent(entry, event)),
|
||||
).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
if (entry.snapshot.status === "running") {
|
||||
settle(entry, {
|
||||
_tag: "Failed",
|
||||
errorText: "Backend event stream ended unexpectedly",
|
||||
});
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
entry.pump = yield* Scope.provide(Effect.forkScoped(pump), scope);
|
||||
|
||||
notify(id);
|
||||
return entry.snapshot as SubagentSnapshot;
|
||||
});
|
||||
|
||||
return yield* doSpawn.pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
reserved--;
|
||||
notify();
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const waitFor = (
|
||||
ids: ReadonlyArray<string>,
|
||||
onPending?: (pending: string[]) => void,
|
||||
) =>
|
||||
Effect.suspend(() => {
|
||||
const unique = [...new Set(ids)];
|
||||
addInterest(unique);
|
||||
const loop = Effect.gen(function* () {
|
||||
while (true) {
|
||||
const pending = unique.filter(
|
||||
(id) => entries.get(id)?.snapshot.status === "running",
|
||||
);
|
||||
if (pending.length === 0) return;
|
||||
onPending?.(pending);
|
||||
yield* nextChange;
|
||||
}
|
||||
});
|
||||
return loop.pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
releaseInterest(unique);
|
||||
pruneSettled();
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
/** Interrupt one running entry, force-closing its scope after 5s. */
|
||||
const abortEntry = (entry: Entry) =>
|
||||
Effect.gen(function* () {
|
||||
if (entry.snapshot.status !== "running") return;
|
||||
const graceful = yield* entry.session.interrupt.pipe(
|
||||
Effect.timeout(STOP_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
if (Result.isFailure(graceful)) {
|
||||
// Settle before closing the scope so the pump's stream-ended
|
||||
// fallback ("Backend event stream ended unexpectedly") cannot win
|
||||
// the race and report the wrong terminal reason.
|
||||
yield* Effect.sync(() => {
|
||||
settle(entry, { _tag: "Interrupted" });
|
||||
entry.snapshot.errorText =
|
||||
"Abort deadline exceeded; session was force-disposed";
|
||||
notify(entry.snapshot.id);
|
||||
});
|
||||
// Bound the close like disposeAll does: a stuck backend finalizer
|
||||
// must not hang cancel after the run is already settled.
|
||||
yield* closeEntryScope(entry).pipe(
|
||||
Effect.timeout(STOP_TIMEOUT_MS),
|
||||
Effect.ignore,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const cancel = (ids: ReadonlyArray<string>) =>
|
||||
Effect.suspend(() => {
|
||||
const unique = [...new Set(ids)];
|
||||
const running = unique
|
||||
.map((id) => entries.get(id))
|
||||
.filter(
|
||||
(entry): entry is Entry => entry?.snapshot.status === "running",
|
||||
);
|
||||
const runningIds = running.map((entry) => entry.snapshot.id);
|
||||
// Mark consumed before interrupting so cancellation does not also
|
||||
// enqueue duplicate automatic result messages into the parent.
|
||||
addInterest(runningIds);
|
||||
const work = Effect.gen(function* () {
|
||||
yield* Effect.forEach(running, abortEntry, {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
while (running.some((entry) => entry.snapshot.status === "running")) {
|
||||
yield* nextChange;
|
||||
}
|
||||
});
|
||||
return work.pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
releaseInterest(runningIds);
|
||||
pruneSettled();
|
||||
}),
|
||||
),
|
||||
Effect.map((): ReadonlyArray<CancelResult> =>
|
||||
unique.map((id) => {
|
||||
const snapshot = entries.get(id)?.snapshot;
|
||||
return {
|
||||
id,
|
||||
title: snapshot?.title ?? "?",
|
||||
status: snapshot?.status ?? "error",
|
||||
cancelled: runningIds.includes(id),
|
||||
};
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const send = (id: string, text: string) =>
|
||||
Effect.suspend((): Effect.Effect<void, SendError> => {
|
||||
const entry = entries.get(id);
|
||||
if (!entry || disposed) {
|
||||
return new SendError({
|
||||
message: `Subagent "${id}" is no longer tracked.`,
|
||||
});
|
||||
}
|
||||
// Restarting a settled subagent occupies a running slot again, so it
|
||||
// must respect the same cap as spawn. Steering an already-running one
|
||||
// does not consume additional capacity.
|
||||
if (entry.snapshot.status !== "running") {
|
||||
if (runningCount() + reserved >= MAX_RUNNING) {
|
||||
return new SendError({
|
||||
message: `Max ${MAX_RUNNING} subagents can run concurrently; restarting "${id}" would exceed that.`,
|
||||
});
|
||||
}
|
||||
// Occupy the slot synchronously: the RunStarted that flips status
|
||||
// arrives via the async pump, and two concurrent restarts must not
|
||||
// both pass the check in that window. Cleared by RunStarted/settle,
|
||||
// or here when the backend rejects the send.
|
||||
entry.restarting = true;
|
||||
return entry.session.send(text).pipe(
|
||||
Effect.onError(() =>
|
||||
Effect.sync(() => {
|
||||
entry.restarting = false;
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
return entry.session.send(text);
|
||||
});
|
||||
|
||||
const disposeAll = Effect.gen(function* () {
|
||||
disposed = true;
|
||||
const all = [...entries.values()];
|
||||
entries.clear();
|
||||
yield* Effect.forEach(
|
||||
all,
|
||||
(entry) =>
|
||||
closeEntryScope(entry).pipe(
|
||||
Effect.timeout(STOP_TIMEOUT_MS),
|
||||
Effect.ignore,
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
// Pruning cleanups are detached; bound them like everything else so a
|
||||
// stuck backend finalizer cannot block runtime shutdown indefinitely.
|
||||
yield* Effect.forEach(
|
||||
[...cleanups],
|
||||
(fiber) =>
|
||||
Fiber.await(fiber).pipe(Effect.timeout(STOP_TIMEOUT_MS), Effect.ignore),
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(Effect.ignore);
|
||||
yield* Effect.sync(() => notify());
|
||||
});
|
||||
|
||||
const view: SubagentReadModel = {
|
||||
list: () => [...entries.values()].map((entry) => entry.snapshot),
|
||||
get: (id) => entries.get(id)?.snapshot,
|
||||
size: () => entries.size,
|
||||
subscribe: (listener) => {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
subscribeTo: (id, listener) => {
|
||||
let set = idListeners.get(id);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
idListeners.set(id, set);
|
||||
}
|
||||
set.add(listener);
|
||||
return () => {
|
||||
set.delete(listener);
|
||||
if (set.size === 0) idListeners.delete(id);
|
||||
};
|
||||
},
|
||||
requestSend: (id, text) => {
|
||||
runDetached(send(id, text).pipe(Effect.ignore));
|
||||
},
|
||||
requestAbort: (id) => {
|
||||
const entry = entries.get(id);
|
||||
if (!entry) return;
|
||||
// UI-initiated aborts are not "consumed": the failed result still
|
||||
// flows back to the parent as a follow-up message, matching v1.
|
||||
runDetached(abortEntry(entry).pipe(Effect.ignore));
|
||||
},
|
||||
setOnSettled: (hook) => {
|
||||
onSettled = hook;
|
||||
},
|
||||
};
|
||||
|
||||
// Safety net: disposing the ManagedRuntime tears everything down even if
|
||||
// the extension forgot to call disposeAll explicitly.
|
||||
yield* Effect.addFinalizer(() => disposeAll);
|
||||
|
||||
return SubagentManager.of({
|
||||
spawn,
|
||||
waitFor,
|
||||
cancel,
|
||||
send,
|
||||
get: (id) => Effect.sync(() => entries.get(id)?.snapshot),
|
||||
list: Effect.sync(() => [...entries.values()].map((e) => e.snapshot)),
|
||||
disposeAll,
|
||||
view,
|
||||
});
|
||||
});
|
||||
|
||||
export const SubagentManagerLive: Layer.Layer<
|
||||
SubagentManager,
|
||||
never,
|
||||
BackendRegistry
|
||||
> = Layer.effect(SubagentManager, makeManager);
|
||||
@@ -0,0 +1,92 @@
|
||||
/** All model-facing strings for the subagents tools. */
|
||||
|
||||
/** Describes subagent_spawn, including harnesses and the fixed concurrency cap. */
|
||||
export const SUBAGENT_SPAWN_TOOL_DESCRIPTION =
|
||||
"Spawn a background subagent: a fully autonomous, headless agent with its own context window and the selected harness's normal host permissions. You choose the harness it runs on: pi (in-process pi session, inherits this environment's tools and config), claude (Claude Code), or codex (Codex CLI). Fire-and-forget: this returns immediately with an id. The subagent's final output is queued back to you as a message when it settles, or collect it explicitly with subagent_wait. Children cannot orchestrate more agents/workflows or ask the user, and cannot see this conversation, so the prompt must be self-contained. Only use trusted working directories. Max 4 subagents can be running at once across all harnesses.";
|
||||
|
||||
/** Adds background subagent delegation to the parent model's available-tools prompt. */
|
||||
export const SUBAGENT_SPAWN_PROMPT_SNIPPET =
|
||||
"Spawn a background subagent on a chosen harness (pi, Claude Code, or Codex; own context, normal tools) for a self-contained task";
|
||||
|
||||
/** Guides the parent model to delegate standalone tasks and avoid unnecessary blocking waits. */
|
||||
export const SUBAGENT_SPAWN_PROMPT_GUIDELINES = [
|
||||
"Use subagent_spawn to delegate self-contained tasks that can run in the background; give it a complete, standalone prompt.",
|
||||
"Pick the subagent harness deliberately: pi unless you have a reason to prefer Claude Code or Codex (e.g. the user asked for one, or the task suits that harness).",
|
||||
"After subagent_spawn, keep working; results arrive automatically. Only call subagent_wait when you cannot proceed without the result.",
|
||||
];
|
||||
|
||||
/** Model-facing schema descriptions for subagent_spawn task and execution options. */
|
||||
export const SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS = {
|
||||
prompt:
|
||||
"Task prompt for the subagent. Must be self-contained: include all needed context, file paths, and what to report back.",
|
||||
name: "Short human-readable name for this subagent, shown in listings and the UI",
|
||||
harness:
|
||||
'Harness to run the subagent on: "pi" (in-process pi session; inherits this environment), "claude" (Claude Code), or "codex" (Codex CLI). Choose deliberately per task.',
|
||||
workingDir:
|
||||
"Trusted working directory for the autonomous child (default: current working directory)",
|
||||
model:
|
||||
'Model hint, interpreted by the chosen harness (pi: "provider/model-id" or model id; claude: model alias like "sonnet"/"opus"; codex: model slug). Omit for the harness default (pi inherits the current model).',
|
||||
reasoningEffort:
|
||||
"Reasoning effort on a shared scale; the harness maps it to its nearest native equivalent (pi thinking level, codex reasoning effort, claude thinking budget). Omit for the harness default (pi inherits the current level).",
|
||||
};
|
||||
|
||||
/** Builds the subagent_spawn result that tells the parent model how to continue or inspect the child. */
|
||||
export function buildSubagentSpawnResult(options: {
|
||||
id: string;
|
||||
title: string;
|
||||
harness: string;
|
||||
modelLabel: string;
|
||||
cwd: string;
|
||||
}) {
|
||||
return (
|
||||
`Spawned subagent ${options.id} "${options.title}" (${options.harness}: ${options.modelLabel}, ${options.cwd}).\n` +
|
||||
`It runs in the background. Its result will be delivered to you when it finishes, ` +
|
||||
`or use subagent_wait(ids: ["${options.id}"]) to block for it, subagent_cancel to stop it, subagent_check to peek, subagent_list to see all.`
|
||||
);
|
||||
}
|
||||
|
||||
/** Describes explicit blocking collection of one or more subagent results. */
|
||||
export const SUBAGENT_WAIT_TOOL_DESCRIPTION =
|
||||
"Block until all listed subagents have settled, then return their final outputs. Prefer letting results arrive automatically; use this only when you need a result before continuing.";
|
||||
|
||||
/** Model-facing schema description for the subagent ids to await. */
|
||||
export const SUBAGENT_WAIT_PARAMETER_DESCRIPTIONS = {
|
||||
ids: 'Subagent ids to wait for, e.g. ["sa-1", "sa-2"]',
|
||||
};
|
||||
|
||||
/** Describes aborting running subagents while retaining their partial transcripts. */
|
||||
export const SUBAGENT_CANCEL_TOOL_DESCRIPTION =
|
||||
"Cancel one or more running subagents. This aborts their active work but preserves their partial session transcripts on disk.";
|
||||
|
||||
/** Model-facing schema description for the subagent ids to cancel. */
|
||||
export const SUBAGENT_CANCEL_PARAMETER_DESCRIPTIONS = {
|
||||
ids: 'Subagent ids to cancel, e.g. ["sa-1", "sa-2"]',
|
||||
};
|
||||
|
||||
/** Describes nonblocking inspection of a subagent without consuming its result. */
|
||||
export const SUBAGENT_CHECK_TOOL_DESCRIPTION =
|
||||
"Peek at a subagent's status and recent activity without blocking. Does not consume its result.";
|
||||
|
||||
/** Model-facing schema description for the subagent id to inspect. */
|
||||
export const SUBAGENT_CHECK_PARAMETER_DESCRIPTIONS = {
|
||||
id: "Subagent id",
|
||||
};
|
||||
|
||||
/** Describes listing all tracked running and settled subagents. */
|
||||
export const SUBAGENT_LIST_TOOL_DESCRIPTION =
|
||||
"List all subagents (running and finished) with their harness and status.";
|
||||
|
||||
/** Builds the child completion/failure wrapper injected into the parent model's context. */
|
||||
export function buildSubagentResultMessage(options: {
|
||||
id: string;
|
||||
title: string;
|
||||
status: "running" | "done" | "error";
|
||||
errorText?: string;
|
||||
output: string;
|
||||
}) {
|
||||
const verb = options.status === "error" ? "failed" : "finished";
|
||||
let text = `Subagent ${options.id} "${options.title}" ${verb}.`;
|
||||
if (options.errorText) text += `\nError: ${options.errorText}`;
|
||||
text += `\n\n${options.output}`;
|
||||
return text;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
export function createDeferredResultDelivery<T extends { id: string }>() {
|
||||
const pending = new Map<string, T>();
|
||||
|
||||
return {
|
||||
defer(result: T) {
|
||||
pending.set(result.id, result);
|
||||
},
|
||||
consume(ids: Iterable<string>) {
|
||||
for (const id of ids) pending.delete(id);
|
||||
},
|
||||
drain() {
|
||||
const results = [...pending.values()];
|
||||
pending.clear();
|
||||
return results;
|
||||
},
|
||||
clear() {
|
||||
pending.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Layer composition and the async entry-point boundary.
|
||||
*
|
||||
* Everything inside the extension is Effect generators; this module is where
|
||||
* tool handlers (plain async functions) run those effects against one shared
|
||||
* ManagedRuntime.
|
||||
*/
|
||||
|
||||
import { Cause, Exit, Layer, ManagedRuntime, type Effect } from "effect";
|
||||
import { BackendRegistry, type SubagentBackend } from "./backend.ts";
|
||||
import { claudeBackend } from "./backends/claude.ts";
|
||||
import { codexBackend } from "./backends/codex.ts";
|
||||
import { piBackend } from "./backends/pi.ts";
|
||||
import type { BackendName } from "./domain.ts";
|
||||
|
||||
const BackendRegistryLive = Layer.sync(BackendRegistry, () => {
|
||||
const backends: SubagentBackend[] = [piBackend, claudeBackend, codexBackend];
|
||||
return new Map<BackendName, SubagentBackend>(
|
||||
backends.map((backend) => [backend.name, backend]),
|
||||
);
|
||||
});
|
||||
|
||||
import { SubagentManagerLive } from "./manager.ts";
|
||||
|
||||
const AppLayer = SubagentManagerLive.pipe(Layer.provide(BackendRegistryLive));
|
||||
|
||||
export function createSubagentRuntime() {
|
||||
return ManagedRuntime.make(AppLayer);
|
||||
}
|
||||
|
||||
export type SubagentRuntime = ReturnType<typeof createSubagentRuntime>;
|
||||
|
||||
/**
|
||||
* Run an effect from an async tool handler. Typed failures and defects are
|
||||
* converted to thrown Errors (what pi's tool contract expects); interruption
|
||||
* (tool AbortSignal) throws `interruptMessage`.
|
||||
*/
|
||||
export async function runTool<A, E>(
|
||||
runtime: SubagentRuntime,
|
||||
effect: Effect.Effect<A, E>,
|
||||
options: { signal?: AbortSignal; interruptMessage?: string } = {},
|
||||
) {
|
||||
const exit = await runtime.runPromiseExit(
|
||||
effect,
|
||||
options.signal ? { signal: options.signal } : undefined,
|
||||
);
|
||||
if (Exit.isSuccess(exit)) return exit.value;
|
||||
if (Cause.hasInterruptsOnly(exit.cause)) {
|
||||
throw new Error(options.interruptMessage ?? "Operation was aborted.");
|
||||
}
|
||||
const [first] = Cause.prettyErrors(exit.cause);
|
||||
throw new Error(first?.message ?? Cause.pretty(exit.cause));
|
||||
}
|
||||
@@ -0,0 +1,583 @@
|
||||
/**
|
||||
* Takeover UI for subagents (ported from v1, rendering from the synchronous
|
||||
* SubagentReadModel instead of live pi sessions):
|
||||
* - SubagentDashboard: full popup (overlay) listing all subagents.
|
||||
* - TakeoverView: full interactive view of one subagent with an input line
|
||||
* to steer/continue it.
|
||||
*/
|
||||
|
||||
import type {
|
||||
ExtensionCommandContext,
|
||||
KeybindingsManager,
|
||||
Theme,
|
||||
} from "@earendil-works/pi-coding-agent";
|
||||
import type { Component, Focusable, TUI } from "@earendil-works/pi-tui";
|
||||
import { Input, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
||||
import { formatElapsed, type SubagentSnapshot } from "../domain.ts";
|
||||
import { formatContextUtilization } from "../format.ts";
|
||||
import type { SubagentReadModel } from "../manager.ts";
|
||||
import { buildTranscriptLines } from "./transcript.ts";
|
||||
|
||||
function configuredKeys(
|
||||
keybindings: KeybindingsManager,
|
||||
binding: Parameters<KeybindingsManager["getKeys"]>[0],
|
||||
) {
|
||||
return keybindings.getKeys(binding).join("/") || "unbound";
|
||||
}
|
||||
|
||||
function statusGlyph(snap: SubagentSnapshot, theme: Theme): string {
|
||||
switch (snap.status) {
|
||||
case "running":
|
||||
return theme.fg("warning", "■");
|
||||
case "done":
|
||||
return theme.fg("success", "■");
|
||||
case "error":
|
||||
return theme.fg("error", "■");
|
||||
}
|
||||
}
|
||||
|
||||
function statusWord(snap: SubagentSnapshot, theme: Theme): string {
|
||||
switch (snap.status) {
|
||||
case "running":
|
||||
return theme.fg("warning", "running");
|
||||
case "done":
|
||||
return theme.fg("success", "done");
|
||||
case "error":
|
||||
return theme.fg("error", "failed");
|
||||
}
|
||||
}
|
||||
|
||||
// --- Entry points --------------------------------------------------------------
|
||||
|
||||
export interface TakeoverOptions {
|
||||
readonly badge?: string;
|
||||
}
|
||||
|
||||
export async function openSubagentTakeover(
|
||||
ctx: ExtensionCommandContext,
|
||||
view: SubagentReadModel,
|
||||
id: string,
|
||||
options?: TakeoverOptions,
|
||||
) {
|
||||
if (!view.get(id)) return;
|
||||
await ctx.ui.custom<null>(
|
||||
(tui, theme, keybindings, done) =>
|
||||
new TakeoverView(tui, theme, keybindings, id, view, done, options),
|
||||
{
|
||||
overlay: true,
|
||||
overlayOptions: { anchor: "center", width: "100%", maxHeight: "100%" },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export async function openSubagentPicker(
|
||||
ctx: ExtensionCommandContext,
|
||||
view: SubagentReadModel,
|
||||
) {
|
||||
const selection: DashboardSelection = { index: 0 };
|
||||
|
||||
while (true) {
|
||||
if (view.size() === 0) {
|
||||
ctx.ui.notify("No subagents", "info");
|
||||
return;
|
||||
}
|
||||
|
||||
const picked = await ctx.ui.custom<string | null>(
|
||||
(tui, theme, keybindings, done) =>
|
||||
new SubagentDashboard(tui, theme, keybindings, view, selection, done),
|
||||
{
|
||||
overlay: true,
|
||||
overlayOptions: { anchor: "center", width: "100%", maxHeight: "100%" },
|
||||
},
|
||||
);
|
||||
|
||||
if (!picked) return;
|
||||
if (!view.get(picked)) continue;
|
||||
|
||||
await openSubagentTakeover(ctx, view, picked);
|
||||
// After leaving the takeover view, fall back to the dashboard.
|
||||
}
|
||||
}
|
||||
|
||||
// --- Dashboard (fullscreen overlay) ----------------------------------------------
|
||||
|
||||
export interface DashboardSelection {
|
||||
id?: string;
|
||||
index: number;
|
||||
}
|
||||
|
||||
export function reconcileDashboardSelection(
|
||||
selection: DashboardSelection,
|
||||
subs: ReadonlyArray<Pick<SubagentSnapshot, "id">>,
|
||||
) {
|
||||
const stableIndex = selection.id
|
||||
? subs.findIndex((snap) => snap.id === selection.id)
|
||||
: -1;
|
||||
selection.index =
|
||||
stableIndex >= 0
|
||||
? stableIndex
|
||||
: Math.min(Math.max(0, selection.index), Math.max(0, subs.length - 1));
|
||||
selection.id = subs[selection.index]?.id;
|
||||
}
|
||||
|
||||
class SubagentDashboard implements Component {
|
||||
private tui: TUI;
|
||||
private theme: Theme;
|
||||
private keybindings: KeybindingsManager;
|
||||
private view: SubagentReadModel;
|
||||
private selection: DashboardSelection;
|
||||
private done: (value: string | null) => void;
|
||||
|
||||
private closed = false;
|
||||
private ticker: ReturnType<typeof setInterval>;
|
||||
private unsubChange: () => void;
|
||||
|
||||
constructor(
|
||||
tui: TUI,
|
||||
theme: Theme,
|
||||
keybindings: KeybindingsManager,
|
||||
view: SubagentReadModel,
|
||||
selection: DashboardSelection,
|
||||
done: (value: string | null) => void,
|
||||
) {
|
||||
this.tui = tui;
|
||||
this.theme = theme;
|
||||
this.keybindings = keybindings;
|
||||
this.view = view;
|
||||
this.selection = selection;
|
||||
this.done = done;
|
||||
// Elapsed times, token counts, and statuses tick along at 1Hz.
|
||||
this.ticker = setInterval(() => this.tui.requestRender(), 1000);
|
||||
this.unsubChange = view.subscribe(() => this.tui.requestRender());
|
||||
}
|
||||
|
||||
private subs(): ReadonlyArray<SubagentSnapshot> {
|
||||
return this.view.list();
|
||||
}
|
||||
|
||||
private cleanup() {
|
||||
if (this.closed) return false;
|
||||
this.closed = true;
|
||||
clearInterval(this.ticker);
|
||||
this.unsubChange();
|
||||
return true;
|
||||
}
|
||||
|
||||
private close(result: string | null) {
|
||||
if (this.cleanup()) this.done(result);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
handleInput(data: string): void {
|
||||
const subs = this.subs();
|
||||
reconcileDashboardSelection(this.selection, subs);
|
||||
|
||||
if (this.keybindings.matches(data, "tui.select.cancel")) {
|
||||
this.close(null);
|
||||
return;
|
||||
}
|
||||
if (this.keybindings.matches(data, "tui.select.confirm")) {
|
||||
const snap = subs[this.selection.index];
|
||||
if (snap) this.close(snap.id);
|
||||
return;
|
||||
}
|
||||
if (this.keybindings.matches(data, "tui.select.up") || data === "k") {
|
||||
if (subs.length > 0) {
|
||||
this.selection.index =
|
||||
(this.selection.index - 1 + subs.length) % subs.length;
|
||||
this.selection.id = subs[this.selection.index]?.id;
|
||||
this.tui.requestRender();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.keybindings.matches(data, "tui.select.down") || data === "j") {
|
||||
if (subs.length > 0) {
|
||||
this.selection.index = (this.selection.index + 1) % subs.length;
|
||||
this.selection.id = subs[this.selection.index]?.id;
|
||||
this.tui.requestRender();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (data === "x") {
|
||||
const snap = subs[this.selection.index];
|
||||
if (snap && snap.status === "running") this.view.requestAbort(snap.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private pad(text: string, width: number): string {
|
||||
const truncated = truncateToWidth(text, width);
|
||||
return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));
|
||||
}
|
||||
|
||||
private borderSegment(width: number, title: string): string {
|
||||
const theme = this.theme;
|
||||
const label = title
|
||||
? ` ${truncateToWidth(title, Math.max(0, width - 3))} `
|
||||
: "";
|
||||
const labelWidth = visibleWidth(label);
|
||||
return (
|
||||
theme.fg("border", "─") +
|
||||
(label ? theme.fg("text", label) : "") +
|
||||
theme.fg("border", "─".repeat(Math.max(0, width - 1 - labelWidth)))
|
||||
);
|
||||
}
|
||||
|
||||
render(width: number): string[] {
|
||||
const theme = this.theme;
|
||||
const subs = this.subs();
|
||||
reconcileDashboardSelection(this.selection, subs);
|
||||
|
||||
const rows = this.tui.terminal.rows || 30;
|
||||
// Render exactly terminal rows - 1 so the overlay covers the header,
|
||||
// chat, editor, and extra footer lines while leaving pi's final footer
|
||||
// row visible.
|
||||
const bodyHeight = Math.max(6, rows - 5);
|
||||
const innerWidth = width - 2;
|
||||
|
||||
const lines: string[] = [];
|
||||
|
||||
// Header: title left, count right
|
||||
const headerLeft = theme.fg("accent", theme.bold("Subagents"));
|
||||
const headerRight = theme.fg(
|
||||
"muted",
|
||||
`${subs.length} agent${subs.length === 1 ? "" : "s"}`,
|
||||
);
|
||||
const headerPad = Math.max(
|
||||
1,
|
||||
width - visibleWidth(headerLeft) - visibleWidth(headerRight) - 4,
|
||||
);
|
||||
lines.push(
|
||||
truncateToWidth(
|
||||
` ${headerLeft}${" ".repeat(headerPad)}${headerRight} `,
|
||||
width,
|
||||
),
|
||||
);
|
||||
|
||||
// Top border with panel title
|
||||
const settled = subs.filter((s) => s.status !== "running").length;
|
||||
lines.push(
|
||||
theme.fg("border", "╭") +
|
||||
this.borderSegment(innerWidth, `agents · ${settled}/${subs.length}`) +
|
||||
theme.fg("border", "╮"),
|
||||
);
|
||||
|
||||
// Rows
|
||||
const divider = theme.fg("border", "│");
|
||||
const rowLines = this.renderRows(subs, innerWidth, bodyHeight);
|
||||
for (let i = 0; i < bodyHeight; i++) {
|
||||
lines.push(divider + this.pad(rowLines[i] ?? "", innerWidth) + divider);
|
||||
}
|
||||
|
||||
// Bottom border
|
||||
lines.push(
|
||||
theme.fg("border", "╰") +
|
||||
theme.fg("border", "─".repeat(innerWidth)) +
|
||||
theme.fg("border", "╯"),
|
||||
);
|
||||
|
||||
// Hints
|
||||
lines.push(
|
||||
truncateToWidth(
|
||||
theme.fg(
|
||||
"dim",
|
||||
` ${configuredKeys(this.keybindings, "tui.select.up")}/${configuredKeys(this.keybindings, "tui.select.down")}/jk select · ${configuredKeys(this.keybindings, "tui.select.confirm")} take over · x abort · ${configuredKeys(this.keybindings, "tui.select.cancel")} close`,
|
||||
),
|
||||
width,
|
||||
),
|
||||
);
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
private renderRows(
|
||||
subs: ReadonlyArray<SubagentSnapshot>,
|
||||
width: number,
|
||||
height: number,
|
||||
): string[] {
|
||||
const theme = this.theme;
|
||||
const out: string[] = [];
|
||||
|
||||
// Scroll window around selection
|
||||
let start = 0;
|
||||
if (subs.length > height) {
|
||||
start = Math.min(
|
||||
Math.max(0, this.selection.index - Math.floor(height / 2)),
|
||||
subs.length - height,
|
||||
);
|
||||
}
|
||||
const visible = subs.slice(start, start + height);
|
||||
|
||||
for (let i = 0; i < visible.length; i++) {
|
||||
const snap = visible[i];
|
||||
const index = start + i;
|
||||
const isSelected = index === this.selection.index;
|
||||
|
||||
// Left: marker, status square, title, dim id
|
||||
const marker = isSelected ? theme.fg("accent", "❯") : " ";
|
||||
const title = isSelected
|
||||
? theme.fg("accent", snap.title)
|
||||
: theme.fg("text", snap.title);
|
||||
const left = ` ${marker} ${statusGlyph(snap, theme)} ${title} ${theme.fg("dim", snap.id)}`;
|
||||
|
||||
// Right: backend · model · context utilization · elapsed · status
|
||||
const utilization = formatContextUtilization(snap.usage);
|
||||
const dot = theme.fg("dim", " · ");
|
||||
const rightParts = [
|
||||
theme.fg("muted", snap.backend),
|
||||
theme.fg("muted", snap.meta.modelLabel ?? "?"),
|
||||
...(utilization ? [theme.fg("muted", utilization)] : []),
|
||||
theme.fg("muted", formatElapsed(snap)),
|
||||
statusWord(snap, theme),
|
||||
];
|
||||
const right = `${rightParts.join(dot)} `;
|
||||
|
||||
const rightWidth = visibleWidth(right);
|
||||
const leftMax = Math.max(0, width - rightWidth - 2);
|
||||
const leftTruncated = truncateToWidth(left, leftMax);
|
||||
const gap = Math.max(2, width - visibleWidth(leftTruncated) - rightWidth);
|
||||
out.push(truncateToWidth(leftTruncated + " ".repeat(gap) + right, width));
|
||||
}
|
||||
|
||||
if (start > 0) {
|
||||
out[0] = truncateToWidth(theme.fg("dim", ` ... ${start} more`), width);
|
||||
}
|
||||
if (start + height < subs.length) {
|
||||
out[out.length - 1] = truncateToWidth(
|
||||
theme.fg("dim", ` ... ${subs.length - start - height} more`),
|
||||
width,
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
invalidate(): void {}
|
||||
}
|
||||
|
||||
// --- Takeover view ------------------------------------------------------------
|
||||
|
||||
const TRANSCRIPT_SCROLL_STEP = 6;
|
||||
|
||||
class TakeoverView implements Component, Focusable {
|
||||
private tui: TUI;
|
||||
private theme: Theme;
|
||||
private keybindings: KeybindingsManager;
|
||||
private id: string;
|
||||
private view: SubagentReadModel;
|
||||
private done: (value: null) => void;
|
||||
private options?: TakeoverOptions;
|
||||
|
||||
private input = new Input();
|
||||
/** Scroll offset in lines from the bottom of the transcript. 0 = pinned to bottom. */
|
||||
private scrollOffset = 0;
|
||||
private unsubscribe: () => void;
|
||||
private renderTimer?: ReturnType<typeof setTimeout>;
|
||||
private ticker: ReturnType<typeof setInterval>;
|
||||
private closed = false;
|
||||
|
||||
private _focused = false;
|
||||
get focused(): boolean {
|
||||
return this._focused;
|
||||
}
|
||||
set focused(value: boolean) {
|
||||
this._focused = value;
|
||||
this.input.focused = value;
|
||||
}
|
||||
|
||||
constructor(
|
||||
tui: TUI,
|
||||
theme: Theme,
|
||||
keybindings: KeybindingsManager,
|
||||
id: string,
|
||||
view: SubagentReadModel,
|
||||
done: (value: null) => void,
|
||||
options?: TakeoverOptions,
|
||||
) {
|
||||
this.tui = tui;
|
||||
this.theme = theme;
|
||||
this.keybindings = keybindings;
|
||||
this.id = id;
|
||||
this.view = view;
|
||||
this.done = done;
|
||||
this.options = options;
|
||||
this.unsubscribe = view.subscribeTo(id, () => this.scheduleRender());
|
||||
// Elapsed time in the header ticks along at 1Hz.
|
||||
this.ticker = setInterval(() => this.tui.requestRender(), 1000);
|
||||
this.input.onSubmit = (value: string) => {
|
||||
const text = value.trim();
|
||||
if (!text) return;
|
||||
this.input.setValue("");
|
||||
this.view.requestSend(this.id, text);
|
||||
this.scrollOffset = 0;
|
||||
this.tui.requestRender();
|
||||
};
|
||||
}
|
||||
|
||||
private snap(): SubagentSnapshot | undefined {
|
||||
return this.view.get(this.id);
|
||||
}
|
||||
|
||||
private scheduleRender() {
|
||||
if (this.renderTimer) return;
|
||||
// Streaming can emit an event per token. Limit terminal repaints so this
|
||||
// view cannot starve input handling or make the child look frozen.
|
||||
this.renderTimer = setTimeout(() => {
|
||||
this.renderTimer = undefined;
|
||||
if (!this.closed) this.tui.requestRender();
|
||||
}, 50);
|
||||
}
|
||||
|
||||
private cleanup() {
|
||||
if (this.closed) return false;
|
||||
this.closed = true;
|
||||
this.unsubscribe();
|
||||
clearInterval(this.ticker);
|
||||
if (this.renderTimer) clearTimeout(this.renderTimer);
|
||||
this.renderTimer = undefined;
|
||||
return true;
|
||||
}
|
||||
|
||||
private close() {
|
||||
if (this.cleanup()) this.done(null);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
handleInput(data: string): void {
|
||||
if (this.keybindings.matches(data, "app.clear")) {
|
||||
const snap = this.snap();
|
||||
if (snap?.status === "running") this.view.requestAbort(this.id);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
this.keybindings.matches(data, "app.interrupt") ||
|
||||
this.keybindings.matches(data, "tui.select.cancel")
|
||||
) {
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
if (this.keybindings.matches(data, "tui.editor.cursorUp")) {
|
||||
this.scrollOffset += TRANSCRIPT_SCROLL_STEP;
|
||||
this.tui.requestRender();
|
||||
return;
|
||||
}
|
||||
if (this.keybindings.matches(data, "tui.editor.cursorDown")) {
|
||||
this.scrollOffset = Math.max(
|
||||
0,
|
||||
this.scrollOffset - TRANSCRIPT_SCROLL_STEP,
|
||||
);
|
||||
this.tui.requestRender();
|
||||
return;
|
||||
}
|
||||
if (this.keybindings.matches(data, "tui.editor.pageUp")) {
|
||||
this.scrollOffset += this.viewportHeight();
|
||||
this.tui.requestRender();
|
||||
return;
|
||||
}
|
||||
if (this.keybindings.matches(data, "tui.editor.pageDown")) {
|
||||
this.scrollOffset = Math.max(
|
||||
0,
|
||||
this.scrollOffset - this.viewportHeight(),
|
||||
);
|
||||
this.tui.requestRender();
|
||||
return;
|
||||
}
|
||||
this.input.handleInput(data);
|
||||
this.tui.requestRender();
|
||||
}
|
||||
|
||||
private viewportHeight(): number {
|
||||
const rows = this.tui.terminal.rows || 30;
|
||||
// The complete view renders viewport + 7 chrome rows. Using rows - 8
|
||||
// makes the overlay exactly terminal rows - 1.
|
||||
return Math.max(6, rows - 8);
|
||||
}
|
||||
|
||||
render(width: number): string[] {
|
||||
const theme = this.theme;
|
||||
const border = theme.fg("borderAccent", "─".repeat(Math.max(1, width)));
|
||||
const lines: string[] = [];
|
||||
const snap = this.snap();
|
||||
|
||||
if (!snap) {
|
||||
lines.push(border);
|
||||
lines.push(theme.fg("dim", `${this.id} is no longer tracked`));
|
||||
lines.push(border);
|
||||
return lines;
|
||||
}
|
||||
|
||||
lines.push(border);
|
||||
const utilization = formatContextUtilization(snap.usage);
|
||||
const header =
|
||||
`${statusGlyph(snap, theme)} ` +
|
||||
theme.fg("accent", theme.bold(`${snap.id} · ${snap.title}`)) +
|
||||
theme.fg("muted", ` · ${snap.status} · ${formatElapsed(snap)}`) +
|
||||
(this.options?.badge
|
||||
? theme.fg("muted", ` · ${this.options.badge}`)
|
||||
: "") +
|
||||
theme.fg("dim", ` · ${snap.backend}: ${snap.meta.modelLabel ?? "?"}`) +
|
||||
(utilization ? theme.fg("dim", ` · ${utilization}`) : "");
|
||||
lines.push(truncateToWidth(header, width));
|
||||
lines.push(border);
|
||||
|
||||
// Fixed-height transcript viewport. Error and scroll status consume rows
|
||||
// inside the viewport so streaming/scrolling never changes overlay height.
|
||||
const transcript = buildTranscriptLines(snap, width, theme);
|
||||
const viewport = this.viewportHeight();
|
||||
const errorRows = snap.errorText ? 1 : 0;
|
||||
const scrollRows = this.scrollOffset > 0 ? 1 : 0;
|
||||
const transcriptCapacity = Math.max(1, viewport - errorRows - scrollRows);
|
||||
const maxOffset = Math.max(0, transcript.length - transcriptCapacity);
|
||||
if (this.scrollOffset > maxOffset) this.scrollOffset = maxOffset;
|
||||
|
||||
const body: string[] = [];
|
||||
if (snap.errorText) {
|
||||
body.push(
|
||||
truncateToWidth(theme.fg("error", `error: ${snap.errorText}`), width),
|
||||
);
|
||||
}
|
||||
|
||||
const capacity = Math.max(
|
||||
1,
|
||||
viewport - body.length - (this.scrollOffset > 0 ? 1 : 0),
|
||||
);
|
||||
const end = transcript.length - this.scrollOffset;
|
||||
const visible = transcript.slice(Math.max(0, end - capacity), end);
|
||||
if (visible.length === 0) body.push(theme.fg("dim", "(no output yet)"));
|
||||
else body.push(...visible);
|
||||
|
||||
if (this.scrollOffset > 0) {
|
||||
body.push(
|
||||
truncateToWidth(
|
||||
theme.fg("dim", `... ${this.scrollOffset} lines below · ↓/pgdn`),
|
||||
width,
|
||||
),
|
||||
);
|
||||
}
|
||||
while (body.length < viewport) body.push("");
|
||||
lines.push(...body.slice(0, viewport));
|
||||
|
||||
lines.push(border);
|
||||
lines.push(...this.input.render(width));
|
||||
lines.push(
|
||||
truncateToWidth(
|
||||
theme.fg(
|
||||
"dim",
|
||||
`${configuredKeys(this.keybindings, "tui.input.submit")} send · ${configuredKeys(this.keybindings, "app.interrupt")} back · ${configuredKeys(this.keybindings, "app.clear")} abort run · ${configuredKeys(this.keybindings, "tui.editor.cursorUp")}/${configuredKeys(this.keybindings, "tui.editor.cursorDown")} scroll · ${configuredKeys(this.keybindings, "tui.editor.pageUp")}/${configuredKeys(this.keybindings, "tui.editor.pageDown")} page`,
|
||||
),
|
||||
width,
|
||||
),
|
||||
);
|
||||
lines.push(border);
|
||||
return lines;
|
||||
}
|
||||
|
||||
invalidate(): void {
|
||||
this.input.invalidate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* Transcript rendering for the takeover view: turns a SubagentSnapshot's
|
||||
* normalized transcript + live state into plain wrapped lines. Ported from
|
||||
* v1, with the session-poking replaced by snapshot reads.
|
||||
*/
|
||||
|
||||
import type { Theme } from "@earendil-works/pi-coding-agent";
|
||||
import {
|
||||
truncateToWidth,
|
||||
visibleWidth,
|
||||
wrapTextWithAnsi,
|
||||
} from "@earendil-works/pi-tui";
|
||||
import type { SubagentSnapshot, TranscriptItem } from "../domain.ts";
|
||||
|
||||
const ANSI_PATTERN =
|
||||
// eslint-disable-next-line no-control-regex
|
||||
/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[a-zA-Z\d]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;
|
||||
|
||||
/**
|
||||
* Strip raw ANSI codes, expand tabs, and drop control chars. Terminal-expanded
|
||||
* tabs (and stray escapes) make lines wider than the width we declare to the
|
||||
* TUI, which desyncs the renderer and smears the overlay.
|
||||
*/
|
||||
export function sanitizeText(text: string): string {
|
||||
return text
|
||||
.replace(ANSI_PATTERN, "")
|
||||
.replaceAll("\t", " ")
|
||||
.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "");
|
||||
}
|
||||
|
||||
function renderUserText(
|
||||
theme: Theme,
|
||||
text: string,
|
||||
width: number,
|
||||
out: string[],
|
||||
) {
|
||||
const clean = sanitizeText(text).trim();
|
||||
if (!clean) return;
|
||||
const wrapped = wrapTextWithAnsi(clean, Math.max(10, width - 2));
|
||||
for (let i = 0; i < wrapped.length; i++) {
|
||||
const prefix = i === 0 ? theme.fg("accent", "> ") : " ";
|
||||
out.push(
|
||||
truncateToWidth(prefix + theme.fg("userMessageText", wrapped[i]), width),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function renderThinking(
|
||||
theme: Theme,
|
||||
text: string,
|
||||
width: number,
|
||||
out: string[],
|
||||
) {
|
||||
const reasoning = sanitizeText(text).trim();
|
||||
if (!reasoning) return;
|
||||
const prefix = theme.fg("dim", "~ ");
|
||||
const wrapped = wrapTextWithAnsi(reasoning, Math.max(10, width - 2));
|
||||
for (let i = 0; i < wrapped.length; i++) {
|
||||
out.push(
|
||||
truncateToWidth(
|
||||
(i === 0 ? prefix : " ") + theme.fg("muted", theme.italic(wrapped[i])),
|
||||
width,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function renderAssistantItem(
|
||||
theme: Theme,
|
||||
item: Extract<TranscriptItem, { kind: "assistant" }>,
|
||||
width: number,
|
||||
out: string[],
|
||||
) {
|
||||
for (const part of item.parts) {
|
||||
if (part.type === "text") {
|
||||
const text = sanitizeText(part.text).trim();
|
||||
if (!text) continue;
|
||||
out.push(...wrapTextWithAnsi(text, width));
|
||||
} else if (part.type === "thinking") {
|
||||
renderThinking(
|
||||
theme,
|
||||
part.redacted ? "[redacted reasoning]" : part.text,
|
||||
width,
|
||||
out,
|
||||
);
|
||||
} else if (part.type === "toolCall") {
|
||||
const preview = part.argsPreview ? sanitizeText(part.argsPreview) : "";
|
||||
const line =
|
||||
theme.fg("muted", "→ ") +
|
||||
theme.fg("toolTitle", part.name) +
|
||||
(preview && preview !== "{}" ? theme.fg("dim", ` ${preview}`) : "");
|
||||
out.push(truncateToWidth(line, width));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function renderToolResultItem(
|
||||
theme: Theme,
|
||||
item: Extract<TranscriptItem, { kind: "toolResult" }>,
|
||||
width: number,
|
||||
out: string[],
|
||||
) {
|
||||
const firstLine =
|
||||
sanitizeText(item.outputPreview ?? "")
|
||||
.split("\n")
|
||||
.find((line) => line.trim()) ?? "";
|
||||
const label = item.isError
|
||||
? theme.fg("error", " error: ")
|
||||
: theme.fg("dim", " output: ");
|
||||
out.push(
|
||||
truncateToWidth(label + theme.fg("dim", firstLine || "(no output)"), width),
|
||||
);
|
||||
}
|
||||
|
||||
/** Render a subagent's conversation as plain lines, wrapped to `width`. */
|
||||
export function buildTranscriptLines(
|
||||
snap: SubagentSnapshot,
|
||||
width: number,
|
||||
theme: Theme,
|
||||
): string[] {
|
||||
const out: string[] = [];
|
||||
|
||||
for (const item of snap.transcript) {
|
||||
const before = out.length;
|
||||
if (item.kind === "user") {
|
||||
renderUserText(theme, item.text, width, out);
|
||||
} else if (item.kind === "assistant") {
|
||||
renderAssistantItem(theme, item, width, out);
|
||||
} else {
|
||||
renderToolResultItem(theme, item, width, out);
|
||||
}
|
||||
if (out.length > before) out.push("");
|
||||
}
|
||||
while (out.length > 0 && out[out.length - 1] === "") out.pop();
|
||||
|
||||
// Live streaming assistant buffers (cleared when the finalized message lands).
|
||||
if (snap.liveAssistant) {
|
||||
const { thinking, text } = snap.liveAssistant;
|
||||
const before = out.length;
|
||||
if (out.length > 0) out.push("");
|
||||
if (thinking.trim()) renderThinking(theme, thinking, width, out);
|
||||
if (text.trim())
|
||||
out.push(...wrapTextWithAnsi(sanitizeText(text).trim(), width));
|
||||
if (out.length === before + 1) out.pop();
|
||||
}
|
||||
|
||||
// Live tool executions (present until the ToolEnd lands in the transcript).
|
||||
for (const tool of snap.liveTools) {
|
||||
if (out.length > 0) out.push("");
|
||||
const marker = tool.done
|
||||
? tool.isError
|
||||
? theme.fg("error", "error")
|
||||
: theme.fg("success", "done")
|
||||
: theme.fg("warning", "running");
|
||||
let line = `${theme.fg("toolTitle", tool.name)} · ${marker}`;
|
||||
const preview = tool.outputPreview && sanitizeText(tool.outputPreview);
|
||||
if (preview) line += theme.fg("dim", ` · ${preview}`);
|
||||
out.push(truncateToWidth(line, width));
|
||||
}
|
||||
|
||||
// Queued steering/follow-up messages: show them immediately so Enter
|
||||
// visibly acknowledges the user's input instead of appearing to do nothing.
|
||||
for (const message of snap.queued) {
|
||||
if (out.length > 0) out.push("");
|
||||
const prefix = theme.fg("warning", `> [queued ${message.kind}] `);
|
||||
const wrapped = wrapTextWithAnsi(
|
||||
sanitizeText(message.text),
|
||||
Math.max(10, width - visibleWidth(prefix)),
|
||||
);
|
||||
for (let i = 0; i < wrapped.length; i++) {
|
||||
out.push(
|
||||
truncateToWidth(
|
||||
(i === 0 ? prefix : " ".repeat(visibleWidth(prefix))) +
|
||||
theme.fg("muted", wrapped[i]),
|
||||
width,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
Reference in New Issue
Block a user