Skip to content
Closed
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
18 changes: 13 additions & 5 deletions docs/execution-trace-stream.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +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 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
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 @@ -27,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 Down
14 changes: 11 additions & 3 deletions packages/app/src/agent-driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,19 @@ 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,
},
};
}
}

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

export type CodexCalls = Map<string, string>;
const safe = (value: unknown, limit = 32768) => safeDiagnosticText(typeof value === "string" ? value : JSON.stringify(value ?? ""), limit);
const argumentsValue = (value: unknown): unknown => {
if (typeof value !== "string") return value ?? {};
try { return JSON.parse(value); } catch { return value; }
};

/** Raw exec events are self-contained snapshots; no tool state is needed across byte chunks. */
export function parseCodexExec(value: any, sequence: number): TraceEvent[] {
const make = (type: TraceEventType, title: unknown, preview: unknown, id?: string, parentId?: string): TraceEvent => ({
sequence, id: id ?? String(sequence), type, title: safe(title, 512), preview: safe(preview),
...(parentId ? { parentId } : {}), display: { source: "codex exec --json", eventType: safe(value?.type, 128) },
});
if (!value || typeof value !== "object") return [make("warning", "Invalid Codex event", "Expected a JSON object")];
if (value.type === "turn.completed") return [make("usage", "Token usage", value.usage)];
if (value.type === "error" || value.type === "turn.failed") return [make("error", "Codex error", value.message ?? value.error?.message ?? value.error)];
if (value.type === "thread.started" || value.type === "turn.started") return [make("metadata", value.type, value.thread_id ?? "")];
if (!["item.started", "item.updated", "item.completed"].includes(value.type)) return [make("metadata", "Unknown Codex event", { type: safe(value.type, 128) })];
const item = value.item;
if (!item || typeof item !== "object" || typeof item.id !== "string") return [make("warning", "Invalid Codex item", "Missing item identity")];
const id = safe(item.id, 512), parent = typeof item.parent_id === "string" ? safe(item.parent_id, 512) : undefined;
const completed = value.type === "item.completed";
const recordId = `${id}:${value.type}`;
const call = (title: unknown, args: unknown) => make("tool_call", title, argumentsValue(args), id, parent);
const result = (title: unknown, output: unknown) => make("tool_result", title, output, recordId, id);
switch (item.type) {
case "reasoning": return [make("reasoning", "Reasoning", item.text, recordId, parent)];
case "agent_message": return [make("assistant_message", "Assistant", item.text, recordId, parent)];
case "command_execution":
return completed ? [result(item.command ?? "Command result", { output: item.aggregated_output ?? "", exitCode: item.exit_code, status: item.status })]
: [call(item.command ?? "Command", { command: item.command })];
case "mcp_tool_call": {
const title = `${item.server ?? "MCP"}: ${item.tool ?? "Tool"}`;
return completed ? [result(title, item.error ?? item.result)] : [call(title, item.arguments)];
}
case "file_change":
return [make("file_change", "File changes", { changes: item.changes, status: item.status }, recordId, parent)];
case "web_search":
return completed ? [result("Web search", item.action ?? item.query)] : [call("Web search", item.action ?? { query: item.query })];
case "todo_list": return [make("metadata", "Plan", item.items, recordId, parent)];
case "error": return [make("error", "Codex error", item.message, recordId, parent)];
default: return [make("metadata", "Unknown Codex item", { type: safe(item.type, 128), status: safe(item.status, 128) }, recordId, parent)];
}
}

export function parseCodexNativeCall(value: any, sequence: number, calls: CodexCalls): TraceEvent[] | null {
const payload = value?.payload;
if (value?.type !== "response_item" || !payload) return null;
const kind = payload.type;
if (!["function_call", "custom_tool_call", "function_call_output", "custom_tool_call_output"].includes(kind)) return null;
const callId = safe(payload.call_id ?? payload.id ?? String(sequence), 512);
const output = kind.endsWith("_output");
const title = output ? calls.get(callId) ?? "Tool result" : safe(payload.name ?? "Tool call", 512);
if (!output) {
if (calls.size >= 4096) calls.delete(calls.keys().next().value!);
calls.set(callId, title);
}
const preview = safe(output ? payload.output : argumentsValue(payload.arguments ?? payload.input));
return [{ sequence, id: output ? `${callId}:result` : callId, ...(output ? { parentId: callId } : payload.parent_id ? { parentId: safe(payload.parent_id, 512) } : {}),
type: output ? "tool_result" : "tool_call", title, preview,
...(typeof value.timestamp === "string" && Number.isFinite(Date.parse(value.timestamp)) ? { occurredAt: value.timestamp } : {}),
display: { source: "codex native session", ...(!output ? { arguments: argumentsValue(preview) } : {}) } }];
}
8 changes: 6 additions & 2 deletions packages/app/src/exe-vm-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,16 +100,20 @@ export class ExeVmBackend implements ExecutionBackend {
throw new Error(`exe.dev VM creation failed (${created.status}): ${created.body.slice(0, 500)}`);
}

