lm15

package module
v1.1.0-rc.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 12, 2026 License: MIT Imports: 46 Imported by: 0

README

lm15 for Go

One request and response model for every major AI model provider, in Go. Write a Request once and send it to OpenAI, Anthropic, Gemini, xAI, Groq, DeepSeek, OpenRouter, Z.AI, Moonshot, Meta, a cloud (Azure, Bedrock, Vertex) or a model on your own machine: change the model string, keep the program.

router := lm15.NewRouter()
response, err := router.Complete(ctx, &lm15.Request{
    Model:    "anthropic:claude-haiku-4-5",
    Messages: []lm15.Message{lm15.UserMessage("What eats acorns at night?")},
})
fmt.Println(response.TextOr(""))
  • Standard library only. No dependencies; builds for Linux, macOS, Windows and the browser (GOOS=js GOARCH=wasm).
  • Low-level on purpose. Typed requests, responses, stream events, tools, media, errors and exact JSON serialization. No hidden tool loop, no retries you did not ask for, no prompt templates: the library you build on top decides those.
  • The same behavior in every language. lm15 exists for Python, TypeScript, Rust and Go, graded by one shared contract: the same request produces the same wire bytes and the same response in all four.

Documentation: lm15.dev (every guide has Go examples) · API reference: pkg.go.dev.

Install

Requires Go 1.26.2 or newer.

go get github.com/lm15-dev/lm15-go@v1.1.0-rc.7
import lm15 "github.com/lm15-dev/lm15-go"

v1.1.0-rc.7 is a release candidate (v1.1.0-rc.1 was the first release of lm15 for Go), open for trying before v1.1.0. Python's lm15 1.0 is stable; TypeScript and Rust are release candidates too. Why Go starts at 1.1: see Versions.

Set the key of the provider you call (ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, ...). The router reads it from the environment; nothing else is configured.

Guide

Ask, stream, continue
ctx := context.Background()
router := lm15.NewRouter()
request := &lm15.Request{
    Model:    "gpt-4.1-mini",
    System:   lm15.System("Answer in one sentence."),
    Messages: []lm15.Message{lm15.UserMessage("What eats acorns at night?")},
    Config:   lm15.Config{MaxTokens: lm15.I(200)},
}

response, err := router.Complete(ctx, request)
if err != nil {
    return err
}
fmt.Println(response.TextOr(""), response.FinishReason, *response.Usage.OutputTokens)

// Streaming: text as it arrives, then the same Response Complete returns.
stream := lm15.NewResponseStream(router.Stream(ctx, request), request)
for text, err := range stream.Text() {
    if err != nil {
        return err
    }
    fmt.Print(text)
}
final, err := stream.Response()

// A conversation is the messages so far, plus the reply.
request.Messages = append(request.Messages, final.Message, lm15.UserMessage("And by day?"))

A model string is either provider:model ("gemini:gemini-2.5-flash", "groq:openai/gpt-oss-20b", "ollama:qwen3.5:0.8b") or a bare name the router recognizes ("gpt-4.1-mini", "claude-haiku-4-5").

Tools

lm15 returns the model's tool calls; your program runs them and answers.

weather := lm15.FunctionTool{
    Name:        "get_weather",
    Description: "Current weather for a city.",
    Parameters: lm15.JSONObject{
        lm15.KV("type", "object"),
        lm15.KV("properties", lm15.JSONObject{
            lm15.KV("city", lm15.JSONObject{lm15.KV("type", "string")}),
        }),
        lm15.KV("required", []any{"city"}),
    },
}
request.Tools = []lm15.Tool{weather}
response, err := router.Complete(ctx, request)
var results []lm15.ToolResultPart
for _, call := range response.ToolCalls() {
    city, _ := call.Input.Get("city").(string)
    results = append(results, lm15.ToolResult(call.ID, lookUpWeather(city)))
}
request.Messages = append(request.Messages, response.Message, lm15.ToolMessageParts(results...))
response, err = router.Complete(ctx, request) // the model answers with the results
JSON objects keep their order

Tool parameters, response formats, tool-call input, extensions and provider data are lm15.JSONObject: a list of key/value members, in order. Order is data. A model fills a structured answer in the order its schema lists the fields, so a schema that lists reasoning before answer gets reasoning first.

schema := lm15.JSONObject{
    lm15.KV("type", "object"),
    lm15.KV("properties", lm15.JSONObject{
        lm15.KV("reasoning", lm15.JSONObject{lm15.KV("type", "string")}),
        lm15.KV("answer", lm15.JSONObject{lm15.KV("type", "string")}),
    }),
    lm15.KV("required", []any{"reasoning", "answer"}),
    lm15.KV("additionalProperties", false),
}
request.Config.ResponseFormat = lm15.JSONObject{
    lm15.KV("type", "json_schema"), lm15.KV("name", "worked_answer"), lm15.KV("schema", schema),
}

Read with Get, Lookup, Has, Keys and All (in order); write with Set (a key keeps its place) and Delete. Both copy before writing, so an object you passed to lm15 never changes behind your back. JSON text keeps its order too: lm15.DecodeJSONObject(data). fmt.Println(obj) prints the JSON lm15 would send. A Go map has no order: lm15.ObjectFromMap(m) converts one with its keys sorted.

Images, documents, audio
photo := lm15.Image(lm15.WithPath("camera-trap.jpg")) // or WithURL, WithData, WithFileID
request.Messages = []lm15.Message{lm15.UserParts(lm15.Text("What animal is this?"), photo)}
Errors

Every failure is an *lm15.Error with a Kind you can branch on (KindRateLimit, KindAuth, KindContextLength, KindUnsupportedFeature, ...), the provider's own code and message, and rate-limit evidence when the provider sent it.

var e *lm15.Error
if errors.As(err, &e) && e.Kind.IsA(lm15.KindRateLimit) {
    time.Sleep(time.Duration(*e.RetryAfter * float64(time.Second)))
}
Sign in once, use everywhere

Besides API keys, lm15 can use an account you sign in to (a ChatGPT, Claude, xAI, GitHub Copilot or OpenRouter login), saved in one file that every lm15 language shares. Sign-in is provisional: whether each provider permits it, and how it is billed, is the provider's call.

client, err := lm15.Connect(ctx, lm15.ConnectOptions{}) // pick a provider and model in the terminal
response, err := client.Ask(ctx, "Explain drought stress in oaks.")

See docs/managed-login.md.

Azure, AWS and Google Cloud

The cloud doors (azure:, bedrock-anthropic:, vertex: …) find the identity your machine already has, the way each cloud's own SDK does. Google Cloud, for example:

// Laptop: `gcloud auth application-default login` and
// `gcloud config set project my-project`, nothing else.
router, err := lm15.NewRouterWithConfig(lm15.RouterConfig{})
response, err := router.Complete(ctx, &lm15.Request{Model: "vertex:gemini-2.5-flash",
	Messages: []lm15.Message{lm15.UserMessage("hi")}})

// Cloud Run, GKE, a VM: the attached service account and the project both come
// from the metadata server. Naming it fails fast if it is missing.
deployed, err := lm15.NewRouterWithConfig(lm15.RouterConfig{Credentials: map[string]string{"vertex": "platform"}})

// A Vertex API key, in your project and a region you choose.
keyed, err := lm15.NewRouterWithConfig(lm15.RouterConfig{
	APIKeys:  map[string]lm15.CredentialLike{"vertex": os.Getenv("MY_VERTEX_KEY")},
	Settings: map[string]map[string]string{"vertex": {"location": "europe-west4"}},
})

lm15.ExplainAuth("vertex", lm15.ExplainOptions{}) says which identity and which project lm15 would use, without a network call. When sign-in fails, the error names the fix. The whole path (project setup, workload identity federation, Claude on Vertex) is in the cloud hosts guide; the Go names are the Python ones in Go spelling.

More

Judgments with probabilities (lm15.Judgments, Response.Probabilities), reasoning controls, prompt caching, built-in provider tools (web search, code execution), files and batches, image and speech generation, video, realtime sessions, the model catalog, and reading an OpenAI Chat Completions request into a Request are all in the guides and on pkg.go.dev.

Stability

The chat core is stable within v1.x once v1.1.0 is released: requests, responses, streaming, tools, structured output, errors, credentials and model listing. These ship as provisional and may still change in 1.x with a notice in the contract: files, batches, media generation, stored caches, realtime sessions, Chat Completions ingest and sign-in.

Conformance

This module is graded by lm15-contract at the commit in CONTRACT_PIN: 1,788 of 1,788 checks pass (2026-09-26), as Python, TypeScript and Rust pass every check at theirs. The checks compare the exact requests lm15 builds and the responses it reads against recorded provider traffic.

go build -o bin/lm15-vet ./cmd/lm15-vet
cd ../lm15-contract && python3 harness/check.py --shim go --direction all

Real calls: go run ./examples/live_smoke sends a small set of checks (chat, streaming, structured output, a tool loop, model listing) to every provider you have a key for, and writes receipts. The latest run is in receipts/.

Go-specific differences from the Python reference, and where each part of the contract lives in this module: docs/port-notes.md.

Versions

v1.0.0 was tagged by mistake on 2026-06-11 from an early prototype, before the shared contract existed. Go's module proxy keeps every tag forever, so it is retracted (with v1.0.1, which only carries the retraction) and the first real release is v1.1.0. See RELEASING.md.

Development

go vet ./... && go test ./...
GOOS=js GOARCH=wasm go build ./cmd/lm15-wasm   # the browser runtime

License

MIT. See LICENSE.

Documentation

Overview

Package lm15 is one request and response model for every major AI model provider: write a Request once and send it to OpenAI, Anthropic, Gemini, xAI, Groq, DeepSeek, OpenRouter, Z.AI, Moonshot, Meta, a cloud (Azure, Bedrock, Vertex) or a local server, by changing the model string.

router := lm15.NewRouter() // keys from the environment
response, err := router.Complete(ctx, &lm15.Request{
	Model:    "anthropic:claude-haiku-4-5",
	Messages: []lm15.Message{lm15.UserMessage("What eats acorns at night?")},
})
if err != nil {
	return err
}
fmt.Println(response.TextOr(""))

The package is low-level on purpose: typed requests (Request, Message, the Part kinds), responses (Response), stream events (StreamEvent, ResponseStream), tools (FunctionTool, BuiltinTool), errors (Error, ErrorKind) and exact JSON serialization. It runs no tool loop and retries nothing on its own; programs and libraries built on it decide those.

Routing

LMRouter resolves a model string to a provider: "provider:model" ("gemini:gemini-2.5-flash", "ollama:qwen3.5:0.8b") or a bare name it recognizes ("gpt-4.1-mini"). NewRouterWithConfig sets keys, endpoints, cloud identities, timeouts and saved sign-ins (Auth) explicitly. Each provider also has its own constructor (NewOpenAILM, NewAnthropicLM, NewGeminiLM, ...) returning an LM.

JSON objects

Tool parameters, response formats, tool-call input, extensions and provider data are JSONObject: key/value [Member]s in order. The order is sent as written and read as received, because it is data: a model fills a structured answer in the order its schema lists the fields. Build one with KV or DecodeJSONObject; read it with Get, Lookup and All.

Contract

lm15 exists for Python, TypeScript, Rust and Go, graded by one shared contract (github.com/lm15-dev/lm15-contract): the same request produces the same wire request and the same response in every language. Guides with Go examples: https://lm15.dev/docs/.

Index

Examples

Constants

View Source
const (
	DefaultClaudeCodeVersion      = "2.1.285"
	ClaudeCodeVersionEnv          = "LM15_CLAUDE_CODE_VERSION"
	CodexClientVersionEnv         = "LM15_CODEX_CLIENT_VERSION"
	DefaultClaudeCodeSystemPrompt = "You are Claude Code, Anthropic's official CLI for Claude."
	ClaudeCodeLoginHint           = "Log in again: run `claude` and use /login (Claude subscription auth)"
	OpenAICodexLoginHint          = "Log in again: run `codex login` (ChatGPT subscription auth)"
	XaiLoginHint                  = "Log in again: run lm15.auth.login_xai() (SuperGrok / X Premium subscription auth)"
)

Claude Code constants. DefaultClaudeCodeVersion is the Claude Code release the claude-code door says it is (user-agent: claude-cli/<version>). Anthropic's server reads it: a model can require a newer release (claude-opus-5-5 refuses anything before 2.1.280, live 2026-09-23 and 2026-09-30). The latest release when last receipted (lm15-contract changes/2026-09-30-claude-code-client-version.md); callers move it without a release through the client_version setting or LM15_CLAUDE_CODE_VERSION.

View Source
const (
	DefaultCodexBaseURL       = "https://chatgpt.com/backend-api/codex"
	DefaultCodexOriginator    = "lm15"
	DefaultCodexInstructions  = "You are a helpful assistant."
	DefaultCodexClientVersion = "0.147.0"
	CodexBackend              = "chatgpt-codex"
)

Codex constants.

View Source
const (
	ClaudeCodeClientID  = "9d1c250a-e61b-44d5-88ed-5944d1962f5e"
	ClaudeCodeTokenURL  = "https://platform.claude.com/v1/oauth/token"
	OpenAICodexClientID = "app_EMoamEEZ73f0CkXaXp7hrann"
	OpenAICodexTokenURL = "https://auth.openai.com/oauth/token"

	XaiClientID      = "b1a00492-073a-47ea-816f-4c329264a828"
	XaiDeviceCodeURL = "https://auth.x.ai/oauth2/device/code"
	XaiTokenURL      = "https://auth.x.ai/oauth2/token"
	XaiOAuthScope    = "openid profile email offline_access grok-cli:access api:access"
)
View Source
const (
	// MaxOrderedLevels is Jev's Score ceiling (docs.typesafe.ai/primitives/score).
	MaxOrderedLevels = 10
	// MaxChoiceKeys is Jev's Choice ceiling (docs.typesafe.ai/primitives/choice).
	MaxChoiceKeys = 255
)
View Source
const (
	DefaultTurnMaxBytes  = 16 * 1024 * 1024
	DefaultTurnMaxEvents = 10000
)

The shared defaults: a round conservative payload budget for an explicitly buffering convenience, not a measured percentile.

View Source
const (
	DialectOpenAIResponses = "openai-responses"
	DialectOpenAIChat      = "openai-chat"
	DialectAnthropic       = "anthropic"
	DialectGemini          = "gemini"
	DialectTypeSafe        = "typesafe"
)

Dialect names the wire format an adapter speaks.

View Source
const (
	DefaultConnectTimeout = 10 * time.Second
	DefaultReadTimeout    = 600 * time.Second
	DefaultWriteTimeout   = 600 * time.Second
	DefaultPoolTimeout    = 600 * time.Second
	DefaultMaxConnections = 100
)

The shared defaults (ratified 2026-09-15, A1).

View Source
const (
	RoleUser      = "user"
	RoleAssistant = "assistant"
	RoleTool      = "tool"
	RoleDeveloper = "developer"
)

Role of a Message.

View Source
const (
	PartTypeText       = "text"
	PartTypeImage      = "image"
	PartTypeAudio      = "audio"
	PartTypeVideo      = "video"
	PartTypeDocument   = "document"
	PartTypeBinary     = "binary"
	PartTypeToolCall   = "tool_call"
	PartTypeToolResult = "tool_result"
	PartTypeThinking   = "thinking"
	PartTypeRefusal    = "refusal"
	PartTypeCitation   = "citation"
	PartTypeData       = "data"
)

Part type discriminators.

View Source
const (
	DeltaTypeText         = "text"
	DeltaTypeThinking     = "thinking"
	DeltaTypeAudio        = "audio"
	DeltaTypeImage        = "image"
	DeltaTypeToolCall     = "tool_call"
	DeltaTypeCitation     = "citation"
	DeltaTypeContinuation = "continuation"
)

Delta type discriminators.

View Source
const (
	FinishStop          = "stop"
	FinishLength        = "length"
	FinishToolCall      = "tool_call"
	FinishContentFilter = "content_filter"
	FinishError         = "error"
)

FinishReason values.

View Source
const (
	EffortOff     = "off"
	EffortMinimal = "minimal"
	EffortLow     = "low"
	EffortMedium  = "medium"
	EffortHigh    = "high"
	EffortXHigh   = "xhigh"
	EffortMax     = "max"
)

ReasoningEffort values (MAP-7).

View Source
const (
	CodeAuth               = "auth"
	CodeBilling            = "billing"
	CodeRateLimit          = "rate_limit"
	CodeInvalidRequest     = "invalid_request"
	CodeContextLength      = "context_length"
	CodeTimeout            = "timeout"
	CodeServer             = "server"
	CodeUnsupportedModel   = "unsupported_model"
	CodeUnsupportedFeature = "unsupported_feature"
	CodeNotConfigured      = "not_configured"
	CodeUnknownModel       = "unknown_model"
	CodeAmbiguousModel     = "ambiguous_model"
	CodeTransport          = "transport"
	CodeLockTimeout        = "lock_timeout"
	CodeStreamAssembly     = "stream_assembly"
	CodeCollectionLimit    = "collection_limit"
	CodeProvider           = "provider"
	CodeAuthOperation      = "auth_operation"
)

ErrorCode values (bidirectional with the error class hierarchy).

View Source
const (
	BatchQueued     = "queued"
	BatchRunning    = "running"
	BatchCancelling = "cancelling"
	BatchCompleted  = "completed"
	BatchFailed     = "failed"
	BatchCancelled  = "cancelled"
	BatchExpired    = "expired"
)

Batch statuses.

View Source
const (
	AdaptDropped     = "dropped"
	AdaptClamped     = "clamped"
	AdaptSubstituted = "substituted"
	AdaptClientSide  = "client_side"
	AdaptSatisfied   = "satisfied"
	AdaptDefaulted   = "defaulted"
)

AdaptationAction values (MAP-13, 2026-09-14): what the wire got that differs from what was asked.

View Source
const (
	AdaptationsNote   = "note"
	AdaptationsSilent = "silent"
	AdaptationsRefuse = "refuse"
)

AdaptationPolicy values: the value of WithAdaptations / RouterConfig.Adaptations.

View Source
const (
	ProbabilitiesOff         = "off"
	ProbabilitiesIfAvailable = "if_available"
	ProbabilitiesRequired    = "required"
)

ProbabilityPolicy values (Config.Probabilities; MAP-14, 2026-09-17).

View Source
const (
	MethodProviderClassification      = "provider_classification"
	MethodCandidateSequenceLikelihood = "candidate_sequence_likelihood"
)

JudgmentMethod values: how a DataPart's distribution was measured.

View Source
const (
	CredentialPlatform    = "platform"
	CredentialWorkload    = "workload"
	CredentialEnvironment = "environment"
	CredentialCLI         = "cli"
)

NamedCredential values (AUTH-1, 2026-09-19): one identity on a cloud door instead of its chain; the same four words on every cloud.

View Source
const DefaultXaiBaseURL = "https://api.x.ai/v1"

DefaultXaiBaseURL is api.x.ai.

View Source
const PlanningKey = "lm15-planning"

PlanningKey is the placeholder credential a planning LM carries.

View Source
const RenewalLeadMs = 300_000.0

RenewalLeadMs is AUTH-20.3's lead: min(300 s, lifetime / 10).

View Source
const Version = "1.1.0-rc.7"

Version is this port's implementation version.

Variables

View Source
var (
	Ollama = tableAccess("ollama")
	VLLM   = tableAccess("vllm")
	SGLang = tableAccess("sglang")
)

Keyless local servers.

StreamablePartTypes / NonStreamablePartTypes partition PartTypes (INV-035).

BatchStatuses is the BatchStatus vocabulary; BatchTerminalStatuses its terminal subset.

View Source
var (
	VideoStatuses         = []string{"queued", "running", "completed", "failed", "cancelled"}
	VideoTerminalStatuses = []string{"completed", "failed", "cancelled"}
)

VideoStatuses is the VideoStatus vocabulary; VideoTerminalStatuses its terminal subset.

View Source
var (
	CacheModes      = []string{"auto", "off"}
	CacheRetentions = []string{"short", "long"}
	CachePrefixes   = []string{"stable", "history"}
)

Cache vocabularies (MAP-6).

View Source
var (
	LiveClientEventTypes = []string{"turn", "audio", "image", "text", "tool_result", "interrupt", "end_audio"}
	LiveServerEventTypes = []string{"audio", "text", "tool_call", "tool_call_delta", "interrupted", "turn_end", "usage", "error"}
)

Live event vocabularies.

View Source
var (
	AuthSchemes        = []string{"bearer", "x-api-key", "api-key", "query-key", "sigv4"}
	CredentialKinds    = []string{"api_key", "bearer_token", "aws"}
	CredentialPolicies = []string{"key", "oauth", "oauth-unless-explicit", "aws-chain", "azure-chain", "gcp-chain"}
	RungKinds          = []string{"env", "ini-profile", "json-file", "subprocess", "http-metadata", "http-token-exchange", "sigv4-sts", "unsigned-sts", "jwt-rs256", "file-cache"}
	AuthStepStates     = []string{"selected", "shadowed", "absent", "unprobed"}
	StreamFramings     = []string{"sse", "aws-event-stream"}
	ModelPlacements    = []string{"body", "path"}
)

Auth vocabularies (spec/auth.md, spec/vocabularies.md, 2026-09-03).

AdaptationActions is the AdaptationAction vocabulary.

AdaptationPolicies is the AdaptationPolicy vocabulary.

View Source
var AnthropicAPI = tableAccess("anthropic")

AnthropicAPI is the Anthropic Messages API on an API key.

View Source
var AnthropicPresetBaseURLs = tableAnthropicPresetBaseURLs

AnthropicPresetBaseURLs are the addresses the Anthropic presets name.

View Source
var AudioEncodings = []string{"pcm16", "opus", "mp3", "aac"}

AudioEncodings is the AudioEncoding vocabulary.

View Source
var AuthFailedForms = []AuthFailedForm{
	{Code: "INVALID_ARGUMENT", Reason: "API_KEY_INVALID"},
	{Code: "invalid-argument", Prefix: "Incorrect API key provided"},
}

AuthFailedForms are the pinned forms (lm15-contract spec/auth-failed.json, carried verbatim; each form has a live receipt).

View Source
var AwsAnthropic = tableAccess("aws-anthropic")

AwsAnthropic is Claude Platform on AWS.

View Source
var Azure = tableAccess("azure")

Azure is Azure OpenAI v1 (Responses wire).

View Source
var AzureAnthropic = tableAccess("azure-anthropic")

AzureAnthropic is Claude in Microsoft Foundry.

View Source
var AzureChat = tableAccess("azure-chat")

AzureChat is Azure OpenAI v1 (Chat Completions wire).

View Source
var BatchOutcomes = []string{"succeeded", "errored", "cancelled", "expired"}

BatchOutcomes is the BatchOutcome vocabulary.

View Source
var BedrockAnthropic = tableAccess("bedrock-anthropic")

BedrockAnthropic is Claude in Amazon Bedrock (mantle).

View Source
var BedrockChat = tableAccess("bedrock-chat")

BedrockChat is Bedrock's Chat Completions door on bedrock-runtime.

View Source
var BedrockMantleChat = tableAccess("bedrock-mantle-chat")

BedrockMantleChat is Bedrock Chat Completions on bedrock-mantle.

View Source
var ClaudeCode = tableAccess("claude-code")

ClaudeCode is the Anthropic dialect on a local Claude Code login.

View Source
var DeclaredLoginProviders = func() []ProviderDefinition {
	out := make([]ProviderDefinition, 0, len(tableDeclaredLogin))
	for _, r := range tableDeclaredLogin {
		out = append(out, definitionOf(r, true))
	}
	return out
}()

DeclaredLoginProviders are the routes that exist only for a managed connection (lm15-python lm15/login/declared.py): kimi-code (Anthropic Messages at api.kimi.com/coding) and github-copilot (Chat Completions at the account's Copilot host). No contract wire receipt, so no registry row (a row is a support claim, AUTH-26); a router routes them only with a managed Auth.

View Source
var DeepInfra = tableAccess("deepinfra")

DeepInfra is DeepInfra open-model inference (Chat Completions dialect).

View Source
var DeepInfraForcedToolChoice = func() []string {
	var out []string
	for _, o := range tableOpenAIChatPresets["deepinfra"].ModelOverrides {
		if o.Knobs["forced_tool_choice"] == "send" {
			out = append(out, o.Prefix)
		}
	}
	return out
}()

DeepInfraForcedToolChoice lists the DeepInfra models measured to honour a forced tool choice (survey of 24, 2026-09-26); each id is a prefix, so a suffixed variant (-0731, -Turbo) inherits its entry. Read from the generated deepinfra preset's model overrides.

View Source
var DeepSeek = tableAccess("deepseek")

DeepSeek is DeepSeek (Chat Completions dialect).

View Source
var DeepSeekAnthropic = tableAccess("deepseek-anthropic")

DeepSeekAnthropic is DeepSeek over the Anthropic Messages wire.

View Source
var DefaultRules = tableDefaultRules

DefaultRules is the complete built-in knowledge of the router; first match wins. Generated from the reference's table (tables_generated.go); pinned by lm15-contract router/resolution.json.

DeltaTypes is the DeltaType vocabulary in declaration order.

View Source
var EffortThinkingBudgets = map[string]int{
	"minimal": 1024, "low": 2048, "medium": 8192, "high": 16384, "xhigh": 24576, "max": 32768,
}

EffortThinkingBudgets is the one effort→budget grading table (MAP-7 rule 3).

View Source
var ErrLoginCancelled = fmt.Errorf("lm15: login cancelled: %w", context.Canceled)

ErrLoginCancelled is the cancellation outcome (AUTH-24 "cancelled"): a login stopped by its context, a closed prompt, CancelLogin, a logout or Close. It wraps context.Canceled — Go's own cancellation — and is never dressed up as an lm15 error.

View Source
var ErrPromptCancelled = errors.New("prompt cancelled")

ErrPromptCancelled is what a UI returns when the person cancels a prompt.

ErrorCodes is the ErrorCode vocabulary in declaration order.

View Source
var ExternalSources = [][3]string{
	{"claude-code-cli", "claude-code", "your Claude Code login (~/.claude/.credentials.json)"},
	{"codex-cli", "openai-codex", "your Codex CLI login (~/.codex/auth.json)"},
	{"pi-xai", "xai", "your Pi agent xAI login (~/.pi/agent/auth.json)"},
}

ExternalSources: source id → provider route and human label.

View Source
var FileReadinessValues = []string{"pending", "ready", "failed"}

FileReadinessValues is the FileReadiness vocabulary.

FinishReasons is the FinishReason vocabulary.

View Source
var Fireworks = tableAccess("fireworks")

Fireworks is Fireworks AI open-model inference (Chat Completions dialect).

View Source
var GeminiAPI = tableAccess("gemini")

GeminiAPI is the Google Gemini API on an API key.

View Source
var Groq = tableAccess("groq")

Groq is Groq Cloud (Chat Completions dialect).

JudgmentMethods is the JudgmentMethod vocabulary.

View Source
var LitellmProviderPrefixes = tableLitellmPrefixes

LitellmProviderPrefixes maps litellm's `<provider>/` prefixes to lm15 doors.

View Source
var Meta = tableAccess("meta")

Meta is the Meta Model API over the Responses wire.

View Source
var MetaAnthropic = tableAccess("meta-anthropic")

MetaAnthropic is Meta over the Anthropic Messages wire.

View Source
var MetaChat = tableAccess("meta-chat")

MetaChat is Meta's Chat Completions wire.

View Source
var ModelNotFoundForms = []ModelNotFoundForm{
	{Code: "not_found_error", Prefix: "model: "},
	{Code: "invalid_request_error", Contains: "The supported API model names are "},
	{Code: "1211"},
	{Code: "1214", Prefix: "modelCode: "},
	{Code: "400", Suffix: " is not a valid model ID"},
	{Code: "invalid-argument", Prefix: "Model not found: "},
	{Code: "validation_error", Contains: "The provided model identifier is invalid"},
	{Code: "invalid_request_error", Prefix: "Deployment ", Suffix: " doesn't exist or isn't accessible."},
}

ModelNotFoundForms are the pinned forms that carry no model-specific code and no not-found class (lm15-contract spec/model-not-found.json, carried verbatim; each form has a live receipt).

View Source
var Moonshotai = tableAccess("moonshotai")

Moonshotai is Moonshot AI Kimi (Chat Completions dialect).

View Source
var MoonshotaiAnthropic = tableAccess("moonshotai-anthropic")

MoonshotaiAnthropic is Moonshot over the Anthropic Messages wire.

View Source
var MoonshotaiResponses = tableAccess("moonshotai-responses")

MoonshotaiResponses is Moonshot's Responses wire.

NamedCredentials is the NamedCredential vocabulary.

View Source
var NamedMeaning = map[string]map[string]string{
	"aws-chain": {
		CredentialPlatform:    "the ECS/EKS container endpoint, else the EC2 instance role (IMDSv2)",
		CredentialWorkload:    "web identity (AWS_WEB_IDENTITY_TOKEN_FILE + AWS_ROLE_ARN) via STS",
		CredentialEnvironment: "AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY",
		CredentialCLI:         "the active `aws` profile (assume-role, SSO, shared files, `aws login`, credential_process)",
	},
	"azure-chain": {
		CredentialPlatform:    "Azure managed identity",
		CredentialWorkload:    "Entra workload identity (AZURE_FEDERATED_TOKEN_FILE)",
		CredentialEnvironment: "an Entra service principal from AZURE_TENANT_ID / AZURE_CLIENT_ID + secret or certificate",
		CredentialCLI:         "`az`, Azure PowerShell or `azd` sign-in",
	},
	"gcp-chain": {
		CredentialPlatform:    "the attached service account (GCE metadata server)",
		CredentialWorkload:    "workload identity federation (GOOGLE_APPLICATION_CREDENTIALS, type external_account)",
		CredentialEnvironment: "a service-account file (GOOGLE_APPLICATION_CREDENTIALS, type service_account)",
		CredentialCLI:         "`gcloud auth application-default login` (the ADC file) or `gcloud auth print-access-token`",
	},
}

NamedMeaning is what each name means on each cloud, for the doctor and for errors.

View Source
var NamedRungs = map[string]map[string][]string{
	"aws-chain": {
		CredentialPlatform:    {"container", "imds"},
		CredentialWorkload:    {"web-identity"},
		CredentialEnvironment: {"env:AWS_ACCESS_KEY_ID"},
		CredentialCLI:         {"assume-role", "sso", "shared-credentials-file", "login", "credential_process", "config-file"},
	},
	"azure-chain": {
		CredentialPlatform:    {"managed-identity"},
		CredentialWorkload:    {"workload-identity"},
		CredentialEnvironment: {"environment"},
		CredentialCLI:         {"az", "pwsh", "azd"},
	},
	"gcp-chain": {
		CredentialPlatform:    {"metadata"},
		CredentialWorkload:    {"adc-env"},
		CredentialEnvironment: {"adc-env"},
		CredentialCLI:         {"adc-file", "gcloud"},
	},
}

NamedRungs is AUTH-1 (amended 2026-09-19): the rungs each named credential covers on each cloud. One word, the same on every cloud; the doctor and every auth error print the concrete mechanism, never just the word. platform on AWS covers two rungs (the container endpoint, then IMDS): both are the machine's own identity, boto3 tries them in this order, and the doctor says which answered. workload and environment on GCP are the same file rung told apart by the file's type (external_account vs service_account); the wrong type is refused by name, never read as the other.

View Source
var OpenAIAPI = tableAccess("openai")

OpenAIAPI is the OpenAI Responses API on an API key.

View Source
var OpenAIChatAPI = tableAccess("openai-chat")

OpenAIChatAPI is the OpenAI Chat Completions dialect on an API key.

View Source
var OpenAIChatPresetBaseURLs = tableOpenAIChatPresetBaseURLs

OpenAIChatPresetBaseURLs are the addresses the Chat presets name.

View Source
var OpenAICodex = tableAccess("openai-codex")

OpenAICodex is the Responses dialect on a local Codex CLI login.

View Source
var OpenAIResponsesPresetBaseURLs = tableOpenAIResponsesPresetBaseURLs

OpenAIResponsesPresetBaseURLs are the addresses the Responses presets name.

View Source
var OpenRouter = tableAccess("openrouter")

OpenRouter is OpenRouter (Chat Completions dialect).

View Source
var Parasail = tableAccess("parasail")

Parasail is Parasail open-model inference (Chat Completions dialect).

PartTypes is the PartType vocabulary in declaration order.

ProbabilityPolicies is the ProbabilityPolicy vocabulary.

View Source
var Providers = func() map[string]ProviderDefinition {
	out := make(map[string]ProviderDefinition, len(providerDefinitions))
	for _, d := range providerDefinitions {
		out[d.ID] = d
	}
	return out
}()

Providers maps every provider id to its definition.

ReasoningEfforts is the ReasoningEffort vocabulary.

View Source
var ReasoningSummaries = []string{"auto", "concise", "detailed"}

ReasoningSummaries is the ReasoningSummary vocabulary.

Roles is the Role vocabulary in declaration order.

View Source
var SerdeKinds = map[string]struct {
	From func(JSONObject) (any, error)
	To   func(any) JSONObject
}{
	"part":                       {func(d JSONObject) (any, error) { return PartFromDict(d) }, func(v any) JSONObject { return PartToDict(v.(Part)) }},
	"message":                    {func(d JSONObject) (any, error) { return MessageFromDict(d) }, func(v any) JSONObject { return MessageToDict(v.(Message)) }},
	"tool":                       {func(d JSONObject) (any, error) { return ToolFromDict(d) }, func(v any) JSONObject { return ToolToDict(v.(Tool)) }},
	"tool_choice":                {func(d JSONObject) (any, error) { return ToolChoiceFromDict(d) }, func(v any) JSONObject { return ToolChoiceToDict(v.(ToolChoice)) }},
	"reasoning":                  {func(d JSONObject) (any, error) { return ReasoningFromDict(d) }, func(v any) JSONObject { return ReasoningToDict(v.(Reasoning)) }},
	"config":                     {func(d JSONObject) (any, error) { return ConfigFromDict(d) }, func(v any) JSONObject { return ConfigToDict(v.(Config)) }},
	"cache_config":               {func(d JSONObject) (any, error) { return CacheConfigFromDict(d) }, func(v any) JSONObject { return CacheConfigToDict(v.(CacheConfig)) }},
	"cache_info":                 {func(d JSONObject) (any, error) { return CacheInfoFromDict(d) }, func(v any) JSONObject { return CacheInfoToDict(v.(CacheInfo)) }},
	"cache_page":                 {func(d JSONObject) (any, error) { return CachePageFromDict(d) }, func(v any) JSONObject { return CachePageToDict(v.(CachePage)) }},
	"cached_prefix":              {func(d JSONObject) (any, error) { return CachedPrefixFromDict(d) }, func(v any) JSONObject { return CachedPrefixToDict(v.(CachedPrefix)) }},
	"token_logprob":              {func(d JSONObject) (any, error) { return TokenLogprobFromDict(d) }, func(v any) JSONObject { return TokenLogprobToDict(v.(TokenLogprob)) }},
	"continuation_state":         {func(d JSONObject) (any, error) { return ContinuationFromDict(d) }, func(v any) JSONObject { return ContinuationToDict(v.(ContinuationState)) }},
	"error_detail":               {func(d JSONObject) (any, error) { return ErrorDetailFromDict(d) }, func(v any) JSONObject { return ErrorDetailToDict(v.(ErrorDetail)) }},
	"delta":                      {func(d JSONObject) (any, error) { return DeltaFromDict(d) }, func(v any) JSONObject { return DeltaToDict(v.(Delta)) }},
	"usage":                      {func(d JSONObject) (any, error) { return UsageFromDict(d) }, func(v any) JSONObject { return UsageToDict(v.(Usage)) }},
	"credential":                 {func(d JSONObject) (any, error) { return CredentialFromDict(d) }, func(v any) JSONObject { return CredentialToDict(v.(Credential)) }},
	"stream_event":               {func(d JSONObject) (any, error) { return StreamEventFromDict(d) }, func(v any) JSONObject { return StreamEventToDict(v.(StreamEvent)) }},
	"request":                    {func(d JSONObject) (any, error) { return RequestFromDict(d) }, func(v any) JSONObject { return RequestToDict(v.(*Request)) }},
	"response":                   {func(d JSONObject) (any, error) { return ResponseFromDict(d) }, func(v any) JSONObject { return ResponseToDict(v.(*Response), false) }},
	"model_info":                 {func(d JSONObject) (any, error) { return ModelInfoFromDict(d) }, func(v any) JSONObject { return ModelInfoToDict(v.(ModelInfo)) }},
	"batch_request":              {func(d JSONObject) (any, error) { return BatchRequestFromDict(d) }, func(v any) JSONObject { return BatchRequestToDict(v.(BatchRequest)) }},
	"batch_job":                  {func(d JSONObject) (any, error) { return BatchJobFromDict(d) }, func(v any) JSONObject { return BatchJobToDict(v.(BatchJobInfo)) }},
	"batch_entry":                {func(d JSONObject) (any, error) { return BatchEntryFromDict(d) }, func(v any) JSONObject { return BatchEntryToDict(v.(BatchEntry)) }},
	"file_upload_request":        {func(d JSONObject) (any, error) { return FileUploadRequestFromDict(d) }, func(v any) JSONObject { return FileUploadRequestToDict(v.(FileUploadRequest)) }},
	"file_info":                  {func(d JSONObject) (any, error) { return FileInfoFromDict(d) }, func(v any) JSONObject { return FileInfoToDict(v.(FileInfo)) }},
	"file_page":                  {func(d JSONObject) (any, error) { return FilePageFromDict(d) }, func(v any) JSONObject { return FilePageToDict(v.(FilePage)) }},
	"image_generation_request":   {func(d JSONObject) (any, error) { return ImageGenerationRequestFromDict(d) }, func(v any) JSONObject { return ImageGenerationRequestToDict(v.(ImageGenerationRequest)) }},
	"image_generation_response":  {func(d JSONObject) (any, error) { return ImageGenerationResponseFromDict(d) }, func(v any) JSONObject { return ImageGenerationResponseToDict(v.(ImageGenerationResponse)) }},
	"speech_generation_request":  {func(d JSONObject) (any, error) { return SpeechGenerationRequestFromDict(d) }, func(v any) JSONObject { return SpeechGenerationRequestToDict(v.(SpeechGenerationRequest)) }},
	"speech_generation_response": {func(d JSONObject) (any, error) { return SpeechGenerationResponseFromDict(d) }, func(v any) JSONObject { return SpeechGenerationResponseToDict(v.(SpeechGenerationResponse)) }},
	"video_generation_request":   {func(d JSONObject) (any, error) { return VideoGenerationRequestFromDict(d) }, func(v any) JSONObject { return VideoGenerationRequestToDict(v.(VideoGenerationRequest)) }},
	"video_job":                  {func(d JSONObject) (any, error) { return VideoJobFromDict(d) }, func(v any) JSONObject { return VideoJobToDict(v.(VideoJobInfo)) }},
	"audio_format":               {func(d JSONObject) (any, error) { return AudioFormatFromDict(d) }, func(v any) JSONObject { return AudioFormatToDict(v.(AudioFormat)) }},
	"live_config":                {func(d JSONObject) (any, error) { return LiveConfigFromDict(d) }, func(v any) JSONObject { return LiveConfigToDict(v.(LiveConfig)) }},
	"live_client_event":          {func(d JSONObject) (any, error) { return LiveClientEventFromDict(d) }, func(v any) JSONObject { return LiveClientEventToDict(v.(LiveClientEvent)) }},
	"live_server_event":          {func(d JSONObject) (any, error) { return LiveServerEventFromDict(d) }, func(v any) JSONObject { return LiveServerEventToDict(v.(LiveServerEvent)) }},
}

SerdeKinds maps the protocol's serde kinds to (from_dict, to_dict).

View Source
var StreamEventTypes = []string{"start", "delta", "end", "error"}

StreamEventTypes is the StreamEventType vocabulary.

View Source
var Together = tableAccess("together")

Together is Together AI open-model inference (Chat Completions dialect).

View Source
var ToolChoiceModes = []string{"auto", "required", "none"}

ToolChoiceModes is the ToolChoiceMode vocabulary.

View Source
var TypeSafeAPI = tableAccess("typesafe")

TypeSafeAPI is the typesafe access policy: bearer key, complete and models only (D11: no stream).

View Source
var Vertex = tableAccess("vertex")

Vertex is Gemini on Google Cloud. API keys (amended 2026-09-26): a Vertex API key in x-goog-api-key on the project-scoped hosts; key first, a token-shaped string still bearer (AuthHeaderFor). No env key: GOOGLE_API_KEY belongs to the Gemini API and vertex-express, and reading it here would silently replace the ADC identity.

View Source
var VertexAnthropic = tableAccess("vertex-anthropic")

VertexAnthropic is Claude on Google Cloud (rawPredict).

View Source
var VertexExpress = tableAccess("vertex-express")

VertexExpress is Vertex express mode (API key).

View Source
var VetHandlers map[string]func(JSONObject) (JSONObject, error)

VetHandlers lists the ops this shim answers.

View Source
var Vocabularies = map[string][]string{
	"Role":                    Roles,
	"PartType":                PartTypes,
	"DeltaType":               DeltaTypes,
	"FinishReason":            FinishReasons,
	"ReasoningEffort":         ReasoningEfforts,
	"ReasoningSummary":        ReasoningSummaries,
	"ErrorCode":               ErrorCodes,
	"StreamEventType":         StreamEventTypes,
	"BatchStatus":             BatchStatuses,
	"BATCH_TERMINAL_STATUSES": BatchTerminalStatuses,
	"BatchOutcome":            BatchOutcomes,
	"VideoStatus":             VideoStatuses,
	"VIDEO_TERMINAL_STATUSES": VideoTerminalStatuses,
	"FileReadiness":           FileReadinessValues,
	"AudioEncoding":           AudioEncodings,
	"ToolChoiceMode":          ToolChoiceModes,
	"CacheMode":               CacheModes,
	"CacheRetention":          CacheRetentions,
	"CachePrefix":             CachePrefixes,
	"LiveClientEventType":     LiveClientEventTypes,
	"LiveServerEventType":     LiveServerEventTypes,
	"AuthScheme":              AuthSchemes,
	"CredentialKind":          CredentialKinds,
	"CredentialPolicy":        CredentialPolicies,
	"RungKind":                RungKinds,
	"AuthStepState":           AuthStepStates,
	"StreamFraming":           StreamFramings,
	"ModelPlacement":          ModelPlacements,
	"AdaptationAction":        AdaptationActions,
	"AdaptationPolicy":        AdaptationPolicies,
	"ProbabilityPolicy":       ProbabilityPolicies,
	"JudgmentMethod":          JudgmentMethods,
	"NamedCredential":         NamedCredentials,
}

Vocabularies maps every vocabulary name to its values (the runtime mirror surface_dump reflects). Names follow spec/vocabularies.md.

View Source
var Xai = tableAccess("xai")

Xai is xAI Grok: Chat Completions dialect with subscription OAuth fallback.

View Source
var Zai = tableAccess("zai")

Zai is Z.AI (Chat Completions dialect).

Functions

func AnthropicAdaptiveClass added in v1.0.1

func AnthropicAdaptiveClass(model string) bool

AnthropicAdaptiveClass reports models that take thinking.type=adaptive (MAP-7 rule 10).

func AuthHeaderFor added in v1.0.1

func AuthHeaderFor(policy AccessPolicy, credential Credential, apiKeyHeader string) (name, value string, ok bool, err error)

AuthHeaderFor returns the (name, value) header carrying the credential, or ok=false when the scheme is not a header (sigv4 signs; query-key rides the query).

func AzureCertificateAssertion added in v1.0.1

func AzureCertificateAssertion(ctx *ChainContext, tenant, clientID, pem, jti string, sendChain bool) (string, error)

AzureCertificateAssertion is the Entra client assertion (RS256, x5t).

func AzureEnvironmentRequest added in v1.0.1

func AzureEnvironmentRequest(ctx *ChainContext, jti string) (string, [][2]string, error)

AzureEnvironmentRequest is the (token URL, form pairs) for the env service principal.

func B added in v1.0.1

func B(v bool) *bool

B returns a pointer to a bool.

func CanonicalProvider added in v1.0.1

func CanonicalProvider(name string) string

CanonicalProvider maps the permanent underscore alias to the hyphenated form.

func ChainCacheKey added in v1.0.1

func ChainCacheKey(policy AccessPolicy, ctx *ChainContext) string

ChainCacheKey is provider id + the identity-selecting settings (AUTH-3).

func ClaudeCodeCredentialsPath added in v1.0.1

func ClaudeCodeCredentialsPath() string

Well-known paths (AUTH-8).

func ClaudeCodeVersionGuidance

func ClaudeCodeVersionGuidance(message string) string

ClaudeCodeVersionGuidance is the claude-code door's minimum-version refusal with what an lm15 caller changes (AUTH-10 backend settings): the server says "run 'claude update'", which does not move the version lm15 claims. Any other message is returned unchanged.

func CoalesceStream

func CoalesceStream(events iter.Seq2[StreamEvent, error], model string) iter.Seq2[StreamEvent, error]

CoalesceStream enforces one leading start and one final merged end event over a raw adapter stream; delta and error events pass through.

func CoalesceStreamWith added in v1.0.1

func CoalesceStreamWith(events iter.Seq2[StreamEvent, error], model string, adaptations []Adaptation) iter.Seq2[StreamEvent, error]

CoalesceStreamWith is CoalesceStream with the build's adaptations stamped on the start event.

func CodexCLIAuthPath added in v1.0.1

func CodexCLIAuthPath() string

func DataPartText added in v1.0.1

func DataPartText(part DataPart) string

DataPartText is a data part on a wire that takes only text: its value as compact canonical JSON, nothing added (changes/2026-09-19-jev-state.md D3; types.md §DataPart). An opaque payload: numbers as written.

func DecodeJSON added in v1.0.1

func DecodeJSON(data []byte) (any, error)

DecodeJSON parses JSON into Go values: objects as JSONObject in the order their keys arrived, lists as []any, numbers as json.Number, so an opaque payload re-encodes exactly as it arrived (key order kept, 1 stays 1, 1.0 stays 1.0). Every wire body and every canonical JSON document lm15 reads goes through here.

func DefaultCredentialsPath added in v1.0.1

func DefaultCredentialsPath() string

DefaultCredentialsPath is $LM15_CREDENTIALS_PATH, else $XDG_CONFIG_HOME/lm15/credentials.json, else ~/.config/lm15/credentials.json.

func EffortForBudget

func EffortForBudget(budget int) string

EffortForBudget is the highest effort whose MAP-7 rule 3 budget is at or below budget ("minimal" below 1024): the grading table read the other way.

func EncodeJSON added in v1.0.1

func EncodeJSON(v any) ([]byte, error)

EncodeJSON serializes a value compactly (no HTML escaping, as every other port does), writing each JSONObject's keys in member order. Text that is not valid Unicode — a lone surrogate U+D800..U+DFFF, or any other invalid UTF-8 — has no UTF-8 form and can reach no provider; it is refused here, before the wire, as the input error it is (INV-055), never silently replaced by U+FFFD.

func EndpointFromEnv added in v1.0.1

func EndpointFromEnv(host *HostSpec, env map[string]string) string

EndpointFromEnv is the first non-empty vendor endpoint variable this door honours (AUTH-10, amended 2026-09-19).

func ExpectedLevel added in v1.0.1

func ExpectedLevel(distribution map[string]float64) (float64, error)

ExpectedLevel is Σ p·i over an ordered judgment's distribution.

func ExtractChatGPTAccountID added in v1.0.1

func ExtractChatGPTAccountID(token string) string

ExtractChatGPTAccountID reads the chatgpt_account_id claim from a Codex token.

func F added in v1.0.1

func F(v float64) *float64

F returns a pointer to a float (Config{Temperature: lm15.F(0.2)}).

func FormatRFC3339 added in v1.0.1

func FormatRFC3339(t time.Time) string

FormatRFC3339 renders whole-second UTC: YYYY-MM-DDTHH:MM:SSZ.

func GCPServiceAccountAssertion added in v1.0.1

func GCPServiceAccountAssertion(ctx *ChainContext, info JSONObject, scope string) (string, string, error)

GCPServiceAccountAssertion is (token_uri, JWT) for a service_account file.

func GeminiLevelClass added in v1.0.1

func GeminiLevelClass(model string) bool

GeminiLevelClass reports the Gemini 3.x class (thinkingLevel, no full off).

func GetClaudeCodeAccessToken added in v1.0.1

func GetClaudeCodeAccessToken(ctx context.Context, path string, refresh bool) (string, error)

GetClaudeCodeAccessToken returns a usable token, refreshing under the lock when expired (double-checked).

func GetXaiAccessToken added in v1.0.1

func GetXaiAccessToken(ctx context.Context, path string, refresh bool) (string, error)

GetXaiAccessToken returns a usable xAI token, refreshing and persisting to the file the credential came from (xAI rotates refresh tokens).

func HandleVetLine added in v1.0.1

func HandleVetLine(line []byte) []byte

HandleVetLine answers one protocol line.

func HasStoredCredential added in v1.0.1

func HasStoredCredential(policy AccessPolicy) bool

HasStoredCredential is the offline probe (files, never the network) for the router's oauth-unless-explicit chain.

func I added in v1.0.1

func I(v int) *int

I returns a pointer to an int (Config{MaxTokens: lm15.I(100)}).

func IsKind added in v1.0.1

func IsKind(err error, kind ErrorKind) bool

IsKind reports whether err is an lm15 Error of class kind (or a subclass).

func IsMediaPart added in v1.0.1

func IsMediaPart(p Part) bool

IsMediaPart reports whether p carries bytes or an address rather than words.

func IsPinnedAuthFailure

func IsPinnedAuthFailure(providerCode, message string, reasons []string) bool

IsPinnedAuthFailure reports whether an error is one of the pinned MAP-18 forms: the code matches exactly, the message passes every text test, and the form's reason, when it names one, is among reasons.

func IsPinnedModelNotFound added in v1.0.1

func IsPinnedModelNotFound(providerCode, message string) bool

IsPinnedModelNotFound reports whether an error is one of the pinned MAP-15 forms: the code matches exactly and the message passes every test given.

func JoinEndpoint added in v1.0.1

func JoinEndpoint(endpoint, path, provider string) (string, error)

JoinEndpoint is an endpoint root (the caller's or the vendor variable's) joined with the door's path. The door's path is appended unless the endpoint already ends with it, or with a leading part of it: the console shows an account root (https://acct.services.ai.azure.com), Microsoft's own examples show …/anthropic and …/openai/v1, and all three must mean the same door. Stated trade-off: a gateway whose own path happens to end with a leading part of the door's path cannot be spelled; none is known.

func NamedMeaningFor added in v1.0.1

func NamedMeaningFor(policy AccessPolicy, name string) string

NamedMeaningFor is the sentence a name means on this door.

func NativeErrorKind added in v1.0.1

func NativeErrorKind(err error) string

NativeErrorKind returns the native exception name for malformed-input errors (TypeError, ValueError, KeyError), or "" for other errors.

func OpenAIChatModelString added in v1.0.1

func OpenAIChatModelString(model string) (string, error)

OpenAIChatModelString reads a model string written for the OpenAI SDK or litellm into lm15's form.

func OpenAIChatModelStringWith added in v1.0.1

func OpenAIChatModelStringWith(model string, providers []ProviderDefinition) (string, error)

OpenAIChatModelStringWith is OpenAIChatModelString that also reads a declared provider's id and aliases (RouterConfig.Providers) as a prefix.

func PKCEChallenge added in v1.0.1

func PKCEChallenge(verifier string) string

PKCEChallenge is the S256 challenge for a verifier.

func ParseRFC3339 added in v1.0.1

func ParseRFC3339(value string) (time.Time, error)

ParseRFC3339 reads "2026-09-03T12:00:00Z" (or an offset) into UTC.

func PiAgentAuthPath added in v1.0.1

func PiAgentAuthPath() string

func PollDeviceCode added in v1.0.1

func PollDeviceCode(ctx context.Context, poll func() (DevicePollResult, error), intervalS, expiresInS float64, provider string, waitBeforeFirst bool, sleep func(time.Duration), clock func() time.Time) (any, error)

PollDeviceCode runs the polling loop; sleep and clock are injectable.

func PresetBaseURL added in v1.0.1

func PresetBaseURL(table map[string]string, name, dialect, defaultPreset string) (string, error)

PresetBaseURL is the address a preset name supplies for one dialect. A name with no entry (other than the dialect's own default) is refused with NotConfiguredError: a request for a named server never goes to the cloud default with whatever key is around (2026-09-11).

func ProfileSettings added in v1.0.1

func ProfileSettings(policy AccessPolicy, ctx *ChainContext) func(string) (string, string)

ProfileSettings returns the setting values the cloud's own configuration carries, as (value, from) in the AUTH-10 vocabulary. AWS region: the active profile. Google project (amended 2026-09-26, the order google-auth and gcloud give it): the GOOGLE_APPLICATION_CREDENTIALS file's project_id (then quota_project_id); gcloud's active configuration; the ADC file's quota_project_id / project_id; the metadata server (online at construction; offline ("", "metadata") = unprobed). Nothing for Azure.

func ProviderIDs added in v1.0.1

func ProviderIDs() []string

ProviderIDs lists every provider id, sorted.

func ResolveChainNamed added in v1.0.1

func ResolveChainNamed(policy AccessPolicy, ctx *ChainContext, named string) (Credential, CredentialSource, error)

ResolveChainNamed walks the chain online; the first rung that yields wins, and the result names the rung (AUTH-1 provenance). A rung that is configured and fails raises. Azure developer commands are the AUTH-1 exception: try all three before reporting their failure. With named, only that name's rungs run and nothing else is tried.

func S added in v1.0.1

func S(v string) *string

S returns a pointer to a string.

func SelectScheme added in v1.0.1

func SelectScheme(policy AccessPolicy, credential Credential) (string, error)

SelectScheme picks the scheme this credential kind travels under.

func SigV4Sign added in v1.0.1

func SigV4Sign(method, rawURL string, headers map[string]string, payload []byte, creds AwsCredentials, region, service string, now time.Time) sigv4.Signature

SigV4Sign exposes the signer for the vet protocol and tests.

func SliceSeq added in v1.0.1

func SliceSeq(events []StreamEvent) iter.Seq2[StreamEvent, error]

SliceSeq turns a slice of events into a stream.

func StoredCredentialState added in v1.0.1

func StoredCredentialState(policy AccessPolicy) string

StoredCredentialState is "usable", "unusable", "logged_out" or "absent" for policy's stored login (AUTH-1 oauth-unless-explicit, R3). Files only.

func TruncateStreamAtStop added in v1.0.1

func TruncateStreamAtStop(events iter.Seq2[StreamEvent, error], stop []string) iter.Seq2[StreamEvent, error]

TruncateStreamAtStop applies a client-side stop to a canonical stream: text is cut at the first sequence, a synthesized end event (finish_reason "stop", no usage) follows, and the source is closed at the cut.

func UsableXaiCredential added in v1.0.1

func UsableXaiCredential(path string) bool

UsableXaiCredential reports a stored login that is fresh or refreshable. Files only; never the network (the oauth-unless-explicit probe).

func ValidateJSONValue added in v1.0.1

func ValidateJSONValue(v any) error

ValidateJSONValue reports whether v is made only of JSON containers and scalars: nil, bool, string, json.Number, Go integers, finite floats, JSONObjects with unique keys, and slices / string-keyed maps of those (reflectively, so []string and map[string]int are accepted; a map has no key order and is written sorted). Structs and other types are rejected.

func WriteClaudeCodeCredential added in v1.0.1

func WriteClaudeCodeCredential(ctx context.Context, cred LocalOAuthCredential, path string) error

WriteClaudeCodeCredential writes the credential under the file lock.

func WriteCodexCLICredential added in v1.0.1

func WriteCodexCLICredential(ctx context.Context, cred LocalOAuthCredential, path, idToken string) error

WriteCodexCLICredential writes the credential under the file lock.

func WriteXaiCredential added in v1.0.1

func WriteXaiCredential(ctx context.Context, cred LocalOAuthCredential, path string) error

WriteXaiCredential writes the credential into a store (default: lm15's own).

func XaiStoredState added in v1.0.1

func XaiStoredState(path string) string

XaiStoredState is the stored xAI subscription's state, offline (spec/auth.md AUTH-1, ratified R2/R3 2026-09-22): "usable" (fresh, or expired with a refresh token); "unusable" (expired, no refresh token); "logged_out" (lm15's non-secret sign-out marker); "absent" (nothing stored). "unusable" and "logged_out" BLOCK the environment key: a failed subscription is never silently replaced by a metered key.

Types

type APIKey added in v1.0.1

type APIKey struct{ Value string }

APIKey is an ordinary provider API key.

func (APIKey) GoString added in v1.0.1

func (APIKey) GoString() string

func (APIKey) IsExpired added in v1.0.1

func (APIKey) IsExpired(time.Time) bool

func (APIKey) Kind added in v1.0.1

func (APIKey) Kind() string

func (APIKey) String added in v1.0.1

func (APIKey) String() string

String redacts (AUTH-5).

func (APIKey) Validate added in v1.0.1

func (k APIKey) Validate() error

Validate checks the value shape.

type AccessPolicy added in v1.0.1

type AccessPolicy struct {
	Provider           string
	Supports           EndpointSupport
	AuthModes          []string
	EnterpriseVariants []string
	EnvKeys            []string
	CredentialPolicy   string   // "" reads as "key"
	AuthScheme         []string // nil reads as ["bearer"]
	Headers            [][2]string
	Host               *HostSpec
	LoginHint          string
	Backend            string // "" reads as "api"
	BackendOptions     map[string]string
	SystemPrefix       string
	BaseURL            string
	// BackendSettings are the BackendOptions a caller may set on a door
	// without a host (AUTH-10, amended 2026-09-30): each names a
	// BackendOptions key and the env variables the router consults for it;
	// its default is the table's BackendOptions value (Default stays "").
	// The subscription doors declare client_version.
	BackendSettings []HostSetting
}

AccessPolicy is how an adapter reaches a backend. Pure data (AUTH-10).

func (AccessPolicy) AuthHeader added in v1.0.1

func (p AccessPolicy) AuthHeader() string

AuthHeader is the first header-carrying scheme (bearer or x-api-key).

func (AccessPolicy) CloudChain added in v1.0.1

func (p AccessPolicy) CloudChain() bool

CloudChain reports whether the credential policy is a cloud chain.

func (AccessPolicy) EffectiveAuthScheme added in v1.0.1

func (p AccessPolicy) EffectiveAuthScheme() []string

EffectiveAuthScheme returns AuthScheme or ["bearer"].

func (AccessPolicy) EffectiveBackend added in v1.0.1

func (p AccessPolicy) EffectiveBackend() string

EffectiveBackend returns Backend or "api".

func (AccessPolicy) EffectiveCredentialPolicy added in v1.0.1

func (p AccessPolicy) EffectiveCredentialPolicy() string

EffectiveCredentialPolicy returns CredentialPolicy or "key".

func (AccessPolicy) Hosted added in v1.0.1

func (p AccessPolicy) Hosted() bool

Hosted reports whether the policy names a cloud host.

func (AccessPolicy) ResolveBackendSettings

func (p AccessPolicy) ResolveBackendSettings(given map[string]string, env func(string) string, sources map[string]string) (map[string]string, error)

ResolveBackendSettings is the door's backend settings (AUTH-10, amended 2026-09-30): the caller's value, then env (when non-nil — the router passes the environment, an adapter built by hand does not), then the table's BackendOptions value. sources, when non-nil, receives each origin (explicit, env:<VAR>, default). A name the door does not declare is a configuration error that lists the names it does: a setting nothing reads would otherwise be dropped with nothing said.

func (AccessPolicy) Validate added in v1.0.1

func (p AccessPolicy) Validate() error

Validate checks the policy invariants.

func (AccessPolicy) WithBackendOptions added in v1.0.1

func (p AccessPolicy) WithBackendOptions(options map[string]string) AccessPolicy

WithBackendOptions returns a copy with the options merged.

func (AccessPolicy) WithBackendSettings

func (p AccessPolicy) WithBackendSettings(values map[string]string) AccessPolicy

WithBackendSettings returns the policy with these resolved backend settings in BackendOptions. client_version on the claude-code backend is also the version the user-agent header claims (claude-cli/<client_version>); on chatgpt-codex it is the /models query parameter.

func (AccessPolicy) WithHeaders added in v1.0.1

func (p AccessPolicy) WithHeaders(headers [][2]string) AccessPolicy

WithHeaders returns a copy with these static headers replaced or appended (names compared case-insensitively).

type Adaptation added in v1.0.1

type Adaptation struct {
	Field   string
	Action  string
	Reason  string
	Asked   any
	Applied any
}

Adaptation is one thing the wire got that differs from what was asked.

  • Field: the config path ("config.seed", "config.temperature", "config.reasoning.summary", "config.tool_choice.allowed").
  • Action: dropped (a hint with no home), clamped (a dial to its nearest level), substituted (the closest spelling), client_side (lm15 does it after the wire), satisfied (the provider's default already is what was asked), defaulted (the wire requires a value the caller did not set).
  • Asked / Applied: what the caller set / what went to the wire (JSON values; nil = absent). Asked is absent for defaulted; Applied is absent for dropped and satisfied.
  • Reason: one sentence naming the provider fact; the adapter's own wording, never pinned by a case.

func AdaptationFromDict added in v1.0.1

func AdaptationFromDict(d JSONObject) (Adaptation, error)

AdaptationFromDict reads one record.

func (Adaptation) IsDeviation added in v1.0.1

func (a Adaptation) IsDeviation() bool

IsDeviation reports whether the action changes what the caller asked for (the actions "refuse" refuses).

func (Adaptation) MarshalJSON added in v1.0.1

func (a Adaptation) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Adaptation) UnmarshalJSON added in v1.0.1

func (a *Adaptation) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (Adaptation) Validate added in v1.0.1

func (a Adaptation) Validate() error

Validate checks the field constraints.

type AnthropicCompat added in v1.0.1

type AnthropicCompat struct {
	ThinkingFormat    string // auto | anthropic | deepseek | adaptive | effort
	ThinkingReplay    string // auto | signed | unsigned
	CacheControl      string // auto | anthropic | none
	StructuredOutput  string // auto | send | reject
	ParallelToolCalls string // auto | send | reject
	SamplingParams    string // auto | send | reject
	ToolResultMedia   string // auto | native | images | reject
	ReasoningEfforts  []string
	ModelPrefixes     []string
	Extensions        JSONObject
}

AnthropicCompat is a partial policy for Messages-family servers.

func AnthropicPreset added in v1.0.1

func AnthropicPreset(name string) (AnthropicCompat, error)

AnthropicPreset returns the named Anthropic preset.

type AnthropicLM

type AnthropicLM struct {
	// contains filtered or unexported fields
}

AnthropicLM is the Anthropic Messages dialect bound to an access policy. ClaudeCodeLM is the same type bound to lm15.ClaudeCode.

func NewAnthropicLM

func NewAnthropicLM(opts ...Option) (*AnthropicLM, error)

NewAnthropicLM constructs the Messages dialect (default policy AnthropicAPI).

func NewClaudeCodeLM added in v1.0.1

func NewClaudeCodeLM(opts ...Option) (*AnthropicLM, error)

NewClaudeCodeLM constructs the Messages dialect on a Claude Code login.

func (*AnthropicLM) Access added in v1.0.1

func (c *AnthropicLM) Access() AccessPolicy

Access returns the bound access policy.

func (*AnthropicLM) AccountID added in v1.0.1

func (c *AnthropicLM) AccountID() string

AccountID returns the account id the credential carries (Codex).

func (*AnthropicLM) Adaptations added in v1.0.1

func (c *AnthropicLM) Adaptations() string

Adaptations returns the MAP-13 policy ("note", "silent", "refuse").

func (*AnthropicLM) BaseURL added in v1.0.1

func (c *AnthropicLM) BaseURL() string

BaseURL returns the base URL.

func (*AnthropicLM) Batch added in v1.0.1

func (c *AnthropicLM) Batch(ctx context.Context, req *BatchRequest) (*BatchJob, error)

Batch submits and wraps the ticket in a handle.

func (*AnthropicLM) BatchCancel added in v1.0.1

func (c *AnthropicLM) BatchCancel(ctx context.Context, batchID string) (BatchJobInfo, error)

func (*AnthropicLM) BatchJob added in v1.0.1

func (c *AnthropicLM) BatchJob(ctx context.Context, batchID string) (*BatchJob, error)

BatchJob re-attaches to a job by id.

func (*AnthropicLM) BatchList added in v1.0.1

func (c *AnthropicLM) BatchList(ctx context.Context, limit int) ([]BatchJobInfo, error)

func (*AnthropicLM) BatchResults added in v1.0.1

func (c *AnthropicLM) BatchResults(ctx context.Context, batchID string) ([]BatchEntry, error)

func (*AnthropicLM) BatchStatus added in v1.0.1

func (c *AnthropicLM) BatchStatus(ctx context.Context, batchID string) (BatchJobInfo, error)

func (*AnthropicLM) BatchSubmit added in v1.0.1

func (c *AnthropicLM) BatchSubmit(ctx context.Context, req *BatchRequest) (BatchJobInfo, error)

func (*AnthropicLM) Batches added in v1.0.1

func (c *AnthropicLM) Batches(ctx context.Context, limit int) ([]*BatchJob, error)

Batches lists this credential's jobs as handles.

func (*AnthropicLM) Build added in v1.0.1

func (c *AnthropicLM) Build(req *Request, stream bool) (*TransportRequest, []Adaptation, error)

Build is BuildRequest with the MAP-13 record of what the build adapted.

func (*AnthropicLM) BuildRequest added in v1.0.1

func (c *AnthropicLM) BuildRequest(req *Request, stream bool) (*TransportRequest, error)

BuildRequest builds the wire request (pure apart from the credential call).

func (*AnthropicLM) Cache added in v1.0.1

func (c *AnthropicLM) Cache(ctx context.Context, prefix *Request, ttlSeconds *int, label string) (CachedPrefix, error)

Cache makes a prompt beginning reusable with the best tier the provider has.

func (*AnthropicLM) CacheCreate added in v1.0.1

func (c *AnthropicLM) CacheCreate(ctx context.Context, prefix *Request, ttlSeconds *int, label string) (CacheInfo, error)

func (*AnthropicLM) CacheDelete added in v1.0.1

func (c *AnthropicLM) CacheDelete(ctx context.Context, cacheID string) error

func (*AnthropicLM) CacheGet added in v1.0.1

func (c *AnthropicLM) CacheGet(ctx context.Context, cacheID string) (CacheInfo, error)

func (*AnthropicLM) CacheList added in v1.0.1

func (c *AnthropicLM) CacheList(ctx context.Context, limit int, cursor string) (CachePage, error)

func (*AnthropicLM) CacheUpdate added in v1.0.1

func (c *AnthropicLM) CacheUpdate(ctx context.Context, cacheID string, ttlSeconds int) (CacheInfo, error)

func (*AnthropicLM) Close added in v1.0.1

func (c *AnthropicLM) Close() error

Close releases the transport.

func (*AnthropicLM) Complete

func (c *AnthropicLM) Complete(ctx context.Context, req *Request) (*Response, error)

Complete performs one call.

func (*AnthropicLM) CredentialOrigin added in v1.0.1

func (c *AnthropicLM) CredentialOrigin() string

CredentialOrigin says where this adapter's credential comes from (AUTH-1 provenance): a label, never the value. For a cloud chain provider this is the rung that last won, or what will be walked when no request has been sent yet.

func (*AnthropicLM) CredentialSource added in v1.0.1

func (c *AnthropicLM) CredentialSource() *CredentialSource

CredentialSource is the provenance of a cloud chain credential after its first resolution (nil for a key, a stored login, or before any request).

func (*AnthropicLM) Endpoint added in v1.0.1

func (c *AnthropicLM) Endpoint() string

Endpoint is the endpoint root a cloud door was given ("" = the template).

func (*AnthropicLM) FileDelete added in v1.0.1

func (c *AnthropicLM) FileDelete(ctx context.Context, fileID string) error

func (*AnthropicLM) FileDownload added in v1.0.1

func (c *AnthropicLM) FileDownload(ctx context.Context, fileID string) ([]byte, error)

func (*AnthropicLM) FileGet added in v1.0.1

func (c *AnthropicLM) FileGet(ctx context.Context, fileID string) (FileInfo, error)

func (*AnthropicLM) FileList added in v1.0.1

func (c *AnthropicLM) FileList(ctx context.Context, limit int, cursor string) (FilePage, error)

func (*AnthropicLM) FileUpload added in v1.0.1

func (c *AnthropicLM) FileUpload(ctx context.Context, req *FileUploadRequest) (FileInfo, error)

func (*AnthropicLM) FileWaitReady added in v1.0.1

func (c *AnthropicLM) FileWaitReady(ctx context.Context, fileID string, pollEvery time.Duration) (FileInfo, error)

FileWaitReady polls until the file leaves pending (ctx bounds the wait).

func (*AnthropicLM) HostSettings added in v1.0.1

func (c *AnthropicLM) HostSettings() map[string]string

HostSettings returns the resolved host settings.

func (*AnthropicLM) ImageGenerate added in v1.0.1

func (c *AnthropicLM) ImageGenerate(ctx context.Context, req *ImageGenerationRequest) (ImageGenerationResponse, error)

func (*AnthropicLM) ListModels added in v1.0.1

func (c *AnthropicLM) ListModels(ctx context.Context) ([]ModelInfo, error)

ListModels fetches the models this credential can use.

func (*AnthropicLM) Live added in v1.0.1

func (c *AnthropicLM) Live(ctx context.Context, config *LiveConfig) (LiveSession, error)

Live opens a live session (dialects with the surface override live()).

func (*AnthropicLM) LiveDecode added in v1.0.1

func (c *AnthropicLM) LiveDecode(raw []byte) ([]LiveServerEvent, error)

func (*AnthropicLM) LiveEncoder added in v1.0.1

func (c *AnthropicLM) LiveEncoder(config *LiveConfig) func(LiveClientEvent) ([]JSONObject, error)

func (*AnthropicLM) LiveSetupFrames added in v1.0.1

func (c *AnthropicLM) LiveSetupFrames(config *LiveConfig) ([]JSONObject, error)

LiveSetupFrames / LiveEncoder / LiveDecode expose the pure live codec.

func (*AnthropicLM) NormalizeError added in v1.0.1

func (c *AnthropicLM) NormalizeError(status int, body string) *Error

NormalizeError maps an HTTP failure body to a typed error (dialects override).

func (*AnthropicLM) ParseResponse added in v1.0.1

func (c *AnthropicLM) ParseResponse(req *Request, resp *HTTPResponse) (*Response, error)

ParseResponse parses a complete body.

func (*AnthropicLM) ParseStreamEvents added in v1.0.1

func (c *AnthropicLM) ParseStreamEvents(req *Request, event sse.Event) ([]StreamEvent, error)

ParseStreamEvents parses one SSE event into canonical events.

func (*AnthropicLM) Plan added in v1.0.1

func (c *AnthropicLM) Plan(req *Request) ([]Adaptation, error)

Plan is what a call with this request WOULD adapt, with no network and no credential invoked (offline, like Resolve). It returns the refusal the call would return (under any policy, or every deviation under "refuse") and the FULL record under every policy, "silent" included: a preview that hid what it saw would be no preview.

func (*AnthropicLM) Provider

func (c *AnthropicLM) Provider() string

Provider returns the canonical provider string.

func (*AnthropicLM) RequestFromOpenAIChat added in v1.0.1

func (c *AnthropicLM) RequestFromOpenAIChat(body JSONObject) (*Request, error)

RequestFromOpenAIChat is MAP-12 (chat dialect only).

func (*AnthropicLM) ResponseFromOpenAIChat added in v1.0.1

func (c *AnthropicLM) ResponseFromOpenAIChat(body JSONObject, model string, choice *int, responseFormat JSONObject) (*Response, error)

ResponseFromOpenAIChat is MAP-12 rule 9 (chat dialect only).

func (*AnthropicLM) SetCredentialOrigin added in v1.0.1

func (c *AnthropicLM) SetCredentialOrigin(label string)

SetCredentialOrigin names the credential's source when the constructor could not know it (the router: an env variable, a placeholder key).

func (*AnthropicLM) SpeechGenerate added in v1.0.1

func (c *AnthropicLM) SpeechGenerate(ctx context.Context, req *SpeechGenerationRequest) (SpeechGenerationResponse, error)

func (*AnthropicLM) Stream

func (c *AnthropicLM) Stream(ctx context.Context, req *Request) iter.Seq2[StreamEvent, error]

Stream yields canonical events: exactly one start, deltas, exactly one final end (MAP-3 / MAP-4 via the coalescer).

func (*AnthropicLM) Supports added in v1.0.1

func (c *AnthropicLM) Supports() EndpointSupport

Supports returns the surfaces this access path carries.

func (*AnthropicLM) VideoGenerate added in v1.0.1

func (c *AnthropicLM) VideoGenerate(ctx context.Context, req *VideoGenerationRequest) (*VideoJob, error)

func (*AnthropicLM) VideoJob added in v1.0.1

func (c *AnthropicLM) VideoJob(ctx context.Context, videoID string) (*VideoJob, error)

func (*AnthropicLM) VideoJobs added in v1.0.1

func (c *AnthropicLM) VideoJobs(ctx context.Context, limit int, model string) ([]*VideoJob, error)

func (*AnthropicLM) VideoList added in v1.0.1

func (c *AnthropicLM) VideoList(ctx context.Context, limit int, model string) ([]VideoJobInfo, error)

func (*AnthropicLM) VideoResult added in v1.0.1

func (c *AnthropicLM) VideoResult(ctx context.Context, videoID string) (VideoPart, error)

func (*AnthropicLM) VideoStatus added in v1.0.1

func (c *AnthropicLM) VideoStatus(ctx context.Context, videoID string) (VideoJobInfo, error)

func (*AnthropicLM) VideoSubmit added in v1.0.1

func (c *AnthropicLM) VideoSubmit(ctx context.Context, req *VideoGenerationRequest) (VideoJobInfo, error)

type AudioDelta

type AudioDelta struct {
	Data      *string
	URL       *string
	FileID    *string
	PartIndex int
	MediaType string
}

AudioDelta is a partial audio chunk. Data may be unaligned base64; an empty string is data (emitted), nil is absent.

func (AudioDelta) MarshalJSON

func (d AudioDelta) MarshalJSON() ([]byte, error)

func (AudioDelta) Type added in v1.0.1

func (AudioDelta) Type() string

func (AudioDelta) Validate added in v1.0.1

func (d AudioDelta) Validate() error

type AudioFormat

type AudioFormat struct {
	Encoding   string
	SampleRate int
	Channels   int
}

AudioFormat describes a live audio stream. Channels 0 reads as 1.

func AudioFormatFromDict added in v1.0.1

func AudioFormatFromDict(d JSONObject) (AudioFormat, error)

AudioFormatFromDict reads an audio format (channels defaults to 1).

func (AudioFormat) EffectiveChannels added in v1.0.1

func (a AudioFormat) EffectiveChannels() int

EffectiveChannels returns Channels or 1.

func (AudioFormat) Validate added in v1.0.1

func (a AudioFormat) Validate() error

Validate checks the format.

type AudioPart

type AudioPart struct{ Media }

AudioPart is audio content.

func Audio added in v1.0.1

func Audio(opts ...MediaOption) AudioPart

Audio creates an audio part (default media type audio/wav).

func (AudioPart) ContinuationStates added in v1.0.1

func (p AudioPart) ContinuationStates() []ContinuationState

func (AudioPart) MarshalJSON

func (p AudioPart) MarshalJSON() ([]byte, error)

func (AudioPart) Type added in v1.0.1

func (AudioPart) Type() string

func (AudioPart) Validate added in v1.0.1

func (p AudioPart) Validate() error

Validate implements Part.

func (AudioPart) WithContinuation added in v1.0.1

func (p AudioPart) WithContinuation(c []ContinuationState) Part

type Auth

type Auth struct {
	// contains filtered or unexported fields
}

Auth is one scope's connections and their lifecycle (spec/auth-managed.md AUTH-14 construction is inert, AUTH-17 what each operation may touch, AUTH-19 generations, replacement, logout and cancellation ordered against commit, AUTH-20 renewal under the lock with a durable in-flight marker and uncertainty never retried blind, AUTH-24 typed outcomes).

Port of lm15-python lm15/login/manager.py, graded by the same runs (lm15-contract harness/managed.py). A slot per provider route carries an identity generation (bumped on every new connection and on logout, never reused) and a credential revision (bumped on every renewal). A bound client pins (connection id, generation); a managed router reads the slot per request. A legacy entry (no slot record) reads as generation 1 with id legacy-<provider>, rewritten only by a managed commit.

func LocalAuth

func LocalAuth(path string) (*Auth, error)

LocalAuth is the private file ($LM15_CREDENTIALS_PATH or ~/.config/lm15/credentials.json, or path).

func MemoryAuth

func MemoryAuth() *Auth

MemoryAuth keeps everything in this process.

func NewAuth

func NewAuth(store Store) *Auth

NewAuth is a manager over store. Construction reads nothing (AUTH-14).

func NewAuthWithSeams

func NewAuthWithSeams(store Store, seams AuthSeams) *Auth

NewAuthWithSeams is NewAuth with injected clocks, transport and environment.

func (*Auth) CancelLogin

func (a *Auth) CancelLogin(ctx context.Context, provider string) (string, error)

CancelLogin durably cancels the slot's active attempt: "cancelled", "complete" when a commit already won (undo is Logout), or "none".

func (*Auth) Close

func (a *Auth) Close()

Close cancels logins this manager is running; never a logout.

func (*Auth) Configure

func (a *Auth) Configure(ctx context.Context, provider, method string, answers, settings map[string]string, replace string) (Connection, error)

Configure saves a recipe connection: env, external:<source>, cloud, local or api_key. No credential is acquired and nothing is verified.

func (*Auth) Connections

func (a *Auth) Connections() ([]Connection, error)

Connections lists the saved connections.

func (*Auth) Descriptor

func (a *Auth) Descriptor(provider string) (ProviderDescriptor, error)

Descriptor is one provider's AUTH-13 descriptor.

func (*Auth) Login

func (a *Auth) Login(ctx context.Context, provider string, opts LoginOptions) (Connection, error)

Login runs one login to completion and saves the connection; it is saved before Login returns. Cancelling ctx (or CancelLogin) returns ErrLoginCancelled.

func (*Auth) Logout

func (a *Auth) Logout(ctx context.Context, providerOrConnection string) (ForgetResult, error)

Logout forgets the connection locally: material removed, generation bumped, pending attempt cancelled, a marker kept so a restart cannot fall back to an ambient key (R3). Never calls a provider's revoke endpoint; never touches another tool's file.

func (*Auth) Methods

func (a *Auth) Methods(provider string) ([]LoginMethod, error)

Methods lists how a provider can be connected.

func (*Auth) Providers

func (a *Auth) Providers() []ProviderDescriptor

Providers is every provider this manager can connect.

func (*Auth) RequestAuth

func (a *Auth) RequestAuth(ctx context.Context, provider string, pinned *[2]string) (RequestAuth, error)

RequestAuth is what a request on provider sends now: the saved connection's credential, renewed under the lock if due. A pinned view (WithPin) or pinned checks the selection: a mismatch is connection_changed, never a silent rebind (AUTH-20.1).

func (*Auth) Selection

func (a *Auth) Selection(provider string) (Connection, RequestAuth, error)

Selection is the saved connection's non-secret request shape, read without renewal (a router's LM): the selection checks, then the base URL, headers, account id or named identity.

func (*Auth) SetAPIKey

func (a *Auth) SetAPIKey(ctx context.Context, provider, key, replace string) (Connection, error)

SetAPIKey saves a literal key (no interpolation, no verification).

func (*Auth) Status

func (a *Auth) Status(provider string) (ConnectionStatus, error)

Status is presence, usability and last verification of a provider's slot (AUTH-24).

func (*Auth) Store

func (a *Auth) Store() Store

Store is where this scope's connections are saved.

func (*Auth) String

func (a *Auth) String() string

String never renders contents.

func (*Auth) Verify

func (a *Auth) Verify(ctx context.Context, provider string) (Verification, error)

Verify is an explicit, non-inference check: resolve (renewing if due) and list models on the route. Not universal; possibly metered by the provider.

func (*Auth) WithPin

func (a *Auth) WithPin(connectionID, generation string) *Auth

WithPin is the same scope with every request-time resolution checked against one (connection id, identity generation) — a bound client's (AUTH-20.1).

type AuthFailedForm

type AuthFailedForm struct {
	Code, Reason, Prefix, Contains, Suffix string
}

AuthFailedForm is one pinned MAP-18 form of a provider's "this key is not valid" answer that arrives without HTTP 401: an exact provider code, an optional Google google.rpc.ErrorInfo reason, and the text tests the message must pass.

type AuthReport added in v1.0.1

type AuthReport struct {
	Provider   string
	Steps      []AuthStep
	Configured bool
	Settings   [][2]string
	// Named is the AUTH-1 named credential the config pins, and
	// NamedMeaning what it means on this cloud; the steps are then only the
	// rungs it covers.
	Named        string
	NamedMeaning string
	// BaseURL is the address a cloud door will send to, and BaseURLSource
	// where it came from ("base_urls", "env $VAR", or "template").
	BaseURL       string
	BaseURLSource string
	// SettingSources says where each setting came from (AUTH-10 "from",
	// amended 2026-09-26): explicit, env:<VAR>, adc-env, gcloud-config,
	// adc-file, metadata, aws-profile, default; unprobed:metadata when only
	// the metadata server could answer; missing.
	SettingSources [][2]string
}

AuthReport is the full answer for one provider.

func ExplainAuth added in v1.0.1

func ExplainAuth(provider string, opts ExplainOptions) (AuthReport, error)

ExplainAuth walks the AUTH-1 chain for a provider and reports every rung.

func (AuthReport) Describe added in v1.0.1

func (r AuthReport) Describe() string

Describe renders the report (no secrets by construction).

func (AuthReport) Selected added in v1.0.1

func (r AuthReport) Selected() (AuthStep, bool)

Selected returns the winning step.

func (AuthReport) String added in v1.0.1

func (r AuthReport) String() string

type AuthSeams

type AuthSeams struct {
	WallClock func() int64   // epoch milliseconds
	Monotonic func() float64 // milliseconds
	Sleep     func(context.Context, time.Duration) error
	Transport Transport
	Env       func(string) string // the environment $VAR recipes read; default os.Getenv
	Home      string              // where other tools' logins live; default $HOME
}

AuthSeams are what tests and the vet shim inject; production leaves them zero.

type AuthStep added in v1.0.1

type AuthStep struct {
	Kind   string // api_keys | env:<VAR> | placeholder | oauth-file | the cloud rung names
	Source string
	Detail string
	State  string // selected | shadowed | absent | unprobed
}

AuthStep is one rung of the credential chain.

func (AuthStep) Describe added in v1.0.1

func (s AuthStep) Describe() string

Describe renders the rung.

type AuthUI

type AuthUI interface {
	Prompt(ctx context.Context, p Prompt) (string, error)
	Notify(n Notice)
}

AuthUI is what an application supplies so a login can talk to a person. Prompt returns the answer (a select answers the option id) and must return promptly with ctx.Err() or ErrPromptCancelled once ctx is done. A UI never opens anything unless that is the application's own choice.

type AwsCredentials added in v1.0.1

type AwsCredentials struct {
	AccessKeyID     string
	SecretAccessKey string
	SessionToken    string
	ExpiresAt       *time.Time
}

AwsCredentials sign requests with SigV4.

func (AwsCredentials) GoString added in v1.0.1

func (a AwsCredentials) GoString() string

func (AwsCredentials) IsExpired added in v1.0.1

func (a AwsCredentials) IsExpired(now time.Time) bool

func (AwsCredentials) Kind added in v1.0.1

func (AwsCredentials) Kind() string

func (AwsCredentials) String added in v1.0.1

func (a AwsCredentials) String() string

func (AwsCredentials) Validate added in v1.0.1

func (a AwsCredentials) Validate() error

type BatchEntry added in v1.0.1

type BatchEntry struct {
	Index    int
	Outcome  string
	Response *Response
	Error    *ErrorDetail
}

BatchEntry is the fate of one request, in submission order.

func BatchEntryFromDict added in v1.0.1

func BatchEntryFromDict(d JSONObject) (BatchEntry, error)

BatchEntryFromDict reads a batch entry.

func (BatchEntry) OK added in v1.0.1

func (e BatchEntry) OK() bool

OK reports outcome == succeeded.

func (BatchEntry) Validate added in v1.0.1

func (e BatchEntry) Validate() error

Validate checks the outcome/payload pairing.

type BatchJob added in v1.0.1

type BatchJob struct {
	// contains filtered or unexported fields
}

BatchJob is a live handle on one provider-side batch job.

func (*BatchJob) Cancel added in v1.0.1

func (j *BatchJob) Cancel(ctx context.Context) (*BatchJob, error)

Cancel requests cancellation.

func (*BatchJob) Done added in v1.0.1

func (j *BatchJob) Done() bool

Done reports a terminal status.

func (*BatchJob) ID added in v1.0.1

func (j *BatchJob) ID() string

ID is the ticket.

func (*BatchJob) Info added in v1.0.1

func (j *BatchJob) Info() BatchJobInfo

Info is the snapshot from the last provider contact.

func (*BatchJob) Refresh added in v1.0.1

func (j *BatchJob) Refresh(ctx context.Context) (*BatchJob, error)

Refresh re-reads the job.

func (*BatchJob) Results added in v1.0.1

func (j *BatchJob) Results(ctx context.Context) ([]BatchEntry, error)

Results returns the entries in submission order.

func (*BatchJob) Status added in v1.0.1

func (j *BatchJob) Status() string

Status is the last known status.

func (*BatchJob) Wait added in v1.0.1

func (j *BatchJob) Wait(ctx context.Context, pollEvery time.Duration) (*BatchJob, error)

Wait polls until the job is terminal; the context bounds the wait (context.DeadlineExceeded past its deadline).

type BatchJobInfo added in v1.0.1

type BatchJobInfo struct {
	ID           string
	Status       string
	Label        string
	CreatedAt    string
	ProviderData JSONObject
}

BatchJobInfo is the ticket: a snapshot of one provider-side job.

func BatchJobFromDict added in v1.0.1

func BatchJobFromDict(d JSONObject) (BatchJobInfo, error)

BatchJobFromDict reads a batch job snapshot.

func (BatchJobInfo) Done added in v1.0.1

func (j BatchJobInfo) Done() bool

Done reports a terminal status.

func (BatchJobInfo) Validate added in v1.0.1

func (j BatchJobInfo) Validate() error

Validate checks the snapshot.

type BatchRequest

type BatchRequest struct {
	Model      string
	Requests   []*Request
	Label      string
	Extensions JSONObject
}

BatchRequest is a batch of requests. Model "" infers from Requests[0].

func BatchRequestFromDict added in v1.0.1

func BatchRequestFromDict(d JSONObject) (BatchRequest, error)

BatchRequestFromDict reads a batch request.

func (BatchRequest) EffectiveModel added in v1.0.1

func (b BatchRequest) EffectiveModel() string

EffectiveModel returns Model or the first request's model (INV-032).

func (BatchRequest) Validate added in v1.0.1

func (b BatchRequest) Validate() error

Validate checks the batch.

type BearerToken added in v1.0.1

type BearerToken struct {
	Value     string
	ExpiresAt *time.Time
}

BearerToken is an OAuth / Entra access token with an optional expiry.

func (BearerToken) GoString added in v1.0.1

func (b BearerToken) GoString() string

func (BearerToken) IsExpired added in v1.0.1

func (b BearerToken) IsExpired(now time.Time) bool

func (BearerToken) Kind added in v1.0.1

func (BearerToken) Kind() string

func (BearerToken) String added in v1.0.1

func (b BearerToken) String() string

func (BearerToken) Validate added in v1.0.1

func (b BearerToken) Validate() error

type BinaryPart

type BinaryPart struct{ Media }

BinaryPart is arbitrary bytes.

func Binary added in v1.0.1

func Binary(opts ...MediaOption) BinaryPart

Binary creates a binary part (default media type application/octet-stream).

func (BinaryPart) ContinuationStates added in v1.0.1

func (p BinaryPart) ContinuationStates() []ContinuationState

func (BinaryPart) MarshalJSON

func (p BinaryPart) MarshalJSON() ([]byte, error)

func (BinaryPart) Type added in v1.0.1

func (BinaryPart) Type() string

func (BinaryPart) Validate added in v1.0.1

func (p BinaryPart) Validate() error

Validate implements Part.

func (BinaryPart) WithContinuation added in v1.0.1

func (p BinaryPart) WithContinuation(c []ContinuationState) Part

type BoundClient

type BoundClient struct {
	Auth      *Auth
	Selection ModelSelection
	// contains filtered or unexported fields
}

BoundClient is one connection, one model; canonical requests and responses.

func Connect

func Connect(ctx context.Context, opts ConnectOptions) (*BoundClient, error)

Connect gets ready to make model requests: it returns a client pinned to a connection and a model the person chose.

func NewBoundClient

func NewBoundClient(auth *Auth, selection ModelSelection, config RouterConfig) (*BoundClient, error)

NewBoundClient pins auth to selection (config.Auth must be nil or auth).

func (*BoundClient) Ask

func (b *BoundClient) Ask(ctx context.Context, text string) (*Response, error)

Ask completes one user message.

func (*BoundClient) Close

func (b *BoundClient) Close() error

Close releases this client's transport. Not a logout.

func (*BoundClient) Complete

func (b *BoundClient) Complete(ctx context.Context, req *Request) (*Response, error)

Complete sends an ordinary canonical Request (its model must be this client's).

func (*BoundClient) Routed

func (b *BoundClient) Routed() string

Routed is "provider:model".

func (*BoundClient) Stream

func (b *BoundClient) Stream(ctx context.Context, req *Request) iter.Seq2[StreamEvent, error]

Stream streams an ordinary canonical Request.

func (*BoundClient) String

func (b *BoundClient) String() string

String never renders a secret.

type BuiltinTool

type BuiltinTool struct {
	Name   string
	Config JSONObject
}

BuiltinTool is a provider-native tool (web_search, code_execution, ...).

func (BuiltinTool) MarshalJSON

func (t BuiltinTool) MarshalJSON() ([]byte, error)

func (BuiltinTool) ToolName

func (t BuiltinTool) ToolName() string

func (BuiltinTool) Validate added in v1.0.1

func (t BuiltinTool) Validate() error

Validate implements Tool.

type CacheConfig

type CacheConfig struct {
	Mode             string
	Retention        string
	Key              string
	PrefixUntilIndex *int
	Prefix           string
	Resource         string
}

CacheConfig names caching INTENTS (MAP-6). Mode "" reads as "auto".

func CacheConfigFromDict added in v1.0.1

func CacheConfigFromDict(d JSONObject) (CacheConfig, error)

CacheConfigFromDict reads a cache config.

func (CacheConfig) EffectiveMode added in v1.0.1

func (c CacheConfig) EffectiveMode() string

EffectiveMode returns Mode, or "auto" when unset.

func (CacheConfig) MarshalJSON added in v1.0.1

func (c CacheConfig) MarshalJSON() ([]byte, error)

func (CacheConfig) Validate added in v1.0.1

func (c CacheConfig) Validate() error

Validate checks INV-027.

type CacheInfo added in v1.0.1

type CacheInfo struct {
	ID           string
	Model        string
	Tokens       *int
	CreatedAt    string
	ExpiresAt    string
	Label        string
	ProviderData JSONObject
}

CacheInfo is a snapshot of one stored cache object (MAP-6 resource tier).

func CacheInfoFromDict added in v1.0.1

func CacheInfoFromDict(d JSONObject) (CacheInfo, error)

CacheInfoFromDict reads a cache snapshot.

func (CacheInfo) Validate added in v1.0.1

func (c CacheInfo) Validate() error

Validate checks the snapshot.

type CachePage added in v1.0.1

type CachePage struct {
	Items      []CacheInfo
	NextCursor string
}

CachePage is one page of cache objects.

func CachePageFromDict added in v1.0.1

func CachePageFromDict(d JSONObject) (CachePage, error)

CachePageFromDict reads a cache page.

func (CachePage) Validate added in v1.0.1

func (p CachePage) Validate() error

Validate checks every item.

type CachedPrefix added in v1.0.1

type CachedPrefix struct {
	Prefix   *Request
	Resource *CacheInfo
	// Provider (optional) is the router destination the prefix was cached
	// through (LMRouter.Cache sets it; router-local names included). Prefix
	// and Resource models stay wire names; Request emits "provider:model".
	// It carries no credential, endpoint or provider declaration: reuse it
	// with the same router configuration.
	Provider string
}

CachedPrefix is a reusable prompt beginning: the prefix Request and, on providers with the resource tier, the stored object.

func CachedPrefixFromDict added in v1.0.1

func CachedPrefixFromDict(d JSONObject) (CachedPrefix, error)

CachedPrefixFromDict reads a cached prefix.

func (CachedPrefix) CacheConfigFor added in v1.0.1

func (c CachedPrefix) CacheConfigFor() CacheConfig

CacheConfigFor marks the seam between prefix and suffix.

func (CachedPrefix) ExpiresAt added in v1.0.1

func (c CachedPrefix) ExpiresAt() string

ExpiresAt is the resource expiry, or "".

func (CachedPrefix) ID added in v1.0.1

func (c CachedPrefix) ID() string

ID is the resource id, or "".

func (CachedPrefix) Request added in v1.0.1

func (c CachedPrefix) Request(messages []Message, config *Config) (*Request, error)

Request appends messages to the prefix and sets the cache boundary. config supplies generation settings; its Cache must be unset.

func (CachedPrefix) RequestFrom added in v1.0.1

func (c CachedPrefix) RequestFrom(suffix *Request, config *Config) (*Request, error)

RequestFrom appends a suffix Request (same model, no system, no tools).

func (CachedPrefix) Validate added in v1.0.1

func (c CachedPrefix) Validate() error

Validate checks the prefix carries a default Config and the resource matches.

type ChainContext added in v1.0.1

type ChainContext struct {
	Env      map[string]string
	Home     string
	Files    map[string]string
	HTTP     HTTPFunc
	Run      RunFunc
	Now      func() time.Time
	Settings map[string]string
}

ChainContext is everything a chain touches, injectable. HTTP / Run nil = offline (the doctor). Files overrides the filesystem (the harness).

func OnlineChainContext added in v1.0.1

func OnlineChainContext(env map[string]string) *ChainContext

OnlineChainContext builds a context over the real environment and network.

type ChainStep added in v1.0.1

type ChainStep struct {
	Kind   string
	Source string
	Detail string
	State  string
}

ChainStep is the doctor's view of one rung.

func ExplainChain added in v1.0.1

func ExplainChain(policy AccessPolicy, ctx *ChainContext, explicit bool) ([]ChainStep, bool, error)

ExplainChain is the AUTH-7 walk over a cloud chain (offline).

func ExplainChainNamed added in v1.0.1

func ExplainChainNamed(policy AccessPolicy, ctx *ChainContext, explicit bool, named string) ([]ChainStep, bool, error)

ExplainChainNamed is ExplainChain under a named credential: only the rungs the name covers are walked (the rest are not steps at all: a named credential never falls through).

type ChoiceOption added in v1.0.1

type ChoiceOption struct {
	Key         string
	Description string
}

ChoiceOption is one option of a Choice judgment.

func Options added in v1.0.1

func Options(keys ...string) []ChoiceOption

Options builds ChoiceOptions from bare keys.

type CitationDelta

type CitationDelta struct {
	Text      *string
	URL       *string
	Title     *string
	PartIndex int
}

CitationDelta is a citation fragment.

func (CitationDelta) MarshalJSON

func (d CitationDelta) MarshalJSON() ([]byte, error)

func (CitationDelta) Type added in v1.0.1

func (CitationDelta) Type() string

func (CitationDelta) Validate added in v1.0.1

func (d CitationDelta) Validate() error

type CitationPart

type CitationPart struct {
	URL          string
	Title        string
	Text         string
	Continuation []ContinuationState
}

CitationPart references source material.

func Citation added in v1.0.1

func Citation(url, title, text string) CitationPart

Citation creates a citation part.

func (CitationPart) ContinuationStates added in v1.0.1

func (p CitationPart) ContinuationStates() []ContinuationState

func (CitationPart) MarshalJSON

func (p CitationPart) MarshalJSON() ([]byte, error)

func (CitationPart) Type added in v1.0.1

func (CitationPart) Type() string

func (CitationPart) Validate added in v1.0.1

func (p CitationPart) Validate() error

Validate implements Part (INV-017).

func (CitationPart) WithContinuation added in v1.0.1

func (p CitationPart) WithContinuation(c []ContinuationState) Part

type ClaudeCodeLM added in v1.0.1

type ClaudeCodeLM = AnthropicLM

ClaudeCodeLM is a name: AnthropicLM bound to lm15.ClaudeCode.

type Config

type Config struct {
	MaxTokens      *int
	Temperature    *float64
	TopP           *float64
	TopK           *int
	Stop           []string
	ResponseFormat JSONObject
	ToolChoice     *ToolChoice
	Reasoning      *Reasoning
	Cache          *CacheConfig
	ServiceTier    string
	UserID         string
	Store          *bool
	Logprobs       *int
	// Sampling knobs promoted from extensions 2026-09-14 (MAP-13 audit):
	// OpenAI (both dialects), Gemini and every OpenAI-compatible server
	// carry them; a wire without them (Anthropic) drops and records.
	Seed             *int
	FrequencyPenalty *float64
	PresencePenalty  *float64
	// Probabilities asks for a distribution over the keys the json_schema
	// declares (MAP-14). "" = off. "if_available": a wire that cannot
	// measure one records dropped; "required": it refuses before the wire.
	Probabilities string
	Extensions    JSONObject
}

Config holds generation parameters. Universal fields are typed; provider-specific settings go in Extensions.

func ConfigFromDict added in v1.0.1

func ConfigFromDict(d JSONObject) (Config, error)

ConfigFromDict reads a config (INV-042: malformed nests are errors).

func (Config) IsDefault added in v1.0.1

func (c Config) IsDefault() bool

IsDefault reports whether every field is unset (serializes to {}).

func (Config) MarshalJSON

func (c Config) MarshalJSON() ([]byte, error)

func (*Config) UnmarshalJSON

func (c *Config) UnmarshalJSON(b []byte) error

func (Config) Validate added in v1.0.1

func (c Config) Validate() error

Validate checks the field constraints and INV-050.

type ConnectOptions

type ConnectOptions struct {
	Provider        string // skip the provider picker
	Model           string // skip the model picker
	Auth            *Auth  // default LocalAuth("")
	UI              AuthUI // default a terminal UI when stdin and stderr are terminals
	Capability      string // reasoning | vision | structured-output
	OpenBrowser     bool   // terminal UI only
	RouterConfig    RouterConfig
	AllowUnverified bool
}

ConnectOptions configures Connect.

type Connection

type Connection struct {
	ID                 string
	Provider           string
	InstanceID         string
	Kind               string
	MethodID           string
	Routes             []string
	Label              string
	CreatedAt          string
	IdentityGeneration string
	CredentialRevision string
	Settings           map[string]string
	AccountLabel       string // untrusted display text (AUTH-12); never proof of identity
}

Connection is secret-free metadata for one saved credential in a scope.

type ConnectionStatus

type ConnectionStatus struct {
	Provider     string
	Presence     string // saved | absent
	Usability    string // ready | renewal_due | needs_login | indeterminate | unknown
	Connection   *Connection
	ExpiresAt    string // RFC 3339, "never", "unknown", or "" when nothing expires
	LoggedOut    bool
	Verification *Verification
	Detail       string
}

ConnectionStatus (AUTH-24): presence, usability and last verification are separate.

func (ConnectionStatus) Ready

func (s ConnectionStatus) Ready() bool

Ready reports usability ready or renewal_due.

type ContinuationDelta

type ContinuationDelta struct {
	Provider  string
	Kind      string
	Data      JSONObject
	PartIndex *int
}

ContinuationDelta is opaque replay state. PartIndex nil attaches to the message; an int attaches to that completed part.

func (ContinuationDelta) MarshalJSON

func (d ContinuationDelta) MarshalJSON() ([]byte, error)

func (ContinuationDelta) ToState

ToState converts the delta to its ContinuationState.

func (ContinuationDelta) Type added in v1.0.1

func (ContinuationDelta) Type() string

func (ContinuationDelta) Validate added in v1.0.1

func (d ContinuationDelta) Validate() error

type ContinuationState

type ContinuationState struct {
	Provider string
	Kind     string
	Data     JSONObject
}

ContinuationState is opaque provider-owned state needed to continue or replay a transcript. Provider is the dialect id (openai, anthropic, gemini, xai), never the access door (MAP-7.8).

func ContinuationFromDict added in v1.0.1

func ContinuationFromDict(d JSONObject) (ContinuationState, error)

ContinuationFromDict reads a state.

func (ContinuationState) MarshalJSON

func (s ContinuationState) MarshalJSON() ([]byte, error)

func (*ContinuationState) UnmarshalJSON

func (s *ContinuationState) UnmarshalJSON(b []byte) error

func (ContinuationState) Validate added in v1.0.1

func (s ContinuationState) Validate() error

Validate checks the state.

type Credential added in v1.0.1

type Credential interface {
	Kind() string
	IsExpired(now time.Time) bool
	// contains filtered or unexported methods
}

Credential is one of APIKey, BearerToken, AwsCredentials.

func CredentialFromDict added in v1.0.1

func CredentialFromDict(d JSONObject) (Credential, error)

CredentialFromDict reads the canonical JSON form.

func ResolveChain added in v1.0.1

func ResolveChain(policy AccessPolicy, ctx *ChainContext) (Credential, error)

ResolveChain walks the chain online; the first rung that yields wins.

func TokenExchangeParse added in v1.0.1

func TokenExchangeParse(policy AccessPolicy, rung string, status int, body JSONObject, ctx *ChainContext) (Credential, error)

TokenExchangeParse is the credential a rung produces from a pinned body.

type CredentialFileStore added in v1.0.1

type CredentialFileStore struct{ Path string }

CredentialFileStore is a locked, atomic, private credential file keyed by provider id: {"<provider>": {...}}.

func NewCredentialFileStore added in v1.0.1

func NewCredentialFileStore(path string) *CredentialFileStore

NewCredentialFileStore opens a store ("" = the default path).

func (*CredentialFileStore) Delete added in v1.0.1

func (s *CredentialFileStore) Delete(ctx context.Context, provider string) error

Delete removes one provider's credential.

func (*CredentialFileStore) List added in v1.0.1

func (s *CredentialFileStore) List() ([]string, error)

List returns the provider ids with stored credentials.

func (*CredentialFileStore) Mutate added in v1.0.1

func (s *CredentialFileStore) Mutate(ctx context.Context, provider string, fn func(current JSONObject) (JSONObject, error)) (JSONObject, error)

Mutate is the serialized read-modify-write; fn returns nil to leave the entry unchanged. Returns the post-write credential.

func (*CredentialFileStore) Read added in v1.0.1

func (s *CredentialFileStore) Read(provider string) (JSONObject, error)

Read returns the stored credential for provider, or nil.

func (*CredentialFileStore) String added in v1.0.1

func (s *CredentialFileStore) String() string

String never shows contents.

func (*CredentialFileStore) Write added in v1.0.1

func (s *CredentialFileStore) Write(ctx context.Context, provider string, credential JSONObject) error

Write replaces one provider's credential.

type CredentialFunc added in v1.0.1

type CredentialFunc func(ctx context.Context) (Credential, error)

CredentialFunc adapts a function to CredentialProvider.

func (CredentialFunc) Credential added in v1.0.1

func (f CredentialFunc) Credential(ctx context.Context) (Credential, error)

Credential implements CredentialProvider.

type CredentialLike added in v1.0.1

type CredentialLike = any

CredentialLike is what every api_key= argument accepts: a string (the APIKey shorthand), a Credential value, or a CredentialProvider.

type CredentialProvider added in v1.0.1

type CredentialProvider interface {
	Credential(ctx context.Context) (Credential, error)
}

CredentialProvider supplies a credential per request (AUTH-2). The adapter invokes it at request-build time and never caches the result; caching and refreshing belong to the provider itself.

func CredentialProviderFor added in v1.0.1

func CredentialProviderFor(policy AccessPolicy, ctx *ChainContext) CredentialProvider

CredentialProviderFor is the AUTH-2 provider over a cloud chain with the AUTH-3 in-memory cache.

func NamedCredentialProviderFor added in v1.0.1

func NamedCredentialProviderFor(policy AccessPolicy, ctx *ChainContext, named string) (CredentialProvider, error)

NamedCredentialProviderFor is CredentialProviderFor under a named credential (AUTH-1): an unknown name fails at construction, not on the first request.

type CredentialSource added in v1.0.1

type CredentialSource struct {
	Rung      string
	Label     string
	Named     string
	ExpiresAt *time.Time
}

CredentialSource is where a resolved credential came from (AUTH-1 provenance, 2026-09-19). Never the value: the rung's fixture kind, its human label, the name that selected it (platform …) when one did, and the expiry if known.

func ChainCredentialSource added in v1.0.1

func ChainCredentialSource(p CredentialProvider) *CredentialSource

ChainCredentialSource reports the provenance of a cloud credential provider after its first resolution (nil for any other provider).

func (CredentialSource) Describe added in v1.0.1

func (s CredentialSource) Describe(now time.Time) string

Describe renders the source for an error or the doctor.

type DataPart added in v1.0.1

type DataPart struct {
	Value         any
	Probabilities map[string]map[string]float64
	Method        string
	Continuation  []ContinuationState
}

DataPart is structured data as content (changes/2026-09-17-judgments.md, D2). In a user/system message: structured input (a provider that reads JSON state takes Value as such; a text-only wire gets it as compact JSON text). In an assistant message: the answer to a json_schema request that declares judgments (MAP-14) — Value is the model's JSON object, Probabilities a distribution per judgment over its declared keys when one was measured, Method how (JudgmentMethod). Value is an opaque payload: any JSON value, verbatim (INV-002); nil is the JSON null.

func Data added in v1.0.1

func Data(value any) DataPart

Data creates a data part (structured input, or a judged answer).

func DataPartFromText added in v1.0.1

func DataPartFromText(text string, found []Judgment) (DataPart, bool)

DataPartFromText is the model's JSON object as a DataPart (value only), or false when the text is not a JSON object (a truncated answer stays a TextPart).

func DataWithProbabilities added in v1.0.1

func DataWithProbabilities(value any, probabilities map[string]map[string]float64, method string) DataPart

DataWithProbabilities creates a judged answer carrying its distributions.

func (DataPart) ContinuationStates added in v1.0.1

func (p DataPart) ContinuationStates() []ContinuationState

func (DataPart) MarshalJSON added in v1.0.1

func (p DataPart) MarshalJSON() ([]byte, error)

func (DataPart) Type added in v1.0.1

func (DataPart) Type() string

func (DataPart) Validate added in v1.0.1

func (p DataPart) Validate() error

Validate implements Part (INV-052: method iff probabilities; inner maps non-empty, floats in [0, 1]; the sum is not validated — providers round).

func (DataPart) WithContinuation added in v1.0.1

func (p DataPart) WithContinuation(c []ContinuationState) Part

type Delta

type Delta interface {
	Type() string
	Validate() error
	// contains filtered or unexported methods
}

Delta is a typed fragment of a Part arriving during streaming; a closed sum. PartIndex names a slot (MAP-9).

func DeltaFromDict added in v1.0.1

func DeltaFromDict(d JSONObject) (Delta, error)

DeltaFromDict reads a delta (part_index defaults to 0).

type DevicePollResult added in v1.0.1

type DevicePollResult struct {
	Pending  bool
	SlowDown bool
	Interval *float64 // seconds, when the server names one
	Complete bool
	Value    any
	Failed   bool
	Message  string
}

DevicePollResult is one poll outcome.

type Dismisser

type Dismisser interface {
	Dismiss(p Prompt)
}

Dismisser is an optional AuthUI method: a displayed prompt became stale (the loopback return won the race).

type DocumentPart

type DocumentPart struct{ Media }

DocumentPart is a document (PDF, ...).

func Document added in v1.0.1

func Document(opts ...MediaOption) DocumentPart

Document creates a document part (default media type application/pdf).

func (DocumentPart) ContinuationStates added in v1.0.1

func (p DocumentPart) ContinuationStates() []ContinuationState

func (DocumentPart) MarshalJSON

func (p DocumentPart) MarshalJSON() ([]byte, error)

func (DocumentPart) Type added in v1.0.1

func (DocumentPart) Type() string

func (DocumentPart) Validate added in v1.0.1

func (p DocumentPart) Validate() error

Validate implements Part.

func (DocumentPart) WithContinuation added in v1.0.1

func (p DocumentPart) WithContinuation(c []ContinuationState) Part

type EndpointSupport added in v1.0.1

type EndpointSupport struct {
	Complete     bool
	Stream       bool
	Live         bool
	Files        bool
	Batches      bool
	Images       bool
	Speech       bool
	Video        bool
	ResponsesAPI bool
	Models       bool
	Caches       bool
	Extra        []string
}

EndpointSupport declares the surfaces an access path carries. A dialect that implements a surface still refuses when the policy does not carry it.

func (EndpointSupport) SupportsEndpoint added in v1.0.1

func (s EndpointSupport) SupportsEndpoint(name string) bool

SupportsEndpoint reports whether the named surface is carried.

type Error added in v1.0.1

type Error struct {
	Kind         ErrorKind
	Code         string
	Message      string
	Provider     string
	ProviderCode string
	Status       int // 0 = none
	RequestID    string
	RetryAfter   *float64

	// RateLimitHeaders is the bounded, immutable snapshot of provider
	// rate-limit evidence (docs/error-diagnostics.md, 2026-09-19): lowercase
	// header name → the values in arrival order, closed allowlist, at most
	// four values of 1–256 printable ASCII characters each. Empty means no
	// retained evidence, not unlimited quota. Never a credential.
	RateLimitHeaders RateLimitHeaders

	// Feature (CapabilityError, MAP-13): the config path the refusal is
	// about — "config.top_k", "messages[0].parts[1]", "tools[name]" — so a
	// policy layer can act without parsing prose. Empty when the refusal
	// is not about one addressable field.
	Feature string

	// Guidance metadata (AuthError / NotConfiguredError).
	EnvKeys        []string
	CredentialHint string
	// CredentialOrigin (AuthError, AUTH-1 provenance): where the rejected
	// credential came from — a label, never the value.
	CredentialOrigin string

	// CollectionLimitError: the breached budget and what was kept.
	Limit         string            // "max_bytes" | "max_events"
	Maximum       int               // the configured budget
	RetainedBytes int               // bytes charged for the accepted events
	PartialEvents []LiveServerEvent // every accepted event, in order
	RejectedEvent LiveServerEvent   // a byte overflow's received-but-not-kept event; nil on a count overflow

	// StreamAssemblyError: what assembled, and the first offending part.
	Partial   *Response
	PartIndex *int

	// UnknownModelError / AmbiguousModelError.
	Model     string
	Providers []string

	// LockTimeoutError.
	Path     string
	LockPath string

	// AuthOperationError (AUTH-24): programs match on Reason; CommitState
	// says whether the store changed; Recovery is guidance for a person,
	// never an instruction to retry. The ids are safe references.
	Reason       string
	Stage        string
	CommitState  string
	Recovery     string
	Operation    string
	ConnectionID string
	AttemptID    string
	MethodID     string
	// contains filtered or unexported fields
}

Error is the one lm15 error type. Kind is the canonical class; Code the ErrorCode literal. Use errors.As(err, &e) and e.Kind.IsA(...).

func AsError added in v1.0.1

func AsError(err error) *Error

AsError extracts an *Error from err, or nil.

func AuthErrorf added in v1.0.1

func AuthErrorf(provider string, envKeys []string, credentialHint string, format string, args ...any) *Error

AuthErrorf builds an AuthError with the class's guidance appended.

func Errorf added in v1.0.1

func Errorf(kind ErrorKind, format string, args ...any) *Error

Errorf builds an Error of kind with a formatted message.

func MapHTTPError

func MapHTTPError(status int, message, provider string, envKeys []string, providerCode, requestID string, retryAfter *float64) *Error

MapHTTPError maps an HTTP status + message to a typed ProviderError (the dialects add their own envelope parsing before falling back here).

func NotConfiguredErrorf added in v1.0.1

func NotConfiguredErrorf(provider string, envKeys []string, credentialHint string, format string, args ...any) *Error

NotConfiguredErrorf builds a NotConfiguredError with guidance appended.

func UnsupportedFeature added in v1.0.1

func UnsupportedFeature(provider, feature, format string, args ...any) *Error

UnsupportedFeature builds an UnsupportedFeatureError about one addressable config path (MAP-13 rule 4): feature is "config.top_k", "messages[0].parts[1]", "tools[name]", ...

func UnsupportedFeatureErrorf added in v1.0.1

func UnsupportedFeatureErrorf(provider string, format string, args ...any) *Error

UnsupportedFeatureErrorf builds an UnsupportedFeatureError.

func WithCredentialHint added in v1.0.1

func WithCredentialHint(err *Error, hint string) *Error

WithCredentialHint rewrites an AuthError's guidance for subscription (OAuth) adapters; every other error passes through unchanged.

func WithCredentialOrigin added in v1.0.1

func WithCredentialOrigin(err *Error, origin string) *Error

WithCredentialOrigin names where an AuthError's credential came from (AUTH-1 provenance, 2026-09-19): its own line under the provider's message, before the guidance, added once. Non-auth errors pass through.

func (*Error) ClassName added in v1.0.1

func (e *Error) ClassName() string

ClassName returns the canonical class name the vet protocol reports.

func (*Error) Error added in v1.0.1

func (e *Error) Error() string

Error renders the message with provider / HTTP status / request id context for provider errors (the message FIELD is what the contract pins).

func (*Error) Is added in v1.0.1

func (e *Error) Is(target error) bool

Is supports errors.Is(err, &lm15.Error{Kind: KindRateLimit}) by class.

func (*Error) PartialTurn added in v1.0.1

func (e *Error) PartialTurn() *Turn

PartialTurn materializes a CollectionLimitError's accepted events as an incomplete Turn, on demand (raw events are always available on the error without decoding).

func (*Error) Retryable added in v1.0.1

func (e *Error) Retryable() bool

Retryable is the caller's retry-policy datum; lm15 never retries.

func (*Error) Unwrap added in v1.0.1

func (e *Error) Unwrap() error

Unwrap exposes the cause (a transport failure, a JSON error).

func (*Error) WithCause added in v1.0.1

func (e *Error) WithCause(cause error) *Error

WithCause attaches a cause.

func (*Error) WithFeature added in v1.0.1

func (e *Error) WithFeature(feature string) *Error

WithFeature names the config path a capability refusal is about.

type ErrorDetail

type ErrorDetail struct {
	Code         string
	Message      string
	ProviderCode string
	HTTPResponse HTTPResponseDetail
}

ErrorDetail is structured error information. HTTPResponse is the bounded handshake diagnostics of an in-stream error (2026-09-19); empty means no HTTP evidence, not success.

func ErrorDetailFromDict added in v1.0.1

func ErrorDetailFromDict(d JSONObject) (ErrorDetail, error)

ErrorDetailFromDict reads an error detail (message defaults to "").

func (ErrorDetail) MarshalJSON

func (e ErrorDetail) MarshalJSON() ([]byte, error)

func (ErrorDetail) Validate added in v1.0.1

func (e ErrorDetail) Validate() error

Validate checks the code vocabulary.

type ErrorKind added in v1.0.1

type ErrorKind string

ErrorKind is the canonical error class (spec/vocabularies.md ErrorCode). The class hierarchy is replicated as data: IsA walks it.

LM15Error
├── TransportError
├── LockTimeoutError
├── StreamAssemblyError
├── CollectionLimitError
├── ConfigurationError
│   ├── NotConfiguredError
│   ├── UnknownModelError
│   └── AmbiguousModelError
├── CapabilityError
│   └── UnsupportedFeatureError
└── ProviderError
    ├── AuthError
    ├── BillingError
    ├── RateLimitError
    ├── InvalidRequestError
    │   ├── ContextLengthError
    │   └── UnsupportedModelError
    ├── TimeoutError
    └── ServerError
const (
	KindLM15Error          ErrorKind = "LM15Error"
	KindTransport          ErrorKind = "TransportError"
	KindLockTimeout        ErrorKind = "LockTimeoutError"
	KindStreamAssembly     ErrorKind = "StreamAssemblyError"
	KindCollectionLimit    ErrorKind = "CollectionLimitError"
	KindConfiguration      ErrorKind = "ConfigurationError"
	KindNotConfigured      ErrorKind = "NotConfiguredError"
	KindUnknownModel       ErrorKind = "UnknownModelError"
	KindAmbiguousModel     ErrorKind = "AmbiguousModelError"
	KindCapability         ErrorKind = "CapabilityError"
	KindUnsupportedFeature ErrorKind = "UnsupportedFeatureError"
	KindProvider           ErrorKind = "ProviderError"
	KindAuth               ErrorKind = "AuthError"
	KindBilling            ErrorKind = "BillingError"
	KindRateLimit          ErrorKind = "RateLimitError"
	KindInvalidRequest     ErrorKind = "InvalidRequestError"
	KindContextLength      ErrorKind = "ContextLengthError"
	KindUnsupportedModel   ErrorKind = "UnsupportedModelError"
	KindTimeout            ErrorKind = "TimeoutError"
	KindServer             ErrorKind = "ServerError"
	KindMissingCredential  ErrorKind = "MissingCredentialError" // router subclass of NotConfiguredError
	KindCredentialLockWait ErrorKind = "CredentialLockTimeout"  // auth subclass of LockTimeoutError
	KindDeviceCodeExpired  ErrorKind = "DeviceCodeExpiredError" // authkit subclass of AuthError
	// KindAuthOperation: a managed-auth lifecycle operation failed locally
	// (spec/auth-managed.md AUTH-24). Root-level, never retried.
	KindAuthOperation ErrorKind = "AuthOperationError"
)

func ErrorKindForCode added in v1.0.1

func ErrorKindForCode(code string) ErrorKind

ErrorKindForCode returns the class for a canonical code (unknown → ProviderError).

func (ErrorKind) CanonicalCode added in v1.0.1

func (k ErrorKind) CanonicalCode() string

CanonicalCode is the ErrorCode literal for a class (most-specific first).

func (ErrorKind) IsA added in v1.0.1

func (k ErrorKind) IsA(parent ErrorKind) bool

IsA reports whether kind is parent or a descendant of it.

func (ErrorKind) Retryable added in v1.0.1

func (k ErrorKind) Retryable() bool

Retryable reports whether the class is in the retryable set (RateLimitError, TimeoutError, ServerError, TransportError, LockTimeoutError).

type ExplainOptions added in v1.0.1

type ExplainOptions struct {
	Env                   map[string]string
	APIKeys               map[string]CredentialLike
	ClaudeCredentialsPath string
	CodexAuthPath         string
	XaiCredentialsPath    string
	Files                 map[string]string
	Home                  string
	Settings              map[string]string
	// Credential names one identity on a cloud door (AUTH-1: "platform",
	// "workload", "environment", "cli"); only its rungs are walked.
	Credential string
	// BaseURL is an explicit endpoint root for a cloud door (the router's
	// BaseURLs entry); "" reads the vendor's variable, then the template.
	BaseURL string
	// Now overrides the clock used for expiry details.
	Now func() time.Time
	// Auth is a managed Auth (AUTH-15 mode B): the walk is the managed
	// router's — explicit entry, named identity, the saved connection;
	// environment keys shown and not consulted. Store reads only, no renewal.
	Auth *Auth
}

ExplainOptions parameterizes ExplainAuth. Env nil = the process env.

type FileInfo added in v1.0.1

type FileInfo struct {
	ID           string
	Filename     string
	MediaType    string
	SizeBytes    *int
	CreatedAt    string
	ExpiresAt    string
	Readiness    string
	Downloadable *bool
	ProviderData JSONObject
}

FileInfo is a snapshot of one stored file. Readiness "" reads as "ready".

func FileInfoFromDict added in v1.0.1

func FileInfoFromDict(d JSONObject) (FileInfo, error)

FileInfoFromDict reads a file snapshot.

func (FileInfo) EffectiveReadiness added in v1.0.1

func (f FileInfo) EffectiveReadiness() string

EffectiveReadiness returns Readiness or "ready".

func (FileInfo) Ready added in v1.0.1

func (f FileInfo) Ready() bool

Ready reports readiness == ready.

func (FileInfo) Validate added in v1.0.1

func (f FileInfo) Validate() error

Validate checks the snapshot.

type FilePage added in v1.0.1

type FilePage struct {
	Items      []FileInfo
	NextCursor string
}

FilePage is one page of stored files.

func FilePageFromDict added in v1.0.1

func FilePageFromDict(d JSONObject) (FilePage, error)

FilePageFromDict reads a page.

func (FilePage) Validate added in v1.0.1

func (p FilePage) Validate() error

Validate checks every item.

type FileStore

type FileStore struct {
	// contains filtered or unexported fields
}

FileStore is the AUTH-8 private file with the AUTH-4 lock every lm15 SDK takes on this path and atomic writes; AUTH-25 strictness.

func NewFileStore

func NewFileStore(path string) (*FileStore, error)

NewFileStore anchors path (or the AUTH-8 default) now; nothing is read or created.

func (*FileStore) Description

func (f *FileStore) Description() string

func (*FileStore) Lock

func (f *FileStore) Lock(ctx context.Context) (StoreGuard, error)

func (*FileStore) Path

func (f *FileStore) Path() string

Path is the file.

func (*FileStore) Read

func (f *FileStore) Read() (JSONObject, error)

func (*FileStore) Reserve

func (f *FileStore) Reserve(ctx context.Context) error

type FileUploadRequest

type FileUploadRequest struct {
	Filename   string
	Bytes      []byte
	MediaType  string
	Extensions JSONObject
	Path       string
}

FileUploadRequest uploads bytes or a local path. Files are account-scoped (no model). MediaType "" reads as application/octet-stream.

func FileUploadRequestFromDict added in v1.0.1

func FileUploadRequestFromDict(d JSONObject) (FileUploadRequest, error)

FileUploadRequestFromDict reads an upload request.

func (FileUploadRequest) Content added in v1.0.1

func (r FileUploadRequest) Content() ([]byte, error)

Content returns the bytes (a path is read now).

func (FileUploadRequest) EffectiveMediaType added in v1.0.1

func (r FileUploadRequest) EffectiveMediaType() string

EffectiveMediaType returns MediaType or the octet-stream default.

func (FileUploadRequest) Validate added in v1.0.1

func (r FileUploadRequest) Validate() error

Validate checks exactly one of Bytes / Path.

type ForgetResult

type ForgetResult struct {
	Provider           string
	Forgot             bool
	Routes             []string
	IdentityGeneration string
}

ForgetResult is what a logout did.

type FunctionTool

type FunctionTool struct {
	Name        string
	Description string
	Parameters  JSONObject
}

FunctionTool is a function specification sent to the model. Parameters is an opaque JSON Schema; nil reads as the default {"type": "object", "properties": {}} (INV-033).

func (FunctionTool) EffectiveParameters added in v1.0.1

func (t FunctionTool) EffectiveParameters() JSONObject

EffectiveParameters returns Parameters, or the default schema when nil.

func (FunctionTool) MarshalJSON

func (t FunctionTool) MarshalJSON() ([]byte, error)

func (FunctionTool) ToolName

func (t FunctionTool) ToolName() string

func (FunctionTool) Validate added in v1.0.1

func (t FunctionTool) Validate() error

Validate implements Tool.

type GeminiLM

type GeminiLM struct {
	// contains filtered or unexported fields
}

GeminiLM is the Google Gemini GenerateContent dialect.

func NewGeminiLM

func NewGeminiLM(opts ...Option) (*GeminiLM, error)

NewGeminiLM constructs the Gemini dialect (default policy GeminiAPI).

func (*GeminiLM) Access added in v1.0.1

func (c *GeminiLM) Access() AccessPolicy

Access returns the bound access policy.

func (*GeminiLM) AccountID added in v1.0.1

func (c *GeminiLM) AccountID() string

AccountID returns the account id the credential carries (Codex).

func (*GeminiLM) Adaptations added in v1.0.1

func (c *GeminiLM) Adaptations() string

Adaptations returns the MAP-13 policy ("note", "silent", "refuse").

func (*GeminiLM) BaseURL added in v1.0.1

func (c *GeminiLM) BaseURL() string

BaseURL returns the base URL.

func (*GeminiLM) Batch added in v1.0.1

func (c *GeminiLM) Batch(ctx context.Context, req *BatchRequest) (*BatchJob, error)

Batch submits and wraps the ticket in a handle.

func (*GeminiLM) BatchCancel added in v1.0.1

func (c *GeminiLM) BatchCancel(ctx context.Context, batchID string) (BatchJobInfo, error)

func (*GeminiLM) BatchJob added in v1.0.1

func (c *GeminiLM) BatchJob(ctx context.Context, batchID string) (*BatchJob, error)

BatchJob re-attaches to a job by id.

func (*GeminiLM) BatchList added in v1.0.1

func (c *GeminiLM) BatchList(ctx context.Context, limit int) ([]BatchJobInfo, error)

func (*GeminiLM) BatchResults added in v1.0.1

func (c *GeminiLM) BatchResults(ctx context.Context, batchID string) ([]BatchEntry, error)

func (*GeminiLM) BatchStatus added in v1.0.1

func (c *GeminiLM) BatchStatus(ctx context.Context, batchID string) (BatchJobInfo, error)

func (*GeminiLM) BatchSubmit added in v1.0.1

func (c *GeminiLM) BatchSubmit(ctx context.Context, req *BatchRequest) (BatchJobInfo, error)

func (*GeminiLM) Batches added in v1.0.1

func (c *GeminiLM) Batches(ctx context.Context, limit int) ([]*BatchJob, error)

Batches lists this credential's jobs as handles.

func (*GeminiLM) Build added in v1.0.1

func (c *GeminiLM) Build(req *Request, stream bool) (*TransportRequest, []Adaptation, error)

Build is BuildRequest with the MAP-13 record of what the build adapted.

func (*GeminiLM) BuildRequest added in v1.0.1

func (c *GeminiLM) BuildRequest(req *Request, stream bool) (*TransportRequest, error)

BuildRequest builds the wire request (pure apart from the credential call).

func (*GeminiLM) Cache added in v1.0.1

func (c *GeminiLM) Cache(ctx context.Context, prefix *Request, ttlSeconds *int, label string) (CachedPrefix, error)

Cache makes a prompt beginning reusable with the best tier the provider has.

func (*GeminiLM) CacheCreate added in v1.0.1

func (c *GeminiLM) CacheCreate(ctx context.Context, prefix *Request, ttlSeconds *int, label string) (CacheInfo, error)

func (*GeminiLM) CacheDelete added in v1.0.1

func (c *GeminiLM) CacheDelete(ctx context.Context, cacheID string) error

func (*GeminiLM) CacheGet added in v1.0.1

func (c *GeminiLM) CacheGet(ctx context.Context, cacheID string) (CacheInfo, error)

func (*GeminiLM) CacheList added in v1.0.1

func (c *GeminiLM) CacheList(ctx context.Context, limit int, cursor string) (CachePage, error)

func (*GeminiLM) CacheUpdate added in v1.0.1

func (c *GeminiLM) CacheUpdate(ctx context.Context, cacheID string, ttlSeconds int) (CacheInfo, error)

func (*GeminiLM) Close added in v1.0.1

func (c *GeminiLM) Close() error

Close releases the transport.

func (*GeminiLM) Complete

func (c *GeminiLM) Complete(ctx context.Context, req *Request) (*Response, error)

Complete performs one call.

func (*GeminiLM) CredentialOrigin added in v1.0.1

func (c *GeminiLM) CredentialOrigin() string

CredentialOrigin says where this adapter's credential comes from (AUTH-1 provenance): a label, never the value. For a cloud chain provider this is the rung that last won, or what will be walked when no request has been sent yet.

func (*GeminiLM) CredentialSource added in v1.0.1

func (c *GeminiLM) CredentialSource() *CredentialSource

CredentialSource is the provenance of a cloud chain credential after its first resolution (nil for a key, a stored login, or before any request).

func (*GeminiLM) Endpoint added in v1.0.1

func (c *GeminiLM) Endpoint() string

Endpoint is the endpoint root a cloud door was given ("" = the template).

func (*GeminiLM) FileDelete added in v1.0.1

func (c *GeminiLM) FileDelete(ctx context.Context, fileID string) error

func (*GeminiLM) FileDownload added in v1.0.1

func (c *GeminiLM) FileDownload(ctx context.Context, fileID string) ([]byte, error)

func (*GeminiLM) FileGet added in v1.0.1

func (c *GeminiLM) FileGet(ctx context.Context, fileID string) (FileInfo, error)

func (*GeminiLM) FileList added in v1.0.1

func (c *GeminiLM) FileList(ctx context.Context, limit int, cursor string) (FilePage, error)

func (*GeminiLM) FileUpload added in v1.0.1

func (c *GeminiLM) FileUpload(ctx context.Context, req *FileUploadRequest) (FileInfo, error)

func (*GeminiLM) FileWaitReady added in v1.0.1

func (c *GeminiLM) FileWaitReady(ctx context.Context, fileID string, pollEvery time.Duration) (FileInfo, error)

FileWaitReady polls until the file leaves pending (ctx bounds the wait).

func (*GeminiLM) HostSettings added in v1.0.1

func (c *GeminiLM) HostSettings() map[string]string

HostSettings returns the resolved host settings.

func (*GeminiLM) ImageGenerate added in v1.0.1

func (c *GeminiLM) ImageGenerate(ctx context.Context, req *ImageGenerationRequest) (ImageGenerationResponse, error)

func (*GeminiLM) ListModels added in v1.0.1

func (c *GeminiLM) ListModels(ctx context.Context) ([]ModelInfo, error)

ListModels fetches the models this credential can use.

func (*GeminiLM) Live added in v1.0.1

func (c *GeminiLM) Live(ctx context.Context, config *LiveConfig) (LiveSession, error)

Live opens a live session (dialects with the surface override live()).

func (*GeminiLM) LiveDecode added in v1.0.1

func (c *GeminiLM) LiveDecode(raw []byte) ([]LiveServerEvent, error)

func (*GeminiLM) LiveEncoder added in v1.0.1

func (c *GeminiLM) LiveEncoder(config *LiveConfig) func(LiveClientEvent) ([]JSONObject, error)

func (*GeminiLM) LiveSetupFrames added in v1.0.1

func (c *GeminiLM) LiveSetupFrames(config *LiveConfig) ([]JSONObject, error)

LiveSetupFrames / LiveEncoder / LiveDecode expose the pure live codec.

func (*GeminiLM) NormalizeError added in v1.0.1

func (c *GeminiLM) NormalizeError(status int, body string) *Error

NormalizeError maps an HTTP failure body to a typed error (dialects override).

func (*GeminiLM) ParseResponse added in v1.0.1

func (c *GeminiLM) ParseResponse(req *Request, resp *HTTPResponse) (*Response, error)

ParseResponse parses a complete body.

func (*GeminiLM) ParseStreamEvents added in v1.0.1

func (c *GeminiLM) ParseStreamEvents(req *Request, event sse.Event) ([]StreamEvent, error)

ParseStreamEvents parses one SSE event into canonical events.

func (*GeminiLM) Plan added in v1.0.1

func (c *GeminiLM) Plan(req *Request) ([]Adaptation, error)

Plan is what a call with this request WOULD adapt, with no network and no credential invoked (offline, like Resolve). It returns the refusal the call would return (under any policy, or every deviation under "refuse") and the FULL record under every policy, "silent" included: a preview that hid what it saw would be no preview.

func (*GeminiLM) Provider

func (c *GeminiLM) Provider() string

Provider returns the canonical provider string.

func (*GeminiLM) RequestFromOpenAIChat added in v1.0.1

func (c *GeminiLM) RequestFromOpenAIChat(body JSONObject) (*Request, error)

RequestFromOpenAIChat is MAP-12 (chat dialect only).

func (*GeminiLM) ResponseFromOpenAIChat added in v1.0.1

func (c *GeminiLM) ResponseFromOpenAIChat(body JSONObject, model string, choice *int, responseFormat JSONObject) (*Response, error)

ResponseFromOpenAIChat is MAP-12 rule 9 (chat dialect only).

func (*GeminiLM) SetCredentialOrigin added in v1.0.1

func (c *GeminiLM) SetCredentialOrigin(label string)

SetCredentialOrigin names the credential's source when the constructor could not know it (the router: an env variable, a placeholder key).

func (*GeminiLM) SpeechGenerate added in v1.0.1

func (c *GeminiLM) SpeechGenerate(ctx context.Context, req *SpeechGenerationRequest) (SpeechGenerationResponse, error)

func (*GeminiLM) Stream

func (c *GeminiLM) Stream(ctx context.Context, req *Request) iter.Seq2[StreamEvent, error]

Stream yields canonical events: exactly one start, deltas, exactly one final end (MAP-3 / MAP-4 via the coalescer).

func (*GeminiLM) Supports added in v1.0.1

func (c *GeminiLM) Supports() EndpointSupport

Supports returns the surfaces this access path carries.

func (*GeminiLM) VideoGenerate added in v1.0.1

func (c *GeminiLM) VideoGenerate(ctx context.Context, req *VideoGenerationRequest) (*VideoJob, error)

func (*GeminiLM) VideoJob added in v1.0.1

func (c *GeminiLM) VideoJob(ctx context.Context, videoID string) (*VideoJob, error)

func (*GeminiLM) VideoJobs added in v1.0.1

func (c *GeminiLM) VideoJobs(ctx context.Context, limit int, model string) ([]*VideoJob, error)

func (*GeminiLM) VideoList added in v1.0.1

func (c *GeminiLM) VideoList(ctx context.Context, limit int, model string) ([]VideoJobInfo, error)

func (*GeminiLM) VideoResult added in v1.0.1

func (c *GeminiLM) VideoResult(ctx context.Context, videoID string) (VideoPart, error)

func (*GeminiLM) VideoStatus added in v1.0.1

func (c *GeminiLM) VideoStatus(ctx context.Context, videoID string) (VideoJobInfo, error)

func (*GeminiLM) VideoSubmit added in v1.0.1

func (c *GeminiLM) VideoSubmit(ctx context.Context, req *VideoGenerationRequest) (VideoJobInfo, error)

type HTTPFunc added in v1.0.1

type HTTPFunc func(method, url string, headers map[string]string, body []byte, timeout time.Duration) (int, map[string]string, []byte, error)

HTTPFunc performs one HTTP call for a chain rung (never following redirects).

type HTTPResponse added in v1.0.1

type HTTPResponse struct {
	Status  int
	Reason  string
	Headers [][2]string
	Body    []byte
}

HTTPResponse is a buffered provider-level response.

func JSONResponse added in v1.0.1

func JSONResponse(status int, body JSONObject) *HTTPResponse

JSONResponse wraps a JSON body as an HTTPResponse (batch entries, tests).

func (*HTTPResponse) Header added in v1.0.1

func (r *HTTPResponse) Header(name string) string

Header returns the first header value with this name.

func (*HTTPResponse) JSON added in v1.0.1

func (r *HTTPResponse) JSON() (JSONObject, error)

JSON decodes the body as a JSON object.

func (*HTTPResponse) Text added in v1.0.1

func (r *HTTPResponse) Text() string

Text returns the body as UTF-8 text.

type HTTPResponseDetail added in v1.0.1

type HTTPResponseDetail struct {
	RequestID        string
	RetryAfter       *float64
	RateLimitHeaders RateLimitHeaders
}

HTTPResponseDetail is the optional handshake block of an in-stream ErrorDetail (spec/types.md, 2026-09-19): request id, retry hint and the rate-limit snapshot of the HTTP reply the stream rode on. Empty means no evidence, never success.

func (HTTPResponseDetail) IsEmpty added in v1.0.1

func (h HTTPResponseDetail) IsEmpty() bool

IsEmpty reports whether the block carries nothing (omitted on the wire).

func (HTTPResponseDetail) Validate added in v1.0.1

func (h HTTPResponseDetail) Validate() error

Validate checks the field constraints.

type HTTPTransport added in v1.0.1

type HTTPTransport struct {
	Client         *http.Client
	Timeouts       Timeouts
	MaxConnections int
	// contains filtered or unexported fields
}

HTTPTransport is the net/http transport with the connection budget: one pool shared by every LM of a router, MaxConnections wide, each operation bounded by Timeouts. Requests advertise Accept-Encoding: identity (a compressed SSE body buffers in proxies); a reply that arrives gzip/x-gzip/deflate anyway is inflated incrementally, and br, zstd or any other coding is a transport error naming the coding — encoded bytes never reach a parser (INV-053).

func NewHTTPTransport added in v1.0.1

func NewHTTPTransport() *HTTPTransport

NewHTTPTransport creates the default transport with the shared defaults.

func NewHTTPTransportWith added in v1.0.1

func NewHTTPTransportWith(timeouts Timeouts, maxConnections int) *HTTPTransport

NewHTTPTransportWith creates a transport with an explicit budget (zero fields take the defaults).

func (*HTTPTransport) Do added in v1.0.1

Do implements Transport.

type HostSetting added in v1.0.1

type HostSetting struct {
	Name    string
	Env     []string
	Default string
}

HostSetting is one host setting: its name, the env variables consulted in order, and its default ("" = required).

type HostSpec added in v1.0.1

type HostSpec struct {
	BaseURL            string
	Settings           []HostSetting
	Paths              map[string]string
	ModelIn            string // "" reads as "body"
	AnthropicVersionIn string // "" reads as "header"
	StreamFraming      string // "" reads as "sse"
	RequiredHeaders    [][2]string
	SigV4Service       string
	// EndpointEnv: the cloud vendor's own variables, consulted in order by
	// the router, that name a full endpoint root for this door
	// (AZURE_OPENAI_ENDPOINT, AWS_ENDPOINT_URL_BEDROCK_RUNTIME). An endpoint
	// replaces the root of BaseURL (the part before the first path
	// segment); the door's path is appended unless already present
	// (AUTH-10, amended 2026-09-19).
	EndpointEnv []string
}

HostSpec is how a dialect reaches a cloud door (AUTH-10 host).

func (HostSpec) EffectiveAnthropicVersionIn added in v1.0.1

func (h HostSpec) EffectiveAnthropicVersionIn() string

EffectiveAnthropicVersionIn returns AnthropicVersionIn or "header".

func (HostSpec) EffectiveModelIn added in v1.0.1

func (h HostSpec) EffectiveModelIn() string

EffectiveModelIn returns ModelIn or "body".

func (HostSpec) EffectiveStreamFraming added in v1.0.1

func (h HostSpec) EffectiveStreamFraming() string

EffectiveStreamFraming returns StreamFraming or "sse".

func (HostSpec) PathTemplate added in v1.0.1

func (h HostSpec) PathTemplate() string

PathTemplate is the door's path under the root ("/openai/v1", "/v1/projects/{project}/locations/{location}/publishers/google"); "" when the template is a bare host.

func (HostSpec) RootTemplate added in v1.0.1

func (h HostSpec) RootTemplate() string

RootTemplate is BaseURL up to (not including) the first path segment: the part an endpoint override replaces.

func (HostSpec) SettingNames added in v1.0.1

func (h HostSpec) SettingNames() []string

SettingNames lists the setting names.

func (HostSpec) URLOnlySettings added in v1.0.1

func (h HostSpec) URLOnlySettings() map[string]bool

URLOnlySettings are the settings an endpoint override makes unnecessary: those that appear in the root of the template and nowhere else — not in the path, not in a required header, and not the SigV4 signing region (AWS's own SDK requires a region even with endpoint_url; the signature's credential scope names it).

type ImageDelta

type ImageDelta struct {
	Data      *string
	URL       *string
	FileID    *string
	PartIndex int
	MediaType string
}

ImageDelta is a partial image chunk.

func (ImageDelta) MarshalJSON

func (d ImageDelta) MarshalJSON() ([]byte, error)

func (ImageDelta) Type added in v1.0.1

func (ImageDelta) Type() string

func (ImageDelta) Validate added in v1.0.1

func (d ImageDelta) Validate() error

type ImageGenerationRequest

type ImageGenerationRequest struct {
	Model      string
	Prompt     string
	Size       string
	Images     []ImagePart
	Extensions JSONObject
}

ImageGenerationRequest: text (and optional input images) in, images out.

func ImageGenerationRequestFromDict added in v1.0.1

func ImageGenerationRequestFromDict(d JSONObject) (ImageGenerationRequest, error)

ImageGenerationRequestFromDict reads an image generation request.

func (ImageGenerationRequest) Validate added in v1.0.1

func (r ImageGenerationRequest) Validate() error

Validate checks the request.

type ImageGenerationResponse

type ImageGenerationResponse struct {
	Images       []ImagePart
	Text         string
	ID           string
	Model        string
	Usage        Usage
	ProviderData JSONObject
}

ImageGenerationResponse carries generated images plus any narration.

func ImageGenerationResponseFromDict added in v1.0.1

func ImageGenerationResponseFromDict(d JSONObject) (ImageGenerationResponse, error)

ImageGenerationResponseFromDict reads an image generation response.

func (ImageGenerationResponse) Validate added in v1.0.1

func (r ImageGenerationResponse) Validate() error

Validate checks at least one image.

type ImagePart

type ImagePart struct {
	Media
	Detail string
}

ImagePart is an image; Detail is one of low/high/auto.

func Image added in v1.0.1

func Image(opts ...MediaOption) ImagePart

Image creates an image part (default media type image/png).

func (ImagePart) ContinuationStates added in v1.0.1

func (p ImagePart) ContinuationStates() []ContinuationState

func (ImagePart) MarshalJSON

func (p ImagePart) MarshalJSON() ([]byte, error)

func (ImagePart) Type added in v1.0.1

func (ImagePart) Type() string

func (ImagePart) Validate added in v1.0.1

func (p ImagePart) Validate() error

Validate implements Part.

func (ImagePart) WithContinuation added in v1.0.1

func (p ImagePart) WithContinuation(c []ContinuationState) Part

type InferenceModelInfo

type InferenceModelInfo struct {
	InputModalities   []string // nil reads as ["text"]
	OutputModalities  []string // nil reads as ["text"]
	ContextWindow     *int
	MaxOutputTokens   *int
	SupportsReasoning bool
	ReasoningEfforts  []string
	Pricing           *InferencePricing
	Extensions        JSONObject
}

InferenceModelInfo describes a model's inference capabilities.

func (InferenceModelInfo) Validate added in v1.0.1

func (i InferenceModelInfo) Validate() error

Validate checks the info.

type InferencePricing

type InferencePricing struct {
	InputPerMillion      *float64
	OutputPerMillion     *float64
	CacheReadPerMillion  *float64
	CacheWritePerMillion *float64
	Currency             string // "" reads as USD
	Dimensions           JSONObject
}

InferencePricing is per-million-token pricing (advisory metadata).

func (InferencePricing) EffectiveCurrency added in v1.0.1

func (p InferencePricing) EffectiveCurrency() string

EffectiveCurrency returns Currency or USD.

func (InferencePricing) Estimate added in v1.0.1

func (p InferencePricing) Estimate(u Usage) float64

Estimate computes a cost lower bound; nil counts are unknown and skipped.

func (InferencePricing) Validate added in v1.0.1

func (p InferencePricing) Validate() error

Validate checks the rates.

type JSONObject added in v1.0.1

type JSONObject []Member

JSONObject is a JSON object that keeps its keys in the order they were written or received. Order is data: a model fills structured output in the order the schema lists its properties, and a signature or an upload covers the exact bytes. Every object lm15 decodes is a JSONObject in the order it arrived, and every object it encodes is written in member order.

A JSONObject is a slice, so a literal lists its members in order (lm15.KV keeps go vet quiet about unkeyed fields). Read with Get, Lookup and All; write with Set and Delete. Set and Delete never write into memory another copy of the object can see: they copy first, so an object you handed to lm15, or received from it, never changes behind your back. That costs one copy per call; objects here are small.

A nil JSONObject is "absent"; JSONObject{} is the empty object. Keys are unique: an object with a repeated key is not a JSON value lm15 accepts or sends.

Example

A schema lists its properties in the order the model should fill them: here the reasoning, then the answer it leads to.

package main

import (
	"fmt"

	lm15 "github.com/lm15-dev/lm15-go"
)

func main() {
	schema := lm15.JSONObject{
		lm15.KV("type", "object"),
		lm15.KV("properties", lm15.JSONObject{
			lm15.KV("reasoning", lm15.JSONObject{lm15.KV("type", "string")}),
			lm15.KV("answer", lm15.JSONObject{lm15.KV("type", "string")}),
		}),
		lm15.KV("required", []any{"reasoning", "answer"}),
	}
	schema.Set("additionalProperties", false)
	out, _ := lm15.EncodeJSON(schema)
	fmt.Println(string(out))
}
Output:
{"type":"object","properties":{"reasoning":{"type":"string"},"answer":{"type":"string"}},"required":["reasoning","answer"],"additionalProperties":false}

func AdaptationToDict added in v1.0.1

func AdaptationToDict(a Adaptation) JSONObject

AdaptationToDict serializes one record (asked/applied omitted when nil).

func AudioFormatToDict added in v1.0.1

func AudioFormatToDict(a AudioFormat) JSONObject

AudioFormatToDict serializes an audio format.

func BatchEntryToDict added in v1.0.1

func BatchEntryToDict(e BatchEntry) JSONObject

BatchEntryToDict serializes a batch entry (its response WITH provider_data).

func BatchJobToDict added in v1.0.1

func BatchJobToDict(j BatchJobInfo) JSONObject

BatchJobToDict serializes a batch job snapshot.

func BatchRequestToDict added in v1.0.1

func BatchRequestToDict(b BatchRequest) JSONObject

BatchRequestToDict serializes a batch request.

func CacheConfigToDict added in v1.0.1

func CacheConfigToDict(c CacheConfig) JSONObject

CacheConfigToDict serializes a cache config.

func CacheInfoToDict added in v1.0.1

func CacheInfoToDict(c CacheInfo) JSONObject

CacheInfoToDict serializes a cache snapshot.

func CachePageToDict added in v1.0.1

func CachePageToDict(p CachePage) JSONObject

CachePageToDict serializes a cache page.

func CachedPrefixToDict added in v1.0.1

func CachedPrefixToDict(c CachedPrefix) JSONObject

CachedPrefixToDict serializes a cached prefix.

func Choice added in v1.0.1

func Choice(instruction string, options ...ChoiceOption) (JSONObject, error)

Choice emits a choice judgment property: keys with optional descriptions.

func ConfigToDict added in v1.0.1

func ConfigToDict(c Config) JSONObject

ConfigToDict serializes a config (store=false and logprobs=0 are data).

func ContinuationData added in v1.0.1

func ContinuationData(states []ContinuationState, provider, kind string) JSONObject

ContinuationData returns the data of the first matching state, or nil.

func ContinuationToDict added in v1.0.1

func ContinuationToDict(s ContinuationState) JSONObject

ContinuationToDict serializes a state (data is always emitted).

func CredentialToDict added in v1.0.1

func CredentialToDict(c Credential) JSONObject

CredentialToDict is the canonical JSON of a credential (AUTH-2). Absent fields are omitted, never null. This is the only way a value leaves the type: callers that serialize a credential are sending it on purpose.

func DecodeJSONObject added in v1.0.1

func DecodeJSONObject(data []byte) (JSONObject, error)

DecodeJSONObject parses JSON and requires an object.

Example

JSON text keeps its order, and so does everything lm15 decodes.

package main

import (
	"fmt"

	lm15 "github.com/lm15-dev/lm15-go"
)

func main() {
	obj, _ := lm15.DecodeJSONObject([]byte(`{"zeta": 1, "alpha": 2.0}`))
	for key, value := range obj.All() {
		fmt.Println(key, value)
	}
}
Output:
zeta 1
alpha 2.0

func DecodeJWTPayload added in v1.0.1

func DecodeJWTPayload(token string) JSONObject

DecodeJWTPayload returns a JWT's claims (nil when not a JWT).

func DefaultParameters

func DefaultParameters() JSONObject

DefaultParameters is the schema an omitted FunctionTool.Parameters means.

func DeltaToDict added in v1.0.1

func DeltaToDict(dl Delta) JSONObject

DeltaToDict serializes a delta: only nil fields are dropped; empty strings are emitted; part_index is always emitted (except a nil ContinuationDelta index).

func ErrorDetailToDict added in v1.0.1

func ErrorDetailToDict(e ErrorDetail) JSONObject

ErrorDetailToDict serializes an error detail.

func FileInfoToDict added in v1.0.1

func FileInfoToDict(f FileInfo) JSONObject

FileInfoToDict serializes a file snapshot (readiness always; downloadable=false is data).

func FilePageToDict added in v1.0.1

func FilePageToDict(p FilePage) JSONObject

FilePageToDict serializes a page.

func FileUploadRequestToDict added in v1.0.1

func FileUploadRequestToDict(r FileUploadRequest) JSONObject

FileUploadRequestToDict serializes an upload request (bytes as base64).

func ImageGenerationRequestToDict added in v1.0.1

func ImageGenerationRequestToDict(r ImageGenerationRequest) JSONObject

ImageGenerationRequestToDict serializes an image generation request.

func ImageGenerationResponseToDict added in v1.0.1

func ImageGenerationResponseToDict(r ImageGenerationResponse) JSONObject

ImageGenerationResponseToDict serializes an image generation response.

func Judgments added in v1.0.1

func Judgments(name string, strict bool, properties ...JudgmentProperty) (JSONObject, error)

Judgments emits a response_format declaring the given judgment properties in the order given: the schema lists them, and required names them, in that order.

func LiveClientEventToDict added in v1.0.1

func LiveClientEventToDict(e LiveClientEvent) JSONObject

LiveClientEventToDict serializes a client event (no cleaning: every field verbatim).

func LiveConfigToDict added in v1.0.1

func LiveConfigToDict(c LiveConfig) JSONObject

LiveConfigToDict serializes a live config.

func LiveServerEventToDict added in v1.0.1

func LiveServerEventToDict(e LiveServerEvent) JSONObject

LiveServerEventToDict serializes a server event.

func MessageToDict added in v1.0.1

func MessageToDict(m Message) JSONObject

MessageToDict serializes a message.

func ModelInfoToDict added in v1.0.1

func ModelInfoToDict(m ModelInfo) JSONObject

ModelInfoToDict serializes model metadata (a default origin is dropped).

func NormalizeTransportRequest added in v1.0.1

func NormalizeTransportRequest(req *TransportRequest) JSONObject

NormalizeTransportRequest renders a wire request in the protocol's shape.

func ObjectFromMap

func ObjectFromMap(m map[string]any) JSONObject

ObjectFromMap converts a Go map into a JSONObject. A Go map has no key order, so the keys come out sorted, the order encoding/json writes a map in; nested maps are converted the same way. Build a JSONObject directly (or parse one with DecodeJSONObject) when the order matters, as it does for a JSON Schema's properties.

Example

A Go map has no order: converted, its keys come out sorted.

package main

import (
	"fmt"

	lm15 "github.com/lm15-dev/lm15-go"
)

func main() {
	obj := lm15.ObjectFromMap(map[string]any{"zeta": 1, "alpha": 2})
	fmt.Println(obj.Keys())
}
Output:
[alpha zeta]

func PartToDict added in v1.0.1

func PartToDict(p Part) JSONObject

PartToDict serializes a part.

func ReasoningToDict added in v1.0.1

func ReasoningToDict(r Reasoning) JSONObject

ReasoningToDict serializes reasoning.

func RequestToDict added in v1.0.1

func RequestToDict(r *Request) JSONObject

RequestToDict serializes a request.

func ResponseToDict added in v1.0.1

func ResponseToDict(r *Response, includeProviderData bool) JSONObject

ResponseToDict serializes a response; provider_data only when asked.

func Score added in v1.0.1

func Score(instruction string, levels ...ScoreLevel) (JSONObject, error)

Score emits an ordered judgment: levels low → high.

func SpeechGenerationRequestToDict added in v1.0.1

func SpeechGenerationRequestToDict(r SpeechGenerationRequest) JSONObject

SpeechGenerationRequestToDict serializes a speech request.

func SpeechGenerationResponseToDict added in v1.0.1

func SpeechGenerationResponseToDict(r SpeechGenerationResponse) JSONObject

SpeechGenerationResponseToDict serializes a speech response.

func StreamEventToDict added in v1.0.1

func StreamEventToDict(e StreamEvent) JSONObject

StreamEventToDict serializes a stream event.

func SurfaceDump

func SurfaceDump() JSONObject

SurfaceDump is the reflection-driven surface the vet protocol's surface_dump op reports: every canonical type's fields (snake_case, from the struct fields), every vocabulary, and every provider's access policy.

func TokenExchangeBuild added in v1.0.1

func TokenExchangeBuild(policy AccessPolicy, rung string, inputs JSONObject, ctx *ChainContext) (JSONObject, error)

TokenExchangeBuild is the exact token-exchange request a rung would send under the fixed clock.

func TokenLogprobToDict added in v1.0.1

func TokenLogprobToDict(t TokenLogprob) JSONObject

TokenLogprobToDict serializes a token logprob.

func ToolChoiceToDict added in v1.0.1

func ToolChoiceToDict(tc ToolChoice) JSONObject

ToolChoiceToDict serializes a tool choice.

func ToolToDict added in v1.0.1

func ToolToDict(t Tool) JSONObject

ToolToDict serializes a tool (parameters always emitted, INV-033).

func UsageToDict added in v1.0.1

func UsageToDict(u Usage) JSONObject

UsageToDict serializes usage (every counter omit-empty).

func VideoGenerationRequestToDict added in v1.0.1

func VideoGenerationRequestToDict(r VideoGenerationRequest) JSONObject

VideoGenerationRequestToDict serializes a video request.

func VideoJobToDict added in v1.0.1

func VideoJobToDict(j VideoJobInfo) JSONObject

VideoJobToDict serializes a video job snapshot.

func YesNo added in v1.0.1

func YesNo(instruction string) JSONObject

YesNo emits a boolean judgment property.

func (JSONObject) All

func (o JSONObject) All() iter.Seq2[string, any]

All iterates the members in order: for key, value := range obj.All().

func (JSONObject) Clone

func (o JSONObject) Clone() JSONObject

Clone returns a shallow copy (nested objects and lists are shared). It keeps nil distinct from empty.

func (*JSONObject) Delete

func (o *JSONObject) Delete(key string)

Delete removes key, keeping the order of the other members. It copies the object first; deleting an absent key does nothing.

func (JSONObject) Get

func (o JSONObject) Get(key string) any

Get returns the value stored under key, or nil when the key is absent. Use Lookup to tell an absent key from a JSON null.

func (JSONObject) Has

func (o JSONObject) Has(key string) bool

Has reports whether key is present.

func (JSONObject) Keys

func (o JSONObject) Keys() []string

Keys returns the keys in order.

func (JSONObject) Lookup

func (o JSONObject) Lookup(key string) (any, bool)

Lookup returns the value stored under key and whether the key is present.

func (JSONObject) MarshalJSON

func (o JSONObject) MarshalJSON() ([]byte, error)

MarshalJSON writes the members in order, compactly, without HTML escaping. A repeated key is an error.

func (*JSONObject) Set

func (o *JSONObject) Set(key string, value any)

Set stores value under key: in place of the existing member, keeping its position, or as a new last member. It copies the object first.

func (JSONObject) String

func (o JSONObject) String() string

String is the object as compact JSON, in member order, so fmt.Println and %v show what would be sent. An object that cannot be written (a repeated key, a value with no JSON form) shows its members instead.

func (*JSONObject) UnmarshalJSON

func (o *JSONObject) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a JSON object keeping its key order; numbers stay json.Number, nested objects become JSONObjects.

type Judgment added in v1.0.1

type Judgment struct {
	Name         string
	Kind         JudgmentKind
	Keys         []string // declared answer keys, in order
	Instruction  string   // the property's description (the question); "" = none
	Descriptions map[string]string
	Titles       map[string]string
}

Judgment is one declared judgment read off a schema property.

func JudgmentsInSchema added in v1.0.1

func JudgmentsInSchema(schema any) []Judgment

JudgmentsInSchema lists the judgments a json_schema declares, in property order (MAP-14 §1). Any property that is not one of the three shapes is ordinary structured output and is absent from the result.

func RequestJudgments added in v1.0.1

func RequestJudgments(req *Request) []Judgment

RequestJudgments lists the judgments a request's response_format declares.

func (Judgment) Ordered added in v1.0.1

func (j Judgment) Ordered() bool

Ordered reports whether the judgment is a level scale.

type JudgmentKind added in v1.0.1

type JudgmentKind string

JudgmentKind is one of "boolean", "choice", "ordered".

const (
	JudgmentBoolean JudgmentKind = "boolean"
	JudgmentChoice  JudgmentKind = "choice"
	JudgmentOrdered JudgmentKind = "ordered"
)

type JudgmentProperty added in v1.0.1

type JudgmentProperty struct {
	Name   string
	Schema JSONObject
}

JudgmentProperty is one named judgment for Judgments.

type LM added in v1.0.1

type LM interface {
	Provider() string
	Access() AccessPolicy
	Supports() EndpointSupport
	BaseURL() string

	Complete(ctx context.Context, req *Request) (*Response, error)
	Stream(ctx context.Context, req *Request) iter.Seq2[StreamEvent, error]
	ListModels(ctx context.Context) ([]ModelInfo, error)

	// Plan is what a call WOULD adapt (MAP-13), with no network and no
	// credential invoked; it returns the refusal the call would return.
	Plan(req *Request) ([]Adaptation, error)
	// Adaptations is the MAP-13 policy this adapter runs under.
	Adaptations() string

	// Pure hooks (what the contract pins).
	BuildRequest(req *Request, stream bool) (*TransportRequest, error)
	// Build is BuildRequest with the MAP-13 record of the build.
	Build(req *Request, stream bool) (*TransportRequest, []Adaptation, error)
	ParseResponse(req *Request, resp *HTTPResponse) (*Response, error)
	ParseStreamEvents(req *Request, event sse.Event) ([]StreamEvent, error)
	NormalizeError(status int, body string) *Error

	// Files.
	FileUpload(ctx context.Context, req *FileUploadRequest) (FileInfo, error)
	FileGet(ctx context.Context, fileID string) (FileInfo, error)
	FileList(ctx context.Context, limit int, cursor string) (FilePage, error)
	FileDelete(ctx context.Context, fileID string) error
	FileDownload(ctx context.Context, fileID string) ([]byte, error)
	FileWaitReady(ctx context.Context, fileID string, pollEvery time.Duration) (FileInfo, error)

	// Batch.
	BatchSubmit(ctx context.Context, req *BatchRequest) (BatchJobInfo, error)
	BatchStatus(ctx context.Context, batchID string) (BatchJobInfo, error)
	BatchResults(ctx context.Context, batchID string) ([]BatchEntry, error)
	BatchCancel(ctx context.Context, batchID string) (BatchJobInfo, error)
	BatchList(ctx context.Context, limit int) ([]BatchJobInfo, error)
	Batch(ctx context.Context, req *BatchRequest) (*BatchJob, error)
	BatchJob(ctx context.Context, batchID string) (*BatchJob, error)
	Batches(ctx context.Context, limit int) ([]*BatchJob, error)

	// Cache resources.
	CacheCreate(ctx context.Context, prefix *Request, ttlSeconds *int, label string) (CacheInfo, error)
	CacheGet(ctx context.Context, cacheID string) (CacheInfo, error)
	CacheList(ctx context.Context, limit int, cursor string) (CachePage, error)
	CacheDelete(ctx context.Context, cacheID string) error
	CacheUpdate(ctx context.Context, cacheID string, ttlSeconds int) (CacheInfo, error)
	Cache(ctx context.Context, prefix *Request, ttlSeconds *int, label string) (CachedPrefix, error)

	// Generation.
	ImageGenerate(ctx context.Context, req *ImageGenerationRequest) (ImageGenerationResponse, error)
	SpeechGenerate(ctx context.Context, req *SpeechGenerationRequest) (SpeechGenerationResponse, error)

	// Video.
	VideoSubmit(ctx context.Context, req *VideoGenerationRequest) (VideoJobInfo, error)
	VideoStatus(ctx context.Context, videoID string) (VideoJobInfo, error)
	VideoResult(ctx context.Context, videoID string) (VideoPart, error)
	VideoList(ctx context.Context, limit int, model string) ([]VideoJobInfo, error)
	VideoGenerate(ctx context.Context, req *VideoGenerationRequest) (*VideoJob, error)
	VideoJob(ctx context.Context, videoID string) (*VideoJob, error)
	VideoJobs(ctx context.Context, limit int, model string) ([]*VideoJob, error)

	// Live.
	Live(ctx context.Context, config *LiveConfig) (LiveSession, error)

	// Ingest (MAP-12); non-chat dialects refuse.
	RequestFromOpenAIChat(body JSONObject) (*Request, error)
	// ResponseFromOpenAIChat reads a Chat Completions body; responseFormat
	// (optional) is the request's, so a judgment answer folds into a DataPart.
	ResponseFromOpenAIChat(body JSONObject, model string, choice *int, responseFormat JSONObject) (*Response, error)

	Close() error
}

LM is a provider adapter: a dialect bound to an access policy. Every concrete adapter (OpenAILM, OpenAIChatLM, AnthropicLM, GeminiLM) and the router's returned values satisfy it.

func AdapterForProvider added in v1.0.1

func AdapterForProvider(provider string, credential CredentialLike, baseURL string, settings map[string]string, clock func() time.Time, extra ...Option) (LM, error)

AdapterForProvider constructs the LM a contract case's provider names, exactly as the router would, with the given credential and base URL. Extra options can supply an embedding's transport or adaptation policy.

type LMRouter added in v1.0.1

type LMRouter struct {
	Config RouterConfig
	// contains filtered or unexported fields
}

LMRouter routes model strings to provider LMs; one LM per provider, built lazily, reused, and the one transport those LMs share (the router's pool is one pool; Close releases every socket).

func NewRouter added in v1.0.1

func NewRouter() *LMRouter

NewRouter creates a router over the process environment.

func NewRouterWithConfig added in v1.0.1

func NewRouterWithConfig(config RouterConfig) (*LMRouter, error)

NewRouterWithConfig creates a router; the config's provider-keyed maps are checked for typos and the config for consistency.

func (*LMRouter) Cache added in v1.0.1

func (r *LMRouter) Cache(ctx context.Context, prefix *Request, ttlSeconds *int, label string) (CachedPrefix, error)

Cache is the MAP-6 door, routed by the prefix's model.

func (*LMRouter) Close added in v1.0.1

func (r *LMRouter) Close() error

Close closes every connection this router holds. Idempotent; the router may be used again afterwards (a fresh transport is built).

func (*LMRouter) Complete added in v1.0.1

func (r *LMRouter) Complete(ctx context.Context, req *Request) (*Response, error)

Complete performs one call through the routed LM.

func (*LMRouter) CompleteFromOpenAIChat added in v1.0.1

func (r *LMRouter) CompleteFromOpenAIChat(ctx context.Context, model string, messages []any, kwargs JSONObject) (*Response, error)

CompleteFromOpenAIChat answers the OpenAI SDK's / litellm's call with a canonical Response.

func (*LMRouter) LM added in v1.0.1

func (r *LMRouter) LM(model string) (LM, error)

LM resolves, then constructs or reuses the provider LM.

func (*LMRouter) Plan added in v1.0.1

func (r *LMRouter) Plan(req *Request) ([]Adaptation, error)

Plan is the MAP-13 pre-flight: what this request WOULD adapt on its route, no network and no credential (like Resolve); it returns what the call would return. A route with no key gets a throwaway planning LM (not cached): the build's bytes are discarded, so no key is needed.

func (*LMRouter) RequestFromOpenAIChat added in v1.0.1

func (r *LMRouter) RequestFromOpenAIChat(model string, messages []any, kwargs JSONObject) (*Request, LM, error)

RequestFromOpenAIChat reads the OpenAI SDK / litellm call (model, messages, kwargs) into the Request it builds and the LM it routes to.

func (*LMRouter) Resolve added in v1.0.1

func (r *LMRouter) Resolve(model string) (Resolution, error)

Resolve is the offline lookup (also the explain method).

func (*LMRouter) ResolveOpenAIChat added in v1.0.1

func (r *LMRouter) ResolveOpenAIChat(model string) (Resolution, error)

ResolveOpenAIChat is Resolve for the OpenAI-shaped door: a bare OpenAI name takes the Chat Completions door.

func (*LMRouter) ResponseStreamFromOpenAIChat added in v1.0.1

func (r *LMRouter) ResponseStreamFromOpenAIChat(ctx context.Context, model string, messages []any, kwargs JSONObject) (*ResponseStream, error)

ResponseStreamFromOpenAIChat is the lazy ResponseStream form.

func (*LMRouter) Stream added in v1.0.1

func (r *LMRouter) Stream(ctx context.Context, req *Request) iter.Seq2[StreamEvent, error]

Stream streams through the routed LM.

func (*LMRouter) StreamFromOpenAIChat added in v1.0.1

func (r *LMRouter) StreamFromOpenAIChat(ctx context.Context, model string, messages []any, kwargs JSONObject) iter.Seq2[StreamEvent, error]

StreamFromOpenAIChat is the streaming twin: typed lm15 events.

type LiveClientAudioEvent

type LiveClientAudioEvent struct {
	Data      string
	MediaType string
}

LiveClientAudioEvent streams input audio (base64). MediaType "" reads as audio/pcm;rate=16000.

func (LiveClientAudioEvent) EffectiveMediaType added in v1.0.1

func (e LiveClientAudioEvent) EffectiveMediaType() string

EffectiveMediaType returns MediaType or the default.

func (LiveClientAudioEvent) Type added in v1.0.1

func (LiveClientAudioEvent) Validate added in v1.0.1

func (e LiveClientAudioEvent) Validate() error

type LiveClientEndAudioEvent

type LiveClientEndAudioEvent struct{}

LiveClientEndAudioEvent ends the audio input turn.

func (LiveClientEndAudioEvent) Type added in v1.0.1

func (LiveClientEndAudioEvent) Validate added in v1.0.1

func (LiveClientEndAudioEvent) Validate() error

type LiveClientEvent

type LiveClientEvent interface {
	Type() string
	Validate() error
	// contains filtered or unexported methods
}

LiveClientEvent is a closed sum of the events a client sends.

func LiveClientEventFromDict added in v1.0.1

func LiveClientEventFromDict(d JSONObject) (LiveClientEvent, error)

LiveClientEventFromDict reads a client event.

type LiveClientImageEvent

type LiveClientImageEvent struct {
	Data      string
	MediaType string
}

LiveClientImageEvent streams an input frame (base64). MediaType "" reads as image/jpeg.

func (LiveClientImageEvent) EffectiveMediaType added in v1.0.1

func (e LiveClientImageEvent) EffectiveMediaType() string

EffectiveMediaType returns MediaType or the default.

func (LiveClientImageEvent) Type added in v1.0.1

func (LiveClientImageEvent) Validate added in v1.0.1

func (e LiveClientImageEvent) Validate() error

type LiveClientInterruptEvent

type LiveClientInterruptEvent struct{}

LiveClientInterruptEvent interrupts the model.

func (LiveClientInterruptEvent) Type added in v1.0.1

func (LiveClientInterruptEvent) Validate added in v1.0.1

func (LiveClientInterruptEvent) Validate() error

type LiveClientTextEvent

type LiveClientTextEvent struct{ Text string }

LiveClientTextEvent sends text.

func (LiveClientTextEvent) Type added in v1.0.1

func (LiveClientTextEvent) Type() string

func (LiveClientTextEvent) Validate added in v1.0.1

func (LiveClientTextEvent) Validate() error

type LiveClientToolResultEvent

type LiveClientToolResultEvent struct {
	ID      string
	Content []Part
}

LiveClientToolResultEvent answers a tool call.

func (LiveClientToolResultEvent) Type added in v1.0.1

func (LiveClientToolResultEvent) Validate added in v1.0.1

func (e LiveClientToolResultEvent) Validate() error

type LiveClientTurnEvent

type LiveClientTurnEvent struct {
	Parts        []Part
	TurnComplete bool
}

LiveClientTurnEvent sends prompt parts; TurnComplete says whether the model may answer now (set it explicitly in literals; NewLiveClientTurnEvent defaults it to true).

func NewLiveClientTurnEvent added in v1.0.1

func NewLiveClientTurnEvent(parts ...Part) LiveClientTurnEvent

NewLiveClientTurnEvent creates a complete turn.

func (LiveClientTurnEvent) Type added in v1.0.1

func (LiveClientTurnEvent) Type() string

func (LiveClientTurnEvent) Validate added in v1.0.1

func (e LiveClientTurnEvent) Validate() error

type LiveConfig

type LiveConfig struct {
	Model        string
	System       *SystemPrompt
	Tools        []Tool
	Voice        string
	InputFormat  *AudioFormat
	OutputFormat *AudioFormat
	Extensions   JSONObject
}

LiveConfig configures a live session.

func LiveConfigFromDict added in v1.0.1

func LiveConfigFromDict(d JSONObject) (LiveConfig, error)

LiveConfigFromDict reads a live config.

func (LiveConfig) Validate added in v1.0.1

func (c LiveConfig) Validate() error

Validate checks the config.

type LiveServerAudioEvent

type LiveServerAudioEvent struct {
	Data      string
	MediaType string
}

LiveServerAudioEvent carries output audio (base64).

func (LiveServerAudioEvent) Type added in v1.0.1

func (LiveServerAudioEvent) Validate added in v1.0.1

func (e LiveServerAudioEvent) Validate() error

type LiveServerErrorEvent

type LiveServerErrorEvent struct{ Error ErrorDetail }

LiveServerErrorEvent reports a failure.

func (LiveServerErrorEvent) Type added in v1.0.1

func (LiveServerErrorEvent) Validate added in v1.0.1

func (e LiveServerErrorEvent) Validate() error

type LiveServerEvent

type LiveServerEvent interface {
	Type() string
	Validate() error
	// contains filtered or unexported methods
}

LiveServerEvent is a closed sum of the events a server sends.

func LiveServerEventFromDict added in v1.0.1

func LiveServerEventFromDict(d JSONObject) (LiveServerEvent, error)

LiveServerEventFromDict reads a server event.

type LiveServerInterruptedEvent

type LiveServerInterruptedEvent struct{}

LiveServerInterruptedEvent reports a barge-in.

func (LiveServerInterruptedEvent) Type added in v1.0.1

func (LiveServerInterruptedEvent) Validate added in v1.0.1

func (LiveServerInterruptedEvent) Validate() error

type LiveServerTextEvent

type LiveServerTextEvent struct{ Text string }

LiveServerTextEvent carries output text (or a transcript).

func (LiveServerTextEvent) Type added in v1.0.1

func (LiveServerTextEvent) Type() string

func (LiveServerTextEvent) Validate added in v1.0.1

func (LiveServerTextEvent) Validate() error

type LiveServerToolCallDeltaEvent

type LiveServerToolCallDeltaEvent struct {
	InputDelta string
	ID         string
	Name       string
}

LiveServerToolCallDeltaEvent streams tool-call arguments.

func (LiveServerToolCallDeltaEvent) Type added in v1.0.1

func (LiveServerToolCallDeltaEvent) Validate added in v1.0.1

type LiveServerToolCallEvent

type LiveServerToolCallEvent struct {
	ID    string
	Name  string
	Input JSONObject
}

LiveServerToolCallEvent asks the client to run a tool.

func (LiveServerToolCallEvent) Type added in v1.0.1

func (LiveServerToolCallEvent) Validate added in v1.0.1

func (e LiveServerToolCallEvent) Validate() error

type LiveServerTurnEndEvent

type LiveServerTurnEndEvent struct{ Usage Usage }

LiveServerTurnEndEvent ends a turn with its usage.

func (LiveServerTurnEndEvent) Type added in v1.0.1

func (LiveServerTurnEndEvent) Validate added in v1.0.1

func (e LiveServerTurnEndEvent) Validate() error

type LiveServerUsageEvent added in v1.0.1

type LiveServerUsageEvent struct{ Usage Usage }

LiveServerUsageEvent bills a response that did not end the turn.

func (LiveServerUsageEvent) Type added in v1.0.1

func (LiveServerUsageEvent) Validate added in v1.0.1

func (e LiveServerUsageEvent) Validate() error

type LiveSession added in v1.0.1

type LiveSession interface {
	Send(ctx context.Context, event LiveClientEvent) error
	SendTurn(ctx context.Context, parts ...Part) error
	SendAudio(ctx context.Context, data []byte, mediaType string) error
	SendImage(ctx context.Context, data []byte, mediaType string) error
	SendText(ctx context.Context, text string) error
	SendToolResult(ctx context.Context, callID string, output string) error
	Interrupt(ctx context.Context) error
	EndAudio(ctx context.Context) error
	Recv(ctx context.Context) (LiveServerEvent, error)
	// Turn reads until the turn's boundary (turn_end / interrupted / error)
	// or a tool_call the caller must answer (LIVE-1), under the default
	// collection budget (DefaultTurnMaxBytes, DefaultTurnMaxEvents).
	Turn(ctx context.Context) (*Turn, error)
	// TurnView opens a bounded collector over the next turn; zero limits
	// take the defaults. Raw Recv iteration is the deliberate
	// no-collection alternative.
	TurnView(limits TurnLimits) (*TurnView, error)
	Close() error
}

LiveSession is a realtime session: send typed client events, receive typed server events. The codec is the contract; the session mechanics are this port's idiom.

type LoadedCredential added in v1.0.1

type LoadedCredential struct {
	Provider  CredentialProvider
	AccountID string
	Source    string // "explicit", "stored" or "named"
	// Origin is the AUTH-1 provenance label: honest about what lm15 can
	// see (a caller's provider is not introspected). Never the value.
	Origin string
}

LoadedCredential is the credential an adapter will send, and where it came from.

func LoadCredential added in v1.0.1

func LoadCredential(policy AccessPolicy, explicit CredentialProvider, credentialsPath string) (LoadedCredential, error)

LoadCredential resolves the credential an adapter sends under policy: an explicit credential wins (AUTH-1); a stored-login policy loads its file; a key policy with nothing is a typed not-configured error.

func LoadCredentialNamed added in v1.0.1

func LoadCredentialNamed(policy AccessPolicy, explicit CredentialProvider, credentialsPath string, named string) (LoadedCredential, error)

LoadCredentialNamed is LoadCredential with a named credential (AUTH-1, 2026-09-19): one identity on a cloud door, read from this process's environment, never the chain. It cannot be combined with an explicit credential: two answers to "who am I" is a configuration error.

type LocalOAuthCredential added in v1.0.1

type LocalOAuthCredential struct {
	AccessToken  string
	RefreshToken string
	ExpiresAt    *int64 // epoch milliseconds
	AccountID    string
}

LocalOAuthCredential is a locally stored OAuth credential. Token fields never print.

func GetCodexCLIAccessToken added in v1.0.1

func GetCodexCLIAccessToken(ctx context.Context, path string, refresh bool) (LocalOAuthCredential, error)

GetCodexCLIAccessToken returns a usable credential, refreshing under the lock.

func LoadClaudeCodeCredential added in v1.0.1

func LoadClaudeCodeCredential(path string) (LocalOAuthCredential, error)

LoadClaudeCodeCredential reads the Claude Code credential, typed errors on failure.

func LoadCodexCLICredential added in v1.0.1

func LoadCodexCLICredential(path string) (LocalOAuthCredential, error)

LoadCodexCLICredential reads the Codex CLI credential.

func LoadXaiCredential added in v1.0.1

func LoadXaiCredential(path string) (LocalOAuthCredential, error)

LoadXaiCredential reads the stored xAI credential.

func Login added in v1.0.1

func Login(ctx context.Context, provider, credentialsPath string, echo func(string)) (LocalOAuthCredential, error)

Login runs the flow lm15 owns for provider (today: xai); every other provider fails typed, naming the real path.

func LoginXai added in v1.0.1

func LoginXai(ctx context.Context, path string, echo func(string)) (LocalOAuthCredential, error)

LoginXai runs the device-code login, persists and returns the credential.

func PollXaiDeviceLogin added in v1.0.1

func PollXaiDeviceLogin(ctx context.Context, device XaiDeviceAuthorization, sleep func(time.Duration)) (LocalOAuthCredential, error)

PollXaiDeviceLogin polls until the user approves.

func ReadClaudeCodeCredential added in v1.0.1

func ReadClaudeCodeCredential(path string) *LocalOAuthCredential

ReadClaudeCodeCredential is the optional-style loader.

func ReadCodexCLICredential added in v1.0.1

func ReadCodexCLICredential(path string) *LocalOAuthCredential

ReadCodexCLICredential is the optional-style loader.

func ReadXaiCredential added in v1.0.1

func ReadXaiCredential(path string) *LocalOAuthCredential

ReadXaiCredential is the optional-style loader.

func RefreshClaudeCodeCredential added in v1.0.1

func RefreshClaudeCodeCredential(ctx context.Context, refreshToken string) (LocalOAuthCredential, error)

RefreshClaudeCodeCredential exchanges a refresh token.

func RefreshCodexCLICredential added in v1.0.1

func RefreshCodexCLICredential(ctx context.Context, refreshToken string) (LocalOAuthCredential, error)

RefreshCodexCLICredential exchanges a refresh token.

func RefreshXaiCredential added in v1.0.1

func RefreshXaiCredential(ctx context.Context, refreshToken string) (LocalOAuthCredential, error)

RefreshXaiCredential exchanges a refresh token.

func (LocalOAuthCredential) Expired added in v1.0.1

func (c LocalOAuthCredential) Expired() bool

Expired reports whether the recorded expiry has passed.

func (LocalOAuthCredential) String added in v1.0.1

func (c LocalOAuthCredential) String() string

String redacts (AUTH-5).

type LoginMethod

type LoginMethod struct {
	ID           string
	Label        string
	Kind         string // account | api_key | cloud_identity | local_server
	Flow         string // authorization_code | device_code | form | source_recipe
	Availability string
	Reason       string
	Fields       []MethodField
	Delivery     []string // loopback | manual | device
	Subscription bool     // backed by a provider subscription, per provider docs; never an entitlement promise
	BillingNote  string
	Guidance     string
}

LoginMethod is a named way to establish a connection (AUTH-13.3). Availability: "supported" has a recorded receipt; "unverified" exists without one (explicit opt-in only); "unavailable" cannot run here.

type LoginOptions

type LoginOptions struct {
	Method          string // "" = ask the UI when more than one selectable method remains (AUTH-13.6)
	UI              AuthUI
	Settings        map[string]string
	Answers         map[string]string
	Replace         string // the connection id being replaced; without it an occupied slot is connection_exists
	Lifetime        time.Duration
	AllowUnverified bool // unverified methods run only with this (AUTH-13.5)
}

LoginOptions configures one login.

type Media added in v1.0.1

type Media struct {
	MediaType    string
	Data         string
	URL          string
	FileID       string
	Path         string
	Continuation []ContinuationState
}

Media holds the fields every media part shares: exactly one of Data (base64), URL, FileID, Path.

func MediaOf added in v1.0.1

func MediaOf(p Part) (Media, bool)

MediaOf returns the Media of a media part.

func (Media) Base64 added in v1.0.1

func (m Media) Base64() (string, error)

Base64 returns the media bytes as base64 (inline data verbatim, a path read now).

func (Media) Bytes added in v1.0.1

func (m Media) Bytes() ([]byte, error)

Bytes returns the media bytes: inline data decoded, or the path read now.

type MediaOption added in v1.0.1

type MediaOption func(*Media)

MediaOption configures a media factory.

func WithBase64 added in v1.0.1

func WithBase64(data string) MediaOption

WithBase64 embeds an already-encoded base64 string (or data URI).

func WithData added in v1.0.1

func WithData(data []byte) MediaOption

WithData embeds raw bytes (base64-encoded).

func WithFileID added in v1.0.1

func WithFileID(id string) MediaOption

WithFileID addresses the media by a provider file id.

func WithMediaType added in v1.0.1

func WithMediaType(mediaType string) MediaOption

WithMediaType sets the MIME type.

func WithPath added in v1.0.1

func WithPath(path string) MediaOption

WithPath addresses the media by a local path (read at request time).

func WithURL added in v1.0.1

func WithURL(url string) MediaOption

WithURL addresses the media by URL.

type Member

type Member struct {
	Key   string
	Value any
}

Member is one key/value pair of a JSONObject.

func KV

func KV(key string, value any) Member

KV builds a Member. It is the short, vet-clean way to write an object literal outside this package:

schema := lm15.JSONObject{
	lm15.KV("type", "object"),
	lm15.KV("properties", lm15.JSONObject{
		lm15.KV("reasoning", lm15.JSONObject{lm15.KV("type", "string")}),
		lm15.KV("answer", lm15.JSONObject{lm15.KV("type", "string")}),
	}),
}

type MemoryStore

type MemoryStore struct {
	// contains filtered or unexported fields
}

MemoryStore is a process-lifetime document: Auth.Memory, tests, short-lived tools.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore is an empty memory store.

func (*MemoryStore) Description

func (m *MemoryStore) Description() string

func (*MemoryStore) Lock

func (m *MemoryStore) Lock(ctx context.Context) (StoreGuard, error)

func (*MemoryStore) Read

func (m *MemoryStore) Read() (JSONObject, error)

func (*MemoryStore) Reserve

func (m *MemoryStore) Reserve(context.Context) error

type Message

type Message struct {
	Role         string
	Parts        []Part
	Continuation []ContinuationState
}

Message is a contribution to a conversation, attributed to a speaker.

func AssistantMessage

func AssistantMessage(parts ...Part) Message

AssistantMessage creates an assistant message from parts.

func AssistantText added in v1.0.1

func AssistantText(text string) Message

AssistantText creates an assistant message from text.

func DeveloperMessage added in v1.0.1

func DeveloperMessage(text string) Message

DeveloperMessage creates a developer (high-authority instruction) message.

func DeveloperParts added in v1.0.1

func DeveloperParts(parts ...Part) Message

DeveloperParts creates a developer message from parts.

func MessageFromDict added in v1.0.1

func MessageFromDict(d JSONObject) (Message, error)

MessageFromDict reads a message (INV-047).

func ToolMessage added in v1.0.1

func ToolMessage(callID, output string) Message

ToolMessage answers one tool call with text output.

func ToolMessageParts added in v1.0.1

func ToolMessageParts(results ...ToolResultPart) Message

ToolMessageParts creates a tool message from explicit results.

func UserMessage

func UserMessage(text string) Message

UserMessage creates a user message from text.

func UserParts added in v1.0.1

func UserParts(parts ...Part) Message

UserParts creates a user message from parts.

func (Message) First added in v1.0.1

func (m Message) First(match func(Part) bool) (Part, bool)

First returns the first part matching the predicate.

func (Message) MarshalJSON

func (m Message) MarshalJSON() ([]byte, error)

func (Message) PartsOf added in v1.0.1

func (m Message) PartsOf(match func(Part) bool) []Part

PartsOf returns the parts matching the predicate.

func (Message) Text added in v1.0.1

func (m Message) Text() *string

Text is the joined text when EVERY part is a TextPart (nil otherwise).

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(b []byte) error

func (Message) Validate added in v1.0.1

func (m Message) Validate() error

Validate checks role/part compatibility (INV-022..024).

type MethodField

type MethodField struct {
	ID       string
	Label    string
	Type     string // text | secret | select
	Required bool
	Options  []SelectOption
	Help     string
}

MethodField is one input a login method needs before it can start.

type ModelChoice

type ModelChoice struct {
	Provider     string
	Model        string
	ConnectionID string
	Source       string // provider | manual
	FetchedAt    string
	Capability   string // the requested capability, if any
	State        string // supported | unsupported | unknown
}

ModelChoice is a model the saved connection can select, and where that came from.

func ModelChoices

func ModelChoices(ctx context.Context, auth *Auth, provider, capability string, includeUnknown bool, config RouterConfig) ([]ModelChoice, error)

ModelChoices lists the models the saved connection on provider can select, fetched now with the saved credential (renewing if due; no inference). With capability, only supported ones unless includeUnknown.

type ModelInfo

type ModelInfo struct {
	ID         string
	Provider   string
	APIFamily  string
	Aliases    []string
	Origin     ModelOrigin
	Inference  *InferenceModelInfo
	Extensions JSONObject
}

ModelInfo is optional model metadata (listing, catalogs, routing).

func ModelInfoFromDict added in v1.0.1

func ModelInfoFromDict(d JSONObject) (ModelInfo, error)

ModelInfoFromDict reads model metadata.

func (ModelInfo) MarshalJSON

func (m ModelInfo) MarshalJSON() ([]byte, error)

func (*ModelInfo) UnmarshalJSON

func (m *ModelInfo) UnmarshalJSON(b []byte) error

func (ModelInfo) Validate added in v1.0.1

func (m ModelInfo) Validate() error

Validate checks the info.

type ModelNotFoundForm added in v1.0.1

type ModelNotFoundForm struct {
	Code, Prefix, Contains, Suffix string
}

ModelNotFoundForm is one pinned MAP-15 form of a provider's "no such model" answer: an exact provider code, and the text tests the message must pass.

type ModelOrigin

type ModelOrigin struct {
	Type         string
	ID           string
	BaseModel    string
	ProviderData JSONObject
}

ModelOrigin describes where a model comes from. Type "" reads as "provider".

func (ModelOrigin) EffectiveType added in v1.0.1

func (o ModelOrigin) EffectiveType() string

EffectiveType returns Type or "provider".

type ModelOverride added in v1.0.1

type ModelOverride struct {
	Prefix string
	Knobs  map[string]string
}

ModelOverride is a per-model-family knob override (first matching prefix wins).

type ModelRegistry added in v1.0.1

type ModelRegistry struct {
	// contains filtered or unexported fields
}

ModelRegistry is an in-memory catalog keyed by (provider, id).

func ModelRegistryFromDicts added in v1.0.1

func ModelRegistryFromDicts(dicts []JSONObject) (*ModelRegistry, error)

ModelRegistryFromDicts builds a registry from canonical ModelInfo dicts.

func NewModelRegistry added in v1.0.1

func NewModelRegistry() *ModelRegistry

NewModelRegistry creates an empty registry.

func (*ModelRegistry) Add added in v1.0.1

func (r *ModelRegistry) Add(m ModelInfo, replace bool) error

Add registers a model; replace=false refuses duplicates.

func (*ModelRegistry) Get added in v1.0.1

func (r *ModelRegistry) Get(provider, model string) (ModelInfo, bool)

Get finds a model by provider and id or alias.

func (*ModelRegistry) List added in v1.0.1

func (r *ModelRegistry) List(provider string) []ModelInfo

List returns every model (optionally for one provider), in insertion order.

func (*ModelRegistry) Providers added in v1.0.1

func (r *ModelRegistry) Providers() []string

Providers lists the distinct providers, sorted.

func (*ModelRegistry) Resolve added in v1.0.1

func (r *ModelRegistry) Resolve(model, provider string) (ModelInfo, bool)

Resolve finds a model by id or alias across providers (unique match only).

type ModelSelection

type ModelSelection struct {
	Provider           string
	Model              string
	ConnectionID       string
	IdentityGeneration string
}

ModelSelection is an exact route + model bound to one connection id and generation.

func (ModelSelection) Routed

func (s ModelSelection) Routed() string

Routed is "provider:model".

type Notice

type Notice struct {
	Type            string
	URL             string // auth_url: session-sensitive (state, PKCE challenge)
	Instructions    string
	UserCode        string // device_code: show it, never log it (AUTH-21)
	VerificationURL string
	ExpiresInS      float64
	IntervalS       float64
	Stage           string // progress
	Message         string // progress, info
	Links           [][2]string
}

Notice tells the person something. Type: auth_url | device_code | progress | info.

type OpenAIChatCompat added in v1.0.1

type OpenAIChatCompat struct {
	InstructionRole           string // auto | developer | system
	MaxTokensField            string // auto | max_completion_tokens | max_tokens
	StreamUsage               string // auto | include | omit
	ToolResultName            string // auto | include | omit
	AssistantAfterToolResult  string // auto | insert | omit
	ThinkingFormat            string // auto | none | reasoning_effort | openrouter | deepseek | kimi | qwen | qwen_chat_template
	ThinkingReplay            string // auto | native | as_text | omit
	AssistantReasoningContent string // auto | include_empty | omit
	StrictTools               string // auto | include | omit
	BuiltinTools              string // auto | reject | groq
	ToolResultMedia           string // auto | native | images | reject
	CacheControl              string // auto | none | openai | openai_implicit | anthropic
	UserField                 string // auto | user | user_id | safety_identifier
	ForcedToolChoice          string // auto | send | reject
	JSONSchema                string // auto | send | reject
	// TokenScoring (MAP-14 §4): can the server score named tokens
	// (logprob_token_ids on the completions endpoint) so lm15 can deliver a
	// distribution over declared keys? auto | none | logprob_token_ids.
	// Receipted on vLLM 0.29.0 (honoured) and 0.25.1 (200, silently
	// absent) 2026-09-17; the response-side check catches the latter.
	TokenScoring     string
	ReasoningEfforts []string
	// ReasoningOff is what an explicit reasoning-off becomes: auto | send |
	// lowest. "send" puts the dial's off word on the wire (MAP-5). "lowest"
	// is for a model that cannot stop reasoning on a server that accepts the
	// off word and reasons anyway: the lowest level (ReasoningEfforts[0],
	// else "low") is sent and the substitution recorded (MAP-13 §4.2).
	// Ratified 2026-09-26 (changes/2026-09-26-inference-hosts-live.md).
	ReasoningOff   string
	Routing        JSONObject
	Extensions     JSONObject
	ModelOverrides []ModelOverride
}

OpenAIChatCompat is a partial policy for Chat Completions servers.

func MergeOpenAIChatCompat added in v1.0.1

func MergeOpenAIChatCompat(base OpenAIChatCompat, override *OpenAIChatCompat) OpenAIChatCompat

MergeOpenAIChatCompat layers override on base ("" inherits).

func OpenAIChatPreset added in v1.0.1

func OpenAIChatPreset(name string) (OpenAIChatCompat, error)

OpenAIChatPreset returns the named Chat preset.

func (OpenAIChatCompat) ForModel added in v1.0.1

func (c OpenAIChatCompat) ForModel(model string) OpenAIChatCompat

ForModel applies the first matching model override.

func (OpenAIChatCompat) Validate added in v1.0.1

func (c OpenAIChatCompat) Validate() error

Validate checks the override knob names.

type OpenAIChatLM

type OpenAIChatLM struct {
	// contains filtered or unexported fields
}

OpenAIChatLM is the OpenAI Chat Completions dialect: OpenAI's legacy endpoint and every OpenAI-compatible server (ollama, Groq, OpenRouter, vLLM, SGLang, DeepSeek, xAI, ...). Server quirks are OpenAIChatCompat presets; xAI's provider facts branch on the bound policy.

func NewOpenAIChatLM

func NewOpenAIChatLM(opts ...Option) (*OpenAIChatLM, error)

NewOpenAIChatLM constructs the Chat Completions dialect (default policy OpenAIChatAPI).

func NewXaiLM added in v1.0.1

func NewXaiLM(opts ...Option) (*OpenAIChatLM, error)

NewXaiLM constructs the xAI adapter (Chat Completions dialect, xai preset, oauth-unless-explicit credential policy).

func (*OpenAIChatLM) Access added in v1.0.1

func (c *OpenAIChatLM) Access() AccessPolicy

Access returns the bound access policy.

func (*OpenAIChatLM) AccountID added in v1.0.1

func (c *OpenAIChatLM) AccountID() string

AccountID returns the account id the credential carries (Codex).

func (*OpenAIChatLM) Adaptations added in v1.0.1

func (c *OpenAIChatLM) Adaptations() string

Adaptations returns the MAP-13 policy ("note", "silent", "refuse").

func (*OpenAIChatLM) BaseURL added in v1.0.1

func (c *OpenAIChatLM) BaseURL() string

BaseURL returns the base URL.

func (*OpenAIChatLM) Batch added in v1.0.1

func (c *OpenAIChatLM) Batch(ctx context.Context, req *BatchRequest) (*BatchJob, error)

Batch submits and wraps the ticket in a handle.

func (*OpenAIChatLM) BatchCancel added in v1.0.1

func (c *OpenAIChatLM) BatchCancel(ctx context.Context, batchID string) (BatchJobInfo, error)

func (*OpenAIChatLM) BatchJob added in v1.0.1

func (c *OpenAIChatLM) BatchJob(ctx context.Context, batchID string) (*BatchJob, error)

BatchJob re-attaches to a job by id.

func (*OpenAIChatLM) BatchList added in v1.0.1

func (c *OpenAIChatLM) BatchList(ctx context.Context, limit int) ([]BatchJobInfo, error)

func (*OpenAIChatLM) BatchResults added in v1.0.1

func (c *OpenAIChatLM) BatchResults(ctx context.Context, batchID string) ([]BatchEntry, error)

func (*OpenAIChatLM) BatchStatus added in v1.0.1

func (c *OpenAIChatLM) BatchStatus(ctx context.Context, batchID string) (BatchJobInfo, error)

func (*OpenAIChatLM) BatchSubmit added in v1.0.1

func (c *OpenAIChatLM) BatchSubmit(ctx context.Context, req *BatchRequest) (BatchJobInfo, error)

func (*OpenAIChatLM) Batches added in v1.0.1

func (c *OpenAIChatLM) Batches(ctx context.Context, limit int) ([]*BatchJob, error)

Batches lists this credential's jobs as handles.

func (*OpenAIChatLM) Build added in v1.0.1

func (c *OpenAIChatLM) Build(req *Request, stream bool) (*TransportRequest, []Adaptation, error)

Build is BuildRequest with the MAP-13 record of what the build adapted.

func (*OpenAIChatLM) BuildRequest added in v1.0.1

func (c *OpenAIChatLM) BuildRequest(req *Request, stream bool) (*TransportRequest, error)

BuildRequest builds the wire request (pure apart from the credential call).

func (*OpenAIChatLM) Cache added in v1.0.1

func (c *OpenAIChatLM) Cache(ctx context.Context, prefix *Request, ttlSeconds *int, label string) (CachedPrefix, error)

Cache makes a prompt beginning reusable with the best tier the provider has.

func (*OpenAIChatLM) CacheCreate added in v1.0.1

func (c *OpenAIChatLM) CacheCreate(ctx context.Context, prefix *Request, ttlSeconds *int, label string) (CacheInfo, error)

func (*OpenAIChatLM) CacheDelete added in v1.0.1

func (c *OpenAIChatLM) CacheDelete(ctx context.Context, cacheID string) error

func (*OpenAIChatLM) CacheGet added in v1.0.1

func (c *OpenAIChatLM) CacheGet(ctx context.Context, cacheID string) (CacheInfo, error)

func (*OpenAIChatLM) CacheList added in v1.0.1

func (c *OpenAIChatLM) CacheList(ctx context.Context, limit int, cursor string) (CachePage, error)

func (*OpenAIChatLM) CacheUpdate added in v1.0.1

func (c *OpenAIChatLM) CacheUpdate(ctx context.Context, cacheID string, ttlSeconds int) (CacheInfo, error)

func (*OpenAIChatLM) Close added in v1.0.1

func (c *OpenAIChatLM) Close() error

Close releases the transport.

func (*OpenAIChatLM) Complete

func (c *OpenAIChatLM) Complete(ctx context.Context, req *Request) (*Response, error)

Complete performs one call.

func (*OpenAIChatLM) CredentialOrigin added in v1.0.1

func (c *OpenAIChatLM) CredentialOrigin() string

CredentialOrigin says where this adapter's credential comes from (AUTH-1 provenance): a label, never the value. For a cloud chain provider this is the rung that last won, or what will be walked when no request has been sent yet.

func (*OpenAIChatLM) CredentialSource added in v1.0.1

func (c *OpenAIChatLM) CredentialSource() *CredentialSource

CredentialSource is the provenance of a cloud chain credential after its first resolution (nil for a key, a stored login, or before any request).

func (*OpenAIChatLM) Endpoint added in v1.0.1

func (c *OpenAIChatLM) Endpoint() string

Endpoint is the endpoint root a cloud door was given ("" = the template).

func (*OpenAIChatLM) FileDelete added in v1.0.1

func (c *OpenAIChatLM) FileDelete(ctx context.Context, fileID string) error

func (*OpenAIChatLM) FileDownload added in v1.0.1

func (c *OpenAIChatLM) FileDownload(ctx context.Context, fileID string) ([]byte, error)

func (*OpenAIChatLM) FileGet added in v1.0.1

func (c *OpenAIChatLM) FileGet(ctx context.Context, fileID string) (FileInfo, error)

func (*OpenAIChatLM) FileList added in v1.0.1

func (c *OpenAIChatLM) FileList(ctx context.Context, limit int, cursor string) (FilePage, error)

func (*OpenAIChatLM) FileUpload added in v1.0.1

func (c *OpenAIChatLM) FileUpload(ctx context.Context, req *FileUploadRequest) (FileInfo, error)

func (*OpenAIChatLM) FileWaitReady added in v1.0.1

func (c *OpenAIChatLM) FileWaitReady(ctx context.Context, fileID string, pollEvery time.Duration) (FileInfo, error)

FileWaitReady polls until the file leaves pending (ctx bounds the wait).

func (*OpenAIChatLM) HostSettings added in v1.0.1

func (c *OpenAIChatLM) HostSettings() map[string]string

HostSettings returns the resolved host settings.

func (*OpenAIChatLM) ImageGenerate added in v1.0.1

func (c *OpenAIChatLM) ImageGenerate(ctx context.Context, req *ImageGenerationRequest) (ImageGenerationResponse, error)

func (*OpenAIChatLM) ListModels added in v1.0.1

func (c *OpenAIChatLM) ListModels(ctx context.Context) ([]ModelInfo, error)

ListModels fetches the models this credential can use.

func (*OpenAIChatLM) Live added in v1.0.1

func (c *OpenAIChatLM) Live(ctx context.Context, config *LiveConfig) (LiveSession, error)

Live opens a live session (dialects with the surface override live()).

func (*OpenAIChatLM) LiveDecode added in v1.0.1

func (c *OpenAIChatLM) LiveDecode(raw []byte) ([]LiveServerEvent, error)

func (*OpenAIChatLM) LiveEncoder added in v1.0.1

func (c *OpenAIChatLM) LiveEncoder(config *LiveConfig) func(LiveClientEvent) ([]JSONObject, error)

func (*OpenAIChatLM) LiveSetupFrames added in v1.0.1

func (c *OpenAIChatLM) LiveSetupFrames(config *LiveConfig) ([]JSONObject, error)

LiveSetupFrames / LiveEncoder / LiveDecode expose the pure live codec.

func (*OpenAIChatLM) NormalizeError added in v1.0.1

func (c *OpenAIChatLM) NormalizeError(status int, body string) *Error

NormalizeError maps an HTTP failure body to a typed error (dialects override).

func (*OpenAIChatLM) ParseResponse added in v1.0.1

func (c *OpenAIChatLM) ParseResponse(req *Request, resp *HTTPResponse) (*Response, error)

ParseResponse parses a complete body.

func (*OpenAIChatLM) ParseStreamEvents added in v1.0.1

func (c *OpenAIChatLM) ParseStreamEvents(req *Request, event sse.Event) ([]StreamEvent, error)

ParseStreamEvents parses one SSE event into canonical events.

func (*OpenAIChatLM) Plan added in v1.0.1

func (c *OpenAIChatLM) Plan(req *Request) ([]Adaptation, error)

Plan is what a call with this request WOULD adapt, with no network and no credential invoked (offline, like Resolve). It returns the refusal the call would return (under any policy, or every deviation under "refuse") and the FULL record under every policy, "silent" included: a preview that hid what it saw would be no preview.

func (*OpenAIChatLM) Provider

func (c *OpenAIChatLM) Provider() string

Provider returns the canonical provider string.

func (*OpenAIChatLM) RequestFromOpenAIChat added in v1.0.1

func (c *OpenAIChatLM) RequestFromOpenAIChat(body JSONObject) (*Request, error)

RequestFromOpenAIChat is MAP-12 (chat dialect only).

func (*OpenAIChatLM) ResponseFromOpenAIChat added in v1.0.1

func (c *OpenAIChatLM) ResponseFromOpenAIChat(body JSONObject, model string, choice *int, responseFormat JSONObject) (*Response, error)

ResponseFromOpenAIChat is MAP-12 rule 9 (chat dialect only).

func (*OpenAIChatLM) SetCredentialOrigin added in v1.0.1

func (c *OpenAIChatLM) SetCredentialOrigin(label string)

SetCredentialOrigin names the credential's source when the constructor could not know it (the router: an env variable, a placeholder key).

func (*OpenAIChatLM) SpeechGenerate added in v1.0.1

func (c *OpenAIChatLM) SpeechGenerate(ctx context.Context, req *SpeechGenerationRequest) (SpeechGenerationResponse, error)

func (*OpenAIChatLM) Stream

func (c *OpenAIChatLM) Stream(ctx context.Context, req *Request) iter.Seq2[StreamEvent, error]

Stream yields canonical events: exactly one start, deltas, exactly one final end (MAP-3 / MAP-4 via the coalescer).

func (*OpenAIChatLM) Supports added in v1.0.1

func (c *OpenAIChatLM) Supports() EndpointSupport

Supports returns the surfaces this access path carries.

func (*OpenAIChatLM) VideoGenerate added in v1.0.1

func (c *OpenAIChatLM) VideoGenerate(ctx context.Context, req *VideoGenerationRequest) (*VideoJob, error)

func (*OpenAIChatLM) VideoJob added in v1.0.1

func (c *OpenAIChatLM) VideoJob(ctx context.Context, videoID string) (*VideoJob, error)

func (*OpenAIChatLM) VideoJobs added in v1.0.1

func (c *OpenAIChatLM) VideoJobs(ctx context.Context, limit int, model string) ([]*VideoJob, error)

func (*OpenAIChatLM) VideoList added in v1.0.1

func (c *OpenAIChatLM) VideoList(ctx context.Context, limit int, model string) ([]VideoJobInfo, error)

func (*OpenAIChatLM) VideoResult added in v1.0.1

func (c *OpenAIChatLM) VideoResult(ctx context.Context, videoID string) (VideoPart, error)

func (*OpenAIChatLM) VideoStatus added in v1.0.1

func (c *OpenAIChatLM) VideoStatus(ctx context.Context, videoID string) (VideoJobInfo, error)

func (*OpenAIChatLM) VideoSubmit added in v1.0.1

func (c *OpenAIChatLM) VideoSubmit(ctx context.Context, req *VideoGenerationRequest) (VideoJobInfo, error)

type OpenAICodexLM added in v1.0.1

type OpenAICodexLM = OpenAILM

OpenAICodexLM is a name: OpenAILM bound to lm15.OpenAICodex.

type OpenAILM

type OpenAILM struct {
	// contains filtered or unexported fields
}

OpenAILM is the OpenAI Responses dialect bound to an access policy. OpenAICodexLM is the same type bound to the Codex login policy: the backend branches are keyed on access.Backend (AUTH-10).

func NewOpenAICodexLM added in v1.0.1

func NewOpenAICodexLM(opts ...Option) (*OpenAILM, error)

NewOpenAICodexLM constructs the Responses dialect on a Codex CLI login.

func NewOpenAILM

func NewOpenAILM(opts ...Option) (*OpenAILM, error)

NewOpenAILM constructs the Responses dialect (default policy OpenAIAPI).

func (*OpenAILM) Access added in v1.0.1

func (c *OpenAILM) Access() AccessPolicy

Access returns the bound access policy.

func (*OpenAILM) AccountID added in v1.0.1

func (c *OpenAILM) AccountID() string

AccountID returns the account id the credential carries (Codex).

func (*OpenAILM) Adaptations added in v1.0.1

func (c *OpenAILM) Adaptations() string

Adaptations returns the MAP-13 policy ("note", "silent", "refuse").

func (*OpenAILM) BaseURL added in v1.0.1

func (c *OpenAILM) BaseURL() string

BaseURL returns the base URL.

func (*OpenAILM) Batch added in v1.0.1

func (c *OpenAILM) Batch(ctx context.Context, req *BatchRequest) (*BatchJob, error)

Batch submits and wraps the ticket in a handle.

func (*OpenAILM) BatchCancel added in v1.0.1

func (c *OpenAILM) BatchCancel(ctx context.Context, batchID string) (BatchJobInfo, error)

func (*OpenAILM) BatchJob added in v1.0.1

func (c *OpenAILM) BatchJob(ctx context.Context, batchID string) (*BatchJob, error)

BatchJob re-attaches to a job by id.

func (*OpenAILM) BatchList added in v1.0.1

func (c *OpenAILM) BatchList(ctx context.Context, limit int) ([]BatchJobInfo, error)

func (*OpenAILM) BatchResults added in v1.0.1

func (c *OpenAILM) BatchResults(ctx context.Context, batchID string) ([]BatchEntry, error)

func (*OpenAILM) BatchStatus added in v1.0.1

func (c *OpenAILM) BatchStatus(ctx context.Context, batchID string) (BatchJobInfo, error)

func (*OpenAILM) BatchSubmit added in v1.0.1

func (c *OpenAILM) BatchSubmit(ctx context.Context, req *BatchRequest) (BatchJobInfo, error)

func (*OpenAILM) Batches added in v1.0.1

func (c *OpenAILM) Batches(ctx context.Context, limit int) ([]*BatchJob, error)

Batches lists this credential's jobs as handles.

func (*OpenAILM) Build added in v1.0.1

func (c *OpenAILM) Build(req *Request, stream bool) (*TransportRequest, []Adaptation, error)

Build is BuildRequest with the MAP-13 record of what the build adapted.

func (*OpenAILM) BuildRequest added in v1.0.1

func (c *OpenAILM) BuildRequest(req *Request, stream bool) (*TransportRequest, error)

BuildRequest builds the wire request (pure apart from the credential call).

func (*OpenAILM) Cache added in v1.0.1

func (c *OpenAILM) Cache(ctx context.Context, prefix *Request, ttlSeconds *int, label string) (CachedPrefix, error)

Cache makes a prompt beginning reusable with the best tier the provider has.

func (*OpenAILM) CacheCreate added in v1.0.1

func (c *OpenAILM) CacheCreate(ctx context.Context, prefix *Request, ttlSeconds *int, label string) (CacheInfo, error)

func (*OpenAILM) CacheDelete added in v1.0.1

func (c *OpenAILM) CacheDelete(ctx context.Context, cacheID string) error

func (*OpenAILM) CacheGet added in v1.0.1

func (c *OpenAILM) CacheGet(ctx context.Context, cacheID string) (CacheInfo, error)

func (*OpenAILM) CacheList added in v1.0.1

func (c *OpenAILM) CacheList(ctx context.Context, limit int, cursor string) (CachePage, error)

func (*OpenAILM) CacheUpdate added in v1.0.1

func (c *OpenAILM) CacheUpdate(ctx context.Context, cacheID string, ttlSeconds int) (CacheInfo, error)

func (*OpenAILM) Close added in v1.0.1

func (c *OpenAILM) Close() error

Close releases the transport.

func (*OpenAILM) Complete

func (c *OpenAILM) Complete(ctx context.Context, req *Request) (*Response, error)

Complete performs one call.

func (*OpenAILM) CredentialOrigin added in v1.0.1

func (c *OpenAILM) CredentialOrigin() string

CredentialOrigin says where this adapter's credential comes from (AUTH-1 provenance): a label, never the value. For a cloud chain provider this is the rung that last won, or what will be walked when no request has been sent yet.

func (*OpenAILM) CredentialSource added in v1.0.1

func (c *OpenAILM) CredentialSource() *CredentialSource

CredentialSource is the provenance of a cloud chain credential after its first resolution (nil for a key, a stored login, or before any request).

func (*OpenAILM) Endpoint added in v1.0.1

func (c *OpenAILM) Endpoint() string

Endpoint is the endpoint root a cloud door was given ("" = the template).

func (*OpenAILM) FileDelete added in v1.0.1

func (c *OpenAILM) FileDelete(ctx context.Context, fileID string) error

func (*OpenAILM) FileDownload added in v1.0.1

func (c *OpenAILM) FileDownload(ctx context.Context, fileID string) ([]byte, error)

func (*OpenAILM) FileGet added in v1.0.1

func (c *OpenAILM) FileGet(ctx context.Context, fileID string) (FileInfo, error)

func (*OpenAILM) FileList added in v1.0.1

func (c *OpenAILM) FileList(ctx context.Context, limit int, cursor string) (FilePage, error)

func (*OpenAILM) FileUpload added in v1.0.1

func (c *OpenAILM) FileUpload(ctx context.Context, req *FileUploadRequest) (FileInfo, error)

func (*OpenAILM) FileWaitReady added in v1.0.1

func (c *OpenAILM) FileWaitReady(ctx context.Context, fileID string, pollEvery time.Duration) (FileInfo, error)

FileWaitReady polls until the file leaves pending (ctx bounds the wait).

func (*OpenAILM) HostSettings added in v1.0.1

func (c *OpenAILM) HostSettings() map[string]string

HostSettings returns the resolved host settings.

func (*OpenAILM) ImageGenerate added in v1.0.1

func (c *OpenAILM) ImageGenerate(ctx context.Context, req *ImageGenerationRequest) (ImageGenerationResponse, error)

func (*OpenAILM) ListModels added in v1.0.1

func (c *OpenAILM) ListModels(ctx context.Context) ([]ModelInfo, error)

ListModels fetches the models this credential can use.

func (*OpenAILM) Live added in v1.0.1

func (c *OpenAILM) Live(ctx context.Context, config *LiveConfig) (LiveSession, error)

Live opens a live session (dialects with the surface override live()).

func (*OpenAILM) LiveDecode added in v1.0.1

func (c *OpenAILM) LiveDecode(raw []byte) ([]LiveServerEvent, error)

func (*OpenAILM) LiveEncoder added in v1.0.1

func (c *OpenAILM) LiveEncoder(config *LiveConfig) func(LiveClientEvent) ([]JSONObject, error)

func (*OpenAILM) LiveSetupFrames added in v1.0.1

func (c *OpenAILM) LiveSetupFrames(config *LiveConfig) ([]JSONObject, error)

LiveSetupFrames / LiveEncoder / LiveDecode expose the pure live codec.

func (*OpenAILM) NormalizeError added in v1.0.1

func (c *OpenAILM) NormalizeError(status int, body string) *Error

NormalizeError maps an HTTP failure body to a typed error (dialects override).

func (*OpenAILM) ParseResponse added in v1.0.1

func (c *OpenAILM) ParseResponse(req *Request, resp *HTTPResponse) (*Response, error)

ParseResponse parses a complete body.

func (*OpenAILM) ParseStreamEvents added in v1.0.1

func (c *OpenAILM) ParseStreamEvents(req *Request, event sse.Event) ([]StreamEvent, error)

ParseStreamEvents parses one SSE event into canonical events.

func (*OpenAILM) Plan added in v1.0.1

func (c *OpenAILM) Plan(req *Request) ([]Adaptation, error)

Plan is what a call with this request WOULD adapt, with no network and no credential invoked (offline, like Resolve). It returns the refusal the call would return (under any policy, or every deviation under "refuse") and the FULL record under every policy, "silent" included: a preview that hid what it saw would be no preview.

func (*OpenAILM) Provider

func (c *OpenAILM) Provider() string

Provider returns the canonical provider string.

func (*OpenAILM) RequestFromOpenAIChat added in v1.0.1

func (c *OpenAILM) RequestFromOpenAIChat(body JSONObject) (*Request, error)

RequestFromOpenAIChat is MAP-12 (chat dialect only).

func (*OpenAILM) ResponseFromOpenAIChat added in v1.0.1

func (c *OpenAILM) ResponseFromOpenAIChat(body JSONObject, model string, choice *int, responseFormat JSONObject) (*Response, error)

ResponseFromOpenAIChat is MAP-12 rule 9 (chat dialect only).

func (*OpenAILM) SetCredentialOrigin added in v1.0.1

func (c *OpenAILM) SetCredentialOrigin(label string)

SetCredentialOrigin names the credential's source when the constructor could not know it (the router: an env variable, a placeholder key).

func (*OpenAILM) SpeechGenerate added in v1.0.1

func (c *OpenAILM) SpeechGenerate(ctx context.Context, req *SpeechGenerationRequest) (SpeechGenerationResponse, error)

func (*OpenAILM) Stream

func (c *OpenAILM) Stream(ctx context.Context, req *Request) iter.Seq2[StreamEvent, error]

Stream yields canonical events: exactly one start, deltas, exactly one final end (MAP-3 / MAP-4 via the coalescer).

func (*OpenAILM) Supports added in v1.0.1

func (c *OpenAILM) Supports() EndpointSupport

Supports returns the surfaces this access path carries.

func (*OpenAILM) VideoGenerate added in v1.0.1

func (c *OpenAILM) VideoGenerate(ctx context.Context, req *VideoGenerationRequest) (*VideoJob, error)

func (*OpenAILM) VideoJob added in v1.0.1

func (c *OpenAILM) VideoJob(ctx context.Context, videoID string) (*VideoJob, error)

func (*OpenAILM) VideoJobs added in v1.0.1

func (c *OpenAILM) VideoJobs(ctx context.Context, limit int, model string) ([]*VideoJob, error)

func (*OpenAILM) VideoList added in v1.0.1

func (c *OpenAILM) VideoList(ctx context.Context, limit int, model string) ([]VideoJobInfo, error)

func (*OpenAILM) VideoResult added in v1.0.1

func (c *OpenAILM) VideoResult(ctx context.Context, videoID string) (VideoPart, error)

func (*OpenAILM) VideoStatus added in v1.0.1

func (c *OpenAILM) VideoStatus(ctx context.Context, videoID string) (VideoJobInfo, error)

func (*OpenAILM) VideoSubmit added in v1.0.1

func (c *OpenAILM) VideoSubmit(ctx context.Context, req *VideoGenerationRequest) (VideoJobInfo, error)

type OpenAIResponsesCompat added in v1.0.1

type OpenAIResponsesCompat struct {
	DeveloperRole        string // auto | developer | system
	MaxOutputTokensField string // auto | max_output_tokens | max_completion_tokens | max_tokens
	ReasoningFormat      string // auto | none | responses_reasoning | reasoning_effort | openrouter | deepseek | qwen | qwen_chat_template | zai
	ToolResultName       string // auto | include | omit
	StrictTools          string // auto | include | omit
	CacheControl         string // auto | none | openai | openai_implicit | anthropic
	CommentaryPhase      string // auto | omit | tag
	EditImageField       string // auto | array | indexed
	BuiltinTools         string // auto | openai | verbatim
	ToolResultMedia      string // auto | native | images | reject
	Routing              JSONObject
	Extensions           JSONObject
}

OpenAIResponsesCompat is a partial policy for Responses-family servers.

func MergeOpenAIResponsesCompat added in v1.0.1

func MergeOpenAIResponsesCompat(base OpenAIResponsesCompat, override *OpenAIResponsesCompat) OpenAIResponsesCompat

MergeOpenAIResponsesCompat layers override on base ("" inherits).

func OpenAIResponsesPreset added in v1.0.1

func OpenAIResponsesPreset(name string) (OpenAIResponsesCompat, error)

OpenAIResponsesPreset returns the named Responses preset.

type Option

type Option func(*lmOptions)

Option configures an adapter constructor.

func WithAPIKey added in v1.0.1

func WithAPIKey(credential CredentialLike) Option

WithAPIKey sets the credential: a string (APIKey shorthand), a Credential value, a CredentialProvider, or a func returning one.

func WithAPIVersion added in v1.0.1

func WithAPIVersion(v string) Option

WithAPIVersion sets the anthropic-version header.

func WithAccess added in v1.0.1

func WithAccess(p AccessPolicy) Option

WithAccess binds an access policy (AUTH-10).

func WithAccountID added in v1.0.1

func WithAccountID(id string) Option

WithAccountID sets the ChatGPT account id (Codex backend).

func WithAdaptations added in v1.0.1

func WithAdaptations(policy string) Option

WithAdaptations sets the MAP-13 policy: "note" (default: adapt and record), "silent" (adapt, record nothing), "refuse" (every deviation is an UnsupportedFeatureError before the wire).

func WithAnthropicCompat added in v1.0.1

func WithAnthropicCompat(c AnthropicCompat) Option

WithAnthropicCompat sets an Anthropic compat value.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL overrides the base URL.

func WithClaudeCodeVersion added in v1.0.1

func WithClaudeCodeVersion(v string) Option

WithClaudeCodeVersion sets the claude-cli user-agent version.

func WithClock added in v1.0.1

func WithClock(clock func() time.Time) Option

WithClock fixes the clock every time-dependent byte reads.

func WithCodexClientVersion added in v1.0.1

func WithCodexClientVersion(v string) Option

WithCodexClientVersion sets the Codex client_version option.

func WithCodexOriginator added in v1.0.1

func WithCodexOriginator(v string) Option

WithCodexOriginator sets the Codex originator header.

func WithCompatPreset added in v1.0.1

func WithCompatPreset(name string) Option

WithCompatPreset names the server dialect preset (also supplies its address).

func WithCredential added in v1.0.1

func WithCredential(c Credential) Option

WithCredential sets a credential value.

func WithCredentialProvider added in v1.0.1

func WithCredentialProvider(p CredentialProvider) Option

WithCredentialProvider sets a credential provider.

func WithCredentialsPath added in v1.0.1

func WithCredentialsPath(path string) Option

WithCredentialsPath overrides the stored-login file path.

func WithNamedCredential added in v1.0.1

func WithNamedCredential(name string) Option

WithNamedCredential names one identity on a cloud door instead of its chain (AUTH-1, 2026-09-19): "platform", "workload", "environment", "cli".

func WithOpenAIChatCompat added in v1.0.1

func WithOpenAIChatCompat(c OpenAIChatCompat) Option

WithOpenAIChatCompat sets a Chat Completions compat value.

func WithOpenAIResponsesCompat added in v1.0.1

func WithOpenAIResponsesCompat(c OpenAIResponsesCompat) Option

WithOpenAIResponsesCompat sets a Responses compat value.

func WithSettings added in v1.0.1

func WithSettings(settings map[string]string) Option

WithSettings sets host settings (region, project, resource, ...).

func WithTransport added in v1.0.1

func WithTransport(t Transport) Option

WithTransport sets the transport.

func WithUploadBaseURL added in v1.0.1

func WithUploadBaseURL(url string) Option

WithUploadBaseURL sets Gemini's upload root.

type PKCEPair added in v1.0.1

type PKCEPair struct {
	Verifier  string
	Challenge string
	Method    string
}

PKCEPair is a verifier (secret) and its S256 challenge.

func GeneratePKCE added in v1.0.1

func GeneratePKCE() (PKCEPair, error)

GeneratePKCE creates a fresh pair: 64 random bytes → 86-char verifier.

func (PKCEPair) String added in v1.0.1

func (p PKCEPair) String() string

String hides the verifier.

type Part

type Part interface {
	Type() string
	ContinuationStates() []ContinuationState
	// WithContinuation returns a copy carrying these states.
	WithContinuation([]ContinuationState) Part
	Validate() error
	// contains filtered or unexported methods
}

Part is the atom of content: a closed sum of twelve variants. Switch on the concrete type, or on Type().

func PartFromDict added in v1.0.1

func PartFromDict(d JSONObject) (Part, error)

PartFromDict reads a part (INV-040, INV-041, INV-044).

func ReplaceTextWithData added in v1.0.1

func ReplaceTextWithData(parts []Part, found []Judgment) []Part

ReplaceTextWithData swaps the single text part of a judgment answer for its DataPart (MAP-14 §3). Any other shape is returned unchanged.

type Prompt

type Prompt struct {
	Type        string
	FieldID     string
	Label       string
	Placeholder string
	Options     []SelectOption // select
	Accepted    string         // manual_code: what may be pasted
}

Prompt asks the person for one answer. Type: text | secret | select | manual_code.

type ProviderDefinition added in v1.0.1

type ProviderDefinition struct {
	ID             string
	Dialect        string
	Access         AccessPolicy
	Compat         string
	PlaceholderKey string
	ConsoleURL     string
	Note           string
	// AdapterOwned: the dialect's own manifest is this policy (openai,
	// anthropic, gemini, xai, claude-code, openai-codex, openai-chat).
	AdapterOwned bool
	// Aliases are extra input spellings (hyphenated) of a declared provider
	// (RouterConfig.Providers); the registry's entries use none.
	Aliases []string
	// CompatValue is a declared provider's compat as a value (Compat holds
	// a preset name); one of the two.
	CompatValue *OpenAIChatCompat
	// Declared: from RouterConfig.Providers, not the receipted registry.
	Declared bool
}

ProviderDefinition is everything lm15 knows about one named provider.

func DeclareChatProvider added in v1.0.1

func DeclareChatProvider(access AccessPolicy, compat OpenAIChatCompat, aliases []string, placeholderKey, consoleURL, note string) (ProviderDefinition, error)

DeclareChatProvider declares a provider the registry does not list — a gateway, a service lm15 has not receipted — speaking the OpenAI Chat Completions wire: access names it (AccessPolicy{Provider, EnvKeys, BaseURL}) and compat describes the server's spellings. It routes like a registry entry in every router built with a RouterConfig that lists it, and answers Resolution.Declared: no live receipt backs it, and lm15 says so.

func LookupProvider added in v1.0.1

func LookupProvider(name string) (ProviderDefinition, bool)

LookupProvider returns the definition for a provider string in either spelling.

func (ProviderDefinition) Bound added in v1.0.1

func (d ProviderDefinition) Bound() bool

Bound reports whether the router binds Access onto the dialect at construction.

func (ProviderDefinition) CredentialPolicy added in v1.0.1

func (d ProviderDefinition) CredentialPolicy() string

CredentialPolicy is the declared AUTH-1 policy.

func (ProviderDefinition) EnvKeys added in v1.0.1

func (d ProviderDefinition) EnvKeys() []string

EnvKeys are the declared environment keys.

func (ProviderDefinition) Hosted added in v1.0.1

func (d ProviderDefinition) Hosted() bool

Hosted reports whether the access policy names a cloud host.

func (ProviderDefinition) Spellings added in v1.0.1

func (d ProviderDefinition) Spellings() []string

Spellings are every input spelling that names this provider: the id and the aliases.

type ProviderDescriptor

type ProviderDescriptor struct {
	ID         string
	Label      string
	Service    string
	Routes     []string
	Methods    []LoginMethod
	ConsoleURL string
}

ProviderDescriptor is a provider a manager can connect (AUTH-13.1). ID is the lm15 route; Service is a presentation group only.

func (ProviderDescriptor) Method

func (d ProviderDescriptor) Method(id string) (LoginMethod, bool)

Method returns the method with this id.

type ProviderManifest added in v1.0.1

type ProviderManifest = AccessPolicy

ProviderManifest is the earlier name: an adapter's manifest is its policy.

type RateLimitHeaders added in v1.0.1

type RateLimitHeaders map[string][]string

RateLimitHeaders is the diagnostic snapshot: lowercase name → values in arrival order. Treat it as immutable; constructors copy it.

func CaptureRateLimits added in v1.0.1

func CaptureRateLimits(headers [][2]string) RateLimitHeaders

CaptureRateLimits builds the snapshot from response headers: closed allowlist, at most four values per name, each 1–256 printable ASCII characters, arrival order preserved. Names are lowercased; values are never normalized.

func (RateLimitHeaders) Clone added in v1.0.1

Clone returns an independent copy.

type Reasoning

type Reasoning struct {
	Effort         string
	ThinkingBudget *int
	Summary        string
}

Reasoning is the one dial (MAP-7): Effort required; ThinkingBudget a cap on budget wires; Summary the visibility knob.

func ReasoningBudget

func ReasoningBudget(tokens int) *Reasoning

ReasoningBudget is a Reasoning given only a thinking budget: Effort is filled from MAP-7 rule 3's table read the other way (amended 2026-10-10).

func ReasoningFromDict added in v1.0.1

func ReasoningFromDict(d JSONObject) (Reasoning, error)

ReasoningFromDict reads reasoning with the legacy leniencies (INV-043).

func (Reasoning) IsOff

func (r Reasoning) IsOff() bool

IsOff reports effort == "off".

func (Reasoning) MarshalJSON added in v1.0.1

func (r Reasoning) MarshalJSON() ([]byte, error)

func (Reasoning) Validate added in v1.0.1

func (r Reasoning) Validate() error

Validate checks INV-026.

type RefusalPart

type RefusalPart struct {
	Text         string
	Continuation []ContinuationState
}

RefusalPart is an explicit refusal (non-empty).

func Refusal added in v1.0.1

func Refusal(content string) RefusalPart

Refusal creates a refusal part.

func (RefusalPart) ContinuationStates added in v1.0.1

func (p RefusalPart) ContinuationStates() []ContinuationState

func (RefusalPart) MarshalJSON

func (p RefusalPart) MarshalJSON() ([]byte, error)

func (RefusalPart) Type added in v1.0.1

func (RefusalPart) Type() string

func (RefusalPart) Validate added in v1.0.1

func (p RefusalPart) Validate() error

Validate implements Part (INV-016).

func (RefusalPart) WithContinuation added in v1.0.1

func (p RefusalPart) WithContinuation(c []ContinuationState) Part

type Request

type Request struct {
	Model    string
	Messages []Message
	System   *SystemPrompt
	Tools    []Tool
	Config   Config
}

Request is a complete request to a foundation model.

func NewRequest added in v1.0.1

func NewRequest(model string, messages []Message, opts ...RequestOption) (*Request, error)

NewRequest builds and validates a request.

func RequestFromDict added in v1.0.1

func RequestFromDict(d JSONObject) (*Request, error)

RequestFromDict reads a request.

func RequestFromOpenAIChat added in v1.0.1

func RequestFromOpenAIChat(body JSONObject, compatPreset string) (*Request, error)

RequestFromOpenAIChat reads a Chat Completions request body into a canonical Request under the named preset's spellings ("" = OpenAI's own).

func RequestFromOpenAIChatCompat added in v1.0.1

func RequestFromOpenAIChatCompat(body JSONObject, compat OpenAIChatCompat) (*Request, error)

RequestFromOpenAIChatCompat reads a body under an explicit compat value.

func (Request) MarshalJSON

func (r Request) MarshalJSON() ([]byte, error)

func (*Request) ToolByName added in v1.0.1

func (r *Request) ToolByName(name string) Tool

ToolByName finds a declared tool.

func (*Request) UnmarshalJSON

func (r *Request) UnmarshalJSON(b []byte) error

func (*Request) Validate added in v1.0.1

func (r *Request) Validate() error

Validate checks INV-030 / INV-031 and every nested value.

func (*Request) WithModel added in v1.0.1

func (r *Request) WithModel(model string) *Request

WithModel returns a copy with another model string.

type RequestAuth

type RequestAuth struct {
	CredentialKind string // bearer | api_key | "" for a named cloud identity
	Credential     string
	Headers        map[string]string
	BaseURL        string
	AccountID      string
	Named          string // a saved cloud recipe: the identity the router's chain runs (AUTH-15)
}

RequestAuth is what a request sends for a saved connection. Credential is secret.

func (RequestAuth) String

func (r RequestAuth) String() string

String never renders the credential.

type RequestOption added in v1.0.1

type RequestOption func(*Request)

RequestOption configures NewRequest.

func WithConfig added in v1.0.1

func WithConfig(c Config) RequestOption

WithConfig sets the config.

func WithSystem added in v1.0.1

func WithSystem(text string) RequestOption

WithSystem sets the system prompt.

func WithTools added in v1.0.1

func WithTools(tools ...Tool) RequestOption

WithTools sets the tools.

type Resolution added in v1.0.1

type Resolution struct {
	Requested string
	Model     string
	Provider  string
	Adapter   string
	Source    string // "prefix" | "catalog" | "rule"
	Rule      *RouteRule
	EnvKey    string
	ModelInfo *ModelInfo
	Compat    string
	// Declared: the provider comes from RouterConfig.Providers, not the
	// receipted registry.
	Declared bool
	// CredentialPolicy is the provider's AUTH-1 policy.
	CredentialPolicy string
	// PlaceholderKey is a keyless local server's default key.
	PlaceholderKey string
}

Resolution is the complete answer to "how did you route this string".

func Resolve added in v1.0.1

func Resolve(model string, config RouterConfig) (Resolution, error)

Resolve is the pure lookup: no network, no credential invocation.

func (Resolution) Describe added in v1.0.1

func (r Resolution) Describe() string

Describe renders a one-paragraph explanation.

func (Resolution) String added in v1.0.1

func (r Resolution) String() string

type ResolvedAnthropicCompat added in v1.0.1

type ResolvedAnthropicCompat struct {
	ThinkingFormat    string
	ThinkingReplay    string
	CacheControl      string
	StructuredOutput  string
	ParallelToolCalls string
	SamplingParams    string
	ToolResultMedia   string
	ReasoningEfforts  []string
	ModelPrefixes     []string
	Extensions        JSONObject
}

ResolvedAnthropicCompat is a fully resolved Messages policy.

func ResolveAnthropicCompat added in v1.0.1

func ResolveAnthropicCompat(p AnthropicCompat) ResolvedAnthropicCompat

ResolveAnthropicCompat fills every knob.

type ResolvedOpenAIChatCompat added in v1.0.1

type ResolvedOpenAIChatCompat struct {
	InstructionRole           string
	MaxTokensField            string
	StreamUsage               string
	ToolResultName            string
	AssistantAfterToolResult  string
	ThinkingFormat            string
	ThinkingReplay            string
	AssistantReasoningContent string
	StrictTools               string
	BuiltinTools              string
	ToolResultMedia           string
	CacheControl              string
	UserField                 string
	ForcedToolChoice          string
	JSONSchema                string
	TokenScoring              string
	ReasoningOff              string
	ReasoningEfforts          []string
	Routing                   JSONObject
	Extensions                JSONObject
}

ResolvedOpenAIChatCompat is a fully resolved Chat policy.

func ResolveOpenAIChatCompat added in v1.0.1

func ResolveOpenAIChatCompat(p OpenAIChatCompat) ResolvedOpenAIChatCompat

ResolveOpenAIChatCompat fills every knob.

type ResolvedOpenAIResponsesCompat added in v1.0.1

type ResolvedOpenAIResponsesCompat struct {
	DeveloperRole        string
	MaxOutputTokensField string
	ReasoningFormat      string
	ToolResultName       string
	StrictTools          string
	CacheControl         string
	CommentaryPhase      string
	EditImageField       string
	BuiltinTools         string
	ToolResultMedia      string
	Routing              JSONObject
	Extensions           JSONObject
}

ResolvedOpenAIResponsesCompat is a fully resolved Responses policy.

func ResolveOpenAIResponsesCompat added in v1.0.1

func ResolveOpenAIResponsesCompat(p OpenAIResponsesCompat) ResolvedOpenAIResponsesCompat

ResolveOpenAIResponsesCompat fills every knob.

type Response

type Response struct {
	ID           string
	Model        string
	Message      Message
	FinishReason string
	Usage        Usage
	Logprobs     []TokenLogprob // nil = not reported
	ProviderData JSONObject
	// Adaptations is what the wire got that differs from what was asked
	// (MAP-13): a dropped hint, a clamped dial, a client-side stop. Empty
	// when the request went out exactly as written. Data, never printed.
	Adaptations []Adaptation
	// LogprobsIncomplete: see the type comment.
	LogprobsIncomplete bool
}

Response is what a foundation model returned.

LogprobsIncomplete (the wire's logprobs_complete=false) means local text editing (a client-side stop inside a token) left retained text without its original scores; remaining scores describe whole original tokens only. False (the default, "complete") does not promise the provider supplied scores at all.

func ApplyClientSideStop added in v1.0.1

func ApplyClientSideStop(response *Response, stop []string) *Response

ApplyClientSideStop cuts the response's visible text at the first stop sequence. The text parts are one stream in document order: a sequence that starts at the end of one part and finishes at the start of the next is a hit. The part holding the start is cut there; every later part is removed. Scores follow the rule above.

func MaterializeResponse

func MaterializeResponse(events iter.Seq2[StreamEvent, error], request *Request) (*Response, error)

MaterializeResponse consumes a complete stream, requiring a final end event.

func ResponseFromDict added in v1.0.1

func ResponseFromDict(d JSONObject) (*Response, error)

ResponseFromDict reads a response.

func ResponseFromOpenAIChat added in v1.0.1

func ResponseFromOpenAIChat(body JSONObject, model string, choice *int, responseFormat JSONObject) (*Response, error)

ResponseFromOpenAIChat reads a Chat Completions response body into a canonical Response (MAP-12 rule 9), under the openai-chat provider name. responseFormat (optional) is the request's, so a judgment answer folds into a DataPart (MAP-14 §3).

func (*Response) Citations added in v1.0.1

func (r *Response) Citations() []CitationPart

Citations returns the citation parts.

func (*Response) Data added in v1.0.1

func (r *Response) Data() any

Data is the answer of a judgment request: the DataPart's value. Falls back to the parsed JSON text of a plain structured-output response so Data reads the same on a wire that answered with text; nil when neither.

func (*Response) DataPart added in v1.0.1

func (r *Response) DataPart() (DataPart, bool)

DataPart returns the message's first data part, if any.

func (*Response) Expected added in v1.0.1

func (r *Response) Expected(field string) (float64, bool)

Expected is Σ p·i over an ordered judgment's levels (Jev's score); ok is false when the field has no distribution or its keys are not level indexes.

func (*Response) JSON added in v1.0.1

func (r *Response) JSON() any

JSON returns the parsed JSON text, or nil when parsing fails.

func (*Response) LogprobsComplete added in v1.0.1

func (r *Response) LogprobsComplete() bool

LogprobsComplete is the wire's spelling of !LogprobsIncomplete.

func (Response) MarshalJSON

func (r Response) MarshalJSON() ([]byte, error)

func (*Response) Method added in v1.0.1

func (r *Response) Method() string

Method is how the distributions were measured (JudgmentMethod), or "".

func (*Response) ParseJSON added in v1.0.1

func (r *Response) ParseJSON(out any) error

ParseJSON parses the response text as exact JSON.

func (*Response) Probabilities added in v1.0.1

func (r *Response) Probabilities() map[string]map[string]float64

Probabilities are the per-judgment distributions over the declared keys, or nil when none was measured (never a fabricated one).

func (*Response) Text

func (r *Response) Text() *string

Text is the visible answer text: the joined TextParts when the message holds only text, citation and thinking parts; nil otherwise.

func (*Response) TextOr added in v1.0.1

func (r *Response) TextOr(fallback string) string

TextOr returns Text() or the fallback.

func (*Response) ToolCalls

func (r *Response) ToolCalls() []ToolCallPart

ToolCalls returns the tool call parts.

func (*Response) UnmarshalJSON

func (r *Response) UnmarshalJSON(b []byte) error

func (*Response) Validate added in v1.0.1

func (r *Response) Validate() error

Validate checks INV-036.

type ResponseStream added in v1.0.1

type ResponseStream struct {

	// CleanupErrors are failures that followed the end event (a read error
	// while draining); the Response is complete regardless.
	CleanupErrors []error
	// contains filtered or unexported fields
}

ResponseStream is a lazy stream-backed assembler: iterate Text() or Events(), then Response() for the same Response Complete returns.

func NewResponseStream added in v1.0.1

func NewResponseStream(events iter.Seq2[StreamEvent, error], request *Request) *ResponseStream

NewResponseStream wraps a stream of canonical events.

func (*ResponseStream) Close added in v1.0.1

func (s *ResponseStream) Close() error

Close stops reading without draining. An unfinished stream has no complete response (MAP-3).

func (*ResponseStream) Events added in v1.0.1

func (s *ResponseStream) Events() iter.Seq2[StreamEvent, error]

Events yields the canonical events as they arrive.

func (*ResponseStream) Response added in v1.0.1

func (s *ResponseStream) Response() (*Response, error)

Response drains the stream (if needed) and returns the assembled Response.

func (*ResponseStream) Text added in v1.0.1

func (s *ResponseStream) Text() iter.Seq2[string, error]

Text yields text fragments as they arrive.

type RouteRule added in v1.0.1

type RouteRule struct {
	Prefix   string
	Provider string
	Note     string
}

RouteRule maps a model-id prefix to a provider.

type RouterConfig added in v1.0.1

type RouterConfig struct {
	Registry       *ModelRegistry
	Rules          []RouteRule       // nil = DefaultRules
	Env            map[string]string // nil = the process environment
	APIKeys        map[string]CredentialLike
	BaseURLs       map[string]string
	Settings       map[string]map[string]string
	Credentials    map[string]string
	Transport      Transport
	Timeouts       *Timeouts
	MaxConnections int
	Adaptations    string
	Providers      []ProviderDefinition
	// Auth is managed authentication (AUTH-15 mode B): its saved connections
	// supply the credential when no explicit APIKeys / Credentials entry
	// does. With it, environment keys, other tools' login files and the
	// machine's cloud identity are never consulted: a missing, expired,
	// rejected or signed-out connection is a typed AuthOperationError, never
	// a silent switch to a metered key. Keyless local servers still work
	// without a connection. It also routes the connection-only providers
	// (kimi-code, github-copilot).
	Auth *Auth
}

RouterConfig is everything the router consults. All explicit.

BaseURLs: a provider string → the address to send to: a proxy in front of OpenAI, a vLLM server on another port. On a cloud door (azure, bedrock, vertex) the entry is the endpoint root — what the console shows, a private endpoint, a gateway — and the door appends its own path (/openai/v1, /anthropic/v1) unless the URL already ends with it; the door's auth scheme, error mapping and doctor stay attached. Without an entry the vendor's own variable is read (AZURE_OPENAI_ENDPOINT, ANTHROPIC_FOUNDRY_BASE_URL, AWS_ENDPOINT_URL_BEDROCK_RUNTIME / AWS_ENDPOINT_URL), then the URL is built from Settings. With an endpoint, resource is not needed; region still is on AWS (it signs).

Credentials maps a cloud provider string → one named identity: "platform" (the machine's own), "workload" (the federated Kubernetes kind), "environment" (a service principal or static keys from env variables), "cli" (az / aws / gcloud sign-in). That rung only is used and the cloud's chain is not walked (AUTH-1, amended 2026-09-19). An APIKeys entry and a Credentials entry for one provider is refused.

Providers declares providers the registry does not list (DeclareChatProvider). They route like registry entries in every router built with this config and answer Resolution.Declared.

Timeouts and MaxConnections shape the one transport the router builds and shares across its LMs; defaults are the provider SDKs' (connect 10 s, read/write/pool 600 s, 100 connections). Transport replaces that transport with one you built; it cannot be combined with the two knobs.

Adaptations is the MAP-13 policy every LM the router builds runs under: "note" (default), "silent", "refuse".

func (RouterConfig) Validate added in v1.0.1

func (c RouterConfig) Validate() error

Validate checks the config's own consistency (the provider-keyed maps are checked by NewRouterWithConfig).

type RunFunc added in v1.0.1

type RunFunc func(argv []string, timeout time.Duration) (string, error)

RunFunc runs a CLI and returns its stdout.

type Rung added in v1.0.1

type Rung struct {
	Name    string // the fixture kind: "env:AWS_REGION", "assume-role", "imds", …
	Kind    string // RungKinds
	Source  string
	Needs   string                               // "" | "network" | "subprocess"
	Probe   func(*ChainContext) (string, string) // ("usable"|"configured"|"absent", detail)
	Acquire func(*ChainContext) (Credential, error)
}

Rung is one step of a chain.

func ChainFor added in v1.0.1

func ChainFor(policy AccessPolicy) ([]Rung, error)

ChainFor returns the rungs of a cloud chain policy.

func NamedRungsFor added in v1.0.1

func NamedRungsFor(policy AccessPolicy, name string) ([]Rung, error)

NamedRungsFor is the rungs a named credential covers on this door, in chain order. An unknown name fails here, at construction.

type ScoreLevel added in v1.0.1

type ScoreLevel struct {
	Name        string
	Description string
}

ScoreLevel is one level of a Score judgment, low → high.

type SelectOption

type SelectOption struct {
	ID          string
	Label       string
	Description string
}

SelectOption is one choice of a select field or prompt.

type SpeechGenerationRequest added in v1.0.1

type SpeechGenerationRequest struct {
	Model      string
	Prompt     string
	Voice      string
	Format     string
	Extensions JSONObject
}

SpeechGenerationRequest is text-to-speech. Omitted voice/format mean the server's defaults.

func SpeechGenerationRequestFromDict added in v1.0.1

func SpeechGenerationRequestFromDict(d JSONObject) (SpeechGenerationRequest, error)

SpeechGenerationRequestFromDict reads a speech request.

func (SpeechGenerationRequest) Validate added in v1.0.1

func (r SpeechGenerationRequest) Validate() error

Validate checks the request.

type SpeechGenerationResponse added in v1.0.1

type SpeechGenerationResponse struct {
	Audio        AudioPart
	ID           string
	Model        string
	Usage        Usage
	ProviderData JSONObject
}

SpeechGenerationResponse carries the synthesized audio.

func SpeechGenerationResponseFromDict added in v1.0.1

func SpeechGenerationResponseFromDict(d JSONObject) (SpeechGenerationResponse, error)

SpeechGenerationResponseFromDict reads a speech response.

func (SpeechGenerationResponse) Validate added in v1.0.1

func (r SpeechGenerationResponse) Validate() error

Validate checks the response.

type StaticCredential added in v1.0.1

type StaticCredential struct{ Value Credential }

StaticCredential wraps a fixed credential as a provider.

func (StaticCredential) Credential added in v1.0.1

func (s StaticCredential) Credential(context.Context) (Credential, error)

Credential implements CredentialProvider.

func (StaticCredential) String added in v1.0.1

func (s StaticCredential) String() string

String redacts.

type Store

type Store interface {
	// Description is where it lives, for people ("memory", a path). Never contents.
	Description() string
	// Read is a private copy of the whole document, unlocked: for status and selection.
	Read() (JSONObject, error)
	// Lock takes exclusive access (cross-process where the backend can).
	Lock(ctx context.Context) (StoreGuard, error)
	// Reserve proves the store can be written before any external authorization starts (AUTH-17).
	Reserve(ctx context.Context) error
}

Store is the document contract every store implements (file, memory, an application's own).

type StoreGuard

type StoreGuard interface {
	Read() (JSONObject, error)
	Write(document JSONObject) error
	Unlock()
}

StoreGuard is the store, locked: Read is the document now; Write replaces it durably (a guard may write more than once, AUTH-20.4). Unlock releases.

type StreamAccumulator added in v1.0.1

type StreamAccumulator struct {
	// contains filtered or unexported fields
}

StreamAccumulator folds canonical stream events into a Response (MAP-9).

func NewStreamAccumulator added in v1.0.1

func NewStreamAccumulator(request *Request) *StreamAccumulator

NewStreamAccumulator creates an accumulator for a request.

func (*StreamAccumulator) Push added in v1.0.1

func (a *StreamAccumulator) Push(event StreamEvent)

Push folds one event. Error events are ignored (the caller decides).

func (*StreamAccumulator) Response added in v1.0.1

func (a *StreamAccumulator) Response() (*Response, error)

Response builds the Response, or a StreamAssemblyError when a tool call never carried a name (MAP-9); the error carries the partial.

type StreamDeltaEvent

type StreamDeltaEvent struct{ Delta Delta }

StreamDeltaEvent carries a typed delta.

func (StreamDeltaEvent) MarshalJSON

func (e StreamDeltaEvent) MarshalJSON() ([]byte, error)

func (StreamDeltaEvent) Type added in v1.0.1

func (StreamDeltaEvent) Type() string

func (StreamDeltaEvent) Validate added in v1.0.1

func (e StreamDeltaEvent) Validate() error

type StreamEndEvent

type StreamEndEvent struct {
	FinishReason string
	Usage        *Usage
	ProviderData JSONObject
}

StreamEndEvent closes a stream (exactly one, final, MAP-3).

func (StreamEndEvent) MarshalJSON

func (e StreamEndEvent) MarshalJSON() ([]byte, error)

func (StreamEndEvent) Type added in v1.0.1

func (StreamEndEvent) Type() string

func (StreamEndEvent) Validate added in v1.0.1

func (e StreamEndEvent) Validate() error

type StreamErrorEvent

type StreamErrorEvent struct{ Error ErrorDetail }

StreamErrorEvent reports a failure.

func (StreamErrorEvent) MarshalJSON

func (e StreamErrorEvent) MarshalJSON() ([]byte, error)

func (StreamErrorEvent) Type added in v1.0.1

func (StreamErrorEvent) Type() string

func (StreamErrorEvent) Validate added in v1.0.1

func (e StreamErrorEvent) Validate() error

type StreamEvent

type StreamEvent interface {
	Type() string
	Validate() error
	// contains filtered or unexported methods
}

StreamEvent is one of StreamStartEvent, StreamDeltaEvent, StreamEndEvent, StreamErrorEvent.

func ParseStreamBody added in v1.0.1

func ParseStreamBody(lm LM, req *Request, body []byte) ([]StreamEvent, error)

ParseStreamBody replays an SSE body through the adapter and the coalescer: the canonical post-coalesce event trace.

func ResponseToEvents added in v1.0.1

func ResponseToEvents(r *Response) ([]StreamEvent, error)

ResponseToEvents converts a Response to stream events (lossless for the Delta vocabulary; a non-streamable part is an error).

func StreamEventFromDict added in v1.0.1

func StreamEventFromDict(d JSONObject) (StreamEvent, error)

StreamEventFromDict reads a stream event.

type StreamStartEvent

type StreamStartEvent struct {
	ID          string
	Model       string
	Adaptations []Adaptation
}

StreamStartEvent opens a stream (exactly one, MAP-4). Adaptations (MAP-13) is what the wire got that differs from what was asked, known before the first byte and so carried by the first event.

func (StreamStartEvent) MarshalJSON

func (e StreamStartEvent) MarshalJSON() ([]byte, error)

func (StreamStartEvent) Type added in v1.0.1

func (StreamStartEvent) Type() string

func (StreamStartEvent) Validate added in v1.0.1

func (e StreamStartEvent) Validate() error

type SystemPrompt added in v1.0.1

type SystemPrompt struct {
	// contains filtered or unexported fields
}

SystemPrompt is a system instruction: a string, or prompt parts.

func System added in v1.0.1

func System(text string) *SystemPrompt

System creates a text system prompt.

func SystemParts added in v1.0.1

func SystemParts(parts ...Part) *SystemPrompt

SystemParts creates a system prompt from prompt parts.

func (*SystemPrompt) IsText added in v1.0.1

func (s *SystemPrompt) IsText() bool

IsText reports whether the prompt is the string form.

func (*SystemPrompt) Parts added in v1.0.1

func (s *SystemPrompt) Parts() []Part

Parts returns the parts form (nil for the string form).

func (*SystemPrompt) Text added in v1.0.1

func (s *SystemPrompt) Text() string

Text returns the string form ("" for the parts form).

func (*SystemPrompt) Validate added in v1.0.1

func (s *SystemPrompt) Validate() error

Validate checks INV-024 and the non-empty string rule.

type TerminalUI

type TerminalUI struct {
	OpenBrowser bool
	// contains filtered or unexported fields
}

TerminalUI prompts on the process's terminal.

func InteractiveTerminalUI

func InteractiveTerminalUI(openBrowser bool) *TerminalUI

InteractiveTerminalUI is a TerminalUI when stdin and stderr are both terminals, else nil (AUTH-23: never prompt a server).

func (*TerminalUI) Notify

func (t *TerminalUI) Notify(n Notice)

Notify prints the notice.

func (*TerminalUI) Prompt

func (t *TerminalUI) Prompt(ctx context.Context, p Prompt) (string, error)

Prompt asks on the terminal.

type TextDelta

type TextDelta struct {
	Text               string
	PartIndex          int
	Logprobs           []TokenLogprob
	LogprobsIncomplete bool
}

TextDelta is a text fragment (with the fragment's own logprobs when streamed). LogprobsIncomplete (wire logprobs_complete=false) means local text editing removed scores that cannot describe the retained text (a stop inside a token); scores always describe original, whole provider tokens. Materialization ANDs the flag across text events.

func (TextDelta) MarshalJSON

func (d TextDelta) MarshalJSON() ([]byte, error)

func (TextDelta) Type added in v1.0.1

func (TextDelta) Type() string

func (TextDelta) Validate added in v1.0.1

func (d TextDelta) Validate() error

type TextPart

type TextPart struct {
	Text         string
	Continuation []ContinuationState
}

TextPart is a block of text.

func Text

func Text(content string) TextPart

Text creates a text part.

func (TextPart) ContinuationStates added in v1.0.1

func (p TextPart) ContinuationStates() []ContinuationState

func (TextPart) MarshalJSON

func (p TextPart) MarshalJSON() ([]byte, error)

MarshalJSON on every part variant.

func (TextPart) Type added in v1.0.1

func (TextPart) Type() string

func (TextPart) Validate added in v1.0.1

func (p TextPart) Validate() error

Validate implements Part.

func (TextPart) WithContinuation added in v1.0.1

func (p TextPart) WithContinuation(c []ContinuationState) Part

type ThinkingDelta

type ThinkingDelta struct {
	Text      string
	PartIndex int
}

ThinkingDelta is a reasoning fragment.

func (ThinkingDelta) MarshalJSON

func (d ThinkingDelta) MarshalJSON() ([]byte, error)

func (ThinkingDelta) Type added in v1.0.1

func (ThinkingDelta) Type() string

func (ThinkingDelta) Validate added in v1.0.1

func (d ThinkingDelta) Validate() error

type ThinkingPart

type ThinkingPart struct {
	Text         string
	Continuation []ContinuationState
}

ThinkingPart is a model reasoning trace. Hidden thinking is empty Text with replay state in Continuation (MAP-7 rule 11).

func Thinking added in v1.0.1

func Thinking(content string) ThinkingPart

Thinking creates a thinking part.

func (ThinkingPart) ContinuationStates added in v1.0.1

func (p ThinkingPart) ContinuationStates() []ContinuationState

func (ThinkingPart) MarshalJSON

func (p ThinkingPart) MarshalJSON() ([]byte, error)

func (ThinkingPart) Type added in v1.0.1

func (ThinkingPart) Type() string

func (ThinkingPart) Validate added in v1.0.1

func (p ThinkingPart) Validate() error

Validate implements Part.

func (ThinkingPart) WithContinuation added in v1.0.1

func (p ThinkingPart) WithContinuation(c []ContinuationState) Part

type Timeouts added in v1.0.1

type Timeouts struct {
	Connect time.Duration
	Read    time.Duration
	Write   time.Duration
	Pool    time.Duration
}

Timeouts is how long to wait at each step of a request. Defaults follow the provider SDKs, not general-purpose HTTP clients: a model that thinks for minutes before its first byte is ordinary, and a client that gives up at 60 s turns that into a "network failure" and, under a retry loop, restarts the generation each time. Every timeout is per operation, not per request: Read bounds the wait for the NEXT byte, so a slow stream that keeps trickling never times out.

  • Connect: TCP + TLS to the host.
  • Read: the next byte of the reply — headers first, then each chunk.
  • Write: sending the request bytes.
  • Pool: a free connection when MaxConnections are all busy (0 waits).

A zero field takes the default; negative is refused.

func DefaultTimeouts added in v1.0.1

func DefaultTimeouts() Timeouts

DefaultTimeouts are the provider SDKs' defaults.

func (Timeouts) Validate added in v1.0.1

func (t Timeouts) Validate() error

Validate refuses negative values.

type TokenLogprob added in v1.0.1

type TokenLogprob struct {
	Token   string
	Logprob float64
	Bytes   []int
	TokenID *int
	Top     []TopLogprob
}

TokenLogprob is the chosen token at one decoding step with alternatives.

func TokenLogprobFromDict added in v1.0.1

func TokenLogprobFromDict(d JSONObject) (TokenLogprob, error)

TokenLogprobFromDict reads a token logprob.

func (TokenLogprob) MarshalJSON added in v1.0.1

func (t TokenLogprob) MarshalJSON() ([]byte, error)

func (TokenLogprob) Validate added in v1.0.1

func (t TokenLogprob) Validate() error

Validate implements the constraints.

type Tool

type Tool interface {
	ToolName() string
	Validate() error
	// contains filtered or unexported methods
}

Tool is FunctionTool or BuiltinTool.

func ToolFromDict added in v1.0.1

func ToolFromDict(d JSONObject) (Tool, error)

ToolFromDict reads a tool (INV-034 dispatch).

type ToolCallDelta

type ToolCallDelta struct {
	Input     string
	PartIndex int
	ID        string
	Name      string
}

ToolCallDelta is a tool-call input fragment, optionally carrying identity.

func (ToolCallDelta) MarshalJSON

func (d ToolCallDelta) MarshalJSON() ([]byte, error)

func (ToolCallDelta) Type added in v1.0.1

func (ToolCallDelta) Type() string

func (ToolCallDelta) Validate added in v1.0.1

func (d ToolCallDelta) Validate() error

type ToolCallInfo

type ToolCallInfo struct {
	ID    string
	Name  string
	Input JSONObject
}

ToolCallInfo is the callback view of a tool call (no discriminator).

func ToolCallInfoFrom added in v1.0.1

func ToolCallInfoFrom(p ToolCallPart) ToolCallInfo

ToolCallInfoFrom builds the info from a part.

func (ToolCallInfo) ToPart

func (t ToolCallInfo) ToPart() ToolCallPart

ToPart converts back to a ToolCallPart.

type ToolCallPart

type ToolCallPart struct {
	ID           string
	Name         string
	Input        JSONObject
	Continuation []ContinuationState
}

ToolCallPart is the model's request for an external computation.

func ToolCall added in v1.0.1

func ToolCall(id, name string, input JSONObject) ToolCallPart

ToolCall creates a tool call part.

func (ToolCallPart) ContinuationStates added in v1.0.1

func (p ToolCallPart) ContinuationStates() []ContinuationState

func (ToolCallPart) MarshalJSON

func (p ToolCallPart) MarshalJSON() ([]byte, error)

func (ToolCallPart) Type added in v1.0.1

func (ToolCallPart) Type() string

func (ToolCallPart) Validate added in v1.0.1

func (p ToolCallPart) Validate() error

Validate implements Part.

func (ToolCallPart) WithContinuation added in v1.0.1

func (p ToolCallPart) WithContinuation(c []ContinuationState) Part

type ToolChoice

type ToolChoice struct {
	Mode     string
	Allowed  []string
	Parallel *bool
}

ToolChoice says how the model should use tools. Mode "" reads as "auto".

func ToolChoiceFrom added in v1.0.1

func ToolChoiceFrom(mode string, tools ...Tool) ToolChoice

ToolChoiceFrom builds a choice from tools or names.

func ToolChoiceFromDict added in v1.0.1

func ToolChoiceFromDict(d JSONObject) (ToolChoice, error)

ToolChoiceFromDict reads a tool choice (INV-045 mode → auto).

func (ToolChoice) EffectiveMode added in v1.0.1

func (t ToolChoice) EffectiveMode() string

EffectiveMode returns Mode, or "auto" when unset.

func (ToolChoice) MarshalJSON added in v1.0.1

func (t ToolChoice) MarshalJSON() ([]byte, error)

func (ToolChoice) Validate added in v1.0.1

func (t ToolChoice) Validate() error

Validate checks INV-028.

type ToolResultPart

type ToolResultPart struct {
	ID           string
	Content      []Part
	Name         string
	IsError      bool
	Continuation []ContinuationState
}

ToolResultPart is the result of an external computation, sent back.

func ToolError added in v1.0.1

func ToolError(id, output string) ToolResultPart

ToolError creates an error tool result.

func ToolResult

func ToolResult(id, output string) ToolResultPart

ToolResult creates a tool result carrying one text part.

func ToolResultParts added in v1.0.1

func ToolResultParts(id string, content ...Part) ToolResultPart

ToolResultParts creates a tool result from parts.

func (ToolResultPart) ContinuationStates added in v1.0.1

func (p ToolResultPart) ContinuationStates() []ContinuationState

func (ToolResultPart) MarshalJSON

func (p ToolResultPart) MarshalJSON() ([]byte, error)

func (ToolResultPart) Type added in v1.0.1

func (ToolResultPart) Type() string

func (ToolResultPart) Validate added in v1.0.1

func (p ToolResultPart) Validate() error

Validate implements Part (INV-013, INV-014).

func (ToolResultPart) WithContinuation added in v1.0.1

func (p ToolResultPart) WithContinuation(c []ContinuationState) Part

type TopLogprob added in v1.0.1

type TopLogprob struct {
	Token   string
	Logprob float64
	Bytes   []int
	TokenID *int
}

TopLogprob is one scored alternative token at a decoding step.

func (TopLogprob) Validate added in v1.0.1

func (t TopLogprob) Validate() error

Validate implements the constraints.

type Transport added in v1.0.1

type Transport interface {
	Do(ctx context.Context, req *TransportRequest) (*TransportResponse, error)
}

Transport sends wire requests. The default is net/http; on js/wasm Go's net/http rides the browser's fetch, so the same transport works there.

type TransportRequest

type TransportRequest struct {
	Method         string
	URL            string
	Headers        [][2]string
	Body           []byte
	ConnectTimeout time.Duration // 0 = the transport's
	ReadTimeout    time.Duration // 0 = the transport's
}

TransportRequest is a finished wire request: method, URL (query included), ordered headers, body. Dialects produce it; a Transport sends it.

func (*TransportRequest) Header added in v1.0.1

func (r *TransportRequest) Header(name string) string

Header returns the first header value with this name (case-insensitive).

func (*TransportRequest) SetHeader added in v1.0.1

func (r *TransportRequest) SetHeader(name, value string)

SetHeader replaces or appends a header (case-insensitive).

type TransportResponse added in v1.0.1

type TransportResponse struct {
	Status  int
	Reason  string
	Headers [][2]string
	Body    io.ReadCloser
}

TransportResponse is a streaming HTTP response. Body is the DECODED body: a Content-Encoding the transport can inflate has been inflated (INV-053).

func (*TransportResponse) Header added in v1.0.1

func (r *TransportResponse) Header(name string) string

Header returns the first header value with this name.

type Turn added in v1.0.1

type Turn struct {
	EndedBy        string // turn_end | interrupted | error | tool_call | incomplete
	Text           string
	Audio          []byte
	AudioMediaType string
	ToolCalls      []ToolCallInfo
	Usage          *Usage
	Error          *ErrorDetail
	Events         []LiveServerEvent
}

Turn is one materialized live turn (LIVE-1, LIVE-2).

func MaterializeTurn added in v1.0.1

func MaterializeTurn(events []LiveServerEvent) *Turn

MaterializeTurn collects events into a Turn.

func (*Turn) OK added in v1.0.1

func (t *Turn) OK() bool

OK reports whether the turn ended normally.

type TurnLimits added in v1.0.1

type TurnLimits struct {
	MaxBytes  int
	MaxEvents int
}

TurnLimits bounds one turn view's collection: MaxBytes charges the compact ASCII JSON of every accepted canonical event; MaxEvents counts them. Zero takes the default; both must be positive.

type TurnView added in v1.0.1

type TurnView struct {
	// contains filtered or unexported fields
}

TurnView collects one turn under a budget. Iterate with Next until ok is false, or call Result for the materialized Turn; both stop at the turn's boundary (turn_end, interrupted, error) or a tool_call the caller must answer (LIVE-1). A view that overflowed is sealed: every later call returns the same CollectionLimitError, even after Close. Closing a view never closes the session.

func NewTurnView added in v1.0.1

func NewTurnView(source eventSource, limits TurnLimits) (*TurnView, error)

NewTurnView creates a view over a session (or any event source) with the given limits (zero fields take the defaults).

func (*TurnView) Close added in v1.0.1

func (v *TurnView) Close() error

Close seals the view; it never closes the session.

func (*TurnView) Events added in v1.0.1

func (v *TurnView) Events() []LiveServerEvent

Events are the accepted events so far, in order.

func (*TurnView) Next added in v1.0.1

func (v *TurnView) Next(ctx context.Context) (event LiveServerEvent, ok bool, err error)

Next receives one event under the budget. ok is false at the turn's boundary (after the boundary event itself was returned) or on failure.

func (*TurnView) Result added in v1.0.1

func (v *TurnView) Result(ctx context.Context) (*Turn, error)

Result drains the view to the turn's boundary and returns the Turn (the same one on repeat).

func (*TurnView) RetainedBytes added in v1.0.1

func (v *TurnView) RetainedBytes() int

RetainedBytes is the byte charge of the accepted events.

func (*TurnView) Snapshot added in v1.0.1

func (v *TurnView) Snapshot() *Turn

Snapshot materializes the accepted events so far, on demand, as an incomplete Turn (ok=false) unless the boundary was reached.

type TypeSafeLM added in v1.0.1

type TypeSafeLM struct {
	// contains filtered or unexported fields
}

TypeSafeLM is the TypeSafe System One dialect (POST /v1/systemone).

func NewTypeSafeLM added in v1.0.1

func NewTypeSafeLM(opts ...Option) (*TypeSafeLM, error)

NewTypeSafeLM constructs the typesafe adapter.

func (*TypeSafeLM) Access added in v1.0.1

func (c *TypeSafeLM) Access() AccessPolicy

Access returns the bound access policy.

func (*TypeSafeLM) AccountID added in v1.0.1

func (c *TypeSafeLM) AccountID() string

AccountID returns the account id the credential carries (Codex).

func (*TypeSafeLM) Adaptations added in v1.0.1

func (c *TypeSafeLM) Adaptations() string

Adaptations returns the MAP-13 policy ("note", "silent", "refuse").

func (*TypeSafeLM) BaseURL added in v1.0.1

func (c *TypeSafeLM) BaseURL() string

BaseURL returns the base URL.

func (*TypeSafeLM) Batch added in v1.0.1

func (c *TypeSafeLM) Batch(ctx context.Context, req *BatchRequest) (*BatchJob, error)

Batch submits and wraps the ticket in a handle.

func (*TypeSafeLM) BatchCancel added in v1.0.1

func (c *TypeSafeLM) BatchCancel(ctx context.Context, batchID string) (BatchJobInfo, error)

func (*TypeSafeLM) BatchJob added in v1.0.1

func (c *TypeSafeLM) BatchJob(ctx context.Context, batchID string) (*BatchJob, error)

BatchJob re-attaches to a job by id.

func (*TypeSafeLM) BatchList added in v1.0.1

func (c *TypeSafeLM) BatchList(ctx context.Context, limit int) ([]BatchJobInfo, error)

func (*TypeSafeLM) BatchResults added in v1.0.1

func (c *TypeSafeLM) BatchResults(ctx context.Context, batchID string) ([]BatchEntry, error)

func (*TypeSafeLM) BatchStatus added in v1.0.1

func (c *TypeSafeLM) BatchStatus(ctx context.Context, batchID string) (BatchJobInfo, error)

func (*TypeSafeLM) BatchSubmit added in v1.0.1

func (c *TypeSafeLM) BatchSubmit(ctx context.Context, req *BatchRequest) (BatchJobInfo, error)

func (*TypeSafeLM) Batches added in v1.0.1

func (c *TypeSafeLM) Batches(ctx context.Context, limit int) ([]*BatchJob, error)

Batches lists this credential's jobs as handles.

func (*TypeSafeLM) Build added in v1.0.1

func (c *TypeSafeLM) Build(req *Request, stream bool) (*TransportRequest, []Adaptation, error)

Build is BuildRequest with the MAP-13 record of what the build adapted.

func (*TypeSafeLM) BuildRequest added in v1.0.1

func (c *TypeSafeLM) BuildRequest(req *Request, stream bool) (*TransportRequest, error)

BuildRequest builds the wire request (pure apart from the credential call).

func (*TypeSafeLM) Cache added in v1.0.1

func (c *TypeSafeLM) Cache(ctx context.Context, prefix *Request, ttlSeconds *int, label string) (CachedPrefix, error)

Cache makes a prompt beginning reusable with the best tier the provider has.

func (*TypeSafeLM) CacheCreate added in v1.0.1

func (c *TypeSafeLM) CacheCreate(ctx context.Context, prefix *Request, ttlSeconds *int, label string) (CacheInfo, error)

func (*TypeSafeLM) CacheDelete added in v1.0.1

func (c *TypeSafeLM) CacheDelete(ctx context.Context, cacheID string) error

func (*TypeSafeLM) CacheGet added in v1.0.1

func (c *TypeSafeLM) CacheGet(ctx context.Context, cacheID string) (CacheInfo, error)

func (*TypeSafeLM) CacheList added in v1.0.1

func (c *TypeSafeLM) CacheList(ctx context.Context, limit int, cursor string) (CachePage, error)

func (*TypeSafeLM) CacheUpdate added in v1.0.1

func (c *TypeSafeLM) CacheUpdate(ctx context.Context, cacheID string, ttlSeconds int) (CacheInfo, error)

func (*TypeSafeLM) Close added in v1.0.1

func (c *TypeSafeLM) Close() error

Close releases the transport.

func (*TypeSafeLM) Complete added in v1.0.1

func (c *TypeSafeLM) Complete(ctx context.Context, req *Request) (*Response, error)

Complete performs one call.

func (*TypeSafeLM) CredentialOrigin added in v1.0.1

func (c *TypeSafeLM) CredentialOrigin() string

CredentialOrigin says where this adapter's credential comes from (AUTH-1 provenance): a label, never the value. For a cloud chain provider this is the rung that last won, or what will be walked when no request has been sent yet.

func (*TypeSafeLM) CredentialSource added in v1.0.1

func (c *TypeSafeLM) CredentialSource() *CredentialSource

CredentialSource is the provenance of a cloud chain credential after its first resolution (nil for a key, a stored login, or before any request).

func (*TypeSafeLM) Endpoint added in v1.0.1

func (c *TypeSafeLM) Endpoint() string

Endpoint is the endpoint root a cloud door was given ("" = the template).

func (*TypeSafeLM) FileDelete added in v1.0.1

func (c *TypeSafeLM) FileDelete(ctx context.Context, fileID string) error

func (*TypeSafeLM) FileDownload added in v1.0.1

func (c *TypeSafeLM) FileDownload(ctx context.Context, fileID string) ([]byte, error)

func (*TypeSafeLM) FileGet added in v1.0.1

func (c *TypeSafeLM) FileGet(ctx context.Context, fileID string) (FileInfo, error)

func (*TypeSafeLM) FileList added in v1.0.1

func (c *TypeSafeLM) FileList(ctx context.Context, limit int, cursor string) (FilePage, error)

func (*TypeSafeLM) FileUpload added in v1.0.1

func (c *TypeSafeLM) FileUpload(ctx context.Context, req *FileUploadRequest) (FileInfo, error)

func (*TypeSafeLM) FileWaitReady added in v1.0.1

func (c *TypeSafeLM) FileWaitReady(ctx context.Context, fileID string, pollEvery time.Duration) (FileInfo, error)

FileWaitReady polls until the file leaves pending (ctx bounds the wait).

func (*TypeSafeLM) HostSettings added in v1.0.1

func (c *TypeSafeLM) HostSettings() map[string]string

HostSettings returns the resolved host settings.

func (*TypeSafeLM) ImageGenerate added in v1.0.1

func (c *TypeSafeLM) ImageGenerate(ctx context.Context, req *ImageGenerationRequest) (ImageGenerationResponse, error)

func (*TypeSafeLM) ListModels added in v1.0.1

func (c *TypeSafeLM) ListModels(ctx context.Context) ([]ModelInfo, error)

ListModels fetches the models this credential can use.

func (*TypeSafeLM) Live added in v1.0.1

func (c *TypeSafeLM) Live(ctx context.Context, config *LiveConfig) (LiveSession, error)

Live opens a live session (dialects with the surface override live()).

func (*TypeSafeLM) LiveDecode added in v1.0.1

func (c *TypeSafeLM) LiveDecode(raw []byte) ([]LiveServerEvent, error)

func (*TypeSafeLM) LiveEncoder added in v1.0.1

func (c *TypeSafeLM) LiveEncoder(config *LiveConfig) func(LiveClientEvent) ([]JSONObject, error)

func (*TypeSafeLM) LiveSetupFrames added in v1.0.1

func (c *TypeSafeLM) LiveSetupFrames(config *LiveConfig) ([]JSONObject, error)

LiveSetupFrames / LiveEncoder / LiveDecode expose the pure live codec.

func (*TypeSafeLM) NormalizeError added in v1.0.1

func (c *TypeSafeLM) NormalizeError(status int, body string) *Error

NormalizeError maps an HTTP failure body to a typed error (dialects override).

func (*TypeSafeLM) ParseResponse added in v1.0.1

func (c *TypeSafeLM) ParseResponse(req *Request, resp *HTTPResponse) (*Response, error)

ParseResponse parses a complete body.

func (*TypeSafeLM) ParseStreamEvents added in v1.0.1

func (c *TypeSafeLM) ParseStreamEvents(req *Request, event sse.Event) ([]StreamEvent, error)

ParseStreamEvents parses one SSE event into canonical events.

func (*TypeSafeLM) Plan added in v1.0.1

func (c *TypeSafeLM) Plan(req *Request) ([]Adaptation, error)

Plan is what a call with this request WOULD adapt, with no network and no credential invoked (offline, like Resolve). It returns the refusal the call would return (under any policy, or every deviation under "refuse") and the FULL record under every policy, "silent" included: a preview that hid what it saw would be no preview.

func (*TypeSafeLM) Provider added in v1.0.1

func (c *TypeSafeLM) Provider() string

Provider returns the canonical provider string.

func (*TypeSafeLM) RequestFromOpenAIChat added in v1.0.1

func (c *TypeSafeLM) RequestFromOpenAIChat(body JSONObject) (*Request, error)

RequestFromOpenAIChat is MAP-12 (chat dialect only).

func (*TypeSafeLM) ResponseFromOpenAIChat added in v1.0.1

func (c *TypeSafeLM) ResponseFromOpenAIChat(body JSONObject, model string, choice *int, responseFormat JSONObject) (*Response, error)

ResponseFromOpenAIChat is MAP-12 rule 9 (chat dialect only).

func (*TypeSafeLM) SetCredentialOrigin added in v1.0.1

func (c *TypeSafeLM) SetCredentialOrigin(label string)

SetCredentialOrigin names the credential's source when the constructor could not know it (the router: an env variable, a placeholder key).

func (*TypeSafeLM) SpeechGenerate added in v1.0.1

func (c *TypeSafeLM) SpeechGenerate(ctx context.Context, req *SpeechGenerationRequest) (SpeechGenerationResponse, error)

func (*TypeSafeLM) Stream added in v1.0.1

func (c *TypeSafeLM) Stream(ctx context.Context, req *Request) iter.Seq2[StreamEvent, error]

Stream yields canonical events: exactly one start, deltas, exactly one final end (MAP-3 / MAP-4 via the coalescer).

func (*TypeSafeLM) Supports added in v1.0.1

func (c *TypeSafeLM) Supports() EndpointSupport

Supports returns the surfaces this access path carries.

func (*TypeSafeLM) VideoGenerate added in v1.0.1

func (c *TypeSafeLM) VideoGenerate(ctx context.Context, req *VideoGenerationRequest) (*VideoJob, error)

func (*TypeSafeLM) VideoJob added in v1.0.1

func (c *TypeSafeLM) VideoJob(ctx context.Context, videoID string) (*VideoJob, error)

func (*TypeSafeLM) VideoJobs added in v1.0.1

func (c *TypeSafeLM) VideoJobs(ctx context.Context, limit int, model string) ([]*VideoJob, error)

func (*TypeSafeLM) VideoList added in v1.0.1

func (c *TypeSafeLM) VideoList(ctx context.Context, limit int, model string) ([]VideoJobInfo, error)

func (*TypeSafeLM) VideoResult added in v1.0.1

func (c *TypeSafeLM) VideoResult(ctx context.Context, videoID string) (VideoPart, error)

func (*TypeSafeLM) VideoStatus added in v1.0.1

func (c *TypeSafeLM) VideoStatus(ctx context.Context, videoID string) (VideoJobInfo, error)

func (*TypeSafeLM) VideoSubmit added in v1.0.1

func (c *TypeSafeLM) VideoSubmit(ctx context.Context, req *VideoGenerationRequest) (VideoJobInfo, error)

type Usage

type Usage struct {
	InputTokens       *int
	OutputTokens      *int
	TotalTokens       *int
	CacheReadTokens   *int
	CacheWriteTokens  *int
	ReasoningTokens   *int
	InputAudioTokens  *int
	OutputAudioTokens *int
}

Usage carries provider-verbatim token counters. nil = not reported, distinct from a reported 0 (INV-029).

func SumUsage added in v1.0.1

func SumUsage(acc *Usage, more Usage) Usage

SumUsage is the field-wise sum; absent on either side stays absent (INV-029).

func UsageFromDict added in v1.0.1

func UsageFromDict(d JSONObject) (Usage, error)

UsageFromDict reads usage (total auto-computed per INV-029).

func (Usage) IsEmpty added in v1.0.1

func (u Usage) IsEmpty() bool

IsEmpty reports whether nothing was reported (serializes to {}).

func (Usage) MarshalJSON

func (u Usage) MarshalJSON() ([]byte, error)

func (Usage) Normalize added in v1.0.1

func (u Usage) Normalize() Usage

Normalize returns the Usage with total_tokens auto-computed when both primaries are present and no total was reported (INV-029).

func (*Usage) UnmarshalJSON

func (u *Usage) UnmarshalJSON(b []byte) error

func (Usage) Validate added in v1.0.1

func (u Usage) Validate() error

Validate checks every counter is >= 0.

type Verification

type Verification struct {
	Result    string // valid | rejected | unverified
	CheckedAt string
	Check     string
	Detail    string
}

Verification is the last explicit check of a connection.

type VideoGenerationRequest added in v1.0.1

type VideoGenerationRequest struct {
	Model      string
	Prompt     string
	Seconds    *int
	Images     []ImagePart
	Extensions JSONObject
}

VideoGenerationRequest submits a video job.

func VideoGenerationRequestFromDict added in v1.0.1

func VideoGenerationRequestFromDict(d JSONObject) (VideoGenerationRequest, error)

VideoGenerationRequestFromDict reads a video request.

func (VideoGenerationRequest) Validate added in v1.0.1

func (r VideoGenerationRequest) Validate() error

Validate checks the request.

type VideoJob added in v1.0.1

type VideoJob struct {
	// contains filtered or unexported fields
}

VideoJob is a live handle on one provider-side video job.

func (*VideoJob) Done added in v1.0.1

func (j *VideoJob) Done() bool

Done reports a terminal status.

func (*VideoJob) ID added in v1.0.1

func (j *VideoJob) ID() string

ID is the ticket.

func (*VideoJob) Info added in v1.0.1

func (j *VideoJob) Info() VideoJobInfo

Info is the snapshot from the last provider contact.

func (*VideoJob) Progress added in v1.0.1

func (j *VideoJob) Progress() *int

Progress is the last known percentage, if reported.

func (*VideoJob) Refresh added in v1.0.1

func (j *VideoJob) Refresh(ctx context.Context) (*VideoJob, error)

Refresh re-reads the job.

func (*VideoJob) Result added in v1.0.1

func (j *VideoJob) Result(ctx context.Context) (VideoPart, error)

Result fetches the finished video; it never implicitly waits.

func (*VideoJob) Status added in v1.0.1

func (j *VideoJob) Status() string

Status is the last known status.

func (*VideoJob) Wait added in v1.0.1

func (j *VideoJob) Wait(ctx context.Context, pollEvery time.Duration) (*VideoJob, error)

Wait polls until a terminal status (including failure); ctx bounds it.

type VideoJobInfo added in v1.0.1

type VideoJobInfo struct {
	ID           string
	Status       string
	Progress     *int
	CreatedAt    string
	Model        string
	ProviderData JSONObject
}

VideoJobInfo is the ticket of a video job.

func VideoJobFromDict added in v1.0.1

func VideoJobFromDict(d JSONObject) (VideoJobInfo, error)

VideoJobFromDict reads a video job snapshot.

func (VideoJobInfo) Done added in v1.0.1

func (j VideoJobInfo) Done() bool

Done reports a terminal status.

func (VideoJobInfo) Validate added in v1.0.1

func (j VideoJobInfo) Validate() error

Validate checks the snapshot.

type VideoPart

type VideoPart struct{ Media }

VideoPart is video content.

func Video added in v1.0.1

func Video(opts ...MediaOption) VideoPart

Video creates a video part (default media type video/mp4).

func (VideoPart) ContinuationStates added in v1.0.1

func (p VideoPart) ContinuationStates() []ContinuationState

func (VideoPart) MarshalJSON

func (p VideoPart) MarshalJSON() ([]byte, error)

func (VideoPart) Type added in v1.0.1

func (VideoPart) Type() string

func (VideoPart) Validate added in v1.0.1

func (p VideoPart) Validate() error

Validate implements Part.

func (VideoPart) WithContinuation added in v1.0.1

func (p VideoPart) WithContinuation(c []ContinuationState) Part

type XaiDeviceAuthorization added in v1.0.1

type XaiDeviceAuthorization struct {
	UserCode                string
	VerificationURI         string
	VerificationURIComplete string
	IntervalS               float64
	ExpiresInS              float64
	// contains filtered or unexported fields
}

XaiDeviceAuthorization is one pending device authorization.

func StartXaiDeviceLogin added in v1.0.1

func StartXaiDeviceLogin(ctx context.Context) (XaiDeviceAuthorization, error)

StartXaiDeviceLogin requests a device authorization.

func (XaiDeviceAuthorization) String added in v1.0.1

func (d XaiDeviceAuthorization) String() string

String hides the device code.

type XaiLM added in v1.0.1

type XaiLM = OpenAIChatLM

XaiLM is a name: OpenAIChatLM bound to lm15.Xai with the xai preset.

Directories

Path Synopsis
cmd
lm15-vet command
Command lm15-vet is the lm15 vet shim: newline-delimited JSON on stdin/stdout per lm15-contract/harness/PROTOCOL.md.
Command lm15-vet is the lm15 vet shim: newline-delimited JSON on stdin/stdout per lm15-contract/harness/PROTOCOL.md.
lm15-wasm command
lm15-wasm exposes the actual Go SDK to a browser worker through wasm_exec.js.
lm15-wasm exposes the actual Go SDK to a browser worker through wasm_exec.js.
examples
live_smoke command
Command live_smoke sends real requests through the Go port and records receipts.
Command live_smoke sends real requests through the Go port and records receipts.
internal
browserbridge
Package browserbridge is the JSON boundary for the browser's Go runtime.
Package browserbridge is the JSON boundary for the browser's Go runtime.
fslock
Package fslock is an advisory, cross-process, exclusive file lock with atomic private JSON writes (spec/auth.md AUTH-4).
Package fslock is an advisory, cross-process, exclusive file lock with atomic private JSON writes (spec/auth.md AUTH-4).
rs256
Package rs256 signs JWTs with RSASSA-PKCS1-v1_5 / SHA-256 using the platform RSA (crypto/rsa), and pins lm15's compact JWS serialization: compact JSON with keys in the caller's order, base64url without padding.
Package rs256 signs JWTs with RSASSA-PKCS1-v1_5 / SHA-256 using the platform RSA (crypto/rsa), and pins lm15's compact JWS serialization: compact JSON with keys in the caller's order, base64url without padding.
sigv4
Package sigv4 implements AWS Signature Version 4 (standard library only).
Package sigv4 implements AWS Signature Version 4 (standard library only).
sse
Package sse parses Server-Sent Events from a byte stream.
Package sse parses Server-Sent Events from a byte stream.
ws
Package ws is a minimal WebSocket client (RFC 6455) with no dependencies: a client handshake, masked text/binary frames, fragmentation, ping/pong, and the close handshake.
Package ws is a minimal WebSocket client (RFC 6455) with no dependencies: a client handshake, masked text/binary frames, fragmentation, ping/pong, and the close handshake.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL