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
46 changes: 44 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. Codex and Claude retain native-primary compatibility until their stream producers
are enabled. Pi keeps its published native session as primary; see
native discovery commands remain supported. Codex retains a native primary until
its stream producer is implemented. Claude declares the stream producer described
below. 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 Expand Up @@ -45,3 +46,44 @@ Launch source declarations are persisted on the run (`trace_sources`), exposed
by run detail and diagnostics. Artifact rows retain source kind, guest path,
media type, provider, format/CLI/harness versions where supplied. Historical
native-only runs still use their existing provider parser and artifact semantics.

## Claude Code stdout producer (GEN-2138)

New Claude jobs run print mode with `--output-format stream-json --verbose`.
A standalone Python 3 stdlib supervisor reads the CLI's stdout JSONL and appends
Factorize v1 records to `/tmp/factorize-artifacts/<run>/claude/trace.jsonl`, flushing
every event. Python 3 is required in the guest. The CLI inherits prompt stdin and
stderr; stderr stays in `/tmp/factorize.stderr`, never in the trace. The wrapper
preserves the child exit status and forwards SIGINT/SIGTERM, recording interruption
and abnormal exits. It bounds input records at 16 MiB and previews at 32 Ki characters and display payloads at 1 MiB.
Malformed/unknown records, unknown content blocks, oversized lines and incomplete
EOF records produce diagnostic warnings rather than poisoning the projection.
A partial line waits for LF while the CLI runs. At EOF it becomes a warning.

`--forward-subagent-text` is deliberately **disabled**. Root Agent/Task calls and
results are the subagent activity visible by default; we do not invent child text
or replay transcripts into the root stream. If a CLI emits nested messages, their
`parent_tool_use_id` is preserved as `parentId`. Tool calls keep their native IDs;
all results in a user record are emitted separately with the matching name and
`parentId`, and `display.isError` retains tool failure status. System/task lifecycle
records retain their payload. Assistant and result usage remain separate usage
receipts (per-message versus total; do not sum both). The result receipt omits the
repeated final-answer text, avoiding duplicate assistant activity.
`--include-partial-messages` is also disabled to avoid duplicate delta/full-message
projection. `--json-schema` is not used.

The normalized append-only stream is the primary live source and durable terminal
artifact, so terminal reconciliation uses the same bytes, IDs and ordering as
live projection. Native project-session JSONL remains a separate audit/recovery
artifact; it cannot overwrite an accepted primary stream. Historical runs with no
persisted source declaration continue to use native discovery. Native fallback
parsing retains tool IDs, result names and error flags, including across artifact
read chunks.

`packages/app/test/fixtures/claude-2.1.293/` contains synthetic, version-pinned
schema fixtures for Claude Code 2.1.293 (the installed CLI version used during
implementation). They model default root/subagent-tool behavior, not forwarded
child text. Boundary tests execute the exact guest supervisor with a fake CLI,
including live pre-exit visibility, malformed/partial lines, UTF-8 fragmentation,
terminal reprojection, failure exits and native recovery. CLI flags follow
https://code.claude.com/docs/en/cli-reference .
8 changes: 6 additions & 2 deletions packages/app/src/agent-driver.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { CLAUDE_STREAM_HARNESS } from "./claude-stream";
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 @@ -37,10 +38,13 @@ class CodexDriver implements AgentDriver {
class ClaudeDriver implements AgentDriver {
readonly kind = "claude" as const;
launch(runId: string, config: AgentConfiguration): AgentLaunchSpec {
const args = ["-p", "--dangerously-skip-permissions", "--session-id", runId];
const path = `/tmp/factorize-artifacts/${runId}/claude/trace.jsonl`;
const args = ["-u", "-c", CLAUDE_STREAM_HARNESS, path, "claude", "-p", "--output-format", "stream-json", "--verbose", "--dangerously-skip-permissions", "--session-id", runId];
if (config.model?.trim()) args.push("--model", config.model.trim());
if (config.effort?.trim()) args.push("--effort", config.effort.trim());
return { executable: "claude", args, env: {}, stdin: "prompt", artifacts: { roots: ["$HOME/.claude/projects"], fileNameIncludes: runId, sessionId: runId, discoverCommand: `find "$HOME/.claude/projects" -type f -name '*${runId}.jsonl' -print | head -1` } };
const artifacts: ArtifactLocator = { roots: ["$HOME/.claude/projects"], fileNameIncludes: runId, sessionId: runId, discoverCommand: `find "$HOME/.claude/projects" -type f -name '*${runId}.jsonl' -print | head -1` };
const nativeSession = { kind: "native_session" as const, path: artifacts.roots[0], mediaType: "application/x-ndjson" as const, provider: this.kind, discoverCommand: artifacts.discoverCommand };
return { executable: "python3", args, env: {}, stdin: "prompt", artifacts, traceSources: { primary: { kind: "execution_stream", path, mediaType: "application/x-ndjson", provider: this.kind, formatVersion: "1", harnessVersion: "claude-stream-v1" }, nativeSession } };
}
}

Expand Down
122 changes: 122 additions & 0 deletions packages/app/src/claude-stream.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/** Standalone guest harness. Python's stdlib avoids a dependency on a Node install in the VM. */
export const CLAUDE_STREAM_HARNESS = String.raw`
import json, os, signal, subprocess, sys

path = sys.argv[1]
tools = {}
record_number = 0
MAX_LINE = 16 * 1024 * 1024

def text(value):
if isinstance(value, str):
return value
if isinstance(value, list):
return "\n".join(text(x.get("text", x.get("thinking", ""))) if isinstance(x, dict) else text(x) for x in value)
return json.dumps(value, ensure_ascii=False)

def emit(kind, title, preview, identity, parent=None, display=None):
preview = text(preview)
if len(preview) > 32768:
preview = preview[:32768] + "\n… output truncated in trace view"
display = display or {}
if len(json.dumps(display, ensure_ascii=False).encode("utf-8")) > 1024 * 1024:
display = dict(truncated=True, diagnostic="Display payload exceeded 1 MiB")
item = dict(version=1, id=str(identity), type=kind, title=str(title)[:1024], preview=preview, display=display)
if parent:
item["parentId"] = str(parent)
stream.write(json.dumps(item, ensure_ascii=False) + "\n")
stream.flush()

def normalize(value):
global record_number
record_number += 1
base = "claude:" + str(record_number)
if not isinstance(value, dict):
emit("warning", "Invalid Claude stream record", value, base)
return
base = str(value.get("uuid") or base)
parent = value.get("parent_tool_use_id") or (value.get("tool_use_id") if value.get("type") == "system" else None)
kind = value.get("type")
if kind in ("assistant", "user"):
message = value.get("message") or {}
content = message.get("content", [])
if isinstance(content, str):
content = [dict(type="text", text=content)]
if not isinstance(content, list):
emit("warning", "Invalid Claude message", value, base, parent)
return
for i, block in enumerate(content):
identity = base + ":" + str(i)
if not isinstance(block, dict):
emit("warning", "Unknown Claude content block", block, identity, parent)
continue
block_kind = block.get("type")
if block_kind == "tool_use":
tool_id = str(block.get("id") or identity)
name = str(block.get("name") or "Tool call")
tools[tool_id] = name
emit("tool_call", name, block.get("input", {}), tool_id, parent, dict(arguments=block.get("input", {})))
elif block_kind == "tool_result":
tool_id = str(block.get("tool_use_id") or "")
emit("tool_result", tools.get(tool_id, "Tool result"), block.get("content", ""), identity, tool_id or parent,
dict(toolUseId=tool_id, isError=bool(block.get("is_error")), toolName=tools.get(tool_id)))
elif block_kind == "thinking":
emit("reasoning", "Reasoning", block.get("thinking", ""), identity, parent)
elif block_kind == "text":
emit("assistant_message" if kind == "assistant" else "user_message", "Assistant" if kind == "assistant" else "User", block.get("text", ""), identity, parent)
else:
emit("warning", "Unknown Claude content block", block, identity, parent)
if message.get("usage"):
emit("usage", "Usage", message["usage"], base + ":usage", parent, dict(usage=message["usage"]))
if value.get("error"):
emit("error", "Claude assistant error", value["error"], base + ":error", parent)
elif kind == "result":
failed = value.get("is_error") or value.get("subtype") != "success"
# result.result repeats the final assistant answer. Keep only the completion receipt.
details = {k: v for k, v in value.items() if k not in ("result", "type", "uuid")}
emit("error" if failed else "metadata", "Claude " + str(value.get("subtype", "result")), details, base, parent, details)
if value.get("usage"):
emit("usage", "Total usage", value["usage"], base + ":usage", parent, dict(usage=value["usage"], modelUsage=value.get("modelUsage", {})))
elif kind in ("system", "error", "abort", "interrupt"):
subtype = str(value.get("subtype", kind))
event_kind = "error" if kind in ("error", "abort", "interrupt") or any(x in subtype for x in ("error", "abort", "interrupt")) else "metadata"
emit(event_kind, "Claude " + subtype, value, base, parent, value)
else:
emit("warning", "Unknown Claude stream event", value, base, parent)

os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "a", encoding="utf-8") as stream:
try:
child = subprocess.Popen(sys.argv[2:], stdin=sys.stdin, stdout=subprocess.PIPE, stderr=sys.stderr)
except OSError as error:
emit("error", "Claude launch failed", str(error), "claude:launch-error")
sys.exit(127)
def stop(signum, frame):
emit("error", "Claude interrupted", dict(signal=signum), "claude:signal:" + str(signum))
child.send_signal(signum)
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
while True:
line = child.stdout.readline(MAX_LINE + 1)
if not line:
break
if len(line) > MAX_LINE:
while line and not line.endswith(b"\n"):
line = child.stdout.readline(MAX_LINE + 1)
record_number += 1
emit("warning", "Oversized Claude stream record", "Record exceeded 16 MiB", "claude:" + str(record_number))
continue
if not line.strip():
continue
try:
if not line.endswith(b"\n"):
raise ValueError("Unterminated JSONL record at EOF")
normalize(json.loads(line))
except (ValueError, TypeError, AttributeError, RecursionError) as error:
record_number += 1
emit("warning", "Unparseable Claude stream record", str(error) + ": " + line[:32768].decode("utf-8", errors="replace"), "claude:" + str(record_number))
code = child.wait()
if code:
emit("error", "Claude process exited", dict(exitCode=code), "claude:exit")
sys.exit(code if code >= 0 else 128 - code)
`;
4 changes: 3 additions & 1 deletion packages/app/src/postgres/run-scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ export class RunScheduler {
}

private sources(run: PersistedRun): TraceSources {
return run.executionTarget.traceSources ?? driverTraceSources(run.executionTarget.agentKind as AgentKind, agentDriver(run.executionTarget.agentKind as AgentKind).launch(run.id, {}));
// Runs launched before source declarations must keep their native projection.
const launch = agentDriver(run.executionTarget.agentKind as AgentKind).launch(run.id, {});
return run.executionTarget.traceSources ?? { primary: { kind: "native_session", path: launch.artifacts.roots[0], mediaType: "application/x-ndjson", provider: run.executionTarget.agentKind as AgentKind, discoverCommand: launch.artifacts.discoverCommand } };
}

private async collectArtifact(run: PersistedRun, backend: ExeVmBackend, source?: TraceSource, primary?: boolean) {
Expand Down
24 changes: 17 additions & 7 deletions packages/app/src/trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,17 +41,26 @@ function parseCodex(value: any, sequence: number): TraceEvent[] {
return [];
}

function parseClaude(value: any, sequence: number): TraceEvent[] {
function parseClaude(value: any, sequence: number, tools: Map<string, string>): TraceEvent[] {
if (!value || typeof value !== "object") return [event(sequence, "warning", "Invalid Claude session record", value, {})];
const message = value.message ?? value;
if (value.type === "user" || message.role === "user") {
const toolResult = Array.isArray(message.content) && message.content.find((x: any) => x?.type === "tool_result");
return [event(sequence, toolResult ? "tool_result" : "user_message", toolResult ? "Tool result" : "User", contentText(toolResult?.content ?? message.content), value)];
const blocks = Array.isArray(message.content) ? message.content : [];
const results = blocks.filter((block: any) => block?.type === "tool_result");
if (results.length) return results.map((block: any, index: number) => ({
...event(sequence + index, "tool_result", tools.get(block.tool_use_id) ?? "Tool result", contentText(block.content), { ...value, id: `${value.uuid ?? sequence}:${index}`, parentId: block.tool_use_id }),
display: { toolUseId: block.tool_use_id, isError: Boolean(block.is_error) },
}));
return [event(sequence, "user_message", "User", contentText(message.content), value)];
}
if (value.type === "assistant" || message.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));
else if (block.type === "tool_use") entries.push({ ...event(sequence + entries.length, "tool_call", String(block.name ?? "Tool call"), block.input, { ...value, id: block.id }), display: { arguments: block.input ?? {} } });
else if (block.type === "tool_use") {
tools.set(block.id, String(block.name ?? "Tool call"));
entries.push({ ...event(sequence + entries.length, "tool_call", String(block.name ?? "Tool call"), block.input, { ...value, id: block.id }), display: { arguments: block.input ?? {} } });
}
else if (block.type === "text") entries.push(event(sequence + entries.length, "assistant_message", "Assistant", block.text, value));
}
return entries;
Expand All @@ -60,7 +69,7 @@ function parseClaude(value: any, sequence: number): TraceEvent[] {
}

/** Parses source JSONL into bounded, provider-neutral display events. */
export function parseTrace(provider: "codex" | "claude" | "pi", jsonl: string, sourceKind: TraceSource["kind"] = "native_session"): TraceEvent[] {
export function parseTrace(provider: "codex" | "claude" | "pi", jsonl: string, sourceKind: TraceSource["kind"] = "native_session", claudeTools = new Map<string, string>()): TraceEvent[] {
const events: TraceEvent[] = [];
for (const line of jsonl.split(/\r?\n/)) {
if (!line.trim()) continue;
Expand All @@ -73,7 +82,7 @@ export function parseTrace(provider: "codex" | "claude" | "pi", jsonl: string, s
events.push({ sequence: events.length + 1, id: record.id, type: record.type, title: clipped(record.title), preview: clipped(record.preview), ...(typeof record.parentId === "string" ? { parentId: record.parentId } : {}), ...(typeof record.role === "string" ? { role: record.role } : {}), ...(typeof record.occurredAt === "string" ? { occurredAt: record.occurredAt } : {}), display: record.display && typeof record.display === "object" && !Array.isArray(record.display) ? record.display : {} });
continue;
}
const parsed = provider === "codex" ? parseCodex(value, events.length + 1) : provider === "claude" ? parseClaude(value, events.length + 1) : parsePi(value, events.length + 1);
const parsed = provider === "codex" ? parseCodex(value, events.length + 1) : provider === "claude" ? parseClaude(value, events.length + 1, claudeTools) : parsePi(value, events.length + 1);
events.push(...parsed);
}
return events.map((item, index) => ({ ...item, sequence: index + 1 }));
Expand Down Expand Up @@ -112,10 +121,11 @@ export async function consumeTraceStream(provider: "codex" | "claude" | "pi", st
const reader = stream.getReader(), decoder = new TextDecoder();
let batch: TraceEvent[] = [], sequence = 0;
let pending = "";
const claudeTools = new Map<string, string>();
const flush = async () => { if (!batch.length) return; const ready = batch; batch = []; await consumeBatch(ready); };
const consume = async (line: string) => {
if (!line.trim()) return;
const parsed = parseTrace(provider, line, sourceKind);
const parsed = parseTrace(provider, line, sourceKind, claudeTools);
for (const item of parsed) { batch.push({ ...item, sequence: ++sequence }); if (batch.length >= batchSize) await flush(); }
};
for (;;) {
Expand Down
Loading
Loading