diff --git a/docs/cli/run.md b/docs/cli/run.md index e37edf757f..1a17173ba6 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -134,7 +134,7 @@ depend on the process cwd. | `total_cost_usd` | Total inference cost in USD, as reported by the runtime (raw floating-point aggregate across all iterations; no fullsend-side pricing-table fallback). See [Cost data contract](../guides/infrastructure/distributed-tracing.md#cost-data-contract) | | `num_turns` | Number of conversation turns | | `iterations` | Number of agent iterations run; an iteration killed at the budget is not retried (see [Budget and deadline](#budget-and-deadline)) | -| `per_model_usage` | Per-model breakdown, present only when a runtime reports one (today: `pi` with the `Agent` tool enabled, and `claude` when Claude Code's result carries `modelUsage`). See below | +| `per_model_usage` | Per-model breakdown, present only when a runtime reports one (today: `pi` with the `Agent` tool enabled, `claude` when Claude Code's result carries `modelUsage`, and `codex` for an agent with registered sub-agent roles or a spawn in its stream). See below | | `fallback_from` | Models the run moved off, in the order tried, before `model` took over: models the Vertex project did not serve, and on `claude` any model Claude Code's own `--fallback-model` handling left, for example on overload (`claude` and `pi`; see [Claude Code](../runtimes/claude.md#models)). Absent when the first model ran | | `fallback_reasons` | Why the run moved off each `fallback_from` entry, at the same index: `not_served` when the runner retried because the Vertex project does not serve the model, `claude_code:` when Claude Code switched models itself (its `model_fallback` trigger, for example `claude_code:last_resort`). Absent when the first model ran | @@ -142,9 +142,12 @@ depend on the process cwd. A map from model spec to `{requests, input_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens, cost_usd}`. -On `pi` the key is the pi model spec (`anthropic-vertex/claude-opus-4-6`). It exists because a pi -sub-agent is a separate `pi` process whose tokens never appear in the parent's stream, so without it -`total_cost_usd` would grow with no way to attribute it. +On `pi` the key is the pi model spec (`anthropic-vertex/claude-opus-4-6`); on `codex` it is the +model id codex ran (`gpt-5.6-luna`, or the id after `gateway/`). It exists because a sub-agent's tokens never appear in the parent's +stream: a pi sub-agent is a separate `pi` process, and a codex sub-agent is a separate thread whose +usage codex records only in that thread's rollout. Without it `total_cost_usd` would grow with no +way to attribute it on pi, and the child tokens the runner adds to the totals on codex could not be +attributed to a model. On `claude` the key is the model id Claude Code reports (`claude-haiku-4-5@20251001`), with one entry per model that ran, sub-agents included. The token totals come from the result event's @@ -155,7 +158,8 @@ records its last value rather than adding each result's. `requests` has no count Code's result and stays `0`. A result without `modelUsage` keeps the parent-only `usage` totals and records no breakdown, and an iteration that ends without a result (cancelled at the budget) contributes to the totals but not to the breakdown, so the invariant below can fall short in those -two cases. The rest of this section describes the `pi` breakdown. +two cases. The rest of this section describes the `pi` breakdown; `codex` follows it, with the +differences in the last bullet. - **What folds.** Tokens and cost, from both the parent and every child, summed across retry iterations. Each iteration contributes one `requests` for the parent plus one per sub-agent call, @@ -169,9 +173,16 @@ two cases. The rest of this section describes the `pi` breakdown. - **What stays parent-only.** `num_turns` and `tool_calls` are read from the parent's stream and are not broken down or added to per model — a child's turns and tool calls are recorded in its own session transcript (`transcripts/-sub-*.jsonl`) instead. -- A model spec of `unknown` is a usage record that carries no model spec at all; its cost is - bucketed there rather than dropped. A dispatch rejected *before* a model was resolved writes - no record, so it never reaches the breakdown. +- A model spec of `unknown` is a pi usage record, or a codex child rollout, that carries no model + at all; its usage is bucketed there rather than dropped. A dispatch rejected *before* a model was + resolved writes no record, so it never reaches the breakdown. +- **On codex.** `cost_usd` is `0` in every entry: codex reports no dollar cost, so compare tokens + there. `requests` counts one per child rollout that reported usage (codex writes one per thread); + `wait`, `send_input` and `close_agent` calls add none, and a child that errored before its first + response has no usage and adds no `requests`. A codex iteration that exits non-zero, after a + failed or interrupted turn, a cancel or a timeout, still counts what its children had recorded + when the runner read them: codex writes a child's usage as each response completes. After a + cancel or a timeout the run warns that usage recorded after the read is not counted. ## Budget and deadline diff --git a/internal/runtime/codex_integrity.go b/internal/runtime/codex_integrity.go index eec64b7488..7b8b3616b9 100644 --- a/internal/runtime/codex_integrity.go +++ b/internal/runtime/codex_integrity.go @@ -78,6 +78,10 @@ type codexRunnerHeldDigestSet struct { RoleFiles map[string]string } +// delegating reports whether Bootstrap registered native sub-agent roles for +// this run. It reads the runner-held record, never the manifest. +func (d codexRunnerHeldDigestSet) delegating() bool { return len(d.RoleFiles) > 0 } + // codexEnvPair is one runner-owned environment assignment. type codexEnvPair struct { Key string diff --git a/internal/runtime/codex_run.go b/internal/runtime/codex_run.go index 79137224e2..b58ba0bac0 100644 --- a/internal/runtime/codex_run.go +++ b/internal/runtime/codex_run.go @@ -608,6 +608,9 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri } } + childIDs := &codexChildIDs{} + reader = io.TeeReader(reader, childIDs) + handler := params.OnEvent if handler == nil { renderer := NewEventRenderer(printer) @@ -655,6 +658,24 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri r.ConfigDir()) } + // The fold runs whatever the exit code: codex writes a child's usage as + // each response completes, and the parent's entry keeps per_model_usage + // summing to the totals across a retry. A read failure is a warning. + if digests.delegating() || len(childIDs.IDs) > 0 { + n, ferr := r.foldCodexChildUsage(params.SandboxName, childIDs.IDs, metrics) + if ferr != nil { + printer.StepWarn("Sub-agent usage not fully counted: " + redactSummary(sanitizeOutput(ferr.Error()))) + } + if n > 0 { + printer.StepInfo(fmt.Sprintf("%d sub-agent thread(s) folded into the run metrics", n)) + } + // At the budget or on a cancel OpenShell kills nothing, so codex's + // children can record more after the read. + if len(childIDs.IDs) > 0 && (ctx.Err() != nil || exitCode == 124 || exitCode == -1) { + printer.StepWarn("Sub-agent usage may be undercounted: codex was stopped, and its children can record more after the read") + } + } + if exitCode == 0 && lastResult != nil && lastResult.IsError { msg := lastResult.ErrorMessage if msg == "" { diff --git a/internal/runtime/codex_subagents.go b/internal/runtime/codex_subagents.go new file mode 100644 index 0000000000..0e933cd217 --- /dev/null +++ b/internal/runtime/codex_subagents.go @@ -0,0 +1,293 @@ +package runtime + +import ( + "bufio" + "bytes" + "encoding/json" + "fmt" + "regexp" + "slices" + "strings" + "time" + + "github.com/fullsend-ai/fullsend/internal/sandbox" +) + +// Native child accounting for the Codex runtime. A child's tokens never reach +// the parent's `exec --json` stream; codex records them only in the child's +// rollout under $CODEX_HOME/sessions/ (rollout--.jsonl). +// After codex exits, Run reads each child's model and usage from it and folds +// them into RunMetrics. Child reasoning goes to the run total only, as on pi. + +// codexChildUsageMarker starts the line printed before each child's rollout +// lines. A rollout line that imitates it can only misattribute its own child. +const codexChildUsageMarker = "fullsend-child" + +// codexChildUnreadableMarker starts the line printed for a child whose +// rollout fails test -r, that a failed search did not find, or that has more +// than one rollout. +const codexChildUnreadableMarker = "fullsend-unreadable" + +// codexChildUsageMaxBytes bounds the read: the sessions directory is +// agent-writable. A real read is a few kilobytes. +const codexChildUsageMaxBytes = 1 << 20 + +// codexChildUsageMaxTokens is far above any real counter. A child past it is +// skipped with a warning, so planted counters cannot wrap the run's sums. +const codexChildUsageMaxTokens = 1 << 40 + +// codexChildUsageThreadID is a codex thread id. Ids go into a shell command, +// so nothing else is accepted. +var codexChildUsageThreadID = regexp.MustCompile(`^[0-9a-f-]{36}$`) + +// codexChildUsage is what one child's rollout reported. +type codexChildUsage struct { + ID string + // Model is from the last turn_context that decodes, the child's own (a + // fork copies the parent's ahead of it); "" when there is none. + Model string + // Usage is the thread total of the last token_usage_record that decodes. + Usage codexUsage + // HasUsage is false when the rollout has no record; such a child adds + // nothing, not even a request. + HasUsage bool + // Unreadable marks a rollout that failed test -r, a failed search, or an + // id with more than one rollout. + Unreadable bool + // BadLine marks a line that did not decode (torn, cut or planted). + BadLine bool +} + +// codexChildUsageReadCommand renders the in-sandbox command that prints, per +// child, a marker line, the rollout's last two turn_context and last two +// token_usage_record lines: the parser keeps the last that decodes, so a torn +// last line falls back to the one before it. The record, not token_count: codex zeroes token_count's +// counters when a request overflows the context window. A rollout it cannot +// read, or that a failed search cannot find, prints the unreadable marker, +// and so does an id with more than one rollout (codex writes one; copies are +// planted), whose copies all go uncounted; +// one a clean search misses prints nothing; a path outside sessionsDir is +// skipped; head -c bounds the output. +func codexChildUsageReadCommand(sessionsDir string, ids []string) (string, error) { + ids = slices.Clone(ids) + slices.Sort(ids) + ids = slices.Compact(ids) + quoted := make([]string, 0, len(ids)) + for _, id := range ids { + if !codexChildUsageThreadID.MatchString(id) { + return "", fmt.Errorf("child thread id %q is not a codex thread id", id) + } + quoted = append(quoted, shellQuote(id)) + } + return fmt.Sprintf( + `for id in %s; do files=$(command -p find %s -type f -name "rollout-*-$id.jsonl" 2>/dev/null) || [ -n "$files" ] || printf '%%s %%s\n' %s "$id"; if [ "$(printf '%%s\n' "$files" | command -p grep -c .)" -gt 1 ]; then printf '%%s %%s\n' %s "$id"; continue; fi; printf '%%s\n' "$files" | while IFS= read -r f; do case $f in %s/*) ;; *) continue ;; esac; if [ ! -r "$f" ]; then printf '%%s %%s\n' %s "$id"; continue; fi; printf '%%s %%s\n' %s "$id"; command -p grep -a -e '"type":"turn_context"' -- "$f" 2>/dev/null | command -p tail -n 2; command -p grep -a -e '"type":"token_usage_record"' -- "$f" 2>/dev/null | command -p tail -n 2; done; done | command -p head -c %d`, + strings.Join(quoted, " "), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(codexChildUnreadableMarker), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(codexChildUsageMarker), codexChildUsageMaxBytes), nil +} + +// parseCodexChildUsage decodes the read command's output. Lines before the +// first marker, and lines that do not decode (a cut, planted text, a counter +// past the int range), are skipped. +func parseCodexChildUsage(data []byte) []codexChildUsage { + var out []codexChildUsage + marker := []byte(codexChildUsageMarker + " ") + unreadable := []byte(codexChildUnreadableMarker + " ") + scanner := bufio.NewScanner(bytes.NewReader(data)) + scanner.Buffer(make([]byte, 0, 64*1024), maxTranscriptLineSize) + for scanner.Scan() { + line := bytes.TrimSpace(scanner.Bytes()) + if len(line) == 0 { + continue + } + if id, ok := bytes.CutPrefix(line, marker); ok { + out = append(out, codexChildUsage{ID: string(id)}) + continue + } + if id, ok := bytes.CutPrefix(line, unreadable); ok { + out = append(out, codexChildUsage{ID: string(id), Unreadable: true}) + continue + } + if len(out) == 0 { + continue + } + var env struct { + Type string `json:"type"` + Payload struct { + Model string `json:"model"` + Thread codexUsage `json:"thread_token_usage"` + } `json:"payload"` + } + cur := &out[len(out)-1] + if json.Unmarshal(line, &env) != nil { + cur.BadLine = true + continue + } + switch { + case env.Type == "turn_context": + cur.Model = strings.TrimSpace(env.Payload.Model) + case env.Type == "token_usage_record": + cur.Usage = env.Payload.Thread + cur.HasUsage = true + } + } + return out +} + +// codexChildIDs collects the thread ids of completed spawn_agent items from +// a tee of the `exec --json` stream: the parser's events carry no thread id. +// A final line without a newline is not scanned; in codex it is the terminal +// event. +type codexChildIDs struct { + IDs []string + line []byte + overlong bool +} + +func (c *codexChildIDs) Write(p []byte) (int, error) { + rest := p + for { + i := bytes.IndexByte(rest, '\n') + if i < 0 { + c.take(rest) + return len(p), nil + } + c.take(rest[:i]) + if !c.overlong { + c.scan(c.line) + } + c.line, c.overlong = c.line[:0], false + rest = rest[i+1:] + } +} + +// take appends to the pending line and drops a line that reaches +// streamBufSize, as parseCodexStream does. +func (c *codexChildIDs) take(b []byte) { + if c.overlong || len(c.line)+len(b) >= streamBufSize { + c.overlong = true + c.line = c.line[:0] + return + } + c.line = append(c.line, b...) +} + +func (c *codexChildIDs) scan(line []byte) { + // Pre-filter: few lines name the tool. + if !bytes.Contains(line, []byte("spawn_agent")) { + return + } + var evt struct { + Type string `json:"type"` + Item struct { + codexCollabToolCallItem + Type string `json:"type"` + } `json:"item"` + } + if json.Unmarshal(line, &evt) != nil || evt.Type != "item.completed" || evt.Item.Type != "collab_tool_call" || + evt.Item.Tool != "spawn_agent" || evt.Item.Status != "completed" { + return + } + c.IDs = append(c.IDs, evt.Item.ReceiverThreadIDs...) +} + +// foldCodexChildUsage adds the parent's entry to m.PerModelUsage, always, so +// the breakdown sums to the totals when iterations are summed. It then folds +// each child's usage into the totals and the breakdown, one request per +// rollout, and returns how many it folded. The error lists what was not +// counted; the caller warns and keeps the run. No sandbox command runs +// without child ids. A child with no model goes under piSubagentUnknownModel, +// as on pi. The figures are agent-written, so counters are floored at zero +// and a child past codexChildUsageMaxTokens is skipped. +func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, m *RunMetrics) (folded int, err error) { + per := m.PerModelUsage + if per == nil { + per = make(map[string]ModelUsage, len(childIDs)+1) + } + add := func(key string, u ModelUsage) { + entry := per[key] + entry.Add(u) + per[key] = entry + } + parent := m.Model + if parent == "" { + parent = piSubagentUnknownModel + } + add(parent, ModelUsage{ + Requests: 1, + InputTokens: m.InputTokens, + OutputTokens: m.OutputTokens, + CacheCreationInputTokens: m.CacheCreationInputTokens, + CacheReadInputTokens: m.CacheReadInputTokens, + CostUSD: m.TotalCostUSD, + }) + m.PerModelUsage = per + if len(childIDs) == 0 { + return 0, nil + } + + cmd, err := codexChildUsageReadCommand(r.codexSessionsDir(), childIDs) + if err != nil { + return 0, err + } + // A read that fails still folds whatever stdout came back. + var lost []string + stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, cmd, 10*time.Second) + if err != nil { + lost = append(lost, err.Error()) + } else if exitCode != 0 { + lost = append(lost, fmt.Sprintf("exited %d: %s", exitCode, strings.TrimSpace(sanitizeOutput(stderr)))) + } + unreadable, overMaxTokens, badLines := 0, 0, 0 + for _, child := range parseCodexChildUsage([]byte(stdout)) { + if child.Unreadable { + unreadable++ + } + if child.BadLine { + badLines++ + } + if !child.HasUsage { + continue + } + // counters() floors only its subtractions; the raw fields are + // floored here. + c := child.Usage.counters() + reasoning, cacheWrite, cacheRead := nonNegative(c.Reasoning), nonNegative(c.CacheWrite), nonNegative(c.CacheRead) + if max(c.Input, c.Output, reasoning, cacheWrite, cacheRead) > codexChildUsageMaxTokens { + overMaxTokens++ + continue + } + // The model is agent-written and becomes a metrics.json key. + key := redactSummary(child.Model) + if key == "" { + key = piSubagentUnknownModel + } + add(key, ModelUsage{ + Requests: 1, + InputTokens: c.Input, + OutputTokens: c.Output, + CacheCreationInputTokens: cacheWrite, + CacheReadInputTokens: cacheRead, + }) + m.InputTokens += c.Input + m.OutputTokens += c.Output + m.ReasoningTokens += reasoning + m.CacheCreationInputTokens += cacheWrite + m.CacheReadInputTokens += cacheRead + folded++ + } + if unreadable > 0 { + lost = append(lost, fmt.Sprintf("%d child rollout(s) could not be read", unreadable)) + } + if badLines > 0 { + lost = append(lost, fmt.Sprintf("%d child rollout(s) had a line that did not decode", badLines)) + } + if overMaxTokens > 0 { + lost = append(lost, fmt.Sprintf("%d child(ren) with a counter past %d not counted", overMaxTokens, codexChildUsageMaxTokens)) + } + if len(stdout) >= codexChildUsageMaxBytes { + lost = append(lost, fmt.Sprintf("cut at %d bytes; children at and past the cut are not fully counted", codexChildUsageMaxBytes)) + } + if len(lost) > 0 { + return folded, fmt.Errorf("reading the child rollouts: %s", strings.Join(lost, "; ")) + } + return folded, nil +} diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go new file mode 100644 index 0000000000..6d9e80b0a1 --- /dev/null +++ b/internal/runtime/codex_subagents_test.go @@ -0,0 +1,839 @@ +package runtime + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/ui" +) + +// delegating reads the runner-held role set only, never the manifest. +func TestCodexRunnerHeldDigestSet_Delegating(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + roles map[string]string + want bool + }{ + {name: "nil map: no role registered", roles: nil, want: false}, + {name: "empty map: no role registered", roles: map[string]string{}, want: false}, + {name: "one role registered", roles: map[string]string{"default": "d0d0"}, want: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + d := codexRunnerHeldDigestSet{ConfigTOML: "cfg", RoleFiles: tt.roles} + assert.Equal(t, tt.want, d.delegating(), "delegating follows the runner-held role set only") + }) + } +} + +// Thread ids of the fixtures (testdata/codex/README.md, "Child rollout +// fixtures") and of the spawn items in collab_spawn.ndjson. +const ( + codexChildSameModelID = "01a06300-0000-7000-8000-0000000000a1" + codexChildOtherModelID = "01a06300-0000-7000-8000-0000000000a2" + codexChildFailedID = "01a06300-0000-7000-8000-0000000000a3" + codexChildNoModelID = "01a06300-0000-7000-8000-0000000000a4" + codexChildForkedID = "01a06300-0000-7000-8000-0000000000a5" + codexChildFailedSpawnID = "01a06300-0000-7000-8000-0000000000a9" +) + +// codexChildFixtures maps each child id to its rollout fixture. +var codexChildFixtures = map[string]string{ + codexChildSameModelID: "child_usage_same_model.jsonl", + codexChildOtherModelID: "child_usage_other_model.jsonl", + codexChildFailedID: "child_usage_failed.jsonl", + codexChildNoModelID: "child_usage_no_model.jsonl", + codexChildForkedID: "child_usage_forked.jsonl", +} + +// writeCodexChildRollouts lays the child fixtures out as codex would under a +// sessions directory (YYYY/MM/DD/rollout--.jsonl) and +// returns that directory. +func writeCodexChildRollouts(t *testing.T, ids ...string) string { + t.Helper() + sessions := filepath.Join(t.TempDir(), "sessions") + day := filepath.Join(sessions, "2026", "09", "29") + require.NoError(t, os.MkdirAll(day, 0o755)) + for _, id := range ids { + name := "rollout-2026-09-29T15-46-38-" + id + ".jsonl" + require.NoError(t, os.WriteFile(filepath.Join(day, name), readCodexFixture(t, codexChildFixtures[id]), 0o644)) + } + return sessions +} + +// runCodexChildUsageRead runs the read command under /bin/sh, so a quoting +// slip fails the test, and parses what it printed. +func runCodexChildUsageRead(t *testing.T, sessions string, ids []string) []codexChildUsage { + t.Helper() + cmd, err := codexChildUsageReadCommand(sessions, ids) + require.NoError(t, err) + out, err := exec.Command("/bin/sh", "-c", cmd).Output() + require.NoError(t, err) + return parseCodexChildUsage(out) +} + +func TestCodexChildUsageReadCommand_RejectsBadIDs(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + id string + }{ + {name: "path segment", id: "../etc/passwd"}, + {name: "upper case", id: "01A06300-0000-7000-8000-0000000000A1"}, + {name: "too short", id: "01a06300-0000-7000-8000-00000000a1"}, + {name: "shell text", id: "'; rm -rf /; '"}, + {name: "empty", id: ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + _, err := codexChildUsageReadCommand("/sandbox/codex-config/sessions", []string{codexChildSameModelID, tt.id}) + require.Error(t, err) + assert.Contains(t, err.Error(), "is not a codex thread id") + }) + } +} + +func TestCodexChildUsageReadCommand_Executes(t *testing.T) { + t.Parallel() + + sessions := writeCodexChildRollouts(t, codexChildSameModelID, codexChildOtherModelID, codexChildFailedID) + // Unsorted, one id twice, one id with no rollout. + ids := []string{codexChildFailedID, codexChildSameModelID, codexChildSameModelID, codexChildOtherModelID, "01a06300-0000-7000-8000-0000000000ff"} + + cmd, err := codexChildUsageReadCommand(sessions, ids) + require.NoError(t, err) + assert.True(t, strings.HasSuffix(cmd, fmt.Sprintf("| command -p head -c %d", codexChildUsageMaxBytes)), + "the read is bounded inside the sandbox, not after the bytes arrived") + assert.Contains(t, cmd, `-type f -name "rollout-*-$id.jsonl"`, + "only regular rollout files, found by thread id; never a cat of the directory") + assert.Equal(t, 1, strings.Count(cmd, shellQuote(codexChildSameModelID)), "a repeated id is read once") + + got := runCodexChildUsageRead(t, sessions, ids) + require.Len(t, got, 3, "an id with no rollout yields no record; a repeated id one; sorted by id") + assert.Equal(t, codexChildUsage{ + ID: codexChildSameModelID, Model: "gpt-5.6-luna", HasUsage: true, + Usage: codexUsage{InputTokens: 7381, CacheWriteInputTokens: 7378, OutputTokens: 8}, + }, got[0], "the thread total of the record, not the sum of the two token_counts") + assert.Equal(t, codexChildUsage{ + ID: codexChildOtherModelID, Model: "gpt-5.6-terra", HasUsage: true, + Usage: codexUsage{InputTokens: 4000, CachedInputTokens: 1000, CacheWriteInputTokens: 2000, OutputTokens: 300, ReasoningOutputTokens: 100}, + }, got[1]) + assert.Equal(t, codexChildUsage{ID: codexChildFailedID, Model: "gpt-5.6-nonexistent"}, got[2], + "a child that errored before its first response has a model and no usage") +} + +// The read takes the last record's thread total; a token_count is zeroed +// after a context-window overflow and empty before the first response. +func TestCodexChildUsageReadCommand_ReadsTheThreadTotal(t *testing.T) { + t.Parallel() + + usage := func(in, out, total int) string { + return fmt.Sprintf(`{"input_tokens":%d,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":%d,"reasoning_output_tokens":0,"total_tokens":%d}`, in, out, total) + } + count := func(info string) string { + return `{"type":"event_msg","payload":{"type":"token_count","info":` + info + `}}` + } + record := func(in, out int) string { + return `{"type":"token_usage_record","payload":{"thread_token_usage":` + usage(in, out, in+out) + `}}` + } + rollout := strings.Join([]string{ + `{"type":"turn_context","payload":{"model":"gpt-5.6-luna"}}`, + count(`null`), + record(3000, 4), + count(`{"total_token_usage":` + usage(3000, 4, 3004) + `}`), + record(90000, 20), + count(`{"total_token_usage":` + usage(0, 0, 258400) + `,"last_token_usage":` + usage(0, 0, 168380) + `,"model_context_window":258400}`), + }, "\n") + "\n" + sessions := writeCodexChildRollouts(t) + require.NoError(t, os.WriteFile(filepath.Join(sessions, "2026", "09", "29", "rollout-2026-09-29T15-46-38-"+codexChildSameModelID+".jsonl"), []byte(rollout), 0o644)) + + got := runCodexChildUsageRead(t, sessions, []string{codexChildSameModelID}) + require.Len(t, got, 1) + assert.Equal(t, codexChildUsage{ + ID: codexChildSameModelID, Model: "gpt-5.6-luna", HasUsage: true, + Usage: codexUsage{InputTokens: 90000, OutputTokens: 20}, + }, got[0], "the last record's thread total, not the zeroed token_count after it") +} + +// A codex killed mid-write leaves a torn last line; the record before it +// still counts. +func TestCodexChildUsageReadCommand_FallsBackPastATornRecord(t *testing.T) { + t.Parallel() + + rollout := `{"type":"turn_context","payload":{"model":"gpt-5.6-luna"}}` + "\n" + + `{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tokens":30,"output_tokens":3}}}` + "\n" + + `{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tok` + sessions := writeCodexChildRollouts(t) + require.NoError(t, os.WriteFile(filepath.Join(sessions, "2026", "09", "29", "rollout-2026-09-29T15-46-38-"+codexChildSameModelID+".jsonl"), []byte(rollout), 0o644)) + + got := runCodexChildUsageRead(t, sessions, []string{codexChildSameModelID}) + require.Len(t, got, 1) + assert.Equal(t, codexChildUsage{ID: codexChildSameModelID, Model: "gpt-5.6-luna", HasUsage: true, Usage: codexUsage{InputTokens: 30, OutputTokens: 3}, BadLine: true}, got[0]) +} + +// A forked child's rollout starts with the parent's turn_context lines; the +// read names the child by its own, the last. +func TestCodexChildUsageReadCommand_NamesAForkedChildByItsOwnTurn(t *testing.T) { + t.Parallel() + + got := runCodexChildUsageRead(t, writeCodexChildRollouts(t, codexChildForkedID), []string{codexChildForkedID}) + require.Len(t, got, 1) + assert.Equal(t, codexChildUsage{ + ID: codexChildForkedID, Model: "gpt-5.6-terra", HasUsage: true, + Usage: codexUsage{InputTokens: 600, OutputTokens: 40, ReasoningOutputTokens: 10}, + }, got[0], "the child's model and record, not the parent's inherited turn_context or token_count") +} + +// A planted file name with a newline splits into several paths; only those +// under the sessions directory are opened. +func TestCodexChildUsageReadCommand_SkipsPathsOutsideTheSessionsDirectory(t *testing.T) { + t.Parallel() + + sessions := writeCodexChildRollouts(t) + day := filepath.Join(sessions, "2026", "09", "29") + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-a\nb-"+codexChildSameModelID+".jsonl"), []byte("{}\n"), 0o644)) + cwd := t.TempDir() + record := `{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tokens":99,"output_tokens":9}}}` + "\n" + require.NoError(t, os.WriteFile(filepath.Join(cwd, "b-"+codexChildSameModelID+".jsonl"), []byte(record), 0o644)) + + cmd, err := codexChildUsageReadCommand(sessions, []string{codexChildSameModelID}) + require.NoError(t, err) + sh := exec.Command("/bin/sh", "-c", cmd) + sh.Dir = cwd + out, err := sh.Output() + require.NoError(t, err) + got := parseCodexChildUsage(out) + require.Len(t, got, 1) + assert.Equal(t, codexChildUsage{ID: codexChildSameModelID, Unreadable: true}, got[0], + "the fragment under the sessions directory is not a file, so it is reported; the one in the working directory is skipped") +} + +func TestParseCodexChildUsage(t *testing.T) { + t.Parallel() + + turn := func(model string) string { + return `{"type":"turn_context","payload":{"model":"` + model + `"}}` + } + record := func(in, out int) string { + return fmt.Sprintf(`{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tokens":%d,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":%d,"reasoning_output_tokens":0,"total_tokens":%d}}}`, in, out, in+out) + } + data := strings.Join([]string{ + record(999, 999), // before any marker: nobody's line + codexChildUsageMarker + " " + codexChildSameModelID, + turn("gpt-5.6-terra"), + turn("gpt-5.6-sol"), + record(10, 1), + "not json", + record(20, 2), + "", + codexChildUsageMarker + " " + codexChildOtherModelID, + record(5, 5), + codexChildUsageMarker + " " + codexChildFailedID, + turn("gpt-5.6-terra"), + `{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tokens":7,"cach`, + }, "\n") + + got := parseCodexChildUsage([]byte(data)) + require.Len(t, got, 3) + assert.Equal(t, codexChildUsage{ID: codexChildSameModelID, Model: "gpt-5.6-sol", HasUsage: true, Usage: codexUsage{InputTokens: 20, OutputTokens: 2}, BadLine: true}, + got[0], "the last turn_context names the model, the last record wins, a malformed line is skipped and flagged") + assert.Equal(t, codexChildUsage{ID: codexChildOtherModelID, HasUsage: true, Usage: codexUsage{InputTokens: 5, OutputTokens: 5}}, + got[1], "no turn_context: the model stays empty and the fold buckets it") + assert.Equal(t, codexChildUsage{ID: codexChildFailedID, Model: "gpt-5.6-terra", BadLine: true}, + got[2], "a truncated last line (the head -c cut) is not usage") + assert.Empty(t, parseCodexChildUsage(nil)) +} + +func TestCodexChildIDs_CollectsCompletedSpawns(t *testing.T) { + t.Parallel() + + stream := readCodexFixture(t, "collab_spawn.ndjson") + want := []string{codexChildSameModelID, codexChildOtherModelID, codexChildFailedID} + + whole := &codexChildIDs{} + n, err := whole.Write(stream) + require.NoError(t, err) + assert.Equal(t, len(stream), n, "an io.Writer reports every byte consumed or the TeeReader fails") + assert.Equal(t, want, whole.IDs, + "the three completed spawns in stream order; the failed spawn's receiver is not a child; wait and close items name no new thread") + assert.NotContains(t, whole.IDs, codexChildFailedSpawnID) + + chunked := &codexChildIDs{} + for i := 0; i < len(stream); i += 7 { + _, err := chunked.Write(stream[i:min(i+7, len(stream))]) + require.NoError(t, err) + } + assert.Equal(t, want, chunked.IDs, "lines are reassembled across Write calls, as a TeeReader delivers them") +} + +func TestCodexChildIDs_SkipsOverlongLine(t *testing.T) { + t.Parallel() + + spawn := `{"type":"item.completed","item":{"id":"item_1","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["` + codexChildSameModelID + `"],"prompt":null,"agents_states":{},"status":"completed"}}` + // A completed spawn padded past the bound. + overlong := `{"type":"item.completed","item":{"id":"item_0","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["` + codexChildOtherModelID + `"],"prompt":"` + strings.Repeat("a", streamBufSize) + `","agents_states":{},"status":"completed"}}` + + // A line of exactly the bound is dropped too, as parseCodexStream drops it. + head := `{"type":"item.completed","item":{"id":"item_2","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["` + codexChildFailedID + `"],"prompt":"` + tail := `","agents_states":{},"status":"completed"}}` + exact := head + strings.Repeat("a", streamBufSize-len(head)-len(tail)) + tail + require.Len(t, exact, streamBufSize) + + c := &codexChildIDs{} + _, err := c.Write([]byte(overlong + "\n" + exact + "\n" + spawn + "\n")) + require.NoError(t, err) + assert.Equal(t, []string{codexChildSameModelID}, c.IDs, + "a line at or past the parser's own bound is dropped whole, as parseCodexStream drops it, even when it names a child; the next line is still scanned") + assert.Empty(t, c.line, "nothing pending after a newline") +} + +// A failed child shows only as failed wait and close items and never fails +// the run. +func TestParseCodexStream_FailedCollabItem(t *testing.T) { + t.Parallel() + + events, threadID := collectCodexEvents(t, "collab_spawn.ndjson") + assert.Equal(t, "01a06300-0000-7000-8000-000000000050", threadID) + + tools := codexEventsOfType[ToolUseEvent](events) + require.Len(t, tools, 9, "four spawns, two waits, three closes") + for _, tool := range tools { + assert.Equal(t, "Agent", tool.Name) + } + assert.Equal(t, "spawn_agent (1 agent(s))", tools[0].Summary) + assert.Equal(t, "spawn_agent (1 agent(s)) (failed)", tools[3].Summary, "a failed spawn is reported, not hidden") + assert.Equal(t, "wait (2 agent(s))", tools[4].Summary) + assert.Equal(t, "wait (1 agent(s)) (failed)", tools[5].Summary, "the errored child's wait carries status failed") + assert.Equal(t, "close_agent (1 agent(s)) (failed)", tools[8].Summary) + + result := codexOnlyResult(t, events) + assert.False(t, result.IsError, "a failed child never sets the run verdict") + assert.Equal(t, 1, result.NumTurns) + assert.Equal(t, 15, result.InputTokens) + assert.Equal(t, 1140, result.OutputTokens) + assert.Equal(t, 291, result.ReasoningTokens) + assert.Equal(t, 13618, result.CacheCreationInputTokens) + assert.Equal(t, 40590, result.CacheReadInputTokens) +} + +// fakeOpenshellCodexChildren answers the manifest cat from storeDir, streams +// streamFixture for the launch, and runs the read command under sh against +// sessionsDir. FULLSEND_TEST_CHILD_READ_FAIL=1 makes the read exit 1 (with +// FULLSEND_TEST_CHILD_READ_STDERR on stderr), =after makes it time out after +// printing; FULLSEND_TEST_CODEX_EXIT sets the launch's exit status (killed: +// SIGKILL, as the budget's context kill ends it). +func fakeOpenshellCodexChildren(t *testing.T, logPath, storeDir, streamFixture, sessionsDir string) { + t.Helper() + binDir := t.TempDir() + script := `#!/bin/sh +echo "$@" >> '` + logPath + `' +if [ "$2" = "exec" ]; then + for last; do :; done + case "$last" in + cat\ *) f=$(printf '%s' "${last#cat }" | tr -d "'" | tr '/' '_'); cat '` + storeDir + `'/"$f"; exit $? ;; + *"exec --json"*) cat '` + streamFixture + `'; [ "${FULLSEND_TEST_CODEX_EXIT:-}" = killed ] && kill -9 $$; exit "${FULLSEND_TEST_CODEX_EXIT:-0}" ;; + *` + codexChildUsageMarker + `*) + if [ "${FULLSEND_TEST_CHILD_READ_FAIL:-}" = 1 ]; then echo "fake openshell: refusing the rollout read${FULLSEND_TEST_CHILD_READ_STDERR:+ $FULLSEND_TEST_CHILD_READ_STDERR}" >&2; exit 1; fi + sh -c "$(printf '%s' "$last" | sed 's#` + CodexRuntime{}.codexSessionsDir() + `#` + sessionsDir + `#g')"; rc=$? + if [ "${FULLSEND_TEST_CHILD_READ_FAIL:-}" = after ]; then exit 124; fi + exit $rc ;; + esac + exit 0 +fi +exit 0 +` + require.NoError(t, os.WriteFile(filepath.Join(binDir, "openshell"), []byte(script), 0o755)) + t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +// codexParentMetrics is the parent's iteration in collab_spawn.ndjson. +func codexParentMetrics(model string) *RunMetrics { + return &RunMetrics{Model: model, NumTurns: 1, InputTokens: 15, OutputTokens: 1140, ReasoningTokens: 291, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590} +} + +// codexTokenTotals is the run-level view the tests compare; RunMetrics +// itself carries an atomic and must not be copied. +type codexTokenTotals struct{ input, output, reasoning, cacheWrite, cacheRead int } + +func codexTotalsOf(m *RunMetrics) codexTokenTotals { + return codexTokenTotals{m.InputTokens, m.OutputTokens, m.ReasoningTokens, m.CacheCreationInputTokens, m.CacheReadInputTokens} +} + +// assertCodexUsageSumsToTotals checks that per_model_usage sums to the run +// totals (docs/cli/run.md); reasoning is run-level only. +func assertCodexUsageSumsToTotals(t *testing.T, m *RunMetrics) { + t.Helper() + var sum ModelUsage + for _, u := range m.PerModelUsage { + sum.Add(u) + } + assert.Equal(t, m.InputTokens, sum.InputTokens, "input") + assert.Equal(t, m.OutputTokens, sum.OutputTokens, "output") + assert.Equal(t, m.CacheCreationInputTokens, sum.CacheCreationInputTokens, "cache_creation") + assert.Equal(t, m.CacheReadInputTokens, sum.CacheReadInputTokens, "cache_read") + assert.Equal(t, m.TotalCostUSD, sum.CostUSD, "cost (0 on codex)") +} + +// Per fixture: parent 15/1140/291/13618/40590, luna child 3/8/0/7378/0, +// terra child 1000/200/100/2000/1000, no-model child 50/5/0/0/0 under +// unknown, failed child nothing. +func TestFoldCodexChildUsage(t *testing.T) { + r := CodexRuntime{} + parentOnly := ModelUsage{Requests: 1, InputTokens: 15, OutputTokens: 1140, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590} + lunaBoth := ModelUsage{Requests: 2, InputTokens: 18, OutputTokens: 1148, CacheCreationInputTokens: 20996, CacheReadInputTokens: 40590} + terra := ModelUsage{Requests: 1, InputTokens: 1000, OutputTokens: 200, CacheCreationInputTokens: 2000, CacheReadInputTokens: 1000} + + for name, tc := range map[string]struct { + ids []string + folded int + want map[string]ModelUsage + totals codexTokenTotals + }{ + "same model aggregates into one entry": { + ids: []string{codexChildSameModelID}, folded: 1, + want: map[string]ModelUsage{"gpt-5.6-luna": lunaBoth}, + totals: codexTokenTotals{18, 1148, 291, 20996, 40590}, + }, + "different model gets its own entry": { + ids: []string{codexChildOtherModelID}, folded: 1, + want: map[string]ModelUsage{"gpt-5.6-luna": parentOnly, "gpt-5.6-terra": terra}, + totals: codexTokenTotals{1015, 1340, 391, 15618, 41590}, + }, + "failed child contributes nothing, not even a request": { + ids: []string{codexChildFailedID}, folded: 0, + want: map[string]ModelUsage{"gpt-5.6-luna": parentOnly}, + totals: codexTokenTotals{15, 1140, 291, 13618, 40590}, + }, + "a child with usage but no model buckets under unknown": { + ids: []string{codexChildNoModelID}, folded: 1, + want: map[string]ModelUsage{"gpt-5.6-luna": parentOnly, piSubagentUnknownModel: {Requests: 1, InputTokens: 50, OutputTokens: 5}}, + totals: codexTokenTotals{65, 1145, 291, 13618, 40590}, + }, + "all three": { + ids: []string{codexChildSameModelID, codexChildOtherModelID, codexChildFailedID}, folded: 2, + want: map[string]ModelUsage{"gpt-5.6-luna": lunaBoth, "gpt-5.6-terra": terra}, + totals: codexTokenTotals{1018, 1348, 391, 22996, 41590}, + }, + } { + t.Run(name, func(t *testing.T) { + sessions := writeCodexChildRollouts(t, codexChildSameModelID, codexChildOtherModelID, codexChildFailedID, codexChildNoModelID) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + + m := codexParentMetrics("gpt-5.6-luna") + n, err := r.foldCodexChildUsage("sb", tc.ids, m) + require.NoError(t, err) + assert.Equal(t, tc.folded, n, "one per child thread with usage") + assert.Equal(t, tc.want, m.PerModelUsage) + assert.Equal(t, tc.totals, codexTotalsOf(m), "child reasoning is in the run total only") + assert.Zero(t, m.TotalCostUSD, "codex reports no cost; nothing is invented") + assertCodexUsageSumsToTotals(t, m) + }) + } +} + +// A planted negative counter cannot lower the run's figures. +func TestFoldCodexChildUsage_ClampsNegativeCounters(t *testing.T) { + sessions := writeCodexChildRollouts(t) + rollout := `{"type":"turn_context","payload":{"model":"gpt-5.6-luna"}}` + "\n" + + `{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tokens":10,"cached_input_tokens":-5000,"cache_write_input_tokens":-7000,"output_tokens":20,"reasoning_output_tokens":-900,"total_tokens":30}}}` + "\n" + require.NoError(t, os.WriteFile(filepath.Join(sessions, "2026", "09", "29", "rollout-2026-09-29T15-46-38-"+codexChildSameModelID+".jsonl"), []byte(rollout), 0o644)) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + + m := codexParentMetrics("gpt-5.6-luna") + n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID}, m) + require.NoError(t, err) + assert.Equal(t, 1, n) + // Input 10+5000+7000 and output 20+900: inflation is accepted, as on pi. + assert.Equal(t, codexTokenTotals{15 + 12010, 1140 + 920, 291, 13618, 40590}, codexTotalsOf(m)) + assert.Equal(t, ModelUsage{Requests: 2, InputTokens: 15 + 12010, OutputTokens: 1140 + 920, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590}, + m.PerModelUsage["gpt-5.6-luna"]) + assertCodexUsageSumsToTotals(t, m) +} + +// A read cut at the bound is a warning; the children before the cut stay +// folded. +func TestFoldCodexChildUsage_CutReadIsAWarning(t *testing.T) { + sessions := writeCodexChildRollouts(t, codexChildSameModelID) + day := filepath.Join(sessions, "2026", "09", "29") + big := `{"type":"turn_context","payload":{"model":"` + strings.Repeat("x", 600<<10) + `"}}` + "\n" + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-2026-09-29T15-46-38-"+codexChildOtherModelID+".jsonl"), []byte(big), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-2026-09-29T15-46-38-"+codexChildFailedID+".jsonl"), append(readCodexFixture(t, "child_usage_other_model.jsonl"), big...), 0o644)) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + + m := codexParentMetrics("gpt-5.6-luna") + n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID, codexChildOtherModelID, codexChildFailedID}, m) + require.Error(t, err) + assert.Contains(t, err.Error(), "cut at") + assert.Contains(t, err.Error(), "had a line that did not decode", "the cut line is reported too") + assert.Equal(t, 1, n, "the child before the cut") + assert.NotContains(t, m.PerModelUsage, "gpt-5.6-terra", "the child past the cut") + assert.Equal(t, 2, m.PerModelUsage["gpt-5.6-luna"].Requests) + assertCodexUsageSumsToTotals(t, m) +} + +// An unreadable rollout, or one a failed search misses, is a warning; +// readable children stay folded. +func TestFoldCodexChildUsage_UnreadableRolloutIsAWarning(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("file modes do not stop root") + } + tests := []struct { + name string + lock func(t *testing.T, sessions string) string + }{ + {name: "rollout file", lock: func(t *testing.T, sessions string) string { + return filepath.Join(sessions, "2026", "09", "29", "rollout-2026-09-29T15-46-38-"+codexChildOtherModelID+".jsonl") + }}, + {name: "sessions subdirectory", lock: func(t *testing.T, sessions string) string { + dir := filepath.Join(sessions, "2026", "09", "30") + require.NoError(t, os.MkdirAll(dir, 0o755)) + name := "rollout-2026-09-29T15-46-38-" + codexChildOtherModelID + ".jsonl" + require.NoError(t, os.Rename(filepath.Join(sessions, "2026", "09", "29", name), filepath.Join(dir, name))) + return dir + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sessions := writeCodexChildRollouts(t, codexChildSameModelID, codexChildOtherModelID) + locked := tt.lock(t, sessions) + require.NoError(t, os.Chmod(locked, 0)) + t.Cleanup(func() { _ = os.Chmod(locked, 0o755) }) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + + m := codexParentMetrics("gpt-5.6-luna") + n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID, codexChildOtherModelID}, m) + require.Error(t, err) + assert.Contains(t, err.Error(), "1 child rollout(s) could not be read", "a failed search that still found a rollout is not a warning for it") + assert.Equal(t, 1, n, "the readable child is still folded") + assert.Equal(t, 2, m.PerModelUsage["gpt-5.6-luna"].Requests) + assertCodexUsageSumsToTotals(t, m) + }) + } +} + +// Codex writes one rollout per thread, so a copy is planted: the id is +// reported and none of its copies count, while other children still do. +func TestFoldCodexChildUsage_DuplicateRolloutsCountNothing(t *testing.T) { + sessions := writeCodexChildRollouts(t, codexChildSameModelID, codexChildOtherModelID) + day := filepath.Join(sessions, "2026", "09", "29") + data, err := os.ReadFile(filepath.Join(day, "rollout-2026-09-29T15-46-38-"+codexChildOtherModelID+".jsonl")) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-copy-"+codexChildOtherModelID+".jsonl"), data, 0o644)) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + + m := codexParentMetrics("gpt-5.6-luna") + n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID, codexChildOtherModelID}, m) + require.Error(t, err) + assert.Contains(t, err.Error(), "1 child rollout(s) could not be read") + assert.Equal(t, 1, n, "the luna child only") + assert.NotContains(t, m.PerModelUsage, "gpt-5.6-terra", "neither copy counts") + assertCodexUsageSumsToTotals(t, m) +} + +// A credential planted as the child's model is redacted from the key. +func TestFoldCodexChildUsage_RedactsThePlantedModel(t *testing.T) { + token := "ghp_" + strings.Repeat("A", 36) + sessions := writeCodexChildRollouts(t) + rollout := `{"type":"turn_context","payload":{"model":"` + token + `"}}` + "\n" + + `{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tokens":10,"output_tokens":2}}}` + "\n" + require.NoError(t, os.WriteFile(filepath.Join(sessions, "2026", "09", "29", "rollout-2026-09-29T15-46-38-"+codexChildSameModelID+".jsonl"), []byte(rollout), 0o644)) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + + m := codexParentMetrics("gpt-5.6-luna") + n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID}, m) + require.NoError(t, err) + assert.Equal(t, 1, n) + assert.Len(t, m.PerModelUsage, 2) + for spec := range m.PerModelUsage { + assert.NotContains(t, spec, token) + } + assertCodexUsageSumsToTotals(t, m) +} + +// A child with any counter past codexChildUsageMaxTokens is skipped with a +// warning. +func TestFoldCodexChildUsage_SkipsCountersOverMaxTokens(t *testing.T) { + for _, field := range []string{"input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens"} { + t.Run(field, func(t *testing.T) { + sessions := writeCodexChildRollouts(t) + day := filepath.Join(sessions, "2026", "09", "29") + for id, value := range map[string]string{codexChildSameModelID: "9223372036854775807", codexChildOtherModelID: "9223372036854775799"} { + rollout := `{"type":"token_usage_record","payload":{"thread_token_usage":{"` + field + `":` + value + `}}}` + "\n" + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-a-"+id+".jsonl"), []byte(rollout), 0o644)) + } + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + + m := codexParentMetrics("gpt-5.6-luna") + n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID, codexChildOtherModelID}, m) + require.Error(t, err, "a skipped child is a warning, as a cut or unreadable read is") + assert.Contains(t, err.Error(), "2 child(ren) with a counter past") + assert.Zero(t, n) + assert.Equal(t, codexTokenTotals{15, 1140, 291, 13618, 40590}, codexTotalsOf(m)) + assertCodexUsageSumsToTotals(t, m) + }) + } +} + +// No child id, no sandbox command (PATH has no openshell); the parent's +// entry still lands, under unknown when it has no model. +func TestFoldCodexChildUsage_NoChildrenNoSandbox(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + + for _, model := range []string{"gpt-5.6-luna", ""} { + m := codexParentMetrics(model) + n, err := CodexRuntime{}.foldCodexChildUsage("sb", nil, m) + require.NoError(t, err, "no id, no sandbox command") + assert.Zero(t, n) + key := model + if key == "" { + key = piSubagentUnknownModel + } + assert.Equal(t, map[string]ModelUsage{key: {Requests: 1, InputTokens: 15, OutputTokens: 1140, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590}}, m.PerModelUsage) + assert.Equal(t, codexTokenTotals{15, 1140, 291, 13618, 40590}, codexTotalsOf(m), "the parent's numbers are not double-counted into the totals") + assertCodexUsageSumsToTotals(t, m) + } +} + +func TestFoldCodexChildUsage_ReadFailuresKeepTheParentEntry(t *testing.T) { + r := CodexRuntime{} + parentOnly := map[string]ModelUsage{"gpt-5.6-luna": {Requests: 1, InputTokens: 15, OutputTokens: 1140, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590}} + + t.Run("a bad id never reaches the shell", func(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + m := codexParentMetrics("gpt-5.6-luna") + n, err := r.foldCodexChildUsage("sb", []string{codexChildSameModelID, "'; rm -rf /; '"}, m) + require.Error(t, err) + assert.Contains(t, err.Error(), "is not a codex thread id") + assert.Zero(t, n) + assert.Equal(t, parentOnly, m.PerModelUsage) + }) + + t.Run("openshell cannot start", func(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + m := codexParentMetrics("gpt-5.6-luna") + _, err := r.foldCodexChildUsage("sb", []string{codexChildSameModelID}, m) + require.Error(t, err) + assert.Contains(t, err.Error(), "reading the child rollouts") + assert.Equal(t, parentOnly, m.PerModelUsage) + assert.Equal(t, codexTokenTotals{15, 1140, 291, 13618, 40590}, codexTotalsOf(m), "totals untouched") + }) + + t.Run("a timed-out read folds the stdout that came back", func(t *testing.T) { + sessions := writeCodexChildRollouts(t, codexChildSameModelID) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + t.Setenv("FULLSEND_TEST_CHILD_READ_FAIL", "after") + m := codexParentMetrics("gpt-5.6-luna") + n, err := r.foldCodexChildUsage("sb", []string{codexChildSameModelID}, m) + require.Error(t, err) + assert.Contains(t, err.Error(), "timed out") + assert.Equal(t, 1, n) + assert.Equal(t, 2, m.PerModelUsage["gpt-5.6-luna"].Requests) + assertCodexUsageSumsToTotals(t, m) + }) + + t.Run("the read command exits non-zero", func(t *testing.T) { + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", t.TempDir()) + t.Setenv("FULLSEND_TEST_CHILD_READ_FAIL", "1") + m := codexParentMetrics("gpt-5.6-luna") + _, err := r.foldCodexChildUsage("sb", []string{codexChildSameModelID}, m) + require.Error(t, err) + assert.Contains(t, err.Error(), "exited 1") + assert.Contains(t, err.Error(), "refusing the rollout read", "stderr is in the message") + assert.Equal(t, parentOnly, m.PerModelUsage) + assertCodexUsageSumsToTotals(t, m) + }) +} + +// sumCodexIterations sums iterations as internal/cli aggregateRunMetrics does. +func sumCodexIterations(ms ...*RunMetrics) *RunMetrics { + sum := &RunMetrics{PerModelUsage: map[string]ModelUsage{}} + for _, m := range ms { + sum.InputTokens += m.InputTokens + sum.OutputTokens += m.OutputTokens + sum.ReasoningTokens += m.ReasoningTokens + sum.CacheCreationInputTokens += m.CacheCreationInputTokens + sum.CacheReadInputTokens += m.CacheReadInputTokens + sum.TotalCostUSD += m.TotalCostUSD + for spec, u := range m.PerModelUsage { + entry := sum.PerModelUsage[spec] + entry.Add(u) + sum.PerModelUsage[spec] = entry + } + } + return sum +} + +func TestFoldCodexChildUsage_TwoIterationsSumToTotals(t *testing.T) { + sessions := writeCodexChildRollouts(t, codexChildSameModelID, codexChildOtherModelID) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + r := CodexRuntime{} + + first := codexParentMetrics("gpt-5.6-luna") + n, err := r.foldCodexChildUsage("sb", []string{codexChildSameModelID, codexChildOtherModelID}, first) + require.NoError(t, err) + assert.Equal(t, 2, n) + + // The retry dispatched nothing; its parent entry still lands. + second := &RunMetrics{Model: "gpt-5.6-luna", NumTurns: 1, InputTokens: 100, OutputTokens: 50, ReasoningTokens: 7, CacheCreationInputTokens: 20, CacheReadInputTokens: 30} + n, err = r.foldCodexChildUsage("sb", nil, second) + require.NoError(t, err) + assert.Zero(t, n) + + sum := sumCodexIterations(first, second) + assert.Equal(t, map[string]ModelUsage{ + "gpt-5.6-luna": {Requests: 3, InputTokens: 118, OutputTokens: 1198, CacheCreationInputTokens: 21016, CacheReadInputTokens: 40620}, + "gpt-5.6-terra": {Requests: 1, InputTokens: 1000, OutputTokens: 200, CacheCreationInputTokens: 2000, CacheReadInputTokens: 1000}, + }, sum.PerModelUsage, "two parent iterations and one luna child under luna; the terra child alone under terra") + assert.Equal(t, codexTokenTotals{1118, 1398, 398, 23016, 41620}, codexTotalsOf(sum)) + assertCodexUsageSumsToTotals(t, sum) +} + +// runCodexWithChildren runs Run against the fake with the rollouts of the +// three children the stream spawns; delegating sets RoleFiles on the +// runner-held digests. It returns the metrics, exit code, output and argv log. +func runCodexWithChildren(t *testing.T, streamFixture string, delegating bool) (*RunMetrics, int, string, string) { + t.Helper() + logPath := filepath.Join(t.TempDir(), "openshell.log") + storeDir := t.TempDir() + r := CodexRuntime{} + seedCodexManifest(t, storeDir, r, nil) + if delegating { + d, ok := lookupRunnerHeldDigests("sb") + require.True(t, ok) + d.RoleFiles = map[string]string{"default": "d0d0", "explore": "e0e0"} + recordRunnerHeldDigests("sb", d) + } + sessions := writeCodexChildRollouts(t, codexChildSameModelID, codexChildOtherModelID, codexChildFailedID) + fakeOpenshellCodexChildren(t, logPath, storeDir, filepath.Join("testdata", "codex", streamFixture), sessions) + + var out bytes.Buffer + metrics := &RunMetrics{} + exit, err := r.Run(context.Background(), RunParams{ + SandboxName: "sb", + RepoDir: "/sandbox/workspace/repo", + Model: "openai/gpt-5.6-luna", + Timeout: time.Minute, + }, ui.New(&out), time.Now(), metrics) + require.NoError(t, err) + return metrics, exit, out.String(), readFileString(t, logPath) +} + +// A spawn in the stream alone (no RoleFiles) triggers the read. +func TestCodexRun_FoldsChildUsage(t *testing.T) { + metrics, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", false) + + assert.Equal(t, 0, exit) + assert.Equal(t, "gpt-5.6-luna", metrics.Model) + assert.Equal(t, codexTokenTotals{1018, 1348, 391, 22996, 41590}, codexTotalsOf(metrics), + "parent (15/1140/291/13618/40590) plus the luna child (3/8/0/7378/0) plus the terra child (1000/200/100/2000/1000); the failed child nothing") + assert.Equal(t, map[string]ModelUsage{ + "gpt-5.6-luna": {Requests: 2, InputTokens: 18, OutputTokens: 1148, CacheCreationInputTokens: 20996, CacheReadInputTokens: 40590}, + "gpt-5.6-terra": {Requests: 1, InputTokens: 1000, OutputTokens: 200, CacheCreationInputTokens: 2000, CacheReadInputTokens: 1000}, + }, metrics.PerModelUsage) + assertCodexUsageSumsToTotals(t, metrics) + assert.Zero(t, metrics.TotalCostUSD) + assert.Equal(t, 1, metrics.NumTurns, "turns stay parent-only") + assert.Contains(t, out, "2 sub-agent thread(s) folded into the run metrics") + assert.Equal(t, 1, strings.Count(log, codexChildUsageMarker), "one read command, after the run") + assert.Contains(t, log, shellQuote(codexChildFailedID), "the failed child's rollout is read too; it is its content that contributes nothing") + assert.NotContains(t, log, codexChildFailedSpawnID, "the failed spawn's receiver is never looked up") +} + +// A delegating agent that spawned nothing gets the parent's entry and no +// sandbox command. +func TestCodexRun_DelegatingWithoutSpawnHasParentEntry(t *testing.T) { + metrics, exit, _, log := runCodexWithChildren(t, "basic_run.ndjson", true) + + assert.Equal(t, 0, exit) + assert.Equal(t, map[string]ModelUsage{ + "gpt-5.6-luna": {Requests: 1, InputTokens: 12, OutputTokens: 284, CacheCreationInputTokens: 11087, CacheReadInputTokens: 32508}, + }, metrics.PerModelUsage, "the numbers TestApplyCodexMetrics pins for basic_run.ndjson") + assertCodexUsageSumsToTotals(t, metrics) + assert.NotContains(t, log, codexChildUsageMarker, "no id, no sandbox command") +} + +// A non-delegating agent with no spawn writes the same metrics.json as before. +func TestCodexRun_NoSpawnNoBreakdown(t *testing.T) { + metrics, exit, _, log := runCodexWithChildren(t, "basic_run.ndjson", false) + + assert.Equal(t, 0, exit) + assert.Nil(t, metrics.PerModelUsage) + data, err := json.Marshal(metrics) + require.NoError(t, err) + assert.NotContains(t, string(data), "per_model_usage", "omitempty keeps the key out") + assert.NotContains(t, log, codexChildUsageMarker) +} + +// A failed read is a warning; the iteration keeps its exit code and the +// parent's entry. +func TestCodexRun_ChildReadFailureIsAWarning(t *testing.T) { + token := "ghp_" + strings.Repeat("B", 36) + t.Setenv("FULLSEND_TEST_CHILD_READ_FAIL", "1") + t.Setenv("FULLSEND_TEST_CHILD_READ_STDERR", token) + metrics, exit, out, _ := runCodexWithChildren(t, "collab_spawn.ndjson", false) + + assert.Equal(t, 0, exit, "losing the children's tokens must not fail an iteration that succeeded") + assert.Contains(t, out, "! Sub-agent usage not fully counted: reading the child rollouts: exited 1: fake openshell: refusing the rollout read") + assert.NotContains(t, out, token, "the warning goes through the shared secret redactor") + assert.NotContains(t, out, "folded into the run metrics") + assert.Equal(t, codexTokenTotals{15, 1140, 291, 13618, 40590}, codexTotalsOf(metrics), "the parent's tokens only") + assert.Equal(t, map[string]ModelUsage{ + "gpt-5.6-luna": {Requests: 1, InputTokens: 15, OutputTokens: 1140, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590}, + }, metrics.PerModelUsage) + assertCodexUsageSumsToTotals(t, metrics) +} + +// A non-zero codex exit still reads the children; with an exit-0 retry the +// breakdown still sums to the totals. +func TestCodexRun_NonZeroExitStillReadsTheChildren(t *testing.T) { + t.Setenv("FULLSEND_TEST_CODEX_EXIT", "137") + failed, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", true) + + assert.Equal(t, 137, exit) + assert.Equal(t, map[string]ModelUsage{ + "gpt-5.6-luna": {Requests: 2, InputTokens: 18, OutputTokens: 1148, CacheCreationInputTokens: 20996, CacheReadInputTokens: 40590}, + "gpt-5.6-terra": {Requests: 1, InputTokens: 1000, OutputTokens: 200, CacheCreationInputTokens: 2000, CacheReadInputTokens: 1000}, + }, failed.PerModelUsage, "the parent's entry and the children it spawned") + assert.Equal(t, codexTokenTotals{1018, 1348, 391, 22996, 41590}, codexTotalsOf(failed)) + assert.Equal(t, 1, strings.Count(log, codexChildUsageMarker), "one read command, after the run") + assert.Contains(t, out, "2 sub-agent thread(s) folded into the run metrics") + assertCodexUsageSumsToTotals(t, failed) + + t.Setenv("FULLSEND_TEST_CODEX_EXIT", "0") + retry, exit, _, _ := runCodexWithChildren(t, "collab_spawn.ndjson", true) + require.Equal(t, 0, exit) + assertCodexUsageSumsToTotals(t, sumCodexIterations(failed, retry)) + assert.NotContains(t, out, "may be undercounted", "codex exited on its own; its children were done") +} + +// A codex stopped at the budget (the context kill, -1, or openshell's own +// timeout, 124) may still be running; the run says the children's later +// usage is not counted. +func TestCodexRun_BudgetStopWarnsOfLaterChildUsage(t *testing.T) { + for exitEnv, want := range map[string]int{"killed": -1, "124": 124} { + t.Run(exitEnv, func(t *testing.T) { + t.Setenv("FULLSEND_TEST_CODEX_EXIT", exitEnv) + _, exit, out, _ := runCodexWithChildren(t, "collab_spawn.ndjson", false) + + assert.Equal(t, want, exit) + assert.Contains(t, out, "2 sub-agent thread(s) folded into the run metrics") + assert.Contains(t, out, "! Sub-agent usage may be undercounted: codex was stopped") + }) + } +} diff --git a/internal/runtime/testdata/codex/README.md b/internal/runtime/testdata/codex/README.md index c694a18987..109f02247e 100644 --- a/internal/runtime/testdata/codex/README.md +++ b/internal/runtime/testdata/codex/README.md @@ -26,6 +26,24 @@ ARG exists run `CODEX_VERSION=0.152.1 ./regen.sh`. | `truncated.ndjson` | Killed mid-write — the last line stops mid-token and there is no terminal event. (The repo's `end-of-file-fixer` hook keeps a trailing newline after it; the line is still unparseable, which is what the fixture tests.) | | `unknown_types.ndjson` | An unknown top-level event type and an unknown item type: skipped, the run still completes. | | `second_turn_unfinished.ndjson` | A completed turn followed by a second `turn.started` that never finishes: the run is incomplete, not the first turn's success. | +| `collab_spawn.ndjson` | Three completed `spawn_agent` items, one **failed** one whose receiver is not a child, failed `wait` and `close_agent` items for the errored child inside a completed turn, and the parent usage of the 2026-09-29 paid probe. A hook-denied spawn emits no item; the failed one is hand-authored to pin the status filter. | + +## Child rollout fixtures (`child_usage_*.jsonl`) + +Codex **rollouts** (`$CODEX_HOME/sessions/**/rollout-*.jsonl`) for `foldCodexChildUsage`, not +`exec --json` streams, modelled on the 0.157.0 paid probe of 2026-09-29, with synthetic ids. The fold reads each rollout's last `turn_context` (`payload.model`) and last +`token_usage_record` (`payload.thread_token_usage`). + +| Fixture | Covers | +|---|---| +| `child_usage_same_model.jsonl` | A child on the parent's model, `gpt-5.6-luna`, with two cumulative `token_count` lines (3000 then 7381 input) and the `token_usage_record` of its second response, whose thread total (7381) is the child's whole usage. | +| `child_usage_other_model.jsonl` | A child on `gpt-5.6-terra`, every normalized counter non-zero. | +| `child_usage_failed.jsonl` | A child whose model the provider rejected (404): `turn_context` names the model, `task_complete` carries `error`, and there is no `token_usage_record`, so it contributes nothing. | +| `child_usage_no_model.jsonl` | A child with a `token_usage_record` and no `turn_context`: its usage is bucketed under `unknown`. | +| `child_usage_forked.jsonl` | A forked child (hand-authored from codex 0.159.3's fork rules): the parent's `turn_context` (`gpt-5.6-luna`) and `token_count` copied ahead of the child's own `turn_context` (`gpt-5.6-terra`) and `token_usage_record`; its usage lands under `gpt-5.6-terra`. | + +The tests lay the rollouts out under a temporary sessions tree as +`2026/09/29/rollout-2026-09-29T15-46-38-.jsonl`, the name codex gives a rollout. ## Event structs diff --git a/internal/runtime/testdata/codex/child_usage_failed.jsonl b/internal/runtime/testdata/codex/child_usage_failed.jsonl new file mode 100644 index 0000000000..9a53c2738c --- /dev/null +++ b/internal/runtime/testdata/codex/child_usage_failed.jsonl @@ -0,0 +1,5 @@ +{"timestamp":"2026-09-29T19:46:40.162Z","ordinal":0,"type":"session_meta","payload":{"session_id":"01a06300-0000-7000-8000-000000000050","id":"01a06300-0000-7000-8000-0000000000a3","parent_thread_id":"01a06300-0000-7000-8000-000000000050","timestamp":"2026-09-29T19:46:40.136Z","cwd":"/sandbox/workspace/repo","originator":"codex_exec","cli_version":"0.157.0","source":{"subagent":{"thread_spawn":{"parent_thread_id":"01a06300-0000-7000-8000-000000000050","depth":1,"agent_path":null,"agent_nickname":"Mendel","agent_role":"challenger"}}},"thread_source":"subagent","agent_nickname":"Mendel","agent_role":"challenger","model_provider":"openai","base_instructions":"(trimmed)","history_mode":"paginated","multi_agent_version":"v1"}} +{"timestamp":"2026-09-29T19:46:40.162Z","ordinal":1,"type":"event_msg","payload":{"type":"task_started","turn_id":"01a06300-0000-7000-8000-0000000000b3","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","started_at":1790711200,"model_context_window":258400,"collaboration_mode_kind":"default"}} +{"timestamp":"2026-09-29T19:46:40.786Z","ordinal":2,"type":"turn_context","payload":{"turn_id":"01a06300-0000-7000-8000-0000000000b3","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","cwd":"/sandbox/workspace/repo","approval_policy":"never","sandbox_policy":{"type":"danger-full-access"},"model":"gpt-5.6-nonexistent","multi_agent_version":"v1","effort":"medium","summary":"auto"}} +{"timestamp":"2026-09-29T19:46:40.795Z","ordinal":3,"type":"event_msg","payload":{"type":"item_completed","thread_id":"01a06300-0000-7000-8000-0000000000a3","turn_id":"01a06300-0000-7000-8000-0000000000b3","item":{"type":"UserMessage","id":"01a06300-0000-7000-8000-0000000000c3","content":[{"type":"text","text":"Challenge the findings.","text_elements":[]}]},"started_at_ms":1790711200795,"completed_at_ms":1790711200795}} +{"timestamp":"2026-09-29T19:47:27.725Z","ordinal":4,"type":"event_msg","payload":{"type":"task_complete","turn_id":"01a06300-0000-7000-8000-0000000000b3","last_agent_message":null,"error":{"message":"unexpected status 404 Not Found: The model `gpt-5.6-nonexistent` does not exist or you do not have access to it., url: https://api.openai.com/v1/responses","codex_error_info":"other"},"started_at":1790711200,"completed_at":1790711247,"duration_ms":47562}} diff --git a/internal/runtime/testdata/codex/child_usage_forked.jsonl b/internal/runtime/testdata/codex/child_usage_forked.jsonl new file mode 100644 index 0000000000..71222884ee --- /dev/null +++ b/internal/runtime/testdata/codex/child_usage_forked.jsonl @@ -0,0 +1,6 @@ +{"timestamp":"2026-09-29T19:46:20.000Z","ordinal":0,"type":"turn_context","payload":{"turn_id":"01a06300-0000-7000-8000-0000000000b0","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","cwd":"/sandbox/workspace/repo","approval_policy":"never","sandbox_policy":{"type":"danger-full-access"},"model":"gpt-5.6-luna","multi_agent_version":"v1","effort":"medium","summary":"auto"}} +{"timestamp":"2026-09-29T19:46:30.000Z","ordinal":1,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":54208,"cached_input_tokens":40590,"cache_write_input_tokens":13618,"output_tokens":1140,"reasoning_output_tokens":291,"total_tokens":55348},"last_token_usage":{"input_tokens":54208,"cached_input_tokens":40590,"cache_write_input_tokens":13618,"output_tokens":1140,"reasoning_output_tokens":291,"total_tokens":55348},"model_context_window":258400},"rate_limits":null}} +{"timestamp":"2026-09-29T19:46:38.900Z","ordinal":2,"type":"event_msg","payload":{"type":"task_started","turn_id":"01a06300-0000-7000-8000-0000000000b5","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","started_at":1790711198,"model_context_window":258400,"collaboration_mode_kind":"default"}} +{"timestamp":"2026-09-29T19:46:39.400Z","ordinal":3,"type":"turn_context","payload":{"turn_id":"01a06300-0000-7000-8000-0000000000b5","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","cwd":"/sandbox/workspace/repo","approval_policy":"never","sandbox_policy":{"type":"danger-full-access"},"model":"gpt-5.6-terra","multi_agent_version":"v1","effort":"low","summary":"auto"}} +{"timestamp":"2026-09-29T19:46:41.000Z","ordinal":4,"type":"token_usage_record","payload":{"thread_id":"01a06300-0000-7000-8000-0000000000a5","turn_id":"01a06300-0000-7000-8000-0000000000b5","session_id":"01a06300-0000-7000-8000-000000000050","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","response_id":"resp_fixture_a5_1","usage":{"input_tokens":600,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":40,"reasoning_output_tokens":10,"total_tokens":640},"turn_token_usage":{"input_tokens":600,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":40,"reasoning_output_tokens":10,"total_tokens":640},"thread_token_usage":{"input_tokens":600,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":40,"reasoning_output_tokens":10,"total_tokens":640}}} +{"timestamp":"2026-09-29T19:46:41.010Z","ordinal":5,"type":"event_msg","payload":{"type":"task_complete","turn_id":"01a06300-0000-7000-8000-0000000000b5","last_agent_message":"Done.","started_at":1790711198,"completed_at":1790711201,"duration_ms":2100,"time_to_first_token_ms":900}} diff --git a/internal/runtime/testdata/codex/child_usage_no_model.jsonl b/internal/runtime/testdata/codex/child_usage_no_model.jsonl new file mode 100644 index 0000000000..295cceaa1d --- /dev/null +++ b/internal/runtime/testdata/codex/child_usage_no_model.jsonl @@ -0,0 +1,3 @@ +{"timestamp":"2026-09-29T19:46:39.000Z","ordinal":0,"type":"session_meta","payload":{"session_id":"01a06300-0000-7000-8000-000000000050","id":"01a06300-0000-7000-8000-0000000000a4","parent_thread_id":"01a06300-0000-7000-8000-000000000050","agent_role":null,"multi_agent_version":"v1"}} +{"timestamp":"2026-09-29T19:46:39.400Z","ordinal":1,"type":"token_usage_record","payload":{"thread_id":"01a06300-0000-7000-8000-0000000000a4","turn_id":"01a06300-0000-7000-8000-0000000000b4","session_id":"01a06300-0000-7000-8000-000000000050","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","response_id":"resp_fixture_a4_1","usage":{"input_tokens":50,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":5,"reasoning_output_tokens":0,"total_tokens":55},"turn_token_usage":{"input_tokens":50,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":5,"reasoning_output_tokens":0,"total_tokens":55},"thread_token_usage":{"input_tokens":50,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":5,"reasoning_output_tokens":0,"total_tokens":55}}} +{"timestamp":"2026-09-29T19:46:39.500Z","ordinal":2,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":50,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":5,"reasoning_output_tokens":0,"total_tokens":55}},"rate_limits":null}} diff --git a/internal/runtime/testdata/codex/child_usage_other_model.jsonl b/internal/runtime/testdata/codex/child_usage_other_model.jsonl new file mode 100644 index 0000000000..6d54bce782 --- /dev/null +++ b/internal/runtime/testdata/codex/child_usage_other_model.jsonl @@ -0,0 +1,6 @@ +{"timestamp":"2026-09-29T19:46:38.900Z","ordinal":0,"type":"session_meta","payload":{"session_id":"01a06300-0000-7000-8000-000000000050","id":"01a06300-0000-7000-8000-0000000000a2","parent_thread_id":"01a06300-0000-7000-8000-000000000050","timestamp":"2026-09-29T19:46:38.880Z","cwd":"/sandbox/workspace/repo","originator":"codex_exec","cli_version":"0.157.0","source":{"subagent":{"thread_spawn":{"parent_thread_id":"01a06300-0000-7000-8000-000000000050","depth":1,"agent_path":null,"agent_nickname":"Curie","agent_role":"security"}}},"thread_source":"subagent","agent_nickname":"Curie","agent_role":"security","model_provider":"openai","base_instructions":"(trimmed)","history_mode":"paginated","multi_agent_version":"v1"}} +{"timestamp":"2026-09-29T19:46:38.900Z","ordinal":1,"type":"event_msg","payload":{"type":"task_started","turn_id":"01a06300-0000-7000-8000-0000000000b2","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","started_at":1790711198,"model_context_window":258400,"collaboration_mode_kind":"default"}} +{"timestamp":"2026-09-29T19:46:39.400Z","ordinal":2,"type":"turn_context","payload":{"turn_id":"01a06300-0000-7000-8000-0000000000b2","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","cwd":"/sandbox/workspace/repo","approval_policy":"never","sandbox_policy":{"type":"danger-full-access"},"model":"gpt-5.6-terra","multi_agent_version":"v1","effort":"low","summary":"auto"}} +{"timestamp":"2026-09-29T19:46:41.000Z","ordinal":3,"type":"token_usage_record","payload":{"thread_id":"01a06300-0000-7000-8000-0000000000a2","turn_id":"01a06300-0000-7000-8000-0000000000b2","session_id":"01a06300-0000-7000-8000-000000000050","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","response_id":"resp_fixture_a2_1","usage":{"input_tokens":4000,"cached_input_tokens":1000,"cache_write_input_tokens":2000,"output_tokens":300,"reasoning_output_tokens":100,"total_tokens":4300},"turn_token_usage":{"input_tokens":4000,"cached_input_tokens":1000,"cache_write_input_tokens":2000,"output_tokens":300,"reasoning_output_tokens":100,"total_tokens":4300},"thread_token_usage":{"input_tokens":4000,"cached_input_tokens":1000,"cache_write_input_tokens":2000,"output_tokens":300,"reasoning_output_tokens":100,"total_tokens":4300}}} +{"timestamp":"2026-09-29T19:46:41.000Z","ordinal":4,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":4000,"cached_input_tokens":1000,"cache_write_input_tokens":2000,"output_tokens":300,"reasoning_output_tokens":100,"total_tokens":4300},"last_token_usage":{"input_tokens":4000,"cached_input_tokens":1000,"cache_write_input_tokens":2000,"output_tokens":300,"reasoning_output_tokens":100,"total_tokens":4300},"model_context_window":258400},"rate_limits":null}} +{"timestamp":"2026-09-29T19:46:41.010Z","ordinal":5,"type":"event_msg","payload":{"type":"task_complete","turn_id":"01a06300-0000-7000-8000-0000000000b2","last_agent_message":"One finding.","started_at":1790711198,"completed_at":1790711201,"duration_ms":2100,"time_to_first_token_ms":900}} diff --git a/internal/runtime/testdata/codex/child_usage_same_model.jsonl b/internal/runtime/testdata/codex/child_usage_same_model.jsonl new file mode 100644 index 0000000000..02345acfd3 --- /dev/null +++ b/internal/runtime/testdata/codex/child_usage_same_model.jsonl @@ -0,0 +1,7 @@ +{"timestamp":"2026-09-29T19:46:38.744Z","ordinal":0,"type":"session_meta","payload":{"session_id":"01a06300-0000-7000-8000-000000000050","id":"01a06300-0000-7000-8000-0000000000a1","parent_thread_id":"01a06300-0000-7000-8000-000000000050","timestamp":"2026-09-29T19:46:38.712Z","cwd":"/sandbox/workspace/repo","originator":"codex_exec","cli_version":"0.157.0","source":{"subagent":{"thread_spawn":{"parent_thread_id":"01a06300-0000-7000-8000-000000000050","depth":1,"agent_path":null,"agent_nickname":"Faraday","agent_role":"correctness"}}},"thread_source":"subagent","agent_nickname":"Faraday","agent_role":"correctness","model_provider":"openai","base_instructions":"(trimmed)","history_mode":"paginated","multi_agent_version":"v1"}} +{"timestamp":"2026-09-29T19:46:38.744Z","ordinal":1,"type":"event_msg","payload":{"type":"task_started","turn_id":"01a06300-0000-7000-8000-0000000000b1","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","started_at":1790711198,"model_context_window":258400,"collaboration_mode_kind":"default"}} +{"timestamp":"2026-09-29T19:46:39.366Z","ordinal":2,"type":"turn_context","payload":{"turn_id":"01a06300-0000-7000-8000-0000000000b1","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","cwd":"/sandbox/workspace/repo","approval_policy":"never","sandbox_policy":{"type":"danger-full-access"},"model":"gpt-5.6-luna","multi_agent_version":"v1","effort":"low","summary":"auto"}} +{"timestamp":"2026-09-29T19:46:39.900Z","ordinal":3,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":3000,"cached_input_tokens":0,"cache_write_input_tokens":2990,"output_tokens":4,"reasoning_output_tokens":0,"total_tokens":3004},"last_token_usage":{"input_tokens":3000,"cached_input_tokens":0,"cache_write_input_tokens":2990,"output_tokens":4,"reasoning_output_tokens":0,"total_tokens":3004},"model_context_window":258400},"rate_limits":null}} +{"timestamp":"2026-09-29T19:46:40.124Z","ordinal":4,"type":"token_usage_record","payload":{"thread_id":"01a06300-0000-7000-8000-0000000000a1","turn_id":"01a06300-0000-7000-8000-0000000000b1","session_id":"01a06300-0000-7000-8000-000000000050","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","response_id":"resp_fixture_a1_2","usage":{"input_tokens":4381,"cached_input_tokens":0,"cache_write_input_tokens":4388,"output_tokens":4,"reasoning_output_tokens":0,"total_tokens":4385},"turn_token_usage":{"input_tokens":7381,"cached_input_tokens":0,"cache_write_input_tokens":7378,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":7389},"thread_token_usage":{"input_tokens":7381,"cached_input_tokens":0,"cache_write_input_tokens":7378,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":7389}}} +{"timestamp":"2026-09-29T19:46:40.124Z","ordinal":5,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":7381,"cached_input_tokens":0,"cache_write_input_tokens":7378,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":7389},"last_token_usage":{"input_tokens":4381,"cached_input_tokens":0,"cache_write_input_tokens":4388,"output_tokens":4,"reasoning_output_tokens":0,"total_tokens":4385},"model_context_window":258400},"rate_limits":null}} +{"timestamp":"2026-09-29T19:46:40.128Z","ordinal":6,"type":"event_msg","payload":{"type":"task_complete","turn_id":"01a06300-0000-7000-8000-0000000000b1","last_agent_message":"No defects found.","started_at":1790711198,"completed_at":1790711200,"duration_ms":1384,"time_to_first_token_ms":1284}} diff --git a/internal/runtime/testdata/codex/collab_spawn.ndjson b/internal/runtime/testdata/codex/collab_spawn.ndjson new file mode 100644 index 0000000000..5918333dde --- /dev/null +++ b/internal/runtime/testdata/codex/collab_spawn.ndjson @@ -0,0 +1,14 @@ +{"type":"thread.started","thread_id":"01a06300-0000-7000-8000-000000000050"} +{"type":"turn.started"} +{"type":"item.started","item":{"id":"item_0","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":[],"prompt":"Review for correctness.","agents_states":{},"status":"in_progress"}} +{"type":"item.completed","item":{"id":"item_0","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a1"],"prompt":"Review for correctness.","agents_states":{"01a06300-0000-7000-8000-0000000000a1":{"status":"pending_init","message":null}},"status":"completed"}} +{"type":"item.completed","item":{"id":"item_1","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a2"],"prompt":"Review for security.","agents_states":{"01a06300-0000-7000-8000-0000000000a2":{"status":"pending_init","message":null}},"status":"completed"}} +{"type":"item.completed","item":{"id":"item_2","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a3"],"prompt":"Challenge the findings.","agents_states":{"01a06300-0000-7000-8000-0000000000a3":{"status":"pending_init","message":null}},"status":"completed"}} +{"type":"item.completed","item":{"id":"item_3","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a9"],"prompt":"Fork me.","agents_states":{},"status":"failed"}} +{"type":"item.completed","item":{"id":"item_4","type":"collab_tool_call","tool":"wait","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a1","01a06300-0000-7000-8000-0000000000a2"],"prompt":null,"agents_states":{"01a06300-0000-7000-8000-0000000000a1":{"status":"completed","message":"No defects found."},"01a06300-0000-7000-8000-0000000000a2":{"status":"completed","message":"One finding."}},"status":"completed"}} +{"type":"item.completed","item":{"id":"item_5","type":"collab_tool_call","tool":"wait","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a3"],"prompt":null,"agents_states":{"01a06300-0000-7000-8000-0000000000a3":{"status":"errored","message":"unexpected status 404 Not Found: The model `gpt-5.6-nonexistent` does not exist or you do not have access to it., url: https://api.openai.com/v1/responses"}},"status":"failed"}} +{"type":"item.completed","item":{"id":"item_6","type":"collab_tool_call","tool":"close_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a1"],"prompt":null,"agents_states":{"01a06300-0000-7000-8000-0000000000a1":{"status":"completed","message":"No defects found."}},"status":"completed"}} +{"type":"item.completed","item":{"id":"item_7","type":"collab_tool_call","tool":"close_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a2"],"prompt":null,"agents_states":{"01a06300-0000-7000-8000-0000000000a2":{"status":"completed","message":"One finding."}},"status":"completed"}} +{"type":"item.completed","item":{"id":"item_8","type":"collab_tool_call","tool":"close_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a3"],"prompt":null,"agents_states":{"01a06300-0000-7000-8000-0000000000a3":{"status":"errored","message":"unexpected status 404 Not Found: The model `gpt-5.6-nonexistent` does not exist or you do not have access to it., url: https://api.openai.com/v1/responses"}},"status":"failed"}} +{"type":"item.completed","item":{"id":"item_9","type":"agent_message","text":"Review complete."}} +{"type":"turn.completed","usage":{"input_tokens":54223,"cached_input_tokens":40590,"cache_write_input_tokens":13618,"output_tokens":1431,"reasoning_output_tokens":291}}