client

package
v0.0.4 Latest Latest
Warning

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

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

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

Documentation

Overview

Package client provides a stateless HTTP and Server-Sent Events (SSE) client for communicating with the TaskSmith Brain Daemon over a Unix domain socket.

Session Operations

Sessions support conversation turns and timeline inspection:

MCP Server Operations

Configured MCP servers are inspected and driven through the workspace-scoped `/v1/workspace/mcps` routes:

Real-Time Server-Sent Events (SSE)

Clients stream typed real-time notifications (api.Event) from the daemon's internal event broker:

All SSE streams yield structured api.Event values whose typed payloads satisfy api.EventPayload.

Daemon Lifecycle

Go consumers drive the whole daemon lifecycle through this package:

This package depends on github.com/masterkeysrd/tasksmith/api, the Go standard library, and dependency-light shared utilities under `internal/core` (system, path, and version helpers), maintaining strict separation from the daemon and engine packages.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidSocketPath = errors.New("client: socket path must not be empty")
	ErrEmptyWorkspace    = errors.New("client: workspace path must not be empty")
	ErrEmptyCWD          = ErrEmptyWorkspace
	ErrEmptySessionID    = errors.New("client: session ID must not be empty")
	ErrEmptySubscriberID = errors.New("client: subscriber ID must not be empty")
	ErrNeedSync          = errors.New("client: stream out of sync")
	ErrSSEIdle           = errors.New("client: sse stream idle")
)

Sentinel errors returned by the client package.

View Source
var SpawnWaitTimeout = 15 * time.Second

SpawnWaitTimeout bounds how long ConnectOrStart waits for a freshly spawned daemon to become healthy. It is a var so tests can shorten the bound.

Functions

func DaemonVersionSkewed

func DaemonVersionSkewed(h *api.HealthResponse) bool

DaemonVersionSkewed reports whether a healthy daemon's build version differs from this client's. Daemons that predate version reporting are treated as skewed so they get upgraded on the next client launch.

func DefaultLockPath

func DefaultLockPath() (string, error)

DefaultLockPath returns the default XDG runtime lockfile path ("brain.lock") paired with DefaultSocketPath.

func DefaultSocketPath

func DefaultSocketPath() (string, error)

DefaultSocketPath returns the default XDG runtime Unix domain socket path ("brain.sock") the daemon serves.

func HasActiveSessions

func HasActiveSessions(sessions []api.Session) bool

HasActiveSessions reports whether any session on the daemon is doing work that a restart would interrupt.

func IsCapabilityMismatch

func IsCapabilityMismatch(err error) (*api.APIError, bool)

IsCapabilityMismatch reports whether err is a structured capability-mismatch error returned when switching models drops active session modalities.

func IsDaemonHealthy

func IsDaemonHealthy(ctx context.Context, c *Client) bool

IsDaemonHealthy reports whether the daemon answers a bounded health ping.

func IsNeedSync

func IsNeedSync(err error) bool

IsNeedSync reports whether err represents a stream cursor desync requiring a full snapshot reload.

func LockPathForSocket

func LockPathForSocket(socketPath string) string

LockPathForSocket returns the lockfile path paired with a socket path: the same directory and base name with a ".lock" extension. A socket that does not end in ".sock" gets ".lock" appended.

func NewCursor

func NewCursor() string

NewCursor returns a fresh canonical UUIDv7 string cursor for event streaming.

func SpawnLogHint

func SpawnLogHint() string

SpawnLogHint returns the daemon log directory for user-facing error messages, falling back to the documented default when it cannot be resolved.

func WaitForSocketHealthy

func WaitForSocketHealthy(ctx context.Context, socketPath string, spawned *SpawnedDaemon, timeout time.Duration, health func(context.Context) (*api.HealthResponse, error)) (*api.HealthResponse, error)

WaitForSocketHealthy polls a health probe against a freshly spawned daemon until it answers, the spawned child exits (surfacing the failure immediately with a pointer to the daemon logs), or timeout elapses. health is injected so callers own their client plumbing without this package depending on the HTTP client; it returns the daemon's health payload when the probe succeeds (may be nil for callers that only track liveness).

func WaitForSocketLockRelease

func WaitForSocketLockRelease(ctx context.Context, socketPath string) error

WaitForSocketLockRelease blocks until the lock paired with socketPath is free (the previous daemon finished teardown). It returns nil immediately when no lock file exists, and a timeout error when the holder never releases; the spawned daemon's own retry window may still recover such a handoff.

Types

type Client

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

Client communicates with the TaskSmith Brain Daemon over a Unix domain socket.

func ConnectOrStart

func ConnectOrStart(ctx context.Context, socketPath string, spawnArgs ...string) (*Client, []string, error)

ConnectOrStart connects to an existing Brain Daemon at socketPath, or spawns a detached background daemon process (`os.Executable() daemon serve --socket <socketPath>`) and polls `/v1/health` until ready. An empty socketPath selects DefaultSocketPath.

When the running daemon was built from a different version than this client, ConnectOrStart restarts it only once every session is confirmed idle. In any other case — an active session or an unknown session state — the existing daemon is kept and the skew is returned as a user-facing notice so callers can surface it in their own UI; the user then restarts the daemon when it is safe instead of having work interrupted.

func New

func New(socketPath string, opts ...Option) (*Client, error)

New constructs a new Client connected to socketPath.

func (*Client) AddPermissionRule

func (c *Client) AddPermissionRule(ctx context.Context, req api.PermissionRuleRequest) (*api.PermissionsResponse, error)

AddPermissionRule appends an allow or deny rule to project or global permissions.

func (*Client) AllowMCPPolicy

func (c *Client) AllowMCPPolicy(ctx context.Context, server string, req api.MCPAllowPolicyRequest) (api.MCPServer, error)

AllowMCPPolicy updates the named server's manifest on disk so req.Value is permitted, reloads the server, and returns the updated state.

func (*Client) AssignModelAliases

AssignModelAliases binds req.Aliases to the named provider model. Aliases currently held by other models are moved atomically before the assignment is saved.

func (*Client) AuthenticateMCP

func (c *Client) AuthenticateMCP(ctx context.Context, name string) (api.MCPAuthResponse, error)

AuthenticateMCP starts or resumes the interactive authorization flow for the named MCP server and returns the URL the user should open in a browser.

func (*Client) CWD

func (c *Client) CWD() string

CWD returns the configured client working directory.

func (*Client) Cancel

func (c *Client) Cancel(ctx context.Context, sessionID string) error

Cancel aborts an in-progress conversational turn on a session.

func (*Client) Changes

func (c *Client) Changes(ctx context.Context, sessionID string) ([]api.FileChange, error)

Changes returns all recorded file mutation entries for a session.

func (*Client) CompleteMCPAuth

func (c *Client) CompleteMCPAuth(ctx context.Context, name string, req api.MCPAuthCallbackRequest) error

CompleteMCPAuth hands a redirect URL copied from the user's browser to the authorization flow in progress for the named MCP server. It is the fallback for browsers that cannot reach the daemon's loopback callback listener.

func (*Client) CompleteProviderAuth

func (c *Client) CompleteProviderAuth(ctx context.Context, provider string, req api.ProviderAuthCallbackRequest) (*api.ProviderAuthResponse, error)

CompleteProviderAuth finishes an in-flight provider OAuth flow with a callback URL the user copied from their browser.

func (*Client) CreateProvider

func (c *Client) CreateProvider(ctx context.Context, req api.CreateProviderRequest) (api.WorkspaceProvider, error)

CreateProvider writes a new provider manifest to the requested scope, stores any API key in the scope's .env file, reloads the workspace, and returns the created provider.

func (*Client) CreateSession

func (c *Client) CreateSession(ctx context.Context, req api.CreateSessionRequest) (*api.Session, error)

CreateSession creates a new session in workspace.

func (*Client) DeleteSession

func (c *Client) DeleteSession(ctx context.Context, sessionID string) error

DeleteSession deletes a session and its associated history and change journals.

func (*Client) DiffChange

func (c *Client) DiffChange(ctx context.Context, sessionID, filePath, entryID string) (string, error)

DiffChange computes the unified diff for a specific journal entry on a path.

func (*Client) Events

func (c *Client) Events(ctx context.Context, subscriberID, since string, topics ...string) iter.Seq2[api.Event, error]

Events opens a real-time Server-Sent Events (SSE) stream with optional subscriberID, since cursor, and initial topics.

func (*Client) EventsWithReady

func (c *Client) EventsWithReady(ctx context.Context, subscriberID, since string, ready func(subscriberID string), topics ...string) iter.Seq2[api.Event, error]

EventsWithReady opens an SSE stream and invokes ready with the server-assigned (or echoed) subscriber ID once connected.

func (*Client) ForkSession

func (c *Client) ForkSession(ctx context.Context, sessionID string, req api.ForkSessionRequest) (*api.Session, error)

ForkSession branches an existing session into a new top-level session that starts from the source's full conversation. An empty title derives one from the source session's title.

func (*Client) GetAgent

func (c *Client) GetAgent(ctx context.Context, name string) (*api.Agent, error)

GetAgent retrieves an effective agent configuration by name.

func (*Client) GetCommand

func (c *Client) GetCommand(ctx context.Context, name string) (*api.Command, error)

GetCommand retrieves a command resource by name.

func (*Client) GetMCPPrompt

func (c *Client) GetMCPPrompt(ctx context.Context, server, prompt string, req api.MCPPromptRequest) (api.MCPPromptResponse, error)

GetMCPPrompt renders a prompt discovered on an MCP server. Prohibited prompts are rejected by the daemon unless req.AllowProhibited is set.

func (*Client) GetModel

func (c *Client) GetModel(ctx context.Context, id string) (*api.Model, error)

GetModel retrieves a model by ID or qualified identifier (e.g. "ollama/qwen3.8").

func (*Client) GetModelQuota

func (c *Client) GetModelQuota(ctx context.Context, model string) (*api.ModelQuota, error)

GetModelQuota reports the remaining quota for a quota-billed model. It returns (nil, nil) when the model's provider does not report quotas.

func (*Client) GetProviderAuthStatus

func (c *Client) GetProviderAuthStatus(ctx context.Context, provider string) (*api.ProviderAuthResponse, error)

GetProviderAuthStatus checks the status of an ongoing or completed interactive OAuth flow.

func (*Client) GetQuotaSnapshots

func (c *Client) GetQuotaSnapshots(ctx context.Context) (*api.QuotaSnapshotResponse, error)

GetQuotaSnapshots returns the multi-bucket quota snapshots across all quota-capable providers in the workspace.

func (*Client) GetSandbox

func (c *Client) GetSandbox(ctx context.Context) (*api.SandboxResponse, error)

GetSandbox retrieves the workspace's sandbox posture: stored sandbox.json scopes, their effective merge, host kernel backend diagnostics, and the resolved path rules.

func (*Client) GetSession

func (c *Client) GetSession(ctx context.Context, sessionID string) (*api.Session, error)

GetSession retrieves session metadata and live status by ID.

func (*Client) GetSkill

func (c *Client) GetSkill(ctx context.Context, name string) (*api.Skill, error)

GetSkill retrieves a skill resource by name.

func (*Client) GetTrustStatus

func (c *Client) GetTrustStatus(ctx context.Context) (*api.TrustStatus, error)

GetTrustStatus checks the trust and executable configuration status for the workspace.

func (*Client) GetWorkspace

func (c *Client) GetWorkspace(ctx context.Context) (*api.Workspace, error)

GetWorkspace retrieves the resolved configuration metadata for the workspace.

func (*Client) GetWorkspaceStatus

func (c *Client) GetWorkspaceStatus(ctx context.Context) (*api.WorkspaceStatus, error)

GetWorkspaceStatus returns the onboarding, trust, and configuration status of the workspace.

func (*Client) Health

func (c *Client) Health(ctx context.Context) (*api.HealthResponse, error)

Health queries the daemon's `/v1/health` endpoint.

func (*Client) InitWorkspace

func (c *Client) InitWorkspace(ctx context.Context, req api.InitWorkspaceRequest) error

InitWorkspace initializes a workspace according to req.

func (*Client) InitWorkspaceWithResult

func (c *Client) InitWorkspaceWithResult(ctx context.Context, req api.InitWorkspaceRequest) (api.InitWorkspaceResponse, error)

func (*Client) KillTask

func (c *Client) KillTask(ctx context.Context, sessionID, taskID string) error

KillTask requests termination of an active background task.

func (*Client) LatestSession

func (c *Client) LatestSession(ctx context.Context) (*api.Session, error)

LatestSession returns the workspace's most recently updated top-level session without hydrating any session runtime, backing quick resume (`-c` / `--continue`). It returns (nil, nil) when the workspace has no sessions.

func (*Client) ListAgents

func (c *Client) ListAgents(ctx context.Context) ([]api.Agent, error)

ListAgents returns all effective agents in the workspace scope.

func (*Client) ListAliasAssignments

func (c *Client) ListAliasAssignments(ctx context.Context) ([]api.AliasAssignment, error)

ListAliasAssignments returns the current standard and custom model alias assignments across all configured providers, flagging duplicates.

func (*Client) ListCommands

func (c *Client) ListCommands(ctx context.Context) ([]api.Command, error)

ListCommands returns all effective command resources in the workspace.

func (*Client) ListMCPs

func (c *Client) ListMCPs(ctx context.Context) ([]api.MCPServer, error)

ListMCPs returns every MCP server configured in the workspace sorted by name, including each server's live connection status and the tools, prompts, and resources discovered on it. Items blocked by a server manifest's policies are included with Allowed set to false.

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context) ([]api.Model, error)

ListModels returns all resolved models across providers in the workspace.

func (*Client) ListProviderCatalog

func (c *Client) ListProviderCatalog(ctx context.Context, name string) ([]api.ProviderCatalogEntry, error)

ListProviderCatalog returns the models the named configured provider can offer, sourced from its static or live catalog when available.

func (*Client) ListProviders

func (c *Client) ListProviders(ctx context.Context) ([]api.ProviderSummary, error)

ListProviders returns the built-in provider presets with their current credential availability.

func (*Client) ListRules

func (c *Client) ListRules(ctx context.Context) ([]api.Rule, error)

ListRules returns all effective rule resources in the workspace.

func (*Client) ListSessions

func (c *Client) ListSessions(ctx context.Context) ([]api.Session, error)

ListSessions lists all sessions in workspace ordered by most recently updated.

func (*Client) ListSkills

func (c *Client) ListSkills(ctx context.Context) ([]api.Skill, error)

ListSkills returns all effective skill resources in the workspace.

func (*Client) ListTools

func (c *Client) ListTools(ctx context.Context, agent string) ([]api.Tool, error)

ListTools returns all effective built-in and custom tool resources in the workspace. When agent is not empty, each tool's Status is classified for that agent (eager, deferred, denied, or inactive).

func (*Client) ListWorkspaceFiles

func (c *Client) ListWorkspaceFiles(ctx context.Context, req api.ListFilesRequest) ([]api.WorkspaceFile, error)

ListWorkspaceFiles lists and searches files and directories in the workspace.

func (*Client) ListWorkspaceProviders

func (c *Client) ListWorkspaceProviders(ctx context.Context) ([]api.WorkspaceProvider, error)

ListWorkspaceProviders returns every configured model provider across the user and workspace scopes, with each provider's manifest path, enablement, auth availability, and declared models.

func (*Client) LogoutProviderAuth

func (c *Client) LogoutProviderAuth(ctx context.Context, provider string) (*api.ProviderAuthResponse, error)

LogoutProviderAuth cancels any in-flight OAuth flow for provider and removes its persisted credentials.

func (*Client) Permissions

func (c *Client) Permissions(ctx context.Context) (*api.PermissionsResponse, error)

Permissions retrieves configured project and global permission rules.

func (*Client) PreviewSession

func (c *Client) PreviewSession(ctx context.Context, req api.PreviewSessionRequest) (*api.SessionPreview, error)

PreviewSession resolves a proposed draft session configuration without creating it.

