Skip to content

Local compaction sends tool_choice=auto with empty tools, causing xAI/Grok HTTP 400 #46773

Open

Description

@xsser

What version of Codex CLI is running?

codex-cli 0.155.1 (latest stable release at the time of this report). The standalone local reproduction below was run on this version. The original live xAI failure was observed on 0.154.0.

What subscription do you have?

Custom Responses API provider: xAI/Grok. The standalone reproduction uses a local mock provider and requires no subscription or API key.

Which model were you using?

grok-4.6 for the live failure and recovery; fixture-model for the deterministic local reproduction.

What platform is your computer?

macOS 26.6.2, Darwin 25.6.0, arm64.

What terminal emulator and version are you using?

Ghostty 1.3.1 for the original TUI session; codex exec for the standalone reproduction.

Codex doctor report

codex doctor --json exits 0. Status-only summary from the regular configuration, with unrelated local service/account/path details omitted:

{
  "codexVersion": "0.155.1",
  "overallStatus": "warning",
  "checks": {
    "installation": "ok",
    "config.load": "ok",
    "runtime.provenance": "ok",
    "network.provider_reachability": "warning",
    "state.rollout_db_parity": "warning",
    "updates.status": "warning"
  }
}

The reproduction below uses an isolated temporary CODEX_HOME and --ignore-user-config; its model endpoint is loopback.

What issue are you seeing?

Pre-turn automatic compaction sends a standard Responses request with tools: [] and tool_choice: "auto". xAI rejects this combination, which prevents a long session from compacting and continuing.

Live upstream error (HTTP 400):

{
  "code": "invalid-argument",
  "error": "Invalid request content: A tool_choice was set on the request but no tools were specified."
}

The original Codex log reports Failed to run pre-sampling compact, with run_auto_compact{reason=ContextLimit phase=PreTurn}. The affected path is local summarization through POST /v1/responses.

What steps can reproduce the bug?

A credential-free reproduction is included below. It runs the installed stock CLI against a local HTTP mock:

  1. Create one synthetic seed turn in an isolated temporary CODEX_HOME. The mock returns a successful SSE response and a deliberately high usage count to trigger compaction on the next turn.
  2. Resume that seed with codex exec resume --last --ephemeral --ignore-user-config, model_context_window=1024, and model_auto_compact_token_limit=128.
  3. The mock records the request shape and rejects a request only when it has no tools but still specifies tool_choice.

Observed on 0.155.1:

Phase Endpoint Tool count tool_choice Result
Seed turn /v1/responses 9 auto HTTP 200, CLI exit 0
Pre-turn local compaction /v1/responses 0 auto HTTP 400 across 6 attempts, CLI exit 1

The failing request shape is emitted by Codex; the mock does not modify the incoming request. The final CLI event is turn.failed, and stderr reports a pre-sampling compaction failure.

Save the script below as fixture-repro.mjs in an empty temporary directory and run:

node fixture-repro.mjs

It uses codex from PATH; optionally set CODEX_BIN to select a different installed binary. It removes the synthetic temporary home and writes only structural request evidence and controlled error text to fixture-evidence.json and fixture-console.txt. A runner exit code of 0 means the bug was reproduced; the nested compaction invocation exits 1.

Standalone Node.js reproduction (standard library only)
#!/usr/bin/env node

import assert from "node:assert/strict";
import { spawn, spawnSync } from "node:child_process";
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
import http from "node:http";
import { fileURLToPath } from "node:url";
import path from "node:path";

const fixtureRoot = path.dirname(fileURLToPath(import.meta.url));
const fixtureHome = path.join(fixtureRoot, `fixture-home-${process.pid}`);
const fixtureWorkdir = path.join(fixtureRoot, "fixture-workdir");
const evidencePath = path.join(fixtureRoot, "fixture-evidence.json");
const consolePath = path.join(fixtureRoot, "fixture-console.txt");
const codexPath = process.env.CODEX_BIN || "codex";

mkdirSync(fixtureHome, { recursive: true, mode: 0o700 });
mkdirSync(fixtureWorkdir, { recursive: true, mode: 0o700 });

const versionResult = spawnSync(codexPath, ["--version"], {
  encoding: "utf8",
  env: { ...process.env, CODEX_HOME: fixtureHome },
});
assert.equal(versionResult.status, 0, versionResult.stderr);
const codexVersion = versionResult.stdout.trim();

const requests = [];
let requestSequence = 0;
let requestPhase = "setup";

function toolShape(body) {
  if (!Object.prototype.hasOwnProperty.call(body, "tools")) {
    return { state: "absent", count: null };
  }
  if (body.tools === null) return { state: "null", count: null };
  if (Array.isArray(body.tools)) return { state: "array", count: body.tools.length };
  return { state: typeof body.tools, count: null };
}

function safeToolChoice(value) {
  if (typeof value === "string") return value;
  if (value === null || value === undefined) return null;
  return { type: typeof value };
}

function writeJson(response, status, value) {
  const encoded = JSON.stringify(value);
  response.writeHead(status, {
    "content-type": "application/json",
    "content-length": Buffer.byteLength(encoded),
  });
  response.end(encoded);
}

function writeSuccessfulSse(response, model) {
  const responseId = `resp_fixture_${requestSequence}`;
  const messageId = `msg_fixture_${requestSequence}`;
  const outputText = "fixture-ready";
  const completedResponse = {
    id: responseId,
    object: "response",
    created_at: 0,
    status: "completed",
    error: null,
    incomplete_details: null,
    instructions: null,
    max_output_tokens: null,
    model,
    output: [{
      id: messageId,
      type: "message",
      status: "completed",
      role: "assistant",
      content: [{ type: "output_text", text: outputText, annotations: [] }],
    }],
    parallel_tool_calls: true,
    previous_response_id: null,
    reasoning: { effort: null, summary: null },
    store: false,
    temperature: null,
    text: { format: { type: "text" } },
    tool_choice: "auto",
    tools: [],
    top_p: null,
    truncation: "disabled",
    usage: {
      // Force the fresh ephemeral turn over the configured auto-compaction limit.
      input_tokens: 5000,
      input_tokens_details: { cached_tokens: 0 },
      output_tokens: 1,
      output_tokens_details: { reasoning_tokens: 0 },
      total_tokens: 5001,
    },
    metadata: {},
  };
  const events = [
    {
      type: "response.output_item.done",
      sequence_number: 0,
      output_index: 0,
      item: completedResponse.output[0],
    },
    {
      type: "response.completed",
      sequence_number: 1,
      response: completedResponse,
    },
  ];
  response.writeHead(200, {
    "content-type": "text/event-stream",
    "cache-control": "no-cache",
    connection: "close",
  });
  for (const event of events) {
    response.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
  }
  response.end();
}

const server = http.createServer((request, response) => {
  const chunks = [];
  let byteCount = 0;
  request.on("data", (chunk) => {
    byteCount += chunk.length;
    if (byteCount <= 16 * 1024 * 1024) chunks.push(chunk);
  });
  request.on("end", () => {
    requestSequence += 1;
    let body;
    try {
      body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
    } catch {
      writeJson(response, 400, { error: { message: "fixture received invalid JSON" } });
      return;
    }

    const tools = toolShape(body);
    const shape = {
      sequence: requestSequence,
      phase: requestPhase,
      method: request.method,
      path: request.url,
      model: typeof body.model === "string" ? body.model : null,
      input_count: Array.isArray(body.input) ? body.input.length : null,
      tools_state: tools.state,
      tools_count: tools.count,
      tool_choice: safeToolChoice(body.tool_choice),
      stream: body.stream === true,
    };
    requests.push(shape);

    const noTools = tools.state === "absent" || tools.state === "null" ||
      (tools.state === "array" && tools.count === 0);
    if (noTools && body.tool_choice !== undefined) {
      writeJson(response, 400, {
        error: {
          message: "A tool_choice was set on the request but no tools were specified",
          type: "invalid_request_error",
          param: "tool_choice",
          code: "invalid_argument",
        },
      });
      return;
    }

    writeSuccessfulSse(response, shape.model ?? "fixture-model");
  });
});

await new Promise((resolve, reject) => {
  server.once("error", reject);
  server.listen(0, "127.0.0.1", resolve);
});

const address = server.address();
assert(address && typeof address === "object");
const baseUrl = `http://127.0.0.1:${address.port}/v1`;
const providerConfig = `{name="Fixture loopback",base_url="${baseUrl}",wire_api="responses",requires_openai_auth=false}`;
const configArgs = [
  "-m", "fixture-model",
  "-c", "model_provider=\"fixture\"",
  "-c", `model_providers.fixture=${providerConfig}`,
  "-c", "model_context_window=1024",
  "-c", "model_auto_compact_token_limit=128",
];
const seedArgs = [
  "exec",
  "--ignore-user-config",
  "--ignore-rules",
  "--skip-git-repo-check",
  "--json",
  "--color", "never",
  "--sandbox", "read-only",
  "-C", fixtureWorkdir,
  ...configArgs,
  "-",
];
const reproduceArgs = [
  "exec", "resume", "--last",
  "--ephemeral",
  "--ignore-user-config",
  "--ignore-rules",
  "--skip-git-repo-check",
  "--json",
  ...configArgs,
  "-",
];

const childEnv = {
  ...process.env,
  CODEX_HOME: fixtureHome,
  HTTP_PROXY: "",
  HTTPS_PROXY: "",
  ALL_PROXY: "",
  http_proxy: "",
  https_proxy: "",
  all_proxy: "",
  NO_PROXY: "127.0.0.1,localhost",
  no_proxy: "127.0.0.1,localhost",
};

async function runCodex(args, prompt) {
  const child = spawn(codexPath, args, {
    cwd: fixtureWorkdir,
    env: childEnv,
    stdio: ["pipe", "pipe", "pipe"],
  });
  let stdout = "";
  let stderr = "";
  let stdinClosedEarly = false;
  child.stdout.setEncoding("utf8");
  child.stderr.setEncoding("utf8");
  child.stdout.on("data", (chunk) => { stdout += chunk; });
  child.stderr.on("data", (chunk) => { stderr += chunk; });
  child.stdin.on("error", (error) => {
    if (error.code === "EPIPE") {
      stdinClosedEarly = true;
      return;
    }
    throw error;
  });
  child.stdin.end(prompt);

  let timedOut = false;
  const timeout = setTimeout(() => {
    timedOut = true;
    child.kill("SIGTERM");
  }, 60_000);
  const exit = await new Promise((resolve) =>
    child.once("exit", (code, signal) => resolve({ code, signal }))
  );
  clearTimeout(timeout);
  return { ...exit, timedOut, stdinClosedEarly, stdout, stderr };
}

// The seed is stored only in the isolated temporary CODEX_HOME, then removed.
requestPhase = "seed";
const seed = await runCodex(seedArgs, "Synthetic fixture seed. Reply fixture-ready.");
requestPhase = "reproduction";
const reproduction = seed.code === 0
  ? await runCodex(reproduceArgs, "Synthetic fixture second turn.")
  : { code: null, signal: null, timedOut: false, stdinClosedEarly: false, stdout: "", stderr: "" };
await new Promise((resolve) => server.close(resolve));
rmSync(fixtureHome, {
  recursive: true,
  force: true,
  maxRetries: 5,
  retryDelay: 100,
});

const controlledError = "A tool_choice was set on the request but no tools were specified";
function sanitizedStdoutEvents(stdout) {
  return stdout.split(/\r?\n/).filter(Boolean).flatMap((line) => {
  try {
    const event = JSON.parse(line);
    const summary = { type: typeof event.type === "string" ? event.type : "unknown" };
    const message = typeof event.message === "string"
      ? event.message
      : typeof event.error?.message === "string"
        ? event.error.message
        : null;
    if (message?.includes(controlledError)) summary.message = controlledError;
    return [summary];
  } catch {
    return [];
  }
  });
}
function sanitizedStderrSignals(stderr) {
  return stderr.split(/\r?\n/)
  .filter((line) => line.includes(controlledError) || /pre-sampling compact/i.test(line))
  .map((line) => line.includes(controlledError) ? controlledError : "pre-sampling compact failure reported")
  .slice(0, 10);
}

const violatingRequests = requests.filter((request) =>
  request.tool_choice !== null &&
  (request.tools_state === "absent" || request.tools_state === "null" ||
    (request.tools_state === "array" && request.tools_count === 0))
);
const evidence = {
  generated_at: new Date().toISOString(),
  codex_version: codexVersion,
  invocations: {
    seed: {
      executable: codexPath,
      args: seedArgs.map((arg) => arg.replace(baseUrl, "http://127.0.0.1:<dynamic>/v1")),
      ephemeral: false,
      purpose: "Create synthetic history only inside the isolated temporary CODEX_HOME.",
    },
    reproduction: {
      executable: codexPath,
      args: reproduceArgs.map((arg) => arg.replace(baseUrl, "http://127.0.0.1:<dynamic>/v1")),
      ephemeral: true,
    },
    ignored_user_config: true,
    isolated_codex_home: true,
    isolated_codex_home_removed: true,
    credentials_configured: false,
    external_requests_configured: false,
  },
  processes: {
    seed: {
      exit_code: seed.code,
      signal: seed.signal,
      timed_out: seed.timedOut,
      stdin_closed_early: seed.stdinClosedEarly,
    },
    reproduction: {
      exit_code: reproduction.code,
      signal: reproduction.signal,
      timed_out: reproduction.timedOut,
      stdin_closed_early: reproduction.stdinClosedEarly,
    },
  },
  requests,
  stdout_events: {
    seed: sanitizedStdoutEvents(seed.stdout),
    reproduction: sanitizedStdoutEvents(reproduction.stdout),
  },
  stderr_signals: {
    seed: sanitizedStderrSignals(seed.stderr),
    reproduction: sanitizedStderrSignals(reproduction.stderr),
  },
  reproduced: violatingRequests.some((request) => request.tool_choice === "auto"),
  violating_request_sequences: violatingRequests.map((request) => request.sequence),
  privacy: "Only sanitized request shape and controlled error text were retained; no headers, instructions, prompts, or input bodies were written.",
};

