Files
ai/controllers/names.go
zeekay f9a0d86d8a The relay's key walk costs no more than its decode, the free floor is reached only with the paid lane off, and the free tier answers as Enso
The key walk ran before the credential and folded, pathed and recorded every key
of a checked object; three million keys in one message cost seconds of CPU and
half a gigabyte. A key that names no field is now skipped at the decoder's
speed, each key is folded once, and an object with more than 256 keys is
refused. The unpriced check folds its list once.

The hand-off to the family pipe runs only with the paid lane off, never for a
strict request and never around a customer's own row under the family's name.
A request relying on a field the pipe does not send, or on retrieved knowledge,
is refused by name rather than answered without it, and legacy functions count
as tools. Refusals before the pipe answered are recorded.

The free tier is served under freeDoor: Enso's free id wherever Enso's catalog
carries it, so the tier answers with Enso's name and maker, never the vendor
route that happened to answer; the pool's own door where it does not.

Claude-Session: https://claude.ai/code/session_013cvpQYtJPnTNfWzbqwtBJZ
2026-09-30 01:08:13 -07:00

200 lines
6.8 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Copyright 2026 Hanzo AI Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
// names.go — one request, read one way.
//
// encoding/json matches a struct field's name without regard to case — by Unicode
// simple folding, the rule bytes.EqualFold applies, so "Stream" and "ſtream" are both
// "stream" — and keeps the last of two keys that match. Every vendor reads the exact
// name. The relay sends the caller's body as written, and this handler decides the
// hold, the stream and the price from its own decode of the same body, so a key that
// differs from a field only in case makes one request two: "stream":true beside
// "Stream":false is billed as a buffered answer while the vendor streams, and a small
// "Messages" beside a large "messages" prices the hold on the one the vendor never
// reads.
//
// So a key that folds onto a field this handler decodes, or onto a sibling key, and
// is not that field's exact name, is refused by name — in the body and in every
// object below it the handler decodes into a struct. Objects decoded into a map keep
// their keys exactly, and a tool's JSON schema may name "Name" beside "name", so
// nothing below those is looked at.
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"strings"
"unicode"
openai "github.com/hanzoai/go-openai"
)
// structured are the objects the handler decodes into structs, by where they sit in the
// body, each with its fields' names keyed by their fold.
var structured = map[string]map[string]string{
"": fieldNames(chatRequest{}),
"stream_options": fieldNames(openai.StreamOptions{}),
"messages[]": fieldNames(openai.ChatCompletionMessage{}),
"messages[].content[]": fieldNames(openai.ChatMessagePart{}),
"messages[].content[].image_url": fieldNames(openai.ChatMessageImageURL{}),
"messages[].tool_calls[]": fieldNames(openai.ToolCall{}),
"messages[].tool_calls[].function": fieldNames(openai.FunctionCall{}),
"tools[]": fieldNames(openai.Tool{}),
"tools[].function": fieldNames(openai.FunctionDefinition{}),
}
// fieldNames is every name encoding/json would match for v's fields, keyed by fold:
// the json tag, and those of embedded structs. An untagged field maps to "", which no
// key equals, so every spelling of its Go name is refused.
func fieldNames(v any) map[string]string {
out := map[string]string{}
var walk func(t reflect.Type)
walk = func(t reflect.Type) {
for i := range t.NumField() {
f := t.Field(i)
tag := f.Tag.Get("json")
if f.Anonymous && tag == "" && f.Type.Kind() == reflect.Struct {
walk(f.Type)
continue
}
name, _, _ := strings.Cut(tag, ",")
if name == "-" || !f.IsExported() {
continue
}
if name == "" {
// An untagged field is matched by its Go name, which no vendor reads:
// every spelling of it is one the handler would read alone.
out[fold(f.Name)] = ""
continue
}
out[fold(name)] = name
}
}
walk(reflect.TypeOf(v))
return out
}
// fold maps s to one spelling per bytes.EqualFold class: each rune becomes the least
// rune of its simple-folding orbit.
func fold(s string) string {
var b strings.Builder
for _, r := range s {
least := r
for f := unicode.SimpleFold(r); f != r; f = unicode.SimpleFold(f) {
least = min(least, f)
}
b.WriteRune(least)
}
return b.String()
}
// maxKeys bounds the keys one struct-decoded object may carry. The request objects
// name a few dozen fields at most; a body with thousands of keys in one of them is
// not a request, and walking it before the credential is read is work the caller
// did not pay for.
const maxKeys = 256
// casefolded is the refusal for the first key in raw that this handler would read as a
// field and a vendor would not, or for an object with more keys than any request
// carries; "" when there is none. A body that is not JSON is left to the decoder,
// which has already refused it.
func casefolded(raw []byte) string {
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
why, _ := walkNames(dec, "")
return why
}
// walkNames reads one value from dec, sitting at path, and returns the refusal for
// the first offending key within it. It runs before the credential is read, so it
// costs no more than the decode it guards: a value at no path the handler decodes
// into a struct is skipped whole at the decoder's speed, and so is the value of any
// key in a checked object that names no field.
func walkNames(dec *json.Decoder, path string) (string, error) {
if !under(path) {
var skip json.RawMessage
return "", dec.Decode(&skip)
}
tok, err := dec.Token()
if err != nil {
return "", err
}
switch tok {
case json.Delim('{'):
fields, checked := structured[path]
seen := map[string]string{}
for n := 0; dec.More(); n++ {
if n == maxKeys {
return fmt.Sprintf("an object in this request carries more than %d fields", maxKeys), nil
}
t, err := dec.Token()
if err != nil {
return "", err
}
key, _ := t.(string)
f := fold(key)
exact, field := fields[f]
if !checked || !field {
// Not a field the handler reads here: the decoder ignores it, and so
// does every vendor that reads it under its own name.
var skip json.RawMessage
if err := dec.Decode(&skip); err != nil {
return "", err
}
continue
}
if exact != key {
return refusedName(key), nil
}
if prev, ok := seen[f]; ok && prev != key {
return refusedName(key), nil
}
seen[f] = key
if why, err := walkNames(dec, strings.TrimPrefix(path+"."+key, ".")); why != "" || err != nil {
return why, err
}
}
_, err = dec.Token()
return "", err
case json.Delim('['):
element := path + "[]"
for dec.More() {
if why, err := walkNames(dec, element); why != "" || err != nil {
return why, err
}
}
_, err = dec.Token()
return "", err
}
return "", nil
}
func refusedName(key string) string {
return fmt.Sprintf("%q differs from a field this API reads only in letter case: send the field under its exact name, once.", key)
}
// under reports a path that is, or leads to, an object the handler decodes into a
// struct.
func under(path string) bool {
for p := range structured {
if p == path || strings.HasPrefix(p, path+".") || strings.HasPrefix(p, path+"[]") {
return true
}
}
return false
}