const prompt = base64(request.prompt), output = "/tmp/factorize.log", unit = vm;
const prompt = base64(request.prompt), output = request.traceSources?.primary.formatVersion === "codex-exec-jsonl" ? request.traceSources.primary.path : "/tmp/factorize.log", unit = vm;
const work = [
"set -eu",
"mkdir -p /home/exedev/workspace",
"cd /home/exedev/workspace",
...(request.traceSources?.primary.kind === "execution_stream" ? [`mkdir -p -- ${shellAtom(request.traceSources.primary.path.slice(0, request.traceSources.primary.path.lastIndexOf("/")) || "/")}`, `touch -- ${shellAtom(request.traceSources.primary.path)}`] : []),
`printf '%s' ${shellAtom(prompt)} | base64 -d > /tmp/factorize-prompt.md`,
`if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=file:/tmp/factorize-prompt.md --property=StandardOutput=append:${output} --property=StandardError=append:/tmp/factorize.stderr ${harnessCommand(request.harness)}; fi`,
`if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=file:/tmp/factorize-prompt.md --property=StandardOutput=${output === "/tmp/factorize.log" ? `append:${output}` : shellAtom(`append:${output}`)} --property=StandardError=append:/tmp/factorize.stderr ${harnessCommand(request.harness)}; fi`,
"echo started",
].join("; ");
if (request.traceSources?.primary.formatVersion === "codex-exec-jsonl") {
const version = await this.api(`ssh ${shellAtom(vm)} ${shellAtom("codex --version")}`).catch(() => null);
if (version?.ok && /^codex-cli [0-9][0-9A-Za-z.+-]*$/.test(version.body.trim())) request.traceSources.primary.cliVersion = version.body.trim();
}
let started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`);
const accepted = (result: BackendCommandResult) => result.ok && result.body.trim() === "started";
for (let attempt = 1; !accepted(started) && attempt < 5; attempt++) started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`);
Expand Down
9 changes: 8 additions & 1 deletion packages/app/src/harness-diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,14 @@ export interface ExecutionDiagnostics {

/** Redact before truncation so a cut cannot expose part of a recognized credential. */
export function safeDiagnosticText(value: string, limit = 2048): string {
const withoutAssignments = value.replace(/^.*["']?(?:[\w-]*(?:token|secret|password|passwd|api[_-]?key|authorization|cookie))["']?\s*[:=].*$/gim, "[REDACTED]");
// Scan assignment keys once per line; a greedy prefix plus nested key
// quantifiers made long, ordinary tool output quadratic to redact.
const withoutAssignments = value.split("\n").map(line => {
for (const match of line.matchAll(/\b([\w-]+)["']?\s*[:=]/g)) {
if (/(?:token|secret|password|passwd|api[_-]?key|authorization|cookie)/i.test(match[1])) return "[REDACTED]";
}
return line;
}).join("\n");
const safe = scrubSession(withoutAssignments)
.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*/gi, "[REDACTED]")
.replace(/\b[A-Z][A-Z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD)\s*=\s*[^\r\n]+/g, "[REDACTED]")
Expand Down
7 changes: 6 additions & 1 deletion packages/app/src/postgres/live-trace-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,12 @@ export class LiveTraceRepository {
start = index + 1;
}
}
const parsed = parseTrace(provider, new TextDecoder("utf-8", { fatal: true }).decode(complete), sourceKind);
const calls = new Map<string, string>();
if (provider === "codex" && sourceKind === "native_session") {
const previous = await client.query<{ id: string; title: string }>("SELECT id,title FROM app.run_trace_events WHERE tenant_id=$1 AND run_id=$2 AND event_type='tool_call' ORDER BY sequence DESC LIMIT 4096", [this.tenantId, runId]);
for (const item of [...previous.rows].reverse()) calls.set(item.id, item.title);
}
const parsed = parseTrace(provider, new TextDecoder("utf-8", { fatal: true }).decode(complete), sourceKind, Number(cursor.next_sequence), calls);
const nextSequence = Number(cursor.next_sequence), events = parsed.map((item, index) => ({ ...item, sequence: nextSequence + index }));
for (let offset = 0; offset < events.length; offset += 250) await this.insertBatch(client, runId, events.slice(offset, offset + 250));
const rollingHash = await sha256(`${cursor.rolling_hash}:${chunk.startOffset}:${endOffset}:${chunk.chunkSha256}`);
Expand Down
15 changes: 11 additions & 4 deletions packages/app/src/postgres/run-scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,15 +104,22 @@ export class RunScheduler {
}

private sources(run: PersistedRun): TraceSources {
// 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 } };
if (run.executionTarget.traceSources) return run.executionTarget.traceSources;
// Runs launched before a source declaration existed must keep their native
// trace even when the current driver now produces an execution stream.
return { primary: this.nativeSource(run) };
}

private nativeSource(run: PersistedRun): TraceSource {
const kind = run.executionTarget.agentKind as AgentKind;
const { traceSources: _sources, ...legacy } = agentDriver(kind).launch(run.id, {});
return driverTraceSources(kind, legacy).primary;
}

private async collectArtifact(run: PersistedRun, backend: ExeVmBackend, source?: TraceSource, primary?: boolean) {
if (!run.executionHandle) throw new Error("Execution handle is missing");
const sources = this.sources(run);
source ??= sources.nativeSession ?? (sources.primary.kind === "native_session" ? sources.primary : driverTraceSources(run.executionTarget.agentKind as AgentKind, agentDriver(run.executionTarget.agentKind as AgentKind).launch(run.id, {})).primary);
source ??= sources.nativeSession ?? (sources.primary.kind === "native_session" ? sources.primary : this.nativeSource(run));
primary ??= sources.primary.kind === "native_session";
const token = await issueArtifactUploadGrant({ tenantId: run.tenantId, runId: run.id, path: source.kind === "execution_stream" ? "trace/stream.jsonl" : "native/session.jsonl", contentType: source.mediaType, provider: source.provider, format: "jsonl", sourceKind: source.kind, sourcePath: source.path, formatVersion: source.formatVersion, cliVersion: source.cliVersion, harnessVersion: source.harnessVersion, primary, expiresAt: Date.now() + 10 * 60_000 }, this.env.SESSION_SIGNING_SECRET);
return backend.collectArtifact(run.executionHandle, { source, contentType: source.mediaType, uploadUrl: `${this.env.APP_ORIGIN}/internal/run-artifacts/${encodeURIComponent(token)}` });
Expand Down
4 changes: 2 additions & 2 deletions packages/app/src/trace-source.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { shellAtom } from "./exe";

/** A guest file, never a terminal log. Execution streams use Factorize JSONL v1. */
/** A guest file, never a terminal log. Execution streams use Factorize JSONL v1 or declared provider stdout JSONL. */
export interface TraceSource {
kind: "execution_stream" | "native_session";
path: string;
Expand All @@ -23,7 +23,7 @@ export function validateTraceSources(sources: TraceSources): void {
sourceCommand(source);
if (source.mediaType !== "application/x-ndjson") throw new Error("Trace sources must be JSONL");
if (!["execution_stream", "native_session"].includes(source.kind) || !["codex", "claude", "pi"].includes(source.provider)) throw new Error("Invalid trace source");
if (source.kind === "execution_stream" && source.formatVersion && source.formatVersion !== "1") throw new Error("Unsupported execution stream version");
if (source.kind === "execution_stream" && source.formatVersion && source.formatVersion !== "1" && !(source.provider === "codex" && source.formatVersion === "codex-exec-jsonl")) throw new Error("Unsupported execution stream version");
}
if (sources.primary.kind === "execution_stream" && ["/tmp/factorize.log", "/tmp/factorize.stderr", "/tmp/factorize-prompt.md"].includes(sources.primary.path)) throw new Error("Trace stream path is reserved for JSONL only");
if (sources.nativeSession) {
Expand Down
Loading
Loading