writeFileSync(evidencePath, `${JSON.stringify(evidence, null, 2)}\n`, { mode: 0o600 });
const consoleLines = [
  `Codex: ${codexVersion}`,
  `Seed exit: ${seed.code}${seed.signal ? ` signal=${seed.signal}` : ""}${seed.timedOut ? " timed_out=true" : ""}`,
  `Reproduction exit: ${reproduction.code}${reproduction.signal ? ` signal=${reproduction.signal}` : ""}${reproduction.timedOut ? " timed_out=true" : ""}`,
  `Captured requests: ${requests.length}`,
  ...requests.map((request) =>
    `#${request.sequence} ${request.method} ${request.path} model=${request.model} tools=${request.tools_state}` +
    `${request.tools_count === null ? "" : `:${request.tools_count}`} tool_choice=${JSON.stringify(request.tool_choice)}`
  ),
  `Reproduced empty-tools plus tool_choice=auto: ${evidence.reproduced ? "yes" : "no"}`,
  `Evidence: ${evidencePath}`,
];
writeFileSync(consolePath, `${consoleLines.join("\n")}\n`, { mode: 0o600 });
process.stdout.write(`${consoleLines.join("\n")}\n`);
process.exitCode = evidence.reproduced ? 0 : 2;

What is the expected behavior?

For a standard Responses request with no available tools, omit tool_choice so a strict compatible provider can perform text-only summarization. Requests with available tools should retain their existing tool-selection behavior.

Additional information

Source-level root cause: the same construction is present on current main at commit 5c5308fc9a9ee789049d646ef11e5400384b9c6f:

Live workaround and verification: in my xAI transport adapter, omitting only tool_choice when tools are absent, null, or an empty array allowed the original conversation to complete compaction and resume. Two resumed turns completed successfully with CLI exit 0. A separate minimal streaming request returned HTTP 200, model grok-4.6, the expected text, and a real response.completed event. The adapter preserves nonempty tools and their selection setting.

The standalone reproduction above bypasses that adapter and demonstrates the current CLI request shape independently of xAI authentication or my existing session history.

Possible fix direction: make tool-choice serialization conditional on the logical availability of tools. Please account for Responses Lite, where tool declarations can be embedded in input rather than the top-level tools field; this report reproduces the standard Responses/custom-provider path. Suggested regression coverage is an empty-tool local-compaction request accepted by a strict mock, plus unchanged behavior for a nonempty tool list.

Activity

  1. added
    bug
    CLI
    context
    custom-model
    on Sep 20, 2026
  2. argszero commented on Sep 20, 2026

    @argszero

    Thanks — this is source-verifiable end to end, and every pointer in the report checks out on the commit you cite (5c5308fc9a9e, which is still current main).

    Source verification of the four claims

    Claim Verified
    Local compaction builds a default Prompt (no tools) compact.rs:287-290 — Prompt { input, base_instructions, ..Default::default() }, so tools is an empty Vec
    The standard path serializes the tool list unconditionally client.rs:920 — Some(create_tools_raw_json_for_responses_api(&prompt.tools)?.into()); the helper is to_raw_value(tools) (tools/src/tool_spec.rs:145-149), so an empty slice becomes the literal [], not an omitted field
    The builder always sets tool_choice client.rs:971 — tool_choice: "auto".to_string(),
    The wire type cannot omit it codex-api/src/common.rs:267 — pub tool_choice: String with no skip_serializing_if (contrast tools at :265-266, which is Option<...> + skip_serializing_if)

    So {"tools": [], "tool_choice": "auto"} is produced by construction, and the only reason it goes unnoticed is that OpenAI accepts the combination.

    Blast radius: two production writers, both transports

    ResponsesApiRequest is built in production in exactly two places: client.rs:966-975 and the guardian sampler (ext/guardian-v2/src/async_scorer/sampler.rs:216-222). The other hits for tool_choice are test fixtures.

    Note the sampler while you are there: it passes tools: None together with tool_choice: "none" at :221. Declaring a tool choice with no tools is therefore an established pattern in this codebase rather than a one-off slip — which also means a fix should not disturb that site (its value is non-empty, so it stays serialized under the approach below).

    Both transports are affected, because the WebSocket payload is derived from the same struct: impl From<&ResponsesApiRequest> for ResponseCreateWsRequest copies tool_choice through, and ResponseCreateWsRequest.tool_choice (common.rs:322) is a bare &'a str with no skip attribute either.

    A fix that matches the file's own idiom

    You would not need to change the field type. The omission idiom already exists one field above in the same struct:

    • common.rs:262 — instructions: String + #[serde(skip_serializing_if = "String::is_empty")]
    • common.rs:315 — the WS mirror uses skip_serializing_if = "str::is_empty" on the same field

    So: keep tool_choice: String, add the same attribute, and set String::new() where the logical tool list is empty. The WS struct needs the str::is_empty twin, or the value can be normalized at the single construction site in client.rs. No consumer changes, no Option churn across the fixtures.

    Omitting the field when there is nothing to select is semantically identical for OpenAI (auto is the default, and with no tools the choice has nothing to act on), so this stays provider-neutral rather than being a custom-provider special case.

    The Responses Lite caveat, with evidence for the right predicate

    You are right to flag it, and there is a concrete artifact that shows why the predicate must be the logical list rather than the serialized field. In the Lite branch (client.rs:894-921) the top-level tools field is set to None and the tool definitions are spliced into the input as an additional_tools developer item instead — while prompt.tools itself is still populated.

    The existing scenario snapshot core/tests/suite/snapshots/all__suite__scenarios__astra_kickoff_remote_compaction_windows.snap captures exactly that: a request that remotely compacts, whose settings block carries tool_choice: "auto", whose tools appear as 00:additional_tools/developer (3; ...), and which has no top-level tools line at all.

    So a predicate keyed on the serialized field would strip tool_choice from Lite (i.e. OpenAI-facing) requests and force that snapshot to change. Keying on prompt.tools.is_empty() selects only the tool-free compaction request and leaves Lite untouched.

    Existing coverage

    The Some(<empty tools>) + "auto" combination currently appears as a fixture in three places — core/src/client_common_tests.rs:117/165/227/252, codex-api/tests/clients.rs:350/438/559, and codex-api/src/endpoint/responses_websocket.rs:948 — but they construct requests rather than assert the serialized body, so nothing pins the shape either way. Regression coverage that would actually fail today: a strict mock that rejects tool_choice when the tool list is empty (your fixture does this), plus unchanged bodies for a non-empty list, plus a Lite case asserting tool_choice survives.

    Related open prior art in the same class ("omit field when unset"): #31290.

    Disclosure: I verified this by reading current main, not by running your fixture — my working environment is read-only, so the CLI was not executed here. I did not find a duplicate report.

  3. ghzlatarev commented on Oct 12, 2026

    @ghzlatarev

    Confirmed on stock 0.162.1 (macOS arm64) and an unmodified source build at 7c9bfb910ef65c8f4a957c53affbd43d5fac2882, including the stdio app-server path.

    This reproduction uses a fresh temporary HOME/CODEX_HOME/workspace, no credentials, and a localhost Responses SSE mock. No reasoning item is needed: each accepted response reports 110 tokens and model_auto_compact_token_limit=100 forces pre-turn local compaction. Post-turn compaction is disabled. The strict mock returns HTTP 400 only for an empty tool list with tool_choice neither omitted nor none.

    Binary / endpoint Request tool counts / choices Turn statuses Completed compactions
    0.162.1 / strict (8, auto), (0, auto), (0, auto) completed, failed, failed 0
    source build / strict (8, auto), (0, auto), (0, auto) completed, failed, failed 0
    0.162.1 / permissive control (8, auto), (0, auto), (8, auto), (0, auto), (8, auto) completed, completed, completed 2

    The failed compaction is retried on the next submitted turn; the ordinary sampling request is never reached on those failed turns. The controlled error is Synthetic strict endpoint: tool_choice set with no tools.

    Use the standalone Python script in this comment:

    python3 compaction-accounting.py --binary codex --limit 100 --strict-empty-tools
    python3 compaction-accounting.py --binary codex --limit 100

    The source still constructs local compaction with a default empty-tool prompt and unconditionally sets tool_choice: "auto".

    This supports the fix direction in the issue: omit tool selection when no logical tools are available, preserving normal selection with available tools and accounting for Responses Lite declarations embedded in input. The permissive control isolates the provider-validation failure; no live provider or production session is involved. No patch is tested by this probe.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    CLIbugcontextcustom-model

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions