Documentation
¶
Overview ¶
Package model captures provider requests and owns per-attempt model transport.
Foundry routing follows Goose 14741e9a. Apache-2.0; see LICENSE.goose.
Context discovery policy derived from Goose 14741e9a providers/openai.rs (Apache-2.0). See LICENSE.goose.
Request parameter policy is derived from Goose 14741e9a and rig-core 0.46.0. Apache-2.0; see LICENSE.goose and LICENSE.rig.
Chat schema adaptation derives from Goose 14741e9a through the reviewed Sailry adapter. Apache-2.0; see LICENSE.goose.
Request layouts derive from rig-core 0.46.0 and the reviewed Sailry wire adapter. MIT and Apache-2.0; see LICENSE.rig.
Inline thinking filter derived from Goose 14741e9a. Apache-2.0; see LICENSE.goose.
Index ¶
- Constants
- Variables
- func Answered(records []canonical.Record) []canonical.Record
- func ApplyPluginMetadata(block *canonical.Block, part fantasy.StreamPart) error
- func ApplyStreamMetadata(block *canonical.Block, part fantasy.StreamPart) error
- func AttachmentFileMIME(binding Binding, mime string) string
- func BuildCall(binding Binding, request Request) (fantasy.Call, error)
- func BuildPluginCall(binding Binding, request Request) (fantasy.Call, error)
- func BuildProjectedCall(binding Binding, request Request) (fantasy.Call, error)
- func BuildVisibleProjectedCall(binding Binding, request Request) (fantasy.Call, error)
- func CompactSession(ctx context.Context, languageModel fantasy.LanguageModel, call fantasy.Call) error
- func ContextLimit(binding Binding) uint32
- func DiscoverACP(ctx context.Context, binding Binding, capture ACPCapture) (protocol.ConversationDiscoveryCatalog, error)
- func DiscoverPlugin(ctx context.Context, binding Binding, capture PluginCapture) (protocol.ConversationDiscoveryCatalog, error)
- func Fault(err error) *protocol.Fault
- func InPlaceOutputLimit(binding Binding, want int64) int64
- func NativeCompactionRoute(languageModel fantasy.LanguageModel) string
- func New(ctx context.Context, binding Binding) (fantasy.LanguageModel, error)
- func NewACP(binding Binding, capture ACPCapture) (fantasy.LanguageModel, error)
- func NewPlugin(_ context.Context, binding Binding, capture PluginCapture) (fantasy.LanguageModel, error)
- func OutputLimit(binding Binding, summary bool) int64
- func PartIndex(part fantasy.StreamPart) (uint64, bool)
- func PartUsage(part fantasy.StreamPart) canonical.Usage
- func PluginBound(provider protocol.ConversationProvider) bool
- func PluginOutput(part fantasy.StreamPart) bool
- func PrepareNativeSearch(ctx context.Context, binding Binding, body map[string]any) (*http.Request, error)
- func ReadsImages(binding Binding) bool
- func ReplayPrefix(call fantasy.Call) string
- func ReplaysNative(binding Binding, record canonical.Record) bool
- func Run(ctx context.Context, languageModel fantasy.LanguageModel, call fantasy.Call, ...) error
- func Scope(binding Binding) canonical.ModelSource
- func SendsToolMedia(binding Binding, mime string, size uint64) bool
- func SetToolSchemas(call *fantasy.Call, schemas map[string]json.RawMessage)
- func StreamSources(part fantasy.StreamPart) (canonical.Sources, bool)
- func SummarySystemBytes(languageModel fantasy.LanguageModel, request string) int
- func VisibleAnsweredRecords(records []canonical.Record) []canonical.Record
- func VisibleRecords(records []canonical.Record) []canonical.Record
- type ACPCapture
- type Attempt
- type Binding
- type Compacted
- type Failure
- type FailureKind
- type MediaChannel
- type MediaOutput
- func GenerateImage(ctx context.Context, binding Binding, channel MediaChannel, prompt string) (MediaOutput, error)
- func GenerateVideo(ctx context.Context, binding Binding, prompt string, poll time.Duration) (MediaOutput, error)
- func ResumeVideo(ctx context.Context, binding Binding, job string, poll time.Duration) (MediaOutput, error)
- func SynthesizeSpeech(ctx context.Context, binding Binding, text, voice string) (MediaOutput, error)
- type PluginCapture
- type Purpose
- type Request
- type Route
- type Tool
- type UsageMetadata
Constants ¶
const ( MaxMediaImageBytes = 64 << 20 MaxMediaVideoBytes = 512 << 20 MaxMediaSpeechBytes = 8 << 20 // MaxSpeechCharacters is the input bound of the speech endpoint. MaxSpeechCharacters = 4096 // MediaVideoPoll is the production interval between video job reads. MediaVideoPoll = 5 * time.Second )
const MainRetries = 10
MainRetries bounds resends of one main or summary request. Both also share the request's cumulative wait budget, regardless of the transient cause.
const ( // MaxToolMediaBytes bounds one media item a tool result sends to a model. // It is the file-image bound and the per-image limit of the strictest API. MaxToolMediaBytes = 5 << 20 )
const UsageMetadataKey = "sailry.usage"
Variables ¶
var ErrNativeUnsupported = errors.New("native compaction is unsupported by this route")
ErrNativeUnsupported reports that the provider rejected the protocol feature itself: its endpoint, parameter or beta flag is unknown there.
var ErrNativeUnusable = errors.New("native compaction returned no usable result")
ErrNativeUnusable reports a completed native request without a usable result, such as a refused or empty summary.
Functions ¶
func Answered ¶
Answered repairs tool pairs among visible records without removing records from the input. It drops a result with no preceding unanswered call and any call with no result, so interrupted turns cannot invalidate later requests.
func ApplyPluginMetadata ¶
func ApplyPluginMetadata(block *canonical.Block, part fantasy.StreamPart) error
func ApplyStreamMetadata ¶
func ApplyStreamMetadata(block *canonical.Block, part fantasy.StreamPart) error
ApplyStreamMetadata is the provider-to-canonical carrier boundary. The engine owns text accumulation and slot identity; transport owns provider signatures.
func AttachmentFileMIME ¶ added in v0.2.4
AttachmentFileMIME selects the wire MIME for a byte-detected chat attachment. An adapter's generic file part or a gateway's fallback encoder does not establish that its downstream API understands that media.
func BuildProjectedCall ¶ added in v0.2.3
BuildProjectedCall consumes records filtered by output.Cache.Project and still selects which records are agent-visible.
func BuildVisibleProjectedCall ¶ added in v0.2.7
BuildVisibleProjectedCall consumes records selected and paired by VisibleAnsweredRecords and audience-filtered by output.Cache.Project.
func CompactSession ¶
func CompactSession(ctx context.Context, languageModel fantasy.LanguageModel, call fantasy.Call) error
CompactSession asks an agent session that holds the history to shrink its own context, after Sailry recorded its handoff. call is the next main request over the compacted history. The command is sent only where the session advertised it and the compacted history still shares messages the session has seen; afterwards the session counts those messages as seen, so the next request sends only what follows them. Otherwise nothing is sent and the next request starts a new session with the handoff.
func ContextLimit ¶
ContextLimit returns the context window of the bound model: the size its provider lists, else the size its server reported when the model was created, else the bundled catalog's size, else 128000. It performs no I/O.
func DiscoverACP ¶
func DiscoverACP(ctx context.Context, binding Binding, capture ACPCapture) (protocol.ConversationDiscoveryCatalog, error)
DiscoverACP lists the models the agent offers a new session. No prompt is sent. Variants the package declares as effort levels fold into one model; nothing is listed that the agent did not report.
func DiscoverPlugin ¶
func DiscoverPlugin(ctx context.Context, binding Binding, capture PluginCapture) (protocol.ConversationDiscoveryCatalog, error)
func InPlaceOutputLimit ¶
InPlaceOutputLimit is the output limit of a summary request that shares the main request's cached prefix. Anthropic caches thinking parameters with the messages, and a manual thinking budget follows max_tokens, so a limit that would change the main request's thinking grows by its budget, keeping the budget and room for want beside it, or else is the main request's own.
func NativeCompactionRoute ¶
func NativeCompactionRoute(languageModel fantasy.LanguageModel) string
NativeCompactionRoute names the protocol, endpoint and model whose native compaction a rejection disables, or "" when the route offers none. Package translations and agent programs have no native compaction here.
func NewACP ¶
func NewACP(binding Binding, capture ACPCapture) (fantasy.LanguageModel, error)
func NewPlugin ¶
func NewPlugin(_ context.Context, binding Binding, capture PluginCapture) (fantasy.LanguageModel, error)
func OutputLimit ¶
OutputLimit is the model's listed output limit, 0 when it lists none. A summary request asks for twice its handoff cap (compact.Output), which is 8,000 tokens for windows from 32,000 through 200,000, bounded by the model's limit. A model that lists none uses at most 8,000, still within the window's summary budget.
func PluginBound ¶
func PluginBound(provider protocol.ConversationProvider) bool
func PluginOutput ¶
func PluginOutput(part fantasy.StreamPart) bool
func PrepareNativeSearch ¶
func PrepareNativeSearch(ctx context.Context, binding Binding, body map[string]any) (*http.Request, error)
PrepareNativeSearch shares the captured model's authorization and declared request policies. Native search owns its input and tool fields.
func ReadsImages ¶
ReadsImages reports whether the bound model takes image input: its listed capability, or the provider's default for a model the provider does not list, bounded by the adapter's declared input capabilities.
func ReplayPrefix ¶
ReplayPrefix identifies the projected request that produced the next reply.
func ReplaysNative ¶
ReplaysNative reports whether a request for binding sends the checkpoint record's native items instead of its summary.
func Run ¶
func Run(ctx context.Context, languageModel fantasy.LanguageModel, call fantasy.Call, purpose Purpose, timer clock.Clock, observe func(Attempt) error, yield func(fantasy.StreamPart) bool, reset func()) error
Run uses reset to discard provisional output before replaying an interrupted attempt. Without it, main output that escaped to the consumer cannot be retried safely.
func Scope ¶
func Scope(binding Binding) canonical.ModelSource
func SendsToolMedia ¶
SendsToolMedia reports whether a request to the bound model carries a tool media item of this type and size.
func SetToolSchemas ¶
func SetToolSchemas(call *fantasy.Call, schemas map[string]json.RawMessage)
SetToolSchemas retains declaration order across Fantasy's map-only schema boundary.
func StreamSources ¶
func StreamSources(part fantasy.StreamPart) (canonical.Sources, bool)
StreamSources returns an independent provider source snapshot. Citation offsets remain provider character offsets; Store validates presentation ranges.
func SummarySystemBytes ¶
func SummarySystemBytes(languageModel fantasy.LanguageModel, request string) int
SummarySystemBytes accounts for the single summary message and ACP framing when the agent cannot carry system text separately. Zero means no byte cap.
func VisibleAnsweredRecords ¶ added in v0.2.7
VisibleAnsweredRecords selects the visible history and repairs its tool pairs.
Types ¶
type ACPCapture ¶
type ACPCapture struct {
Adapter protocol.PluginModelAdapterDeclaration
Program protocol.PluginProgramDeclaration
// Owner is the package; Dir is the program's directory in its data.
Owner, Dir, Version string
Host []string
Pool *program.Pool
// Sessions is the Node's directory for the records of which agent
// session holds each Sailry session (acp_session.go). Empty keeps none.
Sessions string
// contains filtered or unexported fields
}
ACPCapture is what the Node captured for one request to an agent program.
type Attempt ¶
type Attempt struct {
RequestID string
RequestStarted time.Time
Index uint64
Started time.Time
Finished time.Time
FirstToken *time.Time
Usage canonical.Usage
Failure *Failure
// RetryLimit is the last resend allowed if the current failure streak continues.
RetryLimit uint64
// RetryDelay is the wait before the next attempt; nil on the last attempt.
RetryDelay *time.Duration
Status *uint16
ResponseUs *uint64
RequestBytes *uint64
DispatchUs *uint64
RequestSentUs *uint64
Categories []protocol.ConversationObservationCategory
CompleteContext bool
ReasoningStreamed bool
ResponsesBoundary *protocol.ConversationResponsesBoundary
}
type Binding ¶
type Binding struct {
Provider protocol.ConversationProvider
Config protocol.SessionConfig
Secret *protocol.Secret
Session protocol.SessionID
}
type Compacted ¶
type Compacted struct {
Summary string
Native canonical.NativeCompaction
}
Compacted is the outcome of a native compaction. Summary is the provider's readable text, empty for an opaque window.
func CompactNative ¶
func CompactNative(ctx context.Context, languageModel fantasy.LanguageModel, binding Binding, call fantasy.Call, timer clock.Clock, observe func(Attempt) error) (Compacted, error)
CompactNative sends call, the main request over the history to replace, as the route's native compaction with the provider's own summary prompt. It follows Run's retry rules and reports each attempt to observe.
type Failure ¶
type Failure struct {
Kind FailureKind
Message string
// Exhausted marks only Run's terminal recovery outcome. Kind still names
// the provider failure, including when a summary records why it failed.
Exhausted bool
// WaitExhausted distinguishes the cumulative wait budget from the attempt limit.
WaitExhausted bool
// contains filtered or unexported fields
}
type FailureKind ¶
type FailureKind string
const ( NotConfigured FailureKind = "not_configured" Authentication FailureKind = "authentication" ContextOverflow FailureKind = "context_overflow" RateLimited FailureKind = "rate_limited" Quota FailureKind = "quota" Network FailureKind = "network" InvalidRequest FailureKind = "invalid_request" InvalidResponse FailureKind = "invalid_response" Unsupported FailureKind = "unsupported" Cancelled FailureKind = "cancelled" Other FailureKind = "other" )
type MediaChannel ¶
type MediaChannel string
MediaChannel names the provider endpoint that serves one media kind.
const ( // MediaChat sends an image part through the model's normal chat request. MediaChat MediaChannel = "chat" // MediaImages is the OpenAI-compatible POST /images/generations endpoint. MediaImages MediaChannel = "images" // MediaImageTool is the Responses API hosted image generation tool. MediaImageTool MediaChannel = "image_tool" // MediaGemini is Gemini's native generateContent image output. MediaGemini MediaChannel = "gemini" // MediaVideos is the OpenAI-compatible POST /videos job endpoint. MediaVideos MediaChannel = "videos" // MediaSpeech is the OpenAI-compatible POST /audio/speech endpoint. MediaSpeech MediaChannel = "speech" )
func MediaChannelFor ¶
func MediaChannelFor(kind protocol.MediaKind, provider protocol.ConversationProvider, entry protocol.ConversationModel) (MediaChannel, bool)
MediaChannelFor selects the channel driver for one media kind from the model's capability tags and its provider's API and authentication. A model without the tag, or on a channel without a driver, has no route.
type MediaOutput ¶
type MediaOutput struct {
Data []byte
MediaType string
Usage canonical.Usage
// Job identifies an accepted provider job that outlives a local stop.
Job string
// Ended reports that the provider ended Job without a video, so nothing
// remains to fetch.
Ended bool
}
MediaOutput is one generated asset and the usage its provider reported.
func GenerateImage ¶
func GenerateImage(ctx context.Context, binding Binding, channel MediaChannel, prompt string) (MediaOutput, error)
GenerateImage runs one image generation on the channel selected for the bound model and returns PNG bytes.
func GenerateVideo ¶
func GenerateVideo(ctx context.Context, binding Binding, prompt string, poll time.Duration) (MediaOutput, error)
GenerateVideo submits one OpenAI-compatible video job, waits for it and downloads the MP4. Stopping locally does not cancel an accepted job.
func ResumeVideo ¶
func ResumeVideo(ctx context.Context, binding Binding, job string, poll time.Duration) (MediaOutput, error)
ResumeVideo waits for a job an earlier call submitted and downloads its MP4. It never submits a job, so a prompt is not paid for twice.
func SynthesizeSpeech ¶
func SynthesizeSpeech(ctx context.Context, binding Binding, text, voice string) (MediaOutput, error)
SynthesizeSpeech reads text aloud through the OpenAI-compatible speech endpoint and returns MP3 audio.
type PluginCapture ¶
type PluginCapture struct {
User string
Declaration protocol.PluginModelAdapterDeclaration
Bundle plugins.ScriptBundle
Memory *plugins.MemoryTracker
Headers http.Header
Access *protocol.Secret
Key *protocol.Secret
Secrets []protocol.Secret
Client *http.Client
// Settings are the package's current public setting values, which its
// prepare and discovery exports receive.
Settings map[string]json.RawMessage
}
type Request ¶
type Request struct {
System string
Records []canonical.Record
Tools []Tool
ToolSchemas map[string]json.RawMessage
MaxOutputTokens *int64
Temperature *float64
Headers map[string]string
Assets map[string][]byte
// Delegated marks a request of a delegated session, which an account
// service counts as the agent's own.
Delegated bool
// contains filtered or unexported fields
}
type Route ¶
type Route struct {
// PromptBytes bounds the text of one prompt. Zero means no bound beside
// the model's window.
PromptBytes int
// Session reports that the transport keeps a conversation per Sailry
// session and sends it only the messages it has not seen. A request whose
// earlier history differs replays the whole history in one prompt.
Session bool
// Resident reports that such a conversation holds this session's history
// now, in a running program or one it can resume, so the next request
// sends only its new messages.
Resident bool
// Compact reports that the resident conversation advertises the agent's
// own `/compact` command (CompactSession).
Compact bool
// Native identifies the route and model whose protocol compacts the
// history itself (CompactNative); empty when it has no such method.
Native string
}
Route describes how a constructed model reaches its model, beyond the window its binding declares. The Node's model factory chooses the transport from the binding (provider SDK, package translation or agent program); the transport reports these facts. They do not move the compaction threshold, which follows the model's window and policy on every route: they shape how a compaction runs and how the compacted history is sized.
func RouteOf ¶
func RouteOf(languageModel fantasy.LanguageModel, session protocol.SessionID) Route
RouteOf reports the route of a model the factory constructed. A transport without a session or prompt bound has the zero Route.
func (Route) ReplayWindow ¶
ReplayWindow is the window of a history sent whole in one prompt: the model's window within the token equivalent of PromptBytes. A compacted history begins with its summary, which no agent session has seen, so it is always sent whole; its summary and retained tail are sized to fit.
type Tool ¶
type Tool = fantasy.FunctionTool
type UsageMetadata ¶
type UsageMetadata struct {
Reported bool `json:"reported"`
Precise bool `json:"precise"`
Input *int64 `json:"input"`
Output *int64 `json:"output"`
Total *int64 `json:"total"`
Reasoning *int64 `json:"reasoning"`
CacheRead *int64 `json:"cache_read"`
CacheWrite *int64 `json:"cache_write"`
UncachedInput *int64 `json:"uncached_input,omitempty"`
CandidateOutput *int64 `json:"candidate_output,omitempty"`
ToolInput *int64 `json:"tool_input,omitempty"`
Raw json.RawMessage `json:"raw,omitempty"`
}
UsageMetadata preserves reported field presence for one attempt. Scalar Fantasy usage is a convenience projection; these pointers are authoritative.
func (UsageMetadata) MarshalJSON ¶
func (metadata UsageMetadata) MarshalJSON() ([]byte, error)
func (*UsageMetadata) Options ¶
func (*UsageMetadata) Options()
func (*UsageMetadata) UnmarshalJSON ¶
func (metadata *UsageMetadata) UnmarshalJSON(data []byte) error
Source Files
¶
- acp.go
- acp_discovery.go
- acp_session.go
- acp_text.go
- anthropic_api_key.go
- attachment_input.go
- binding.go
- catalog.go
- claude.go
- claude_cache.go
- cloud.go
- cloud_routes.go
- compaction.go
- context.go
- errors.go
- history.go
- media.go
- metadata.go
- observation_facts.go
- options.go
- parameters.go
- plugin.go
- plugin_discovery.go
- plugin_framing.go
- plugin_request.go
- plugin_response.go
- plugin_transport.go
- raw_schema.go
- replay.go
- replay_context.go
- responses_cache.go
- retry.go
- retry_policy.go
- route.go
- sdk.go
- sdk_anthropic.go
- sdk_google.go
- sdk_http2.go
- sdk_openai.go
- sdk_request.go
- sdk_sources.go
- sdk_usage_observer.go
- search_request.go
- source_wire.go
- thinking.go
- tool_media.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package acpfixture is a scripted Agent Client Protocol agent for tests.
|
Package acpfixture is a scripted Agent Client Protocol agent for tests. |