inferencesetup

package
v1.0.0-rc.13 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 47 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package inferencesetup owns inference-role configuration and verification.

Index

Constants

View Source
const (
	RoleChat         = "primary"
	RoleRecovery     = "alternative"
	RoleAutocomplete = "autocomplete"
	RoleNextEdit     = "next-edit"
	RoleEmbedding    = "embedding"
	RoleImage        = transport.ImageRole
	RoleVideo        = transport.VideoRole
)
View Source
const EmbeddingChangedSubject = "inferencesetup.events.embedding_changed"

EmbeddingChangedSubject announces a committed embedding assignment or enablement change; consumers reread persisted configuration.

Variables

View Source
var CompletionContract = servicecontract.Contract{
	ID: "instructed-code-completion", Summary: "Declare an instructed code-completion operation",
	Description: "Declare whether a provider model uses the chat completion chain or one bounded prompt operation. Assigning the model still requires successful execution of the selected IDE completion operation.",
	Operations: []servicecontract.Operation{{
		ID: "declare", Summary: "Declare instructed code-completion support",
		Spec: "Declare which operation a provider model serves for code completion: the chat\ncompletion chain, or one bounded prompt operation using the model's own\nfill-in-the-middle tokens. The declaration is recorded against the model, and\nassigning the model still requires the selected operation to run successfully.",
		Inputs: []servicecontract.Input{
			{ID: "provider", Summary: "Connection selector or provider type the declaration applies to", Type: "string", Required: true},
			{ID: "model", Summary: "Model the declaration applies to", Type: "string", Required: true},
			{ID: "completionMode", Summary: "Declared completion mode", Type: "string", Required: true, Values: []string{modelregistry.CompletionInstruct, modelregistry.CompletionPrompt}},
		},
		Output: servicecontract.Output{
			Stdout: "The model identity and the completion mode now declared for it.",
			Format: "text",
		},
		Outcomes: []servicecontract.Outcome{
			{Code: 0, When: "the mode is declared", Meaning: "the completion route resolves through the declared operation"},
		},
		Refusals: []servicecontract.Refusal{
			{When: "the provider or model is not registered", Message: "names the connection and the command that lists its models"},
			{When: "the mode is not one this runtime serves", Message: "names the unsupported mode and the modes it accepts"},
		},
	}},
}

CompletionContract describes explicit operator declaration without claiming native verification.

View Source
var ConfigurationContract = servicecontract.Contract{
	ID: "inference-configuration", Summary: "Configure AI roles independently",
	Description: "Configure Chat, Recovery, Autocomplete and Workspace Search independently using cloud accounts, custom endpoints or local models.",
	Operations: []servicecontract.Operation{
		{
			ID: "read", Summary: "Read AI configuration", Description: "Read saved assignments and connections without starting inference or waiting for provider discovery.",
			Spec: "List common defaults, their stored values and inherited values before session,\nagent and model constraints. --all includes advanced settings; --describe adds\ncomplete descriptions and the locations of settings held outside this store.",
			Output: servicecontract.Output{
				Stdout: "Every declared setting with the value in force, its scope and its fallback.",
				Format: "text",
			},
			Outcomes: []servicecontract.Outcome{
				{Code: 0, When: "the settings are rendered", Meaning: "an unset setting is reported as inherited rather than as missing"},
			},
			Refusals: []servicecontract.Refusal{
				{When: "the local store cannot be read", Message: "names the store that failed; an unreadable store is never rendered as an unset configuration"},
			},
		},
		{
			ID: "apply", Summary: "Verify and apply reviewed roles", Description: "Verify proposed routes and execution settings before atomically saving their assignments, settings and evidence. Failed or cancelled verification preserves the current configuration. Chat and Recovery verify tool calls and consumption of their results. Required image input is checked with distinct colors; required audio input is checked with distinct beep counts. These input checks do not qualify speech transcription quality.",
			Spec: `Set a default for future launches. Names use dotted namespaces and snake_case
fields; units are part of numeric names. Legacy names remain aliases of the same row.

Examples:
  contenox-runtime config set inference.context.window_tokens 131072
  contenox-runtime config set inference.generation.max_output_tokens 8192
  contenox-runtime config set inference.reasoning.effort high
  contenox-runtime config set inference.autocomplete.model qwen2.5-coder:7b
  contenox-runtime config set execution.permissions.policy hitl-policy-strict.json

Use --scope global to set the fallback for a workspace-scoped key. Other keys
are global. Session pickers and slash commands do not save defaults.
Use 'config get <key> --explain' to inspect inheritance and constraints.`,
			Inputs: []servicecontract.Input{
				{ID: "proposals", Summary: "Reviewed role assignments to verify before saving", Type: "array", Required: true},
			},
			Examples: []servicecontract.Example{
				{Command: "contenox-runtime config set inference.context.window_tokens 131072", Explanation: "Session history window in tokens."},
				{Command: "contenox-runtime config set inference.generation.max_output_tokens 8192", Explanation: "Response token cap."},
				{Command: "contenox-runtime config set inference.reasoning.effort high", Explanation: "Reasoning effort for supported models."},
				{Command: "contenox-runtime config set inference.autocomplete.model qwen2.5-coder:7b", Explanation: "Autocomplete model."},
				{Command: "contenox-runtime config set execution.permissions.policy hitl-policy-strict.json", Explanation: "Envelope a dispatched unit runs under."},
			},
			Output: servicecontract.Output{
				Stdout: "The setting and the value now in force.",
				Format: "text",
			},
			Outcomes: []servicecontract.Outcome{
				{Code: 0, When: "the value is stored", Meaning: "the next launch reads it"},
			},
			Refusals: []servicecontract.Refusal{
				{When: "the key is not a declared setting", Message: "names the unknown key and lists the valid ones"},
				{When: "the value is rejected by its own rule", Message: "names the constraint, such as a boolean or a non-negative count"},
				{When: "the requested scope does not apply to the key", Message: "names the key as global and points at the session control for a temporary override"},
			},
		},
		{
			ID: "configure-resources", Summary: "Verify and apply device and resource settings", Description: "Exercise the selected role with its proposed device and resources before committing changes. Concurrent role, settings or credential edits require another review.",
			Spec: "Write the device, context, thread, batch, KV cache and residency settings of one role. The proposed settings are exercised through the role before they are committed, so a configuration that cannot run is refused rather than saved.",
			Inputs: []servicecontract.Input{
				{ID: "role", Summary: "Role whose device and resource settings are verified", Type: "string", Required: true, Values: RoleIDs()},
				{ID: "options", Summary: "Device, context, thread, batch, KV cache and residency settings to verify", Type: "object"},
			},
			Output: servicecontract.Output{
				Stdout: "The setting and the value now in force.",
				Format: "text",
			},
			Outcomes: []servicecontract.Outcome{
				{Code: 0, When: "the settings are exercised and committed", Meaning: "the role runs with the resources that were verified"},
			},
			Refusals: []servicecontract.Refusal{
				{When: "the role cannot run with the proposed resources", Message: "names the role and the resource that failed"},
				{When: "the role or an assignment changed during verification", Message: "requires another review instead of committing over the change"},
			},
		},
		{
			ID: "connect", Summary: "Connect an account or endpoint", Description: "Save one named provider connection and discover its models. Discovery errors remain attached to the saved connection.",
			Spec: `Register a named LLM backend endpoint in the local SQLite database.

The --type flag determines which provider protocol is used.
  openai, anthropic,
  gemini                        Cloud providers. Base URL inferred if --url is omitted. Requires --api-key-env.
  openai-codex                  ChatGPT subscription. Fixed endpoint; use backend login, no API key.
  modeld                        Native inference worker (local or remote gRPC).
  ollama                        Local daemon (requires 'ollama serve') or hosted Ollama Cloud (use
                                --url https://ollama.com/api and --api-key-env OLLAMA_API_KEY).
  vllm                          Self-hosted OpenAI-compatible endpoint (requires --url).
  vertex-google                 Google Cloud Vertex AI / Gemini (requires gcloud auth application-default login).
  scripted-test                 TEST ONLY. Replays a scripted dialog from a JSON file (requires --script).

API keys should be passed via --api-key-env (reads from environment) rather than
--api-key (inline literal) to avoid leaking secrets into shell history.

The scripted-test type is a fake: it calls no model and replays the turns in its
--script file in order, one per model turn. Every surface that names the active
provider shows "scripted-test", and 'contenox-runtime doctor' warns while it is the default.
It proves the machinery (chain loop, tool dispatch, HITL gate), not the agent's
judgement — you wrote the tool calls, so no real model was asked to choose them.

Examples:
  contenox-runtime backend add ollama     --type ollama
  contenox-runtime backend add ollama-cloud --type ollama    --url https://ollama.com/api --api-key-env OLLAMA_API_KEY
  contenox-runtime backend add openai     --type openai      --api-key-env OPENAI_API_KEY
  contenox-runtime backend add gemini     --type gemini      --api-key-env GEMINI_API_KEY
  contenox-runtime backend add myvllm    --type vllm         --url http://gpu-host:8000
  contenox-runtime backend add contenox --type contenox
  contenox-runtime backend add scripted  --type scripted-test --script ./dialog.json`,
			Inputs: []servicecontract.Input{
				{ID: "id", Summary: "Existing connection to update", Type: "string"},
				{ID: "name", Summary: "Connection name", Type: "string", Required: true, Positional: 1, Placeholder: "<name>"},
				{ID: "provider", Summary: "Supported provider type", Type: "string", Required: true, Flag: servicecontract.FlagSpec{Name: "type", Scope: servicecontract.FlagScopeCommand}},
				{ID: "url", Summary: "Provider API base URL", Type: "string", Required: true, Flag: servicecontract.FlagSpec{Name: "url", Scope: servicecontract.FlagScopeCommand}},
				{ID: "apiKey", Summary: "API key for this connection", Type: "secret", Flag: servicecontract.FlagSpec{Name: "api-key", Scope: servicecontract.FlagScopeCommand, Hidden: true}},
				{ID: "apiKeyEnv", Summary: "Environment variable containing the API key", Type: "string", Flag: servicecontract.FlagSpec{Name: "api-key-env", Scope: servicecontract.FlagScopeCommand}},
				{ID: "credentialSource", Summary: "Selected source of this connection's credentials", Type: "string", Required: true, Flag: servicecontract.FlagSpec{Name: "credential-source", Scope: servicecontract.FlagScopeCommand}},
				{ID: "credentialFile", Summary: "Credential JSON file to validate and import", Type: "string", Flag: servicecontract.FlagSpec{Name: "credential-file", Scope: servicecontract.FlagScopeCommand}},
			},
			Examples: []servicecontract.Example{
				{Command: "contenox-runtime backend add ollama --type ollama", Explanation: "A local daemon."},
				{Command: "contenox-runtime backend add ollama-cloud --type ollama --url https://ollama.com/api --api-key-env OLLAMA_API_KEY", Explanation: "A hosted Ollama endpoint."},
				{Command: "contenox-runtime backend add openai --type openai --api-key-env OPENAI_API_KEY", Explanation: "A cloud provider with an inferred base URL."},
				{Command: "contenox-runtime backend add myvllm --type vllm --url http://gpu-host:8000", Explanation: "A self-hosted OpenAI-compatible endpoint."},
			},
			Output: servicecontract.Output{
				Stdout: "The saved connection and the models discovery found for it.",
				Stderr: "A discovery failure, which stays attached to the saved connection.",
				Format: "text",
			},
			Outcomes: []servicecontract.Outcome{
				{Code: 0, When: "the connection is saved", Meaning: "the connection is usable by every role that names it"},
			},
			Refusals: []servicecontract.Refusal{
				{When: "the provider type is not one this runtime speaks", Message: "names the unsupported type and lists the supported ones"},
				{When: "a required field for the chosen type is absent", Message: "names the field, such as a URL for a self-hosted endpoint"},
				{When: "the endpoint is unreachable", Message: "reports the discovery failure and keeps the saved connection"},
			},
		},
	},
}

ConfigurationContract describes persistent setup independently of native health and recommendations.

View Source
var ErrConfigurationChanged = errors.New("inference configuration changed during verification; review the current configuration and retry")

ErrConfigurationChanged requires a fresh review after a concurrent configuration edit.

View Source
var ErrRoleDisabled = errors.New("inference role is turned off")

ErrRoleDisabled marks a request that needs an optional role the operator turned off.

View Source
var ErrSetupIncomplete = errors.New("inference setup is incomplete")
View Source
var RegistrationContract = servicecontract.Contract{
	ID: "inference-model-registration", Summary: "Register a model on this connection",
	Description: "Declare a model identity, context and operation capabilities when this endpoint has no usable model catalog. Registration is scoped to this connection. Each assigned role still requires production verification.",
	Operations: []servicecontract.Operation{{
		ID: "register", Summary: "Save model declaration",
		Spec: `Set a manual provider/model override.

The --think flag records whether this provider/model supports reasoning request
controls, and --vision whether it accepts image input. Both are provider-level:
they apply to every backend of that type. A flag you omit leaves its setting as
it was.

--context, --max-output, --capabilities and the pricing flags are backend-level.
Pass --backend to write them to one backend, or let them fan out to every
backend of the given provider type. A capability list REPLACES the observed set
rather than adding to it, so --capabilities states the whole set.

--completion declares how the model completes code: instruct runs the chat
completion chain, prompt runs one bounded prompt operation, and fim runs the
model's native fill-in-the-middle tokens in the format --fim-format names (the
formats are those the runtime declares). A fim declaration also states
--context when the connection does not report the model's context window, keeps
the capabilities already declared or observed for the model, and adds
autocomplete. --completion stands alone: it declares the contract and does not
verify or assign the model, which the autocomplete role assignment then does
with a real completion request.

Pricing is USD per million tokens and is what the monthly spend ceiling is
metered against: a model with no declared rate card costs nothing as far as the
meter is concerned.`,
		Inputs: []servicecontract.Input{{
			ID: "registration", Summary: "Connection id, model identity and the declared facts and capabilities", Type: "object", Required: true,
		}},
		Output: servicecontract.Output{
			Stdout: "The model identity and the facts now recorded for it.",
			Format: "text",
		},
		Outcomes: []servicecontract.Outcome{
			{Code: 0, When: "the declaration is stored", Meaning: "every surface reading this connection sees the declared facts"},
		},
		Refusals: []servicecontract.Refusal{
			{When: "the connection does not exist", Message: "names the connection and the command that lists them"},
			{When: "a capability list is scoped to one backend", Message: "refuses the partial scope rather than writing facts to a single backend"},
		},
	}},
}

RegistrationContract describes explicit model registration independently of catalog discovery or verification.

Functions

func AssignmentSources

func AssignmentSources() []string

AssignmentSources lists every assignment source a role may record.

func OptionalRoles

func OptionalRoles() []string

OptionalRoles lists the roles an operator may turn off. Every other role is required.

func RoleIDs

func RoleIDs() []string

RoleIDs is every inference role an assignment may name.

func RolesServed

func RolesServed(d modelregistry.ModelDescriptor) []string

RolesServed lists the inference roles this entry's curated contracts qualify it for: chat and recovery need a tool-capable chat tier, the remaining roles need their explicit execution contract. The list is never nil.

func ValidateEmbedding

func ValidateEmbedding(vector []float64) error

ValidateEmbedding rejects vectors that cannot represent a searchable document or query.

func VerifyRetrieval

func VerifyRetrieval(ctx context.Context, models llmrepo.ModelRepo, assignment Assignment) (int, error)

VerifyRetrieval exercises document and query encoding and requires the matching passage to outrank unrelated text.

func VerifyToolUse

func VerifyToolUse(ctx context.Context, chat ChatOperation) error

VerifyToolUse exercises a structured tool call and consumption of its result through production chat.

Types

type Assignment

type Assignment struct {
	Inputs   InputRequirement `json:"inputs"`
	Role     string           `json:"role"`
	Provider string           `json:"provider"`
	Model    string           `json:"model"`
}

Assignment identifies one explicitly selected inference route.

type AssignmentSource

type AssignmentSource string

AssignmentSource names which path saved a role assignment.

const (
	SourceUser    AssignmentSource = "user"
	SourcePlanner AssignmentSource = "planner"
)

Assignment sources. Every path that saves a role assignment records exactly one.

func (AssignmentSource) Valid

func (s AssignmentSource) Valid() bool

Valid reports whether the source is one of the declared assignment sources.

type AvailableModel

