Skip to content

Responses Phase 2: tool passthrough so Codex can drive its own tools - #63

Merged
FMXExpress merged 1 commit into
claude/pr62-responses-streamingfrom
claude/pr63-responses-tools-passthrough
May 28, 2026
Merged

FMXExpress merged 1 commit into
claude/pr62-responses-streamingfrom
claude/pr63-responses-tools-passthrough

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Phase 2 of /v1/responses. Stacked on PR #62 (streaming). When #62 lands, this PR's base auto-rebases to main.

Why this exists

PR #62 fixed the SSE event shape so Codex stops crashing on the response — but PasClaw was still running its internal tool loop. Codex defines apply_patch / shell_command / mcp__Kai__* tools and expects to execute them itself via function_call output items. With #62 only, the model's tool attempts vanished into PasClaw's fs_ / shell_ / skills_ handlers and Codex never saw them — read-only questions worked, agentic tasks didn't.

What this PR ships

Tools parsing

request.tools[] → TToolDefinitionArray (function-type entries forwarded to the provider) + ToolsRawJSON (verbatim echo for response.tools). Custom-type tools (Codex's grammar-constrained apply_patch) skipped at the provider boundary — neither Anthropic nor OpenAI Chat-Completions support Lark-grammar output constraints, and proper plumbing would need provider-side changes well out of scope. They still appear in the echoed tools field so the SDK validator doesn't trip; the model just won't structure-emit them.

Input-item parsing

Extended to handle three types:

Item type Becomes
message (existing) mrUser / mrAssistant / mrSystem / mrTool TMessage with text
function_call mrAssistant TMessage with a single TToolCall carrying call_id, name, arguments
function_call_output mrTool TMessage with ToolCallId = call_id and Content = output

Unknown types (reasoning, image, computer_call, …) logged at debug and skipped.

Branched execution

HasFunctionTools = True  → Provider.Chat(Msgs, ToolDefs, Model, Options)
                           Single round-trip. No internal tool loop.
                           No BuildSystemPrompt either (Codex sends
                           its own developer message + AGENTS.md;
                           injecting PasClaw's identity preamble
                           on top confuses the model).
otherwise                → existing RunToolLoop path (unchanged for
                           non-Codex flows like
                           curl /v1/responses -d '{"input":"hi"}').

Response shape extensions

BuildResponsesObject now accepts ToolCalls + ToolsRawJSON. Each tool call produces a function_call output item via the new FunctionCallItemJSON helper:

{
  "id":        "fc_<resp-suffix>_<n>",
  "type":      "function_call",
  "status":    "completed",
  "call_id":   "<tool call id from model>",
  "name":      "<func name>",
  "arguments": "<raw json string>"
}

response.tools is now the echoed ToolsRawJSON (or [] if absent).

Streaming events

EmitResponsesStream now emits a function_call sub-sequence per tool call, after any message sub-sequence:

event: response.output_item.added              { function_call in_progress, args="" }
event: response.function_call_arguments.delta  { full args, one delta }
event: response.function_call_arguments.done
event: response.output_item.done               { function_call completed with args }

All event helpers gained an OutputIdx parameter so output_index tracks which item we're inside (message at 0, function_calls following). Two new helpers (FunctionCallArgsDeltaEvent / FunctionCallArgsDoneEvent) serialize the args-streaming events with the same sequence_number discipline as the text events.

Codex test path after this lands

POST /v1/responses {stream:true, tools:[…], input:[…user…]}
  → tools parsed; function tools forwarded; custom skipped
  → Provider.Chat() single shot
  → if model emits text only: standard text sub-sequence
     (Codex displays the answer)
  → if model emits function_call: function_call sub-sequence
     (Codex executes the tool, posts function_call_output back
     on the next turn)
  → multi-turn agentic loop works end-to-end

Known limitations

  • Single delta still — the synchronous Chat() doesn't expose incremental output deltas. Real partial streaming will land in a follow-up that hooks the provider's OnChunk callback.
  • Custom-type tools (Codex's apply_patch) not forwarded. Documented above. Codex degrades to "model writes apply_patch text directly" for those, which it can usually still handle as a fallback.
  • No tool_choice plumbing — Codex sends "tool_choice":"auto" and we don't translate it to the provider. The default behaviour matches auto anyway, so no observable regression, but explicit "required" / "none" requests won't be honored.

Test plan

  • pasclaw serve + Codex CLI → ask "create a file foo.txt with 'hi' in it" → model emits a shell_command or apply_patch tool call → Codex executes locally → on the next turn the model gets the output and confirms
  • Same setup, ask a read-only question ("what's in pasclaw.dpr?") → still works (Codex reads via its shell_command tool, PasClaw doesn't intercept)
  • curl -N -X POST .../v1/responses -d '{"model":"…","input":"hi","stream":true}' (no tools) → uses the legacy path, internal tool loop runs as before, single text response
  • curl ... -d '{"model":"…","input":"hi","tools":[{"type":"function","name":"f","description":"x","parameters":{"type":"object"}}],"stream":false}' (one tool, no stream) → JSON response with output: [function_call?, message?] depending on what the model decides
  • Multi-turn: follow-up request includes a previous function_call_output input item → AppendToolResult produces a properly-shaped mrTool message, the model uses it
  • Existing /v1/chat and /v1/chat/completions endpoints unchanged

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

After Phase A (#62) PasClaw's /v1/responses handler emitted parseable
SSE events but ran an internal tool loop — Codex CLI's tool
definitions and tool execution lived only client-side, so the model's
function_call attempts vanished into PasClaw's fs_/shell_/skills/
handlers instead of reaching Codex. Codex would receive text but
never have its `apply_patch` / `shell_command` / `mcp__Kai__*` tools
invoked, which is the whole point of running it.

This PR adds the passthrough path:

  1. Parse request.tools[] -> TToolDefinitionArray of function-type
     tools, plus ToolsRawJSON capturing the verbatim array for echo
     in response.tools.

     Custom-type tools (Codex's grammar-constrained apply_patch)
     are skipped at the provider boundary -- Anthropic / OpenAI
     Chat-Completions don't natively support Lark-grammar output
     constraints -- but they still appear in ToolsRawJSON so the
     SDK validator doesn't trip. The model just won't attempt
     them; the user-visible degradation is "model writes
     apply_patch text directly instead of as a structured tool
     call." Proper custom-tool support would require provider-
     side grammar plumbing that's well out of scope.

  2. Extend input-item parsing to handle function_call and
     function_call_output items in addition to the existing
     message items.

       function_call         -> synthesize an mrAssistant TMessage
                                carrying a single TToolCall with
                                call_id, name, arguments. One per
                                item; consecutive ones group fine
                                with Anthropic / OpenAI's tolerant
                                multi-assistant-message handling.
       function_call_output  -> mrTool TMessage with ToolCallId =
                                call_id and Content = output.
                                Provider request builders match
                                tool_result blocks by this id.

     Unknown item types (reasoning, image, computer_call, …) are
     logged at debug and skipped. Phase 2 covers the two Codex
     needs; the rest are future scope.

  3. Branch the execution path:
       HasFunctionTools = True  -> FProvider.Chat(Msgs, ToolDefs,
                                   Model, Options). Single round-
                                   trip. No internal tool loop.
                                   No BuildSystemPrompt either,
                                   because Codex sends its own
                                   developer message + AGENTS.md
                                   and injecting a PasClaw identity
                                   preamble on top confuses the
                                   model.
       otherwise                -> existing RunToolLoop path
                                   (unchanged behaviour for non-
                                   Codex flows like
                                   curl /v1/responses -d
                                   '{"input":"hi"}').

  4. Unify the output via OutContent / OutToolCalls / OutUsage
     locals so the final EmitResponsesStream / BuildResponsesObject
     call is the same shape regardless of which path produced
     them.

  5. Extend BuildResponsesObject signature to accept ToolCalls and
     ToolsRawJSON:

       function BuildResponsesObject(const Id, Model, Status,
                                     Content: string;
                                     const ToolCalls: array of
                                                      TToolCall;
                                     const ToolsRawJSON: string;
                                     Usage: TUsageInfo): TJsonObject;

     Each ToolCall produces a function_call output item via the
     new FunctionCallItemJSON helper:

       {
         "id":      "fc_<resp-suffix>_<n>",  -- item id
         "type":    "function_call",
         "status":  "completed",
         "call_id": "<tool call id from model>",
         "name":    "<func name>",
         "arguments": "<raw json string>"    -- string per schema
       }

     ToolsRawJSON, when non-empty, is pasted verbatim into the
     response.tools field; otherwise the field is "[]".

  6. Extend EmitResponsesStream to emit a function_call sub-
     sequence per tool call, after any message sub-sequence:

       response.output_item.added                { function_call in_progress, args="" }
       response.function_call_arguments.delta    { full args, one delta }
       response.function_call_arguments.done
       response.output_item.done                 { function_call completed with args }

     ItemAddedEvent / ItemDoneEvent / ContentPart*Event /
     Text*Event helpers all gain an OutputIdx parameter so the
     output_index field tracks which item we're inside; message
     events stay at index 0, function_calls follow.

     Two new helpers FunctionCallArgsDeltaEvent /
     FunctionCallArgsDoneEvent serialize the args-streaming
     events with the same sequence_number discipline as the
     text events (PR #62 review fix).

Codex test path after this lands:
  POST /v1/responses {stream:true, tools:[…], input:[…user…]}
    -> tools parsed; function tools forwarded; custom skipped
    -> Provider.Chat() single shot
    -> if model emits text only: standard text sub-sequence
       (Codex displays the answer)
    -> if model emits function_call: function_call sub-sequence
       (Codex executes the tool, posts function_call_output back
       on the next turn)
    -> multi-turn agentic loop works end-to-end

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit 71b120f into claude/pr62-responses-streaming May 28, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7dd8bdd1fa

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1753 to +1755
AppendToolResult(
InputObj.GetStr('call_id', ''),
InputObj.GetStr('output', ''));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve prior function calls for tool outputs

When a Responses client uses the normal previous_response_id flow, the follow-up request contains only a function_call_output item plus the prior response id, not the earlier function_call item. This branch appends only an mrTool message; checked the OpenAI/Anthropic chat builders, and they serialize that as a tool result without a preceding assistant tool call, which providers reject or cannot match. Please store/replay the prior function call for previous_response_id, or synthesize the assistant tool-call message before appending this tool result.

Useful? React with 👍 / 👎.

FMXExpress added a commit that referenced this pull request May 29, 2026
…ssthrough

[reopen #63] Responses Phase 2: tool passthrough so Codex can drive its own tools
FMXExpress pushed a commit that referenced this pull request May 29, 2026
Closes two of the three known limitations from PR #63's description
(custom-type grammar tools remain documented future work — that one
needs provider-side change to support Lark-grammar output
constraints that neither Anthropic nor OpenAI Chat-Completions
natively expose).

1. tool_choice forwarding
   TChatOptions gains a ToolChoice: string field, with the three
   string forms every provider can represent:

       ""         => emit nothing (provider default; typically
                     "auto" when tools are present)
       "auto"     => model decides
       "none"     => model must not call any tool
       "required" => model must call one of the tools

   Provider mappings:
     Anthropic Messages API: emits tool_choice object alongside
       tools[]. auto -> {type: "auto"}, required -> {type: "any"},
       none -> field omitted (the cleaner Anthropic convention).
     OpenAI Chat Completions: emits tool_choice as the bare string
       form ("auto" / "none" / "required") — 1:1 mapping.
     Gemini: skipped. The generateContent API has tool_config but
       the mapping is more involved; deferred until a real Gemini
       Codex-flow user shows up.

   HandleResponses reads request.tool_choice. Only the three
   string forms are accepted; the object form (force a specific
   function by name) is logged at debug and dropped — needs per-
   provider translation that's substantial enough to be its own
   PR if a client actually needs it.

2. Real partial streaming
   The passthrough+stream path now uses Provider.ChatStream with
   an OnChunk callback that emits response.output_text.delta
   events as the model produces fragments. Replaces the
   single-delta whole-text approach from PR #62. First-byte-time
   improves dramatically for streaming-capable providers
   (Anthropic streams natively; OpenAI-compat's ChatStream
   currently delegates to Chat and returns the whole text — for
   that case the new code feeds the whole text through OnChunk as
   one synthesized chunk, so the event shape stays consistent).

   New module-level event helpers Res*Evt() replace the previous
   local-inside-EmitResponsesStream helpers so both the
   single-delta (EmitResponsesStream, used by the legacy
   RunToolLoop path) and the true-streaming
   (StreamResponsesViaProvider, used by the passthrough path)
   variants build events from the same code. All take Seq as
   first arg, all carry the per-event sequence_number openai-python
   validators require (PR #62 review fix).

   TResponsesStreamState class holds the streaming state
   (Streamer, MsgItemId, Seq counter, TextStarted flag,
   accumulated text, EmptyItem/EmptyPart JSON for lazy message
   sub-sequence open) and exposes OnChunk as a method-of-object
   the provider's TStreamCallback can bind to.

   Event sequence the new path emits:

     response.created            { in_progress, empty output }
     response.in_progress
     [ on first text chunk — lazy open ]
       response.output_item.added             { message in_progress }
       response.content_part.added            { empty output_text part }
     [ per text chunk ]
       response.output_text.delta             { just-this-fragment }
     [ after ChatStream returns, if any text was emitted ]
       response.output_text.done              { accumulated text }
       response.content_part.done             { full part }
       response.output_item.done              { message completed }
     [ per tool call in Resp.ToolCalls ]
       response.output_item.added             { function_call in_progress }
       response.function_call_arguments.delta { full args, one delta }
       response.function_call_arguments.done
       response.output_item.done              { function_call completed }
     response.completed                       { full output, usage }

   The Codex flow with PR #63 + this PR works end-to-end:
   incremental text rendering during model output, function_call
   items streamed back as the model emits them, multi-turn
   agentic loop with client-side tool execution.

   HandleResponses dispatch:
     HasFunctionTools + WantsStream  -> StreamResponsesViaProvider (Exit)
     HasFunctionTools + not stream   -> Provider.Chat() + WriteJSON (PR #63 path)
     not HasFunctionTools + stream   -> RunToolLoop + EmitResponsesStream
                                         (PR #62 single-delta — RunToolLoop
                                         is synchronous so there are no
                                         incremental data to stream)
     not HasFunctionTools + not stream -> RunToolLoop + WriteJSON (legacy)

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
FMXExpress pushed a commit that referenced this pull request May 29, 2026
Closes two of the three known limitations from PR #63's description
(custom-type grammar tools remain documented future work — that one
needs provider-side change to support Lark-grammar output
constraints that neither Anthropic nor OpenAI Chat-Completions
natively expose).

1. tool_choice forwarding
   TChatOptions gains a ToolChoice: string field, with the three
   string forms every provider can represent:

       ""         => emit nothing (provider default; typically
                     "auto" when tools are present)
       "auto"     => model decides
       "none"     => model must not call any tool
       "required" => model must call one of the tools

   Provider mappings:
     Anthropic Messages API: emits tool_choice object alongside
       tools[]. auto -> {type: "auto"}, required -> {type: "any"},
       none -> field omitted (the cleaner Anthropic convention).
     OpenAI Chat Completions: emits tool_choice as the bare string
       form ("auto" / "none" / "required") — 1:1 mapping.
     Gemini: skipped. The generateContent API has tool_config but
       the mapping is more involved; deferred until a real Gemini
       Codex-flow user shows up.

   HandleResponses reads request.tool_choice. Only the three
   string forms are accepted; the object form (force a specific
   function by name) is logged at debug and dropped — needs per-
   provider translation that's substantial enough to be its own
   PR if a client actually needs it.

2. Real partial streaming
   The passthrough+stream path now uses Provider.ChatStream with
   an OnChunk callback that emits response.output_text.delta
   events as the model produces fragments. Replaces the
   single-delta whole-text approach from PR #62. First-byte-time
   improves dramatically for streaming-capable providers
   (Anthropic streams natively; OpenAI-compat's ChatStream
   currently delegates to Chat and returns the whole text — for
   that case the new code feeds the whole text through OnChunk as
   one synthesized chunk, so the event shape stays consistent).

   New module-level event helpers Res*Evt() replace the previous
   local-inside-EmitResponsesStream helpers so both the
   single-delta (EmitResponsesStream, used by the legacy
   RunToolLoop path) and the true-streaming
   (StreamResponsesViaProvider, used by the passthrough path)
   variants build events from the same code. All take Seq as
   first arg, all carry the per-event sequence_number openai-python
   validators require (PR #62 review fix).

   TResponsesStreamState class holds the streaming state
   (Streamer, MsgItemId, Seq counter, TextStarted flag,
   accumulated text, EmptyItem/EmptyPart JSON for lazy message
   sub-sequence open) and exposes OnChunk as a method-of-object
   the provider's TStreamCallback can bind to.

   Event sequence the new path emits:

     response.created            { in_progress, empty output }
     response.in_progress
     [ on first text chunk — lazy open ]
       response.output_item.added             { message in_progress }
       response.content_part.added            { empty output_text part }
     [ per text chunk ]
       response.output_text.delta             { just-this-fragment }
     [ after ChatStream returns, if any text was emitted ]
       response.output_text.done              { accumulated text }
       response.content_part.done             { full part }
       response.output_item.done              { message completed }
     [ per tool call in Resp.ToolCalls ]
       response.output_item.added             { function_call in_progress }
       response.function_call_arguments.delta { full args, one delta }
       response.function_call_arguments.done
       response.output_item.done              { function_call completed }
     response.completed                       { full output, usage }

   The Codex flow with PR #63 + this PR works end-to-end:
   incremental text rendering during model output, function_call
   items streamed back as the model emits them, multi-turn
   agentic loop with client-side tool execution.

   HandleResponses dispatch:
     HasFunctionTools + WantsStream  -> StreamResponsesViaProvider (Exit)
     HasFunctionTools + not stream   -> Provider.Chat() + WriteJSON (PR #63 path)
     not HasFunctionTools + stream   -> RunToolLoop + EmitResponsesStream
                                         (PR #62 single-delta — RunToolLoop
                                         is synchronous so there are no
                                         incremental data to stream)
     not HasFunctionTools + not stream -> RunToolLoop + WriteJSON (legacy)

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants