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
5 changes: 3 additions & 2 deletions docs/execution-trace-stream.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ An agent launch may declare `traceSources.primary` with `kind: execution_stream`
an absolute guest `path`, `mediaType: application/x-ndjson`, and its `provider`.
`formatVersion`, `cliVersion`, and `harnessVersion` identify the producing harness
when known. Declare the native audit session separately as `nativeSession`;
native discovery commands remain supported. Existing drivers declare a native
primary until GEN-2137/2138/2139 implement their stream producers.
native discovery commands remain supported. Codex and Claude retain native-primary compatibility until their stream producers
are enabled. Pi keeps its published native session as primary; see
[Pi session contract](pi-session-contract.md).

Execution streams contain UTF-8, newline-terminated JSON objects in append order:

Expand Down
46 changes: 46 additions & 0 deletions docs/pi-session-contract.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Pi native session projection

Factorize supports the exe.dev **@earendil-works/pi-coding-agent 1.1.0**
binary and its published **session JSONL v3** contract. Pi launches check
`pi --version` before passing the prompt to the CLI; a different version fails
with a harness diagnostic. Guest image owners must install the supported release.
An upgrade requires reviewing the release's session/message contracts, capturing
new versioned fixtures, and changing the version constant and tests together.

The compatibility reference is the release's
[session format](https://github.com/earendil-works/pi/blob/v1.1.0/packages/coding-agent/docs/session-format.md)
and [message types](https://github.com/earendil-works/pi/blob/v1.1.0/packages/coding-agent/docs/message-types.md),
also shipped in the binary's docs directory. Fixtures live in
`packages/app/test/fixtures/pi/1.1.0`; their README documents reproduction.

Pi's primary source is the native session discovered under its run-specific
`--session-dir`. Both live projection and terminal reconciliation read this file.
Source receipts record `native_session`, CLI version `1.1.0`, and format version
`3`. Plain print-mode stdout remains terminal output and is never advertised as
a complete execution stream.

Projection retains all branches in append order, including abandoned history.
It does not rebuild only the active model context or apply context edits to
historical display content. Every event retains its native entry ID, parent,
and ISO timestamp; display provenance also retains null roots and the nested
Unix-millisecond message timestamp. Several content-block or usage events may
share one native entry ID. `display.blockIndex` identifies content blocks;
`display.toolCallId` links tool calls and results independently of entry IDs.

The UI shows text/thinking, tool arguments/results, direct bash executions,
usage, compaction and branch summaries. Metadata retains model/thinking changes,
system prompt/tool patches, context edits, labels, session info, custom entries,
unknown roles and future records. Compaction retains `firstKeptEntryId`,
checkpoint, and token counts; branches retain `fromId` and their actual parent.
Arguments, results and extension metadata are bounded for display; images and
opaque replay signatures are omitted. The native artifact remains exact.

The projector never rewrites or migrates stored artifacts. Pi itself migrates
v1 (linear) to v2 (tree) and v2 `hookMessage` to v3 `custom` on load. Historical
headers without a version or with non-v3 versions are marked
`best_effort_unmigrated`; available IDs are preserved and absent ancestry is
not invented. Legacy `hookMessage` is displayed as custom metadata. Unknown
future types use bounded metadata, malformed JSON uses warning events, and
invalid timestamps remain display metadata rather than invalid database dates.
This fallback is for retained artifacts, not authorization to launch unreviewed
CLI versions.
5 changes: 4 additions & 1 deletion packages/app/src/agent-driver.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { PI_CLI_VERSION, PI_SESSION_VERSION } from "./pi-trace";
import type { TraceSources } from "./trace-source";
export type AgentKind = "codex" | "claude" | "pi";

Expand Down Expand Up @@ -50,7 +51,9 @@ class PiDriver implements AgentDriver {
const args = ["-p", "--session-id", runId, "--session-dir", sessionDir];
if (config.model?.trim()) args.push("--model", config.model.trim());
if (config.effort?.trim()) args.push("--thinking", config.effort.trim());
return { executable: "pi", args, env: {}, stdin: "prompt", artifacts: { roots: [sessionDir], fileNameIncludes: ".jsonl", sessionId: runId, discoverCommand: `find '${sessionDir}' -type f -name '*.jsonl' -print | head -1` } };
const discoverCommand = `find '${sessionDir}' -type f -name '*.jsonl' -print | head -1`;
// Guest images own installation. Refuse version drift before consuming stdin.
return { executable: "/bin/sh", args: ["-c", `test "$(pi --version)" = "${PI_CLI_VERSION}" || { echo "Factorize requires Pi ${PI_CLI_VERSION}" >&2; exit 1; }; exec pi "$@"`, "factorize-pi", ...args], env: {}, stdin: "prompt", artifacts: { roots: [sessionDir], fileNameIncludes: ".jsonl", sessionId: runId, discoverCommand }, traceSources: { primary: { kind: "native_session", path: sessionDir, mediaType: "application/x-ndjson", provider: "pi", cliVersion: PI_CLI_VERSION, formatVersion: PI_SESSION_VERSION, discoverCommand } } };
}
}

Expand Down
86 changes: 86 additions & 0 deletions packages/app/src/pi-trace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import type { TraceEvent, TraceEventType } from "./trace";

/** The exe.dev Pi binary and its published session contract, not stdout events. */
export const PI_CLI_VERSION = "1.1.0";
export const PI_SESSION_VERSION = "3";
const LIMIT = 32_768;
const clip = (value: unknown): string => {
const text = typeof value === "string" ? value : JSON.stringify(value ?? "");
return text.length <= LIMIT ? text : text.slice(0, LIMIT) + "\n… output truncated in trace view";
};
const object = (value: any): value is Record<string, any> => !!value && typeof value === "object" && !Array.isArray(value);

/** Bound arbitrary extension payloads; omit binary images and opaque replay signatures. */
function safe(value: any, depth = 0): any {
if (typeof value === "string") return clip(value);
if (value === null || typeof value !== "object") return value;
if (depth >= 6) return "[nested metadata omitted]";
if (Array.isArray(value)) return value.slice(0, 64).map(item => safe(item, depth + 1));
if (value.type === "image") return { type: "image", mimeType: clip(value.mimeType), omitted: true };
return Object.fromEntries(Object.entries(value).slice(0, 64).filter(([key]) => !["thinkingSignature", "thoughtSignature", "textSignature"].includes(key)).map(([key, item]) => [clip(key), safe(item, depth + 1)]));
}
function bounded(value: any): any {
const result = safe(value);
const json = JSON.stringify(result ?? null);
return json.length <= LIMIT ? result : { truncated: true, preview: clip(json) };
}
const text = (content: any): string => Array.isArray(content)
? clip(content.map(block => object(block) ? block.type === "image" ? `[Image: ${clip(block.mimeType)}; binary omitted]` : block.text ?? block.thinking ?? `[Content block: ${clip(block.type)}]` : "").join("\n"))
: clip(content);

/** Each derived event retains the native entry ID/parent; tool IDs are separate links. */
export function parsePi(input: any, sequence: number): TraceEvent[] {
const value = object(input) ? input : { type: "invalid_record", data: input };
const message = object(value.message) ? value.message : {};
const provenance = {
entryType: value.type ?? "unknown", entryId: value.id ?? null,
parentId: value.parentId ?? null, timestamp: value.timestamp ?? null,
...(message.timestamp !== undefined ? { messageTimestamp: message.timestamp } : {}),
};
const make = (type: TraceEventType, title: string, preview: any, extra: Record<string, unknown> = {}): TraceEvent => ({
sequence, id: String(value.id ?? `pi:${sequence}`),
...(typeof value.parentId === "string" ? { parentId: value.parentId } : {}),
type, title: clip(title), preview: clip(preview),
...(typeof message.role === "string" ? { role: message.role } : {}),
...(typeof value.timestamp === "string" && Number.isFinite(Date.parse(value.timestamp)) ? { occurredAt: value.timestamp } : {}),
display: { ...bounded(provenance), ...extra },
});
const metadata = (title: string, record: any = value) => make("metadata", title, bounded(record), { metadata: bounded(record) });
if (value.type === "session") return [make("metadata", "Session started", value.cwd ?? "", {
version: value.version ?? 1, cwd: clip(value.cwd), parentSession: value.parentSession ? clip(value.parentSession) : null,
compatibility: value.version === 3 ? "supported" : "best_effort_unmigrated",
})];
if (value.type === "compaction" || value.type === "branch_summary") return [make(value.type === "compaction" ? "compaction" : "branch", value.type === "compaction" ? "Context compacted" : "Branch summary", value.summary, {
firstKeptEntryId: value.firstKeptEntryId ?? null, fromId: value.fromId ?? null,
tokensBefore: value.tokensBefore, fromHook: value.fromHook, details: bounded(value.details),
usage: bounded(value.usage), systemMessage: bounded(value.systemMessage),
})];
if (value.type === "usage") return [make("usage", `Usage: ${clip(value.kind)}`, bounded(value.usage), { kind: clip(value.kind), provider: clip(value.provider), model: clip(value.model), usage: bounded(value.usage) })];
const titles: Record<string, string> = { model_change: "Model changed", thinking_level_change: "Thinking level changed", custom: "Custom entry", custom_message: "Custom message", label: "Entry label", session_info: "Session info", context_edit: "Context edited" };
if (value.type !== "message") return [metadata(Object.hasOwn(titles, value.type) ? titles[value.type]! : `Unknown entry: ${clip(value.type)}`)];
const role = message.role;
if (role === "user") return [make("user_message", "User", text(message.content))];
if (role === "toolResult") return [make("tool_result", message.toolName ?? "Tool result", text(message.content), {
toolCallId: message.toolCallId, isError: message.isError, details: bounded(message.details),
usage: bounded(message.usage), nestedCalls: bounded(message.nestedCalls),
})];
if (role === "bashExecution") return [make("command", message.command ?? "Command", message.output, {
exitCode: message.exitCode, cancelled: message.cancelled, truncated: message.truncated,
fullOutputPath: message.fullOutputPath ? clip(message.fullOutputPath) : undefined, excludeFromContext: message.excludeFromContext,
})];
if (role === "branchSummary" || role === "compactionSummary") return [make(role === "branchSummary" ? "branch" : "compaction", role === "branchSummary" ? "Branch summary" : "Context compacted", message.summary, { fromId: message.fromId, tokensBefore: message.tokensBefore })];
if (role !== "assistant") return [metadata(role === "system" ? "System prompt changed" : role === "custom" || role === "hookMessage" ? "Custom message" : `Unknown message role: ${clip(role)}`, message)];
const entries: TraceEvent[] = [];
for (const [blockIndex, block] of (Array.isArray(message.content) ? message.content : []).entries()) {
const extra = { blockIndex, provider: clip(message.provider), model: clip(message.model), thinkingLevel: message.thinkingLevel, stopReason: message.stopReason };
if (!object(block)) { entries.push(metadata("Invalid content block", block)); continue; }
if (block.type === "thinking") entries.push(make("reasoning", "Reasoning", block.redacted ? "[Redacted thinking]" : block.thinking, { ...extra, redacted: block.redacted }));
else if (block.type === "toolCall") entries.push(make("tool_call", block.name ?? "Tool call", bounded(block.arguments ?? {}), { ...extra, toolCallId: block.id, namespace: block.namespace, arguments: bounded(block.arguments ?? {}) }));
else if (block.type === "text") entries.push(make("assistant_message", "Assistant", block.text, extra));
else entries.push(make("metadata", `Unknown content block: ${clip(block.type)}`, bounded(block), { ...extra, metadata: bounded(block) }));
}
if (!entries.length) entries.push(make("assistant_message", "Assistant", text(message.content)));
if (message.usage) entries.push(make("usage", "Model usage", bounded(message.usage), { provider: clip(message.provider), model: clip(message.model), usage: bounded(message.usage) }));
if (message.errorMessage || ["error", "aborted"].includes(message.stopReason)) entries.push(make(message.stopReason === "error" ? "error" : "warning", "Assistant " + message.stopReason, message.errorMessage ?? message.stopReason));
return entries.map((entry, index) => ({ ...entry, sequence: sequence + index }));
}
22 changes: 1 addition & 21 deletions packages/app/src/trace.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { parsePi } from "./pi-trace";
import type { TraceSource } from "./trace-source";
export type TraceEventType = "user_message" | "assistant_message" | "reasoning" | "tool_call" | "tool_result" | "command" | "file_change" | "compaction" | "branch" | "usage" | "warning" | "error" | "metadata";

Expand Down Expand Up @@ -26,27 +27,6 @@ function event(sequence: number, type: TraceEventType, title: string, preview: u
return { sequence, id: String(source.id ?? source.uuid ?? `${sequence}`), ...(source.parentId || source.parentUuid ? { parentId: String(source.parentId ?? source.parentUuid) } : {}), type, ...(source.role ? { role: String(source.role) } : {}), title, preview: clipped(preview), ...(source.timestamp ? { occurredAt: String(source.timestamp) } : {}), display: {} };
}

function parsePi(value: any, sequence: number): TraceEvent[] {
if (value.type === "session") return [event(sequence, "metadata", "Session started", value.cwd ?? "", value)];
if (value.type === "compaction") return [event(sequence, "compaction", "Context compacted", value.summary, value)];
if (value.type === "branch_summary") return [event(sequence, "branch", "Branch summary", value.summary, value)];
if (value.type !== "message") return [event(sequence, "metadata", String(value.type ?? "Event"), value, value)];
const message = value.message ?? {}, role = message.role;
if (role === "user") return [event(sequence, "user_message", "User", contentText(message.content), { ...value, role })];
if (role === "toolResult") return [event(sequence, "tool_result", String(message.toolName ?? "Tool result"), contentText(message.content), { ...value, role })];
if (role === "bashExecution") return [event(sequence, "command", String(message.command ?? "Command"), message.output, { ...value, role })];
if (role === "assistant") {
const entries: TraceEvent[] = [];
for (const block of Array.isArray(message.content) ? message.content : []) {
if (block.type === "thinking") entries.push(event(sequence + entries.length, "reasoning", "Reasoning", block.thinking, { ...value, role }));
else if (block.type === "toolCall") entries.push({ ...event(sequence + entries.length, "tool_call", String(block.name ?? "Tool call"), block.arguments, { ...value, id: block.id, role }), display: { arguments: block.arguments ?? {} } });
else if (block.type === "text") entries.push(event(sequence + entries.length, "assistant_message", "Assistant", block.text, { ...value, role }));
}
return entries.length ? entries : [event(sequence, "assistant_message", "Assistant", contentText(message.content), { ...value, role })];
}
return [event(sequence, "metadata", String(role ?? "Message"), message.content, { ...value, role })];
}

function parseCodex(value: any, sequence: number): TraceEvent[] {
const payload = value.payload ?? {};
if (value.type === "session_meta") return [event(sequence, "metadata", "Session started", payload.cwd ?? "", { ...value, id: payload.id ?? payload.session_id })];
Expand Down
18 changes: 18 additions & 0 deletions packages/app/test/fixtures/pi/1.1.0/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
These fixtures target the deployed **@earendil-works/pi-coding-agent 1.1.0**,
session JSONL **v3**.

- `documented-v3.jsonl` is a representative contract fixture covering every
published entry type, multi-tool assistant blocks, image omission, usage,
prompt patches, compaction checkpoints, and sibling branches. It includes a
future entry to exercise forward-compatible metadata.
- `native-session.jsonl` is unmodified session output captured from the exe.dev
Pi 1.1.0 binary. The only model is a local deterministic OpenAI-compatible
fixture server; Pi itself serializes the session, invokes bash, and stores its
result. No external credentials or existing sessions are used.
- `python3 capture.py` regenerates the actual-output fixture using the documented
compatible-endpoint configuration. IDs, timestamps, and temporary paths vary.

Compatibility references shipped with that release:
[session format](https://github.com/earendil-works/pi/blob/v1.1.0/packages/coding-agent/docs/session-format.md)
and [message types](https://github.com/earendil-works/pi/blob/v1.1.0/packages/coding-agent/docs/message-types.md).
The installed release copies were used when creating the fixtures.
27 changes: 27 additions & 0 deletions packages/app/test/fixtures/pi/1.1.0/capture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""Capture native JSONL from Pi 1.1.0 using a local, deterministic model.
Run with python3 capture.py. No external model service or credentials are used.
"""
import json, os, pathlib, subprocess, tempfile, threading
from http.server import BaseHTTPRequestHandler, HTTPServer

assert subprocess.check_output(["pi", "--version"], text=True).strip() == "1.1.0"
class Model(BaseHTTPRequestHandler):
def log_message(self, *args): pass
def do_POST(self):
request = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
done = any(m["role"] == "tool" for m in request["messages"])
delta = {"content": "Captured tool result."} if done else {"tool_calls": [{"index": 0, "id": "fixture-call", "type": "function", "function": {"name": "bash", "arguments": '{"command":"printf fixture-output"}'}}]}
chunks = [{"id": "fixture-response", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": delta, "finish_reason": None}]},
{"id": "fixture-response", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {}, "finish_reason": "stop" if done else "tool_calls"}], "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}}]
body = "".join("data: " + json.dumps(c) + "\n\n" for c in chunks) + "data: [DONE]\n\n"
self.send_response(200); self.send_header("Content-Type", "text/event-stream"); self.end_headers(); self.wfile.write(body.encode())
server = HTTPServer(("127.0.0.1", 0), Model)
threading.Thread(target=server.serve_forever, daemon=True).start()
with tempfile.TemporaryDirectory(prefix="factorize-pi-fixture-") as root:
config = pathlib.Path(root, "config"); config.mkdir()
(config / "models.json").write_text(json.dumps({"providers": {"fixture": {"baseUrl": f"http://127.0.0.1:{server.server_port}/v1", "api": "openai-completions", "apiKey": "local-fixture", "models": [{"id": "mock", "reasoning": False, "input": ["text"], "contextWindow": 128000, "maxTokens": 1024}]}}}))
subprocess.run(["pi", "--offline", "--no-extensions", "--no-mcp", "--no-skills", "--no-prompt-templates", "--no-context-files", "--no-approve", "--model", "fixture/mock", "--tools", "bash", "--session-id", "factorize-fixture", "--session-dir", root + "/sessions", "-p", "Run printf fixture-output using bash, then report completion."], cwd=root, env={**os.environ, "PI_CODING_AGENT_DIR": str(config), "PI_TELEMETRY": "0"}, check=True, stdout=subprocess.DEVNULL, timeout=60)
files = list(pathlib.Path(root, "sessions").glob("*.jsonl"))
assert len(files) == 1
pathlib.Path(__file__).with_name("native-session.jsonl").write_bytes(files[0].read_bytes())
server.shutdown()
Loading
Loading