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
58 changes: 54 additions & 4 deletions docs/execution-trace-stream.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ 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 declares raw `codex exec --json` stdout as its primary stream with
`formatVersion: codex-exec-jsonl`; Claude declares the stream producer described below.
Pi keeps its published native session as primary; see
[Pi session contract](pi-session-contract.md).
Codex CLI version is probed in the guest at launch and persisted with the source
for run diagnostics and artifact provenance.

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

```json
{"version":1,"id":"event-1","type":"assistant_message","title":"Assistant","preview":"Hello","display":{}}
Expand All @@ -26,7 +29,13 @@ The backend tails the declared primary file in bounded byte chunks. PostgreSQL
commits offset, pending bytes, events and hash-chain receipt atomically. An
incomplete trailing line waits for a later chunk; terminal reconciliation ignores
an unterminated trailing line, preserving it in the exact artifact. Invalid
complete execution records reject the chunk/projection rather than create events.
complete normalized execution records reject the chunk/projection. Codex raw
JSONL instead emits a bounded warning for malformed JSON and bounded metadata for
unknown future event/item types, then continues. Known Codex items project
reasoning, assistant text, command/MCP/web tool calls and results, file changes,
plans, lifecycle, errors and usage. Tool results reference the item call ID and
use the command or server/tool from the completion snapshot for their title.
Previews are redacted before truncation; unknown payloads are never echoed.
Retries use the same generation, offset and hash. Rename rotation starts a new
projection generation; observable same-inode truncation does likewise. Producers
must use rename rotation, never truncate and regrow between polls: an unobserved
Expand All @@ -45,3 +54,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 .
22 changes: 17 additions & 5 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 @@ -26,21 +27,32 @@ export interface AgentDriver {

class CodexDriver implements AgentDriver {
readonly kind = "codex" as const;
launch(_runId: string, config: AgentConfiguration): AgentLaunchSpec {
const args = ["exec", "--dangerously-bypass-approvals-and-sandbox", "--color", "never", "-c", "model_provider=exe-llm", "-c", 'model_providers.exe-llm.name="exe-llm"', "-c", 'model_providers.exe-llm.base_url="https://llm.int.exe.xyz/v1"'];
launch(runId: string, config: AgentConfiguration): AgentLaunchSpec {
const args = ["exec", "--json", "--dangerously-bypass-approvals-and-sandbox", "--color", "never", "-c", "model_provider=exe-llm", "-c", 'model_providers.exe-llm.name="exe-llm"', "-c", 'model_providers.exe-llm.base_url="https://llm.int.exe.xyz/v1"'];
if (config.model?.trim()) args.push("--model", config.model.trim());
if (config.effort?.trim()) args.push("-c", `model_reasoning_effort=${config.effort.trim()}`);
return { executable: "codex", args, env: {}, stdin: "prompt", artifacts: { roots: ["${CODEX_HOME:-$HOME/.codex}/sessions"], fileNameIncludes: "rollout-", discoverCommand: `find "\${CODEX_HOME:-$HOME/.codex}/sessions" -type f -name 'rollout-*.jsonl' -printf '%T@ %p\\n' | sort -nr | head -1 | cut -d' ' -f2-` } };
const nativeSession = { kind: "native_session" as const, path: "${CODEX_HOME:-$HOME/.codex}/sessions", mediaType: "application/x-ndjson" as const, provider: this.kind, discoverCommand: `find "\${CODEX_HOME:-$HOME/.codex}/sessions" -type f -name 'rollout-*.jsonl' -printf '%T@ %p\\n' | sort -nr | head -1 | cut -d' ' -f2-` };
return {
executable: "codex", args, env: {}, stdin: "prompt",
artifacts: { roots: [nativeSession.path], fileNameIncludes: "rollout-", discoverCommand: nativeSession.discoverCommand },
traceSources: {
primary: { kind: "execution_stream", path: `/tmp/factorize-artifacts/${runId}/codex-exec.jsonl`, mediaType: "application/x-ndjson", provider: this.kind, formatVersion: "codex-exec-jsonl" },
nativeSession,
},
};
}
}

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)
`;
Loading
Loading