diff --git a/README.md b/README.md index ed91e6f..b8d2fc4 100644 --- a/README.md +++ b/README.md @@ -264,7 +264,7 @@ Injection is protocol-aware: Chat system and developer messages are folded into On every shaped free-model request the gateway replaces each named client tool with an opaque wire name, `clint_` plus the first 12 hex characters of the client name's SHA-256 (collisions get a `_2`, `_3`, … suffix), and appends the complete official tool set for the lane: the 1.x definitions (`bash`, `edit`, `glob`, `grep`, `read`, `skill`, `task`, `todowrite`, `webfetch`, `websearch`, `write`) on `/zen`, and the 13-tool 2.x set on `/inference` and `/zen/go`. The digest is not cosmetic: the free tier refuses a shaped body that still carries another client's vocabulary — a Claude Code request that declares both `ReportFindings` and `ScheduleWakeup` is answered with `FreeUsageLimitError`, and removing either name lifts the refusal — so no client tool name reaches the wire. Requests without a `tools` array, with an empty one, or with a legacy `functions` array get the same official set; `tool_choice`, legacy `function_call`, and the tool-call history are rewritten to match. Responses built-in tools and Anthropic server tools are left untouched. -Responses are restored to the names the client declared, for streaming and non-streaming replies, including a Chat tool name split across chunks. If the upstream calls an official tool the client never declared, that name passes through unchanged: the gateway does not replay or hide official tool calls. +Responses are restored to client-declared names in streaming and non-streaming replies, including Chat tool names split across chunks. An official name is mapped when the client declared an equivalent tool; otherwise it remains unchanged in the response. In request history, unknown tool calls and official calls without a declared equivalent are removed with their paired results, and a named `tool_choice` targeting one of those dropped calls is removed too. ### Free model availability diff --git a/README.zh-CN.md b/README.zh-CN.md index c0317d9..9ebc85d 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -262,9 +262,9 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答 ### 工具整形 -每个经过整形的免费模型请求中,网关会把客户端声明的每个具名工具改名为 `clint_`——`A-Za-z0-9_-` 之外的字符替换为 `_`,名称最长 64 字节,冲突时追加 `_2`、`_3` 等后缀——并追加该通道的完整官方工具集:`/zen` 使用 1.x 定义(`bash`、`edit`、`glob`、`grep`、`read`、`skill`、`task`、`todowrite`、`webfetch`、`websearch`、`write`),`/inference` 与 `/zen/go` 使用 13 个工具的 2.x 定义。没有 `tools`、`tools` 为空数组或使用旧版 `functions` 数组的请求同样会补全官方工具集;`tool_choice`、旧版 `function_call` 和工具调用历史会同步改写。Responses 内置工具和 Anthropic 服务端工具保持不变。 +每个经过整形的免费模型请求中,网关会把客户端声明的每个具名工具改名为不透明的线上名称 `clint_` 加上客户端名称 SHA-256 的前 12 个十六进制字符(冲突时追加 `_2`、`_3` 等后缀),并追加该通道的完整官方工具集:`/zen` 使用 1.x 定义(`bash`、`edit`、`glob`、`grep`、`read`、`skill`、`task`、`todowrite`、`webfetch`、`websearch`、`write`),`/inference` 与 `/zen/go` 使用 13 个工具的 2.x 定义。没有 `tools`、`tools` 为空数组或使用旧版 `functions` 数组的请求同样会补全官方工具集;`tool_choice`、旧版 `function_call` 和工具调用历史会同步改写。Responses 内置工具和 Anthropic 服务端工具保持不变。 -响应会恢复为客户端声明的名称,流式与非流式均适用,包括被拆分到多个 Chat 分块中的工具名。如果上游调用了客户端从未声明的官方工具,该名称会原样透传:网关不会重放或隐藏官方工具调用。 +响应(包括流式与非流式,以及拆分到多个 Chat 分块中的工具名)会恢复为客户端声明的名称。只有在客户端声明了等价工具时,官方工具名才会映射到客户端名称;否则响应中的名称保持原样。整形请求历史时,未知工具调用以及没有客户端等价工具的官方调用会连同配对的结果一起移除;若具名 `tool_choice` 指向被移除的工具,也会一并移除。 ### 免费模型可用性 diff --git a/internal/gateway/toolshape.go b/internal/gateway/toolshape.go index 72f2820..20253ee 100644 --- a/internal/gateway/toolshape.go +++ b/internal/gateway/toolshape.go @@ -87,6 +87,40 @@ func officialToolNames(v1 bool) []string { return v2OfficialToolOrder } +// OfficialToolCandidates returns client tool names equivalent to an official name. +func OfficialToolCandidates(officialName string) []string { + switch strings.ToLower(officialName) { + case "bash", "shell": + return []string{"Bash"} + case "edit": + return []string{"Edit"} + case "glob": + return []string{"Glob"} + case "grep": + return []string{"Grep"} + case "question": + return []string{"AskUserQuestion"} + case "read": + return []string{"Read"} + case "skill": + return []string{"Skill"} + case "subagent", "task": + return []string{"Agent", "Task", "Subagent"} + case "todowrite": + return []string{"TodoWrite"} + case "webfetch": + return []string{"WebFetch"} + case "websearch": + return []string{"WebSearch"} + case "write": + return []string{"Write"} + case "patch": + return []string{"Patch"} + default: + return nil + } +} + // officialToolDefinition returns the captured definition for an official name. func officialToolDefinition(name string, v1 bool) (opencodeToolDefinition, bool) { loadOfficialTools() @@ -191,8 +225,26 @@ func renameAndCompleteTools(payload map[string]any, protocol wire.Protocol, v1 b items = list } } + declaredNames := make([]string, 0, len(items)) + for _, item := range items { + entry, ok := item.(map[string]any) + if !ok { + continue + } + if name, ok := renamableToolName(protocol, entry); ok { + declaredNames = append(declaredNames, name) + } + } if protocol == wire.Chat || protocol == wire.Responses { if legacy, ok := payload["functions"].([]any); ok { + for _, rawEntry := range legacy { + entry, ok := rawEntry.(map[string]any) + if ok { + if name := jsonutil.StringAt(entry, "name"); name != "" { + declaredNames = append(declaredNames, name) + } + } + } items = append(items, convertLegacyFunctions(legacy, protocol, renames, used)...) delete(payload, "functions") } @@ -216,10 +268,243 @@ func renameAndCompleteTools(payload map[string]any, protocol wire.Protocol, v1 b } shaped = append(shaped, officialToolset(protocol, v1)...) payload["tools"] = shaped + officialNames := officialToolNames(v1) + bindOfficialToolAliases(renames, declaredNames, officialNames) + declared := make(map[string]string, len(declaredNames)) + for _, name := range declaredNames { + if wireName, ok := renames.Wire(name); ok { + declared[name] = wireName + } + } + sanitizeToolHistory(payload, protocol, declared, renames, officialToolNameSet(v1)) rewriteToolReferences(payload, protocol, renames) return renames, true } +func bindOfficialToolAliases(renames *wire.ToolRenames, declaredNames, officialNames []string) { + for _, official := range officialNames { + candidates := OfficialToolCandidates(official) + for _, declared := range declaredNames { + if _, exists := renames.Wire(declared); !exists { + continue + } + for _, candidate := range candidates { + if match, _ := renames.Resolve(candidate); match == declared { + renames.BindOfficial(official, declared) + break + } + } + if _, exists := renames.Official(official); exists { + break + } + } + } +} + +func officialToolNameSet(v1 bool) map[string]bool { + set := make(map[string]bool) + for _, name := range officialToolNames(v1) { + set[name] = true + } + return set +} + +func sanitizeToolHistory(payload map[string]any, protocol wire.Protocol, declared map[string]string, renames *wire.ToolRenames, laneOfficial map[string]bool) { + dropped := map[string]bool{} + switch protocol { + case wire.Anthropic: + messages := jsonutil.SliceAt(payload, "messages") + for _, rawMessage := range messages { + message, _ := rawMessage.(map[string]any) + for _, rawBlock := range jsonutil.SliceAt(message, "content") { + block, _ := rawBlock.(map[string]any) + if jsonutil.StringAt(block, "type") != "tool_use" { + continue + } + name := jsonutil.StringAt(block, "name") + if wireName, ok := historyToolWireName(name, declared, renames, laneOfficial); ok { + block["name"] = wireName + } else if id := jsonutil.StringAt(block, "id"); id != "" { + dropped[id] = true + } + } + } + keptMessages := make([]any, 0, len(messages)) + for _, rawMessage := range messages { + message, _ := rawMessage.(map[string]any) + content, ok := message["content"].([]any) + if !ok { + keptMessages = append(keptMessages, rawMessage) + continue + } + keptContent := make([]any, 0, len(content)) + for _, rawBlock := range content { + block, _ := rawBlock.(map[string]any) + switch jsonutil.StringAt(block, "type") { + case "tool_use": + if _, ok := historyToolWireName(jsonutil.StringAt(block, "name"), declared, renames, laneOfficial); !ok { + continue + } + case "tool_result": + if dropped[jsonutil.StringAt(block, "tool_use_id")] { + continue + } + } + keptContent = append(keptContent, rawBlock) + } + if len(keptContent) == 0 { + continue + } + message["content"] = keptContent + keptMessages = append(keptMessages, rawMessage) + } + payload["messages"] = keptMessages + case wire.Chat: + messages := jsonutil.SliceAt(payload, "messages") + dropEmptyMessages := make(map[int]bool) + for index, rawMessage := range messages { + message, _ := rawMessage.(map[string]any) + calls, ok := message["tool_calls"].([]any) + if !ok { + continue + } + keptCalls := make([]any, 0, len(calls)) + for _, rawCall := range calls { + call, _ := rawCall.(map[string]any) + function, _ := call["function"].(map[string]any) + name := jsonutil.StringAt(function, "name") + if wireName, ok := historyToolWireName(name, declared, renames, laneOfficial); ok { + function["name"] = wireName + keptCalls = append(keptCalls, rawCall) + } else if id := jsonutil.StringAt(call, "id"); id != "" { + dropped[id] = true + } + } + if len(keptCalls) == 0 { + delete(message, "tool_calls") + dropEmptyMessages[index] = len(calls) > 0 + } else { + message["tool_calls"] = keptCalls + } + } + keptMessages := make([]any, 0, len(messages)) + for index, rawMessage := range messages { + message, _ := rawMessage.(map[string]any) + if jsonutil.StringAt(message, "role") == "tool" && dropped[jsonutil.StringAt(message, "tool_call_id")] { + continue + } + if dropEmptyMessages[index] && !chatMessageHasContent(message) { + continue + } + keptMessages = append(keptMessages, rawMessage) + } + payload["messages"] = keptMessages + case wire.Responses: + items := jsonutil.SliceAt(payload, "input") + for _, rawItem := range items { + item, _ := rawItem.(map[string]any) + switch jsonutil.StringAt(item, "type") { + case "function_call", "custom_tool_call": + name := jsonutil.StringAt(item, "name") + if wireName, ok := historyToolWireName(name, declared, renames, laneOfficial); ok { + item["name"] = wireName + } else if id := jsonutil.FirstString(jsonutil.StringAt(item, "call_id"), jsonutil.StringAt(item, "id")); id != "" { + dropped[id] = true + } + } + } + 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" || kind == "custom_tool_call" { + if _, ok := historyToolWireName(jsonutil.StringAt(item, "name"), declared, renames, laneOfficial); !ok { + continue + } + } + keptItems = append(keptItems, rawItem) + } + payload["input"] = keptItems + } + sanitizeToolChoice(payload, protocol, declared, renames, laneOfficial) +} + +func historyToolWireName(name string, declared map[string]string, renames *wire.ToolRenames, laneOfficial map[string]bool) (string, bool) { + if wireName, ok := declared[name]; ok { + return wireName, true + } + if _, ok := renames.Client(name); ok { + return name, true + } + if laneOfficial[name] { + client, ok := renames.Official(name) + if !ok { + client, _ = renames.Resolve(name) + } + if wireName, ok := declared[client]; ok { + return wireName, true + } + return renames.Wire(client) + } + client, _ := renames.Resolve(name) + if wireName, ok := declared[client]; ok { + return wireName, true + } + return "", false +} + +func chatMessageHasContent(message map[string]any) bool { + for _, key := range []string{"content", "reasoning_content", "reasoning"} { + switch value := message[key].(type) { + case string: + if value != "" { + return true + } + case []any: + if len(value) > 0 { + return true + } + case map[string]any: + if len(value) > 0 { + return true + } + case nil: + default: + return true + } + } + return false +} + +func sanitizeToolChoice(payload map[string]any, protocol wire.Protocol, declared map[string]string, renames *wire.ToolRenames, laneOfficial map[string]bool) { + choice, ok := payload["tool_choice"].(map[string]any) + if !ok { + return + } + kind := jsonutil.StringAt(choice, "type") + if kind != "tool" && kind != "function" && kind != "custom" { + return + } + target := choice + if protocol == wire.Chat { + if function, ok := choice["function"].(map[string]any); ok { + target = function + } + } + name := jsonutil.StringAt(target, "name") + if name == "" { + return + } + wireName, ok := historyToolWireName(name, declared, renames, laneOfficial) + if !ok { + delete(payload, "tool_choice") + return + } + target["name"] = wireName +} + // renamableToolName returns the client tool name of one definition. Responses // built-in tools (web search and similar) have no client name and are left // untouched. diff --git a/internal/protocol/stream.go b/internal/protocol/stream.go index 4e61a6c..e5cbf86 100644 --- a/internal/protocol/stream.go +++ b/internal/protocol/stream.go @@ -273,6 +273,17 @@ func (reader *renameStreamReader) Read(data []byte) (int, error) { // The final chunk is drained before the error is reported so a // truncated stream still delivers every byte the upstream sent. reader.err = err + if errors.Is(err, io.EOF) { + if final := reader.renamer.finish(); len(final) > 0 { + if len(reader.pending) > 0 && !bytes.HasSuffix(reader.pending, []byte("\n\n")) && !bytes.HasSuffix(reader.pending, []byte("\r\n\r\n")) { + if !bytes.HasSuffix(reader.pending, []byte("\n")) { + reader.pending = append(reader.pending, '\n') + } + reader.pending = append(reader.pending, '\n') + } + reader.pending = append(reader.pending, final...) + } + } if len(reader.pending) == 0 { return 0, err } @@ -299,7 +310,13 @@ func (reader *renameStreamReader) rewriteLine(line string) []byte { return []byte(line) } raw := strings.TrimSpace(strings.TrimPrefix(body, "data:")) - if raw == "" || raw == "[DONE]" { + if raw == "" { + return []byte(line) + } + if raw == "[DONE]" { + if final := reader.renamer.finish(); len(final) > 0 { + return append(final, []byte(line)...) + } return []byte(line) } rewritten := reader.renamer.rewriteFrame(raw) @@ -314,9 +331,12 @@ func (reader *renameStreamReader) rewriteLine(line string) []byte { // fragments, so a value that is still a prefix of a known wire name is held // back until it either completes the match or diverges. type streamToolRenameState struct { - decided bool - renamed bool - pending string + decided bool + renamed bool + pending string + pendingArguments strings.Builder + callIndex any + choiceIndex any } // streamToolRenamer rewrites the tool names of one protocol's SSE frames, @@ -326,6 +346,7 @@ type streamToolRenamer struct { protocol Protocol renames *ToolRenames tools map[string]*streamToolRenameState + order []string } // rewriteFrame rewrites one SSE data payload, which is raw JSON text. Frames @@ -341,7 +362,7 @@ func (renamer *streamToolRenamer) rewriteFrame(raw string) []byte { } return RenameResponseTool([]byte(raw), renamer.protocol, renamer.renames) } - if !strings.Contains(raw, `"tool_calls"`) { + if !strings.Contains(raw, `"tool_calls"`) && !strings.Contains(raw, `"finish_reason"`) { return []byte(raw) } return renamer.rewriteChatFrame(raw) @@ -357,8 +378,15 @@ func (renamer *streamToolRenamer) rewriteChatFrame(raw string) []byte { return []byte(raw) } changed := false - for _, rawChoice := range jsonutil.SliceAt(payload, "choices") { + for choicePosition, rawChoice := range jsonutil.SliceAt(payload, "choices") { choice, _ := rawChoice.(map[string]any) + choiceIndex := choice["index"] + if choiceIndex == nil { + choiceIndex = choicePosition + } + finishReason, hasFinishReason := choice["finish_reason"].(string) + finished := hasFinishReason && finishReason != "" + seen := map[string]bool{} for _, container := range []string{"delta", "message"} { message, _ := choice[container].(map[string]any) if message == nil { @@ -370,23 +398,53 @@ func (renamer *streamToolRenamer) rewriteChatFrame(raw string) []byte { if function == nil { continue } - state := renamer.toolState(fmt.Sprint(jsonutil.FirstAny(call["index"], jsonutil.StringAt(call, "id"), callIndex))) + key := fmt.Sprint(jsonutil.FirstAny(call["index"], jsonutil.StringAt(call, "id"), callIndex)) + state := renamer.toolState(key) + state.callIndex = jsonutil.FirstAny(call["index"], callIndex) + state.choiceIndex = choiceIndex + seen[key] = true if name, ok := function["name"].(string); ok && name != "" { if renamer.applyNameFragment(state, function, name) { changed = true } } - if _, ok := function["arguments"]; ok && !state.decided { - // Arguments can only start once the name is complete: flush - // whatever was held back, verbatim. - if state.pending != "" { - function["name"] = state.pending + if arguments, exists := function["arguments"]; exists && !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 + changed = true + } + state.decided = true + } + } + if state.decided && renamer.releasePendingArguments(state, function) { + changed = true + } + if finished && !state.decided && (state.pending != "" || state.pendingArguments.Len() > 0) { + if renamer.finishState(state, function) { changed = true } - state.decided = true } } } + if finished { + if calls := renamer.pendingCalls(choiceIndex, seen); len(calls) > 0 { + delta, _ := choice["delta"].(map[string]any) + if delta == nil { + delta = map[string]any{} + choice["delta"] = delta + } + existing := jsonutil.SliceAt(delta, "tool_calls") + delta["tool_calls"] = append(existing, calls...) + changed = true + } + } } if !changed { return []byte(raw) @@ -398,6 +456,114 @@ func (renamer *streamToolRenamer) rewriteChatFrame(raw string) []byte { return encoded } +func (renamer *streamToolRenamer) releasePendingArguments(state *streamToolRenameState, function map[string]any) bool { + if state.pendingArguments.Len() == 0 { + return false + } + arguments := state.pendingArguments.String() + if current, exists := function["arguments"]; exists { + fragment, ok := current.(string) + if !ok { + return false + } + arguments += fragment + } + function["arguments"] = arguments + state.pendingArguments.Reset() + return true +} + +func (renamer *streamToolRenamer) finishState(state *streamToolRenameState, function map[string]any) bool { + changed := false + if state.pending != "" { + function["name"] = state.pending + changed = true + } + if renamer.releasePendingArguments(state, function) { + changed = true + } + state.decided, state.renamed = true, false + return changed +} + +func (renamer *streamToolRenamer) pendingCalls(choiceIndex any, skip map[string]bool) []any { + var calls []any + for _, key := range renamer.order { + if skip[key] { + continue + } + state := renamer.tools[key] + if state == nil || state.decided || fmt.Sprint(state.choiceIndex) != fmt.Sprint(choiceIndex) { + continue + } + if state.pending == "" && state.pendingArguments.Len() == 0 { + continue + } + calls = append(calls, renamer.pendingCall(state)) + } + return calls +} + +func (renamer *streamToolRenamer) pendingCall(state *streamToolRenameState) any { + function := map[string]any{} + if state.pending != "" { + function["name"] = state.pending + } + if state.pendingArguments.Len() > 0 { + function["arguments"] = state.pendingArguments.String() + } + call := map[string]any{"index": state.callIndex, "function": function} + state.decided, state.renamed = true, false + state.pendingArguments.Reset() + return call +} + +func (renamer *streamToolRenamer) finish() []byte { + if renamer.protocol != Chat { + return nil + } + type choiceCalls struct { + index any + calls []any + } + var groups []*choiceCalls + byIndex := map[string]*choiceCalls{} + for _, key := range renamer.order { + state := renamer.tools[key] + if state == nil || state.decided || state.pending == "" && state.pendingArguments.Len() == 0 { + continue + } + index := state.choiceIndex + if index == nil { + index = 0 + } + indexKey := fmt.Sprint(index) + group := byIndex[indexKey] + if group == nil { + group = &choiceCalls{index: index} + byIndex[indexKey] = group + groups = append(groups, group) + } + group.calls = append(group.calls, renamer.pendingCall(state)) + } + if len(groups) == 0 { + return nil + } + choices := make([]any, 0, len(groups)) + for _, group := range groups { + choices = append(choices, map[string]any{ + "index": group.index, + "delta": map[string]any{"tool_calls": group.calls}, + "finish_reason": nil, + }) + } + encoded, err := json.Marshal(map[string]any{"choices": choices}) + if err != nil { + return nil + } + return append(append([]byte("data: "), encoded...), '\n', '\n') +} + // applyNameFragment folds one name fragment into a tool's rename state and // reports whether the frame changed. Once the accumulated name matches a wire // name exactly, it is replaced by the client name; while it is still a proper @@ -446,6 +612,7 @@ func (renamer *streamToolRenamer) toolState(key string) *streamToolRenameState { } state := &streamToolRenameState{} renamer.tools[key] = state + renamer.order = append(renamer.order, key) return state } diff --git a/internal/protocol/tools.go b/internal/protocol/tools.go index 6efe2a7..e6ab03a 100644 --- a/internal/protocol/tools.go +++ b/internal/protocol/tools.go @@ -27,6 +27,7 @@ const toolWireNameLimit = 64 type ToolRenames struct { toWire map[string]string toClient map[string]string + official map[string]string // byCase and byShape map a folded client name back to the one declared // client tool it names. A value of "" marks a fold two tools share: that // name is never guessed between. @@ -39,6 +40,7 @@ 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{}, } @@ -75,6 +77,28 @@ func (r *ToolRenames) Client(wire string) (string, bool) { return client, ok } +// BindOfficial records the declared client tool that matches one official name. +func (r *ToolRenames) BindOfficial(official, client string) { + if r == nil || official == "" || client == "" { + return + } + if r.official == nil { + r.official = map[string]string{} + } + if _, exists := r.official[official]; !exists { + r.official[official] = client + } +} + +// Official returns the declared client tool bound to an official name. +func (r *ToolRenames) Official(official string) (string, bool) { + if r == nil || official == "" { + return "", false + } + client, ok := r.official[official] + return client, ok +} + // 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. @@ -159,8 +183,9 @@ func (r *ToolRenames) HasLongerPrefix(prefix string) bool { // Resolve maps a tool name the upstream reported back to the name the client // declared. It is the response-side counterpart of the wire rename: an exact -// wire name restores, a clint_ prefix is stripped as a best-effort recovery -// (for example after a configuration reload mid-stream), and a name that +// wire name restores, an official alias maps to the matching client tool, a +// clint_ prefix is stripped as a best-effort recovery (for example after a +// configuration reload mid-stream), and a name that // differs from exactly one declared client tool only in case, or else only in // case and separators (todowrite → todo_write), is folded onto that tool. A // name two tools fold to is never guessed between. It reports whether the @@ -172,6 +197,9 @@ func (r *ToolRenames) Resolve(wire string) (string, bool) { if client, ok := r.Client(wire); ok { return client, client != wire } + if client, ok := r.Official(wire); ok { + return client, client != wire + } client := wire if rest, ok := strings.CutPrefix(wire, ClientToolPrefix); ok && rest != "" { client = rest