mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
fix(free-tier): hide client tool names from shaped requests (#161)
The free tier refuses a shaped body whose tool list still reads as another client's session. A Claude Code request that declares both ReportFindings and ScheduleWakeup is answered with FreeUsageLimitError — the same 429 a genuinely exhausted IP receives — and the refusal is deterministic: rename either name and the same request succeeds, and two empty placeholder tools carrying just those two names reproduce it. Schema, size and tool count do not matter. The gateway forwarded client tools as clint_<name>, so every Claude Code session behind CLIProxyAPI was refused (14 tools, both markers present) while the official CLI kept working and small requests through the gateway were fine. Client tools now get an opaque wire name: clint_ plus 12 hex characters of the name's SHA-256, collision-suffixed like before. Descriptions and schemas are untouched, so the model still knows what a tool does, and the response path still restores the names the client declared, streaming included. Verified against the captured Claude Code request (95 KB, 14 tools): 3/3 429 before the change, 3/3 200 after, and the same request replayed through CLIProxyAPI (Anthropic /v1/messages -> chat -> /inference) returns 200. Session ids are unaffected: they are normalized by CanonicalSessionID, and an implausible session timestamp is a separate 429 trigger documented there.
This commit is contained in:
1 parent
9946e66fa6
commit
4a4db10387
6 files changed
+194
-37
No files matched your search
@@ -262,7 +262,7 @@ Injection is protocol-aware: Chat system and developer messages are folded into
|
||||
|
||||
### Tool shaping
|
||||
|
||||
On every shaped free-model request the gateway renames each named client tool to `clint_<name>` — characters outside `A-Za-z0-9_-` become `_`, names are capped at 64 bytes, and 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`. 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.
|
||||
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.
|
||||
|
||||
|
||||
@@ -174,7 +174,7 @@ func v1BashDescription(base string) string {
|
||||
}
|
||||
|
||||
// renameAndCompleteTools makes the tool list read as an official CLI session:
|
||||
// every named client tool is renamed with the clint_ prefix, legacy functions
|
||||
// every named client tool is renamed to an opaque wire name, legacy functions
|
||||
// arrays are converted, and the full official set for the lane is appended.
|
||||
// The returned map restores the client names in the upstream response.
|
||||
func renameAndCompleteTools(payload map[string]any, protocol wire.Protocol, v1 bool) (*wire.ToolRenames, bool) {
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
wire "opencode2api/internal/protocol"
|
||||
)
|
||||
|
||||
// TestPrepareAnonymousBodyHidesClientToolNames pins the fix for the free tier's
|
||||
// client detection: a Claude Code request that declares both of these tools is
|
||||
// answered with FreeUsageLimitError, and renaming either name lifts the
|
||||
// refusal. The shaped body must therefore never spell a client tool name.
|
||||
func TestPrepareAnonymousBodyHidesClientToolNames(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"model": "deepseek-v4.1-flash-free",
|
||||
"messages": [{"role": "user", "content": "hi"}],
|
||||
"stream": false,
|
||||
"tools": [
|
||||
{"type": "function", "function": {"name": "Read", "description": "Read a file.",
|
||||
"parameters": {"type": "object", "properties": {"file_path": {"type": "string"}}}}},
|
||||
{"type": "function", "function": {"name": "ReportFindings", "description": "Report findings.",
|
||||
"parameters": {"type": "object", "properties": {}}}},
|
||||
{"type": "function", "function": {"name": "ScheduleWakeup", "description": "Schedule a wakeup.",
|
||||
"parameters": {"type": "object", "properties": {}}}}
|
||||
]
|
||||
}`)
|
||||
|
||||
shaped, renames := prepareAnonymousBody(body, wire.Chat, false)
|
||||
if len(shaped) == 0 {
|
||||
t.Fatal("no shaped body")
|
||||
}
|
||||
text := string(shaped)
|
||||
// The two Claude Code markers are distinctive enough to assert over the
|
||||
// whole body; a generic name like Read also appears in the official prompt
|
||||
// prose, so the tool list is what must stay free of it.
|
||||
for _, marker := range []string{"ReportFindings", "ScheduleWakeup"} {
|
||||
if strings.Contains(text, marker) {
|
||||
t.Errorf("shaped body still spells the client tool %q", marker)
|
||||
}
|
||||
}
|
||||
for _, client := range []string{"Read", "ReportFindings", "ScheduleWakeup"} {
|
||||
if _, ok := renames.Wire(client); !ok {
|
||||
t.Errorf("no wire name recorded for %q", client)
|
||||
}
|
||||
}
|
||||
|
||||
var payload struct {
|
||||
Stream bool `json:"stream"`
|
||||
Tools []struct {
|
||||
Function struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"function"`
|
||||
} `json:"tools"`
|
||||
}
|
||||
if err := json.Unmarshal(shaped, &payload); err != nil {
|
||||
t.Fatalf("shaped body is not JSON: %v", err)
|
||||
}
|
||||
if !payload.Stream {
|
||||
t.Error("shaped body is not streaming")
|
||||
}
|
||||
names := make(map[string]bool, len(payload.Tools))
|
||||
for _, tool := range payload.Tools {
|
||||
names[tool.Function.Name] = true
|
||||
}
|
||||
// The official set is what makes the request read as an OpenCode session;
|
||||
// dropping it is refused just like keeping a foreign tool name.
|
||||
for _, official := range []string{"read", "edit", "shell"} {
|
||||
if !names[official] {
|
||||
t.Errorf("shaped body is missing the official tool %q", official)
|
||||
}
|
||||
}
|
||||
for client := range map[string]bool{"Read": true, "ReportFindings": true, "ScheduleWakeup": true} {
|
||||
wireName, _ := renames.Wire(client)
|
||||
if !names[wireName] {
|
||||
t.Errorf("client tool %q is not declared under its wire name %q", client, wireName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrepareAnonymousBodyRestoresToolCalls keeps the response side honest: a
|
||||
// call the model makes to a renamed client tool comes back under the name the
|
||||
// client declared.
|
||||
func TestPrepareAnonymousBodyRestoresToolCalls(t *testing.T) {
|
||||
body := []byte(`{"model":"deepseek-v4.1-flash-free","messages":[{"role":"user","content":"hi"}],
|
||||
"tools":[{"type":"function","function":{"name":"ScheduleWakeup","parameters":{"type":"object","properties":{}}}}]}`)
|
||||
_, renames := prepareAnonymousBody(body, wire.Chat, false)
|
||||
wireName, ok := renames.Wire("ScheduleWakeup")
|
||||
if !ok {
|
||||
t.Fatal("no wire name recorded")
|
||||
}
|
||||
if got := renames.Restore(wireName); got != "ScheduleWakeup" {
|
||||
t.Errorf("Restore(%q) = %q, want ScheduleWakeup", wireName, got)
|
||||
}
|
||||
}
|
||||
@@ -587,11 +587,13 @@ func (g *Gateway) inferenceClient(proxy *proxyTransport, baseURL, model string)
|
||||
// tools are renamed and completed for the lane v1 selects; an unchanged body is
|
||||
// returned as is.
|
||||
//
|
||||
// Every named client tool becomes clint_<name> (sanitized and collision-safe)
|
||||
// and the full official set for the lane is appended, so the request looks like
|
||||
// an official CLI session on both the v1 (/zen) and v2 lanes. System One
|
||||
// payloads are decision requests, not agent traffic, so they are forwarded
|
||||
// verbatim, as is a body that is not a JSON object.
|
||||
// Every named client tool becomes an opaque clint_<digest> (see
|
||||
// protocol.ClientToolWireName: a client tool name that survives on the wire is
|
||||
// what the free tier refuses) and the full official set for the lane is
|
||||
// appended, so the request looks like an official CLI session on both the v1
|
||||
// (/zen) and v2 lanes. System One payloads are decision requests, not agent
|
||||
// traffic, so they are forwarded verbatim, as is a body that is not a JSON
|
||||
// object.
|
||||
func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool) ([]byte, *wire.ToolRenames) {
|
||||
if protocol == wire.SystemOne {
|
||||
return body, nil
|
||||
|
||||
+19
-30
@@ -1,6 +1,8 @@
|
||||
package protocol
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
@@ -8,9 +10,15 @@ import (
|
||||
// ClientToolPrefix marks every client tool the gateway renames on a shaped
|
||||
// free-tier request. The prefix keeps client tools distinct from the official
|
||||
// OpenCode set the gateway appends, and lets responses be restored to the names
|
||||
// the client declared.
|
||||
// the client declared. What follows it is a digest, never the client name: the
|
||||
// free tier refuses bodies that still read as another client's session.
|
||||
const ClientToolPrefix = "clint_"
|
||||
|
||||
// clientToolDigestLength is how many hex characters of the client name digest
|
||||
// a wire name carries. Twelve is far past the collision point for the handful
|
||||
// of tools one request declares.
|
||||
const clientToolDigestLength = 12
|
||||
|
||||
// toolWireNameLimit is the longest tool name the upstreams accept.
|
||||
const toolWireNameLimit = 64
|
||||
|
||||
@@ -193,20 +201,21 @@ func (r *ToolRenames) Restore(wire string) string {
|
||||
return client
|
||||
}
|
||||
|
||||
// ClientToolWireName builds the wire name for one client tool. The name keeps
|
||||
// only [A-Za-z0-9_-], collapses every other run to a single underscore, and is
|
||||
// trimmed; an empty result becomes "tool". It is truncated to fit alongside the
|
||||
// prefix and the 64-byte limit, and collisions with used names get a _2, _3, …
|
||||
// ClientToolWireName builds the wire name for one client tool. The name is
|
||||
// deliberately opaque: the free tier refuses a shaped body that still carries
|
||||
// another client's vocabulary (Claude Code's ReportFindings and ScheduleWakeup
|
||||
// together are enough, and dropping either name lifts the refusal), so no
|
||||
// client tool name may reach the wire. The digest keeps one client tool on one
|
||||
// wire name across requests, and collisions with used names get a _2, _3, …
|
||||
// suffix. The chosen name is recorded in used.
|
||||
func ClientToolWireName(name string, used map[string]bool) string {
|
||||
if used == nil {
|
||||
used = map[string]bool{}
|
||||
}
|
||||
clean := sanitizeToolName(name)
|
||||
if clean == "" {
|
||||
clean = "tool"
|
||||
}
|
||||
if max := toolWireNameLimit - len(ClientToolPrefix); len(clean) > max {
|
||||
digest := sha256.Sum256([]byte(name))
|
||||
clean := hex.EncodeToString(digest[:])[:clientToolDigestLength]
|
||||
max := toolWireNameLimit - len(ClientToolPrefix)
|
||||
if len(clean) > max {
|
||||
clean = clean[:max]
|
||||
}
|
||||
base := ClientToolPrefix + clean
|
||||
@@ -227,23 +236,3 @@ func ClientToolWireName(name string, used map[string]bool) string {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sanitizeToolName reduces a client tool name to the character set upstreams
|
||||
// accept, collapsing invalid runs into one underscore.
|
||||
func sanitizeToolName(name string) string {
|
||||
var builder strings.Builder
|
||||
underscored := false
|
||||
for _, char := range name {
|
||||
switch {
|
||||
case char >= 'a' && char <= 'z', char >= 'A' && char <= 'Z', char >= '0' && char <= '9', char == '-', char == '_':
|
||||
builder.WriteRune(char)
|
||||
underscored = char == '_'
|
||||
default:
|
||||
if !underscored {
|
||||
builder.WriteByte('_')
|
||||
underscored = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.Trim(builder.String(), "_-")
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package protocol
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The free tier refuses a shaped body whose tools still name another client's
|
||||
// session: Claude Code declaring both ReportFindings and ScheduleWakeup is
|
||||
// answered with FreeUsageLimitError. The wire name therefore may not echo the
|
||||
// client name, which is what these tests pin down.
|
||||
func TestClientToolWireNameIsOpaque(t *testing.T) {
|
||||
used := map[string]bool{}
|
||||
for _, client := range []string{"ScheduleWakeup", "ReportFindings", "Read", "Bash", "mcp__server__do_thing"} {
|
||||
wireName := ClientToolWireName(client, used)
|
||||
if !strings.HasPrefix(wireName, ClientToolPrefix) {
|
||||
t.Errorf("wire name %q does not carry the client prefix", wireName)
|
||||
}
|
||||
if len(wireName) > toolWireNameLimit {
|
||||
t.Errorf("wire name %q is longer than %d bytes", wireName, toolWireNameLimit)
|
||||
}
|
||||
if strings.Contains(strings.ToLower(wireName), strings.ToLower(client)) {
|
||||
t.Errorf("wire name %q still spells the client name %q", wireName, client)
|
||||
}
|
||||
if strings.ContainsAny(wireName, " \t\r\n") {
|
||||
t.Errorf("wire name %q is not one token", wireName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientToolWireNameIsStable(t *testing.T) {
|
||||
first := ClientToolWireName("ReportFindings", map[string]bool{})
|
||||
second := ClientToolWireName("ReportFindings", map[string]bool{})
|
||||
if first != second {
|
||||
t.Fatalf("same client tool got %q then %q", first, second)
|
||||
}
|
||||
other := ClientToolWireName("ScheduleWakeup", map[string]bool{})
|
||||
if first == other {
|
||||
t.Fatalf("two client tools share the wire name %q", first)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientToolWireNameSuffixesCollisions(t *testing.T) {
|
||||
used := map[string]bool{}
|
||||
first := ClientToolWireName("Read", used)
|
||||
// Hand the allocator a used set that already holds this tool's name, the
|
||||
// way a second definition of the same client tool would.
|
||||
retry := ClientToolWireName("Read", used)
|
||||
if retry == first {
|
||||
t.Fatalf("a taken wire name was handed out twice: %q", first)
|
||||
}
|
||||
if !strings.HasSuffix(retry, "_2") {
|
||||
t.Errorf("collision suffix missing from %q", retry)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolRenamesRestoreOpaqueNames(t *testing.T) {
|
||||
renames := NewToolRenames()
|
||||
used := map[string]bool{}
|
||||
for _, client := range []string{"ReportFindings", "schedule_wakeup"} {
|
||||
wireName := ClientToolWireName(client, used)
|
||||
if wireName == client {
|
||||
t.Fatalf("%q was not renamed", client)
|
||||
}
|
||||
renames.Add(client, wireName)
|
||||
if got := renames.Restore(wireName); got != client {
|
||||
t.Errorf("Restore(%q) = %q, want %q", wireName, got, client)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user