type AvailableModel struct {
	ContextTokens          int      `json:"contextTokens"`
	Digest                 string   `json:"digest"`
	NativeBackend          string   `json:"nativeBackend"`
	Registered             bool     `json:"registered"`
	DeclaredCapabilities   []string `json:"declaredCapabilities"`
	AdvertisedCapabilities []string `json:"advertisedCapabilities"`
	AdapterCapabilities    []string `json:"adapterCapabilities"`
	Vision                 bool     `json:"vision"`
	Audio                  bool     `json:"audio"`
	Provider               string   `json:"provider"`
	Name                   string   `json:"name"`
	Chat                   bool     `json:"chat"`
	Embed                  bool     `json:"embed"`
	Prompt                 bool     `json:"prompt"`
	FIMFormat              string   `json:"fimFormat,omitempty"`
	NextEditFormat         string   `json:"nextEditFormat,omitempty"`
	Autocomplete           bool     `json:"autocomplete"`
	NextEdit               bool     `json:"nextEdit"`
	CompletionMode         string   `json:"completionMode,omitempty"`
}

AvailableModel reports a model advertised by a connected provider.

type ChatOperation

ChatOperation executes a chat request against one selected connection and model.

type CompletionContractMissingError

type CompletionContractMissingError struct {
	Connection string
	Model      string
}

CompletionContractMissingError reports an autocomplete assignment whose model carries no declared code-completion contract.

func (*CompletionContractMissingError) Error

Error implements error.

type CompletionDeclaration

type CompletionDeclaration struct {
	Provider      string
	Model         string
	Mode          string
	FIMFormat     string
	ContextLength int
}

CompletionDeclaration states how one model completes code on one connection. Mode is instruct, prompt or fim; FIMFormat names the native format and applies to fim alone. ContextLength states the model's context window for fim when its connection does not report one.

type CompletionFactory

type CompletionFactory interface {
	Complete(context.Context, Assignment, string, string) (string, error)
	CompletionFingerprint(context.Context) (string, error)
	ExecutionFingerprint(context.Context, string, string) (string, error)
}

CompletionFactory verifies completion through the same operation used by the IDE.

type Configuration

type Configuration struct {
	Roles         []RoleStatus                         `json:"roles"`
	Providers     []ProviderConnection                 `json:"providers"`
	ProviderTypes []providerservice.ProviderCapability `json:"providerTypes"`
	Models        []AvailableModel                     `json:"models"`
}

Configuration is a read-only view of saved configuration and current observations.

type ConnectionUnavailableError

type ConnectionUnavailableError struct {
	Connection string
	Reason     string
}

ConnectionUnavailableError reports an assignment naming a connection that is absent or whose catalog could not be read, so no model of it can be checked.

func (*ConnectionUnavailableError) Error

Error implements error.

type ContextLengthRequiredError

type ContextLengthRequiredError struct {
	Connection string
	Model      string
}

ContextLengthRequiredError reports a fill-in-the-middle declaration for a model whose connection does not report a context length and whose declaration states none.

func (*ContextLengthRequiredError) Error

Error implements error.

type InputRequirement

type InputRequirement string

InputRequirement selects the input capabilities a Chat or Recovery route must verify.

const (
	// InputText requires text and structured tool use.
	InputText InputRequirement = "text"
	// InputImages also requires image understanding.
	InputImages InputRequirement = "images"
	// InputAudio also requires audio understanding.
	InputAudio InputRequirement = "audio"
	// InputImagesAndAudio requires both image and audio understanding.
	InputImagesAndAudio InputRequirement = "images-and-audio"
)

type ModelFactory

type ModelFactory interface {
	Models(context.Context) (llmrepo.ModelRepo, func(), error)
}

ModelFactory returns a model repository reflecting the latest persisted provider configuration.

type ModelNotDiscoveredError

type ModelNotDiscoveredError struct {
	Connection string
	Model      string
	Curated    bool
}

ModelNotDiscoveredError reports an assignment naming a model its connection does not serve. Curated is true when the model is a curated local artifact the connection can download, which a surface answers with the acquisition operation instead of a configuration repair.

func (*ModelNotDiscoveredError) Error

func (e *ModelNotDiscoveredError) Error() string

Error implements error.

type NextEditFactory

type NextEditFactory interface {
	NextEdit(context.Context, Assignment, modelcontract.NextEditInput) ([]modelcontract.TextEdit, error)
	NextEditExecutionFingerprint(context.Context, string) (string, error)
}

NextEditFactory executes and fingerprints a model's declared independent edit operation.

type OperationDeps

type OperationDeps struct {
	DB      libdbexec.DBManager
	Bus     libbus.Messenger
	State   *runtimestate.State
	Tracker libtracker.ActivityTracker
	// Models executes native completion, prompt completion and next edit on the selected route.
	Models llmrepo.ModelRepo
	// Agent runs the instructed completion chain.
	Agent codecompletion.Prompter
	// Chain is the loaded instructed completion chain.
	Chain *taskengine.TaskChainDefinition
}

OperationDeps are the collaborators OperationModelFactory requires; every field must be set.

type OperationModelFactory

type OperationModelFactory struct {
	RuntimeModelFactory
	// contains filtered or unexported fields
}

OperationModelFactory serves ModelFactory, CompletionFactory and NextEditFactory from the production completion and next-edit services.

func NewOperationModelFactory

func NewOperationModelFactory(deps OperationDeps) (*OperationModelFactory, error)

NewOperationModelFactory refuses a construction that lacks any dependency, naming it.

func (*OperationModelFactory) Complete

func (f *OperationModelFactory) Complete(ctx context.Context, assignment Assignment, prefix, suffix string) (string, error)

Complete runs the production completion operation the assigned route declares.

func (*OperationModelFactory) CompletionFingerprint

func (f *OperationModelFactory) CompletionFingerprint(ctx context.Context) (string, error)

CompletionFingerprint identifies the loaded instructed completion chain.

func (*OperationModelFactory) ExecutionFingerprint

func (f *OperationModelFactory) ExecutionFingerprint(ctx context.Context, mode, format string) (string, error)

ExecutionFingerprint identifies the completion operation selected by mode and FIM format.

func (*OperationModelFactory) NextEdit

NextEdit runs the production next-edit operation the assigned route declares.

func (*OperationModelFactory) NextEditExecutionFingerprint

func (f *OperationModelFactory) NextEditExecutionFingerprint(ctx context.Context, format string) (string, error)

NextEditExecutionFingerprint identifies the next-edit operation for format.

type ProposalRevision

type ProposalRevision struct {
	Reason    string                     `json:"reason"`
	Proposals []RouteProposal            `json:"proposals"`
	Execution transport.SessionExecution `json:"execution"`
}

ProposalRevision returns a changed native execution for review without committing any role.

func (*ProposalRevision) Error

func (r *ProposalRevision) Error() string

Error reports why the reviewed group needs another review.

type ProviderConnection

type ProviderConnection struct {
	RegistrationCapabilities []string `json:"registrationCapabilities"`
	CredentialSource         string   `json:"credentialSource"`
	AuthorizationState       string   `json:"authorizationState"`
	AuthorizationError       string   `json:"authorizationError,omitempty"`
	DiscoveryState           string   `json:"discoveryState"`
	Revision                 string   `json:"revision"`
	Selector                 string   `json:"selector"`
	ID                       string   `json:"id"`
	Name                     string   `json:"name"`
	Type                     string   `json:"type"`
	URL                      string   `json:"url"`
	State                    string   `json:"state"`
	Error                    string   `json:"error,omitempty"`
}

ProviderConnection reports a saved connection and its latest discovery result.

type ProviderRequest

type ProviderRequest struct {
	CredentialSource string
	CredentialFile   string
	ID               string
	Name             string
	Provider         string
	Endpoint         string
	APIKey           string
	APIKeyEnv        string
}

ProviderRequest is one native provider configuration submitted by the IDE.

type ProviderResult

type ProviderResult struct {
	ID             string `json:"id"`
	DiscoveryError string `json:"discoveryError,omitempty"`
}

ProviderResult identifies the saved connection and reports an unsuccessful discovery refresh.

type RegisterModelRequest

type RegisterModelRequest struct {
	ConnectionID string                  `json:"connectionId"`
	Model        string                  `json:"model"`
	Facts        runtimetypes.ModelFacts `json:"facts"`
}

RegisterModelRequest declares one model on an existing connection.

type RoleStatus

type RoleStatus struct {
	Assignment
	Enabled         bool             `json:"enabled"`
	AssignmentState string           `json:"assignmentState"`
	ConnectionID    string           `json:"connectionId"`
	Revision        string           `json:"revision"`
	Name            string           `json:"name"`
	State           string           `json:"state"`
	Detail          string           `json:"detail,omitempty"`
	Problem         string           `json:"problem,omitempty"`
	Inherited       bool             `json:"inherited"`
	Source          AssignmentSource `json:"source,omitempty"`
	Verification    *Verification    `json:"verification,omitempty"`
}

RoleStatus reports the effective assignment and whether its current configuration was verified.

type RouteProposal

type RouteProposal struct {
	Assignment
	RoleRevision       string                   `json:"roleRevision"`
	ConnectionRevision string                   `json:"connectionRevision"`
	Fingerprint        string                   `json:"fingerprint"`
	SettingsChange     SettingsChange           `json:"settingsChange"`
	Settings           modeldconn.WorkerOptions `json:"settings"`
}

RouteProposal is one reviewed route and its explicit resource-setting policy.

type RuntimeModelFactory

type RuntimeModelFactory struct {
	DB      libdbexec.DBManager
	Bus     libbus.Messenger
	State   *runtimestate.State
	Tracker libtracker.ActivityTracker
}

RuntimeModelFactory builds a short-lived model runtime from current persisted provider configuration.

func (RuntimeModelFactory) Models

func (f RuntimeModelFactory) Models(ctx context.Context) (llmrepo.ModelRepo, func(), error)

Models returns a model repository that observes the factory's current runtime state.

type Service

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

Service owns inference-role assignment and verification.

func New

New constructs the inference setup service from required runtime dependencies.

func (*Service) Apply

func (s *Service) Apply(ctx context.Context, proposals []RouteProposal, source AssignmentSource) ([]Verification, error)

Apply verifies a reviewed group before atomically committing its routes, settings and evidence, recording source as their origin.

func (*Service) Assign

func (s *Service) Assign(ctx context.Context, assignment Assignment, source AssignmentSource) (*Verification, error)

Assign verifies and atomically persists one explicit role assignment, recording source as its origin.

func (*Service) AssignAll

func (s *Service) AssignAll(ctx context.Context, assignments []Assignment, source AssignmentSource) ([]Verification, error)

AssignAll verifies every route before atomically persisting the complete assignment set, recording source as its origin.

func (*Service) CompletionContract

func (s *Service) CompletionContract(ctx context.Context, assignment Assignment) (string, string, error)

CompletionContract resolves the selected connection's completion mode and FIM format.

func (*Service) CompletionMode

func (s *Service) CompletionMode(ctx context.Context, assignment Assignment) (string, error)

CompletionMode resolves the selected connection's declared production operation.

func (*Service) Configuration

func (s *Service) Configuration(ctx context.Context) (Configuration, error)

Configuration reads setup without refreshing discovery or requiring a running model.

func (*Service) ConfigurationFingerprint

func (s *Service) ConfigurationFingerprint(ctx context.Context, assignment Assignment) (string, error)

ConfigurationFingerprint returns the fingerprint of the production route and execution contract for an assignment.

func (*Service) ConfigureProvider

func (s *Service) ConfigureProvider(ctx context.Context, request ProviderRequest) error

ConfigureProvider saves a connection and requires its discovery refresh to finish.

func (*Service) ConfigureWorker

func (s *Service) ConfigureWorker(ctx context.Context, role string, options modeldconn.WorkerOptions) (*Verification, error)

ConfigureWorker verifies a role's proposed device and resource settings before saving them.

func (*Service) ConnectProvider

func (s *Service) ConnectProvider(ctx context.Context, request ProviderRequest) (ProviderResult, error)

ConnectProvider saves a connection and reports discovery separately from persistence.

func (*Service) DeclareCompletion

func (s *Service) DeclareCompletion(ctx context.Context, provider, model, mode string) error

DeclareCompletion persists an explicit operator contract and refreshes discovery without verifying or assigning the route.

func (*Service) DeclareCompletionContract

func (s *Service) DeclareCompletionContract(ctx context.Context, declaration CompletionDeclaration) error

DeclareCompletionContract records the code-completion contract of one model: the chat completion chain (instruct), one bounded prompt operation (prompt), or a native fill-in-the-middle format (fim). Instruct and prompt declare through Service.DeclareCompletion; fim registers the model on its connection through Service.RegisterModel, keeping the capabilities and facts already declared or observed for it. The declaration neither verifies nor assigns the route.

func (*Service) Embed

func (s *Service) Embed(ctx context.Context, value string) ([]float32, error)

Embed executes workspace-search embedding through the currently verified embedding role.

func (*Service) InheritRecovery

func (s *Service) InheritRecovery(ctx context.Context) error

InheritRecovery clears an explicit recovery route so recovery follows verified Chat.

func (*Service) InvalidateProvider

func (s *Service) InvalidateProvider(ctx context.Context, provider string) error

InvalidateProvider removes verification evidence for every role using a provider.

func (*Service) LoginProvider

func (s *Service) LoginProvider(ctx context.Context, id string, authorize func(modelauth.DeviceCode) error) error

LoginProvider completes a provider-owned device login and refreshes its catalog.

func (*Service) ModelFactory

func (s *Service) ModelFactory() ModelFactory

ModelFactory returns the factory the service builds its model repositories from, so a host that composes extra collaborators into it can reach them.

func (*Service) NextEditContract

func (s *Service) NextEditContract(ctx context.Context, assignment Assignment) (string, error)

NextEditContract resolves the selected connection's declared independent edit format.

func (*Service) Ready

func (s *Service) Ready(ctx context.Context) (bool, error)

Ready requires every effective inference role that is turned on to have a verified route.

func (*Service) RefreshProvider

func (s *Service) RefreshProvider(ctx context.Context, provider string) error

RefreshProvider updates discovered capabilities without changing configuration.

func (*Service) RegisterModel

func (s *Service) RegisterModel(ctx context.Context, request RegisterModelRequest) error

RegisterModel saves a connection-scoped model declaration without issuing a discovery request.

func (*Service) RemoveProvider

func (s *Service) RemoveProvider(ctx context.Context, id string) error

RemoveProvider deletes a connection and invalidates roles whose routes included it.

func (*Service) RenderMedia

func (s *Service) RenderMedia(ctx context.Context, options mediageneration.Options) (transport.MediaResult, error)

RenderMedia uses the enabled role's verified model and persisted device allocation.

func (*Service) Review

func (s *Service) Review(ctx context.Context, proposals []RouteProposal) ([]RouteProposal, error)

Review captures role and connection revisions and the proposed execution contract without running inference. Previously captured revisions refuse concurrent edits instead of replacing the user's reviewed configuration.

func (*Service) RoleRevision

func (s *Service) RoleRevision(ctx context.Context, role string) (string, error)

RoleRevision identifies persisted assignment and execution-setting changes for a role.

func (*Service) Roles

func (s *Service) Roles(ctx context.Context) ([]RoleStatus, error)

Roles returns the effective role assignments and their verification state.

func (*Service) SaveProvider

func (s *Service) SaveProvider(ctx context.Context, request ProviderRequest) (ProviderResult, error)

SaveProvider atomically saves connection configuration and credentials without waiting for discovery.

func (*Service) SetNextEditEnabled

func (s *Service) SetNextEditEnabled(ctx context.Context, enabled bool) error

SetNextEditEnabled persists whether automatic current-file edit previews may run.

func (*Service) SetRoleEnabled

func (s *Service) SetRoleEnabled(ctx context.Context, role string, enabled bool) error

SetRoleEnabled persists whether an optional role is turned on. A role that is off unless chosen must hold verified evidence before it can be turned on.

func (*Service) VerifiedRole

func (s *Service) VerifiedRole(ctx context.Context, role string) (RoleStatus, error)

VerifiedRole returns a role only when its current provider, model, and configuration fingerprint match successful verification evidence.

func (*Service) Verify

func (s *Service) Verify(ctx context.Context, role string) (*Verification, error)

Verify repeats the real capability request for the current assignment and refreshes its evidence.

type SettingsChange

type SettingsChange string

SettingsChange specifies whether verification retains or replaces local execution settings.

const (
	// PreserveSettings verifies with the current persisted execution settings.
	PreserveSettings SettingsChange = "preserve"
	// ReplaceSettings verifies proposed execution settings before committing them.
	ReplaceSettings SettingsChange = "replace"
)

type Verification

type Verification struct {
	Inputs                InputRequirement             `json:"inputs"`
	NativeExecutions      []transport.SessionExecution `json:"nativeExecutions,omitempty"`
	ConfigurationRevision string                       `json:"configurationRevision,omitempty"`
	RoleRevision          string                       `json:"roleRevision"`
	Role                  string                       `json:"role"`
	Provider              string                       `json:"provider"`
	Model                 string                       `json:"model"`
	Fingerprint           string                       `json:"fingerprint"`
	Dimension             int                          `json:"dimension,omitempty"`
	VerifiedAt            time.Time                    `json:"verifiedAt"`
	Sample                string                       `json:"sample,omitempty"`
}

Verification records the route and result proven by a real capability request.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL