executor

package
v0.5.23 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: Apache-2.0 Imports: 71 Imported by: 0

Documentation

Overview

Package executor provides runtime execution capabilities for various AI service providers. This file implements the AI Studio executor that routes requests through a websocket-backed transport for the AI Studio provider.

Package executor provides runtime execution capabilities for various AI service providers. This file implements the Antigravity executor that proxies requests to the antigravity upstream using OAuth credentials.

Package executor provides runtime execution capabilities for various AI service providers. This file implements the Gemini CLI executor that talks to Cloud Code Assist endpoints using OAuth credentials from auth metadata.

Package executor provides runtime execution capabilities for various AI service providers. It includes stateless executors that handle API requests, streaming responses, token counting, and authentication refresh for different AI service providers.

Package executor provides runtime execution capabilities for various AI service providers. This file implements the Vertex AI Gemini executor that talks to Google Vertex AI endpoints using service account credentials or API keys.

Index

Constants

View Source
const (
	DefaultOpenCodeURL = "http://localhost:4096"
)

OpenCode default configuration

View Source
const (
	// LoggingStoreKey is the context key for the thread-safe logging store.
	LoggingStoreKey loggingContextKey = "SWITCHAI_LOGGING_STORE"
)

Variables

This section is empty.

Functions

func ApplyReasoningEffortMetadata

func ApplyReasoningEffortMetadata(payload []byte, metadata map[string]any, model, field string, allowCompat bool) []byte

ApplyReasoningEffortMetadata applies reasoning effort overrides from metadata to the given JSON path. Metadata values take precedence over any existing field when the model supports thinking, intentionally overwriting caller-provided values to honor suffix/default metadata priority.

func ApplyThinkingMetadata

func ApplyThinkingMetadata(payload []byte, metadata map[string]any, model string) []byte

ApplyThinkingMetadata applies thinking config from model suffix metadata (e.g., (high), (8192)) for standard Gemini format payloads. It normalizes the budget when the model supports thinking.

func BuildOpenAIResponse

func BuildOpenAIResponse(model, content string, usage *OpenAIUsage) ([]byte, error)

BuildOpenAIResponse wraps content in OpenAI chat completion format.

func BuildOpenAIStreamChunk

func BuildOpenAIStreamChunk(model, content string, isFirst bool) []byte

BuildOpenAIStreamChunk creates an SSE chunk for streaming responses. Returns raw JSON (upstream handler adds "data: " prefix).

func BuildOpenAIStreamChunkFast

func BuildOpenAIStreamChunkFast(id string, created int64, model, content string, isFirst bool) []byte

BuildOpenAIStreamChunkFast creates an SSE chunk using pre-formatted string templates. This avoids struct allocation and reflection-based json.Marshal (~5x faster). The id and created are pre-computed once per stream (OpenAI spec: same for all chunks).

func BuildOpenAIStreamDone

func BuildOpenAIStreamDone() []byte

BuildOpenAIStreamDone returns the final [DONE] marker for SSE streams. Returns raw marker (upstream handler adds "data: " prefix).

func BuildOpenAIStreamFinishChunk

func BuildOpenAIStreamFinishChunk(model string) []byte

BuildOpenAIStreamFinishChunk creates the final chunk with finish_reason. Returns raw JSON (upstream handler adds "data: " prefix).

func BuildOpenAIStreamFinishChunkFast

func BuildOpenAIStreamFinishChunkFast(id string, created int64, model string) []byte

BuildOpenAIStreamFinishChunkFast creates the final finish chunk using templates.

func FetchAntigravityModels

func FetchAntigravityModels(ctx context.Context, auth *switchailocalauth.Auth, cfg *config.Config) []*registry.ModelInfo

FetchAntigravityModels retrieves available models using the supplied auth.

func FetchOpenCodeModels

func FetchOpenCodeModels(ctx context.Context, cfg *config.Config) []*registry.ModelInfo

FetchOpenCodeModels retrieves available models from the local OpenCode server.

func FilterSSEUsageMetadata

func FilterSSEUsageMetadata(payload []byte) []byte

FilterSSEUsageMetadata removes usageMetadata from SSE events that are not terminal (finishReason != "stop"). Stop chunks are left untouched. This function is shared between aistudio and antigravity executors.

func FinalizeAPIResponse

func FinalizeAPIResponse(ctx context.Context, cfg *config.Config)

FinalizeAPIResponse aggregates all upstream attempts into a single request/response log.

func IsStallError added in v0.2.0

func IsStallError(err error) bool

IsStallError reports whether err is a *stallError. Useful for the P1 retry classifier.

func NormalizeMultimodalContent added in v0.4.0

func NormalizeMultimodalContent(payload []byte) []byte

NormalizeMultimodalContent rewrites non-canonical content blocks in an OpenAI-shaped chat-completions request so the upstream provider sees the canonical OpenAI multimodal shape.

Why: clients built on the Vercel AI SDK v5 (OpenCode, Cursor, parts of Continue.dev) increasingly emit content blocks like

{"type":"image","image":"data:image/png;base64,..."}
{"type":"audio","audio":{"data":"...","mediaType":"audio/wav"}}
{"type":"file","data":"...","mediaType":"image/png"}

that aren't OpenAI-canonical and are silently dropped by upstream providers (or by older translator paths). We translate them in-place to

{"type":"image_url","image_url":{"url":"data:image/png;base64,..."}}
{"type":"input_audio","input_audio":{"data":"...","format":"wav"}}

which is what every OpenAI-compat upstream we route to (MiniMax, Groq, xiaomi, switchai) accepts. Idempotent: blocks already in canonical shape pass through untouched.

Pure transformation — no I/O, no provider awareness. Called by every executor right after sdktranslator.TranslateRequest so it sits at the boundary between client-format diversity and the single shape upstream providers expect.

func NormalizeReasoningEffortLevel

func NormalizeReasoningEffortLevel(payload []byte, model string) []byte

NormalizeReasoningEffortLevel validates and normalizes the reasoning_effort or reasoning.effort field for level-based thinking models.

func NormalizeThinkingConfig

func NormalizeThinkingConfig(payload []byte, model string, allowCompat bool) []byte

NormalizeThinkingConfig normalizes thinking-related fields in the payload based on model capabilities. For models without thinking support, it strips reasoning fields. For models with level-based thinking, it validates and normalizes the reasoning effort level. For models with numeric budget thinking, it strips the effort string fields.

func StripThinkingFields

func StripThinkingFields(payload []byte, effortOnly bool) []byte

StripThinkingFields removes thinking-related fields from the payload for models that do not support thinking. If effortOnly is true, only removes effort string fields (for models using numeric budgets).

func StripUsageMetadataFromJSON

func StripUsageMetadataFromJSON(rawJSON []byte) ([]byte, bool)

StripUsageMetadataFromJSON drops usageMetadata unless finishReason is present (terminal). It handles both formats: - Aistudio: candidates.0.finishReason - Antigravity: response.candidates.0.finishReason

func ValidateThinkingConfig

func ValidateThinkingConfig(payload []byte, model string) error

ValidateThinkingConfig checks for unsupported reasoning levels on level-based models. Returns a statusErr with 400 when an unsupported level is supplied to avoid silently downgrading requests.

Types

type AIStudioExecutor

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

AIStudioExecutor routes AI Studio requests through a websocket-backed transport.

func NewAIStudioExecutor

func NewAIStudioExecutor(cfg *config.Config, provider string, relay *wsrelay.Manager) *AIStudioExecutor

NewAIStudioExecutor creates a new AI Studio executor instance.

Parameters:

  • cfg: The application configuration
  • provider: The provider name
  • relay: The websocket relay manager

Returns:

  • *AIStudioExecutor: A new AI Studio executor instance

func (*AIStudioExecutor) CountTokens

CountTokens counts tokens for the given request using the AI Studio API.

func (*AIStudioExecutor) Execute

Execute performs a non-streaming request to the AI Studio API.

func (*AIStudioExecutor) ExecuteStream

ExecuteStream performs a streaming request to the AI Studio API.

func (*AIStudioExecutor) Identifier

func (e *AIStudioExecutor) Identifier() string

Identifier returns the executor identifier.

func (*AIStudioExecutor) PrepareRequest

func (e *AIStudioExecutor) PrepareRequest(_ *http.Request, _ *switchailocalauth.Auth) error

PrepareRequest prepares the HTTP request for execution (no-op for AI Studio).