func (*Client) QueryMetrics

func (c *Client) QueryMetrics(ctx context.Context, q api.MetricsQuery) (api.MetricsResult, error)

QueryMetrics runs a generic metrics query.

func (*Client) ReadMCPResource

func (c *Client) ReadMCPResource(ctx context.Context, server string, req api.MCPResourceRequest) (api.MCPResourceResponse, error)

ReadMCPResource reads a resource URI from an MCP server. Prohibited resources are rejected by the daemon unless req.AllowProhibited is set.

func (*Client) ReloadWorkspace

func (c *Client) ReloadWorkspace(ctx context.Context) error

ReloadWorkspace requests the daemon to reload workspace resources from disk.

func (*Client) RemovePermissionRule

func (c *Client) RemovePermissionRule(ctx context.Context, req api.PermissionRuleRequest) (*api.PermissionsResponse, error)

RemovePermissionRule deletes a rule from project or global permissions.

func (*Client) RestartMCP

func (c *Client) RestartMCP(ctx context.Context, name string) (api.MCPServer, error)

RestartMCP reconnects the named MCP server and re-discovers its tools, prompts, and resources, returning the updated server state.

func (*Client) Revert

func (c *Client) Revert(ctx context.Context, sessionID string, req api.RevertRequest) error

Revert reverts a single journal entry, a single file to baseline, or all tracked files in the session.

func (*Client) RevokeTrust

func (c *Client) RevokeTrust(ctx context.Context) error

RevokeTrust removes the workspace from the trust store.

func (*Client) Send

func (c *Client) Send(ctx context.Context, sessionID string, req api.SendRequest) error

Send submits a user message to a session and triggers a conversational turn in the daemon's background runtime.

func (*Client) SessionUsage

func (c *Client) SessionUsage(ctx context.Context, sessionID string) (api.SessionUsage, error)

SessionUsage returns the token, cost and tool usage of a session.

func (*Client) SetMCPEnabled

func (c *Client) SetMCPEnabled(ctx context.Context, name string, enabled bool) ([]api.MCPServer, error)

SetMCPEnabled patches availability for the named MCP server (its manifest's spec.enabled or a WORKSPACE.md MCPs policy exclusion), reloads the workspace, and returns the updated MCP listing.

func (*Client) SetProviderEnabled

func (c *Client) SetProviderEnabled(ctx context.Context, name string, enabled bool) ([]api.WorkspaceProvider, error)

SetProviderEnabled patches the named provider manifest's spec.enabled flag, reloads the workspace, and returns the updated provider listing.

func (*Client) SetToolEnabled

func (c *Client) SetToolEnabled(ctx context.Context, name string, enabled bool) ([]api.Tool, error)

SetToolEnabled patches availability for the named tool (its manifest's spec.enabled or a WORKSPACE.md tools policy exclusion), reloads the workspace, and returns the updated tool listing.

func (*Client) Shutdown

func (c *Client) Shutdown(ctx context.Context) error

Shutdown requests a graceful daemon shutdown via `POST /v1/shutdown`.

func (*Client) SocketPath

func (c *Client) SocketPath() string

SocketPath returns the Unix domain socket path configured on the client.

func (*Client) StartProviderAuth

func (c *Client) StartProviderAuth(ctx context.Context, provider string) (*api.ProviderAuthResponse, error)

StartProviderAuth initiates interactive OAuth for a provider.

func (*Client) StreamTaskOutput

func (c *Client) StreamTaskOutput(ctx context.Context, sessionID, taskID string) iter.Seq2[string, error]

StreamTaskOutput streams live task output (both backlog and live updates) for a task.

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context, subscriberID, since string, topics ...string) (*api.SubscriptionResponse, error)

Subscribe subscribes an active SSE stream (identified by subscriberID) to additional topics.

func (*Client) Tasks

func (c *Client) Tasks(ctx context.Context, sessionID string) ([]api.Task, error)

Tasks returns all background tasks for a session.

func (*Client) Timeline

func (c *Client) Timeline(ctx context.Context, sessionID string) ([]api.TimelineEntry, error)

Timeline returns the chronological session timeline for a session.

func (*Client) TrustWorkspace

func (c *Client) TrustWorkspace(ctx context.Context, scope string) error

TrustWorkspace records a trust decision for the workspace.

func (*Client) Unsubscribe

func (c *Client) Unsubscribe(ctx context.Context, subscriberID string, topics ...string) (*api.SubscriptionResponse, error)

Unsubscribe unsubscribes an active SSE stream (identified by subscriberID) from topics.

func (*Client) UpdateProviderModels

func (c *Client) UpdateProviderModels(ctx context.Context, name string, req api.UpdateProviderModelsRequest) ([]api.WorkspaceProvider, error)

UpdateProviderModels rewrites the named provider manifest's declared models and optional default completion model, reloads the workspace, and returns the updated provider listing.

func (*Client) UpdateSandbox

func (c *Client) UpdateSandbox(ctx context.Context, req api.UpdateSandboxRequest) (*api.SandboxResponse, error)

UpdateSandbox overwrites one scope's sandbox settings (global or project) and returns the refreshed sandbox posture.

func (*Client) UpdateSession

func (c *Client) UpdateSession(ctx context.Context, sessionID string, req api.UpdateSessionRequest) (*api.Session, error)

UpdateSession modifies session metadata (title, agent, model) on an existing session.

func (*Client) UploadMedia

func (c *Client) UploadMedia(ctx context.Context, sessionID string, data []byte, mimeType, filename string) (*api.Media, error)

UploadMedia stores raw media bytes in the session's content-addressed <session-dir>/media/<sha256> store and returns a lightweight descriptor.

func (*Client) Usage

func (c *Client) Usage(ctx context.Context, req api.UsageRequest) (api.UsageSummary, error)

Usage returns the usage summary of the workspace or of all workspaces.

func (*Client) VerifyProvider

VerifyProvider tests credentials or endpoint reachability for a provider.

func (*Client) Watch

func (c *Client) Watch(ctx context.Context, since string, topics ...string) iter.Seq2[api.Event, error]

Watch returns an iterator of events multiplexed over a shared SSE connection. It subscribes to topics, replaying from since if non-empty, and yields events.

func (*Client) WithCWD

func (c *Client) WithCWD(cwd string) *Client

WithCWD returns a shallow copy of Client with its working directory set to cwd.

type Option

type Option func(*Client)

Option configures a Client.

func WithCWD

func WithCWD(cwd string) Option

WithCWD configures the default client working directory sent via api.HeaderCWD.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient overrides the underlying *http.Client used by the client.

func WithSSEIdleTimeout

func WithSSEIdleTimeout(d time.Duration) Option

WithSSEIdleTimeout overrides how long an SSE stream may stay silent before the client treats the connection as dead and fails the stream so callers reconnect. The daemon emits heartbeat comments every 15 seconds, so the default (4x that interval) only trips on genuinely half-open connections.

type SpawnedDaemon

type SpawnedDaemon struct {
	PID  int
	Done <-chan struct{}
}

SpawnedDaemon describes a detached daemon child process spawned by SpawnDetached. The process is reaped asynchronously; Done closes when the child exits for any reason, letting callers waiting on the socket notice an early startup failure immediately instead of polling until their deadline.

func SpawnDetached

func SpawnDetached(socketPath string, spawnArgs ...string) (*SpawnedDaemon, error)

SpawnDetached resolves the current executable and spawns a background detached daemon process. If spawnArgs is empty, default arguments ["daemon", "serve", "--socket", <socketPath>] are used. The child process is detached with Setsid and reaped asynchronously in a goroutine.

func SpawnDetachedWithLog

func SpawnDetachedWithLog(socketPath, stderrPath string, spawnArgs ...string) (*SpawnedDaemon, error)

SpawnDetachedWithLog behaves like SpawnDetached and additionally redirects the child's stderr to stderrPath when provided, so startup failures of a detached daemon are recoverable instead of silently discarded. If stderrPath is empty, a best-effort path inside the XDG logs directory is used; stderr is discarded when the log directory cannot be resolved.

Jump to

Keyboard shortcuts

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