feat(free-tier): prefix client tools with clint_ and complete the official set

Shaped free-model requests now look like an official CLI session on every
lane. Each client tool is renamed to a sanitized, collision-free clint_ name
and the full official tool set for the lane is appended (11 tools on the 1.x
/zen lane, 13 on 2.x /inference and /zen/go). Requests without tools, with an
empty array, or with a legacy functions array receive the official set too,
and tool_choice, function_call and the tool-call history are rewritten to
match.

Responses, streaming and not, are restored to the names the client declared,
including a Chat in a stream split across chunks. Unmapped names pass through,
so an official tool the client never declared is never hidden or replayed.
This commit is contained in:
Jason Xu committed 2026-10-25 05:58:02 +08:00
1 parent 97cdb29713
commit fd4c1c6d40
15 files changed
+1088 -507

No files matched your search

+46 -33
View File
@@ -503,29 +503,26 @@ func ResponseUsage(protocol Protocol, body []byte) (Usage, bool) {
return decodeOpenAIUsage(usage), true
}
// RenameResponseTool rewrites tool call names matching fromName to toName inside
// a serialized JSON response or SSE event data object for the given protocol.
// It is used to restore a client's original read-related tool name (e.g.
// "reAd" or "read_file") after the v1 lane's shaper aliased it to "read" on the
// outbound wire.
// RenameResponseTool rewrites tool call names that carry a client alias back to
// the name the client declared, inside a serialized JSON response or SSE event
// data object for the given protocol. It is the counterpart of the outbound
// clint_ renaming applied to shaped free-tier requests.
//
// The bytes.Contains check is only a fast path that skips the unmarshal for
// frames that cannot contain the name; correctness does not depend on it,
// because every name that is rewritten is compared exactly after decoding.
// Names that do not match fromName, including ones already equal to toName,
// are left alone.
func RenameResponseTool(body []byte, protocol Protocol, fromName, toName string) []byte {
if fromName == "" || toName == "" || fromName == toName || len(body) == 0 {
// frames that cannot contain an alias; every rewrite is an exact map lookup
// after decoding. Names without a mapping are left alone.
func RenameResponseTool(body []byte, protocol Protocol, renames *ToolRenames) []byte {
if renames.Empty() || len(body) == 0 {
return body
}
if !bytes.Contains(body, []byte(fromName)) {
if !bytes.Contains(body, []byte(ClientToolPrefix)) {
return body
}
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
return body
}
if !renameToolInMap(payload, protocol, fromName, toName) {
if !renameToolInMap(payload, protocol, renames) {
return body
}
encoded, err := json.Marshal(payload)
@@ -535,12 +532,33 @@ func RenameResponseTool(body []byte, protocol Protocol, fromName, toName string)
return encoded
}
// renameToolInMap rewrites matching tool names in a decoded response or stream
// renameToolInMap rewrites aliased tool names in a decoded response or stream
// event and reports whether anything changed. Every place a protocol reports a
// tool call is visited: Chat message and delta tool_calls, Responses
// function_call items under "item", "output" and a "response" envelope, and
// Anthropic tool_use blocks under "content_block" or "content".
func renameToolInMap(payload map[string]any, protocol Protocol, fromName, toName string) bool {
// tool call is visited: Chat message, delta and legacy function_call tool
// calls, Responses function_call and custom_tool_call items under "item",
// "output" and a "response" envelope, and Anthropic tool_use blocks under
// "content_block" or "content".
func renameToolInMap(payload map[string]any, protocol Protocol, renames *ToolRenames) bool {
rename := func(container map[string]any) bool {
name, ok := container["name"].(string)
if !ok {
return false
}
client, ok := renames.Client(name)
if !ok {
return false
}
container["name"] = client
return true
}
renameItem := func(item map[string]any) bool {
switch jsonutil.StringAt(item, "type") {
case "function_call", "custom_tool_call":
return rename(item)
default:
return false
}
}
changed := false
switch protocol {
case Chat:
@@ -550,47 +568,42 @@ func renameToolInMap(payload map[string]any, protocol Protocol, fromName, toName
container := jsonutil.MapAt(choice, key)
for _, rawCall := range jsonutil.SliceAt(container, "tool_calls") {
call, _ := rawCall.(map[string]any)
if function, ok := call["function"].(map[string]any); ok && jsonutil.StringAt(function, "name") == fromName {
function["name"] = toName
if function, ok := call["function"].(map[string]any); ok && rename(function) {
changed = true
}
}
if function, ok := container["function_call"].(map[string]any); ok && rename(function) {
changed = true
}
}
}
case Responses:
if item, ok := payload["item"].(map[string]any); ok {
if jsonutil.StringAt(item, "type") == "function_call" && jsonutil.StringAt(item, "name") == fromName {
item["name"] = toName
changed = true
}
if item, ok := payload["item"].(map[string]any); ok && renameItem(item) {
changed = true
}
for _, rawItem := range jsonutil.SliceAt(payload, "output") {
item, _ := rawItem.(map[string]any)
if jsonutil.StringAt(item, "type") == "function_call" && jsonutil.StringAt(item, "name") == fromName {
item["name"] = toName
if renameItem(item) {
changed = true
}
}
if resp, ok := payload["response"].(map[string]any); ok {
for _, rawItem := range jsonutil.SliceAt(resp, "output") {
item, _ := rawItem.(map[string]any)
if jsonutil.StringAt(item, "type") == "function_call" && jsonutil.StringAt(item, "name") == fromName {
item["name"] = toName
if renameItem(item) {
changed = true
}
}
}
case Anthropic:
if block, ok := payload["content_block"].(map[string]any); ok {
if jsonutil.StringAt(block, "type") == "tool_use" && jsonutil.StringAt(block, "name") == fromName {
block["name"] = toName
if jsonutil.StringAt(block, "type") == "tool_use" && rename(block) {
changed = true
}
}
for _, rawBlock := range jsonutil.SliceAt(payload, "content") {
block, _ := rawBlock.(map[string]any)
if jsonutil.StringAt(block, "type") == "tool_use" && jsonutil.StringAt(block, "name") == fromName {
block["name"] = toName
if jsonutil.StringAt(block, "type") == "tool_use" && rename(block) {
changed = true
}
}
+26 -29
View File
@@ -227,22 +227,21 @@ func ForwardStream(ctx context.Context, w http.ResponseWriter, reader io.Reader,
return usage, observer.Reported(), cause
}
// RenameStreamReader wraps an SSE stream reader and rewrites tool call names
// matching fromName back to toName before downstream parsers or writers consume
// the stream. When fromName or toName is empty (or identical), reader is
// returned unchanged.
// RenameStreamReader wraps an SSE stream reader and rewrites aliased tool call
// names back to the names the client declared before downstream parsers or
// writers consume the stream. An empty rename set returns reader unchanged.
//
// It is a pull-based transform instead of a goroutine plus io.Pipe so a client
// that disconnects mid-stream cannot strand a blocked writer. Chat frames go
// through the fragment-aware rewriter, while the other protocols use the
// stateless RenameResponseTool rewrite on each frame.
func RenameStreamReader(reader io.Reader, protocol Protocol, fromName, toName string) io.Reader {
if fromName == "" || toName == "" || fromName == toName {
func RenameStreamReader(reader io.Reader, protocol Protocol, renames *ToolRenames) io.Reader {
if renames.Empty() {
return reader
}
return &renameStreamReader{
buffer: bufio.NewReaderSize(reader, 64<<10),
renamer: &streamToolRenamer{protocol: protocol, fromName: fromName, toName: toName, tools: map[string]*streamToolRenameState{}},
renamer: &streamToolRenamer{protocol: protocol, renames: renames, tools: map[string]*streamToolRenameState{}},
}
}
@@ -312,8 +311,8 @@ func (reader *renameStreamReader) rewriteLine(line string) []byte {
// streamToolRenameState tracks how one tool call's name was resolved while a
// stream is rewritten. Chat deltas may repeat a growing name prefix or append
// fragments, so a value that is still a prefix of fromName is held back until
// it either completes the match or diverges.
// 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
@@ -325,23 +324,22 @@ type streamToolRenameState struct {
// chunks is reassembled before it is matched.
type streamToolRenamer struct {
protocol Protocol
fromName string
toName string
renames *ToolRenames
tools map[string]*streamToolRenameState
}
// rewriteFrame rewrites one SSE data payload, which is raw JSON text. Frames
// that cannot carry a tool name are returned untouched, so only a payload that
// mentions the source name (Anthropic and Responses) or "tool_calls" (Chat) is
// mentions a client alias (Anthropic and Responses) or "tool_calls" (Chat) is
// decoded.
func (renamer *streamToolRenamer) rewriteFrame(raw string) []byte {
if renamer.protocol != Chat {
// Anthropic and Responses streams always carry a complete tool name in
// a single event, so the stateless object rewrite is exact.
if !strings.Contains(raw, renamer.fromName) {
if !strings.Contains(raw, ClientToolPrefix) {
return []byte(raw)
}
return RenameResponseTool([]byte(raw), renamer.protocol, renamer.fromName, renamer.toName)
return RenameResponseTool([]byte(raw), renamer.protocol, renamer.renames)
}
if !strings.Contains(raw, `"tool_calls"`) {
return []byte(raw)
@@ -401,11 +399,11 @@ func (renamer *streamToolRenamer) rewriteChatFrame(raw string) []byte {
}
// applyNameFragment folds one name fragment into a tool's rename state and
// reports whether the frame changed. Once the accumulated name completes
// fromName, it is replaced by toName; while it is still a prefix of fromName
// the name is held back; on divergence the accumulated name is written out as
// is. After a resolved rename, any further fragment is dropped, because it
// belongs to a longer name the client never declared.
// 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
// prefix of one the name is held back; on divergence the accumulated name is
// written out as is. After a resolved rename, any further fragment is dropped,
// because it belongs to a longer name the client never declared.
func (renamer *streamToolRenamer) applyNameFragment(state *streamToolRenameState, function map[string]any, fragment string) bool {
if state.decided {
if !state.renamed {
@@ -420,21 +418,20 @@ func (renamer *streamToolRenamer) applyNameFragment(state *streamToolRenameState
return false
}
state.pending = mergeToolName(state.pending, fragment)
switch {
case state.pending == renamer.fromName:
function["name"] = renamer.toName
if client, ok := renamer.renames.Client(state.pending); ok {
function["name"] = client
state.decided, state.renamed = true, true
return true
case strings.HasPrefix(renamer.fromName, state.pending):
// Still a prefix of the alias: hold the fragment until a later frame
// either completes the match or diverges.
}
if renamer.renames.HasLongerPrefix(state.pending) {
// Still a prefix of a known wire name: hold the fragment until a later
// frame either completes the match or diverges.
delete(function, "name")
return true
default:
function["name"] = state.pending
state.decided = true
return true
}
function["name"] = state.pending
state.decided = true
return true
}
// toolState returns the rename state for a tool key, creating it on first
+175
View File
@@ -0,0 +1,175 @@
package protocol
import (
"strconv"
"strings"
)
// 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.
const ClientToolPrefix = "clint_"
// toolWireNameLimit is the longest tool name the upstreams accept.
const toolWireNameLimit = 64
// 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 {
toWire map[string]string
toClient map[string]string
}
// NewToolRenames returns an empty rename set.
func NewToolRenames() *ToolRenames {
return &ToolRenames{toWire: map[string]string{}, toClient: map[string]string{}}
}
// Empty reports whether no tool was renamed.
func (r *ToolRenames) Empty() bool {
return r == nil || len(r.toWire) == 0
}
// Count reports how many client tools were renamed.
func (r *ToolRenames) Count() int {
if r == nil {
return 0
}
return len(r.toWire)
}
// Wire returns the wire name registered for an exact client name.
func (r *ToolRenames) Wire(client string) (string, bool) {
if r == nil || client == "" {
return "", false
}
wire, ok := r.toWire[client]
return wire, ok
}
// Client returns the client name registered for an exact wire name.
func (r *ToolRenames) Client(wire string) (string, bool) {
if r == nil || wire == "" {
return "", false
}
client, ok := r.toClient[wire]
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.
func (r *ToolRenames) Add(client, wire string) {
if r == nil || client == "" || wire == "" || client == wire {
return
}
if existing, ok := r.toWire[client]; ok {
if existing != wire {
return
}
}
if _, taken := r.toClient[wire]; taken {
return
}
r.toWire[client] = wire
r.toClient[wire] = client
}
// HasPrefix reports whether any wire name starts with prefix.
func (r *ToolRenames) HasPrefix(prefix string) bool {
if r == nil || prefix == "" {
return false
}
for wire := range r.toClient {
if strings.HasPrefix(wire, prefix) {
return true
}
}
return false
}
// HasLongerPrefix reports whether any wire name is longer than prefix and
// starts with it. A stream fragment builder uses this to hold a partial name
// back until the next chunk resolves it.
func (r *ToolRenames) HasLongerPrefix(prefix string) bool {
if r == nil || prefix == "" {
return false
}
for wire := range r.toClient {
if len(wire) > len(prefix) && strings.HasPrefix(wire, prefix) {
return true
}
}
return false
}
// Restore maps a wire name back to the client name. When the exact mapping is
// gone (for example after a configuration reload mid-stream), stripping the
// prefix is the best available recovery; a name without it is returned as is.
func (r *ToolRenames) Restore(wire string) string {
if client, ok := r.Client(wire); ok {
return client
}
if strings.HasPrefix(wire, ClientToolPrefix) {
if rest := strings.TrimPrefix(wire, ClientToolPrefix); rest != "" {
return rest
}
}
return wire
}
// 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, …
// 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 {
clean = clean[:max]
}
base := ClientToolPrefix + clean
if !used[base] {
used[base] = true
return base
}
for suffix := 2; ; suffix++ {
tag := "_" + strconv.Itoa(suffix)
cut := toolWireNameLimit - len(tag)
if cut > len(base) {
cut = len(base)
}
candidate := base[:cut] + tag
if !used[candidate] {
used[candidate] = true
return candidate
}
}
}
// 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(), "_-")
}