diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 982b2991..2014239d 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -429,7 +429,7 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { if external == upstreamRoute.Protocol { usage, usageReported, err = wire.ForwardStream(r.Context(), w, streamBody, upstreamRoute.Protocol, model) } else { - usage, usageReported, err = wire.TranscodeStream(r.Context(), w, streamBody, upstreamRoute.Protocol, external, model) + usage, usageReported, err = wire.TranscodeStream(r.Context(), w, streamBody, upstreamRoute.Protocol, external, model, toolRenames) } if meta != nil { meta.Usage, meta.UsageReported = usage, usageReported diff --git a/internal/gateway/rotation.go b/internal/gateway/rotation.go index b37f6b4f..21f77f91 100644 --- a/internal/gateway/rotation.go +++ b/internal/gateway/rotation.go @@ -306,7 +306,7 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter, defer g.monitor.EndStream() } streamBody := wire.RenameStreamReader(resp.Body, route.Protocol, toolRenames) - usage, reported, committed, err := wire.RotationStream(original.Context(), w, streamBody, route.Protocol, external, alias, ready) + usage, reported, committed, err := wire.RotationStream(original.Context(), w, streamBody, route.Protocol, external, alias, toolRenames, ready) if meta != nil { meta.Usage = usage meta.UsageReported = reported diff --git a/internal/gateway/tooladapt.go b/internal/gateway/tooladapt.go new file mode 100644 index 00000000..8d0a9c30 --- /dev/null +++ b/internal/gateway/tooladapt.go @@ -0,0 +1,509 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "runtime" + "strings" + + wire "opencode2api/internal/protocol" +) + +// Codex declares one general executor, exec_command, where the other agents +// have dedicated shell and file tools. The free tier always advertises the +// official OpenCode set, so a model can call shell/read/edit/... even when the +// downstream client has no handler for them. These adapters bind those official +// names to exec_command and rewrite their arguments into a command Codex can +// run. They are registered per request and only when the client actually +// declared exec_command (or, for patch, its custom apply_patch tool), so Claude +// Code and OpenCode clients keep their native tools unchanged. + +// bindExecCommandAdapters registers the argument rewrites for official tools +// that a shaped Codex request maps to exec_command or apply_patch. The shell +// rewrite is platform-neutral because the command text is passed through to the +// client's own shell; the file rewrites synthesize an executor command and run +// only on Windows, where the gateway and the client share a host. +func bindExecCommandAdapters(renames *wire.ToolRenames) { + if renames == nil { + return + } + bind := func(official, client string, transform wire.ArgumentTransform) bool { + declared, ok := renames.Official(official) + if !ok || !sameToolName(declared, client) { + return false + } + renames.SetArgumentTransform(official, transform) + return true + } + bind("shell", "exec_command", shellToExecCommand) + bind("bash", "exec_command", shellToExecCommand) + bind("todowrite", "update_plan", todoWriteToUpdatePlan) + if runtime.GOOS != "windows" { + return + } + bind("read", "exec_command", readToExecCommand) + bind("write", "exec_command", writeToExecCommand) + bind("edit", "exec_command", editToExecCommand) + bind("glob", "exec_command", globToExecCommand) + bind("grep", "exec_command", grepToExecCommand) + bind("webfetch", "exec_command", webfetchToExecCommand) + bind("websearch", "exec_command", websearchToExecCommand) + bind("skill", "exec_command", skillToExecCommand) + if declared, ok := renames.Official("patch"); ok && sameToolName(declared, "apply_patch") && renames.Custom(declared) { + renames.SetArgumentTransform("patch", patchToCustomInput) + } +} + +// sameToolName folds case and the separators agents use in tool names, so +// exec_command, exec-command and ExecCommand name one tool. +func sameToolName(left, right string) bool { + return foldToolName(left) == foldToolName(right) +} + +func foldToolName(name string) string { + var builder strings.Builder + for _, char := range strings.ToLower(name) { + switch char { + case '_', '.', '-', ' ', '\t', '\r', '\n': + continue + } + builder.WriteRune(char) + } + return builder.String() +} + +// decodeArguments reads one tool call's arguments object. Empty arguments are +// an empty object, and malformed JSON is returned to the caller unchanged. +func decodeArguments(raw string) (map[string]any, error) { + if strings.TrimSpace(raw) == "" { + return map[string]any{}, nil + } + var arguments map[string]any + if err := json.Unmarshal([]byte(raw), &arguments); err != nil { + return nil, err + } + if arguments == nil { + arguments = map[string]any{} + } + return arguments, nil +} + +func encodeArguments(arguments map[string]any) (string, error) { + encoded, err := json.Marshal(arguments) + if err != nil { + return "", err + } + return string(encoded), nil +} + +func stringArgument(arguments map[string]any, key string) string { + value, _ := arguments[key].(string) + return value +} + +func intArgument(arguments map[string]any, key string) int { + value, ok := arguments[key] + if !ok { + return 0 + } + switch typed := value.(type) { + case float64: + return int(typed) + case int: + return typed + case json.Number: + number, err := typed.Int64() + if err == nil { + return int(number) + } + } + return 0 +} + +func boolArgument(arguments map[string]any, key string) bool { + value, _ := arguments[key].(bool) + return value +} + +// execCommandArguments renders the exec_command call for a synthesized command. +func execCommandArguments(command, workdir string) (string, error) { + arguments := map[string]any{"cmd": command} + if workdir != "" { + arguments["workdir"] = workdir + } + return encodeArguments(arguments) +} + +// shellToExecCommand maps the official shell arguments (command, workdir, +// timeout, background) to exec_command's cmd and workdir. The command text is +// already written for the client's shell, so it is passed through verbatim. +func shellToExecCommand(raw string) (string, error) { + arguments, err := decodeArguments(raw) + if err != nil { + return raw, err + } + command := stringArgument(arguments, "command") + if command == "" { + return raw, nil + } + return execCommandArguments(command, stringArgument(arguments, "workdir")) +} + +// readToExecCommand renders the official read arguments as a PowerShell read, +// including directory listings and offset/limit windows. +func readToExecCommand(raw string) (string, error) { + arguments, err := decodeArguments(raw) + if err != nil { + return raw, err + } + path := stringArgument(arguments, "path") + if path == "" { + return raw, nil + } + literal := psLiteral(path) + script := fmt.Sprintf(`if (Test-Path -LiteralPath %s -PathType Container) { Get-ChildItem -LiteralPath %s | ForEach-Object { $_.Name } } else `, literal, literal) + offset := intArgument(arguments, "offset") + limit := intArgument(arguments, "limit") + switch { + case offset <= 0 && limit <= 0: + script += fmt.Sprintf(`{ Get-Content -LiteralPath %s -Raw -Encoding UTF8 }`, literal) + default: + lines := []string{fmt.Sprintf(`$lines = @(Get-Content -LiteralPath %s -Encoding UTF8)`, literal)} + if skip := offset - 1; skip > 0 { + lines = append(lines, fmt.Sprintf(`if ($lines.Count -gt %d) { $lines = $lines[%d..($lines.Count - 1)] } else { $lines = @() }`, skip, skip)) + } + if limit > 0 { + lines = append(lines, fmt.Sprintf(`if ($lines.Count -gt %d) { $lines = $lines[0..%d] }`, limit, limit-1)) + } + lines = append(lines, "$lines -join \"`n\"") + script += "{ " + strings.Join(lines, "; ") + " }" + } + return execCommandArguments(script, "") +} + +// writeToExecCommand renders the official write arguments as a PowerShell +// write that creates parent directories and keeps UTF-8 without a BOM. +func writeToExecCommand(raw string) (string, error) { + arguments, err := decodeArguments(raw) + if err != nil { + return raw, err + } + path := stringArgument(arguments, "path") + if path == "" { + return raw, nil + } + content, ok := arguments["content"].(string) + if !ok { + content = "" + } + script := fmt.Sprintf(`$p = %s +$c = %s +$d = Split-Path -Parent $p +if ($d -and -not (Test-Path -LiteralPath $d)) { New-Item -ItemType Directory -Path $d -Force | Out-Null } +Set-Content -LiteralPath $p -Value $c -NoNewline -Encoding utf8 +Write-Output ('Wrote ' + $p)`, psLiteral(path), psQuoted(content)) + return execCommandArguments(script, "") +} + +// editToExecCommand renders the official edit arguments as an exact-string +// replacement in PowerShell, failing loudly when the target is missing or not +// unique. +func editToExecCommand(raw string) (string, error) { + arguments, err := decodeArguments(raw) + if err != nil { + return raw, err + } + path := stringArgument(arguments, "path") + oldString, hasOld := arguments["oldString"].(string) + newString, hasNew := arguments["newString"].(string) + if path == "" || !hasOld || !hasNew { + return raw, nil + } + script := fmt.Sprintf(`$p = %s +$old = %s +$new = %s +$all = %t +try { + if ($old -eq '') { throw 'oldString must not be empty' } + if (-not (Test-Path -LiteralPath $p)) { throw ('file not found: ' + $p) } + $text = Get-Content -LiteralPath $p -Raw -Encoding UTF8 + if ($null -eq $text) { $text = '' } + $index = $text.IndexOf($old) + if ($index -lt 0) { throw 'oldString not found' } + if ($all) { $text = $text.Replace($old, $new) } else { + if ($text.IndexOf($old, $index + $old.Length) -ge 0) { throw 'oldString is not unique; set replaceAll' } + $text = $text.Substring(0, $index) + $new + $text.Substring($index + $old.Length) + } + Set-Content -LiteralPath $p -Value $text -NoNewline -Encoding utf8 + Write-Output ('Edited ' + $p) +} catch { + Write-Error $_.Exception.Message + exit 1 +}`, psLiteral(path), psQuoted(oldString), psQuoted(newString), boolArgument(arguments, "replaceAll")) + return execCommandArguments(script, "") +} + +// globToExecCommand renders the official glob arguments as a PowerShell file +// search whose pattern is translated to a .NET regular expression. +func globToExecCommand(raw string) (string, error) { + arguments, err := decodeArguments(raw) + if err != nil { + return raw, err + } + pattern := stringArgument(arguments, "pattern") + if pattern == "" { + return raw, nil + } + path := stringArgument(arguments, "path") + if path == "" { + path = "." + } + limit := intArgument(arguments, "limit") + if limit <= 0 { + limit = 100 + } + expression := globToRegexp(pattern) + force := "" + if boolArgument(arguments, "hidden") { + force = " -Force" + } + script := fmt.Sprintf(`$root = %s +$rx = %s +Get-ChildItem -LiteralPath $root -Recurse -File%s -ErrorAction SilentlyContinue | Where-Object { $_.FullName.Replace('\','/') -match $rx } | Select-Object -First %d -ExpandProperty FullName`, psLiteral(path), psLiteral(expression), force, limit) + return execCommandArguments(script, "") +} + +// grepToExecCommand renders the official grep arguments as a PowerShell +// Select-String search that keeps the file:line:text output shape. +func grepToExecCommand(raw string) (string, error) { + arguments, err := decodeArguments(raw) + if err != nil { + return raw, err + } + pattern := stringArgument(arguments, "pattern") + if pattern == "" { + return raw, nil + } + path := stringArgument(arguments, "path") + if path == "" { + path = "." + } + limit := intArgument(arguments, "limit") + if limit <= 0 { + limit = 100 + } + simple := "" + if boolArgument(arguments, "literal") { + simple = " -SimpleMatch" + } + caseSensitive := "" + if boolArgument(arguments, "caseSensitive") { + caseSensitive = " -CaseSensitive" + } + script := fmt.Sprintf(`$root = %s +$pattern = %s +$include = %s +$files = if (Test-Path -LiteralPath $root -PathType Container) { Get-ChildItem -LiteralPath $root -Recurse -File -ErrorAction SilentlyContinue } else { Get-Item -LiteralPath $root -ErrorAction SilentlyContinue } +if ($include) { $files = $files | Where-Object { $_.Name -like $include } } +$files | Select-String -Pattern $pattern%s%s -ErrorAction SilentlyContinue | Select-Object -First %d | ForEach-Object { '{0}:{1}:{2}' -f $_.Path, $_.LineNumber, $_.Line }`, psLiteral(path), psLiteral(pattern), psLiteral(stringArgument(arguments, "include")), simple, caseSensitive, limit) + return execCommandArguments(script, "") +} + +// websearchToExecCommand runs the official websearch query through Bing and +// returns the result page text. It is a fallback for clients that have no web +// search of their own; the model can fetch a result with webfetch. curl handles +// the query escaping without the .NET calls that constrained language mode +// blocks. +func websearchToExecCommand(raw string) (string, error) { + arguments, err := decodeArguments(raw) + if err != nil { + return raw, err + } + query := strings.TrimSpace(stringArgument(arguments, "query")) + if query == "" { + return raw, nil + } + limit := intArgument(arguments, "contextMaxCharacters") + if limit <= 0 || limit > 20000 { + limit = 8000 + } + script := fmt.Sprintf(`$q = %s +$html = & curl.exe -s -L --max-time 30 -A 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' -G --data-urlencode ('q=' + $q) --data-urlencode 'count=10' 'https://www.bing.com/search' +$text = ($html -join ' ') +$text = $text -replace '(?s)|', ' ' +$text = $text -replace '<[^>]+>', ' ' +$text = $text -replace '\s+', ' ' +if ($text.Length -gt %d) { $text = $text.Substring(0, %d) } +Write-Output $text`, psLiteral(query), limit, limit) + return encodeArguments(map[string]any{"cmd": script}) +} + +func webfetchToExecCommand(raw string) (string, error) { + arguments, err := decodeArguments(raw) + if err != nil { + return raw, err + } + url := stringArgument(arguments, "url") + if url == "" { + return raw, nil + } + timeout := intArgument(arguments, "timeout") + if timeout <= 0 { + timeout = 60 + } + if timeout > 120 { + timeout = 120 + } + script := fmt.Sprintf(`$response = Invoke-WebRequest -Uri %s -UseBasicParsing -TimeoutSec %d +$response.Content`, psLiteral(url), timeout) + return execCommandArguments(script, "") +} + +// skillToExecCommand renders the official skill arguments as a search for the +// skill's SKILL.md in the agent skill roots, falling back to a recursive +// lookup by directory name. +func skillToExecCommand(raw string) (string, error) { + arguments, err := decodeArguments(raw) + if err != nil { + return raw, err + } + id := stringArgument(arguments, "id") + if id == "" { + return raw, nil + } + script := fmt.Sprintf(`$id = %s; $roots = @((Join-Path $env:USERPROFILE '.codex\skills'), (Join-Path $env:USERPROFILE '.codex\skills\.system'), (Join-Path $env:USERPROFILE '.claude\skills'), (Join-Path $env:USERPROFILE '.config\opencode\skills'), (Join-Path $env:USERPROFILE '.pi\agent\skills'), '.codex\skills', '.claude\skills', '.opencode\skills') | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -Unique; $found = $null; foreach ($root in $roots) { $candidate = Join-Path $root (Join-Path $id 'SKILL.md'); if (Test-Path -LiteralPath $candidate) { $found = $candidate; break } }; if (-not $found) { $found = Get-ChildItem -Path $roots -Recurse -Filter SKILL.md -ErrorAction SilentlyContinue | Where-Object { $_.Directory.Name -eq $id } | Select-Object -First 1 -ExpandProperty FullName }; if ($found) { Get-Content -LiteralPath $found -Raw -Encoding UTF8 } else { Write-Output ('Skill not found: ' + $id); Get-ChildItem -Path $roots -Recurse -Filter SKILL.md -ErrorAction SilentlyContinue | ForEach-Object { $_.Directory.Name } | Sort-Object -Unique }`, psLiteral(id)) + return execCommandArguments(script, "") +} + +// patchToCustomInput maps the official patch tool's patchText to the freeform +// input envelope the Responses bridge uses for Codex's custom apply_patch tool. +// todoWriteToUpdatePlan converts the official todo list into the plan the Codex +// update_plan tool expects. Cancelled entries are dropped because Codex has no +// cancelled status; the other statuses are shared. +func todoWriteToUpdatePlan(raw string) (string, error) { + arguments, err := decodeArguments(raw) + if err != nil { + return raw, err + } + todos, ok := arguments["todos"].([]any) + if !ok { + return raw, nil + } + plan := make([]any, 0, len(todos)) + for _, rawTodo := range todos { + todo, _ := rawTodo.(map[string]any) + step := strings.TrimSpace(stringArgument(todo, "content")) + if step == "" { + continue + } + status := strings.ToLower(strings.TrimSpace(stringArgument(todo, "status"))) + switch status { + case "in_progress", "completed": + case "cancelled": + continue + default: + status = "pending" + } + plan = append(plan, map[string]any{"step": step, "status": status}) + } + return encodeArguments(map[string]any{"plan": plan}) +} + +func patchToCustomInput(raw string) (string, error) { + arguments, err := decodeArguments(raw) + if err != nil { + return raw, err + } + patch := stringArgument(arguments, "patchText") + if patch == "" { + return raw, nil + } + return encodeArguments(map[string]any{"input": patch}) +} + +// psLiteral embeds a value in a PowerShell single-quoted string. Single-quoted +// strings take backslashes, dollar signs and backticks literally, so only a +// quote needs doubling. +func psLiteral(value string) string { + return "'" + strings.ReplaceAll(value, "'", "''") + "'" +} + +// psQuoted embeds arbitrary text, including newlines, in a PowerShell +// double-quoted string. Backticks, dollar signs, quotes and line breaks are +// escaped so the text is neither expanded nor reinterpreted. The Codex sandbox +// runs PowerShell in constrained language mode, where .NET static methods such +// as base64 decoding are blocked, so string literals are the portable encoding. +func psQuoted(value string) string { + replacer := strings.NewReplacer( + "\x60", "\x60\x60", + "$", "\x60$", + "\"", "\x60\"", + "\r", "\x60r", + "\n", "\x60n", + "\t", "\x60t", + ) + return "\"" + replacer.Replace(value) + "\"" +} + +// globToRegexp translates a glob into an anchored .NET regular expression over +// paths normalized to forward slashes. ** spans directories, * stays within +// one segment, ? matches one character, and {a,b} alternates. +func globToRegexp(pattern string) string { + var builder strings.Builder + builder.WriteString("^(?:.*/)?") + runes := []rune(strings.ReplaceAll(pattern, "\\", "/")) + for index := 0; index < len(runes); index++ { + char := runes[index] + switch char { + case '*': + if index+1 < len(runes) && runes[index+1] == '*' { + index++ + if index+1 < len(runes) && runes[index+1] == '/' { + index++ + builder.WriteString("(?:.*/)?") + } else { + builder.WriteString(".*") + } + continue + } + builder.WriteString("[^/]*") + case '?': + builder.WriteString("[^/]") + case '{': + end := index + 1 + for end < len(runes) && runes[end] != '}' { + end++ + } + if end < len(runes) { + builder.WriteString("(?:") + for optionIndex, option := range strings.Split(string(runes[index+1:end]), ",") { + if optionIndex > 0 { + builder.WriteString("|") + } + builder.WriteString(regexpQuote(option)) + } + builder.WriteString(")") + index = end + continue + } + builder.WriteString("\\{") + default: + builder.WriteString(regexpQuote(string(char))) + } + } + builder.WriteString("$") + return builder.String() +} + +// regexpQuote escapes one regular-expression character. It uses the .NET +// escape set shared with Go's regexp for the punctuation globs care about. +func regexpQuote(value string) string { + var builder strings.Builder + for _, char := range value { + if strings.ContainsRune(`\.+*?()|[]{}^$`, char) { + builder.WriteByte('\\') + } + builder.WriteRune(char) + } + return builder.String() +} diff --git a/internal/gateway/toolshape.go b/internal/gateway/toolshape.go index 20253ee7..c988dc72 100644 --- a/internal/gateway/toolshape.go +++ b/internal/gateway/toolshape.go @@ -88,39 +88,53 @@ func officialToolNames(v1 bool) []string { } // OfficialToolCandidates returns client tool names equivalent to an official name. +// exec_command is Codex's single workhorse tool: shell maps to it directly, +// and the file tools get it as a fallback with translated arguments. The +// fallbacks are registered only for clients that declare exec_command, so a +// Claude Code or OpenCode client keeps its native tool names. func OfficialToolCandidates(officialName string) []string { switch strings.ToLower(officialName) { case "bash", "shell": - return []string{"Bash"} + return []string{"Bash", "exec_command"} case "edit": - return []string{"Edit"} + return windowsToolCandidates("Edit") case "glob": - return []string{"Glob"} + return windowsToolCandidates("Glob") case "grep": - return []string{"Grep"} + return windowsToolCandidates("Grep") case "question": return []string{"AskUserQuestion"} case "read": - return []string{"Read"} + return windowsToolCandidates("Read") case "skill": - return []string{"Skill"} + return windowsToolCandidates("Skill") case "subagent", "task": return []string{"Agent", "Task", "Subagent"} case "todowrite": - return []string{"TodoWrite"} + return []string{"TodoWrite", "update_plan"} case "webfetch": - return []string{"WebFetch"} + return windowsToolCandidates("WebFetch") case "websearch": - return []string{"WebSearch"} + return windowsToolCandidates("WebSearch") case "write": - return []string{"Write"} + return windowsToolCandidates("Write") case "patch": - return []string{"Patch"} + return []string{"Patch", "apply_patch"} default: return nil } } +// windowsToolCandidates appends the Codex exec_command fallback on Windows, +// where the synthesized commands can be PowerShell. Other platforms keep only +// the native client tool names. +func windowsToolCandidates(names ...string) []string { + if runtime.GOOS != "windows" { + return names + } + return append(names, "exec_command") +} + // officialToolDefinition returns the captured definition for an official name. func officialToolDefinition(name string, v1 bool) (opencodeToolDefinition, bool) { loadOfficialTools() @@ -249,6 +263,13 @@ func renameAndCompleteTools(payload map[string]any, protocol wire.Protocol, v1 b delete(payload, "functions") } } + codexClient := false + for _, name := range declaredNames { + if sameToolName(name, "exec_command") { + codexClient = true + break + } + } shaped := make([]any, 0, len(items)+len(officialToolNames(v1))) for _, item := range items { entry, ok := item.(map[string]any) @@ -261,15 +282,27 @@ func renameAndCompleteTools(payload map[string]any, protocol wire.Protocol, v1 b shaped = append(shaped, item) continue } + custom := isCustomToolDefinition(protocol, entry) + // Codex clients always declare exec_command. Some bridges render the + // freeform apply_patch tool as a plain function, which keeps the name + // but loses the custom marker; treat it as custom again so the + // official patch call is emitted as a custom tool call. + if !custom && codexClient && sameToolName(name, "apply_patch") { + custom = true + } if wireName := clientWireName(renames, used, name); wireName != name { setToolName(protocol, entry, wireName) } + if custom { + renames.MarkCustom(name) + } shaped = append(shaped, entry) } shaped = append(shaped, officialToolset(protocol, v1)...) payload["tools"] = shaped officialNames := officialToolNames(v1) bindOfficialToolAliases(renames, declaredNames, officialNames) + bindExecCommandAdapters(renames) declared := make(map[string]string, len(declaredNames)) for _, name := range declaredNames { if wireName, ok := renames.Wire(name); ok { @@ -301,6 +334,41 @@ func bindOfficialToolAliases(renames *wire.ToolRenames, declaredNames, officialN } } +// isCustomToolDefinition reports whether one tool was declared as a freeform +// custom tool (Codex's apply_patch). Chat and Anthropic carry custom tools as +// functions with the bridge's single-string input schema; Responses marks them +// with type "custom". +func isCustomToolDefinition(protocol wire.Protocol, entry map[string]any) bool { + switch protocol { + case wire.Responses: + return jsonutil.StringAt(entry, "type") == "custom" + case wire.Chat: + function, _ := entry["function"].(map[string]any) + parameters, _ := function["parameters"].(map[string]any) + return isCustomToolSchema(parameters) + default: + return false + } +} + +// isCustomToolSchema matches the function schema the bridge renders for a +// Responses custom tool: exactly one freeform string input. +func isCustomToolSchema(schema map[string]any) bool { + if schema == nil { + return false + } + properties, _ := schema["properties"].(map[string]any) + if len(properties) != 1 { + return false + } + input, _ := properties["input"].(map[string]any) + if input == nil || jsonutil.StringAt(input, "type") != "string" { + return false + } + required, _ := schema["required"].([]any) + return len(required) == 1 && required[0] == "input" +} + func officialToolNameSet(v1 bool) map[string]bool { set := make(map[string]bool) for _, name := range officialToolNames(v1) { @@ -416,8 +484,10 @@ func sanitizeToolHistory(payload map[string]any, protocol wire.Protocol, declare keptItems := make([]any, 0, len(items)) for _, rawItem := range items { item, _ := rawItem.(map[string]any) - if jsonutil.StringAt(item, "type") == "function_call_output" && dropped[jsonutil.StringAt(item, "call_id")] { - continue + if kind := jsonutil.StringAt(item, "type"); kind == "function_call_output" || kind == "custom_tool_call_output" { + if dropped[jsonutil.StringAt(item, "call_id")] { + continue + } } if kind := jsonutil.StringAt(item, "type"); kind == "function_call" || kind == "custom_tool_call" { if _, ok := historyToolWireName(jsonutil.StringAt(item, "name"), declared, renames, laneOfficial); !ok { diff --git a/internal/gateway/toolshape_test.go b/internal/gateway/toolshape_test.go new file mode 100644 index 00000000..0ffff28e --- /dev/null +++ b/internal/gateway/toolshape_test.go @@ -0,0 +1,105 @@ +package gateway + +import ( + "encoding/json" + "testing" + + wire "opencode2api/internal/protocol" +) + +func TestRenameAndCompleteToolsBindsCodexAdapters(t *testing.T) { + var payload map[string]any + raw := `{ + "tools": [ + {"type":"function","name":"exec_command","parameters":{"type":"object","properties":{"cmd":{"type":"string"}}}}, + {"type":"custom","name":"apply_patch"} + ] + }` + if err := json.Unmarshal([]byte(raw), &payload); err != nil { + t.Fatal(err) + } + renames, ok := renameAndCompleteTools(payload, wire.Responses, false) + if !ok { + t.Fatal("renameAndCompleteTools returned false") + } + for _, testCase := range []struct{ official, client string }{ + {"patch", "apply_patch"}, + {"shell", "exec_command"}, + } { + declared, ok := renames.Official(testCase.official) + if !ok || !sameToolName(declared, testCase.client) { + t.Fatalf("official %q bound to %q, want %q", testCase.official, declared, testCase.client) + } + if _, ok := renames.ArgumentTransform(testCase.official); !ok { + t.Fatalf("official %q has no argument transform", testCase.official) + } + } + if !renames.Custom("apply_patch") { + t.Fatal("apply_patch was not marked custom") + } + assertTransformJSON(t, renames, "patch", `{"patchText":"*** Begin Patch\n*** End Patch"}`, map[string]any{ + "input": "*** Begin Patch\n*** End Patch", + }) + assertTransformJSON(t, renames, "shell", `{"command":"echo hi","workdir":"C:\\tmp"}`, map[string]any{ + "cmd": "echo hi", + "workdir": `C:\tmp`, + }) +} + +func TestRenameAndCompleteToolsBindsTodoWrite(t *testing.T) { + var payload map[string]any + raw := `{ + "tools": [ + {"type":"function","name":"exec_command","parameters":{"type":"object","properties":{"cmd":{"type":"string"}}}}, + {"type":"function","name":"update_plan","parameters":{"type":"object","properties":{"plan":{"type":"array"}}}} + ] + }` + if err := json.Unmarshal([]byte(raw), &payload); err != nil { + t.Fatal(err) + } + renames, ok := renameAndCompleteTools(payload, wire.Responses, true) + if !ok { + t.Fatal("renameAndCompleteTools returned false") + } + declared, ok := renames.Official("todowrite") + if !ok || !sameToolName(declared, "update_plan") { + t.Fatalf("official todowrite bound to %q, want update_plan", declared) + } + if _, ok := renames.ArgumentTransform("todowrite"); !ok { + t.Fatal("official todowrite has no argument transform") + } + assertTransformJSON(t, renames, "todowrite", `{"todos":[{"content":"a","status":"in_progress"},{"content":"b","status":"cancelled"}]}`, map[string]any{ + "plan": []any{map[string]any{"step": "a", "status": "in_progress"}}, + }) +} + +func assertTransformJSON(t *testing.T, renames *wire.ToolRenames, official, raw string, want map[string]any) { + t.Helper() + transform, ok := renames.ArgumentTransform(official) + if !ok { + t.Fatalf("%s: no argument transform", official) + } + got, err := transform(raw) + if err != nil { + t.Fatalf("%s: %v", official, err) + } + var gotValue any + if err := json.Unmarshal([]byte(got), &gotValue); err != nil { + t.Fatalf("%s: invalid JSON %q: %v", official, got, err) + } + wantJSON, err := json.Marshal(want) + if err != nil { + t.Fatal(err) + } + var wantValue any + if err := json.Unmarshal(wantJSON, &wantValue); err != nil { + t.Fatal(err) + } + gotJSON, err := json.Marshal(gotValue) + if err != nil { + t.Fatal(err) + } + if string(gotJSON) != string(wantJSON) { + t.Fatalf("%s: got %s, want %s", official, gotJSON, wantJSON) + } +} diff --git a/internal/protocol/content.go b/internal/protocol/content.go index 49644d28..54fc1330 100644 --- a/internal/protocol/content.go +++ b/internal/protocol/content.go @@ -384,17 +384,19 @@ func decodeChatToolChoice(value any) bridgeToolChoice { } // decodeResponsesToolChoice maps a Responses tool_choice onto the bridge. A -// string is the mode as is; a function object is a named choice, whose name -// sits at the top level rather than nested as in Chat. +// string is the mode as is; a function or custom object is a named choice, +// whose name sits at the top level rather than nested as in Chat. func decodeResponsesToolChoice(value any) bridgeToolChoice { if mode, ok := value.(string); ok { return bridgeToolChoice{Mode: mode} } choice, _ := value.(map[string]any) - if jsonutil.StringAt(choice, "type") == "function" { + switch jsonutil.StringAt(choice, "type") { + case "function", "custom": return bridgeToolChoice{Mode: "named", Name: jsonutil.StringAt(choice, "name")} + default: + return bridgeToolChoice{} } - return bridgeToolChoice{} } // decodeAnthropicToolChoice maps an Anthropic tool_choice onto the bridge, diff --git a/internal/protocol/request.go b/internal/protocol/request.go index 9ba6a18a..42a522b1 100644 --- a/internal/protocol/request.go +++ b/internal/protocol/request.go @@ -1,6 +1,7 @@ package protocol import ( + "encoding/json" "errors" "fmt" "sort" @@ -25,6 +26,9 @@ func PrepareRequest(from, to Protocol, input map[string]any, upstreamURL string) // a clone of the client's and needs the same guard. jsonutil.Put(output, "max_output_tokens", floorResponsesMaxTokens(output["max_output_tokens"])) } + if to == Chat { + normalizeChatEmptyContent(output) + } normalizeToolReasoningHistory(to, jsonutil.StringAt(output, "model"), upstreamURL, output) return output, nil } @@ -260,6 +264,35 @@ func requestEnablesReasoning(input map[string]any) bool { return false } +// normalizeChatEmptyContent replaces a null or missing message content with +// an empty string. OpenAI-shaped clients serialize a tool-call-only assistant +// turn with "content": null, which strict Chat providers (Alibaba DashScope, +// Cloudflare Workers AI) reject with "The content field is a required field" +// even though the OpenAI schema permits null. The field is a string there, and +// an empty string carries the same meaning. A same-protocol body is cloned and +// never passes through the Chat encoder, so the repair runs on the prepared +// upstream body to cover both paths. +func normalizeChatEmptyContent(input map[string]any) bool { + messages, ok := input["messages"].([]any) + if !ok { + return false + } + + changed := false + for _, rawMessage := range messages { + message, ok := rawMessage.(map[string]any) + if !ok { + continue + } + if content, present := message["content"]; present && content != nil { + continue + } + message["content"] = "" + changed = true + } + return changed +} + // normalizeChatToolReasoningHistory ensures every assistant tool-call turn // carries reasoning_content. Some clients discard this non-standard field // while retaining tool_calls, which otherwise makes the next thinking-mode @@ -530,6 +563,23 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest CallID: jsonutil.StringAt(item, "call_id"), Result: item["output"], }) + case "custom_tool_call": + // Responses custom tools (Codex's freeform apply_patch) have + // a raw string input where function tools have JSON + // arguments. Carry the text under "input" so a Chat or + // Anthropic upstream can read the turn. + appendBridgeBlock(&request.Messages, "assistant", bridgeBlock{ + Kind: "tool_call", + ID: jsonutil.FirstString(jsonutil.StringAt(item, "call_id"), jsonutil.StringAt(item, "id")), + Name: jsonutil.StringAt(item, "name"), + ArgumentsJSON: customToolCallArguments(item["input"]), + }) + case "custom_tool_call_output": + appendBridgeBlock(&request.Messages, "user", bridgeBlock{ + Kind: "tool_result", + CallID: jsonutil.StringAt(item, "call_id"), + Result: item["output"], + }) case "message", "": role := jsonutil.StringAt(item, "role") blocks, err := decodeOpenAIBlocksChecked(item["content"]) @@ -558,15 +608,22 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest // Built-in Responses tools (web_search, file_search, code_interpreter, …) // have no Chat/Anthropic equivalent; skip them during cross-protocol // bridging so requests that mix function tools with built-in plugins - // still reach the upstream. - if jsonutil.StringAt(tool, "type") != "function" { + // still reach the upstream. A custom tool has no direct equivalent + // either, but its freeform input can be represented as one function + // argument, so it is carried across instead of dropped. + kind := jsonutil.StringAt(tool, "type") + if kind != "function" && kind != "custom" { continue } + schema := tool["parameters"] + if kind == "custom" { + schema = customToolSchema() + } request.Tools = append(request.Tools, bridgeTool{ Name: jsonutil.StringAt(tool, "name"), Description: jsonutil.StringAt(tool, "description"), - Schema: tool["parameters"], - Strict: jsonutil.BoolAt(tool, "strict"), + Schema: schema, + Strict: kind == "function" && jsonutil.BoolAt(tool, "strict"), }) } request.ToolChoice = decodeResponsesToolChoice(input["tool_choice"]) @@ -674,6 +731,32 @@ func appendBridgeBlock(messages *[]bridgeMessage, role string, block bridgeBlock *messages = append(*messages, bridgeMessage{Role: role, Blocks: []bridgeBlock{block}}) } +// customToolCallArguments renders a Responses custom tool call's freeform +// input as the JSON arguments object the bridge carries. Chat and Anthropic +// tool calls have no freeform slot, so the raw text travels under "input". +func customToolCallArguments(input any) string { + text, _ := input.(string) + encoded, err := json.Marshal(map[string]string{"input": text}) + if err != nil { + return "{}" + } + return string(encoded) +} + +// customToolSchema renders a Responses custom tool's freeform input as the +// function schema Chat and Anthropic upstreams can call. customToolCallArguments +// writes the same "input" key into history calls and Responses results. +func customToolSchema() any { + return map[string]any{ + "type": "object", + "properties": map[string]any{ + "input": map[string]any{"type": "string"}, + }, + "required": []any{"input"}, + "additionalProperties": false, + } +} + // bridgeBlocksOnlyTools reports whether blocks is non-empty and holds only // tool calls and tool results. func bridgeBlocksOnlyTools(blocks []bridgeBlock) bool { @@ -814,7 +897,7 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) { if budget := reasoningBudget(request.Reasoning); budget <= 0 { return } - encoded := map[string]any{"role": "assistant", "content": nil} + encoded := map[string]any{"role": "assistant", "content": ""} carryBudget(encoded) if encoded["reasoning_budget_tokens"] == nil { return @@ -843,7 +926,7 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) { if len(results) > 0 { return nil, fmt.Errorf("messages[%d]: assistant message contains tool results", i) } - encoded := map[string]any{"role": "assistant", "content": nil} + encoded := map[string]any{"role": "assistant", "content": ""} carryBudget(encoded) if value, ok := bridgeReasoningText(reasoning); ok { encoded["reasoning_content"] = value diff --git a/internal/protocol/request_test.go b/internal/protocol/request_test.go new file mode 100644 index 00000000..7cf5c57f --- /dev/null +++ b/internal/protocol/request_test.go @@ -0,0 +1,36 @@ +package protocol + +import "testing" + +func TestNormalizeChatEmptyContent(t *testing.T) { + input := map[string]any{ + "messages": []any{ + map[string]any{"role": "assistant", "content": nil}, + map[string]any{"role": "user"}, + map[string]any{"role": "assistant", "content": "keep"}, + }, + } + if !normalizeChatEmptyContent(input) { + t.Fatal("expected a change") + } + messages := input["messages"].([]any) + for index, want := range []string{"", "", "keep"} { + message := messages[index].(map[string]any) + if got := message["content"]; got != want { + t.Fatalf("message %d content = %v, want %q", index, got, want) + } + } + if normalizeChatEmptyContent(map[string]any{"messages": []any{map[string]any{"content": "x"}}}) { + t.Fatal("unchanged messages reported a change") + } + if normalizeChatEmptyContent(map[string]any{}) { + t.Fatal("missing messages reported a change") + } +} + +func TestDecodeResponsesToolChoiceCustom(t *testing.T) { + choice := decodeResponsesToolChoice(map[string]any{"type": "custom", "name": "apply_patch"}) + if choice.Mode != "named" || choice.Name != "apply_patch" { + t.Fatalf("choice = %+v, want named apply_patch", choice) + } +} diff --git a/internal/protocol/response.go b/internal/protocol/response.go index 603ffaac..87b7f3b3 100644 --- a/internal/protocol/response.go +++ b/internal/protocol/response.go @@ -109,6 +109,13 @@ func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeRespon Name: jsonutil.StringAt(item, "name"), ArgumentsJSON: jsonutil.StringAt(item, "arguments"), }) + case "custom_tool_call": + response.Tools = append(response.Tools, bridgeBlock{ + Kind: "tool_call", + ID: jsonutil.FirstString(jsonutil.StringAt(item, "call_id"), jsonutil.StringAt(item, "id")), + Name: jsonutil.StringAt(item, "name"), + ArgumentsJSON: customToolCallArguments(item["input"]), + }) default: return response, fmt.Errorf("Responses response has unsupported output item type %q", jsonutil.StringAt(item, "type")) } @@ -558,12 +565,21 @@ func renameToolInMap(payload map[string]any, protocol Protocol, renames *ToolRen if !ok { return false } - client, changed := renames.Resolve(name) - if !changed { - return false + changed := false + if transform, ok := renames.ArgumentTransform(name); ok { + if arguments, ok := container["arguments"].(string); ok { + if rewritten, err := transform(arguments); err == nil && rewritten != arguments { + container["arguments"] = rewritten + changed = true + } + } } - container["name"] = client - return true + client, renamed := renames.Resolve(name) + if renamed { + container["name"] = client + changed = true + } + return changed } renameItem := func(item map[string]any) bool { switch jsonutil.StringAt(item, "type") { diff --git a/internal/protocol/response_test.go b/internal/protocol/response_test.go new file mode 100644 index 00000000..5ed21cdd --- /dev/null +++ b/internal/protocol/response_test.go @@ -0,0 +1,37 @@ +package protocol + +import "testing" + +func TestRenameToolInMapAppliesArgumentTransform(t *testing.T) { + renames := NewToolRenames() + renames.Add("apply_patch", "clint_x") + renames.BindOfficial("patch", "apply_patch") + renames.MarkCustom("apply_patch") + renames.SetArgumentTransform("patch", func(string) (string, error) { + return customToolCallArguments("P"), nil + }) + payload := map[string]any{ + "output": []any{ + map[string]any{"type": "function_call", "name": "patch", "arguments": `{"patchText":"P"}`}, + }, + } + if !renameToolInMap(payload, Responses, renames) { + t.Fatal("renameToolInMap reported no change") + } + item := payload["output"].([]any)[0].(map[string]any) + if got := item["name"]; got != "apply_patch" { + t.Fatalf("name = %v, want apply_patch", got) + } + if got := item["arguments"]; got != `{"input":"P"}` { + t.Fatalf("arguments = %v, want the transformed input envelope", got) + } +} + +func TestCustomToolInput(t *testing.T) { + if got := customToolInput(`{"input":"hello"}`); got != "hello" { + t.Fatalf("customToolInput = %q, want hello", got) + } + if got := customToolInput(`raw`); got != "raw" { + t.Fatalf("customToolInput = %q, want the original text", got) + } +} diff --git a/internal/protocol/rotation_stream.go b/internal/protocol/rotation_stream.go index bdea42dd..83587d6c 100644 --- a/internal/protocol/rotation_stream.go +++ b/internal/protocol/rotation_stream.go @@ -56,13 +56,13 @@ func (e *ClientWriteError) Unwrap() error { return e.Err } // terminal event; a *ClientWriteError when writing to the client failed; the // error returned by ready; or whatever ended the read, errSSEUnexpectedEOF // included. A client cancellation does not get a synthetic error event. -func RotationStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, from, to Protocol, alias string, ready func() error) (usage Usage, reported, committed bool, result error) { +func RotationStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, from, to Protocol, alias string, renames *ToolRenames, ready func() error) (usage Usage, reported, committed bool, result error) { flusher, ok := w.(http.Flusher) if !ok { return usage, false, false, fmt.Errorf("streaming is unsupported") } parser := streamUsageObserver(from).parser - emitter := bridgeStreamEmitter(w, flusher, to, alias) + emitter := bridgeStreamEmitter(w, flusher, to, alias, renames.Custom) pending := []bridgeStreamEvent{} var upstreamFailure error emit := func(event bridgeStreamEvent) error { diff --git a/internal/protocol/stream.go b/internal/protocol/stream.go index 5cb6bf06..06046ac1 100644 --- a/internal/protocol/stream.go +++ b/internal/protocol/stream.go @@ -72,7 +72,7 @@ type bridgeStreamEvent struct { // A canceled client gets no synthetic upstream error event: the gateway // cancels the request context when the client goes away, and writing after // that only wastes the remaining attempt. -func TranscodeStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, from, to Protocol, model string) (Usage, bool, error) { +func TranscodeStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, from, to Protocol, model string, renames *ToolRenames) (Usage, bool, error) { flusher, ok := w.(http.Flusher) if !ok { return Usage{}, false, fmt.Errorf("response writer does not support streaming") @@ -85,7 +85,7 @@ func TranscodeStream(ctx context.Context, w http.ResponseWriter, reader io.Reade responseArgs: map[string]bool{}, responseReasoning: map[string]bool{}, } - emitter := bridgeStreamEmitter(w, flusher, to, model) + emitter := bridgeStreamEmitter(w, flusher, to, model, renames.Custom) termination := streamOpen readErr := readSSE(reader, func(eventName, data string) error { events, err := parser.Parse(eventName, data) @@ -220,7 +220,7 @@ func ForwardStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, if cause == nil { cause = errSSEUnexpectedEOF } - emitter := bridgeStreamEmitter(w, flusher, protocol, model) + emitter := bridgeStreamEmitter(w, flusher, protocol, model, nil) if err := emitUnexpectedStreamError(emitter, cause); err != nil { return usage, observer.Reported(), err } @@ -334,6 +334,8 @@ type streamToolRenameState struct { decided bool renamed bool pending string + upstream string + transform ArgumentTransform pendingArguments strings.Builder callIndex any choiceIndex any @@ -408,24 +410,40 @@ func (renamer *streamToolRenamer) rewriteChatFrame(raw string) []byte { changed = true } } - if arguments, exists := function["arguments"]; exists && !state.decided { - if renamer.renames.HasLongerPrefix(state.pending) { + if arguments, exists := function["arguments"]; exists { + if !state.decided { + if renamer.renames.HasLongerPrefix(state.pending) { + if fragment, ok := arguments.(string); ok { + state.pendingArguments.WriteString(fragment) + delete(function, "arguments") + changed = true + } + } else { + if state.pending != "" { + function["name"] = state.pending + state.upstream = state.pending + state.transform = renamer.argumentTransform(state.upstream) + changed = true + } + state.decided = true + } + } + if state.decided && state.transform != nil { if fragment, ok := arguments.(string); ok { state.pendingArguments.WriteString(fragment) delete(function, "arguments") changed = true } - } else { - if state.pending != "" { - function["name"] = state.pending - changed = true - } - state.decided = true } } - if state.decided && renamer.releasePendingArguments(state, function) { + if state.decided && state.transform == nil && renamer.releasePendingArguments(state, function) { changed = true } + if finished && state.transform != nil && state.pendingArguments.Len() > 0 { + if renamer.flushTransformedArguments(state, function) { + changed = true + } + } if finished && !state.decided && (state.pending != "" || state.pendingArguments.Len() > 0) { if renamer.finishState(state, function) { changed = true @@ -475,6 +493,31 @@ func (renamer *streamToolRenamer) releasePendingArguments(state *streamToolRenam return true } +// argumentTransform returns the registered argument rewrite for an upstream +// tool name, or nil when the call needs no translation. +func (renamer *streamToolRenamer) argumentTransform(name string) ArgumentTransform { + if transform, ok := renamer.renames.ArgumentTransform(name); ok { + return transform + } + return nil +} + +// flushTransformedArguments writes the buffered arguments of one tool call +// through its argument transform. Arguments an upstream streamed in fragments +// are complete by the time the choice finishes. +func (renamer *streamToolRenamer) flushTransformedArguments(state *streamToolRenameState, function map[string]any) bool { + if state.transform == nil || state.pendingArguments.Len() == 0 { + return false + } + arguments := state.pendingArguments.String() + if rewritten, err := state.transform(arguments); err == nil { + arguments = rewritten + } + function["arguments"] = arguments + state.pendingArguments.Reset() + return true +} + // finishState settles a call the choice finished while its name was still // ambiguous: the held-back name and arguments are emitted verbatim. func (renamer *streamToolRenamer) finishState(state *streamToolRenameState, function map[string]any) bool { @@ -499,10 +542,14 @@ func (renamer *streamToolRenamer) pendingCalls(choiceIndex any, skip map[string] continue } state := renamer.tools[key] - if state == nil || state.decided || fmt.Sprint(state.choiceIndex) != fmt.Sprint(choiceIndex) { + if state == nil || fmt.Sprint(state.choiceIndex) != fmt.Sprint(choiceIndex) { continue } - if state.pending == "" && state.pendingArguments.Len() == 0 { + if state.decided { + if state.transform == nil || state.pendingArguments.Len() == 0 { + continue + } + } else if state.pending == "" && state.pendingArguments.Len() == 0 { continue } calls = append(calls, renamer.pendingCall(state)) @@ -514,10 +561,16 @@ func (renamer *streamToolRenamer) pendingCalls(choiceIndex any, skip map[string] // decided. func (renamer *streamToolRenamer) pendingCall(state *streamToolRenameState) any { function := map[string]any{} - if state.pending != "" { + if !state.decided && state.pending != "" { function["name"] = state.pending } - if state.pendingArguments.Len() > 0 { + if state.transform != nil && state.pendingArguments.Len() > 0 { + arguments := state.pendingArguments.String() + if rewritten, err := state.transform(arguments); err == nil { + arguments = rewritten + } + function["arguments"] = arguments + } else if state.pendingArguments.Len() > 0 { function["arguments"] = state.pendingArguments.String() } call := map[string]any{"index": state.callIndex, "function": function} @@ -540,7 +593,14 @@ func (renamer *streamToolRenamer) finish() []byte { byIndex := map[string]*choiceCalls{} for _, key := range renamer.order { state := renamer.tools[key] - if state == nil || state.decided || state.pending == "" && state.pendingArguments.Len() == 0 { + if state == nil { + continue + } + if state.decided { + if state.transform == nil || state.pendingArguments.Len() == 0 { + continue + } + } else if state.pending == "" && state.pendingArguments.Len() == 0 { continue } index := state.choiceIndex @@ -596,6 +656,8 @@ func (renamer *streamToolRenamer) applyNameFragment(state *streamToolRenameState state.pending = mergeToolName(state.pending, fragment) if client, ok := renamer.renames.Client(state.pending); ok { function["name"] = client + state.upstream = state.pending + state.transform = renamer.argumentTransform(state.upstream) state.decided, state.renamed = true, true return true } @@ -610,6 +672,8 @@ func (renamer *streamToolRenamer) applyNameFragment(state *streamToolRenameState // declared is written out as the model sent it. client, renamed := renamer.renames.Resolve(state.pending) function["name"] = client + state.upstream = state.pending + state.transform = renamer.argumentTransform(state.upstream) state.decided, state.renamed = true, renamed return true } diff --git a/internal/protocol/stream_emitter.go b/internal/protocol/stream_emitter.go index 4222caba..c7005967 100644 --- a/internal/protocol/stream_emitter.go +++ b/internal/protocol/stream_emitter.go @@ -28,6 +28,7 @@ type bridgeStreamTool struct { AnthropicIndex int Started bool EmittedArguments int + Custom bool } // bridgeStreamEncoder turns bridge stream events into one downstream protocol's @@ -55,6 +56,8 @@ type bridgeStreamEncoder struct { tools map[string]*bridgeStreamTool order []string + isCustom func(string) bool + sequence int nextOutput int textOpen bool @@ -72,17 +75,24 @@ type bridgeStreamEncoder struct { // bridgeStreamEmitter builds an encoder for the target protocol. The response // ID is taken from the first event that carries one and the model from the // last event that carries one, so the constructor's model is only a fallback. -func bridgeStreamEmitter(writer io.Writer, flusher http.Flusher, target Protocol, model string) *bridgeStreamEncoder { +func bridgeStreamEmitter(writer io.Writer, flusher http.Flusher, target Protocol, model string, isCustom func(string) bool) *bridgeStreamEncoder { return &bridgeStreamEncoder{ - w: writer, - flush: flusher, - target: target, - model: model, - created: time.Now().Unix(), - tools: map[string]*bridgeStreamTool{}, + w: writer, + flush: flusher, + target: target, + model: model, + created: time.Now().Unix(), + tools: map[string]*bridgeStreamTool{}, + isCustom: isCustom, } } +// customTool reports whether a resolved client tool name is a freeform custom +// tool that the client expects as a custom_tool_call item. +func (emitter *bridgeStreamEncoder) customTool(name string) bool { + return emitter.isCustom != nil && emitter.isCustom(name) +} + // Emit encodes one bridge stream event for the target protocol. The response // is opened before the first start or content event. "error" writes an in-band // error event and then returns errStreamUpstreamFailure; "done" finishes the @@ -456,6 +466,7 @@ func (emitter *bridgeStreamEncoder) startTool(tool *bridgeStreamTool) error { emitter.textOpen = false } tool.Started = true + tool.Custom = emitter.customTool(tool.Name) switch emitter.target { case Chat: return emitter.chatChunk(map[string]any{"tool_calls": []any{map[string]any{ @@ -471,6 +482,9 @@ func (emitter *bridgeStreamEncoder) startTool(tool *bridgeStreamTool) error { tool.Index = emitter.nextOutput emitter.nextOutput++ item := map[string]any{"id": tool.ItemID, "type": "function_call", "status": "in_progress", "arguments": "", "call_id": tool.ID, "name": tool.Name} + if tool.Custom { + item = map[string]any{"id": tool.ItemID, "type": "custom_tool_call", "status": "in_progress", "input": "", "call_id": tool.ID, "name": tool.Name} + } return emitter.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": tool.Index, "item": item, "sequence_number": emitter.nextSequence()}) case Anthropic: tool.AnthropicIndex = emitter.nextAnthropic @@ -496,6 +510,11 @@ func (emitter *bridgeStreamEncoder) emitToolDelta(tool *bridgeStreamTool, delta "function": map[string]any{"arguments": delta}, }}}, nil) case Responses: + if tool.Custom { + // Custom tool input is freeform text, while the upstream streamed a + // JSON envelope. The complete input is delivered on the done item. + return nil + } return emitter.sse("response.function_call_arguments.delta", map[string]any{"type": "response.function_call_arguments.delta", "delta": delta, "item_id": tool.ItemID, "output_index": tool.Index, "sequence_number": emitter.nextSequence()}) case Anthropic: return emitter.sse("content_block_delta", map[string]any{"type": "content_block_delta", "index": tool.AnthropicIndex, "delta": map[string]any{"type": "input_json_delta", "partial_json": delta}}) @@ -617,6 +636,20 @@ func (emitter *bridgeStreamEncoder) Finish() error { response.Tools = append(response.Tools, bridgeBlock{Kind: "tool_call", ID: tool.ID, Name: tool.Name, ArgumentsJSON: tool.Arguments.String()}) } completed := encodeBridgeResponse(Responses, response) + if output, ok := completed["output"].([]any); ok { + for _, rawItem := range output { + item, _ := rawItem.(map[string]any) + if jsonutil.StringAt(item, "type") != "function_call" { + continue + } + if !emitter.customTool(jsonutil.StringAt(item, "name")) { + continue + } + item["type"] = "custom_tool_call" + item["input"] = customToolInput(jsonutil.StringAt(item, "arguments")) + delete(item, "arguments") + } + } return emitter.sse("response.completed", map[string]any{"type": "response.completed", "response": completed, "sequence_number": emitter.nextSequence()}) } return nil @@ -649,6 +682,13 @@ func (emitter *bridgeStreamEncoder) finishResponsesItems() error { if err := emitter.startTool(tool); err != nil { return err } + if tool.Custom { + item := map[string]any{"id": tool.ItemID, "type": "custom_tool_call", "status": "completed", "input": customToolInput(arguments), "call_id": tool.ID, "name": tool.Name} + if err := emitter.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": tool.Index, "item": item, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + continue + } if err := emitter.emitPendingToolArguments(tool); err != nil { return err } @@ -663,6 +703,18 @@ func (emitter *bridgeStreamEncoder) finishResponsesItems() error { return nil } +// customToolInput unwraps the bridge's JSON envelope around a custom tool's +// freeform input; the item itself carries the raw text. +func customToolInput(arguments string) string { + var payload map[string]any + if err := json.Unmarshal([]byte(arguments), &payload); err == nil { + if input, ok := payload["input"].(string); ok { + return input + } + } + return arguments +} + // chatChunk writes one Chat chunk with the given delta and finish_reason. func (emitter *bridgeStreamEncoder) chatChunk(delta map[string]any, finish any) error { return emitter.sse("", map[string]any{ diff --git a/internal/protocol/tools.go b/internal/protocol/tools.go index e6ab03a7..51ff1e0b 100644 --- a/internal/protocol/tools.go +++ b/internal/protocol/tools.go @@ -22,6 +22,11 @@ const clientToolDigestLength = 12 // toolWireNameLimit is the longest tool name the upstreams accept. const toolWireNameLimit = 64 +// ArgumentTransform rewrites the JSON arguments of one upstream tool call into +// the argument shape of the client tool it is mapped to. It returns the +// original arguments unchanged when the call cannot be translated. +type ArgumentTransform func(arguments string) (string, error) + // ToolRenames records the client-to-wire tool names of one shaped request. The // zero value and a nil pointer are both empty and safe to use. type ToolRenames struct { @@ -33,16 +38,25 @@ type ToolRenames struct { // name is never guessed between. byCase map[string]string byShape map[string]string + // transforms rewrites the arguments of official tool calls that are bound + // to a client tool with a different argument schema. + transforms map[string]ArgumentTransform + // custom marks client tools that the client declared as freeform custom + // tools (Codex's apply_patch); their results must be returned as custom + // tool calls, not function calls. + custom map[string]bool } // NewToolRenames returns an empty rename set. func NewToolRenames() *ToolRenames { return &ToolRenames{ - toWire: map[string]string{}, - toClient: map[string]string{}, - official: map[string]string{}, - byCase: map[string]string{}, - byShape: map[string]string{}, + toWire: map[string]string{}, + toClient: map[string]string{}, + official: map[string]string{}, + byCase: map[string]string{}, + byShape: map[string]string{}, + transforms: map[string]ArgumentTransform{}, + custom: map[string]bool{}, } } @@ -99,6 +113,52 @@ func (r *ToolRenames) Official(official string) (string, bool) { return client, ok } +// SetArgumentTransform registers the argument rewrite for one official tool +// name. It is only consulted when the upstream reports that official name. +func (r *ToolRenames) SetArgumentTransform(official string, transform ArgumentTransform) { + if r == nil || official == "" || transform == nil { + return + } + if r.transforms == nil { + r.transforms = map[string]ArgumentTransform{} + } + r.transforms[official] = transform +} + +// ArgumentTransform returns the registered argument rewrite for an upstream +// tool name. +func (r *ToolRenames) ArgumentTransform(name string) (ArgumentTransform, bool) { + if r == nil || name == "" { + return nil, false + } + transform, ok := r.transforms[name] + return transform, ok +} + +// MarkCustom records a declared client tool as a freeform custom tool. A name +// the request did not rename is ignored so Custom never reports an undeclared +// tool. +func (r *ToolRenames) MarkCustom(client string) { + if r == nil || client == "" { + return + } + if _, ok := r.toWire[client]; !ok { + return + } + if r.custom == nil { + r.custom = map[string]bool{} + } + r.custom[client] = true +} + +// Custom reports whether a client tool was declared as a freeform custom tool. +func (r *ToolRenames) Custom(client string) bool { + if r == nil || client == "" { + return false + } + return r.custom[client] +} + // Add records one client-to-wire mapping. Adding the same pair twice is a // no-op; a conflicting pair keeps the first wire name so the map stays // invertible.