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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/bridge/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
- Everything the user sends pi (messages, queue edits, Stop) goes through `PiInput`. Messages and queue edits run in one order with the session's own steps (start, model changes, compact); Stop acts at once, and input asked for before it goes back to the message box instead of to pi. Follow pi's queue only from its `queue_update` events, never from what was sent. `PiInput` reports `busy` (a run, a queue, steps in flight, tracked work such as a compaction) after the events that work emits, including each pi event's chunks (`observe`'s callback); the extension stops an off-screen chat's bridge on it, so anything that keeps pi working must count.
- One bridge runs one pi on one session (`--session` at launch); a different chat gets its own bridge, so never switch pi's session in place. Before any input reaches pi, prove it is on the requested session file (`get_state`). pi exits on `--session` for a file it never saved, so resume only files that exist.
- pi is isolated from the user's own pi setup: global extensions, skills and prompt templates are off, and the tool list is explicit. AGENTS.md files load as pi does by default, which is how `~/.ardi/AGENTS.md` reaches it. The only skills pi loads are in `~/.ardi/.agents/skills/` (`--no-skills` plus `--skill`). It gets every built-in tool plus Ardi's browser tools by design; don't narrow it without asking. On Windows the shell tool is `powershell` instead of `bash`, so Git Bash isn't required. For the prompt flag, see `src/agent/AGENTS.md`.
- `runtime/`, `normalization/` and `history/` are adapted from Claudian's pi provider (github.com/YishenTu/claudian, `src/providers/pi`); each file's header names its source. Check the source when fixing pi protocol behavior there.
- `runtime/`, `normalization/` and `history/` started from Claudian's pi provider (github.com/YishenTu/claudian, `src/providers/pi`); each file's header names its source. They are Ardi's own now and needn't match it: follow pi's docs (`rpc.md`, `json.md`, `session-format.md`), and check Claudian only for how it handled the same case.
- Never start a `.cmd` or `.bat` file, directly or with `shell: true`: Node and Bun refuse the first, and cmd.exe re-parses arguments in the second. Resolve commands through `runtime/spawnable.ts`, which runs an npm shim's script with node.
- pi's `check_back` and `schedule_job` tools reach the extension through pi's extension UI protocol: an `editor` dialog titled `SCHEDULE_DIALOG` (`protocol.ts`). `PiSession` never shows it; it forwards it as `schedule_request` and answers the dialog with the extension's `schedule_reply`.
6 changes: 2 additions & 4 deletions src/bridge/PiSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,16 +125,14 @@ export class PiSession {
prepareWorkDir();
const resumeFile = saved(sessionFile);
const proc = new PiProcess(buildPiLaunchSpec(this.target, resumeFile, piPath));
const transport = new PiRPCTransport({ input: proc.stdout, output: proc.stdin });
proc.onClose((error) => this.fail(error ?? new Error("pi exited"), proc.stderrSnapshot));
const normalization = createPiEventNormalizationState();
transport.onEvent((event) => {
const transport = new PiRPCTransport({ input: proc.stdout, output: proc.stdin }, (event) => {
if (this.forwardSchedule(event)) return;
this.input.observe(event, () => {
for (const chunk of normalizePiRPCEvent(event, normalization)) this.send({ type: "chunk", chunk });
});
});
transport.start();
proc.onClose((error) => this.fail(error ?? new Error("pi exited"), proc.stderrSnapshot));
this.phase = { state: "running", process: proc, transport };

const { models } = await transport.request<{ models: Parameters<typeof toModelInfo>[0] }>("get_available_models");
Expand Down
76 changes: 24 additions & 52 deletions src/bridge/history/piHistory.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
// Adapted from Claudian (src/providers/pi/history/PiHistoryStore.ts).
// Rebuilds the chat from pi's session file, which is the record of the
// conversation. Kept: entry parsing, active-branch resolution, message and
// tool-result mapping. Consecutive assistant entries of one run merge into
// one message, as live output renders them.
// Each run also gets its duration, output tokens and whether it was stopped.
// TODO: branches/fork, subagents (both in Claudian).
// Rebuilds the chat from pi's session file (docs/session-format.md), which is
// the record of the conversation. Started from Claudian's PiHistoryStore
// (src/providers/pi/history/PiHistoryStore.ts); it reads only pi's current
// format. Consecutive assistant entries of one run merge into one message, as
// live output renders them. Each run also gets its duration, output tokens
// and whether it was stopped.

import { readFile } from "node:fs/promises";

Expand All @@ -13,7 +12,7 @@ import { getPiCustomMessageDisplayText } from "../normalization/piEventNormaliza
import { extractPiToolResultText, getRecord, getString, isPlainObject, normalizePiToolInput } from "../normalization/piToolNormalization";

interface PiSessionEntry {
id?: string;
id: string;
// The entry's message, or the entry itself for entries without one.
message: Record<string, unknown>;
parentId?: string;
Expand All @@ -25,7 +24,7 @@ export async function readPiHistory(sessionFile: string): Promise<ChatMessage[]>
const entries: PiSessionEntry[] = [];
// Split on LF only: U+2028/U+2029 are valid inside JSON strings.
for (const line of (await readFile(sessionFile, "utf8")).split("\n")) addPiSessionLine(entries, line);
return mapPiSessionEntries(resolvePiActivePath(entries));
return mapPiSessionEntries(activePath(entries));
}

function addPiSessionLine(entries: PiSessionEntry[], line: string): void {
Expand All @@ -39,9 +38,11 @@ function addPiSessionLine(entries: PiSessionEntry[], line: string): void {
return;
}
const type = getString(record.type) ?? "";
if (type === "session") return; // header
const id = getString(record.id);
// The header (type "session") isn't part of the conversation.
if (type === "session" || !id) return;
entries.push({
id: getString(record.id) ?? undefined,
id,
message: getRecord(record.message) ?? record,
parentId: getString(record.parentId) ?? undefined,
raw: record,
Expand All @@ -59,10 +60,10 @@ function mapPiSessionEntries(entries: PiSessionEntry[]): ChatMessage[] {
last.completedAt = writtenAt;
last.durationMs = writtenAt - runStart;
};
for (const [index, entry] of entries.entries()) {
for (const entry of entries) {
const { message } = entry;
const role = getString(message.role);
const id = entry.id ?? `pi-${index}`;
const { id } = entry;
const timestamp = getTimestamp(message.timestamp ?? entry.raw.timestamp);
// When the entry was written, i.e. when that step finished.
const writtenAt = getTimestamp(entry.raw.timestamp ?? message.timestamp);
Expand All @@ -86,7 +87,7 @@ function mapPiSessionEntries(entries: PiSessionEntry[]): ChatMessage[] {
if (run?.role === "assistant" && typeof output === "number") run.outputTokens = (run.outputTokens ?? 0) + output;
if (run?.role === "assistant" && message.stopReason === "aborted") run.interrupted = true;
extendRun(writtenAt);
} else if (isToolResultEntry(entry)) {
} else if (role === "toolResult") {
applyToolResult(messages, entry);
extendRun(writtenAt);
} else if (entry.type === "compaction") {
Expand Down Expand Up @@ -143,16 +144,8 @@ function extractAssistantToolCalls(value: unknown): ToolCall[] {
});
}

function isToolResultEntry(entry: PiSessionEntry): boolean {
return getString(entry.message.role) === "toolResult";
}

function getToolResultCallId(entry: PiSessionEntry): string | null {
return getString(entry.message.toolCallId);
}

function applyToolResult(messages: ChatMessage[], entry: PiSessionEntry): void {
const toolCallId = getToolResultCallId(entry);
const toolCallId = getString(entry.message.toolCallId);
if (!toolCallId) return;
for (let index = messages.length - 1; index >= 0; index--) {
const message = messages[index];
Expand All @@ -167,35 +160,14 @@ function applyToolResult(messages: ChatMessage[], entry: PiSessionEntry): void {
}
}

// Active branch: walk from the leaf (last entry) to the root via parentId,
// keeping tool results that belong to calls on that path.
function resolvePiActivePath(entries: PiSessionEntry[]): PiSessionEntry[] {
const withIds = entries.filter((entry): entry is PiSessionEntry & { id: string } => !!entry.id);
if (withIds.length === 0) return entries;
const hasBranchGraph = withIds.some((entry) => !!entry.parentId && !isToolResultEntry(entry));
if (!hasBranchGraph) return entries;

const byId = new Map(withIds.map((entry) => [entry.id, entry] as const));
const activeIds = new Set<string>();
let current: PiSessionEntry | undefined = withIds.at(-1);
while (current?.id && !activeIds.has(current.id)) {
activeIds.add(current.id);
current = current.parentId ? byId.get(current.parentId) : undefined;
}

const activeToolCallIds = new Set<string>();
for (const entry of entries) {
if (entry.id && activeIds.has(entry.id)) {
for (const call of extractAssistantToolCalls(entry.message.content)) activeToolCallIds.add(call.id);
}
}
return entries.filter((entry) => {
if (isToolResultEntry(entry)) {
const callId = getToolResultCallId(entry);
return (!!callId && activeToolCallIds.has(callId)) || (!!entry.id && activeIds.has(entry.id));
}
return entry.id ? activeIds.has(entry.id) : !!entry.parentId && activeIds.has(entry.parentId);
});
// The active branch: the path from the leaf (the last entry) back to the
// root through each entry's parentId, in file order. Tool results are
// entries on it like any other.
function activePath(entries: PiSessionEntry[]): PiSessionEntry[] {
const byId = new Map(entries.map((entry) => [entry.id, entry] as const));
const onPath = new Set<string>();
for (let entry = entries.at(-1); entry && !onPath.has(entry.id); entry = entry.parentId ? byId.get(entry.parentId) : undefined) onPath.add(entry.id);
return entries.filter((entry) => onPath.has(entry.id));
}

function extractTextContent(value: unknown): string {
Expand Down
62 changes: 28 additions & 34 deletions src/bridge/normalization/piEventNormalization.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Adapted from Claudian (src/providers/pi/normalization/piEventNormalization.ts).
// Started from Claudian (src/providers/pi/normalization/piEventNormalization.ts).
// Maps pi RPC events to Ardi chat chunks. Adds run_start/run_end; custom
// messages, compaction and retries become notices.
// Tool results carry pi's raw `details`; the panel's ToolCard reads them.
Expand All @@ -8,16 +8,16 @@
import type { ChatChunk, ImageAttachment } from "../../chat";
import { extractPiToolResultText, extractPiToolTextContent, getRecord, getString, isPlainObject, normalizePiToolInput } from "./piToolNormalization";

export interface PiEventNormalizationState {
emittedToolIds: Set<string>;
/** Latest native partial-result snapshot per running tool. */
toolOutputs: Map<string, string>;
/** Running tools whose snapshot stopped extending the text already streamed. */
divergedToolOutputIds: Set<string>;
}
// Each tool call of the current run, by id, one stage at a time: streaming
// its output (pi's latest partial-result snapshot), diverged once a snapshot
// stopped extending what was streamed (the result's text then replaces it),
// and done once it has a result. Kept until the run settles, so a call is
// reported once.
type ToolStage = { stage: "streaming" | "diverged"; output: string } | { stage: "done" };
export type PiEventNormalizationState = { tools: Map<string, ToolStage> };

export function createPiEventNormalizationState(): PiEventNormalizationState {
return { divergedToolOutputIds: new Set(), emittedToolIds: new Set(), toolOutputs: new Map() };
return { tools: new Map() };
}

export function normalizePiRPCEvent(event: Record<string, unknown>, state: PiEventNormalizationState): ChatChunk[] {
Expand All @@ -26,6 +26,7 @@ export function normalizePiRPCEvent(event: Record<string, unknown>, state: PiEve
case "agent_start":
return [{ type: "run_start", at: Date.now() }];
case "agent_settled":
state.tools.clear();
return [{ type: "run_end", at: Date.now(), interrupted: event.aborted === true }];
case "message_update":
return normalizeMessageUpdate(event);
Expand Down Expand Up @@ -124,41 +125,34 @@ function normalizeMessageUpdate(event: Record<string, unknown>): ChatChunk[] {

function normalizeToolUse(event: Record<string, unknown>, state: PiEventNormalizationState): ChatChunk[] {
const id = getString(event.toolCallId);
if (!id || state.emittedToolIds.has(id)) return [];
state.emittedToolIds.add(id);
if (!id || state.tools.has(id)) return [];
state.tools.set(id, { stage: "streaming", output: "" });
return [{ type: "tool_use", id, name: getString(event.toolName) ?? "tool", input: normalizePiToolInput(event.args) }];
}

// pi's partialResult is the tool's latest snapshot, but tool_output chunks
// are appended by consumers. Stream only suffix growth; once a snapshot
// stops extending the streamed text, wait for tool_result's final text.
function normalizeToolOutput(event: Record<string, unknown>, state: PiEventNormalizationState): ChatChunk[] {
const id = getString(event.toolCallId);
if (!id) return [];
const content = getToolOutputDelta(id, event.partialResult, state);
return content ? [{ type: "tool_output", id, content }] : [];
}

function getToolOutputDelta(id: string, snapshot: unknown, state: PiEventNormalizationState): string {
const content = extractPiToolTextContent(snapshot);
if (!content) return "";
// pi's partialResult is the tool's latest snapshot, but tool_output chunks
// are appended by consumers. Stream only suffix growth; once a snapshot
// stops extending the streamed text, wait for tool_result's final text.
const previous = state.toolOutputs.get(id) ?? "";
state.toolOutputs.set(id, content);
if (state.divergedToolOutputIds.has(id)) return "";
if (!content.startsWith(previous)) {
state.divergedToolOutputIds.add(id);
return "";
}
return content.slice(previous.length);
const content = extractPiToolTextContent(event.partialResult);
if (!id || !content) return [];
const tool = state.tools.get(id) ?? { stage: "streaming", output: "" };
if (tool.stage === "done") return [];
const grows = tool.stage === "streaming" && content.startsWith(tool.output);
state.tools.set(id, { stage: grows ? "streaming" : "diverged", output: content });
const delta = grows ? content.slice(tool.output.length) : "";
return delta ? [{ type: "tool_output", id, content: delta }] : [];
}

function normalizeToolResult(event: Record<string, unknown>, state: PiEventNormalizationState): ChatChunk[] {
const id = getString(event.toolCallId);
if (!id) return [];
const result = event.result;
const content = result === undefined ? (state.toolOutputs.get(id) ?? "") : extractPiToolResultText(getString(event.toolName) ?? "tool", result);
state.toolOutputs.delete(id);
state.divergedToolOutputIds.delete(id);
const { result } = event;
const tool = state.tools.get(id);
// Without a result, the last snapshot is the output.
const content = result !== undefined ? extractPiToolResultText(getString(event.toolName) ?? "tool", result) : tool && tool.stage !== "done" ? tool.output : "";
state.tools.set(id, { stage: "done" });
const details = isPlainObject(result) ? result.details : undefined;
return [{ type: "tool_result", id, content, isError: event.isError === true, details }];
}
11 changes: 9 additions & 2 deletions src/bridge/runtime/PiJSONL.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
// Copied from Claudian (src/providers/pi/runtime/PiJSONL.ts).
// pi's JSONL: one JSON value per LF-terminated line (U+2028/U+2029 can sit
// inside JSON strings, so nothing else splits). Started from Claudian
// (src/providers/pi/runtime/PiJSONL.ts).
import type { Writable } from 'node:stream';
import { StringDecoder } from 'node:string_decoder';

Expand Down Expand Up @@ -28,7 +30,9 @@ export function subscribePiJSONLLines(
lines.push(decoder.write(typeof chunk === 'string' ? Buffer.from(chunk) : chunk), onLine);
};

// Streams emit `end`, then `close` (or only `close`): the rest is read once.
const handleEnd = (): void => {
stopReading();
lines.push(decoder.end(), onLine);
if (lines.bufferedLength > 0) onLine(lines.take());
onEnd?.();
Expand All @@ -43,10 +47,13 @@ export function subscribePiJSONLLines(
input.on('close', handleEnd);
input.on('error', handleError);

return () => {
const stopReading = (): void => {
input.off('data', handleData);
input.off('end', handleEnd);
input.off('close', handleEnd);
};
return () => {
stopReading();
input.off('error', handleError);
};
}
Expand Down
Loading