func (*AIStudioExecutor) Refresh

Refresh refreshes the authentication credentials (no-op for AI Studio).

type AntigravityExecutor

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

AntigravityExecutor proxies requests to the antigravity upstream.

func NewAntigravityExecutor

func NewAntigravityExecutor(cfg *config.Config) *AntigravityExecutor

NewAntigravityExecutor creates a new Antigravity executor instance.

Parameters:

  • cfg: The application configuration

Returns:

  • *AntigravityExecutor: A new Antigravity executor instance

func (*AntigravityExecutor) CountTokens

CountTokens counts tokens for the given request using the Antigravity API.

func (*AntigravityExecutor) Execute

Execute performs a non-streaming request to the Antigravity API.

func (*AntigravityExecutor) ExecuteStream

func (*AntigravityExecutor) Identifier

func (e *AntigravityExecutor) Identifier() string

Identifier returns the executor identifier.

func (*AntigravityExecutor) PrepareRequest

func (e *AntigravityExecutor) PrepareRequest(_ *http.Request, _ *switchailocalauth.Auth) error

PrepareRequest prepares the HTTP request for execution (no-op for Antigravity).

func (*AntigravityExecutor) Refresh

Refresh refreshes the authentication credentials using the refresh token.

type Attachment

type Attachment struct {
	Type string `json:"type"` // "file", "folder", "glob"
	Path string `json:"path"`
}

Attachment defines a file or folder to be included in the CLI prompt.

type CLIExecutionError

type CLIExecutionError struct {
	Status  int
	Message string
}

CLIExecutionError carries an HTTP status code through the executor → handler chain. The handler layer checks for the StatusCode() interface to set the HTTP response status.

func (*CLIExecutionError) Error

func (e *CLIExecutionError) Error() string

func (*CLIExecutionError) StatusCode

func (e *CLIExecutionError) StatusCode() int

type CLIFlags

type CLIFlags struct {
	Sandbox     bool `json:"sandbox"`
	AutoApprove bool `json:"auto_approve"`
	Yolo        bool `json:"yolo"`
}

CLIFlags defines provider-agnostic flags to be mapped to CLI-specific arguments.

type CLIOptions

type CLIOptions struct {
	Attachments []Attachment `json:"attachments"`
	Flags       CLIFlags     `json:"flags"`
	SessionID   string       `json:"session_id"`
}

CLIOptions defines the structure for extra_body.cli options.

type ClaudeExecutor

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

ClaudeExecutor is a stateless executor for Anthropic Claude over the messages API. If api_key is unavailable on auth, it falls back to legacy via ClientAdapter.

func NewClaudeExecutor

func NewClaudeExecutor(cfg *config.Config) *ClaudeExecutor

func (*ClaudeExecutor) ExecuteStream

func (*ClaudeExecutor) Identifier

func (e *ClaudeExecutor) Identifier() string

func (*ClaudeExecutor) PrepareRequest

func (e *ClaudeExecutor) PrepareRequest(_ *http.Request, _ *switchailocalauth.Auth) error

func (*ClaudeExecutor) Refresh

type CodexExecutor

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

CodexExecutor is a stateless executor for Codex (OpenAI Responses API entrypoint). If api_key is unavailable on auth, it falls back to legacy via ClientAdapter.

func NewCodexExecutor

func NewCodexExecutor(cfg *config.Config) *CodexExecutor

func (*CodexExecutor) ExecuteStream

func (*CodexExecutor) Identifier

func (e *CodexExecutor) Identifier() string

func (*CodexExecutor) PrepareRequest

func (e *CodexExecutor) PrepareRequest(_ *http.Request, _ *switchailocalauth.Auth) error

func (*CodexExecutor) Refresh

type GeminiCLIExecutor

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

GeminiCLIExecutor talks to the Cloud Code Assist endpoint using OAuth credentials from auth metadata.

func NewGeminiCLIExecutor

func NewGeminiCLIExecutor(cfg *config.Config) *GeminiCLIExecutor

NewGeminiCLIExecutor creates a new Gemini CLI executor instance.

Parameters:

  • cfg: The application configuration

Returns:

  • *GeminiCLIExecutor: A new Gemini CLI executor instance

func (*GeminiCLIExecutor) CountTokens

CountTokens counts tokens for the given request using the Gemini CLI API.

func (*GeminiCLIExecutor) Execute

Execute performs a non-streaming request to the Gemini CLI API.

func (*GeminiCLIExecutor) ExecuteStream

ExecuteStream performs a streaming request to the Gemini CLI API.

func (*GeminiCLIExecutor) Identifier

func (e *GeminiCLIExecutor) Identifier() string

Identifier returns the executor identifier.

func (*GeminiCLIExecutor) PrepareRequest

func (e *GeminiCLIExecutor) PrepareRequest(_ *http.Request, _ *switchailocalauth.Auth) error

PrepareRequest prepares the HTTP request for execution (no-op for Gemini CLI).

func (*GeminiCLIExecutor) Refresh

Refresh refreshes the authentication credentials (no-op for Gemini CLI).

type GeminiExecutor

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

GeminiExecutor is a stateless executor for the official Gemini API using API keys. It handles both API key and OAuth bearer token authentication, supporting both regular and streaming requests to the Google Generative Language API.

func NewGeminiExecutor

func NewGeminiExecutor(cfg *config.Config) *GeminiExecutor

NewGeminiExecutor creates a new Gemini executor instance.

Parameters:

  • cfg: The application configuration

Returns:

  • *GeminiExecutor: A new Gemini executor instance

func (*GeminiExecutor) CountTokens

CountTokens counts tokens for the given request using the Gemini API.

func (*GeminiExecutor) Execute

Execute performs a non-streaming request to the Gemini API. It translates the request to Gemini format, sends it to the API, and translates the response back to the requested format.

Parameters:

  • ctx: The context for the request
  • auth: The authentication information
  • req: The request to execute
  • opts: Additional execution options

Returns:

  • switchailocalexecutor.Response: The response from the API
  • error: An error if the request fails

func (*GeminiExecutor) ExecuteStream

ExecuteStream performs a streaming request to the Gemini API.

func (*GeminiExecutor) Identifier

func (e *GeminiExecutor) Identifier() string

Identifier returns the executor identifier.

func (*GeminiExecutor) PrepareRequest

func (e *GeminiExecutor) PrepareRequest(_ *http.Request, _ *switchailocalauth.Auth) error

PrepareRequest prepares the HTTP request for execution (no-op for Gemini).

func (*GeminiExecutor) Refresh

Refresh refreshes the authentication credentials (no-op for Gemini API key).

type GeminiVertexExecutor

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

GeminiVertexExecutor sends requests to Vertex AI Gemini endpoints using service account credentials.

func NewGeminiVertexExecutor

func NewGeminiVertexExecutor(cfg *config.Config) *GeminiVertexExecutor

NewGeminiVertexExecutor creates a new Vertex AI Gemini executor instance.

Parameters:

  • cfg: The application configuration

Returns:

  • *GeminiVertexExecutor: A new Vertex AI Gemini executor instance

func (*GeminiVertexExecutor) CountTokens

CountTokens counts tokens for the given request using the Vertex AI API.

func (*GeminiVertexExecutor) Execute

Execute performs a non-streaming request to the Vertex AI API.

func (*GeminiVertexExecutor) ExecuteStream

ExecuteStream performs a streaming request to the Vertex AI API.

func (*GeminiVertexExecutor) Identifier

func (e *GeminiVertexExecutor) Identifier() string

Identifier returns the executor identifier.

func (*GeminiVertexExecutor) PrepareRequest

func (e *GeminiVertexExecutor) PrepareRequest(_ *http.Request, _ *switchailocalauth.Auth) error

PrepareRequest prepares the HTTP request for execution (no-op for Vertex).

func (*GeminiVertexExecutor) Refresh

Refresh refreshes the authentication credentials (no-op for Vertex).

type IFlowExecutor

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

IFlowExecutor executes OpenAI-compatible chat completions against the iFlow API using API keys derived from OAuth.

func NewIFlowExecutor

func NewIFlowExecutor(cfg *config.Config) *IFlowExecutor

NewIFlowExecutor constructs a new executor instance.

func (*IFlowExecutor) Execute

Execute performs a non-streaming chat completion request.

func (*IFlowExecutor) ExecuteStream

ExecuteStream performs a streaming chat completion request.

func (*IFlowExecutor) Identifier

func (e *IFlowExecutor) Identifier() string

Identifier returns the provider key.

func (*IFlowExecutor) PrepareRequest

func (e *IFlowExecutor) PrepareRequest(_ *http.Request, _ *switchailocalauth.Auth) error

PrepareRequest implements ProviderExecutor but requires no preprocessing.

func (*IFlowExecutor) Refresh

Refresh refreshes OAuth tokens or cookie-based API keys and updates the stored API key.

type LMStudioExecutor

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

LMStudioExecutor provides integration with locally running LM Studio instances. LM Studio is OpenAI-compatible, so this executor forwards requests directly without translation (unlike Ollama which needs API format conversion).

func NewLMStudioExecutor

func NewLMStudioExecutor(cfg *config.Config) *LMStudioExecutor

NewLMStudioExecutor creates a new executor for LM Studio.

func (*LMStudioExecutor) CountTokens

func (*LMStudioExecutor) DiscoverModels

func (e *LMStudioExecutor) DiscoverModels(ctx context.Context) ([]string, error)

DiscoverModels queries LM Studio for available models.

func (*LMStudioExecutor) Execute

Execute forwards OpenAI-format requests to LM Studio server.

func (*LMStudioExecutor) ExecuteStream

func (e *LMStudioExecutor) ExecuteStream(ctx context.Context, _ *auth.Auth, req executor.Request, opts executor.Options) (<-chan executor.StreamChunk, error)

ExecuteStream forwards streaming requests to LM Studio and converts to SSE.

func (*LMStudioExecutor) Identifier

func (e *LMStudioExecutor) Identifier() string

func (*LMStudioExecutor) PrepareRequest

func (e *LMStudioExecutor) PrepareRequest(_ *http.Request, _ *auth.Auth) error

func (*LMStudioExecutor) Refresh

func (e *LMStudioExecutor) Refresh(_ context.Context, a *auth.Auth) (*auth.Auth, error)

type LocalCLIExecutor

type LocalCLIExecutor struct {
	BinaryPath       string
	Args             []string
	Provider         string
	JSONFormatArgs   []string
	StreamFormatArgs []string
	SupportsJSON     bool
	SupportsStream   bool
	UseStdin         bool

	// Capability and Flag mapping fields
	SupportsAttachments bool
	AttachmentPrefix    string
	SandboxFlag         string
	AutoApproveFlag     string
	YoloFlag            string
	SessionFlag         string

	// Billboard shared working directory for CLI requests.
	// When non-empty, a system instruction is prepended to the prompt.
	BillboardDir string

	// Security fields
	PositionalArgsSeparator string
}

LocalCLIExecutor executes prompts by calling a local binary.

func NewLocalCLIExecutor

func NewLocalCLIExecutor(tool cli.DiscoveredTool) *LocalCLIExecutor

NewLocalCLIExecutor creates a new executor from a discovered CLI tool.

func NewLocalCLIExecutorSimple

func NewLocalCLIExecutorSimple(provider, binaryPath string, args []string) *LocalCLIExecutor

NewLocalCLIExecutorSimple creates a basic executor (legacy compatibility).

func (*LocalCLIExecutor) CountTokens

CountTokens returns 0 as CLI tools generally don't expose this via simple one-shot commands.

func (*LocalCLIExecutor) Execute

Execute runs the CLI tool with the prompt and returns an OpenAI-formatted response.

func (*LocalCLIExecutor) ExecuteStream

ExecuteStream runs the CLI tool with streaming and returns OpenAI SSE chunks.

func (*LocalCLIExecutor) Identifier

func (e *LocalCLIExecutor) Identifier() string

func (*LocalCLIExecutor) Refresh

func (e *LocalCLIExecutor) Refresh(ctx context.Context, auth *sdkauth.Auth) (*sdkauth.Auth, error)

Refresh is a no-op for CLI proxy as auth is handled externally by the tool.

type LoggingStore

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

LoggingStore handles thread-safe accumulation of upstream API attempts.

func NewLoggingStore

func NewLoggingStore(cfg *config.Config) *LoggingStore

NewLoggingStore creates a new thread-safe logging store.

func (*LoggingStore) AppendResponseChunk

func (s *LoggingStore) AppendResponseChunk(chunk []byte)

AppendResponseChunk appends a chunk to the latest attempt's response.

func (*LoggingStore) Finalize

func (s *LoggingStore) Finalize(ctx context.Context)

Finalize finalizes the logs and writes them to the Gin context.

func (*LoggingStore) RecordRequest

func (s *LoggingStore) RecordRequest(info upstreamRequestLog)

RecordRequest records an upstream request.

func (*LoggingStore) RecordResponseMetadata

func (s *LoggingStore) RecordResponseMetadata(status int, headers http.Header)

RecordResponseMetadata records status code and headers for the latest attempt.

type MonitoredProcess

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

MonitoredProcess represents a CLI process with Superbrain monitoring.

func (*MonitoredProcess) GetOverwatchContext

func (mp *MonitoredProcess) GetOverwatchContext() *overwatch.OverwatchContext

GetOverwatchContext returns the monitoring context.

func (*MonitoredProcess) GetStderr

func (mp *MonitoredProcess) GetStderr() string

GetStderr returns the captured stderr content.

func (*MonitoredProcess) GetStdout

func (mp *MonitoredProcess) GetStdout() string

GetStdout returns the captured stdout content.

func (*MonitoredProcess) InjectStdin

func (mp *MonitoredProcess) InjectStdin(input string) error

InjectStdin writes to the process stdin.

func (*MonitoredProcess) Kill

func (mp *MonitoredProcess) Kill() error

Kill terminates the process.

func (*MonitoredProcess) Wait

func (mp *MonitoredProcess) Wait() error

Wait waits for the process to complete.

type OllamaExecutor

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

OllamaExecutor provides integration with locally running Ollama instances. It communicates via HTTP to the Ollama API (default: http://localhost:11434).

func NewOllamaExecutor

func NewOllamaExecutor(cfg *config.Config) *OllamaExecutor

NewOllamaExecutor creates a new executor for Ollama.

func (*OllamaExecutor) CountTokens

func (e *OllamaExecutor) CountTokens(ctx context.Context, _ *auth.Auth, req executor.Request, opts executor.Options) (executor.Response, error)

func (*OllamaExecutor) Execute

func (*OllamaExecutor) ExecuteStream

func (e *OllamaExecutor) ExecuteStream(ctx context.Context, _ *auth.Auth, req executor.Request, opts executor.Options) (<-chan executor.StreamChunk, error)

func (*OllamaExecutor) Identifier

func (e *OllamaExecutor) Identifier() string

func (*OllamaExecutor) PrepareRequest

func (e *OllamaExecutor) PrepareRequest(_ *http.Request, _ *auth.Auth) error

func (*OllamaExecutor) Refresh

func (e *OllamaExecutor) Refresh(_ context.Context, a *auth.Auth) (*auth.Auth, error)

type OpenAIChatChoice

type OpenAIChatChoice struct {
	Index        int           `json:"index"`
	Message      OpenAIMessage `json:"message"`
	FinishReason string        `json:"finish_reason"`
}

OpenAIChatChoice represents a choice in an OpenAI chat completion.

type OpenAIChatResponse

type OpenAIChatResponse struct {
	ID      string             `json:"id"`
	Object  string             `json:"object"`
	Created int64              `json:"created"`
	Model   string             `json:"model"`
	Choices []OpenAIChatChoice `json:"choices"`
	Usage   *OpenAIUsage       `json:"usage,omitempty"`
}

OpenAIChatResponse represents a non-streaming OpenAI chat completion response.

type OpenAICompatExecutor

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

OpenAICompatExecutor implements a stateless executor for OpenAI-compatible providers. It performs request/response translation and executes against the provider base URL using per-auth credentials (API key) and per-auth HTTP transport (proxy) from context.

func NewOpenAICompatExecutor

func NewOpenAICompatExecutor(provider string, cfg *config.Config) *OpenAICompatExecutor

NewOpenAICompatExecutor creates an executor bound to a provider key (e.g., "openrouter").

func (*OpenAICompatExecutor) ExecuteStream

func (*OpenAICompatExecutor) Identifier

func (e *OpenAICompatExecutor) Identifier() string

Identifier implements switchailocalauth.ProviderExecutor.

func (*OpenAICompatExecutor) PrepareRequest

func (e *OpenAICompatExecutor) PrepareRequest(_ *http.Request, _ *switchailocalauth.Auth) error

PrepareRequest is a no-op for now (credentials are added via headers at execution time).

func (*OpenAICompatExecutor) Refresh

Refresh is a no-op for API-key based compatibility providers.

type OpenAIMessage

type OpenAIMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

OpenAIMessage represents a message in an OpenAI chat completion.

type OpenAIStreamChunk

type OpenAIStreamChunk struct {
	ID      string                    `json:"id"`
	Object  string                    `json:"object"`
	Created int64                     `json:"created"`
	Model   string                    `json:"model"`
	Choices []OpenAIStreamChunkChoice `json:"choices"`
}

OpenAIStreamChunk represents a streaming chunk in OpenAI SSE format.

type OpenAIStreamChunkChoice

type OpenAIStreamChunkChoice struct {
	Index        int                    `json:"index"`
	Delta        OpenAIStreamChunkDelta `json:"delta"`
	FinishReason *string                `json:"finish_reason"`
}

OpenAIStreamChunkChoice represents a choice in a streaming chunk.

type OpenAIStreamChunkDelta

type OpenAIStreamChunkDelta struct {
	Role    string `json:"role,omitempty"`
	Content string `json:"content,omitempty"`
}

OpenAIStreamChunkDelta represents the delta content in a streaming chunk.

type OpenAIUsage

type OpenAIUsage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

OpenAIUsage represents token usage information.

type OpenCodeExecutor

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

OpenCodeExecutor handles requests to the OpenCode API.

func NewOpenCodeExecutor

func NewOpenCodeExecutor(cfg *config.Config) *OpenCodeExecutor

NewOpenCodeExecutor creates a new OpenCodeExecutor instance.

func (*OpenCodeExecutor) CountTokens

CountTokens provides a token count estimation. Note: This is a rough heuristic (~4 bytes per token). Actual token counts vary by model and tokenizer. For accurate counts, use a dedicated tokenizer.

func (*OpenCodeExecutor) Execute

Execute performs a non-streaming request to the OpenCode API.

func (*OpenCodeExecutor) ExecuteStream

ExecuteStream performs a streaming request to the OpenCode API.

func (*OpenCodeExecutor) Identifier

func (e *OpenCodeExecutor) Identifier() string

Identifier returns the executor identifier.

func (*OpenCodeExecutor) PrepareRequest

func (e *OpenCodeExecutor) PrepareRequest(_ *http.Request, _ *switchailocalauth.Auth) error

PrepareRequest prepares the HTTP request (no-op).

func (*OpenCodeExecutor) Refresh

Refresh refreshes the authentication credentials (no-op).

type OpenCodeSessionStore

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

OpenCodeSessionStore manages the mapping between client session IDs and OpenCode session IDs. It provides thread-safe access to session data with optional TTL-based expiration.

func NewOpenCodeSessionStore

func NewOpenCodeSessionStore(ttl time.Duration) *OpenCodeSessionStore

NewOpenCodeSessionStore creates a new session store with the specified TTL. If ttl is 0, sessions never expire.

func (*OpenCodeSessionStore) Count

func (s *OpenCodeSessionStore) Count() int

Count returns the number of active sessions.

func (*OpenCodeSessionStore) Delete

func (s *OpenCodeSessionStore) Delete(clientSessionID string)

Delete removes a session mapping.

func (*OpenCodeSessionStore) Get

func (s *OpenCodeSessionStore) Get(clientSessionID string) (string, bool)

Get retrieves the OpenCode session ID for a client session ID. Returns empty string if not found or expired.

func (*OpenCodeSessionStore) GetOrCreate

func (s *OpenCodeSessionStore) GetOrCreate(clientSessionID string) (string, bool)

GetOrCreate retrieves an existing OpenCode session ID or signals that a new one should be created. Returns (openCodeSessionID, isNew).

func (*OpenCodeSessionStore) Set

func (s *OpenCodeSessionStore) Set(clientSessionID, openCodeSessionID string)

Set stores the mapping between client session ID and OpenCode session ID.

func (*OpenCodeSessionStore) Stop

func (s *OpenCodeSessionStore) Stop()

Stop gracefully shuts down the session store's cleanup goroutine. This should be called when the store is no longer needed.

func (*OpenCodeSessionStore) Touch

func (s *OpenCodeSessionStore) Touch(clientSessionID string)

Touch updates the last accessed time for a session.

type QwenExecutor

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

QwenExecutor is a stateless executor for Qwen Code using OpenAI-compatible chat completions. If access token is unavailable, it falls back to legacy via ClientAdapter.

func NewQwenExecutor

func NewQwenExecutor(cfg *config.Config) *QwenExecutor

func (*QwenExecutor) ExecuteStream

func (*QwenExecutor) Identifier

func (e *QwenExecutor) Identifier() string

func (*QwenExecutor) PrepareRequest

func (e *QwenExecutor) PrepareRequest(_ *http.Request, _ *switchailocalauth.Auth) error

func (*QwenExecutor) Refresh

type SuperbrainCLIExecutor

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

SuperbrainCLIExecutor wraps LocalCLIExecutor with Superbrain monitoring and healing. It provides real-time process monitoring, failure diagnosis, stdin injection, and process recovery capabilities.

func NewSuperbrainCLIExecutor

func NewSuperbrainCLIExecutor(base *LocalCLIExecutor, cfg *config.SuperbrainConfig) *SuperbrainCLIExecutor

NewSuperbrainCLIExecutor creates a new Superbrain-enhanced CLI executor.

func (*SuperbrainCLIExecutor) CountTokens

CountTokens returns the token count for the given request.

func (*SuperbrainCLIExecutor) Execute

Execute runs the CLI tool with Superbrain monitoring and healing.

func (*SuperbrainCLIExecutor) ExecuteStream

ExecuteStream runs the CLI tool with streaming and Superbrain monitoring.

func (*SuperbrainCLIExecutor) ExecuteWithMonitoredProcess

func (se *SuperbrainCLIExecutor) ExecuteWithMonitoredProcess(ctx context.Context, binaryPath string, args []string, requestID, modelName string) (*MonitoredProcess, error)

ExecuteWithMonitoredProcess executes a CLI command with full Superbrain monitoring. This method provides direct access to the process for stdin injection and monitoring.

func (*SuperbrainCLIExecutor) Identifier

func (se *SuperbrainCLIExecutor) Identifier() string

Identifier returns the provider key handled by this executor.

func (*SuperbrainCLIExecutor) Refresh

func (se *SuperbrainCLIExecutor) Refresh(ctx context.Context, auth *sdkauth.Auth) (*sdkauth.Auth, error)

Refresh attempts to refresh provider credentials.

func (*SuperbrainCLIExecutor) SetAuditLogger

func (se *SuperbrainCLIExecutor) SetAuditLogger(logger *audit.Logger)

SetAuditLogger sets the audit logger for this executor.

func (*SuperbrainCLIExecutor) Stop

func (se *SuperbrainCLIExecutor) Stop()

Stop stops the Superbrain executor and cleans up resources.

func (*SuperbrainCLIExecutor) UpdateConfig

func (se *SuperbrainCLIExecutor) UpdateConfig(cfg *config.SuperbrainConfig)

UpdateConfig updates the Superbrain configuration at runtime.

type VibeExecutor

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

VibeExecutor wraps the local 'vibe' CLI tool.

func NewVibeExecutor

func NewVibeExecutor(cfg *config.Config) *VibeExecutor

func (*VibeExecutor) CountTokens

func (e *VibeExecutor) CountTokens(ctx context.Context, auth *auth.Auth, req executor.Request, opts executor.Options) (executor.Response, error)

func (*VibeExecutor) Execute

func (e *VibeExecutor) Execute(ctx context.Context, auth *auth.Auth, req executor.Request, opts executor.Options) (executor.Response, error)

func (*VibeExecutor) ExecuteStream

func (e *VibeExecutor) ExecuteStream(ctx context.Context, auth *auth.Auth, req executor.Request, opts executor.Options) (<-chan executor.StreamChunk, error)

func (*VibeExecutor) Identifier

func (e *VibeExecutor) Identifier() string

func (*VibeExecutor) PrepareRequest

func (e *VibeExecutor) PrepareRequest(_ *http.Request, _ *auth.Auth) error

func (*VibeExecutor) Refresh

func (e *VibeExecutor) Refresh(_ context.Context, auth *auth.Auth) (*auth.Auth, error)

Jump to

Keyboard shortcuts

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