api

package
v0.11.0-beta.2 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: Apache-2.0, MIT Imports: 70 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ParseError     = -32700
	InvalidRequest = -32600
	MethodNotFound = -32601
	InvalidParams  = -32602
	InternalError  = -32603
)

Standard JSON-RPC error codes.

Variables

This section is empty.

Functions

func CanonicalSession

func CanonicalSession(sess *session.Session) (*session.Session, error)

CanonicalSession validates identity and resolves a real workspace directory without changing process cwd. A copy prevents factories mutating persisted model/provider/history state while binding their tools.

func MasterKeyPath

func MasterKeyPath(cfgDir string) string

MasterKeyPath returns the absolute path to the master key file. Useful for diagnostics: "can the agent read this file?"

func NewSessionEvolution

func NewSessionEvolution(cfg *config.Config, home string, sess *session.Session, provider providers.Provider, tracker cost.Tracker) (*learning.Engine, error)

NewSessionEvolution creates one workspace-bound recorder and proposal engine. Generation is an explicit operator action and uses the session's provider, model and cost admission. No background paid calls or automatic installation.

func PersistAgentSession

func PersistAgentSession(ctx context.Context, store session.Store, id string, a *agent.Agent) error

PersistAgentSession is the shared CLI/API/ACP durable history commit. Title generation is deterministic so an optional provider call cannot consume the deadline needed to save a cancelled turn's partial history.

Types

type AbortParams

type AbortParams struct {
	SessionID string `json:"session_id"`
}

type ConfigCreateParams

type ConfigCreateParams struct {
	Providers      []config.ProviderConfig `json:"providers,omitempty"`
	Models         []config.ModelConfig    `json:"models,omitempty"`
	DefaultModel   string                  `json:"defaultModel,omitempty"`
	VisionProvider string                  `json:"visionProvider,omitempty"`
	ReviewProvider string                  `json:"reviewProvider,omitempty"`
	TTS            *TTSConfig              `json:"tts,omitempty"`
	Gateway        *GatewayConfigFields    `json:"gateway,omitempty"`
}

type ConfigExistsResult

type ConfigExistsResult struct {
	Exists bool `json:"exists"`
}

type ConfigGetResult

type ConfigGetResult struct {
	Version      int                    `json:"version"`
	Agent        map[string]interface{} `json:"agent"`
	UI           map[string]interface{} `json:"ui"`
	Thinking     map[string]interface{} `json:"thinking,omitempty"`
	SystemPrompt string                 `json:"system_prompt,omitempty"`
	Security     map[string]interface{} `json:"security,omitempty"`
	Session      map[string]interface{} `json:"session,omitempty"`
	Cost         map[string]interface{} `json:"cost,omitempty"`
	Compaction   map[string]interface{} `json:"compaction,omitempty"`
	Ouroboros    map[string]interface{} `json:"ouroboros,omitempty"`
	RedTeam      map[string]interface{} `json:"red_team,omitempty"`
	Gateways     map[string]interface{} `json:"gateways,omitempty"`
}

type ConfigUpdateParams

type ConfigUpdateParams struct {
	Patch map[string]interface{} `json:"patch"`
}

type DiscordGatewayConfig

type DiscordGatewayConfig struct {
	BotToken        string `json:"bot_token,omitempty"`
	Enabled         bool   `json:"enabled"`
	NotifyChannelID string `json:"notify_channel_id,omitempty"`
}

type ForkParams

type ForkParams struct {
	SessionID string `json:"session_id"`
	Name      string `json:"name,omitempty"`
}

ForkParams is the payload for agent.fork RPC calls.

type ForkResult

type ForkResult struct {
	Session SessionInfo `json:"session"`
}

ForkResult is returned by agent.fork.

type GatewayConfigFields

type GatewayConfigFields struct {
	Discord  *DiscordGatewayConfig  `json:"discord,omitempty"`
	Telegram *TelegramGatewayConfig `json:"telegram,omitempty"`
	WhatsApp *WhatsAppGatewayConfig `json:"whatsapp,omitempty"`
}

GatewayConfigFields holds gateway configuration for the onboarding wizard.

type GatewayTestParams

type GatewayTestParams struct {
	Gateway string `json:"gateway"` // "discord" | "telegram" | "slack"
	Token   string `json:"token"`
}

type GatewayTestResult

type GatewayTestResult struct {
	OK    bool   `json:"ok"`
	Error string `json:"error,omitempty"`
	User  string `json:"user,omitempty"` // bot username if OK
}

type GoalGetResult

type GoalGetResult struct {
	Objective   string  `json:"objective"`
	Status      string  `json:"status"`
	TokenBudget *int    `json:"token_budget"`
	TokensUsed  int     `json:"tokens_used"`
	TimeUsedS   float64 `json:"time_used_s"`
}

type HealthResult

type HealthResult struct {
	Coordination map[string]bool `json:"coordination,omitempty"`
	Status       string          `json:"status"`
	Version      int             `json:"version"`
}

type ModelInfo

type ModelInfo struct {
	ID               string   `json:"id"`
	Name             string   `json:"name"`
	Family           string   `json:"family"`
	ContextWindow    int      `json:"context_window"`
	DefaultMaxTokens int      `json:"maxTokens"`
	SupportsTools    bool     `json:"supports_tools"`
	SupportsVision   bool     `json:"supports_vision"`
	Reasoning        bool     `json:"reasoning"`
	InputModalities  []string `json:"input_modalities,omitempty"`
	OutputModalities []string `json:"output_modalities,omitempty"`
}

type ModelsListParams

type ModelsListParams struct {
	Provider string `json:"provider"`
}

type ModelsListResult

type ModelsListResult struct {
	Models []ModelInfo `json:"models"`
}

type PlanGetItem

type PlanGetItem struct {
	ID     string `json:"id"`
	Text   string `json:"text"`
	Status string `json:"status"`
}

type PlanGetResult

type PlanGetResult struct {
	Title string        `json:"title"`
	Items []PlanGetItem `json:"items"`
}

type ProviderInfo

type ProviderInfo struct {
	Name   string      `json:"name"`
	Type   string      `json:"type"`
	Models []ModelInfo `json:"models"`
}

type ProvidersListResult

type ProvidersListResult struct {
	Providers []ProviderInfo `json:"providers"`
}

type RPCError

type RPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

type Request

type Request struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

type Response

type Response struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id"`
	Result  interface{}     `json:"result,omitempty"`
	Error   *RPCError       `json:"error,omitempty"`
}

type SecureStore

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

SecureStore handles encryption/decryption of sensitive config values.

func NewSecureStore

func NewSecureStore(cfgDir string) (*SecureStore, error)

NewSecureStore initialises the secure key store. If no master key exists, one is generated and persisted. Returns nil if the config directory is not writable (keys will be stored plain).

func (*SecureStore) Decrypt

func (s *SecureStore) Decrypt(encoded string) (string, error)

Decrypt decrypts a value previously encrypted with Encrypt. Returns the plaintext or an error if the ciphertext is malformed.

func (*SecureStore) DecryptConfig

func (s *SecureStore) DecryptConfig(cfg *config.Config) error

DecryptConfig decrypts all API keys in a config in-place.

func (*SecureStore) Encrypt

func (s *SecureStore) Encrypt(plaintext string) (string, error)

Encrypt encrypts a plaintext value using AES-256-GCM. Returns a base64-encoded ciphertext prefixed with the hex nonce.

func (*SecureStore) HealthCheck

func (s *SecureStore) HealthCheck() error

HealthCheck verifies the secure store can encrypt and decrypt. Returns nil if everything works, or an error describing what's broken. Call this during agent startup to catch env/directory issues early.

func (*SecureStore) IsEncrypted

func (s *SecureStore) IsEncrypted(value string) bool

IsEncrypted returns true if the value looks like an encrypted string (hex_nonce:base64_ciphertext format).

func (*SecureStore) SecureConfig

func (s *SecureStore) SecureConfig(cfg *config.Config) (*config.Config, error)

SecureConfig encrypts all plaintext API keys in a config and returns a new config with encrypted values. The original is not modified. Call this before saving config to disk.

type SendMessageParams

type SendMessageParams struct {
	SessionID string `json:"session_id,omitempty"`
	Message   string `json:"message"`
}

type SendMessageResult

type SendMessageResult struct {
	Response    string `json:"response"`
	ToolCalls   int    `json:"tool_calls"`
	TotalTokens int    `json:"total_tokens"`
	Steps       int    `json:"steps"`
	Model       string `json:"model"`
	Blocked     bool   `json:"blocked"`
	BlockReason string `json:"block_reason,omitempty"`
}

type Server

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

Server is the JSON-RPC 2.0 HTTP server that wraps the existing internal packages behind a clean API for the Ink TUI to consume.

func NewServer

func NewServer(sc ServerConfig) *Server

NewServer creates a new API server. Call Start to begin listening.

func (*Server) Addr

func (s *Server) Addr() string

Addr returns the address the server is listening on. Only valid after Start() has been called.

func (*Server) AskUser

func (s *Server) AskUser(ctx context.Context, prompt string, choices []string) (text string, index int, cancel bool)

AskUser bridges a tool-level ask_user call into the TUI prompt system. Blocks until the user answers or the context is cancelled.

func (*Server) AuthToken

func (s *Server) AuthToken() string

AuthToken is passed only through the launched frontend's environment.

func (*Server) Close

func (s *Server) Close()

Close releases service-owned agents and integrations. The database pool and application-wide services remain owned by the caller.

func (*Server) CoordinationStatus

func (s *Server) CoordinationStatus() map[string]bool

CoordinationStatus contains no model input, credentials, or provider errors.

func (*Server) Ready

func (s *Server) Ready() <-chan struct{}

Ready closes after the listener and HTTP server are initialized. Callers must also watch Start's result for startup failures.

func (*Server) ResolveACPSender

func (s *Server) ResolveACPSender(ctx context.Context, id string) (acp.Sender, error)

ResolveACPSender reuses the same session service and runtime factory as HTTP and desktop clients. ACP never builds a separate, differently wired agent.

func (*Server) SetAskBridge

func (s *Server) SetAskBridge(bridge func(ctx context.Context, prompt string, choices []string) (text string, index int, cancel bool))

SetAskBridge installs a TUI-side bridge for the ask_user tool. When nil, the ask_user tool always returns Cancel:true.

func (*Server) Start

func (s *Server) Start(ctx context.Context) error

Start binds to localhost:0 (OS-chosen port), prints the address to stderr, and blocks until the context is cancelled or SIGINT/SIGTERM is received. Graceful shutdown is handled automatically.

func (*Server) StartBackground

func (s *Server) StartBackground(ctx context.Context) error

StartBackground explicitly starts application-owned delivery. Constructors never launch workers, and closing the server permanently prevents restart.

type ServerConfig

type ServerConfig struct {
	FlowQueue *agent.FlowQueue
	// ConfigCredentialStore explicitly injects the onboarding vault; nil uses OS credentials.
	ConfigCredentialStore credentials.Store
	Canvas                *web.CanvasStore
	DashboardGoalReader   func(context.Context, string) (*agent.Goal, error)
	DashboardPlanReader   func(context.Context, string) (*plan.Plan, error)
	// CoordStore enables durable delivery for explicitly bound peers.
	CallbackDestinations  map[string]string
	CallbackTransport     http.RoundTripper // Explicit application/test injection; nil uses protected HTTPS.
	CoordStore            *coordination.Store
	Config                *config.Config
	SessionStore          session.Store
	Tools                 *tools.Registry
	SessionRuntimeFactory SessionRuntimeFactory
	LearningStore         *learning.Store // optional: correction learning store (§6.5)
	// ListenAddr is the host:port the server binds to (e.g. "127.0.0.1:7777").
	// When empty, the OS picks a random port on localhost (equivalent to
	// "localhost:0"). The TUI path leaves this unset to preserve existing behaviour.
	ListenAddr string
	// FeatureManager gates runtime feature flags (P1). Optional.
	FeatureManager *features.Manager
	// ExtensionsManager is the unified extensions registry (P2). Optional.
	ExtensionsManager *extensions.Manager
	// ReadCache is the speculative read cache (P2). Optional.
	ReadCache *speculative.ReadCache
	// MemoEngine powers the Memo elephant thinking indicator. Optional.
	// If nil, memo RPC endpoints return a static fallback.
	MemoEngine *personality.MemoEngine
	// SyncManager enables auto-push of session state after each turn.
	// Optional — when nil or cfg.Sync.AutoPush is false, auto-push is a no-op.
	SyncManager *syncpkg.Manager
	// HotReloadBus, when set, is wired into every agent created by the
	// server so user.yaml changes are live-applied. Optional.
	HotReloadBus *hotreload.Bus
	// SubagentManager, when set, enables sub-agent tracking in the API
	// and TUI subagent panel. Optional — nil-safe.
	SubagentManager agent.SubagentManager

	// CostTracker, when set, powers the session.usage RPC endpoint.
	// Optional — nil disables the endpoint.
	CostTracker cost.Tracker

	// TasksStore powers the todo.* RPC endpoints (§8.3 todo panel).
	// Optional — nil-safe, endpoints return empty lists when unset.
	TasksStore TaskStore

	// SkillsRegistry powers the skills.* RPC endpoints. Optional — nil-safe.
	SkillsRegistry *skills.Registry

	// DB is the shared Postgres connection pool. Optional — when set, enables
	// Postgres-backed agent stores (GoalStore, etc.).
	DB *sql.DB
}

ServerConfig holds everything the API server needs at startup.

type SessionCreateParams

type SessionCreateParams struct {
	Folder   string `json:"folder,omitempty"`
	Title    string `json:"title,omitempty"`
	Model    string `json:"model,omitempty"`
	Provider string `json:"provider,omitempty"`
}

type SessionCreateResult

type SessionCreateResult struct {
	Session SessionInfo `json:"session"`
}

type SessionDeleteParams

type SessionDeleteParams struct {
	ID string `json:"id"`
}

type SessionInfo

type SessionInfo struct {
	ID        string    `json:"id"`
	Title     string    `json:"title"`
	Name      string    `json:"name"`
	Folder    string    `json:"folder"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	Model     string    `json:"model"`
	Provider  string    `json:"provider"`
	Status    string    `json:"status"`
	ParentID  string    `json:"parent_id,omitempty"`
	Children  []string  `json:"children,omitempty"`
}

type SessionListResult

type SessionListResult struct {
	Sessions []SessionInfo `json:"sessions"`
}

type SessionMessagesResult

type SessionMessagesResult struct {
	Snapshot string              `json:"snapshot,omitempty"`
	ID       string              `json:"id"`
	Messages []providers.Message `json:"messages"`
}

type SessionRuntime

type SessionRuntime struct {
	EvolutionFactory        func(providers.Provider) (*learning.Engine, error)
	HistoryCompactorFactory func(providers.Provider) (agent.HistoryCompactor, bool, error)
	// CheckCurrent runs under caller session admission before cached agent reuse.
	CheckCurrent          func(context.Context) (bool, error)
	ExtensionsManager     *extensions.Manager
	Tools                 *tools.Registry
	Hooks                 *hooks.Registry
	PostWriteVerifier     agent.PostWriteVerifier
	CheckpointSnapshotter agent.CheckpointSnapshotter
	FlowStore             agent.FlowStore
	CompletionAuditor     *audit.Auditor
	GoalStore             *agent.GoalStore
	SubagentManager       agent.SubagentManager
	Cleanup               func()
}

SessionRuntime owns resources used by one agent, never another session. Cleanup must be idempotent; shared stores belong to the application owner.

type SessionRuntimeFactory

type SessionRuntimeFactory func(context.Context, *session.Session) (*SessionRuntime, error)

SessionRuntimeFactory binds dependencies to immutable persisted metadata. It must not call back into Server: agent creation holds the server lock.

type SessionUsageParams

type SessionUsageParams struct {
	SessionID string `json:"session_id,omitempty"`
	Scope     string `json:"scope,omitempty"` // "session" (default), "daily", "all"
}

SessionUsageParams is the payload for session.usage RPC calls.

type SessionUsageResult

type SessionUsageResult struct {
	Report    *cost.UsageReport `json:"report"`
	Daily     *cost.CostSummary `json:"daily,omitempty"`      // populated when scope=daily
	SyncError string            `json:"sync_error,omitempty"` // last auto-push failure for this session
}

SessionUsageResult is returned by session.usage.

type SkillInfoDTO

type SkillInfoDTO struct {
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Category    string   `json:"category"`
	Tags        []string `json:"tags"`
	Enabled     bool     `json:"enabled"`
	Bundled     bool     `json:"bundled"`
}

SkillInfoDTO is the wire format for the skills panel.

type SteerParams

type SteerParams struct {
	SessionID string `json:"session_id"`
	Message   string `json:"message"`
	Role      string `json:"role,omitempty"`
}

SteerParams is the payload for agent.steer RPC calls.

type SubagentInfo

type SubagentInfo struct {
	Name      string `json:"name"`
	Status    string `json:"status"` // "running" | "completed" | "failed"
	ElapsedMs int64  `json:"elapsed_ms"`
	Model     string `json:"model"`
}

type SubagentListResult

type SubagentListResult struct {
	Subagents []SubagentInfo `json:"subagents"`
}

type TTSConfig

type TTSConfig struct {
	Provider string `json:"provider,omitempty"` // "openai" | "elevenlabs" | "edge"
	APIKey   string `json:"apiKey,omitempty"`
	Voice    string `json:"voice,omitempty"`
}

TTSConfig holds text-to-speech settings written as part of config.create.

type TaskDTO

type TaskDTO struct {
	ID        string `json:"id"`
	SessionID string `json:"session_id"`
	Intent    string `json:"intent"`
	Status    string `json:"status"` // "open" | "shipped" | "abandoned"
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
}

TaskDTO is the wire format the todo panel expects.

type TaskStore

type TaskStore interface {
	Add(sessionID, intent string) (*TaskDTO, error)
	Update(id, sessionID, description string) (*TaskDTO, error)
	Toggle(id string) (*TaskDTO, error)
	Remove(id string) error
	List(sessionID string) ([]TaskDTO, error)
}

TaskStore is the complete task-panel contract shared by installed runtimes.

type TasksStoreAdapter

type TasksStoreAdapter struct{ S *tasks.Store }

TasksStoreAdapter adapts *tasks.Store for use as the server's TasksStore.

func (*TasksStoreAdapter) Add

func (a *TasksStoreAdapter) Add(sessionID, intent string) (*TaskDTO, error)

func (*TasksStoreAdapter) List

func (a *TasksStoreAdapter) List(sessionID string) ([]TaskDTO, error)

func (*TasksStoreAdapter) Remove

func (a *TasksStoreAdapter) Remove(id string) error

func (*TasksStoreAdapter) Toggle

func (a *TasksStoreAdapter) Toggle(id string) (*TaskDTO, error)

func (*TasksStoreAdapter) Update

func (a *TasksStoreAdapter) Update(id, sessionID, description string) (*TaskDTO, error)

type TelegramGatewayConfig

type TelegramGatewayConfig struct {
	BotToken     string `json:"bot_token,omitempty"`
	Enabled      bool   `json:"enabled"`
	NotifyChatID int64  `json:"notify_chat_id,omitempty"`
}

type WhatsAppGatewayConfig

type WhatsAppGatewayConfig struct {
	Enabled bool   `json:"enabled"`
	Backend string `json:"backend,omitempty"` // "whatsmeow" | "cloud"
}

type WizardCatalogResult

type WizardCatalogResult struct {
	Providers   []config.WizardOption `json:"providers"`
	Gateways    []config.WizardOption `json:"gateways"`
	TTS         []config.WizardOption `json:"tts"`
	Databases   []config.WizardOption `json:"databases"`
	Review      []config.WizardOption `json:"review"`
	Recommended config.QuickSetup     `json:"recommended"`
}

type WizardQuickSetupParams

type WizardQuickSetupParams struct {
	Provider       string `json:"provider,omitempty"`
	Model          string `json:"model,omitempty"`
	Gateway        string `json:"gateway,omitempty"`
	TTS            string `json:"tts,omitempty"`
	Database       string `json:"database,omitempty"`
	ReviewProvider string `json:"review_provider,omitempty"`
	ReviewModel    string `json:"review_model,omitempty"`
}

type WizardQuickSetupResult

type WizardQuickSetupResult struct {
	Status  string `json:"status"`
	Message string `json:"message"`
}

Jump to

Keyboard shortcuts

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