Skip to content

Missing \call_id\ on injected standalone \unction_call_output\ also breaks normal thread resume / cross-thread send under third-party Responses providers #42067

Open

Description

@SIMON-WORLD

Summary

With Codex Desktop 26.825.51511 (app-server 0.151.0-alpha.7.2) and a third-party
provider using wire_api = "responses" (DeepSeek), resuming an existing thread or
sending a message to it
fails with:

Failed to deserialize the JSON body into the target type: input: missing field `call_id` at line 1 column ~1605392

This is the same root cause as #41690, but that report only covers the automation
path (codex_app__automation_update). Here it also reproduces during ordinary
thread resume
and cross-thread send (e.g., delegating a task to another thread /
send_message_to_thread), so the impact is broader than automations.

Environment

  • Windows
  • Codex Desktop app build: 26.825.51511
  • Embedded app-server / command runner: 0.151.0-alpha.7.2
  • Model provider: DeepSeek (third-party) via a local relay
  • Config:
    • model_provider = "openai-chat-completions"
    • base_url = "http://127.0.0.1:19100/v1"
    • wire_api = "responses"
    • requires_openai_auth = true
    • model = "deepseek-v4-flash-vision-exp"

Reproduction

  1. Use a third-party Responses provider (DeepSeek).
  2. Open a thread that has accumulated tool calls (function_call / function_call_output).
  3. Send a new message (or delegate a task to it).
  4. The turn fails with missing field call_id.

Evidence

The session rollout records a response_item of type function_call_output that has
id, name, namespace, output, and internal_chat_message_metadata_passthrough
but no call_id:

{"type":"function_call_output","id":"...","name":"...","namespace":"codex_app","output":"...","internal_chat_message_metadata_passthrough":"..."}

This item is written into the session at the moment the thread is resumed (triggered by
the new message). When the app-server assembles the request body for the Responses API,
this standalone output lacking call_id is rejected by the strict third-party
deserializer.

Regression note

This worked on 26.820.71523 (8/30) and started failing after the app updated to
26.825.51511 on 8/31, with the same DeepSeek Responses provider throughout. Both
#41690 and #41799 are also on 26.825.51511.

Requested behavior

  • When injecting a standalone function_call_output (no matching call in the immediate
    turn), the app-server should either synthesize a call_id or normalize it into a
    provider-accepted message before sending to third-party Responses providers.
  • Alternatively, expose a provider capability/feature flag so strict Responses providers
    receive a compatible tool-output shape.

Related

