Documentation
¶
Overview ¶
Package sdk embeds the Seshat agent runtime in a Go program.
A Client holds the configuration of the runtime (the provider and the model, the tools, the permission rules, the storage) and creates Sessions; a Session runs the turns of a conversation, calling the model and the tools it asks for, and reports what happens through callbacks and event queues.
The documentation is on the website: the Go SDK reference is at https://seshat-ai.com/en/docs/sdk/go-sdk, the installation guide at https://seshat-ai.com/en/docs/getting-started/installation and the other pages (concepts, the gRPC API, the CLI) at https://seshat-ai.com/en/docs.
Index ¶
- Constants
- func BuildWorkflowNodePrompt(node WorkflowNode, inputs map[string]WorkflowNodeResult) string
- func SandboxAvailable() bool
- func ValidateWorkflow(def WorkflowDefinition) error
- type APIProvider
- type ArtifactGCOptions
- type ArtifactGCReport
- type ArtifactListOptions
- type ArtifactMetadata
- type ArtifactNamespace
- type ArtifactPutRequest
- type ArtifactRef
- type ArtifactRetentionClass
- type ArtifactStore
- type AskResponse
- type CallResult
- type Checkpoint
- type Client
- func (c *Client) AddToolHook(hook ToolHook)
- func (c *Client) Ask(ctx context.Context, prompt string, tools []Tool) (*AskResponse, error)
- func (c *Client) AutoModeAvailable() bool
- func (c *Client) BuildToolSurface(ctx context.Context) (*Surface, error)
- func (c *Client) Close() error
- func (c *Client) CreateSession(ctx context.Context) (*Session, error)
- func (c *Client) CreateSessionWithAdditional(ctx context.Context, additional map[string]any) (*Session, error)
- func (c *Client) DeleteSession(sessionID SessionID) error
- func (c *Client) GetArtifactStore() ArtifactStore
- func (c *Client) GetMonitoring() *MonitoringSystem
- func (c *Client) GetSessionStore() SessionStore
- func (c *Client) HookRegistry() *HookRegistry
- func (c *Client) ListSessions() ([]*SessionInfo, error)
- func (c *Client) LoadSession(ctx context.Context, sessionID SessionID) (*Session, error)
- func (c *Client) LoadSessionWithAdditional(ctx context.Context, sessionID SessionID, additional map[string]any) (*Session, error)
- func (c *Client) MCPResult() *MCPIntegrationResult
- func (c *Client) MemoryInitError() error
- func (c *Client) RegisterHook(event HookEvent, handler HookHandler) (string, error)
- func (c *Client) RegisterTool(tool Tool) error
- func (c *Client) RegisterTools(tools []Tool) error
- func (c *Client) ReloadMCPServers(ctx context.Context, servers []MCPServerConfig) error
- func (c *Client) ReloadPreToolHooks(cfgs []PreToolHookConfig) error
- func (c *Client) RemoveToolHook(id string)
- func (c *Client) RunAgentTask(ctx context.Context, agentType, task string, maxTurns int) (string, error)
- func (c *Client) RunWorkflow(ctx context.Context, def WorkflowDefinition, options WorkflowOptions) (WorkflowResult, error)
- func (c *Client) SandboxKind() SandboxKind
- func (c *Client) SearchTranscriptsByContent(needle string, limit int) ([]SessionID, error)
- func (c *Client) SetProgressFn(progressFn func(ToolProgress))
- func (c *Client) SetPromptFn(promptFn PromptFn)
- func (c *Client) SetResponseChunkFn(chunkFn func(ResponseChunk))
- func (c *Client) SetRuntimeEventFn(runtimeEventFn func(RuntimeEvent))
- func (c *Client) SetWebSearchRunner(fn websearchtool.RunnerFn)
- func (c *Client) ToolNames() []string
- type ClientConfig
- type CompactionRuntimeEvent
- type ContentBlock
- type CredentialResolver
- type DenialLimitConfig
- type DenialTrackingState
- type EntryType
- type EventQueue
- type EventQueueStats
- type ExecutionMode
- type ExecutionStage
- type HookEvent
- type HookHandler
- type HookProgress
- type HookRegistration
- type HookRegistry
- type HookResult
- type HookState
- type ImageContent
- type ImageGenerationConfig
- type LocalTitleConfig
- type LongTermMemory
- type MCPIntegrationOptions
- type MCPIntegrationResult
- type MCPServerConfig
- type MCPServerResult
- type MCPTransportType
- type ManagedPolicy
- type Message
- type MessageID
- type ModelIdentifier
- type MonitoringSystem
- type OAuthDeviceChallenge
- type OAuthDeviceFlow
- func (f *OAuthDeviceFlow) AuthPath() string
- func (f *OAuthDeviceFlow) CredentialResolver() CredentialResolver
- func (f *OAuthDeviceFlow) ResolveAccessToken(ctx context.Context) (string, error)
- func (f *OAuthDeviceFlow) SaveToken(ctx context.Context, token *publicoauth.Token) error
- func (f *OAuthDeviceFlow) Start(ctx context.Context) (*OAuthDeviceChallenge, error)
- func (f *OAuthDeviceFlow) Wait(ctx context.Context, challenge *OAuthDeviceChallenge) (*publicoauth.Token, error)
- type OAuthDeviceFlowConfig
- type PermissionBehavior
- type PermissionContext
- type PermissionMode
- type PermissionResult
- type PlanRuntimeEvent
- type PlanStore
- type PreToolHookConfig
- type PromptConfig
- type PromptFn
- type PromptOption
- type PromptRequest
- type PromptResponse
- type RAGService
- type RemoteExecKind
- type RemoteExecRequest
- type RemoteExecResult
- type RemoteExecutor
- type ResponseChunk
- type ResponseChunkType
- type Role
- type RuntimeEvent
- type RuntimeEventQueue
- type RuntimeEventQueueStats
- type RuntimeEventType
- type SandboxDockerConfig
- type SandboxKind
- type Session
- func (s *Session) ClearPlanMode()
- func (s *Session) ClearRemoteExecutor()
- func (s *Session) Close() error
- func (s *Session) ForcePlanMode()
- func (s *Session) GetEventQueue() *EventQueue
- func (s *Session) GetExecutionMode() ExecutionMode
- func (s *Session) GetID() SessionID
- func (s *Session) GetMessages() []Message
- func (s *Session) GetMetadata() *SessionMetadata
- func (s *Session) GetPermissionContext() *PermissionContext
- func (s *Session) GetPermissionMode() PermissionMode
- func (s *Session) GetRuntimeEventQueue() *RuntimeEventQueue
- func (s *Session) GetStatus() SessionStatus
- func (s *Session) GetToolNames() []string
- func (s *Session) GetTotalTokens() int
- func (s *Session) GetTurnNumber() int
- func (s *Session) Interrupt() error
- func (s *Session) RegisterTool(tool Tool) error
- func (s *Session) SetAppendSystemPrompt(text string)
- func (s *Session) SetPermissionMode(mode PermissionMode)
- func (s *Session) SetProgressFn(progressFn func(ToolProgress))
- func (s *Session) SetRemoteExecutor(executor RemoteExecutor)
- func (s *Session) SetResponseChunkFn(chunkFn func(ResponseChunk))
- func (s *Session) SetRuntimeEventFn(runtimeEventFn func(RuntimeEvent))
- func (s *Session) SetSystemPromptTemplate(text string)
- func (s *Session) SetWorkingDirectory(path string)
- func (s *Session) SubmitMessage(ctx context.Context, content string) (*SessionResponse, error)
- func (s *Session) SubmitMessageWithContent(ctx context.Context, text string, images []ImageContent) (*SessionResponse, error)
- func (s *Session) UnregisterTool(name string) error
- type SessionBackend
- type SessionID
- type SessionInfo
- type SessionMetadata
- type SessionResponse
- type SessionStatus
- type SessionStore
- type SpeechToTextConfig
- type StageRuntimeEvent
- type StopHook
- type StopHookInput
- type StopHookResult
- type StorageConfig
- type StorageProviderType
- type StoredCredentialResolver
- type StoredCredentialResolverConfig
- type Surface
- type TaskRuntimeEvent
- type TextContent
- type TextToSpeechConfig
- type ThinkingContent
- type TitleGenerator
- type TokenUsage
- type Tool
- type ToolDefinition
- type ToolHook
- type ToolHookInput
- type ToolHookResult
- type ToolHookStage
- type ToolHookStop
- type ToolProgress
- type ToolProgressStage
- type ToolResultContent
- type ToolUseContent
- type TranscribeOption
- type TranscriptEntry
- type TranscriptionResult
- type TurnID
- type WebSearchRunnerFn
- type WorkflowDefinition
- type WorkflowDraftOptions
- type WorkflowDraftResult
- type WorkflowNode
- type WorkflowNodeResult
- type WorkflowOptions
- type WorkflowResult
Constants ¶
const ( // SandboxKindLocal is the zero value — Landlock on Linux, unconfined // elsewhere unless RequireSandbox is also set. Today's existing behavior. SandboxKindLocal = sandbox.EnvironmentLocal // SandboxKindDocker routes bash execution through a persistent Docker // container (internal/sandbox.DockerExecutor) — real filesystem/process // isolation plus enforced CPU/memory caps and optional network isolation. // Falls back to SandboxKindLocal with a logged warning if Docker isn't // reachable when the client is constructed. SandboxKindDocker = sandbox.EnvironmentDocker )
Sandbox backend kind values for ClientConfig.SandboxKind.
const ( RoleUser = types.RoleUser RoleAssistant = types.RoleAssistant RoleSystem = types.RoleSystem APIProviderAnthropic = types.APIProviderAnthropic APIProviderBedrock = types.APIProviderBedrock APIProviderCodex = types.APIProviderCodex APIProviderDeepSeek = types.APIProviderDeepSeek APIProviderFoundry = types.APIProviderFoundry APIProviderGemini = types.APIProviderGemini APIProviderMistral = types.APIProviderMistral APIProviderMiniMax = types.APIProviderMiniMax APIProviderOllama = types.APIProviderOllama APIProviderOpenCode = types.APIProviderOpenCode APIProviderOpenAI = types.APIProviderOpenAI APIProviderOpenRouter = types.APIProviderOpenRouter APIProviderVertex = types.APIProviderVertex APIProviderWorkersAI = types.APIProviderWorkersAI APIProviderZAi = types.APIProviderZAi APIProviderKimi = types.APIProviderKimi ExecutionModeExecute = modes.ExecutionModeExecute ExecutionModePlan = modes.ExecutionModePlan PermissionModeAuto = types.PermissionModeAuto PermissionModeBypass = types.PermissionModeBypass PermissionModeOnRequest = types.PermissionModeOnRequest PermissionModeNever = types.PermissionModeNever PermissionModeAcceptEdits = types.PermissionModeAcceptEdits PermissionModeGranular = types.PermissionModeGranular SessionStatusActive = types.SessionStatusActive SessionStatusClosed = types.SessionStatusClosed EntryTypeMessage = types.EntryTypeMessage EntryTypeTurn = types.EntryTypeTurn EntryTypeCompact = types.EntryTypeCompact EntryTypeSystem = types.EntryTypeSystem EntryTypeControl = types.EntryTypeControl ResponseChunkTypeContentBlockStart = types.APIChunkTypeContentBlockStart ResponseChunkTypeContentBlockDelta = types.APIChunkTypeContentBlockDelta ResponseChunkTypeContentBlockStop = types.APIChunkTypeContentBlockStop ResponseChunkTypeMessageDelta = types.APIChunkTypeMessageDelta ResponseChunkTypeMessageStop = types.APIChunkTypeMessageStop ResponseChunkTypeError = types.APIChunkTypeError ToolHookStagePre = execution.ToolHookStagePre ToolHookStagePost = execution.ToolHookStagePost ToolProgressStagePending = types.ToolProgressStagePending ToolProgressStageRunning = types.ToolProgressStageRunning ToolProgressStageCompleted = types.ToolProgressStageCompleted ToolProgressStageFailed = types.ToolProgressStageFailed NamespaceDocuments = storage.NamespaceDocuments NamespaceWebArtifacts = storage.NamespaceWebArtifacts NamespaceBrowserScreenshots = storage.NamespaceBrowserScreenshots NamespaceBrowserDownloads = storage.NamespaceBrowserDownloads NamespaceRAGDocuments = storage.NamespaceRAGDocuments RetentionDurable = storage.RetentionDurable RetentionTemporary = storage.RetentionTemporary RetentionSession = storage.RetentionSession RuntimeEventTypeTurnStarted = types.RuntimeEventTypeTurnStarted RuntimeEventTypeTurnCompleted = types.RuntimeEventTypeTurnCompleted RuntimeEventTypeTurnFailed = types.RuntimeEventTypeTurnFailed RuntimeEventTypeResponseChunk = types.RuntimeEventTypeResponseChunk RuntimeEventTypeToolProgress = types.RuntimeEventTypeToolProgress RuntimeEventTypePlanSubmitted = types.RuntimeEventTypePlanSubmitted RuntimeEventTypeExecutionModeChanged = types.RuntimeEventTypeExecutionModeChanged RuntimeEventTypeTaskChanged = types.RuntimeEventTypeTaskChanged RuntimeEventTypeBrowserSession = types.RuntimeEventTypeBrowserSession RuntimeEventTypeBrowserAction = types.RuntimeEventTypeBrowserAction RuntimeEventTypeBrowserPage = types.RuntimeEventTypeBrowserPage RuntimeEventTypeBrowserSnapshot = types.RuntimeEventTypeBrowserSnapshot RuntimeEventTypeBrowserScreenshot = types.RuntimeEventTypeBrowserScreenshot RuntimeEventTypeStage = types.RuntimeEventTypeStage RuntimeEventTypeCompaction = types.RuntimeEventTypeCompaction // HookEvent constants — lifecycle events emitted throughout the engine. HookEventSessionStart = types.HookEventSessionStart HookEventSessionEnd = types.HookEventSessionEnd HookEventQueryStart = types.HookEventQueryStart HookEventQueryComplete = types.HookEventQueryComplete HookEventIterationStart = types.HookEventIterationStart HookEventIterationStop = types.HookEventIterationStop HookEventIterationContinue = types.HookEventIterationContinue HookEventIterationComplete = types.HookEventIterationComplete HookEventToolUsesStart = types.HookEventToolUsesStart HookEventToolUsesComplete = types.HookEventToolUsesComplete HookEventTurnStart = types.HookEventTurnStart HookEventTurnEnd = types.HookEventTurnEnd HookEventTurnStop = types.HookEventTurnStop HookEventStopFailure = types.HookEventStopFailure HookEventPreToolUse = types.HookEventPreToolUse HookEventPostToolUse = types.HookEventPostToolUse HookEventPostToolUseFail = types.HookEventPostToolUseFail HookEventPreCompact = types.HookEventPreCompact HookEventPostCompact = types.HookEventPostCompact HookEventPreAPICall = types.HookEventPreAPICall HookEventPostAPICall = types.HookEventPostAPICall HookEventOnError = types.HookEventOnError HookEventNotification = types.HookEventNotification HookEventUserPromptSubmit = types.HookEventUserPromptSubmit HookEventSubagentStart = types.HookEventSubagentStart HookEventSubagentStop = types.HookEventSubagentStop HookEventPermissionRequest = types.HookEventPermissionRequest HookEventPermissionDenied = types.HookEventPermissionDenied HookEventSetup = types.HookEventSetup HookEventConfigChange = types.HookEventConfigChange HookEventTeammateIdle = types.HookEventTeammateIdle HookEventTaskCreated = types.HookEventTaskCreated HookEventTaskCompleted = types.HookEventTaskCompleted HookEventElicitation = types.HookEventElicitation HookEventElicitationResult = types.HookEventElicitationResult HookEventWorktreeCreate = types.HookEventWorktreeCreate HookEventWorktreeRemove = types.HookEventWorktreeRemove HookEventInstructionsLoaded = types.HookEventInstructionsLoaded HookEventCwdChanged = types.HookEventCwdChanged HookEventFileChanged = types.HookEventFileChanged // HookState constants HookStateActive = hooks.HookStateActive HookStatePaused = hooks.HookStatePaused HookStateInactive = hooks.HookStateInactive HookStateDead = hooks.HookStateDead // PermissionBehavior constants PermissionBehaviorAllow = types.PermissionBehaviorAllow PermissionBehaviorDeny = types.PermissionBehaviorDeny PermissionBehaviorAsk = types.PermissionBehaviorAsk PermissionBehaviorPassthrough = types.PermissionBehaviorPassthrough // MCPTransport constants MCPTransportStdio MCPTransportType = mcp.TransportTypeStdio MCPTransportHTTP MCPTransportType = mcp.TransportTypeHTTP MCPTransportSSE MCPTransportType = mcp.TransportTypeSSE MCPTransportWebSocket MCPTransportType = mcp.TransportTypeWebSocket )
const DefaultOpenAIDeviceClientID = "app_EMoamEEZ73f0CkXaXp7hrann"
const RemoteExecKindRemote = sandbox.EnvironmentRemote
RemoteExecKindRemote is the Kind a RemoteExecutor implementation should report — it isn't the local host (EnvironmentLocal) or a Dagger container (EnvironmentDocker), it's an external channel back to the host app.
Variables ¶
This section is empty.
Functions ¶
func BuildWorkflowNodePrompt ¶
func BuildWorkflowNodePrompt(node WorkflowNode, inputs map[string]WorkflowNodeResult) string
BuildWorkflowNodePrompt builds the prompt of a node for its agent: the role of its kind (verifier, critic, router), the outputs of the nodes it needs, the prompt of the node and its output format.
func SandboxAvailable ¶
func SandboxAvailable() bool
SandboxAvailable reports whether an OS-level sandbox (currently: Landlock, Linux-only) is available on this host to confine bash tool execution. Host applications use this to surface the unconfined-execution tradeoff to the end user (e.g. in a settings UI) rather than leaving it as a backend-log-only warning.
func ValidateWorkflow ¶
func ValidateWorkflow(def WorkflowDefinition) error
ValidateWorkflow checks a definition: it has at least one node, every node has a unique id and a prompt and a supported kind, a router declares routes, the nodes it needs and routes to exist (a router cannot route to itself), and the dependencies contain no cycle.
Types ¶
type ArtifactGCOptions ¶
Storage data types — re-exported so SDK callers don't need to import internal/storage.
type ArtifactGCReport ¶
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ArtifactListOptions ¶
type ArtifactListOptions = storage.ListOptions
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ArtifactMetadata ¶
type ArtifactMetadata = storage.ArtifactMetadata
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ArtifactNamespace ¶
type ArtifactNamespace = storage.ArtifactNamespace
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ArtifactPutRequest ¶
type ArtifactPutRequest = storage.ArtifactPutRequest
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ArtifactRef ¶
type ArtifactRef = storage.ArtifactRef
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ArtifactRetentionClass ¶
type ArtifactRetentionClass = storage.ArtifactRetentionClass
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ArtifactStore ¶
type ArtifactStore interface {
Put(ctx context.Context, key string, body []byte, contentType string) (ArtifactRef, error)
PutArtifact(ctx context.Context, request ArtifactPutRequest, body []byte) (ArtifactRef, error)
Get(ctx context.Context, key string) ([]byte, error)
OpenReader(ctx context.Context, key string) (io.ReadCloser, ArtifactRef, error)
Stat(ctx context.Context, key string) (ArtifactRef, error)
List(ctx context.Context, options ArtifactListOptions) ([]ArtifactRef, error)
Metadata(ctx context.Context, key string) (ArtifactMetadata, error)
ListMetadata(ctx context.Context, options ArtifactListOptions) ([]ArtifactMetadata, error)
GarbageCollect(ctx context.Context, options ArtifactGCOptions) (ArtifactGCReport, error)
Delete(ctx context.Context, key string) error
Exists(ctx context.Context, key string) (bool, error)
URL(ctx context.Context, key string) (string, error)
}
ArtifactStore is the SDK-owned artifact storage contract.
func DefaultArtifactStore ¶
func DefaultArtifactStore() (ArtifactStore, error)
DefaultArtifactStore returns the process-wide artifact store configured for the runtime.
func NewArtifactStoreFromConfig ¶
func NewArtifactStoreFromConfig(cfg StorageConfig) (ArtifactStore, error)
NewArtifactStoreFromConfig constructs an artifact store from an explicit SDK storage config without touching the process-wide singleton.
type AskResponse ¶
type AskResponse struct {
Content string `json:"content"`
Thinking string `json:"thinking,omitempty"`
ToolUses []ToolUseContent `json:"tool_uses"`
ToolResults []CallResult `json:"tool_results"`
Usage *TokenUsage `json:"usage"`
IsComplete bool `json:"is_complete"`
}
AskResponse represents the response from a single-turn query.
type CallResult ¶
type CallResult = contract.CallResult
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type Checkpoint ¶
type Checkpoint = state.Checkpoint
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client provides a high-level SDK for headless AI operations.
func NewClient ¶
func NewClient(config *ClientConfig) (*Client, error)
NewClient creates a new SDK client.
func (*Client) AddToolHook ¶
AddToolHook registers a host-side tool hook on the shared orchestrator.
func (*Client) AutoModeAvailable ¶
AutoModeAvailable reports whether the permission integrator has an AI-backed auto-mode classifier wired and ready.
func (*Client) BuildToolSurface ¶
BuildToolSurface builds the current external tool surface for the client.
func (*Client) CreateSession ¶
CreateSession creates a new session for multi-turn conversations. The session is assigned a sequential human-readable title of the form "untitled_session_N" where N is 1 + the highest N already in use.
func (*Client) CreateSessionWithAdditional ¶
func (c *Client) CreateSessionWithAdditional(ctx context.Context, additional map[string]any) (*Session, error)
CreateSessionWithAdditional creates a new session with pre-populated additional metadata.
func (*Client) DeleteSession ¶
DeleteSession deletes a session and all associated artifacts from storage.
func (*Client) GetArtifactStore ¶
func (c *Client) GetArtifactStore() ArtifactStore
GetArtifactStore returns the configured SDK-visible artifact store.
func (*Client) GetMonitoring ¶
func (c *Client) GetMonitoring() *MonitoringSystem
GetMonitoring returns the underlying monitoring system.
func (*Client) GetSessionStore ¶
func (c *Client) GetSessionStore() SessionStore
GetSessionStore returns the configured SDK-visible session store.
func (*Client) HookRegistry ¶
func (c *Client) HookRegistry() *HookRegistry
HookRegistry returns the engine's lifecycle hook registry.
func (*Client) ListSessions ¶
func (c *Client) ListSessions() ([]*SessionInfo, error)
ListSessions lists all sessions.
func (*Client) LoadSession ¶
LoadSession loads an existing session.
func (*Client) LoadSessionWithAdditional ¶
func (c *Client) LoadSessionWithAdditional(ctx context.Context, sessionID SessionID, additional map[string]any) (*Session, error)
LoadSessionWithAdditional loads an existing session and merges additional metadata keys. Keys already present in the session are not overwritten.
func (*Client) MCPResult ¶
func (c *Client) MCPResult() *MCPIntegrationResult
MCPResult returns the outcome of MCP server integration.
func (*Client) MemoryInitError ¶
MemoryInitError returns the error from memory service initialization, if any.
func (*Client) RegisterHook ¶
func (c *Client) RegisterHook(event HookEvent, handler HookHandler) (string, error)
RegisterHook registers a handler for a single lifecycle event. It returns an error for an event the runtime never fires (types.ImplementedHookEvents) instead of silently accepting a handler that will never run - see H4 in TODO.md. This is a breaking change: RegisterHook used to always return a bare id.
func (*Client) RegisterTool ¶
RegisterTool registers a tool globally.
func (*Client) RegisterTools ¶
RegisterTools registers multiple tools globally.
func (*Client) ReloadMCPServers ¶
func (c *Client) ReloadMCPServers(ctx context.Context, servers []MCPServerConfig) error
ReloadMCPServers hot-reloads MCP server integrations without restarting the client.
func (*Client) ReloadPreToolHooks ¶
func (c *Client) ReloadPreToolHooks(cfgs []PreToolHookConfig) error
ReloadPreToolHooks replaces this client's entire shell pre-tool hook set with cfgs, live - unlike PreToolHooks on ClientConfig, which is only ever read once inside NewClient. Safe to call with an empty cfgs to clear every hook (e.g. an org revoking what it shares, or a user withdrawing local approval) without leaving a stale, no-longer-wanted command able to run.
func (*Client) RemoveToolHook ¶
RemoveToolHook drops every previously-registered hook with the given ID.
func (*Client) RunAgentTask ¶
func (c *Client) RunAgentTask(ctx context.Context, agentType, task string, maxTurns int) (string, error)
RunAgentTask runs task as agentType (a built-in agent type, e.g. AgentTypeGeneralPurpose) for up to maxTurns autonomous turns - 0 means a single turn, same as Ask - and returns its final text output. Used by RunWorkflow's default executor when a workflow.Node declares Agent/ MaxTurns; exposed publicly so a custom Executor can reuse the same mechanism instead of reimplementing it.
func (*Client) RunWorkflow ¶
func (c *Client) RunWorkflow(ctx context.Context, def WorkflowDefinition, options WorkflowOptions) (WorkflowResult, error)
RunWorkflow runs def. Each node is executed by options.Executor or, when none is given, by asking the model with the prompt of the node and the outputs of the nodes it needs (Ask, with options.Tools).
func (*Client) SandboxKind ¶
func (c *Client) SandboxKind() SandboxKind
SandboxKind reports which sandbox backend this client's bash tool actually resolved to at construction (SandboxKindDocker only if it was requested via ClientConfig.SandboxKind AND Docker passed its health check at startup; SandboxKindLocal otherwise). Host applications use this instead of the package-level SandboxAvailable(), which only ever checks Landlock and so can't reflect a Docker sandbox this specific client is actually using.
func (*Client) SearchTranscriptsByContent ¶
SearchTranscriptsByContent lists sessions whose stored transcript contains needle.
func (*Client) SetProgressFn ¶
func (c *Client) SetProgressFn(progressFn func(ToolProgress))
SetProgressFn updates the host callback for live tool execution progress.
func (*Client) SetPromptFn ¶
SetPromptFn updates the runtime prompt bridge.
func (*Client) SetResponseChunkFn ¶
func (c *Client) SetResponseChunkFn(chunkFn func(ResponseChunk))
SetResponseChunkFn updates the host callback for live model stream chunks.
func (*Client) SetRuntimeEventFn ¶
func (c *Client) SetRuntimeEventFn(runtimeEventFn func(RuntimeEvent))
SetRuntimeEventFn updates the host callback for structured runtime events.
func (*Client) SetWebSearchRunner ¶
func (c *Client) SetWebSearchRunner(fn websearchtool.RunnerFn)
SetWebSearchRunner installs a per-request runner on the web_search tool.
type ClientConfig ¶
type ClientConfig struct {
APIKey string `json:"api_key"`
Model ModelIdentifier `json:"model"`
TitleModel ModelIdentifier `json:"title_model,omitempty"`
// CompactSummaryModel overrides which model generates compaction summaries.
// Zero value means "use Model" (the session's own model), so compaction
// works on any provider without needing an Anthropic key.
CompactSummaryModel ModelIdentifier `json:"compact_summary_model,omitempty"`
// TrustProjectInstructions gates SESHAT.md/AGENTS.md/.seshat/instructions.md
// found in WorkingDir behind project trust before they are injected into
// the system prompt (see docs/project-trust.md). It is called with the
// file's exact path and content; return true to trust and inject it. nil
// fails closed - no project you didn't write or explicitly trust can put
// its own instructions in the model's prompt. A host that already trusts
// projects for other configuration (the terminal interface's `seshat
// trust`) should wire this to the same hash-based check.
TrustProjectInstructions func(path string, content []byte) bool `json:"-"`
PermissionMode PermissionMode `json:"permission_mode"`
MaxTurns int `json:"max_turns"`
AutoCompact bool `json:"auto_compact"`
// Session persistence
PersistSessions bool `json:"persist_sessions"`
SessionStorageDir string `json:"session_storage_dir"`
SessionSQLitePath string `json:"session_sqlite_path"`
SessionBackend SessionBackend `json:"-"`
SessionStore SessionStore `json:"-"`
// MCP
MCPServers []MCPServerConfig `json:"mcp_servers"`
// Callbacks
PromptFn PromptFn `json:"-"`
ProgressFn func(ToolProgress) `json:"-"`
ResponseChunkFn func(ResponseChunk) `json:"-"`
RuntimeEventFn func(RuntimeEvent) `json:"-"`
// OnSessionTitled is called after the engine auto-generates a title for a
// session (once, after the first completed turn). The id is the session ID
// and title is the short, AI-generated label. Use this to refresh the UI.
OnSessionTitled func(id SessionID, title string) `json:"-"`
// Filesystem
WorkingDir string `json:"working_dir"`
// Browser
BrowserRemoteControlURL string `json:"browser_remote_control_url"`
BrowserExecutablePath string `json:"browser_executable_path"`
// BrowserSessionTargetResolver, when set, lets a caller (the desktop app)
// attach a session's browser tool calls directly to an existing CDP tab
// it already shows live to the user, instead of opening an invisible
// incognito context - see internal/web/browser.Config.TargetResolver for
// the full rationale. Optional; nil preserves the default behavior.
BrowserSessionTargetResolver func(ctx context.Context, sessionID SessionID) (targetID string, ok bool) `json:"-"`
// Storage
StorageConfig *StorageConfig `json:"-"`
ArtifactStore ArtifactStore `json:"-"`
StorageGCEnabled bool `json:"storage_gc_enabled"`
StorageGCInterval time.Duration `json:"storage_gc_interval"`
StorageGCLimit int `json:"storage_gc_limit"`
StorageGCNamespaces []string `json:"storage_gc_namespaces"`
// CredentialResolver, if set, is called at client creation to resolve the
// API key for the configured provider. Takes precedence over APIKey.
// Use in server mode to inject per-user credentials from a database.
CredentialResolver CredentialResolver `json:"-"`
// Provider override
ProviderConfig *providers.Config `json:"-"`
// TitleProviderConfig overrides the provider client used only for automatic
// session title generation. This allows a tiny local/Hugging Face-served
// model to title chats while the main chat model stays unchanged.
TitleProviderConfig *providers.Config `json:"-"`
// TitleGenerator takes precedence over TitleProviderConfig/TitleModel.
// Use this for local, no-server title models.
TitleGenerator TitleGenerator `json:"-"`
// LocalTitle configures the default local title generator. It is ignored
// when TitleGenerator is set.
LocalTitle *LocalTitleConfig `json:"local_title,omitempty"`
// Monitoring
Monitoring *MonitoringSystem `json:"-"`
// Interactive prompting
EnablePromptReaderFallback bool `json:"enable_prompt_reader_fallback"`
// Memory
EnableMemory bool `json:"enable_memory"`
MemoryFailFast bool `json:"memory_fail_fast"`
// Feature flags
EnableHooks bool `json:"enable_hooks"`
EnableMonitoring bool `json:"enable_monitoring"`
DisableTitleGeneration bool `json:"disable_title_generation"`
// Model parameters
MaxTokens int `json:"max_tokens"`
MaxIterations int `json:"max_iterations"`
TurnTokenBudget int `json:"turn_token_budget"`
BudgetContinuationLimit int `json:"budget_continuation_limit"`
ContinuationNudgeLimit int `json:"continuation_nudge_limit"`
MaxConsecutiveDenials int `json:"max_consecutive_denials"`
// System prompt
SystemPromptTemplate string `json:"system_prompt_template"`
PromptConfig *PromptConfig `json:"-"`
Companion *companion.Profile `json:"companion,omitempty"`
// ManagedPolicy is what the organization that runs the host imposes on every agent: a text to
// follow and tools never to use. Set it from an administrator's configuration, not from the end
// user's. See ManagedPolicy.
ManagedPolicy *ManagedPolicy `json:"-"`
// Stop hooks
StopHooks []StopHook `json:"-"`
// PreToolHooks are shell-based hooks that fire before each tool execution.
// Each entry is a HookConfig: {Matcher, Command, Timeout}.
// Compatible with crush's pre_tool_use hook format:
// - exit 0 + no JSON → allow (no-op)
// - exit 0 + {"decision":"allow"} → allow + skip permission prompt
// - exit 0 + {"updatedInput":"..."} → rewrite tool input
// - exit 2 + stderr → deny with reason
// - exit 49 → halt entire turn
// Set via ClientConfig.PreToolHooks or loaded automatically from
// config.Hooks["pre_tool_use"] by newClient().
PreToolHooks []PreToolHookConfig `json:"-"`
// RAG / Plan / Memory
RAGService *RAGService `json:"-"`
PlanStore PlanStore `json:"-"`
LongTermMemory LongTermMemory `json:"-"`
// UserID identifies the caller for PlanStore.CreateOrUpdate (submit_plan)
// - a host embedding this SDK for more than one user must set this per
// request/session so plan documents get persisted against the actual
// caller, not left unattributed. Never sent anywhere itself; only
// threaded through to PlanStore.
UserID string `json:"-"`
// Document conversion
// DocumentReaderURL is the base URL of a document-reader service. Used
// to build the default DocumentConverter when that field is left nil.
DocumentReaderURL string `json:"document_reader_url,omitempty"`
// DocumentConverter, when set, is used instead of building a
// service client from DocumentReaderURL. Inject a custom converter
// implementation (local native reader, seshat-intelligence, marker, etc.)
// to back the SDK's document-conversion tools. Takes precedence over
// DocumentReaderURL.
DocumentConverter documentreader.Converter `json:"-"`
// DocumentPageRenderer, when set, backs render_document_page so agents can
// inspect visual pages with a multimodal model after markdown extraction.
DocumentPageRenderer pdfsmart.PageRenderer `json:"-"`
// Automation daemon connection (seshat-automation).
// When set, the schedule_job / list_jobs / update_job / delete_job / pause_job /
// resume_job / run_job_now tools become functional.
AutomationServiceURL string `json:"automation_service_url,omitempty"`
AutomationAPIKey string `json:"-"`
// WebSearchKeys provides per-execution web search provider keys.
// When set, the web_search tool uses these keys instead of reading from the
// process environment, preventing key leakage across concurrent sessions.
// Keys are keyed by provider name: "tavily", "exa", "jina", "langsearch".
WebSearchKeys map[string]string `json:"-"`
// ResearchKeys provides per-execution credentials for the research tools: reddit_client_id,
// reddit_client_secret, youtube_api_key, google_places_api_key, trustpilot_api_key. When set, only
// these are used and the process environment is not read, preventing key leakage across concurrent
// sessions of a shared server. Without them the environment variables of the same names (upper case)
// are used, which suits a single-user host. A research tool without its keys is not offered to the model.
ResearchKeys map[string]string `json:"-"`
// Optional capability-specific providers for multimodal built-in tools.
ImageGeneration *ImageGenerationConfig `json:"image_generation,omitempty"`
TextToSpeech *TextToSpeechConfig `json:"text_to_speech,omitempty"`
SpeechToText *SpeechToTextConfig `json:"speech_to_text,omitempty"`
// RequireSandbox makes the bash tool refuse to run commands when no
// OS-level sandbox (currently: Landlock, Linux-only) is available on the
// host, instead of silently falling back to unconfined execution. Leave
// false for desktop use where refusing to run bash entirely is worse UX
// than a visible unsandboxed-execution warning; set true for multi-tenant
// server deployments where unconfined execution must never happen.
RequireSandbox bool `json:"require_sandbox"`
// SandboxKind selects the OS-level sandbox backend for bash tool
// execution. Empty (SandboxKindLocal) preserves existing behavior.
// SandboxKindDocker routes execution through a persistent Docker
// container — see SandboxDocker.
SandboxKind SandboxKind `json:"sandbox_kind,omitempty"`
// SandboxDocker configures the Docker sandbox backend when SandboxKind
// is SandboxKindDocker. Zero value uses sane, security-conscious
// defaults (see sandbox.DefaultDockerConfig).
SandboxDocker SandboxDockerConfig `json:"-"`
// EnableToolSearch keeps deferred tools (MCP tools, and any built-in
// tool registering with ShouldDefer, e.g. skill) out of the model's
// initial tool list - the model calls the tool_search tool to discover
// and use them instead. False (the default) leaves the
// ENABLE_TOOL_SEARCH environment variable as the decider (so existing
// deployments setting it keep working); true enables it regardless of
// that variable. There is no way to force it off through this field
// alone if the environment variable is also set - unset that variable
// too for a host that wants this field to be the single source of truth.
EnableToolSearch bool `json:"enable_tool_search,omitempty"`
}
ClientConfig represents the client configuration.
func DefaultClientConfig ¶
func DefaultClientConfig() *ClientConfig
DefaultClientConfig returns default client configuration.
type CompactionRuntimeEvent ¶
type CompactionRuntimeEvent = types.CompactionRuntimeEvent
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ContentBlock ¶
type ContentBlock = types.ContentBlock
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type CredentialResolver ¶
type CredentialResolver interface {
ResolveAPIKey(ctx context.Context, provider string) (string, error)
}
CredentialResolver resolves the API key for an LLM provider at client creation time. The provider argument matches types.APIProvider values (e.g. "anthropic", "openai", "codex").
CLI / headless mode: not needed — the default env-var → FileStore resolution in internal/providers/auth.go applies automatically.
Server mode: implement this interface to inject per-user credentials from a database instead of relying on a single global API key.
type DenialLimitConfig ¶
type DenialLimitConfig = types.DenialLimitConfig
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type DenialTrackingState ¶
type DenialTrackingState = types.DenialTrackingState
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type EntryType ¶
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type EventQueue ¶
type EventQueue = execution.EventQueue
SDK-owned eventing, monitoring, and MCP integration types.
type EventQueueStats ¶
type EventQueueStats = execution.EventQueueStats
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ExecutionMode ¶
type ExecutionMode = modes.ExecutionMode
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ExecutionStage ¶
type ExecutionStage = prompt.ExecutionStage
ExecutionStage is the re-exported execution stage type. Use the Stage* constants to specify the desired behavior overlay.
const ( // StageDefault is the baseline mode — no overlay injected. StageDefault ExecutionStage = prompt.StageDefault // StageToolCall tells the model it is expected to dispatch tool calls. StageToolCall ExecutionStage = prompt.StageToolCall // StageToolResult tells the model to integrate the received tool results. StageToolResult ExecutionStage = prompt.StageToolResult // StageContinuation tells the model to resume from where it stopped. StageContinuation ExecutionStage = prompt.StageContinuation // StagePlan puts the engine in plan mode: tools are shown but not executed. StagePlan ExecutionStage = prompt.StagePlan )
Stage constants for use in PromptConfig.
type HookHandler ¶
type HookHandler = hooks.HookHandler
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type HookProgress ¶
type HookProgress = types.HookProgress
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type HookRegistration ¶
type HookRegistration = hooks.HookRegistration
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type HookRegistry ¶
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type HookResult ¶
type HookResult = types.HookResult
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type HookState ¶
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ImageContent ¶
type ImageContent = types.ImageContent
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ImageGenerationConfig ¶
type ImageGenerationConfig struct {
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
APIKey string `json:"api_key,omitempty"`
BaseURL string `json:"base_url,omitempty"`
}
ImageGenerationConfig controls the generate_image built-in tool.
type LocalTitleConfig ¶
type LocalTitleConfig struct {
Enabled bool `json:"enabled,omitempty"`
Runtime string `json:"runtime,omitempty"`
ExecutablePath string `json:"executable_path,omitempty"`
ModelPath string `json:"model_path,omitempty"`
HFRepo string `json:"hf_repo,omitempty"`
HFFile string `json:"hf_file,omitempty"`
CacheDir string `json:"cache_dir,omitempty"`
Args []string `json:"args,omitempty"`
Timeout time.Duration `json:"timeout,omitempty"`
}
LocalTitleConfig runs a small local model for session title generation, without Ollama or a long-running local server. The first runtime is llama.cpp-compatible GGUF through llama-cli.
type LongTermMemory ¶
LongTermMemory — re-exported so SDK callers can inject it without importing internal/memory/longterm.
type MCPIntegrationOptions ¶
type MCPIntegrationOptions = mcp.IntegrationOptions
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type MCPIntegrationResult ¶
type MCPIntegrationResult = mcp.IntegrationResult
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type MCPServerConfig ¶
type MCPServerConfig = mcp.ServerConfig
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type MCPServerResult ¶
type MCPServerResult = mcp.ServerResult
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type MCPTransportType ¶
type MCPTransportType = mcp.TransportType
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ManagedPolicy ¶
type ManagedPolicy struct {
// Instructions is the text every agent must follow, appended to its system prompt.
Instructions string `json:"instructions,omitempty"`
// ForbiddenTools lists tool names that no agent may use. A name matches the tool and its
// aliases; an MCP tool is named like "mcp__server__tool".
ForbiddenTools []string `json:"forbidden_tools,omitempty"`
}
ManagedPolicy is what whoever runs the host (a company, through its server) imposes on every agent: a text the agent must follow and a list of tools it must never use.
It is meant to be set by the host from an administrator's configuration, never from the end user's own settings, and it cannot be loosened from inside a session: the instructions come last in the system prompt whatever a session sets, the forbidden tools are removed from the tool list the model sees, and a deny rule that outranks every other permission rule (the "bypass" permission mode included) refuses a call to them anyway.
The instructions are a soft guarantee (a model follows them very reliably, not absolutely); the forbidden tools are a hard one, applied by the program.
type Message ¶
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type MessageID ¶
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ModelIdentifier ¶
type ModelIdentifier = types.ModelIdentifier
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type MonitoringSystem ¶
type MonitoringSystem = monitoring.System
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type OAuthDeviceChallenge ¶
type OAuthDeviceChallenge struct {
DeviceCode string
UserCode string
VerificationURL string
VerificationURLComplete string
ExpiresIn int
Interval int
}
OAuthDeviceChallenge is the user-facing challenge returned by a device flow.
type OAuthDeviceFlow ¶
type OAuthDeviceFlow struct {
// contains filtered or unexported fields
}
OAuthDeviceFlow is a reusable public wrapper around the OpenAI / Codex device flow. It can persist the resulting token and expose a resolver that plugs directly into sdk.ClientConfig.
func NewOAuthDeviceFlow ¶
func NewOAuthDeviceFlow(config OAuthDeviceFlowConfig) (*OAuthDeviceFlow, error)
NewOAuthDeviceFlow creates a public SDK-friendly device flow for providers backed by ChatGPT OAuth, currently codex and openai.
func (*OAuthDeviceFlow) AuthPath ¶
func (f *OAuthDeviceFlow) AuthPath() string
AuthPath returns the auth-store path used by the flow.
func (*OAuthDeviceFlow) CredentialResolver ¶
func (f *OAuthDeviceFlow) CredentialResolver() CredentialResolver
CredentialResolver returns a resolver that uses the same auth store.
func (*OAuthDeviceFlow) ResolveAccessToken ¶
func (f *OAuthDeviceFlow) ResolveAccessToken(ctx context.Context) (string, error)
ResolveAccessToken resolves a valid access token from the configured auth store, refreshing it when possible.
func (*OAuthDeviceFlow) SaveToken ¶
func (f *OAuthDeviceFlow) SaveToken(ctx context.Context, token *publicoauth.Token) error
SaveToken persists the token into the SDK auth store for this provider.
func (*OAuthDeviceFlow) Start ¶
func (f *OAuthDeviceFlow) Start(ctx context.Context) (*OAuthDeviceChallenge, error)
Start begins the device flow and returns the user challenge to display.
func (*OAuthDeviceFlow) Wait ¶
func (f *OAuthDeviceFlow) Wait(ctx context.Context, challenge *OAuthDeviceChallenge) (*publicoauth.Token, error)
Wait blocks until the device flow completes, optionally persisting the resulting token for later SDK sessions.
type OAuthDeviceFlowConfig ¶
OAuthDeviceFlowConfig configures a public device-flow login that can be used by SDK hosts to authenticate Codex / ChatGPT-backed providers without going through the CLI.
type PermissionContext ¶
type PermissionContext = types.PermissionContext
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type PermissionMode ¶
type PermissionMode = types.PermissionMode
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type PermissionResult ¶
type PermissionResult = types.PermissionResult
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type PlanRuntimeEvent ¶
type PlanRuntimeEvent = types.PlanRuntimeEvent
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type PlanStore ¶
PlanStore — re-exported so SDK callers can inject it without importing internal/tools/builtin.
type PreToolHookConfig ¶
type PreToolHookConfig struct {
Matcher string // regex against tool name; empty = match all
Command string // shell command to execute
Timeout int // timeout in seconds (default 30)
}
PreToolHookConfig is a single shell hook that runs before a tool call.
type PromptConfig ¶
type PromptConfig struct {
// SystemPrompt replaces the entire default system prompt.
// When set, CorePromptSections and StageOverlay are not used.
SystemPrompt *string `json:"system_prompt,omitempty"`
// AppendSystemPrompt is appended after all other sections every turn.
AppendSystemPrompt *string `json:"append_system_prompt,omitempty"`
// Stage sets the execution stage context for this session.
// The corresponding overlay is injected into the dynamic section each turn.
//
// Use StageDefault (the zero value) for normal operation.
// Use StagePlan to suspend tool execution and request a plan description.
// Use StageToolResult / StageContinuation when wiring the loop manually.
Stage ExecutionStage `json:"stage,omitempty"`
// StageOverrides replaces the built-in overlay text for specific stages.
// Key: stage constant (e.g. StagePlan), Value: replacement overlay text.
StageOverrides map[ExecutionStage]string `json:"stage_overrides,omitempty"`
// ToolHints provides per-tool guidance appended to provider-facing descriptions.
// This is an app-level layer: it adds guidance without modifying tool definitions.
// Key: canonical tool name (e.g. "bash", "read"), Value: hint text.
ToolHints map[string]string `json:"tool_hints,omitempty"`
}
PromptConfig provides structured customization of the system prompt.
It is a first-class SDK concept: apps configure it once at the client or session level, and the engine applies it every turn without modifying the core prompt sections.
Structure of the assembled system prompt:
[CorePromptSections] — identity, runtime_contract, working_rules, tool_use, output_discipline [dynamic boundary] [RuntimeContext] — session_id, turn_number, model, available_tools, … [RuntimeGuidance] [MemoryContext] — if memory is enabled [StageOverlay] — injected from Stage / StageOverrides when Stage != StageDefault [AppendSystemPrompt] — appended after all other sections
Tool definitions sent to the provider are built from the tool registry. ToolHints are appended to the provider-facing description of individual tools without requiring changes to the tool definition itself.
type PromptFn ¶
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type PromptOption ¶
type PromptOption = types.PromptOption
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type PromptRequest ¶
type PromptRequest = types.PromptRequest
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type PromptResponse ¶
type PromptResponse = types.PromptResponse
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type RAGService ¶
RAGService — re-exported so SDK callers can inject it without importing internal/rag.
type RemoteExecKind ¶
type RemoteExecKind = sandbox.EnvironmentKind
RemoteExecKind identifies a RemoteExecutor backend (RemoteExecutor.Kind).
type RemoteExecRequest ¶
type RemoteExecRequest = sandbox.RunRequest
RemoteExecRequest is the input to a RemoteExecutor.Run call.
type RemoteExecResult ¶
RemoteExecResult is the output of a RemoteExecutor.Run call.
type RemoteExecutor ¶
RemoteExecutor lets a host application (e.g. seshat-backend, driven by Electron's terminal relay) route a session's bash-tool execution through an external channel instead of the engine's own local subprocess — see Session.SetRemoteExecutor. Implementations satisfy internal/sandbox.Executor; this alias is the exported SDK surface for it.
type ResponseChunk ¶
type ResponseChunk = types.APIResponseChunk
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ResponseChunkType ¶
type ResponseChunkType = types.APIChunkType
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type RuntimeEvent ¶
type RuntimeEvent = types.RuntimeEvent
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type RuntimeEventQueue ¶
type RuntimeEventQueue = execution.RuntimeEventQueue
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type RuntimeEventQueueStats ¶
type RuntimeEventQueueStats = execution.RuntimeEventQueueStats
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type RuntimeEventType ¶
type RuntimeEventType = types.RuntimeEventType
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type SandboxDockerConfig ¶
type SandboxDockerConfig = sandbox.DockerExecutorConfig
SandboxDockerConfig configures the Docker sandbox backend used when ClientConfig.SandboxKind is SandboxKindDocker. See sandbox.DockerExecutorConfig for field-by-field documentation.
type SandboxKind ¶
type SandboxKind = sandbox.EnvironmentKind
SandboxKind selects an OS-level sandbox backend for bash tool execution.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session represents a multi-turn conversation session.
func (*Session) ClearPlanMode ¶
func (s *Session) ClearPlanMode()
ClearPlanMode exits plan mode in the session context, restoring the previous permission mode. This allows the host to pre-exit plan mode on user approval without the model needing to call exit_plan_mode itself.
func (*Session) ClearRemoteExecutor ¶
func (s *Session) ClearRemoteExecutor()
ClearRemoteExecutor detaches this session's remote execution backend — subsequent bash-tool calls fall back to local execution.
func (*Session) Close ¶
Close ends the session: it cancels a turn that is running, persists the memory of the session and releases what it holds (the browser session, the event queues). It is idempotent.
func (*Session) ForcePlanMode ¶
func (s *Session) ForcePlanMode()
ForcePlanMode enters plan mode in the session context directly, allowing the host to force a session into plan mode without waiting for the model to call enter_plan_mode itself.
func (*Session) GetEventQueue ¶
func (s *Session) GetEventQueue() *EventQueue
GetEventQueue returns the streaming event queue of the session, which a caller can read instead of setting a callback.
func (*Session) GetExecutionMode ¶
func (s *Session) GetExecutionMode() ExecutionMode
GetExecutionMode returns the execution mode of the session.
func (*Session) GetMessages ¶
GetMessages returns the conversation so far, in order.
func (*Session) GetMetadata ¶
func (s *Session) GetMetadata() *SessionMetadata
GetMetadata returns the metadata the session keeps about itself, its identifier and status among others.
func (*Session) GetPermissionContext ¶
func (s *Session) GetPermissionContext() *PermissionContext
GetPermissionContext returns the permission context of the session: the mode and the rules its tool calls are checked against.
func (*Session) GetPermissionMode ¶
func (s *Session) GetPermissionMode() PermissionMode
GetPermissionMode returns the permission mode of the session, which decides which tool calls are asked about.
func (*Session) GetRuntimeEventQueue ¶
func (s *Session) GetRuntimeEventQueue() *RuntimeEventQueue
GetRuntimeEventQueue returns the structured runtime event queue of the session, which a caller can read instead of setting a callback.
func (*Session) GetStatus ¶
func (s *Session) GetStatus() SessionStatus
GetStatus returns the current status of the session, or an empty status when the session has no metadata.
func (*Session) GetToolNames ¶
GetToolNames returns the names of the tools available in the session.
func (*Session) GetTotalTokens ¶
GetTotalTokens returns the tokens the session has used so far, or 0 on a nil session.
func (*Session) GetTurnNumber ¶
GetTurnNumber returns the number of turns the session has run, or 0 on a nil session.
func (*Session) Interrupt ¶
Interrupt cancels the turn that is running and marks the session as interrupted. It can be called from another goroutine while SubmitMessage is waiting.
func (*Session) RegisterTool ¶
RegisterTool makes tool available to the model in this session. It returns an error when the tool cannot be registered.
func (*Session) SetAppendSystemPrompt ¶
SetAppendSystemPrompt sets text that is appended to the system prompt of this session. It does nothing on a nil session.
func (*Session) SetPermissionMode ¶
func (s *Session) SetPermissionMode(mode PermissionMode)
SetPermissionMode changes the permission mode of the session from the next tool call on. It does nothing on a nil session.
func (*Session) SetProgressFn ¶
func (s *Session) SetProgressFn(progressFn func(ToolProgress))
SetProgressFn sets the function called with the progress of a running tool. It does nothing on a nil session.
func (*Session) SetRemoteExecutor ¶
func (s *Session) SetRemoteExecutor(executor RemoteExecutor)
SetRemoteExecutor registers executor as this session's remote execution backend — subsequent bash-tool calls in this session run through it instead of a local subprocess (see bash.Tool.executeCommand). A re-registration replaces any previous executor for the session.
func (*Session) SetResponseChunkFn ¶
func (s *Session) SetResponseChunkFn(chunkFn func(ResponseChunk))
SetResponseChunkFn sets the function called with each chunk of the model's response as it streams in. It does nothing on a nil session.
func (*Session) SetRuntimeEventFn ¶
func (s *Session) SetRuntimeEventFn(runtimeEventFn func(RuntimeEvent))
SetRuntimeEventFn sets the function called with each structured runtime event of the session. It does nothing on a nil session.
func (*Session) SetSystemPromptTemplate ¶
SetSystemPromptTemplate sets a template that fully replaces the default system prompt of this session. An empty text clears the override. It does nothing on a nil session.
func (*Session) SetWorkingDirectory ¶
SetWorkingDirectory sets the directory the tools of the session work in (files, shell) from now on. It does nothing on a nil session.
func (*Session) SubmitMessage ¶
SubmitMessage sends a plain-text user message and runs the turn it starts: the model answers, calls the tools it asks for, and the response (messages, tool uses and results, usage, stop reason) comes back when the turn ends. It streams through the callbacks and queues set on the session, and ctx cancels the turn.
func (*Session) SubmitMessageWithContent ¶
func (s *Session) SubmitMessageWithContent(ctx context.Context, text string, images []ImageContent) (*SessionResponse, error)
SubmitMessageWithContent is SubmitMessage for a message that also carries images.
func (*Session) UnregisterTool ¶
UnregisterTool removes the tool called name from this session. It does nothing on a nil session.
type SessionBackend ¶
type SessionBackend interface {
SaveSession(sessionID SessionID, metadata *SessionMetadata) error
LoadSession(sessionID SessionID) (*SessionMetadata, error)
DeleteSession(sessionID SessionID) error
ListSessions() ([]SessionID, error)
AppendTranscriptEntries(sessionID SessionID, entries []TranscriptEntry) error
ReplaceTranscript(sessionID SessionID, entries []TranscriptEntry) error
LoadTranscript(sessionID SessionID) ([]TranscriptEntry, error)
SearchTranscriptsByContent(needle string, limit int) ([]SessionID, error)
SaveCheckpoint(sessionID SessionID, checkpoint *Checkpoint) error
LoadCheckpoint(sessionID SessionID) (*Checkpoint, error)
}
SessionBackend is the SDK-owned low-level persistence backend contract. It matches the runtime's session backend responsibilities without forcing SDK consumers to depend on internal packages.
func NewFilesystemSessionBackend ¶
func NewFilesystemSessionBackend(baseDir string) (SessionBackend, error)
NewFilesystemSessionBackend returns a filesystem-backed session backend rooted at baseDir.
func NewMemorySessionBackend ¶
func NewMemorySessionBackend() SessionBackend
NewMemorySessionBackend returns an in-memory persistence backend suitable for tests or fully in-process runtimes.
func OpenSQLiteSessionBackend ¶
func OpenSQLiteSessionBackend(path string) (SessionBackend, error)
OpenSQLiteSessionBackend opens a SQLite-backed session backend using the shared runtime DB initialization path.
type SessionID ¶
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type SessionInfo ¶
type SessionInfo = state.SessionInfo
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type SessionMetadata ¶
type SessionMetadata = types.SessionMetadata
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type SessionResponse ¶
type SessionResponse struct {
Messages []Message `json:"messages"`
StopReason string `json:"stop_reason"`
ToolUses []ToolUseContent `json:"tool_uses"`
ToolResults []CallResult `json:"tool_results"`
Usage *TokenUsage `json:"usage"`
TotalTokens int `json:"total_tokens"`
TurnNumber int `json:"turn_number"`
IsComplete bool `json:"is_complete"`
Compacted bool `json:"compacted,omitempty"`
CompactPreTokens int `json:"compact_pre_tokens,omitempty"`
CompactPostTokens int `json:"compact_post_tokens,omitempty"`
}
SessionResponse represents the response from a multi-turn session.
type SessionStatus ¶
type SessionStatus = types.SessionStatus
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type SessionStore ¶
type SessionStore interface {
SaveSession(sessionID SessionID, metadata *SessionMetadata) error
LoadSession(sessionID SessionID) (*SessionMetadata, error)
DeleteSession(sessionID SessionID) error
ListSessions() ([]SessionID, error)
AppendTranscriptEntries(sessionID SessionID, entries []TranscriptEntry) error
ReplaceTranscript(sessionID SessionID, entries []TranscriptEntry) error
LoadTranscript(sessionID SessionID) ([]TranscriptEntry, error)
SearchTranscriptsByContent(needle string, limit int) ([]SessionID, error)
SaveCheckpoint(sessionID SessionID, checkpoint *Checkpoint) error
LoadCheckpoint(sessionID SessionID) (*Checkpoint, error)
LoadCanonicalMessages(sessionID SessionID) ([]Message, error)
SaveCanonicalMessages(sessionID SessionID, messages []Message) error
RestoreSessionState(sessionID SessionID) (*SessionMetadata, []Message, error)
SaveSessionState(sessionID SessionID, metadata *SessionMetadata, previousMessages []Message, currentMessages []Message) error
GetSessionInfo(sessionID SessionID) (*SessionInfo, error)
GetAllSessionsInfo() ([]*SessionInfo, error)
Close() error
}
SessionStore is the SDK-owned contract for persisted runtime sessions. It keeps callers on pkg/sdk while remaining compatible with the runtime's internal store implementations.
func NewSessionStore ¶
func NewSessionStore(baseDir string) (SessionStore, error)
NewSessionStore creates the default filesystem-backed session store rooted at baseDir.
func NewSessionStoreWithBackend ¶
func NewSessionStoreWithBackend(backend SessionBackend) (SessionStore, error)
NewSessionStoreWithBackend adapts a caller-provided backend into the SDK's public SessionStore contract.
type SpeechToTextConfig ¶
type SpeechToTextConfig struct {
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
Language string `json:"language,omitempty"`
APIKey string `json:"api_key,omitempty"`
BaseURL string `json:"base_url,omitempty"`
}
SpeechToTextConfig controls the speech_to_text built-in tool.
type StageRuntimeEvent ¶
type StageRuntimeEvent = types.StageRuntimeEvent
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type StopHookInput ¶
type StopHookInput = engine.StopHookInput
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type StopHookResult ¶
type StopHookResult = engine.StopHookResult
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type StorageConfig ¶
type StorageConfig struct {
Provider StorageProviderType
LocalPath string
S3Endpoint string
S3Bucket string
S3AccessKeyID string
S3SecretAccessKey string
S3Region string
S3KeyPrefix string
}
StorageConfig is the SDK-owned artifact storage configuration.
type StorageProviderType ¶
type StorageProviderType string
StorageProviderType selects the underlying artifact storage backend.
const ( StorageProviderLocal StorageProviderType = "local" StorageProviderS3 StorageProviderType = "s3" )
type StoredCredentialResolver ¶
type StoredCredentialResolver struct {
// contains filtered or unexported fields
}
StoredCredentialResolver resolves provider credentials from env vars and the local auth store. It implements CredentialResolver.
func NewStoredCredentialResolver ¶
func NewStoredCredentialResolver(config StoredCredentialResolverConfig) *StoredCredentialResolver
NewStoredCredentialResolver creates a resolver that can inject saved API keys or refreshed OAuth access tokens into sdk.NewClient.
func (*StoredCredentialResolver) ResolveAPIKey ¶
func (r *StoredCredentialResolver) ResolveAPIKey(ctx context.Context, provider string) (string, error)
ResolveAPIKey implements CredentialResolver.
type StoredCredentialResolverConfig ¶
StoredCredentialResolverConfig configures an auth-store backed resolver for SDK client creation. This is the clean bridge between a host-managed login flow and sdk.NewClient.
type Surface ¶
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type TaskRuntimeEvent ¶
type TaskRuntimeEvent = types.TaskRuntimeEvent
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type TextContent ¶
type TextContent = types.TextContent
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type TextToSpeechConfig ¶
type TextToSpeechConfig struct {
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
Voice string `json:"voice,omitempty"`
Format string `json:"format,omitempty"`
APIKey string `json:"api_key,omitempty"`
BaseURL string `json:"base_url,omitempty"`
}
TextToSpeechConfig controls the text_to_speech built-in tool.
type ThinkingContent ¶
type ThinkingContent = types.ThinkingContent
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type TitleGenerator ¶
type TitleGenerator interface {
GenerateTitle(ctx context.Context, firstUserMsg string) (string, error)
}
TitleGenerator generates a short automatic title from a session's first user message. Hosts can inject a local implementation for tiny HF/GGUF models.
type TokenUsage ¶
type TokenUsage = types.TokenUsage
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ToolDefinition ¶
type ToolDefinition = registry.ToolDefinition
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ToolHook ¶
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ToolHookInput ¶
type ToolHookInput = execution.ToolHookInput
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ToolHookResult ¶
type ToolHookResult = execution.ToolHookResult
ToolHookResult and ToolHookStop are what ToolHook.Execute returns. They were missing from this alias block (H5 in TODO.md), so a host in another module could name ToolHook itself but not the type its own Execute method must return, making AddToolHook unusable from outside this module.
type ToolHookStage ¶
type ToolHookStage = execution.ToolHookStage
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ToolHookStop ¶
type ToolHookStop = execution.ToolHookStop
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ToolProgress ¶
type ToolProgress = types.ToolProgress
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ToolProgressStage ¶
type ToolProgressStage = types.ToolProgressStage
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ToolResultContent ¶
type ToolResultContent = types.ToolResultContent
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type ToolUseContent ¶
type ToolUseContent = types.ToolUseContent
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type TranscribeOption ¶
type TranscribeOption func(*transcribeConfig)
TranscribeOption configures an optional TranscribeAudio setting.
func WithTranscribeBaseURL ¶
func WithTranscribeBaseURL(baseURL string) TranscribeOption
WithTranscribeBaseURL overrides the API base URL (default OpenAI's), mainly for tests.
func WithTranscribeLanguage ¶
func WithTranscribeLanguage(language string) TranscribeOption
WithTranscribeLanguage hints the spoken language as an IETF tag (e.g. "en"); omit to auto-detect.
func WithTranscribeModel ¶
func WithTranscribeModel(model string) TranscribeOption
WithTranscribeModel overrides the Whisper model (default "whisper-1").
type TranscriptEntry ¶
type TranscriptEntry = types.TranscriptEntry
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type TranscriptionResult ¶
TranscriptionResult mirrors internal/audio/stt.Response — re-exported so hosts outside this module (which cannot import internal/ packages) can name the return type of TranscribeAudio.
func TranscribeAudio ¶
func TranscribeAudio(ctx context.Context, apiKey string, audioData []byte, opts ...TranscribeOption) (*TranscriptionResult, error)
TranscribeAudio performs a one-off speech-to-text transcription using OpenAI's Whisper API, independent of any chat session. Use this when a host needs raw audio-to-text directly (e.g. a voice-input control in its own UI) rather than the agent-facing speech_to_text tool, which only runs when the model itself decides to call it mid-turn.
audioData may be MP3, MP4, MPEG, MPGA, M4A, WAV, or WebM.
type TurnID ¶
Public aliases keep the SDK consumable without forcing callers onto internal packages.
type WebSearchRunnerFn ¶
type WebSearchRunnerFn = websearchtool.RunnerFn
WebSearchRunnerFn — re-exported so the query layer can wire the DB-backed provider chain into the web_search tool without importing the tool package directly.
type WorkflowDefinition ¶
type WorkflowDefinition = workflow.Definition
WorkflowDefinition is a workflow: a named set of nodes, each one a prompt for an agent, linked by the nodes they need. It is read from YAML or JSON (see LoadFile).
func LoadWorkflowFile ¶
func LoadWorkflowFile(path string) (WorkflowDefinition, error)
LoadWorkflowFile reads a workflow definition from a file: JSON when the extension is .json, YAML otherwise.
type WorkflowDraftOptions ¶
type WorkflowDraftOptions = workflow.DraftOptions
WorkflowDraftOptions asks for a workflow definition to be normalised, validated and rendered. Format is "yaml" (the default, also "yml") or "json".
type WorkflowDraftResult ¶
type WorkflowDraftResult = workflow.DraftResult
WorkflowDraftResult is a normalised definition and its rendering in Format. Diagnostics holds the reason when the definition is invalid or the format is not supported.
func DraftWorkflow ¶
func DraftWorkflow(options WorkflowDraftOptions) (WorkflowDraftResult, error)
DraftWorkflow normalises and validates a definition, then renders it as YAML or JSON. When it fails, it returns the error together with a result whose Diagnostics holds its message.
type WorkflowNode ¶
WorkflowNode is one step of a workflow: a prompt for an agent, run once the nodes listed in Needs have succeeded, and whose output is given to the nodes that need it.\nKind gives the node a role: "agent" (or empty) for a plain step, "verifier", "critic", or "router", a node that chooses among the nodes listed in Routes (at least one is required). MaxTurns is the number of turns the executor should allow the agent of the node, 0 leaving it to the executor, and OutputFormat describes the form the output should take.
type WorkflowNodeResult ¶
type WorkflowNodeResult = workflow.NodeResult
WorkflowNodeResult is the outcome of one node: whether it succeeded, its output or its error, and when it ran.
type WorkflowOptions ¶
WorkflowOptions tunes Client.RunWorkflow: how many nodes may run at once, the tools given to the default executor, and an Executor to use instead of the default one, which asks the model.
type WorkflowResult ¶
WorkflowResult is the outcome of a workflow run: whether every node succeeded, the result of each node by id, and the order in which the nodes that ran finished. A node that did not run because a dependency failed has a result with Success false and no entry in Order.