Skip to content

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

Merged
FMXExpress merged 1 commit into
mainfrom
claude/pr63-responses-tools-passthrough
May 29, 2026
Merged

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

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Re-opening PR #63 which got stranded — was merged into PR #62's branch but never propagated to main. Stacked on new PR #65 (the reopen of #62). When #65 lands, retarget this to main (one GitHub click) and the diff collapses to just Phase 2's commit.

Original PR #63 description follows

After PR #62 the handler emitted parseable SSE events but ran an internal tool loop — Codex CLI's tool definitions and tool execution live 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.

This PR adds the passthrough path.

What this PR ships

Tools parsing

request.tools[] → TToolDefinitionArray (function-type forwarded) + ToolsRawJSON (verbatim echo for response.tools). Custom-type tools (Codex's grammar-constrained apply_patch) skipped at the provider boundary; still appear in echo so SDK validators don't trip.

Input-item parsing

Item type Becomes
message (existing) mrUser/mrAssistant/mrSystem/mrTool TMessage
function_call mrAssistant TMessage with TToolCall
function_call_output mrTool TMessage with ToolCallId = call_id

Branched execution

HasFunctionTools = True  → Provider.Chat(Msgs, ToolDefs, Model, Options)
                           Single round-trip. No internal tool loop.
                           No BuildSystemPrompt (Codex sends its own).
otherwise                → existing RunToolLoop path (unchanged)

Response shape

BuildResponsesObject accepts ToolCalls + ToolsRawJSON. Each tool call → function_call output item with fc_… / call_… ids matching the OpenAI schema. response.tools is now the echoed ToolsRawJSON.

Streaming events

Per tool call:

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 }

All event helpers gained an OutputIdx parameter so output_index tracks which item we're inside.

Codex test path after this lands

Multi-turn agentic loop works end-to-end: model emits function_call, stream delivers it to Codex, Codex executes locally, posts function_call_output back on follow-up, repeats.

Known limitations (PR #66 closes two of three)

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

@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 +1586 to +1587
SetLength(Msgs[MsgCount].ToolCalls, 1);
Msgs[MsgCount].ToolCalls[0] := Tc;

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 parallel calls in one assistant turn

When a Responses turn contains multiple function_call items followed by their function_call_output items (the shape produced by parallel tool calls), this helper creates one assistant message per call, so the provider request becomes assistant(tc1), assistant(tc2), tool(tc1), .... The OpenAI/Anthropic builders serialize each TMessage independently, which leaves tool(tc1) no longer adjacent to the assistant message that declared tc1, causing the next provider call to reject or mis-associate multi-tool turns. Group adjacent function_call items into a single assistant message with multiple ToolCalls before appending the tool outputs.

Useful? React with 👍 / 👎.

@FMXExpress
FMXExpress changed the base branch from claude/pr62-responses-streaming to main May 29, 2026 00:11
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 force-pushed the claude/pr63-responses-tools-passthrough branch from 7dd8bdd to 5c64186 Compare May 29, 2026 00:15
@FMXExpress
FMXExpress merged commit 8c7ac9c into main May 29, 2026
FMXExpress pushed a commit that referenced this pull request May 29, 2026
…_use, tool_choice none, response.failed

Addresses Codex review feedback on PR #66 (now in main) and the open
PR #67.

1. Group parallel function_call inputs into one assistant turn (PR #66)

   When Codex sends multiple function_call items in a single Responses
   API turn (parallel tool use), AppendAssistantToolCall previously
   created one TMessage per call. Anthropic rejects request shapes
   that split a single assistant turn into multiple consecutive
   assistant messages with tool_use blocks. The helper now appends
   to the previous message when it is an empty-content assistant with
   tool_calls, coalescing the parallel turn into one message while
   still creating a new message after any non-assistant boundary
   (function_call_output / message). Matching with
   function_call_output is unaffected since it keys by call_id.

2. Anthropic SSE: accumulate tool_use blocks (PR #67, P1)

   HandleAnthropicSSE was only tracking text_delta / message_delta /
   message_start / message_stop. Tool-call-only assistant turns
   streamed back with no ToolCalls, so the gateway never emitted the
   function_call output items and Codex couldn't execute the tools.

   Added handling for the three events that bracket a tool_use block:
     content_block_start (type=tool_use) -> capture id+name, start buffer
     content_block_delta (type=input_json_delta) -> append partial_json
     content_block_stop -> flush accumulated TToolCall to GStreamLast
   ChatStream now propagates GStreamLast.ToolCalls into Result.

   Also clears the tool-block state and Finalizes GStreamLast on
   entry so the previous call's managed fields don't leak refcounts
   under the subsequent FillChar zero.

3. Anthropic: emit tool_choice {type: "none"} explicitly (PR #67, P2)

   Anthropic supports {"type":"none"} to forbid tool calls; omitting
   tool_choice when tools are present still allows the model to call
   them. BuildRequest now emits the explicit form when ToolChoice =
   "none" so the client's intent reaches the API.

4. Streaming failures emit response.failed (PR #67, P2)

   StreamResponsesViaProvider used to emit response.completed with
   status "completed" and empty output even when the provider raised
   or returned FinishReason="error" after SSE headers were sent.
   Streaming clients (openai-python, Codex) treat that as a successful
   empty response, hiding real errors.

   Added a ResFailedEvt helper and a Failed flag in
   StreamResponsesViaProvider. When the ChatStream call raises or the
   response carries FinishReason="error", capture the error string,
   suppress the fake-text-chunk fallback, and emit response.failed
   with the response object's status set to "failed" and an
   {code:"server_error", message:<err>} error block — matching the
   non-streaming HandleResponses' error shape.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
FMXExpress added a commit that referenced this pull request May 29, 2026
PR #66 + #67 review fixes: parallel calls, Anthropic SSE tool_use, response.failed
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