Activity

  1. added
    bug
    app
    windows-os
    custom-model
    app-server
    on Sep 1, 2026
  2. EmilioEsposito commented on Sep 4, 2026

    @EmilioEsposito

    Current stable reproduction (macOS, OpenRouter)

    I reproduced this on the current installed Desktop bundle:

    • Codex Desktop 26.901.31953
    • bundled Codex CLI/app-server 0.153.1
    • macOS 26.5.1, arm64
    • custom OpenRouter Responses provider

    Disposable reproduction:

    1. From a parent task, call create_thread with a trivial prompt.
    2. The child task immediately enters systemError before any assistant output.
    3. Send a second trivial prompt with send_message_to_thread.
    4. The second turn fails the same way.

    The redacted child rollout contains these two app-server-authored items:

    {"type":"function_call_output","id":"fco_...","name":"create_thread","namespace":"codex_app","output":"..."}
    {"type":"function_call_output","id":"fco_...","name":"send_message_to_thread","namespace":"codex_app","output":"..."}

    Neither item has call_id. Each is immediately followed by invalid_prompt: Invalid Responses API request; the provider validation detail includes path: ["call_id"] and expected string, received undefined.

    This confirms the regression persists in stable 0.153.1 and, in this environment, affects the first turn of an agent-created child as well as a subsequent cross-task send. No accumulated project/tool history is needed.

    The public Responses contract requires function outputs to include the matching call_id: https://developers.openai.com/api/docs/guides/migrate-to-responses#incremental-rollout-checklist

    At current main commit a07158c7846e5cb6684216d779598e540998f295, the non-OpenAI compatibility branch still clears internal metadata and encrypted function arguments but does not normalize a FunctionCallOutput whose call_id is None:

    fn build_responses_request(
    &self,
    prompt: &Prompt,
    model_info: &ModelInfo,
    effort: Option<ReasoningEffortConfig>,
    summary: ReasoningSummaryConfig,
    service_tier: Option<String>,
    responses_metadata: &CodexResponsesMetadata,
    ) -> Result<ResponsesApiRequest> {
    let mut input = prompt.get_formatted_input_for_request(model_info.use_responses_lite);
    let is_openai = self.state.provider.info().is_openai();
    let (instructions, tools) = if model_info.use_responses_lite {
    // These prompt-only items are rebuilt on every request. Hash their visible payloads
    // within the thread so retries and resumed sessions preserve their identity.
    let prefix_namespace = Uuid::new_v5(
    &Uuid::NAMESPACE_OID,
    self.state.thread_id.to_string().as_bytes(),
    );
    let tools = if self.state.provider.capabilities().namespace_tools {
    create_tools_json_for_responses_lite(&prompt.tools)?
    } else {
    create_tools_json_for_responses_api(&prompt.tools)?
    };
    let mut prefix = vec![ResponseItem::AdditionalTools {
    id: Some(ResponseItemId::with_suffix(
    "at",
    Uuid::new_v5(&prefix_namespace, &serde_json::to_vec(&tools)?),
    )),
    role: "developer".to_string(),
    tools,
    }];
    if !prompt.base_instructions.text.is_empty() {
    let mut instructions = ContextualUserFragment::into(BaseInstructionsFragment(
    prompt.base_instructions.text.clone(),
    ));
    instructions.set_id(Some(ResponseItemId::with_suffix(
    "msg",
    Uuid::new_v5(&prefix_namespace, prompt.base_instructions.text.as_bytes()),
    )));
    prefix.push(instructions);
    }
    input.splice(0..0, prefix);
    (String::new(), None)
    } else {
    (
    prompt.base_instructions.text.clone(),
    Some(create_tools_raw_json_for_responses_api(&prompt.tools)?.into()),
    )
    };
    if !is_openai {
    for item in &mut input {
    item.clear_internal_chat_message_metadata_passthrough();
    if let ResponseItem::FunctionCall {
    encrypted_function_args,
    ..
    } = item
    {
    *encrypted_function_args = None;
    }
    }

    This appears to be the same provider-boundary issue described in #42376.

  3. suntaoathome commented on Sep 10, 2026

    @suntaoathome

    Additional CLI /btw reproduction and tested compatibility workaround

    Adding a CLI reproduction and a locally tested patch to this existing cross-thread issue. This is also related to #42088 and #43944.

    Environment: Linux x86_64, source-built Codex, a third-party provider configured with wire_api = "responses". The same construction is present in upstream commit a62e98d18c6550e3bea152ed1b89d1e931dca961; the patch below is based on that commit.

    Reproduction and cause

    1. Start a main CLI thread and a /btw thread.
    2. Deliver a message to the main thread using send_message_to_thread.
    3. The receiver sends a named function_call_output with no call_id, and the affected provider rejects it before inference:
    HTTP 400: Invalid Value: 'input.call_id'. Function call output requires call_id.
    

    This originates inside Codex, not from prompt contents or a proxy removing the field:

    The public app-server reproduction requires only turn/start with an existing threadId, input: [], and:

    {
      "toolOutput": {
        "name": "send_message_to_thread",
        "namespace": "codex_tui",
        "output": "A background thread finished."
      }
    }

    Candidate compatibility approach

    At the provider-request boundary, project each named unpaired notification into a synthetic function_call immediately followed by its matching function_call_output. Keep the name/namespace on the call and preserve the output content. Derive stable IDs from the source item ID, with a positional fallback for older ID-less history.

    The attached patch applies this only in the existing non-OpenAI provider branch. It leaves native OpenAI behavior, already-paired tool outputs, and stored history unchanged. The synthetic call is request context only: it is not executed. It also avoids promoting tool content to user/developer authority.

    This is a tested compatibility workaround for maintainers to evaluate, not a claim that every provider supports the same behavior. A provider capability may be a better long-term selection mechanism. Simply inserting a random call_id would neither establish a matching call nor preserve request identity across retries.

    Validation

    • Independent small synthetic requests against the affected provider: original unpaired representation -> HTTP 400; the same content as a matched call/result pair -> HTTP 200, response status completed. No private project data was used.
    • just test -p codex-api: 183 passed, including new structured-content, stable-ID, duplicate ID-less notification, idempotence, and existing-call preservation tests.
    • just test -p codex-app-server --test all -E 'test(tool_output_compatibility) or test(thread_inject_items_adds_raw_response_items)': 5 passed, covering compatible-provider delivery, unchanged OpenAI delivery, and legacy/paginated history injection.
    • 44 WebSocket tests passed, including the new test that verifies paired notification delivery still reuses incremental input and previous_response_id.
    • Scoped API Clippy and repository formatting completed successfully.

    Validation limits: the unmodified aggregate core test target at this base commit fails to compile because core/tests/suite/hooks.rs:1673 calls the now-three-argument fork_thread API with five arguments. The 44 WebSocket tests were therefore run through a temporary standalone test entry point importing the existing WebSocket suite. No complete workspace test pass is claimed. just bazel-lock-update was attempted but blocked by a connection timeout fetching the pinned V8 source archive; the attached patch has no regenerated Bazel lockfile.

    Focused WebSocket verification entry point

    Temporarily place the following in codex-rs/core/tests/btw_transport_verification.rs, then run just test -p codex-core --test btw_transport_verification from codex-rs. The wrapper was removed after verification and is not part of the patch.

    pub use codex_protocol::error;
    #[path = "suite/client_websockets.rs"]
    mod client_websockets;
    Complete local patch with regression tests (10 files; based on a62e98d)
    diff --git a/codex-rs/app-server/tests/suite/v2/mod.rs b/codex-rs/app-server/tests/suite/v2/mod.rs
    index 4846897d71..6f4ae1589e 100644
    --- a/codex-rs/app-server/tests/suite/v2/mod.rs
    +++ b/codex-rs/app-server/tests/suite/v2/mod.rs
    @@ -127,6 +127,8 @@ mod thread_status;
     mod thread_timeline;
     mod thread_unarchive;
     mod thread_unsubscribe;
    +#[path = "tool_output_compatibility_tests.rs"]
    +mod tool_output_compatibility;
     mod turn_cost_otel;
     mod turn_interrupt;
     mod turn_settings_update;
    diff --git a/codex-rs/app-server/tests/suite/v2/thread_inject_items.rs b/codex-rs/app-server/tests/suite/v2/thread_inject_items.rs
    index 972cf70347..ae4027ad66 100644
    --- a/codex-rs/app-server/tests/suite/v2/thread_inject_items.rs
    +++ b/codex-rs/app-server/tests/suite/v2/thread_inject_items.rs
    @@ -281,9 +281,32 @@ async fn thread_inject_items_adds_raw_response_items_to_thread_history(
             injected_index < user_prompt_index,
             "injected items should be sent before the user prompt"
         );
    -    assert!(
    -        model_input.contains(&named_tool_output),
    -        "named unpaired tool output should be sent in the next model request"
    +    let output_index = model_input
    +        .iter()
    +        .position(|item| {
    +            item["type"] == "function_call_output" && item["output"] == named_tool_output["output"]
    +        })
    +        .context("named notification should be sent in the next model request")?;
    +    assert!(output_index > 0);
    +    let call_id = model_input[output_index - 1]["call_id"]
    +        .as_str()
    +        .context("notification must have a matching call")?;
    +    assert_eq!(
    +        &model_input[output_index - 1..=output_index],
    +        &[
    +            json!({
    +                "type": "function_call",
    +                "name": "send_message_to_thread",
    +                "namespace": "codex_app",
    +                "arguments": "{}",
    +                "call_id": call_id,
    +            }),
    +            json!({
    +                "type": "function_call_output",
    +                "call_id": call_id,
    +                "output": named_tool_output["output"],
    +            }),
    +        ]
         );
     
         let delegated_mock = responses::mount_sse_once(
    diff --git a/codex-rs/app-server/tests/suite/v2/tool_output_compatibility_tests.rs b/codex-rs/app-server/tests/suite/v2/tool_output_compatibility_tests.rs
    new file mode 100644
    index 0000000000..2cd782fd85
    --- /dev/null
    +++ b/codex-rs/app-server/tests/suite/v2/tool_output_compatibility_tests.rs
    @@ -0,0 +1,111 @@
    +use anyhow::Context;
    +use anyhow::Result;
    +use app_test_support::MockResponsesConfig;
    +use app_test_support::TestAppServer;
    +use codex_app_server_protocol::ThreadStartParams;
    +use codex_app_server_protocol::ThreadStartResponse;
    +use codex_app_server_protocol::TurnStartParams;
    +use codex_app_server_protocol::TurnStartResponse;
    +use codex_app_server_protocol::TurnToolOutput;
    +use codex_protocol::models::FunctionCallOutputBody;
    +use core_test_support::responses;
    +use pretty_assertions::assert_eq;
    +use serde_json::json;
    +use tempfile::TempDir;
    +use test_case::test_case;
    +use tokio::time::timeout;
    +
    +#[test_case("Mock provider for test"; "compatible")]
    +#[test_case("OpenAI"; "native")]
    +#[tokio::test]
    +async fn delegated_turn_tool_output_respects_provider(provider_name: &str) -> Result<()> {
    +    let server = responses::start_mock_server().await;
    +    let response = responses::mount_sse_once(
    +        &server,
    +        responses::sse(vec![responses::ev_completed("delegated-response")]),
    +    )
    +    .await;
    +    let codex_home = TempDir::new()?;
    +    MockResponsesConfig::new(&server.uri())
    +        .with_provider_name(provider_name)
    +        .write(codex_home.path())?;
    +    let mut app = TestAppServer::builder()
    +        .with_codex_home(codex_home.path())
    +        .build_initialized()
    +        .await?;
    +    let request = app
    +        .send_thread_start_request_with_auto_env(ThreadStartParams {
    +            model: Some("mock-model".to_string()),
    +            ..Default::default()
    +        })
    +        .await?;
    +    let ThreadStartResponse { thread, .. } = app.read_response(request).await?;
    +    let output = "<codex_delegation>A background thread finished.</codex_delegation>";
    +    let request = app
    +        .send_turn_start_request(TurnStartParams {
    +            thread_id: thread.id,
    +            input: Vec::new(),
    +            tool_output: Some(Box::new(TurnToolOutput {
    +                name: "send_message_to_thread".to_string(),
    +                namespace: Some("codex_tui".to_string()),
    +                output: FunctionCallOutputBody::Text(output.to_string()),
    +            })),
    +            ..Default::default()
    +        })
    +        .await?;
    +    let _: TurnStartResponse = app.read_response(request).await?;
    +    timeout(
    +        std::time::Duration::from_secs(10),
    +        app.read_stream_until_notification_message("turn/completed"),
    +    )
    +    .await??;
    +
    +    let input = response
    +        .single_request()
    +        .input()
    +        .into_iter()
    +        .map(responses::strip_metadata_from_json)
    +        .collect::<Vec<_>>();
    +    let output_index = input
    +        .iter()
    +        .position(|item| item["type"] == "function_call_output" && item["output"] == output)
    +        .context("delegated tool output must reach the provider")?;
    +    if provider_name == "OpenAI" {
    +        assert_eq!(
    +            input[output_index],
    +            json!({
    +                "type": "function_call_output",
    +                "id": input[output_index]["id"],
    +                "name": "send_message_to_thread",
    +                "namespace": "codex_tui",
    +                "output": output,
    +            })
    +        );
    +        assert!(!input.iter().any(|item| item["type"] == "function_call"));
    +        return Ok(());
    +    }
    +    assert!(output_index > 0, "tool output must have a preceding call");
    +    let call = &input[output_index - 1];
    +    let call_id = call["call_id"].as_str().context("call must have an ID")?;
    +    assert!(!call_id.is_empty());
    +    assert_eq!(
    +        &input[output_index - 1..=output_index],
    +        &[
    +            json!({
    +                "type": "function_call",
    +                "id": call["id"],
    +                "name": "send_message_to_thread",
    +                "namespace": "codex_tui",
    +                "arguments": "{}",
    +                "call_id": call_id,
    +            }),
    +            json!({
    +                "type": "function_call_output",
    +                "id": input[output_index]["id"],
    +                "call_id": call_id,
    +                "output": output,
    +            }),
    +        ]
    +    );
    +    Ok(())
    +}
    diff --git a/codex-rs/codex-api/Cargo.toml b/codex-rs/codex-api/Cargo.toml
    index 01cacbe2b4..82a5c50ce3 100644
    --- a/codex-rs/codex-api/Cargo.toml
    +++ b/codex-rs/codex-api/Cargo.toml
    @@ -28,7 +28,7 @@ eventsource-stream = { workspace = true }
     regex-lite = { workspace = true }
     tokio-util = { workspace = true, features = ["codec", "io"] }
     url = { workspace = true }
    -uuid = { workspace = true }
    +uuid = { workspace = true, features = ["v5"] }
     
     [dev-dependencies]
     anyhow = { workspace = true }
    diff --git a/codex-rs/codex-api/src/lib.rs b/codex-rs/codex-api/src/lib.rs
    index 92507807f6..c36508a819 100644
    --- a/codex-rs/codex-api/src/lib.rs
    +++ b/codex-rs/codex-api/src/lib.rs
    @@ -12,6 +12,7 @@ pub(crate) mod safety_buffering;
     pub(crate) mod search;
     pub(crate) mod sse;
     pub(crate) mod telemetry;
    +mod tool_output_compatibility;
     
     pub use crate::requests::headers::build_session_headers;
     pub use codex_client::RequestTelemetry;
    @@ -117,5 +118,6 @@ pub use crate::search::TimeOperation;
     pub use crate::search::WeatherOperation;
     pub use crate::telemetry::SseTelemetry;
     pub use crate::telemetry::WebsocketTelemetry;
    +pub use crate::tool_output_compatibility::pair_unpaired_function_call_outputs;
     pub use codex_protocol::protocol::RealtimeAudioFrame;
     pub use codex_protocol::protocol::RealtimeEvent;
    diff --git a/codex-rs/codex-api/src/tool_output_compatibility.rs b/codex-rs/codex-api/src/tool_output_compatibility.rs
    new file mode 100644
    index 0000000000..ced9185518
    --- /dev/null
    +++ b/codex-rs/codex-api/src/tool_output_compatibility.rs
    @@ -0,0 +1,55 @@
    +use codex_protocol::ResponseItemId;
    +use codex_protocol::models::ResponseItem;
    +use uuid::Uuid;
    +
    +/// Projects named notifications into call/result pairs for Responses providers
    +/// that require every function result to reference a call. Only request copies
    +/// should be passed here: the synthetic calls are not executed or persisted.
    +pub fn pair_unpaired_function_call_outputs(items: &mut Vec<ResponseItem>) {
    +    if !items.iter().any(|item| {
    +        matches!(item, ResponseItem::FunctionCallOutput { call_id: None, name: Some(name), .. } if !name.is_empty())
    +    }) {
    +        return;
    +    }
    +
    +    for (index, mut item) in std::mem::take(items).into_iter().enumerate() {
    +        if let ResponseItem::FunctionCallOutput {
    +            id,
    +            call_id,
    +            name,
    +            namespace,
    +            ..
    +        } = &mut item
    +            && call_id.is_none()
    +            && let Some(function_name) = name.as_ref().filter(|name| !name.is_empty())
    +        {
    +            // Persisted item IDs keep the projection stable across retries,
    +            // resume, and prefix truncation. Older ID-less history uses its
    +            // position, which also distinguishes identical notifications.
    +            let source = id
    +                .as_ref()
    +                .map_or_else(|| format!("position:{index}"), |id| format!("item:{id}"));
    +            let uuid = Uuid::new_v5(
    +                &Uuid::NAMESPACE_OID,
    +                format!("codex:unpaired-function-output:{source}").as_bytes(),
    +            );
    +            let paired_call_id = format!("call_{}", uuid.simple());
    +            items.push(ResponseItem::FunctionCall {
    +                id: Some(ResponseItemId::with_suffix("fc", uuid)),
    +                name: function_name.clone(),
    +                namespace: namespace.take(),
    +                arguments: "{}".to_string(),
    +                encrypted_function_args: None,
    +                call_id: paired_call_id.clone(),
    +                internal_chat_message_metadata_passthrough: None,
    +            });
    +            *call_id = Some(paired_call_id);
    +            *name = None;
    +        }
    +        items.push(item);
    +    }
    +}
    +
    +#[cfg(test)]
    +#[path = "tool_output_compatibility_tests.rs"]
    +mod tests;
    diff --git a/codex-rs/codex-api/src/tool_output_compatibility_tests.rs b/codex-rs/codex-api/src/tool_output_compatibility_tests.rs
    new file mode 100644
    index 0000000000..5912d73ce3
    --- /dev/null
    +++ b/codex-rs/codex-api/src/tool_output_compatibility_tests.rs
    @@ -0,0 +1,107 @@
    +use super::pair_unpaired_function_call_outputs;
    +use codex_protocol::models::ResponseItem;
    +use pretty_assertions::assert_eq;
    +use serde_json::Value;
    +use serde_json::json;
    +
    +#[test]
    +fn pairs_notifications_without_changing_tool_result_content() {
    +    for output in [
    +        json!("A background thread finished."),
    +        json!([
    +            {"type": "input_text", "text": "See the attached image."},
    +            {"type": "input_image", "image_url": "data:image/png;base64,aGVsbG8="}
    +        ]),
    +    ] {
    +        let notification = json!({
    +            "type": "function_call_output",
    +            "id": "fco_notification",
    +            "name": "send_message_to_thread",
    +            "namespace": "codex_tui",
    +            "output": output,
    +        });
    +        let mut items: Vec<ResponseItem> =
    +            serde_json::from_value(json!([notification.clone()])).unwrap();
    +        pair_unpaired_function_call_outputs(&mut items);
    +        let actual = serde_json::to_value(&items).unwrap();
    +        let call_id = actual[0]["call_id"].as_str().unwrap();
    +        assert!(!call_id.is_empty());
    +        assert_eq!(
    +            actual,
    +            json!([
    +                {
    +                    "type": "function_call",
    +                    "id": actual[0]["id"],
    +                    "name": "send_message_to_thread",
    +                    "namespace": "codex_tui",
    +                    "arguments": "{}",
    +                    "call_id": call_id,
    +                },
    +                {
    +                    "type": "function_call_output",
    +                    "id": "fco_notification",
    +                    "call_id": call_id,
    +                    "output": output,
    +                }
    +            ])
    +        );
    +        let original: ResponseItem = serde_json::from_value(notification).unwrap();
    +        let mut repeated = vec![original.clone()];
    +        pair_unpaired_function_call_outputs(&mut repeated);
    +        assert_eq!(items, repeated);
    +        pair_unpaired_function_call_outputs(&mut repeated);
    +        assert_eq!(items, repeated, "projection must be idempotent");
    +
    +        // Moving an identified notification does not change its wire IDs.
    +        let mut prefixed: Vec<ResponseItem> = serde_json::from_value(json!([
    +            {"type": "message", "role": "user", "content": []}
    +        ]))
    +        .unwrap();
    +        prefixed.push(original);
    +        pair_unpaired_function_call_outputs(&mut prefixed);
    +        assert_eq!(&prefixed[1..], items.as_slice());
    +    }
    +}
    +
    +#[test]
    +fn idless_duplicates_get_distinct_stable_pairs_without_rewriting_a_prefix() {
    +    let original: Vec<ResponseItem> = serde_json::from_value(json!([
    +        {"type": "function_call_output", "name": "notify", "output": "same"},
    +        {"type": "function_call_output", "name": "notify", "output": "same"}
    +    ]))
    +    .unwrap();
    +    let mut first = original[..1].to_vec();
    +    pair_unpaired_function_call_outputs(&mut first);
    +    let mut both = original;
    +    pair_unpaired_function_call_outputs(&mut both);
    +    assert_eq!(first.as_slice(), &both[..2]);
    +    let json = serde_json::to_value(&both).unwrap();
    +    assert_ne!(json[0]["call_id"], json[2]["call_id"]);
    +    assert_eq!(json[0]["call_id"], json[1]["call_id"]);
    +    assert_eq!(json[2]["call_id"], json[3]["call_id"]);
    +}
    +
    +#[test]
    +fn preserves_existing_calls_results_and_messages() {
    +    let original: Vec<ResponseItem> = serde_json::from_value(json!([
    +        {"type": "message", "role": "user", "content": []},
    +        {"type": "function_call", "call_id": "real", "name": "run", "arguments": "{}"},
    +        {"type": "function_call_output", "call_id": "real", "output": "done"},
    +        {"type": "custom_tool_call", "call_id": "custom", "name": "edit", "input": "patch"},
    +        {"type": "custom_tool_call_output", "call_id": "custom", "output": "done"}
    +    ]))
    +    .unwrap();
    +    let notification: ResponseItem = serde_json::from_value(json!({
    +        "type": "function_call_output", "name": "notify", "output": "new"
    +    }))
    +    .unwrap();
    +    let mut items = original.clone();
    +    pair_unpaired_function_call_outputs(&mut items);
    +    assert_eq!(items, original);
    +    items.push(notification);
    +    pair_unpaired_function_call_outputs(&mut items);
    +    assert_eq!(&items[..original.len()], original.as_slice());
    +    assert_eq!(items.len(), original.len() + 2);
    +    let serialized: Value = serde_json::to_value(items).unwrap();
    +    assert_eq!(serialized[original.len() + 1]["output"], "new");
    +}
    diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs
    index 8d2db30d7b..1856b547f1 100644
    --- a/codex-rs/core/src/client.rs
    +++ b/codex-rs/core/src/client.rs
    @@ -807,6 +807,7 @@ impl ModelClient {
                 )
             };
             if !is_openai {
    +            codex_api::pair_unpaired_function_call_outputs(&mut input);
                 for item in &mut input {
                     item.clear_internal_chat_message_metadata_passthrough();
                     if let ResponseItem::FunctionCall {
    diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs
    index afe211268f..698b40bce6 100755
    --- a/codex-rs/core/tests/suite/client_websockets.rs
    +++ b/codex-rs/core/tests/suite/client_websockets.rs
    @@ -72,6 +72,9 @@ use tempfile::TempDir;
     use tracing::Instrument;
     use tracing_test::traced_test;
     
    +#[path = "client_websockets_tool_output_tests.rs"]
    +mod tool_output_compatibility;
    +
     const MODEL: &str = "gpt-5.4";
     const OPENAI_BETA_HEADER: &str = "OpenAI-Beta";
     const USER_AGENT_HEADER: &str = "user-agent";
    diff --git a/codex-rs/core/tests/suite/client_websockets_tool_output_tests.rs b/codex-rs/core/tests/suite/client_websockets_tool_output_tests.rs
    new file mode 100644
    index 0000000000..50c03608e5
    --- /dev/null
    +++ b/codex-rs/core/tests/suite/client_websockets_tool_output_tests.rs
    @@ -0,0 +1,71 @@
    +use super::prompt_with_input;
    +use super::stream_until_complete;
    +use super::websocket_harness;
    +use core_test_support::responses::ev_completed;
    +use core_test_support::responses::ev_response_created;
    +use core_test_support::responses::start_websocket_server;
    +use pretty_assertions::assert_eq;
    +use serde_json::json;
    +
    +#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    +async fn pairs_notifications_without_breaking_websocket_incremental_input() {
    +    let server = start_websocket_server(vec![vec![
    +        vec![ev_response_created("resp-1"), ev_completed("resp-1")],
    +        vec![ev_response_created("resp-2"), ev_completed("resp-2")],
    +    ]])
    +    .await;
    +    let harness = websocket_harness(&server).await;
    +    let mut session = harness.client.new_session();
    +    let original = json!([
    +        {
    +            "type": "function_call_output",
    +            "id": "fco_first",
    +            "name": "send_message_to_thread",
    +            "namespace": "codex_tui",
    +            "output": "first notification",
    +        },
    +        {
    +            "type": "function_call_output",
    +            "id": "fco_second",
    +            "name": "send_message_to_thread",
    +            "namespace": "codex_tui",
    +            "output": "second notification",
    +        }
    +    ]);
    +    let first_prompt =
    +        prompt_with_input(vec![serde_json::from_value(original[0].clone()).unwrap()]);
    +    let second_prompt = prompt_with_input(serde_json::from_value(original.clone()).unwrap());
    +    stream_until_complete(&mut session, &harness, &first_prompt).await;
    +    stream_until_complete(&mut session, &harness, &second_prompt).await;
    +
    +    let connection = server.single_connection();
    +    assert_eq!(connection.len(), 2);
    +    let first = connection[0].body_json();
    +    let second = connection[1].body_json();
    +    assert_eq!(second["previous_response_id"], "resp-1");
    +    for (index, request) in [first, second].into_iter().enumerate() {
    +        let call_id = request["input"][0]["call_id"].as_str().unwrap();
    +        assert!(!call_id.is_empty());
    +        assert_eq!(
    +            request["input"],
    +            json!([
    +                {
    +                    "type": "function_call",
    +                    "id": request["input"][0]["id"],
    +                    "name": "send_message_to_thread",
    +                    "namespace": "codex_tui",
    +                    "arguments": "{}",
    +                    "call_id": call_id,
    +                },
    +                {
    +                    "type": "function_call_output",
    +                    "id": original[index]["id"],
    +                    "call_id": call_id,
    +                    "output": original[index]["output"],
    +                }
    +            ])
    +        );
    +    }
    +    assert_eq!(serde_json::to_value(second_prompt.input).unwrap(), original);
    +    server.shutdown().await;
    +}

    Private conversation content, credentials, provider addresses, local machine paths, and author email metadata have been omitted.

  4. bjdx8j4zm5-source commented on Sep 12, 2026

    @bjdx8j4zm5-source

    Workaround (verified): deliver the trigger the way it was delivered before e56e4922eb

    Same setup as reported here (Windows, Codex Desktop, wire_api = "responses", DeepSeek).
    We hit both halves of the failure: the automation never completed a single run, and the
    target thread became permanently unusable — every later user message returned the same
    HTTP 400.

    As @argszero traced above, the trigger used to arrive as a user message; since
    e56e4922eb it arrives as a standalone function_call_output with no call_id. And as
    @njwangcn pointed out, populating call_id alone is not a fix either — there is no
    matching function_call to pair it with.

    So rather than trying to make the item valid, add a local passthrough proxy that rewrites
    it back into the old form before it reaches the provider:

    # every function_call_output without call_id -> plain user message with the same text
    {"type": "function_call_output", "id": "fco_…", "name": "automation_update",
     "namespace": "codex_app", "output": "<heartbeat>…</heartbeat>"}
    # becomes
    {"type": "message", "role": "user",
     "content": [{"type": "input_text", "text": "<heartbeat>…</heartbeat>"}]}

    Everything else — tool calls, reasoning items, streaming — is forwarded unchanged.

    [model_providers.deepseek]
    base_url = "http://127.0.0.1:19100/"   # local shim -> api.deepseek.com
    wire_api = "responses"

    Verified end to end:

    test result
    request containing an orphan function_call_output, sent directly to api.deepseek.com 400 missing field 'call_id'
    identical request through the shim 200, 27 SSE events, clean response.completed
    real codex exec run with the shim as base_url 200, normal model reply
    GET /models and a non-streaming POST /responses 200

    Outcome: the automation actually runs instead of dying on its first trigger, and no
    malformed item is ever persisted — so the "permanently bricked thread" failure mode
    disappears.

    For threads that are already bricked, the same repo ships a repair script that removes
    the orphan outputs from both the rollout JSONL and thread_history_1.sqlite
    (thread_items), realigns thread_history_projection_state, and backs everything up
    before touching it (dry-run by default). Restart Codex afterwards.

    Code + write-up: https://github.com/bjdx8j4zm5-source/codex-strict-responses-fix

    Caveat: this is a client-side workaround, not an app-server fix. The proper fix is either
    attaching a real call_id with a matching function_call, or going back to
    user-message delivery for injected triggers.


    中文版

    同样的环境(Windows + Codex 桌面版 + wire_api = "responses" + DeepSeek)。我们遇到了这个
    问题的两半:自动化一次都没成功运行过,而且目标会话被永久搞坏——之后每条消息都返回同样的
    HTTP 400。

    正如 @argszero 上面定位的:触发内容以前是以 user 消息下发的;e56e4922eb 之后改成
    独立的 function_call_output,且不带 call_id。而 @njwangcn 说得对:只补 call_id 也
    不行——它没有配对的 function_call。

    所以不去"修正"这条记录,而是加一个本地透传代理,把它改回旧格式再发给服务商:

    # 每个缺 call_id 的 function_call_output -> 内容相同的普通 user 消息
    {"type": "function_call_output", "id": "fco_…", "name": "automation_update",
     "namespace": "codex_app", "output": "<heartbeat>…</heartbeat>"}
    # 变成
    {"type": "message", "role": "user",
     "content": [{"type": "input_text", "text": "<heartbeat>…</heartbeat>"}]}

    其余内容(工具调用、reasoning、流式响应)原样透传。

    [model_providers.deepseek]
    base_url = "http://127.0.0.1:19100/"   # 本地代理 -> api.deepseek.com
    wire_api = "responses"

    端到端验证:

    测试 结果
    含孤儿 function_call_output 的请求,直连 api.deepseek.com 400 missing field 'call_id'
    同一请求走代理 200,27 个 SSE 事件,正常 response.completed
    真实 codex exec 以代理为 base_url 200,模型正常回复
    GET /models 与非流式 POST /responses 200

    结果:自动化能真正跑起来(而不是在第一次触发就死掉),并且不会再写入坏记录,因此
    "会话永久损坏"这个失败模式消失。

    对于已经坏掉的会话,同一个仓库里有修复脚本:从 rollout JSONL 和
    thread_history_1.sqlite(thread_items)里删除孤儿输出、校正
    thread_history_projection_state 偏移,改动前自动备份(默认 dry-run),修完重启
    Codex 即可。

    代码与说明:https://github.com/bjdx8j4zm5-source/codex-strict-responses-fix

    说明:这是客户端绕过方案,不是 app-server 的修复。官方正确修法是:补上真实的 call_id
    并配对 function_call,或让注入的触发内容改回 user 消息投递。

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

    appapp-serverbugcustom-modelwindows-os

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions