backend

package
v0.107.6-beta.12 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: Apache-2.0 Imports: 58 Imported by: 0

Documentation

Overview

Package backend exposes K-brain's canonical session and Agent runtime over HTTP.

Index

Constants

View Source
const ImageDelegationHeader = "X-Kbrain-Image-Delegation"

Variables

This section is empty.

Functions

This section is empty.

Types

type BackendHook

type BackendHook struct {
	ID          string        `json:"id"`
	Name        string        `json:"name"`
	Description string        `json:"description,omitempty"`
	Event       string        `json:"event"`
	Enabled     bool          `json:"enabled"`
	Type        HookType      `json:"type"`
	Script      string        `json:"script,omitempty"`
	Requests    []HookRequest `json:"requests,omitempty"`
	TimeoutMS   int           `json:"timeoutMs,omitempty"`
}

type BackendHookRunner

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

func NewBackendHookRunner

func NewBackendHookRunner(store *HookStore) *BackendHookRunner

func (*BackendHookRunner) Scope

func (r *BackendHookRunner) Scope(ctx context.Context, conversationID, runID, cwd string, warn func(BackendHook, string, error)) func(string)

Scope snapshots configuration once; event replay never invokes this callback.

type CronApplyInput

type CronApplyInput struct {
	BaseRevision uint64          `json:"baseRevision"`
	Ops          []CronOperation `json:"ops"`
}

type CronApplyResponse

type CronApplyResponse struct {
	Status string       `json:"status"`
	Cron   CronSnapshot `json:"cron"`
}

type CronHTTPRequest

type CronHTTPRequest struct {
	ID      string            `json:"id"`
	URL     string            `json:"url"`
	Method  string            `json:"method"`
	Headers map[string]string `json:"headers,omitempty"`
	Body    json.RawMessage   `json:"body,omitempty"`
}

type CronModelRef

type CronModelRef struct {
	CustomProviderID string `json:"customProviderId"`
	Model            string `json:"model"`
}

type CronOperation

type CronOperation struct {
	Op    string         `json:"op"`
	ID    string         `json:"id,omitempty"`
	Item  map[string]any `json:"item,omitempty"`
	Patch map[string]any `json:"patch,omitempty"`
	IDs   []string       `json:"ids,omitempty"`
}

type CronRunNowResponse

type CronRunNowResponse struct {
	ExecutionID string `json:"executionId"`
	StartedAt   int64  `json:"startedAt"`
}

type CronRunRecord

type CronRunRecord struct {
	SessionID         string `json:"sessionId,omitempty"`
	RunID             string `json:"runId,omitempty"`
	Counted           bool   `json:"counted"`
	ID                string `json:"id"`
	TaskID            string `json:"taskId"`
	State             string `json:"state"`
	Success           bool   `json:"success"`
	StartedAt         int64  `json:"startedAt"`
	FinishedAt        *int64 `json:"finishedAt,omitempty"`
	DurationMs        uint64 `json:"durationMs"`
	ExitCode          *int   `json:"exitCode,omitempty"`
	Output            string `json:"output"`
	TerminationReason string `json:"terminationReason,omitempty"`
}

type CronSnapshot

type CronSnapshot struct {
	Revision uint64      `json:"revision"`
	Tasks    []*CronTask `json:"tasks"`
}

type CronTask

type CronTask struct {
	ID string `json:"id"`
	// SessionID binds prompt tasks to one durable canonical conversation.
	SessionID           string            `json:"sessionId,omitempty"`
	Name                string            `json:"name"`
	Description         string            `json:"description"`
	Cron                string            `json:"cron"`
	Enabled             bool              `json:"enabled"`
	RemainingExecutions *uint64           `json:"remainingExecutions,omitempty"`
	TimeoutSeconds      uint64            `json:"timeoutSeconds"`
	Type                string            `json:"type"`
	Script              string            `json:"script,omitempty"`
	Requests            []CronHTTPRequest `json:"requests,omitempty"`
	Prompt              string            `json:"prompt,omitempty"`
	SelectedModel       *CronModelRef     `json:"selectedModel,omitempty"`
	Reasoning           string            `json:"reasoning,omitempty"`
	Workdir             string            `json:"workdir,omitempty"`
	LastError           string            `json:"lastError,omitempty"`
}

type Factory

type Factory func(context.Context, string, protocol.ModelRef) (*agent.Agent, error)

type HookOperation

type HookOperation struct {
	Op    string         `json:"op"`
	ID    string         `json:"id,omitempty"`
	Item  map[string]any `json:"item,omitempty"`
	Patch map[string]any `json:"patch,omitempty"`
	IDs   []string       `json:"ids,omitempty"`
}

type HookRequest

type HookRequest struct {
	ID      string            `json:"id"`
	URL     string            `json:"url"`
	Method  string            `json:"method"`
	Headers map[string]string `json:"headers,omitempty"`
	Body    any               `json:"body,omitempty"`
}

type HookStore

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

func NewHookStore

func NewHookStore(path string) (*HookStore, error)

func (*HookStore) Apply

func (*HookStore) Snapshot

func (s *HookStore) Snapshot() HooksSnapshot

type HookType

type HookType string
const (
	HookCommand HookType = "command"
	HookHTTP    HookType = "http"
)

type HooksApplyInput

type HooksApplyInput struct {
	BaseRevision uint64          `json:"baseRevision"`
	Ops          []HookOperation `json:"ops"`
}

type HooksApplyResponse

type HooksApplyResponse struct {
	Status string        `json:"status"`
	Hooks  HooksSnapshot `json:"hooks"`
}

type HooksSnapshot

type HooksSnapshot struct {
	Revision uint64        `json:"revision"`
	Hooks    []BackendHook `json:"hooks"`
}

type ImageAssets added in v0.107.6

type ImageAssets interface {
	ImportAsset(context.Context, imaging.Scope, io.Reader, string) (imaging.ImageAsset, error)
	OpenAsset(context.Context, imaging.Scope, string, string) (io.ReadCloser, imaging.ImageAsset, error)
}

type ImageAuthorization added in v0.107.6

type ImageAuthorization struct {
	Scope        imaging.Scope
	CanConfigure bool
}

ImageAuthorization is issued only by trusted server-side authentication. CanConfigure grants settings and secret management, independently of execution.

type ImageDelegationConfig added in v0.107.6

type ImageDelegationConfig struct {
	BackendID string
	Keys      map[string]ImageDelegationKey
	// Now is optional and primarily useful for deterministic tests.
	Now func() time.Time
	// MaxNonces bounds replay-cache memory. Saturation denies new requests;
	// unexpired entries are never evicted to admit a replay.
	MaxNonces int
}

type ImageDelegationKey added in v0.107.6

type ImageDelegationKey struct {
	PublicKey      ed25519.PublicKey
	AllowConfigure bool
}

ImageDelegationKey is server-owned trust configuration. AllowConfigure is an additional ceiling on the signed configuration grant.

type ImageDependencyChecker added in v0.107.6

type ImageDependencyChecker interface {
	ImageDependenciesInUse(context.Context, imaging.Scope, []string, []string) (bool, error)
}

ImageDependencyChecker is called under SettingsStore.mu. The job service must serialize job acceptance with this check and must not re-enter SettingsStore. Include queued, running, saving, cancelling and unresolved accepted jobs.

type ImageJobs added in v0.107.6

ImageJobs is the public service contract. Execution and recovery belong to imaging.Service; HTTP requests never own the lifetime of accepted jobs.

type ImageModule added in v0.107.6

type ImageModule struct {
	Verification         *ImageVerificationManager
	Settings             *ImageSettingsManager
	Store                *imaging.Store
	Assets               ImageAssets
	Jobs                 ImageJobs
	AllowLocalImageScope bool
	ResolveScope         ImageScopeResolver
}

ImageModule dependencies are assembled by the process owner. Store must be the same store used by Jobs so snapshots and event positions are atomic. The process owner starts/recovers and closes Jobs before closing Assets/Store.

type ImageScopeResolver added in v0.107.6

type ImageScopeResolver func(*http.Request) (ImageAuthorization, error)

ImageScopeResolver verifies any delegated identity and its configuration grant. It runs only after the configured backend Bearer token has been verified.

func NewImageDelegationResolver added in v0.107.6

func NewImageDelegationResolver(cfg ImageDelegationConfig) (ImageScopeResolver, error)

NewImageDelegationResolver returns ImageModule.ResolveScope. The module calls it only after authenticating the backend bearer. No owner/backend/header fallback exists. Trust keys are copied and backend identity is pinned here.

Replay state belongs to one process: deployments must use one verifier per backend, or a shared atomic nonce store before load balancing. On restart, rotate trust keys (or wait >60 seconds before accepting the old keys). This does not make the local-only settings manager multi-tenant.

type ImageSettingsManager added in v0.107.6

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

ImageSettingsManager shares the settings store's one configuration lock. Construct one manager per store, with an explicit private secret file path. Only {OwnerID:"local", BackendID:"local"} is supported until trusted owner delegation and per-owner settings storage are implemented.

func NewImageSettingsManager added in v0.107.6

func NewImageSettingsManager(store *SettingsStore, secretPath string, opts ImageSettingsOptions) (*ImageSettingsManager, error)

func (*ImageSettingsManager) ImageSettings added in v0.107.6

func (m *ImageSettingsManager) ImageSettings(scope imaging.Scope) (imaging.ImageSettings, error)

func (*ImageSettingsManager) ResolveImageConnection added in v0.107.6

func (m *ImageSettingsManager) ResolveImageConnection(ctx context.Context, scope imaging.Scope, id string) (ResolvedImageConnection, error)

func (*ImageSettingsManager) ResolveTarget added in v0.107.6

func (m *ImageSettingsManager) ResolveTarget(ctx context.Context, scope imaging.Scope, id string) (imaging.TargetSnapshot, error)

ResolveTarget implements imaging.Registry for trusted local execution.

func (*ImageSettingsManager) UpdateImageSettings added in v0.107.6

func (*ImageSettingsManager) VerifyImageTarget added in v0.107.6

func (m *ImageSettingsManager) VerifyImageTarget(ctx context.Context, scope imaging.Scope, expectedRevision uint64, targetID string) (imaging.ImageSettings, error)

VerifyImageTarget is retained as a fail-closed compatibility shim. Synchronous callbacks cannot certify durable outputs or preserve submission idempotency. Use ImageVerificationManager.Start/Get with explicit consent instead.

func (*ImageSettingsManager) WithImageTarget added in v0.107.6

func (m *ImageSettingsManager) WithImageTarget(ctx context.Context, scope imaging.Scope, id string, accept func(imaging.TargetSnapshot) error) error

WithImageTarget serializes durable job acceptance with configuration deletion. The service callback must persist its dependency before returning and must not call back into this manager or SettingsStore. Both this callback and the dependency checker acquire service locks AFTER the settings lock.

func (*ImageSettingsManager) WriteImageSecret added in v0.107.6

WriteImageSecret stores a literal and returns its opaque reference. The caller attaches that reference with UpdateImageSettings; no config save spans two files. Rewriting a purpose rotates its value; an empty value revokes it.

type ImageSettingsOptions added in v0.107.6

type ImageSettingsOptions struct {
	Dependencies ImageDependencyChecker
	// Only trusted provider configuration is passed to this resolver. HTTP secret
	// input is always stored literally and never reaches this function.
	ResolveProviderSecret func(context.Context, string) (string, error)
	// Deprecated: ignored. Only durable successful verification jobs may issue evidence.
	VerifyTarget func(context.Context, imaging.Scope, imaging.TargetSnapshot) (imaging.TargetVerification, error)
}

type ImageVerificationManager added in v0.107.6

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

func NewImageVerificationManager added in v0.107.6

func NewImageVerificationManager(settings *ImageSettingsManager, service *imaging.Service, assets ImageAssets) *ImageVerificationManager

func (*ImageVerificationManager) CheckExecution added in v0.107.6

func (v *ImageVerificationManager) CheckExecution(ctx context.Context, scope imaging.Scope, target imaging.TargetSnapshot) error

CheckExecution prevents a queued verification from using a changed binding. Finalization independently checks again after persisted output is available.

func (*ImageVerificationManager) Get added in v0.107.6

Get never submits work. Finalization is idempotent and settings publication is atomic. A failed settings save can be retried without touching the upstream.

func (*ImageVerificationManager) Start added in v0.107.6

type Options

type Options struct {
	Image                   *ImageModule
	Store                   *session.Store
	Factory                 Factory
	EventDir                string
	Token                   string
	Models                  []protocol.ModelRef
	DefaultCWD              string
	Settings                *SettingsStore
	Prompts                 *resources.PromptStore
	MemoryRoot              string
	MemoryStore             *memory.Store
	MemoryRuntimeFactory    MemoryRuntimeFactory
	MemoryOrganizerInterval time.Duration
	QuestionTimeout         time.Duration
	MCP                     *mcp.LiveManager
	MCPCredentialBridge     mcp.CredentialBridge
}

type ProviderUsageResult

type ProviderUsageResult struct {
	Data      []UsageData `json:"data"`
	QueriedAt *int64      `json:"queriedAt"`
	Error     *string     `json:"error"`
	IsStale   bool        `json:"isStale"`
}

type ProviderUsageService

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

func NewProviderUsageService

func NewProviderUsageService(settings *SettingsStore) *ProviderUsageService

func (*ProviderUsageService) ProviderExists

func (s *ProviderUsageService) ProviderExists(id string) bool

func (*ProviderUsageService) Query

func (s *ProviderUsageService) Query(ctx context.Context, providerID string, refresh bool) ProviderUsageResult

func (*ProviderUsageService) Test

func (s *ProviderUsageService) Test(ctx context.Context, providerID string, draft usageConfig) ProviderUsageResult

type ResolvedImageConnection added in v0.107.6

type ResolvedImageConnection struct {
	imaging.ResolvedConnection
	BaseURL        string            `json:"-"`
	AuthKind       string            `json:"-"`
	SecretRefs     map[string]string `json:"-"`
	CustomHeaders  map[string]string `json:"-"`
	UseSystemProxy bool              `json:"-"`
}

ResolvedImageConnection adds the execution endpoint to imaging's private injected client/resolver contract. Neither this object nor its embedded connection can be serialized into a public response.

func (ResolvedImageConnection) MarshalJSON added in v0.107.6

func (ResolvedImageConnection) MarshalJSON() ([]byte, error)

type Server

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

func New

func New(opts Options) (*Server, error)

func (*Server) Close

func (s *Server) Close() error

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

type SettingsStore

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

SettingsStore publishes immutable snapshots only after persistence succeeds.

func NewSettingsStore

func NewSettingsStore(cfg *config.Config, save func(*config.Config) error) *SettingsStore

func (*SettingsStore) Revision

func (s *SettingsStore) Revision() uint64

func (*SettingsStore) Snapshot

func (s *SettingsStore) Snapshot() *config.Config

type UsageData

type UsageData struct {
	PlanName       string   `json:"planName,omitempty"`
	Extra          string   `json:"extra,omitempty"`
	IsValid        *bool    `json:"isValid,omitempty"`
	InvalidMessage string   `json:"invalidMessage,omitempty"`
	Total          *float64 `json:"total,omitempty"`
	Used           *float64 `json:"used,omitempty"`
	Remaining      *float64 `json:"remaining,omitempty"`
	Unit           string   `json:"unit,omitempty"`
}

Jump to

Keyboard shortcuts

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