Gemini on Vertex AI was reachable only through a proxy of the user's own
in front of Vertex AI's OpenAI-compatible endpoint, added as a custom
provider. The Google Vertex AI preset (google-vertex) asks Vertex AI
itself.
* The provider holds a project, a location (global when none is given;
us, eu or a region), an optional credentials file and an optional
service account to go as (provider.Vertex). It has no key and no
URL: Save refuses a key, normalize clears a key and the four URLs
kept by hand, and its one address is
https://<host>/v1/projects/<project>/locations/<location>, the host
following the location (vertexHost). It is ready when it has a
project, never for a key or an account, and an import link can't add
it.
* Each request is signed with a Google token (Sign), and the token goes
to no other address. The credentials are found as Google's libraries
find Application Default Credentials: the provider's file, else
GOOGLE_APPLICATION_CREDENTIALS's, else gcloud's
application_default_credentials.json. A GOOGLE_APPLICATION_CREDENTIALS
that isn't a full path is an error, not unset, since gcloud's file
read in its place may be another account's. authorized_user,
service_account and gcloud's impersonated_service_account are read;
external_account and another universe are refused by name. With a
service account set, the token is traded at IAM Credentials'
generateAccessToken for one of that account's, as gcloud's
--impersonate-service-account does. Tokens are kept in memory per
file and account, minted once for requests made together, again 5
minutes before they expire or when the file changes (gcloud signed
in again). A mint is given 30 seconds; one that fails fails the
requests that waited through it too, and a request given up on
stops waiting. A sign-in Google refuses says the command that makes
that file again: gcloud's for its own files, impersonating as it
did.
* The gateway speaks Gemini to it alone. A Gemini client's request is
relayed as it came, its thinkingConfig, safetySettings and schema
with it: streamed to
publishers/google/models/<model>:streamGenerateContent?alt=sse, or
asked whole to :generateContent. Every other API's is translated
(buildVertex), streamed, and read back with thoughts as reasoning,
never as the answer. The path names a model by its upstream name
when one is set, as the usage log's endpoint does. Gemini 3 is sent a thinkingLevel fitted to the
model's levels, 2.5 a thinkingBudget in the model's range, off
included (Pro's least, as Pro can't stop). A call's thought
signature goes to the client in its id and comes back on the call;
a 400 "Invalid thought signature." is asked again with every call
waved through, for that request, and a 400 refusing minimal is asked
again at the model's lowest level, kept until restart. Neither is
tried for another provider.
* Vertex AI has no list of the models a location serves, so each
location has the ones it answered with on 2026-10-06: 12 at global,
6 Flash at us and eu, the 2.5 trio at a region.
* The preset offers Priority PayGo's and Flex PayGo's request headers
(HeaderHints). GOOGLE_APPLICATION_CREDENTIALS and CLOUDSDK_CONFIG are
in agentenv.Vars, so the desktop app takes them from the login shell
and the tests clear them.
Not read: the metadata server of Compute Engine, Cloud Run and GKE;
workload identity federation; Vertex AI's express-mode API keys. No
quota project is sent.
Reference: docs/subsystems/providers-accounts.md (Google Vertex AI,
Vertex AI tokens, four constraints) and gateway-routing.md (Vertex AI).
Verified: go test ./... (nogui), -race -count=5 on the Vertex tests,
gofmt and vet. A fake Google (token endpoint, IAM Credentials, Vertex
AI) checks each credentials type, the mint shared, bounded and
re-minted, every refusal's advice and that no token reaches another
host. Each of 24 mutations made after review, of the mint, the key
rules, the advice, the upstream path and the retries, fails a test.
Live, against a real project through an impersonated service account,
with magpie in a sandboxed HOME: Chat, Anthropic Messages, Responses and
Gemini clients, streamed and whole, with thinking and with tool calls, a
whole Gemini call and its signature sent back streamed, at global, us
and us-central1, and with Flex PayGo's header. No token was found in its
files or logs afterwards.
204 lines
6.7 KiB
Go
204 lines
6.7 KiB
Go
package provider
|
|
|
|
import (
|
|
"cmp"
|
|
"errors"
|
|
"net"
|
|
"net/url"
|
|
"slices"
|
|
"strings"
|
|
)
|
|
|
|
// Import links let a vendor or a relay hand its users a ready-made provider:
|
|
//
|
|
// magpie://import?preset=deepseek&key=sk-…
|
|
// magpie://import?name=My%20Relay&chat=https://relay.example/v1&key=sk-…
|
|
//
|
|
// Parameters (every value URL-encoded):
|
|
//
|
|
// preset a preset id (magpie presets); the preset's endpoints are used.
|
|
// Not google-vertex, asked at the user's own Google Cloud project
|
|
// region with a preset that has regions, which one
|
|
// name the provider's name; required without a preset
|
|
// id its id; derived from the name when absent
|
|
// key the API key; the user can paste one when absent
|
|
// chat OpenAI Chat Completions base URL (…/v1)
|
|
// responses OpenAI Responses base URL (…/v1)
|
|
// anthropic Anthropic Messages base URL (the root)
|
|
// models model ids to show agents, comma separated
|
|
// catalog models.dev provider id, for names and reasoning levels
|
|
// website the vendor's site; keys: where keys are made
|
|
// icon an https picture of the vendor's own, fetched only after the
|
|
// user confirms; falls back to the generic mark when absent
|
|
//
|
|
// A link never saves anything by itself: the app shows what it would add
|
|
// and the user says yes.
|
|
|
|
// Scheme is the URL scheme magpie registers with the system.
|
|
const Scheme = "magpie"
|
|
|
|
// ParseImport reads an import link into the provider it describes.
|
|
func ParseImport(link string) (Provider, error) {
|
|
u, err := url.Parse(strings.TrimSpace(link))
|
|
if err != nil || !strings.EqualFold(u.Scheme, Scheme) {
|
|
return Provider{}, errors.New("not a magpie:// link")
|
|
}
|
|
action := u.Host
|
|
if action == "" { // magpie:import?… or magpie:///import?…
|
|
action = strings.Trim(u.Opaque+u.Path, "/")
|
|
}
|
|
if action != "import" {
|
|
return Provider{}, errorf("magpie://%s is not something magpie knows; links start magpie://import?", action)
|
|
}
|
|
q := u.Query()
|
|
get := func(k string) string { return strings.TrimSpace(q.Get(k)) }
|
|
|
|
var p Provider
|
|
if id := get("preset"); id != "" {
|
|
if p, err = FromPreset(strings.ToLower(id)); err != nil {
|
|
return Provider{}, err
|
|
}
|
|
if p.IsVertex() {
|
|
// asked at the user's own Google Cloud project, with their
|
|
// own credentials: nothing a link could hand over
|
|
return Provider{}, errorf("%s is added with your own Google Cloud project, not from a link: magpie provider add %s project=<id>, or Add in the app", p.Name, VertexPreset)
|
|
}
|
|
if r := get("region"); r != "" {
|
|
found := false
|
|
pr := Preset(p.Preset)
|
|
for _, reg := range pr.Regions {
|
|
if reg.ID == r {
|
|
p.Chat, p.Responses, p.Anthropic, found = reg.Chat, reg.Responses, reg.Anthropic, true
|
|
// a region with a key page of its own (Qianfan's pay
|
|
// as you go, on the IAM page) shows it before the
|
|
// provider is saved
|
|
if reg.KeysURL != "" {
|
|
p.KeysURL = reg.KeysURL
|
|
}
|
|
// and its docs and prices (Tencent Cloud's TokenHub)
|
|
p.Website = cmp.Or(reg.Website, pr.Website)
|
|
if slices.ContainsFunc(pr.Regions, func(x Region) bool { return x.Catalog != "" }) {
|
|
p.Catalog = cmp.Or(reg.Catalog, pr.Catalog)
|
|
}
|
|
}
|
|
}
|
|
if !found {
|
|
return Provider{}, errorf("%s has no region %q", p.Name, r)
|
|
}
|
|
}
|
|
if n := get("name"); n != "" {
|
|
p.Name = n
|
|
}
|
|
} else {
|
|
p = Provider{Name: get("name"), Catalog: strings.ToLower(get("catalog"))}
|
|
if p.Name == "" {
|
|
return Provider{}, errors.New("the link names no provider: it needs preset= or name=")
|
|
}
|
|
for k, dst := range map[string]*string{"chat": &p.Chat, "responses": &p.Responses, "anthropic": &p.Anthropic} {
|
|
if *dst, err = endpoint(k, get(k)); err != nil {
|
|
return Provider{}, err
|
|
}
|
|
}
|
|
if p.Chat == "" && p.Responses == "" && p.Anthropic == "" {
|
|
return Provider{}, errors.New("the link gives no base URL: it needs chat=, responses= or anthropic=")
|
|
}
|
|
if p.Catalog != "" && p.Catalog != Slug(p.Catalog) {
|
|
p.Catalog = ""
|
|
}
|
|
if p.Catalog != "" {
|
|
p.Icon = IconForCatalog(p.Catalog)
|
|
}
|
|
p.Website = page(get("website"))
|
|
p.KeysURL = page(get("keys"))
|
|
}
|
|
if raw := get("icon"); raw != "" {
|
|
u, err := iconURL(raw)
|
|
if err != nil {
|
|
return Provider{}, err
|
|
}
|
|
p.IconURL = u
|
|
}
|
|
|
|
if id := get("id"); id != "" {
|
|
p.ID = Slug(id)
|
|
} else if get("preset") == "" {
|
|
p.ID = Slug(p.Name)
|
|
}
|
|
if p.ID == "" {
|
|
return Provider{}, errors.New("the link's name has no letters or digits to make an id from")
|
|
}
|
|
if p.ID == "magpie" {
|
|
return Provider{}, errors.New(`"magpie" is what agents call the gateway itself; the link needs another id`)
|
|
}
|
|
if len(p.Name) > 80 {
|
|
p.Name = p.Name[:80]
|
|
}
|
|
|
|
p.Key = get("key")
|
|
if len(p.Key) > 4096 || strings.ContainsFunc(p.Key, func(r rune) bool { return r < ' ' || r == 0x7f }) {
|
|
return Provider{}, errors.New("the link's key is not a key")
|
|
}
|
|
for _, m := range strings.Split(q.Get("models"), ",") {
|
|
if m = strings.TrimSpace(m); m != "" && len(p.Models) < 200 {
|
|
p.Models = append(p.Models, m)
|
|
}
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
// endpoint accepts an https base URL, or plain http to this machine or the
|
|
// local network, where model servers usually run without TLS.
|
|
func endpoint(name, raw string) (string, error) {
|
|
if raw == "" {
|
|
return "", nil
|
|
}
|
|
u, err := url.Parse(raw)
|
|
if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
|
return "", errorf("the link's %s= is not a base URL: %q", name, raw)
|
|
}
|
|
switch u.Scheme {
|
|
case "https":
|
|
case "http":
|
|
if !local(u.Hostname()) {
|
|
return "", errorf("the link's %s= must use https: %q", name, raw)
|
|
}
|
|
default:
|
|
return "", errorf("the link's %s= must use https: %q", name, raw)
|
|
}
|
|
return strings.TrimRight(u.String(), "/"), nil
|
|
}
|
|
|
|
func local(host string) bool {
|
|
if host == "localhost" || strings.HasSuffix(host, ".local") {
|
|
return true
|
|
}
|
|
ip := net.ParseIP(host)
|
|
return ip != nil && (ip.IsLoopback() || ip.IsPrivate())
|
|
}
|
|
|
|
// page keeps a web page link only when it is https.
|
|
func page(raw string) string {
|
|
if u, err := url.Parse(raw); err == nil && u.Scheme == "https" && u.Host != "" && u.User == nil {
|
|
return u.String()
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// iconURL accepts the picture a link names: an https URL on a public host,
|
|
// which the app fetches only after the user confirms the import. A plain
|
|
// http or a bare host is rejected rather than guessed at, since this is the
|
|
// one parameter that makes magpie reach out on the link's behalf.
|
|
func iconURL(raw string) (string, error) {
|
|
u, err := url.Parse(raw)
|
|
if err != nil || u.Host == "" || u.User != nil || u.Fragment != "" {
|
|
return "", errorf("the link's icon= is not a picture URL: %q", raw)
|
|
}
|
|
if u.Scheme != "https" {
|
|
return "", errorf("the link's icon= must use https: %q", raw)
|
|
}
|
|
if local(u.Hostname()) {
|
|
return "", errorf("the link's icon= must be on a public host: %q", raw)
|
|
}
|
|
return u.String(), nil
|
|
}
|