mindwire

package
v0.1.54 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 46 Imported by: 0 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 mindwire is the native, in-process Go SDK for the mindwire engine — one API across every coding-agent harness (Claude Code, Codex, …), the same surface the TypeScript SDK exposes, but running the daemon's own orchestrator directly in your process. There is no HTTP server, no subprocess, and no network hop: New constructs an orchestrator.Supervisor exactly as the daemon binary does and Client calls it directly, so a turn you start here is the same turn the daemon would run, with the same capability gates, session store, event stream, and notifications.

Getting started

import mindwire "github.com/oblien/mindwire/packages/daemon/sdk"

client, err := mindwire.New(mindwire.Options{Agent: "claude-code", CWD: "/path/to/project"})
if err != nil {
	log.Fatal(err)
}
defer client.Close()

run, err := client.Turn(ctx, mindwire.TurnRequest{ChatID: "chat-1", Message: "List the files here."})
if err != nil {
	log.Fatal(err)
}
for ev := range run.Stream(ctx) {
	if ev.Type == mindwire.EventText {
		fmt.Print(ev.Text)
	}
}
res, err := run.Wait(ctx)

Design

  • Everything a consumer touches is spelled mindwire.* (see types.go). These are aliases of the daemon core's public types, so returned values marshal to exactly the daemon's wire shape and no conversion is needed — the SDK never asks you to import a packages/daemon/internal/* package.
  • Streaming is an iter.Seq[Event]: range over Run.Stream and the subscription is released for you when the loop ends. Cancelling the context stops your read, not the turn (turns run on the supervisor's detached context) — call Run.Cancel to actually stop one.
  • Errors mirror the HTTP surface: an *APIError carries the status the daemon would have returned (400/404/409/500), so you branch with errors.As just as you would on an HTTP client.
  • Agent scoping: Client has a default agent (Options.Agent); override per call with ForAgent, or take a cheap WithAgent view that shares the same engine.

One client per state file

A Client owns one StatePath: the one-turn-per-chat gate and the JSON store are per-supervisor, so running two Clients over the same state file is unsupported. Construct a single Client and share it (it is safe for concurrent use); use WithAgent for per-agent views of that one engine.

Example

Construct a client, run a turn, stream its events, and wait for the result.

package main

import (
	"context"
	"fmt"
	"log"

	mindwire "github.com/oblien/mindwire/packages/daemon/sdk"
)

func main() {
	client, err := mindwire.New(mindwire.Options{Agent: "claude-code", CWD: "/path/to/project"})
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	ctx := context.Background()
	run, err := client.Turn(ctx, mindwire.TurnRequest{ChatID: "chat-1", Message: "List the files here."})
	if err != nil {
		log.Fatal(err)
	}

	for ev := range run.Stream(ctx) {
		if ev.Type == mindwire.EventText {
			fmt.Print(ev.Text)
		}
	}

	res, err := run.Wait(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res.Run.Status)
}

Index

Examples

Constants

View Source
const (
	KindFileEdit  = agent.KindFileEdit
	KindFileRead  = agent.KindFileRead
	KindShell     = agent.KindShell
	KindSearch    = agent.KindSearch
	KindWebSearch = agent.KindWebSearch
	KindWebFetch  = agent.KindWebFetch
	KindMCP       = agent.KindMCP
	KindOther     = agent.KindOther
)

ToolKind values, the canonical agent-independent tool classification.

View Source
const (
	EventSession      = agent.EventSession
	EventText         = agent.EventText
	EventThinking     = agent.EventThinking
	EventToolUse      = agent.EventToolUse
	EventToolResult   = agent.EventToolResult
	EventResult       = agent.EventResult
	EventError        = agent.EventError
	EventStatus       = agent.EventStatus
	EventInput        = agent.EventInput
	EventInteraction  = agent.EventInteraction
	EventCompaction   = agent.EventCompaction
	EventContinuation = agent.EventContinuation
)

EventType values, one per kind of stream item.

View Source
const (
	SupportNone     = agent.SupportNone
	SupportNative   = agent.SupportNative
	SupportEmulated = agent.SupportEmulated
)

Support values (a capability's fidelity for hybrid features like history).

View Source
const (
	MemoryProject = agent.MemoryProject
	MemoryUser    = agent.MemoryUser
)

MemoryScope values — the two persistent layers a memory file or prompt template can live at.

View Source
const (
	ProtocolCLI        = agent.ProtocolCLI
	ProtocolHTTP       = agent.ProtocolHTTP
	ProtocolPersistent = agent.ProtocolPersistent
)

Protocol values — how the daemon drives an agent for a turn.

View Source
const (
	OutputStructuredJSON = agent.OutputStructuredJSON
	OutputTerminal       = agent.OutputTerminal
)

OutputMode values — how an agent emits a turn's output.

View Source
const (
	ChannelWebhook  = agent.ChannelWebhook
	ChannelPush     = agent.ChannelPush
	ChannelSlack    = agent.ChannelSlack
	ChannelDiscord  = agent.ChannelDiscord
	ChannelTelegram = agent.ChannelTelegram
)

Notification channel types (delivery payload shape).

View Source
const (
	ScopeGlobal  = agent.ScopeGlobal
	ScopeAgent   = agent.ScopeAgent
	ScopeSession = agent.ScopeSession
)

Notification rule scopes.

View Source
const (
	CheckOK   = agent.CheckOK
	CheckWarn = agent.CheckWarn
	CheckFail = agent.CheckFail
)

Health-check statuses.

View Source
const (
	Finished        = agent.Finished
	Errored         = agent.Errored
	WaitingApproval = agent.WaitingApproval
	WaitingFeedback = agent.WaitingFeedback
	WaitingInput    = agent.WaitingInput
)

Notification conditions.

View Source
const (
	CanonModel              = agent.CanonModel
	CanonFallbackModel      = agent.CanonFallbackModel
	CanonReasoningEffort    = agent.CanonReasoningEffort
	CanonSystemPrompt       = agent.CanonSystemPrompt
	CanonAppendSystemPrompt = agent.CanonAppendSystemPrompt
	CanonPermissionMode     = agent.CanonPermissionMode
	CanonAllowedTools       = agent.CanonAllowedTools
	CanonAllowRules         = agent.CanonAllowRules
	CanonDenyRules          = agent.CanonDenyRules
	CanonExtraDirs          = agent.CanonExtraDirs
	CanonMaxSpendUSD        = agent.CanonMaxSpendUSD
	CanonMaxTurns           = agent.CanonMaxTurns
)

Canonical per-turn setting keys — the agent-agnostic addresses a client uses in TurnOptions.Settings (the runner maps each to the selected agent's own field key). Re-exported so callers avoid magic strings.

Variables

View Source
var ErrHandoffContextChanged = handoffs.ErrPreviewChanged

ErrHandoffContextChanged means no destination was admitted. Refresh and review the source before retrying; use errors.Is to distinguish it from a lost response.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Message string
	Status  int
	Op      string
	Cause   error
}

APIError is returned by operations whose HTTP-daemon equivalent would answer with a non-2xx status, so an in-process caller can branch on Status exactly as an HTTP client would:

400 — bad input or an option the target agent doesn't support
404 — no such run (or no running turn accepting that operation)
409 — a turn is already running for the chat
500 — a persistence failure

Op names the SDK operation that failed (e.g. "Turn", "Run.Cancel"); Message is the same human string the HTTP layer returns; Cause wraps the underlying error when there is one.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

type Action

type Action = agent.Action

Mid-turn interactions the agent surfaces (a question, a plan to approve, todo progress).

type AgentDiscoveryIssue

type AgentDiscoveryIssue = registry.AgentDiscoveryIssue

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type AgentInfo

type AgentInfo struct {
	Version          string           `json:"version"`
	AgentType        string           `json:"agentType"`
	Name             string           `json:"name"`
	Capabilities     Capabilities     `json:"capabilities"`
	Schema           SettingsSchema   `json:"schema"`
	AuthMethods      []AuthMethod     `json:"authMethods"`
	AuthStatus       AuthStatus       `json:"authStatus"`
	InstalledVersion string           `json:"installedVersion"`
	Software         *HarnessSoftware `json:"software,omitempty"`
	Configured       bool             `json:"configured"`
	ConfigPath       string           `json:"configPath"`
}

AgentInfo is the full descriptor for one agent: version, identity, capabilities, dynamic settings schema, auth methods + resting status, installed CLI version, whether it's configured, and its user-editable config path. JSON tags match the HTTP /agent payload exactly.

type AppNotificationChannel

type AppNotificationChannel = shortcuts.Channel

type AppNotificationMessage

type AppNotificationMessage = shortcuts.NotificationMessage

type AppPublication

type AppPublication = shortcuts.Publication

type AppSchedule

type AppSchedule = registry.AppSchedule

type AppScheduleSpec

type AppScheduleSpec = registry.AppScheduleSpec

type AppShortcut

type AppShortcut = registry.AppShortcut

type AppShortcutEdit

type AppShortcutEdit = registry.AppShortcutPatch

type AppShortcutMutation

type AppShortcutMutation struct {
	App      AppShortcut       `json:"app"`
	Snapshot WorkspaceSnapshot `json:"snapshot"`
}

type Apps

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

Apps exposes application resources, readiness, scoped notifications and persisted schedules. Background execution is opt-in via Options.RunScheduledJobs.

func (*Apps) Channels

func (a *Apps) Channels() []AppNotificationChannel

func (*Apps) DeleteSchedule

func (a *Apps) DeleteSchedule(id, jobID string) error

func (*Apps) Get

func (a *Apps) Get(id string) (AppShortcut, error)

func (*Apps) List

func (a *Apps) List() ([]AppShortcut, error)

func (*Apps) Notify

func (a *Apps) Notify(ctx context.Context, id string, message AppNotificationMessage) error

func (*Apps) Open

func (a *Apps) Open(ctx context.Context, id string) (AppShortcut, error)

func (*Apps) PreparePublication

func (a *Apps) PreparePublication(ctx context.Context, id string) (AppPublication, error)

func (*Apps) Register

func (a *Apps) Register(input AppShortcut) (AppShortcutMutation, error)

func (*Apps) RevokeNotificationAccess

func (a *Apps) RevokeNotificationAccess(id string) error

func (*Apps) SaveSchedule

func (a *Apps) SaveSchedule(id string, spec AppScheduleSpec) (AppSchedule, error)

func (*Apps) Schedules

func (a *Apps) Schedules(id string) ([]AppSchedule, error)

func (*Apps) Update

func (a *Apps) Update(id string, input AppShortcutEdit) (AppShortcutMutation, error)

type ArtifactContent

type ArtifactContent = artifact.Content

type Attachment

type Attachment = agent.Attachment

Turn inputs.

type AttachmentUploadChunk

type AttachmentUploadChunk = artifact.UploadChunk

type AttachmentUploadState

type AttachmentUploadState = artifact.UploadState

type Auth

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

Auth is the step-flow authentication sub-API, reachable as Client.Auth. It drives the same generic methods → begin → step → status flow the HTTP /auth/* routes expose: list the ways to authenticate, begin one, feed it inputs until it completes, and read the resting status. It is scoped to its client's default agent and rebinds when you take a WithAgent view; override per call with ForAgent.

func (*Auth) Begin

func (a *Auth) Begin(ctx context.Context, method string, opts ...ScopedOption) (AuthState, error)

Begin starts the named auth method and returns the first step (inputs to collect, a URL to open, or completion). An empty method or an error from the module surfaces as APIError{400}, matching POST /auth/begin.

func (*Auth) Cancel

func (a *Auth) Cancel(ctx context.Context, flowID string, opts ...ScopedOption) (AuthState, error)

Cancel stops the native login represented by AuthState.FlowID.

func (*Auth) Logout

func (a *Auth) Logout(ctx context.Context, opts ...ScopedOption) (AuthStatus, error)

Logout disconnects this harness in the workspace. Running chats are preserved: sign-out returns a conflict until the harness is idle.

func (*Auth) Methods

func (a *Auth) Methods(opts ...ScopedOption) ([]AuthMethod, error)

Methods lists the ways to authenticate the scoped agent (API key, interactive login, …).

func (*Auth) Poll

func (a *Auth) Poll(ctx context.Context, flowID string, opts ...ScopedOption) (AuthState, error)

Poll reads one interactive attempt without accepting a newer attempt's state.

func (*Auth) Status

func (a *Auth) Status(ctx context.Context, opts ...ScopedOption) (AuthStatus, error)

Status reports the scoped agent's resting auth state: whether it's configured, and via which method.

func (*Auth) Step

func (a *Auth) Step(ctx context.Context, input map[string]string, opts ...ScopedOption) (AuthState, error)

Step advances an in-progress auth flow with the collected inputs and returns the next state. A module error surfaces as APIError{400}, matching POST /auth/step.

type AuthMethod

type AuthMethod = agent.AuthMethod

Auth, health checks, and notifications.

type AuthSection

type AuthSection = agent.AuthSection

Auth, health checks, and notifications.

type AuthSource

type AuthSource = agent.AuthSource

Auth, health checks, and notifications.

type AuthState

type AuthState = agent.AuthState

Auth, health checks, and notifications.

type AuthStatus

type AuthStatus = agent.AuthStatus

Auth, health checks, and notifications.

type Bot

type Bot = registry.Bot

type BotEdit

type BotEdit = registry.BotPatch

type BotKnowledge

type BotKnowledge = registry.BotKnowledge

type BotMutation

type BotMutation struct {
	Bot      Bot               `json:"bot"`
	Snapshot WorkspaceSnapshot `json:"snapshot"`
}

type BotPeer

type BotPeer = botservice.Peer

type BotPeerCheck

type BotPeerCheck = botservice.PeerCheck

type BotPeerIdentity

type BotPeerIdentity = botservice.PeerIdentity

type BotPeerRoute

type BotPeerRoute = botservice.PeerRoute

type BotTask

type BotTask = botservice.Task

type BotTaskInput

type BotTaskInput = botservice.TaskInput

type BotTaskInteraction

type BotTaskInteraction = botservice.TaskInteraction

type BotTaskMessage

type BotTaskMessage = botservice.ChatExcerpt

type BotTaskRequest

type BotTaskRequest = botservice.TaskRequest

type BotTaskTool

type BotTaskTool = botservice.TaskTool

type Bots

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

Bots is the persisted identity and native task layer shared by all harnesses.

func (*Bots) Agents

func (b *Bots) Agents() ([]WorkspaceAgent, []WorkspaceProject, error)

func (*Bots) Cancel

func (b *Bots) Cancel(id, runID string) (BotTask, error)

func (*Bots) Chats

func (b *Bots) Chats(id string) ([]WorkspaceChat, error)

func (*Bots) CheckPeer

func (b *Bots) CheckPeer(ctx context.Context, workspaceID string) (BotPeerCheck, error)

CheckPeer confirms a pinned bot-only connection without starting a native task.

func (*Bots) Create

func (b *Bots) Create(bot Bot) (BotMutation, error)

func (*Bots) CreateChat

func (b *Bots) CreateChat(id, chatID, title string, projectIDs ...string) (WorkspaceChat, error)

func (*Bots) Delegate

func (b *Bots) Delegate(id string, input BotTaskRequest) (BotTask, error)

Delegate starts a native turn. Reuse RequestID when retrying the same intent.

func (*Bots) Ensure

func (b *Bots) Ensure(agentID, projectID string) (BotMutation, error)

func (*Bots) Get

func (b *Bots) Get(id string) (Bot, error)

func (*Bots) Input

func (b *Bots) Input(id, runID string, input BotTaskInput) (BotTask, error)

func (*Bots) List

func (b *Bots) List(projectID string, includeArchived bool) ([]Bot, error)

func (*Bots) Pair

func (b *Bots) Pair(workspaceID string, peer BotPeer) (BotPeer, error)

Pair stores an explicitly authorized public identity. Set Enabled to grant access.

func (*Bots) PeerIdentity

func (b *Bots) PeerIdentity() (BotPeerIdentity, error)

func (*Bots) Peers

func (b *Bots) Peers() ([]BotPeer, error)

func (*Bots) RevokePeer

func (b *Bots) RevokePeer(workspaceID string) error

func (*Bots) StartPeerListener

func (b *Bots) StartPeerListener(port int) (BotPeerIdentity, error)

StartPeerListener persists a dedicated bot-only SSH/WebSocket listener. Port zero selects an available port. Cloud routing is provisioned separately.

func (*Bots) Task

func (b *Bots) Task(id, runID string) (BotTask, error)

func (*Bots) Tasks

func (b *Bots) Tasks(id string) ([]BotTask, error)

func (*Bots) Update

func (b *Bots) Update(id string, edit BotEdit) (BotMutation, error)

type Capabilities

type Capabilities = agent.Capabilities

Capabilities + the dynamic settings schema.

type Catalog

type Catalog struct {
	Version              string         `json:"version"`
	Agents               []CatalogEntry `json:"agents"`
	HarnessCompatibility HarnessCatalog `json:"harnessCompatibility"`
	HarnessPolicyVersion int            `json:"harnessPolicyVersion"`
}

Catalog is the picker payload: the core version plus every agent this build supports.

type CatalogEntry

type CatalogEntry = agent.CatalogEntry

Capabilities + the dynamic settings schema.

type ChatListOptions

type ChatListOptions = conversations.Query

type ChatSummary

type ChatSummary = session.ChatSummary

Durable records + setup/health reports.

type Check

type Check = agent.Check

Auth, health checks, and notifications.

type Client

type Client struct {

	// Auth is the step-flow authentication sub-API (methods → begin → step → status), scoped to this
	// client's default agent and rebound by WithAgent. Reachable as client.Auth.
	Auth *Auth
	// Prompts is the persistent prompt/memory sub-API (memory files + saved prompt templates), scoped
	// to this client's default agent and rebound by WithAgent. Reachable as client.Prompts.
	Prompts *Prompts
	// MCP is the persistent MCP-server sub-API (the config an agent loads every run, distinct from a
	// turn's per-turn Options.MCPServers), scoped to this client's default agent and rebound by
	// WithAgent. Reachable as client.MCP.
	MCP *MCP
	// Providers is the custom-LLM-provider sub-API (register an OpenAI-compatible endpoint the built-in
	// catalog has never heard of), scoped to this client's default agent and rebound by WithAgent.
	// Reachable as client.Providers.
	Providers *Providers
	// Workspace owns saved workspace metadata shared across all harness views.
	Workspace    *Workspace
	Bots         *Bots
	Apps         *Apps
	Integrations *Integrations
	Surfaces     *Surfaces
	Execution    *WorkspaceExecution
	// contains filtered or unexported fields
}

Client is an in-process handle to the mindwire engine: the same orchestrator.Supervisor the daemon runs, exposed as a Go library with no HTTP server, subprocess, or network in between. Its method set mirrors the TypeScript SDK's Mindwire class one-for-one; every call maps to the same core operation the matching HTTP route invokes, so behavior (including the capability gates and 400/404/409 error semantics) is identical across the two SDKs.

A Client is safe for concurrent use. One Client owns one StatePath: the one-turn-per-chat gate and the JSON store are per-supervisor, so two Clients over the same state file is unsupported (the TS SDK's process-global client sidesteps this; a second Go instance would race the file).

func New

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

New constructs a Client, wiring the engine exactly as packages/daemon/cmd/daemon/main.go does minus the HTTP server: open the state store, reconcile any run left "running" by a prior process, build the event hub, compose the notification fan-out (built-in channels + any Options.Notifier), and construct the supervisor over every registered adapter. Import side effects (register.go) must have populated the adapter and notify registries first — they do, transitively, from importing this package.

func (*Client) ActOnNativeSession

func (c *Client) ActOnNativeSession(ctx context.Context, chatID string, action NativeSessionAction, options NativeSessionOptions) (NativeSessionReceipt, error)

ActOnNativeSession deduplicates requestId within the connectionId returned by NativeSessionEvents. Keep both on retries; an expired epoch is rejected rather than resending a possibly accepted message. Stop requires ExpectedTurnID.

func (*Client) Agent

func (c *Client) Agent(ctx context.Context, opts ...ScopedOption) (AgentInfo, error)

Agent returns the full descriptor for the scoped agent. ctx bounds the auth-status probe and the CLI-version subprocess (the HTTP handler has no such ctx; the Go SDK threads one so callers can cancel these external touches).

func (*Client) Catalog

func (c *Client) Catalog() Catalog

Catalog lists every registered agent (ID-ordered) with the core version.

func (*Client) Chats

func (c *Client) Chats() []ChatSummary

Chats lists native conversations linked to projects plus drafts/emulated chats. Use ListChats for directory/project filtering, explicit refresh and error handling.

func (*Client) Children

func (c *Client) Children(parentID string) ([]*Run, error)

Children returns handles to the child runs of a resolve parent, oldest→newest — the per-iteration turns of a global-resolve run (mirrors GET /runs/{id}/children). APIError{404} if the id is unknown; an ordinary turn (or a parent with no iterations yet) returns an empty slice, never an error.

func (*Client) Close

func (c *Client) Close() error

Close cancels every in-flight turn this client tree started, then blocks until those turns have fully wound down — including the terminal state persist each one writes. Draining before returning is what makes it safe to tear down the state file/working directory right after Close (an embedder's teardown, or a test's TempDir cleanup): without the drain a just-cancelled turn's async SaveRun would race the removal. It is idempotent and safe to call from any WithAgent view (they share one run set). It closes the SQLite registry after draining turns. The JSON state store has no open resources. A second concurrent Close returns immediately; the first one owns the drain.

func (*Client) Commands

func (c *Client) Commands(ctx context.Context, options CommandsOptions, opts ...ScopedOption) (CommandCatalog, error)

Commands discovers controls and native commands in the project's directory. It does not start or resume a model turn. Execute prompt entries with TurnOptions.Command; use Compact or Config for controls instead of sending their slash text to the model.

func (*Client) Compact

func (c *Client) Compact(ctx context.Context, req CompactRequest) (*Run, error)

Compact runs an on-demand conversation compaction as a first-class Run, mirroring POST /chats/{id}/compact. The agent folds prior context into a summary it carries forward; the Run streams a compaction event and records the boundary in history exactly like an auto-compaction. Gates match the HTTP route: the agent must implement compaction (Capabilities.CompactNow) or APIError{400}; the chat must already have a session to compact or APIError{400}; a live turn → APIError{409}. Like Turn, the compaction runs on the supervisor's detached context (not bound to ctx — stop it with Run.Cancel).

func (*Client) DeleteChat

func (c *Client) DeleteChat(chatID string) (DeleteResult, error)

DeleteChat is a true, irreversible delete (mirrors DELETE /chats/{id}): it purges ALL of the chat's mindwire bookkeeping and, for every session the chat mapped to, removes that agent's native transcript (the source of truth). Returns APIError{409} if a turn is live. Native deletion is best-effort per agent — an adapter without HistoryDeleter (or a failing remove) still leaves the bookkeeping purged; the result reports what happened.

func (*Client) DeleteNotifyChannel

func (c *Client) DeleteNotifyChannel(id string) error

DeleteNotifyChannel removes a channel by id (idempotent).

func (*Client) DeleteNotifyRule

func (c *Client) DeleteNotifyRule(id string) error

DeleteNotifyRule removes a rule by id (idempotent).

func (*Client) Doctor

func (c *Client) Doctor(ctx context.Context, opts ...ScopedOption) (DoctorReport, error)

Doctor runs daemon-level health checks (workspace, auth) plus the scoped agent's own checks.

func (*Client) ForkChat

func (c *Client) ForkChat(srcChatID, newChatID string) (ChatSummary, error)

ForkChat clones a chat into a new id (mirrors POST /chats/{id}/fork). newChatID may be empty to generate one. The fork shares the source's native session until its first turn, which branches it natively in Codex and Claude. Returns APIError{409} if the source has a live turn, APIError{404} if the source is unknown, APIError{400} if the target id is already in use. Returns the new chat's summary.

func (*Client) ForkChatAt

func (c *Client) ForkChatAt(srcChatID string, opts ForkChatOptions) (ChatSummary, error)

func (*Client) GetConfig

func (c *Client) GetConfig(opts ...ScopedOption) (map[string]string, error)

GetConfig returns the scoped agent's declared, non-secret settings (for prefilling a form). Secret and unrecognized keys are filtered out, exactly as the HTTP /config route does.

func (*Client) GetNotifyConfig

func (c *Client) GetNotifyConfig() NotifyConfigStatus

GetNotifyConfig reports the provisioned notification webhook (without the token).

func (*Client) Handoff added in v0.1.54

func (c *Client) Handoff(ctx context.Context, sourceChatID string, request HandoffRequest) (*HandoffResult, error)

Handoff starts a fresh session on another saved agent in the same project. Reuse NewChatID, RequestID and the identical payload after a lost response.

func (*Client) Health

func (c *Client) Health() Health

Health returns the liveness snapshot. It cannot fail in-process.

func (*Client) LatestRun

func (c *Client) LatestRun(chatID string) (*Run, error)

LatestRun returns a handle to the chat's most recent run, or (nil, nil) if the chat has no runs yet.

func (*Client) ListChats

func (c *Client) ListChats(ctx context.Context, options ChatListOptions) ([]ChatSummary, error)

func (*Client) Messages

func (c *Client) Messages(chatID string, opts MessagesOptions) ([]Message, error)

Messages returns a chat's transcript. For an agent with native history it reads the agent's own transcript (falling back to the recorded log if that read is empty or errors); otherwise it returns the daemon's recorded log. Either way the result is windowed by Limit/Before. The recorded fallback is converted from the store's Message to the unified agent.Message shape.

func (*Client) Models

func (c *Client) Models(opts ...ScopedOption) ([]ModelInfo, error)

Models lists the models available to the scoped agent (mirrors GET /models). Only agents that implement the model-listing module answer; others return a 400-status APIError. The list may be empty (no credentials / not-yet-fetched) — that is a valid result, not an error.

func (*Client) NativeSessionActivity

func (c *Client) NativeSessionActivity(ctx context.Context, chatID string, options NativeSessionOptions) (SessionActivity, error)

NativeSessionActivity discovers an existing owner without resuming a thread. Per-session capabilities, rather than harness-wide hints, govern live controls.

func (*Client) NativeSessionEvents

func (c *Client) NativeSessionEvents(ctx context.Context, chatID string, options NativeSessionOptions) iter.Seq2[NativeSessionFrame, error]

NativeSessionEvents observes the existing native process. Breaking iteration detaches this viewer; it never stops the turn. A snapshot replaces the current live-turn projection, while a resume retains it and replays newer updates.

func (*Client) Notifications

func (c *Client) Notifications(ctx context.Context) iter.Seq[Notification]

Notifications streams the daemon's notifications — the same payloads pushed to the webhook — as an iter.Seq: replay buffer first, then live events until ctx is cancelled or the stream closes. The underlying subscription is always released when the range ends (break, return, or ctx-cancel).

func (*Client) NotifyChannelByID

func (c *Client) NotifyChannelByID(id string) (NotifyChannel, error)

NotifyChannelByID returns one channel by id (APIError{404} if unknown).

func (*Client) NotifyChannels

func (c *Client) NotifyChannels() []NotifyChannel

NotifyChannels returns every configured channel.

func (*Client) NotifyRuleByID

func (c *Client) NotifyRuleByID(id string) (NotifyRule, error)

NotifyRuleByID returns one rule by id (APIError{404} if unknown).

func (*Client) NotifyRules

func (c *Client) NotifyRules() []NotifyRule

NotifyRules returns every routing rule.

func (*Client) PreviewHandoff added in v0.1.54

func (c *Client) PreviewHandoff(ctx context.Context, chatID string) (HandoffPreview, error)

PreviewHandoff exports portable context without running either agent. Return Digest as PreviewDigest with reviewed Context; nil Context captures at admission.

func (*Client) Processes

func (c *Client) Processes(ctx context.Context, agent string) iter.Seq[ProcessFrame]

Processes streams live per-turn CPU/memory as an iter.Seq of ProcessFrames — the same on-demand, refcounted sampler the HTTP /processes/stream route serves, here in-process. Subscribing STARTS the sampler if it's the first watcher; ending the range (break, return, or ctx-cancel) releases the subscription and STOPS the sampler when it's the last — so no sampling runs unless someone iterates. When agent is non-empty, each frame's Samples are filtered to that agent. Frames are live snapshots (no replay); an empty Samples slice is a valid keep-alive frame. ok=false (sampler at capacity) yields nothing.

func (*Client) RenameChat

func (c *Client) RenameChat(chatID, title string) (ChatSummary, error)

RenameChat sets a user-chosen title for a chat (mirrors PUT /chats/{id}). The user title wins over the agent's native auto-title in every listing; an empty title clears the rename. Returns the updated summary. A persistence failure surfaces as APIError{500}.

func (*Client) Resolve

func (c *Client) Resolve(ctx context.Context, req ResolveRequest) (*Run, error)

Resolve starts a GLOBAL-RESOLVE run and returns a handle to the PARENT Run, mirroring POST /turns with {mode:"resolve"}. Unlike Turn, the daemon holds the run open and auto-continues the agent's own multi-step work until the task is globally complete (the agent emits the completion sentinel), an unrecoverable error occurs, or a cap is hit; each auto-continued iteration is a child run whose events stream onto the parent's topic (one merged stream — Stream/Wait on the parent see the whole resolve and Wait returns the final aggregate result). Children returns the per-iteration runs. Gates match Turn: unknown agent / missing fields / an unsupported per-turn option → APIError{400}; a chat with a turn already in flight → APIError{409}. Like Turn it runs on the supervisor's detached context (bound by the resolve deadline, not ctx — stop it with Run.Cancel).

func (*Client) Run

func (c *Client) Run(id string) (*Run, error)

Run returns a handle to an existing run by id, or APIError{404} if there is no such run.

func (*Client) SetConfig

func (c *Client) SetConfig(values map[string]string, opts ...ScopedOption) error

SetConfig merges values into the scoped agent's namespaced config, ignoring any key the agent doesn't declare (a persistence failure surfaces as APIError{500}). Keys may be the agent's raw setting keys OR canonical keys (e.g. "reasoningEffort") that resolve to a declared non-secret field — the latter persist under the resolved raw key, mirroring the HTTP /config route.

func (*Client) SetNotifyChannel

func (c *Client) SetNotifyChannel(ch NotifyChannel) (NotifyChannel, error)

SetNotifyChannel upserts a channel, minting an id when the input omits one. Returns the stored channel. APIError{400} for an invalid type or a missing url.

func (*Client) SetNotifyConfig

func (c *Client) SetNotifyConfig(in NotifyConfigInput) error

SetNotifyConfig provisions the notification webhook (url and channel required, or APIError{400}).

func (*Client) SetNotifyRule

func (c *Client) SetNotifyRule(r NotifyRule) (NotifyRule, error)

SetNotifyRule upserts a routing rule, minting an id when the input omits one. Returns the stored rule. APIError{400} for an incoherent scope or an empty channel set.

func (*Client) Setup

func (c *Client) Setup(opts ...ScopedOption) (SetupStatus, error)

Setup starts the scoped agent's toolchain install in the background and returns an immediate status snapshot. Poll SetupStatus for progress + completion. Idempotent: a concurrent Setup re-attaches to the in-flight job rather than starting a second install.

func (*Client) SetupStatus

func (c *Client) SetupStatus(opts ...ScopedOption) (SetupStatus, error)

SetupStatus reports the scoped agent's current install job (running/ok/steps). A never-started agent reports the zero status.

func (*Client) Software

func (c *Client) Software(ctx context.Context, forceRefresh bool, opts ...ScopedOption) (HarnessSoftware, error)

Software returns the daemon's compatibility decision. forceRefresh bypasses the catalog TTL (bounded by a short retry backoff); an unavailable catalog retains the last verified policy.

func (*Client) Stats

func (c *Client) Stats() Stats

Stats returns the process resource snapshot. It reads the Go runtime at call time and cannot fail.

func (*Client) TestNotifyChannel

func (c *Client) TestNotifyChannel(ctx context.Context, id string) error

TestNotifyChannel delivers a synthetic notification to a channel and returns nil on a 2xx, else an error describing the failure. APIError{404} if the channel id is unknown.

func (*Client) Turn

func (c *Client) Turn(ctx context.Context, req TurnRequest) (*Run, error)

Turn starts a turn and returns a handle to the running Run. It enforces the same gates as POST /turns: an unsupported per-turn option → APIError{400}; a chat that already has a turn in flight → APIError{409}. The turn executes on the supervisor's own detached 30-minute context and is NOT bound to ctx — ctx is accepted for call symmetry and future use; stop a turn with Run.Cancel, not ctx.

Example

Turn options are addressed with agent-agnostic canonical keys; the runner maps each to the selected agent's own field. A capability the agent lacks surfaces as an *APIError with Status 400.

package main

import (
	"context"
	"log"

	mindwire "github.com/oblien/mindwire/packages/daemon/sdk"
)

func main() {
	client, err := mindwire.New(mindwire.Options{Agent: "claude-code"})
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	_, err = client.Turn(context.Background(), mindwire.TurnRequest{
		ChatID:  "chat-1",
		Message: "Refactor this package.",
		Options: mindwire.TurnOptions{Settings: map[string]string{mindwire.CanonModel: "opus"}},
	})
	if err != nil {
		log.Fatal(err)
	}
}

func (*Client) Update

func (c *Client) Update(opts ...ScopedOption) (SetupStatus, error)

Update is Setup with force=true: it reinstalls/upgrades even when the toolchain is already present.

func (*Client) UploadAttachment

func (c *Client) UploadAttachment(chatID, name, mime string, data []byte) (Attachment, error)

UploadAttachment stores a file beside the conversation and returns a small reference for Turn or InputWithOptions. The native CLI receives image input or a durable file path, and the data travels with project context switching.

func (*Client) UploadAttachmentChunk

func (c *Client) UploadAttachmentChunk(chatID, id string, chunk AttachmentUploadChunk) (AttachmentUploadState, error)

UploadAttachmentChunk mirrors the resumable authenticated HTTP upload. A retry returns the verified offset, without duplicating bytes or overwriting a file.

func (*Client) VoiceStatus

func (c *Client) VoiceStatus(ctx context.Context, opts ...ScopedOption) (VoiceStatus, error)

VoiceStatus checks the selected harness without recording or starting a turn.

func (*Client) WithAgent

func (c *Client) WithAgent(agentType string) *Client

WithAgent returns a lightweight view of this Client whose default agent is agentType. It shares the same underlying engine (store, hub, supervisor, in-flight run set) — only the scoped-agent default and the Auth binding differ — so it is cheap and needs no Close of its own.

type Command

type Command = agent.Command

type CommandCatalog

type CommandCatalog = agent.CommandCatalog

type CommandInvocation

type CommandInvocation = agent.CommandInvocation

type CommandsOptions

type CommandsOptions struct {
	Directory string
	Refresh   bool // Refresh completed metadata; concurrent discovery is still shared.
}

type CompactRequest

type CompactRequest struct {
	ChatID       string `json:"chatId"`
	Instructions string `json:"instructions,omitempty"`
	RequestID    string `json:"requestId,omitempty"`
	Agent        string `json:"agent,omitempty"`
}

CompactRequest is the input to Compact: the chat to compact, an optional focus for the continuation summary (Instructions — Claude's `/compact <instructions>`; agents that don't honor focus still compact), and the target agent (empty = the client default).

type CompactionInfo

type CompactionInfo = agent.CompactionInfo

Streaming events (the unified turn stream). See Run.Stream.

type Condition

type Condition = agent.Condition

Auth, health checks, and notifications.

type ConditionUX

type ConditionUX = agent.ConditionUX

Auth, health checks, and notifications.

type ContinuationInfo

type ContinuationInfo = agent.ContinuationInfo

ContinuationInfo delimits one iteration of a global-resolve run on the merged parent stream (see Client.Resolve). Carried on an EventContinuation. Field additions to Event/ResultInfo/RunRecord (Subtype, ParentID, Kind, StopReason, Iterations) and to Capabilities (Resolve) propagate through the aliases automatically; only this new named type and the EventContinuation const are added here.

type Conversation

type Conversation = conversations.Conversation

type ConversationOpenRequest

type ConversationOpenRequest = conversations.OpenRequest

type ConversationOpenResult

type ConversationOpenResult = conversations.OpenResult

type ConversationPage

type ConversationPage = conversations.Page

type ConversationQuery

type ConversationQuery = conversations.BrowseQuery

type CreateSavedDesktop

type CreateSavedDesktop = surface.CreateDesktopRequest

type CustomProvider

type CustomProvider = agent.CustomProvider

CustomProvider is one registered custom OpenAI-compatible LLM provider (GET/PUT/DELETE /providers). See Client.Providers and agent/providers.go. The API key is never part of this shape — it is supplied write-only on Set and reported only as HasKey.

type DeleteResult

type DeleteResult struct {
	Deleted      bool     `json:"deleted"`
	Sessions     int      `json:"sessions"`
	NativePurged []string `json:"nativePurged,omitempty"`
	NativeFailed []string `json:"nativeFailed,omitempty"`
}

DeleteResult reports a chat delete (mirrors the HTTP DELETE /chats/{id} response): the bookkeeping was purged, plus which agents' native transcripts were removed vs. failed to remove (best-effort, per session the chat mapped to).

type DesktopCatalog

type DesktopCatalog = surface.DesktopCatalog

type DesktopResolution

type DesktopResolution = surface.DesktopResolution

type DesktopResult

type DesktopResult = surface.DesktopResult

type DesktopRuntimeBinding

type DesktopRuntimeBinding = surface.RuntimeBinding

Saved desktops are durable; control sessions and live leases remain ephemeral.

type DesktopSSHConnection

type DesktopSSHConnection = surface.SSHConnection

type DesktopSSHSettings

type DesktopSSHSettings = surface.SSHSettings

type DesktopVNCSettings

type DesktopVNCSettings = surface.VNCSettings

type DoctorReport

type DoctorReport = orchestrator.DoctorReport

Durable records + setup/health reports.

type EnsureAgentRequest

type EnsureAgentRequest = registry.EnsureAgentRequest

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type EnsureAgentResult

type EnsureAgentResult = registry.EnsureAgentResult

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type Error

type Error struct {
	Message string
	Cause   error
}

Error is the SDK's base error, returned for failures that don't carry an HTTP-style status — chiefly New() failing to open the state file. Cause is the wrapped underlying error, if any.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Event

type Event = agent.Event

Streaming events (the unified turn stream). See Run.Stream.

type EventType

type EventType = agent.EventType

EventType is the kind discriminator on an Event; see the Event* consts. Additive to the wire — a consumer that doesn't recognize a value should ignore that event.

type ExistingAuthConnection

type ExistingAuthConnection = agent.ExistingAuthConnection

Auth, health checks, and notifications.

type Field

type Field = agent.Field

Capabilities + the dynamic settings schema.

type FieldCondition

type FieldCondition = agent.FieldCondition

Capabilities + the dynamic settings schema.

type FieldType

type FieldType = agent.FieldType

Capabilities + the dynamic settings schema.

type FileChange

type FileChange = agent.FileChange

Deep tool normalization: the structured `Action` carried on both a streaming ToolEvent and a transcript ToolPart. Only the sub-object matching Kind is populated. See agent/toolaction.go.

type ForkChatOptions

type ForkChatOptions struct {
	NewChatID string `json:"newChatId,omitempty"`
	// Excludes this user message and everything after it. Reuse NewChatID on retries.
	BeforeMessageID string `json:"beforeMessageId,omitempty"`
}

type HandoffArtifact added in v0.1.54

type HandoffArtifact = agent.HandoffArtifact

type HandoffContext added in v0.1.54

type HandoffContext = agent.HandoffContext

type HandoffLoss added in v0.1.54

type HandoffLoss = agent.HandoffLoss

type HandoffOrigin added in v0.1.54

type HandoffOrigin = registry.HandoffOrigin

type HandoffPreview added in v0.1.54

type HandoffPreview = handoffs.Preview

type HandoffRequest added in v0.1.54

type HandoffRequest = handoffs.Request

type HandoffResult added in v0.1.54

type HandoffResult struct {
	ChatID   string
	Run      *Run
	Snapshot WorkspaceSnapshot
}

type HandoffSource added in v0.1.54

type HandoffSource = agent.HandoffSource

type HandoffSummary added in v0.1.54

type HandoffSummary = agent.HandoffSummary

type HandoffTool added in v0.1.54

type HandoffTool = agent.HandoffTool

type HandoffTurn added in v0.1.54

type HandoffTurn = agent.HandoffTurn

type HarnessCatalog

type HarnessCatalog = toolchain.Catalog

type HarnessDaemonRange

type HarnessDaemonRange = toolchain.DaemonRange

type HarnessExclusion

type HarnessExclusion = toolchain.Exclusion

type HarnessPolicy

type HarnessPolicy = toolchain.Harness

type HarnessRelease

type HarnessRelease = toolchain.Release

type HarnessSoftware

type HarnessSoftware = toolchain.Software

type Health

type Health struct {
	OK                             bool   `json:"ok"`
	NativeAuthSource               bool   `json:"nativeAuthSource"`
	Agent                          string `json:"agent"`
	Version                        string `json:"version"`
	WorkspaceMetadataVersion       int    `json:"workspaceMetadataVersion"`
	BotsVersion                    int    `json:"botsVersion"`
	AppsVersion                    int    `json:"appsVersion"`
	IntegrationsVersion            int    `json:"integrationsVersion"`
	AgentDiscoveryVersion          int    `json:"agentDiscoveryVersion"`
	ProjectLibraryVersion          int    `json:"projectLibraryVersion"`
	ProjectOperationsVersion       int    `json:"projectOperationsVersion"`
	ProjectIconsVersion            int    `json:"projectIconsVersion"`
	ProjectSyncVersion             int    `json:"projectSyncVersion"`
	ConversationBrowserVersion     int    `json:"conversationBrowserVersion"`
	SurfaceProtocolVersion         int    `json:"surfaceProtocolVersion"`
	LocalDesktopVersion            int    `json:"localDesktopVersion"`
	NotificationPreferencesVersion int    `json:"notificationPreferencesVersion"`
	HarnessPolicyVersion           int    `json:"harnessPolicyVersion"`
	WorkspaceIsolationVersion      int    `json:"workspaceIsolationVersion"`
	WorkspaceIsolation             string `json:"workspaceIsolation"`
	WorkspaceExecutionVersion      int    `json:"workspaceExecutionVersion"`
	TerminalProtocolVersion        int    `json:"terminalProtocolVersion"`
	TurnRequestVersion             int    `json:"turnRequestVersion"`
	QueuedInputVersion             int    `json:"queuedInputVersion"`
	NativeSessionVersion           int    `json:"nativeSessionVersion"`
	AttachmentUploadVersion        int    `json:"attachmentUploadVersion"`
	ImageAttachmentsVersion        int    `json:"imageAttachmentsVersion"`
	ChatForkVersion                int    `json:"chatForkVersion"`
	CrossAgentHandoffVersion       int    `json:"crossAgentHandoffVersion"`
}

Health reports the daemon-level liveness snapshot (the /healthz payload): always ok in-process, plus the default agent type and the core's version.

type HistoryQuery

type HistoryQuery = agent.HistoryQuery

Chat transcript shapes.

type HostResources

type HostResources = workspaceexec.Resources

type Inbound

type Inbound = agent.Inbound

Turn inputs.

type InputOptions

type InputOptions struct {
	RequestID   string
	Attachments []Attachment
}

InputOptions adds a stable retry receipt and optional images to a follow-up. Reuse RequestID only when retrying the same text and attachments.

type Integration

type Integration = integrations.Connection

type IntegrationCredentials

type IntegrationCredentials = integrations.Credentials

type IntegrationReceipt

type IntegrationReceipt = integrations.Receipt

type IntegrationSpec

type IntegrationSpec = integrations.Spec

type Integrations

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

Integrations shares the daemon's persistent connections and native bot runtime. Start explicitly opts an embedded host into receiving and executing queued events.

func (*Integrations) Create

func (i *Integrations) Create(spec IntegrationSpec) (Integration, error)

func (*Integrations) Delete

func (i *Integrations) Delete(id string) error

func (*Integrations) Events

func (i *Integrations) Events(id string) ([]IntegrationReceipt, error)

func (*Integrations) Get

func (i *Integrations) Get(id string) (Integration, error)

func (*Integrations) List

func (i *Integrations) List() ([]Integration, error)

func (*Integrations) Retry

func (i *Integrations) Retry(id, eventID string) (IntegrationReceipt, error)

func (*Integrations) Send

func (i *Integrations) Send(ctx context.Context, id, text string) error

func (*Integrations) Start

func (i *Integrations) Start()

func (*Integrations) Update

func (i *Integrations) Update(id string, spec IntegrationSpec) (Integration, error)

func (*Integrations) Webhook

func (i *Integrations) Webhook(w http.ResponseWriter, r *http.Request)

Webhook validates provider signatures itself. Register using Go's path pattern POST /integrations/{id}/webhook; keep management routes behind owner auth.

type Interaction

type Interaction = agent.Interaction

Mid-turn interactions the agent surfaces (a question, a plan to approve, todo progress).

type InteractionResponse

type InteractionResponse = agent.InteractionResponse

Mid-turn interactions the agent surfaces (a question, a plan to approve, todo progress).

type LocalDesktopInfo

type LocalDesktopInfo = surface.LocalDesktopInfo

type LocalDesktopSettings

type LocalDesktopSettings = surface.LocalDesktopSettings

type MCP

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

MCP is the persistent MCP-server sub-API, reachable as Client.MCP. It reads and writes the MCP servers an agent loads on every run from its own on-disk config — Claude's JSON stores (project .mcp.json + user .claude.json) and Codex's config.toml [mcp_servers.*] tables — as opposed to a turn's per-turn Options.MCPServers passthrough. Each call maps one-for-one to a /mcp HTTP route and enforces the same gates: an agent without the underlying optional module surfaces as APIError{400}; a missing server on Get is APIError{404}; an invalid name or unsupported scope is 400. It is scoped to its client's default agent and rebinds under WithAgent; override per call with ForAgent.

A server definition carries an env-var NAME for HTTP bearer auth (BearerTokenEnvVar), never a secret value — no credential ever crosses this surface. dir selects the project-scope working directory — empty resolves to the client's cwd (else the process cwd).

func (*MCP) Delete

func (m *MCP) Delete(scope MemoryScope, dir, name string, opts ...ScopedOption) error

Delete removes one server at a scope. An empty scope defaults to user. Deleting an absent server (or from a missing config) is not an error (idempotent), matching DELETE /mcp/{name}. An unsupported scope is APIError{400}.

func (*MCP) Get

func (m *MCP) Get(scope MemoryScope, dir, name string, opts ...ScopedOption) (MCPServer, error)

Get returns one server by name at a scope. An empty scope defaults to user. A server that isn't configured maps to APIError{404}; an unsupported scope to APIError{400}, matching GET /mcp/{name}.

func (*MCP) List

func (m *MCP) List(dir string, opts ...ScopedOption) (map[MemoryScope]map[string]MCPServer, error)

List returns the scoped agent's persistent MCP servers across every supported scope (Claude: project + user; Codex: user only), keyed scope→name→server. A missing config file yields an empty map for that scope, not an error; any other failure is APIError{500}, matching GET /mcp. An agent without the module is APIError{400}.

func (*MCP) Set

func (m *MCP) Set(scope MemoryScope, dir, name string, server MCPServer, opts ...ScopedOption) (MCPServer, error)

Set writes one server at a scope and returns it (echoed, as PUT /mcp/{name} does). An empty scope defaults to user. An invalid name or unsupported scope is APIError{400}. HTTP auth is expressed via BearerTokenEnvVar (an env-var name) or HTTPHeaders — never a secret value.

type MCPCall

type MCPCall = agent.MCPCall

Deep tool normalization: the structured `Action` carried on both a streaming ToolEvent and a transcript ToolPart. Only the sub-object matching Kind is populated. See agent/toolaction.go.

type MCPServer

type MCPServer = agent.MCPServer

MCPServer is one persistent MCP-server definition (GET/PUT/DELETE /mcp). See Client.MCP and agent/mcp.go. Carries an env-var NAME for HTTP auth (bearerTokenEnvVar), never a secret value.

type MemoryDoc

type MemoryDoc = agent.MemoryDoc

Persistent prompt/memory surface: the agent's memory file (CLAUDE.md / AGENTS.md) and its saved prompt templates (slash-commands / saved prompts), each addressed by a canonical MemoryScope. See Client.Prompts and agent/memory.go, agent/prompts.go.

type MemoryScope

type MemoryScope = agent.MemoryScope

Persistent prompt/memory surface: the agent's memory file (CLAUDE.md / AGENTS.md) and its saved prompt templates (slash-commands / saved prompts), each addressed by a canonical MemoryScope. See Client.Prompts and agent/memory.go, agent/prompts.go.

type Message

type Message = agent.Message

Chat transcript shapes.

type MessagesOptions

type MessagesOptions struct {
	Agent  string
	Limit  int
	Before string
}

MessagesOptions parameterizes Messages: the target agent (empty = the client default) and a paging window (Limit = tail size, Before = return only messages strictly before this id). The zero value returns the whole transcript for the default agent.

type ModelCost

type ModelCost = agent.ModelCost

ModelInfo is one entry in the agent's model list (GET /models), carrying provider-aware metadata when the on-disk catalog can supply it. ModelCost is its per-million-token pricing. See Client.Models and agent/models.go.

type ModelInfo

type ModelInfo = agent.ModelInfo

ModelInfo is one entry in the agent's model list (GET /models), carrying provider-aware metadata when the on-disk catalog can supply it. ModelCost is its per-million-token pricing. See Client.Models and agent/models.go.

type NativeSessionAction

type NativeSessionAction = agent.NativeSessionAction

type NativeSessionCapabilities

type NativeSessionCapabilities = agent.NativeSessionCapabilities

type NativeSessionError

type NativeSessionError = agent.NativeSessionError

type NativeSessionEvent

type NativeSessionEvent = nativesessions.Event

type NativeSessionFrame

type NativeSessionFrame = nativesessions.Frame

type NativeSessionOptions

type NativeSessionOptions struct {
	Agent string
	// Reuse both cursor fields only while retaining the corresponding UI state.
	ConnectionID string
	After        int64
}

type NativeSessionReceipt

type NativeSessionReceipt = agent.NativeSessionReceipt

type NativeSessionSnapshot

type NativeSessionSnapshot = nativesessions.Snapshot

type Notification

type Notification = agent.Notification

Auth, health checks, and notifications.

type NotificationSpec

type NotificationSpec = agent.NotificationSpec

Auth, health checks, and notifications.

type Notifier

type Notifier = notify.Notifier

Notifier is the delivery interface an extra notification channel implements. Pass one via Options.Notifier to fan turn notifications out to your own sink alongside the built-in channels.

type NotifyChannel

type NotifyChannel = agent.NotifyChannel

Auth, health checks, and notifications.

type NotifyChannelType

type NotifyChannelType = agent.NotifyChannelType

Daemon-driven fan-out: named delivery targets + the rules that route notifications to them.

type NotifyConfigInput

type NotifyConfigInput struct {
	URL     string            `json:"url"`
	Channel string            `json:"channel"`
	Token   string            `json:"token,omitempty"`
	Format  NotifyChannelType `json:"format,omitempty"`
}

NotifyConfigInput provisions the notification webhook the daemon POSTs to.

type NotifyConfigStatus

type NotifyConfigStatus struct {
	Configured bool              `json:"configured"`
	URL        string            `json:"url"`
	Channel    string            `json:"channel"`
	Format     NotifyChannelType `json:"format"`
	HasToken   bool              `json:"hasToken"`
}

NotifyConfigStatus reports whether a notification webhook is wired (the token is never returned).

type NotifyRule

type NotifyRule = agent.NotifyRule

Auth, health checks, and notifications.

type NotifyRuleScope

type NotifyRuleScope = agent.NotifyRuleScope

Auth, health checks, and notifications.

type Option

type Option = agent.Option

Capabilities + the dynamic settings schema.

type Options

type Options struct {
	// Agent is the default agent type for scoped calls (e.g. "claude-code"). Empty selects the
	// daemon's default (the first registered adapter by ID). Override per call with ForAgent.
	Agent string
	// CWD is the working directory turns run in unless a TurnRequest overrides it. Empty uses the
	// process directory (a doctor Workspace check warns when unset, matching the daemon).
	CWD string
	// StatePath is the JSON state file backing sessions, runs, config, and creds. Empty defaults to
	// "agent-state.json" — the same default the daemon binary uses.
	StatePath string
	// AuthSource reuses a trusted host connection on the first status read or turn.
	// Reuse "manual" offers Auth.Methods/Begin without automatic first-use import.
	// The source environment is for credential lookup, never a run environment.
	AuthSource *AuthSource
	// WorkspaceDBPath stores authoritative profiles/projects/chat links. Empty uses workspace.db
	// beside StatePath, matching the standalone daemon.
	WorkspaceDBPath string
	// Notifier, if set, receives turn notifications alongside the built-in env-configured channels
	// (a webhook, notify/file, notify/exec). nil = just the built-ins.
	Notifier Notifier
	// RunScheduledJobs explicitly makes this embedded runtime the owner of saved
	// background jobs. Default false: reading/configuring Apps never starts jobs.
	// Use one scheduler owner for a state directory. The standalone daemon owns its scheduler.
	RunScheduledJobs bool
	// RunIntegrations opts this host into resuming and executing incoming messaging events.
	RunIntegrations bool
}

Options configures a Client. The zero value is usable: it opens "agent-state.json" in the current directory and drives the daemon's default agent with no extra notifier.

type OutputMode

type OutputMode = agent.OutputMode

Capabilities + the dynamic settings schema.

type Part

type Part = agent.Part

Chat transcript shapes.

type ProcessFrame

type ProcessFrame = procmon.Frame

Live per-turn resource sampling (Client.Processes). A ProcessFrame is one sampling tick; each ProcessSample is one running turn's summed CPU%/RSS, labeled (agent, chatId, runId). See procmon.

type ProcessSample

type ProcessSample = procmon.Sample

Auth, health checks, and notifications.

type ProjectAuth

type ProjectAuth = projects.Auth

type ProjectFolder

type ProjectFolder = registry.ProjectFolder

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type ProjectIcon

type ProjectIcon = projecticon.Image

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type ProjectLibrary

type ProjectLibrary = registry.ProjectLibrary

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type ProjectLibraryEdit

type ProjectLibraryEdit = registry.ProjectLibraryEdit

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type ProjectOperation

type ProjectOperation = registry.ProjectOperation

type ProjectOperations

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

func (*ProjectOperations) Cancel

func (*ProjectOperations) Get

func (*ProjectOperations) List

func (p *ProjectOperations) List(activeOnly bool) ([]ProjectOperation, error)

func (*ProjectOperations) Retry

func (*ProjectOperations) Watch

Watch yields the latest durable snapshot immediately, then changes until terminal. Cancelling ctx detaches only this observer. Cancel(id) explicitly stops the operation.

type ProjectPlacement

type ProjectPlacement = registry.ProjectPlacement

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type ProjectRemoveRequest

type ProjectRemoveRequest = projects.RemoveRequest

type ProjectRequest

type ProjectRequest = projects.Request

type ProjectSpec

type ProjectSpec = registry.ProjectSpec

type ProjectSync

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

func (*ProjectSync) AcceptCheckpoint

func (s *ProjectSync) AcceptCheckpoint(ctx context.Context, c ProjectSyncCheckpoint) error

func (*ProjectSync) Cancel

func (s *ProjectSync) Cancel(id string) (ProjectSyncOperation, error)

func (*ProjectSync) Checkpoint

func (s *ProjectSync) Checkpoint(id string) (ProjectSyncCheckpoint, error)

func (*ProjectSync) Export

func (*ProjectSync) Get

func (*ProjectSync) GetObject

func (s *ProjectSync) GetObject(id string) ([]byte, error)

func (*ProjectSync) Import

func (*ProjectSync) List

func (s *ProjectSync) List() ([]ProjectSyncOperation, error)

func (*ProjectSync) Missing

func (s *ProjectSync) Missing(ids []string) ([]string, error)

func (*ProjectSync) Objects

func (s *ProjectSync) Objects(id string, cursor int) (ProjectSyncObjectPage, error)

func (*ProjectSync) Preview

func (*ProjectSync) PutObject

func (s *ProjectSync) PutObject(id string, data []byte) error

func (*ProjectSync) RelayCheckpoint

func (s *ProjectSync) RelayCheckpoint(ctx context.Context, target *ProjectSync, id string, progress func(int64)) error

RelayCheckpoint transfers only missing immutable chunks, parents first. The caller may retry after losing connectivity; verified objects are reused.

func (*ProjectSync) Retry

func (s *ProjectSync) Retry(id string) (ProjectSyncOperation, error)

func (*ProjectSync) SwitchTo

func (s *ProjectSync) SwitchTo(ctx context.Context, target *ProjectSync, req ProjectSyncRequest, progress func(int64)) (ProjectSyncOperation, error)

SwitchTo preserves the source and opens no chat or process. Stable request IDs make a lost acknowledgement safe. A conflict is returned as an operation so callers can show its paths and retained recovery checkpoint instead of hiding it.

func (*ProjectSync) Wait

type ProjectSyncCheckpoint

type ProjectSyncCheckpoint = projectsync.Checkpoint

type ProjectSyncConflict

type ProjectSyncConflict = projectsync.Conflict

type ProjectSyncIgnoredPath

type ProjectSyncIgnoredPath = projectsync.IgnoredPath

type ProjectSyncObjectPage

type ProjectSyncObjectPage = projectsync.ObjectPage

type ProjectSyncOperation

type ProjectSyncOperation = projectsync.Operation

type ProjectSyncPreview

type ProjectSyncPreview = projectsync.Preview

type ProjectSyncPreviewRequest

type ProjectSyncPreviewRequest = projectsync.PreviewRequest

type ProjectSyncRequest

type ProjectSyncRequest = projectsync.Request

type PromptTemplate

type PromptTemplate = agent.PromptTemplate

Persistent prompt/memory surface: the agent's memory file (CLAUDE.md / AGENTS.md) and its saved prompt templates (slash-commands / saved prompts), each addressed by a canonical MemoryScope. See Client.Prompts and agent/memory.go, agent/prompts.go.

type Prompts

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

Prompts is the persistent prompt/memory sub-API, reachable as Client.Prompts. It exposes the three layers beneath a turn's per-turn Options.SystemPrompt: an agent's memory file (Claude's CLAUDE.md, Codex's AGENTS.md) and its saved prompt templates (Claude slash-commands, Codex saved prompts). Each call maps one-for-one to a /memory or /prompts HTTP route and enforces the same gates: an agent without the underlying optional module surfaces as APIError{400}; an unsupported scope is 400; a missing template is APIError{404}. It is scoped to its client's default agent and rebinds under WithAgent; override per call with ForAgent.

dir selects the project-scope working directory — empty resolves to the client's cwd (else the process cwd), matching how turns pick a working directory. None of these files is a secret.

func (*Prompts) Delete

func (p *Prompts) Delete(scope MemoryScope, dir, name string, opts ...ScopedOption) error

Delete removes one template at scope. An empty scope defaults to user. Idempotent — deleting an absent template still succeeds. An invalid name or unsupported scope is APIError{400}, matching DELETE /prompts/{name}.

func (*Prompts) DeleteMemory

func (p *Prompts) DeleteMemory(scope MemoryScope, dir string, opts ...ScopedOption) (MemoryDoc, error)

DeleteMemory removes the scoped agent's memory file at scope and returns the resulting doc (Exists=false). An empty scope defaults to user. Idempotent — deleting an absent file still succeeds. A bad scope is APIError{400}, matching DELETE /memory.

func (*Prompts) DeleteSubagent

func (p *Prompts) DeleteSubagent(scope MemoryScope, dir, name string, opts ...ScopedOption) error

DeleteSubagent removes one definition at scope. An empty scope defaults to user. Idempotent — deleting an absent definition still succeeds. An invalid name or unsupported scope is APIError{400}, matching DELETE /subagents/{name}.

func (*Prompts) Get

func (p *Prompts) Get(scope MemoryScope, dir, name string, opts ...ScopedOption) (PromptTemplate, error)

Get returns one template's full content. An empty scope defaults to user — the scope every prompt-supporting agent has. A missing template maps to APIError{404}; an invalid name or unsupported scope to APIError{400}, matching GET /prompts/{name}.

func (*Prompts) List

func (p *Prompts) List(dir string, opts ...ScopedOption) ([]PromptTemplate, error)

List returns the scoped agent's saved prompt templates across every supported scope (Claude: project + user; Codex: user only). Content is omitted here — fetch it with Get. A missing prompt directory yields an empty list for that scope, not an error; any other failure is APIError{500}, matching GET /prompts.

func (*Prompts) Memory

func (p *Prompts) Memory(dir string, opts ...ScopedOption) ([]MemoryDoc, error)

Memory returns the scoped agent's memory file at every supported scope (project + user for both Claude and Codex). Each doc carries its resolved path and whether the file exists; an absent file has Exists=false and empty Content. A read error surfaces as APIError{500}, matching GET /memory.

func (*Prompts) Set

func (p *Prompts) Set(scope MemoryScope, dir, name, content string, opts ...ScopedOption) (PromptTemplate, error)

Set creates or overwrites a template and returns it. An empty scope defaults to user. An invalid name or unsupported scope is APIError{400}, matching PUT /prompts/{name}.

func (*Prompts) SetMemory

func (p *Prompts) SetMemory(scope MemoryScope, dir, content string, opts ...ScopedOption) (MemoryDoc, error)

SetMemory writes the scoped agent's memory file at scope and returns the resulting doc (resolved path, Exists=true). A bad scope or a missing project directory is a caller error → APIError{400}, matching PUT /memory.

func (*Prompts) SetSubagent

func (p *Prompts) SetSubagent(scope MemoryScope, dir, name, content string, opts ...ScopedOption) (Subagent, error)

SetSubagent creates or overwrites a definition verbatim (raw content is canonical) and returns it with parsed Meta. An empty scope defaults to user. An invalid name or unsupported scope is APIError{400}, matching PUT /subagents/{name}.

func (*Prompts) Subagent

func (p *Prompts) Subagent(scope MemoryScope, dir, name string, opts ...ScopedOption) (Subagent, error)

Subagent returns one definition's full raw Content plus parsed Meta. An empty scope defaults to user. A missing definition maps to APIError{404}; an invalid name or unsupported scope to APIError{400}, matching GET /subagents/{name}.

func (*Prompts) Subagents

func (p *Prompts) Subagents(dir string, opts ...ScopedOption) ([]Subagent, error)

Subagents returns the scoped agent's persistent subagent definitions across every supported scope (Claude: project + user). Raw Content is omitted here (fetch it with Subagent); parsed Meta is kept. A missing definitions directory yields an empty list, not an error; any other failure is APIError{500}, matching GET /subagents. An agent without the module is APIError{400}. Distinct from a turn's per-turn Options.Subagents passthrough — this is the on-disk definition store.

type Protocol

type Protocol = agent.Protocol

Capabilities + the dynamic settings schema.

type Providers

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

Providers is the custom-LLM-provider sub-API, reachable as Client.Providers. It registers, lists, and removes the custom OpenAI-compatible endpoints an agent loads on every run from its own native config — opencode's opencode.json `provider.<id>` block and Codex's config.toml `[model_providers.<id>]` tables. Each call maps one-for-one to a /providers HTTP route and enforces the same gates: an agent without the underlying optional module surfaces as APIError{400}; a missing provider on Get is APIError{404}; an invalid id/base URL or unsupported scope is 400. It is scoped to its client's default agent and rebinds under WithAgent; override per call with ForAgent.

SECURITY: the API key is NEVER carried on the CustomProvider value — it is passed write-only to Set and reported only as HasKey. The harness config references it solely through an env-var placeholder; the value is stored in the daemon and enters a run only through the auth env path. dir selects the project-scope working directory — empty resolves to the client's cwd (else the process cwd).

func (*Providers) Delete

func (p *Providers) Delete(scope MemoryScope, dir, id string, opts ...ScopedOption) error

Delete removes one provider at a scope and clears its stored key. An empty scope defaults to user. Deleting an absent provider (or from a missing config) is not an error (idempotent), matching DELETE /providers/{id}. An unsupported scope is APIError{400}.

func (*Providers) Get

func (p *Providers) Get(scope MemoryScope, dir, id string, opts ...ScopedOption) (CustomProvider, error)

Get returns one provider by id at a scope. An empty scope defaults to user. A provider that isn't configured maps to APIError{404}; an unsupported scope to APIError{400}, matching GET /providers/{id}. The key is never returned (only HasKey).

func (*Providers) List

func (p *Providers) List(dir string, opts ...ScopedOption) (map[MemoryScope]map[string]CustomProvider, error)

List returns the scoped agent's registered custom providers across every supported scope (opencode / Codex: user only), keyed scope→id→provider. A missing config file yields an empty map for that scope, not an error; any other failure is APIError{500}, matching GET /providers. An agent without the module is APIError{400}. HasKey reports whether a secret is stored; the key is never returned.

func (*Providers) Set

func (p *Providers) Set(scope MemoryScope, dir, id string, prov CustomProvider, apiKey string, secrets map[string]string, opts ...ScopedOption) (CustomProvider, error)

Set registers one provider at a scope and returns the stored provider (re-read so HasKey and the derived EnvVar reflect the authoritative state). An empty scope defaults to user. The path id wins over any id in prov. Two write-only secret channels, both optional: apiKey is a single key (custom endpoints, single-key catalog brands); secrets is a NAME→VALUE map for catalog providers whose entry declares MULTIPLE env vars (e.g. AWS Bedrock's key/secret/region). Passing neither leaves any previously stored secret intact. An invalid id/base URL or unsupported scope is APIError{400}, matching PUT /providers/{id}.

type Question

type Question = agent.Question

Mid-turn interactions the agent surfaces (a question, a plan to approve, todo progress).

type QuestionAnswer

type QuestionAnswer = agent.QuestionAnswer

Mid-turn interactions the agent surfaces (a question, a plan to approve, todo progress).

type ResolveRequest

type ResolveRequest struct {
	RequestID     string
	ChatID        string
	Message       string
	CWD           string
	Options       TurnOptions
	Agent         string
	MaxIterations int
	Deadline      time.Duration
}

ResolveRequest is the input to Resolve — the same shape as TurnRequest plus the resolve bounds. MaxIterations caps the auto-continued iterations before the run ends with StopReason "capped"; Deadline is the overall wall-clock budget for the whole resolve. Both are optional: a zero value falls back to the daemon defaults.

type RespondInput

type RespondInput = InteractionResponse

RespondInput answers a mid-turn interaction: the interaction id, the chosen decision (allow/deny, approve/reject, or a single option id), any multi-select option ids, and free text.

type ResultInfo

type ResultInfo = agent.ResultInfo

Streaming events (the unified turn stream). See Run.Stream.

type Run

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

Run is a handle to one turn: its durable record plus the control + streaming operations bound to it. Turn, Run, and LatestRun return one. It carries a snapshot of the record (Refresh re-reads it); the control methods and Stream always act on the live supervisor state for the run id.

func (*Run) Agent

func (r *Run) Agent() string

Agent is the agent type that executed the run.

func (*Run) Cancel

func (r *Run) Cancel() error

Cancel hard-stops the turn (kills the CLI). APIError{400} if the agent doesn't support cancellation; APIError{404} if no turn is currently running for this id.

func (*Run) ChatID

func (r *Run) ChatID() string

ChatID is the chat this run belongs to.

func (*Run) Children

func (r *Run) Children() ([]*Run, error)

Children returns handles to this run's child iterations, oldest→newest — the per-iteration turns of a global-resolve run (see Client.Resolve). An ordinary turn returns an empty slice. Convenience for Client.Children(r.ID()).

func (*Run) EndVoice

func (r *Run) EndVoice(clientID string) error

EndVoice stops the microphone conversation while any coding work continues.

func (*Run) ID

func (r *Run) ID() string

ID is the run id.

func (*Run) Interrupt

func (r *Run) Interrupt() error

Interrupt soft-stops the current action while keeping the turn open for a follow-up (softer than Cancel). APIError{400} if unsupported; APIError{404} if no turn is accepting input.

func (*Run) Refresh

func (r *Run) Refresh() (RunRecord, error)

Refresh re-reads the run's durable record from the store, updates this handle's snapshot, and returns it. APIError{404} if the run no longer exists.

func (*Run) Respond

func (r *Run) Respond(in RespondInput) error

Respond answers a permission, question or plan. Native controls require a pending live request. Message-mode questions remain answerable after completion: the daemon steers the active turn or starts a resumed turn (obtain it through LatestRun). APIError{400} indicates an invalid answer; {409} indicates a stale or concurrent reply.

func (*Run) SendInput

func (r *Run) SendInput(text string, opts ...InputOptions) error

SendInput submits a follow-up without cancelling the run. Codex and Claude consume it on their native schedule. Use Client.Turn with QueueIfRunning to also start a new turn if this run has already finished.

func (*Run) SetModel

func (r *Run) SetModel(model string) error

SetModel switches the model of a live turn (empty resets to the agent/CLI default). Best-effort: only a persistent transport consumes it. APIError{400} if unsupported; APIError{404} if no turn is accepting input.

func (*Run) SetPermissionMode

func (r *Run) SetPermissionMode(mode string) error

SetPermissionMode switches a live turn's permission mode and waits for the native harness to acknowledge it. An unsupported mode, rejected change, or turn no longer accepting input returns an APIError instead of silently accepting the change.

func (*Run) Snapshot

func (r *Run) Snapshot() (RunSnapshot, error)

Snapshot restores the current ordered output without replaying it. Follow new output with Stream(ctx, WithAfterSequence(snapshot.Sequence)). Stopped output remains available.

func (*Run) Status

func (r *Run) Status() string

Status is the run's status as of the last snapshot ("running" | "done" | "error" | "cancelled"). Call Refresh to re-read it.

func (*Run) Stream

func (r *Run) Stream(ctx context.Context, opts ...StreamOption) iter.Seq[Event]

Stream yields the run's unified events as an iter.Seq: the replay buffer first, then live events until the run's topic closes (turn end), ctx is cancelled, or the consumer breaks. The underlying subscription is ALWAYS released when the range ends — the "must call cancel" footgun is hidden here.

ctx cancels the READ, not the turn: turns run on the supervisor's detached context, so breaking or cancelling stops your consumption while the turn keeps running (identical to the TS signal). Use Cancel to actually stop the turn.

func (*Run) Subscribe

func (r *Run) Subscribe() (replay []Event, ch <-chan Event, done bool, cancel func())

Subscribe is the low-level primitive Stream is built on: the replay buffer, a live channel, a done flag (true when the run already finished — just drain replay), and a cancel func the caller MUST invoke. Prefer Stream; reach for this only to multiplex a run's events with other channels in a select.

func (*Run) Value

func (r *Run) Value() RunRecord

Value returns the run's durable record as of the last snapshot.

func (*Run) VoiceAudio

func (r *Run) VoiceAudio(ctx context.Context, clientID string, sequence int64, audio VoiceAudio) error

VoiceAudio sends an ordered PCM batch to a run started with Options.Voice.

func (*Run) VoiceEvents

func (r *Run) VoiceEvents(ctx context.Context, clientID string) iter.Seq2[VoiceEvent, error]

VoiceEvents has no audio replay buffer. Subscribe before sending microphone audio. Ending iteration releases voice access without cancelling coding work.

func (*Run) Wait

func (r *Run) Wait(ctx context.Context, opts ...WaitOption) (WaitResult, error)

Wait drains the run's stream to completion (capturing the final result and any error event), refreshes the record, and returns it. By default a run that ends in a state other than "done" yields a *RunFailedError (with the WaitResult still populated); NoErrorOnFailure suppresses that. If ctx is cancelled first, Wait returns the current record and ctx.Err() — the turn keeps running.

Example

Wait returns a *RunFailedError when a turn ends in a non-"done" terminal state; branch on it with errors.As, or pass NoErrorOnFailure to inspect WaitResult.Run.Status yourself.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	mindwire "github.com/oblien/mindwire/packages/daemon/sdk"
)

func main() {
	client, err := mindwire.New(mindwire.Options{Agent: "claude-code"})
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	run, err := client.Turn(context.Background(), mindwire.TurnRequest{ChatID: "chat-1", Message: "hi"})
	if err != nil {
		log.Fatal(err)
	}
	res, err := run.Wait(context.Background())
	var failed *mindwire.RunFailedError
	switch {
	case err == nil:
		fmt.Println("done:", res.Result.Text)
	case errors.As(err, &failed):
		fmt.Println("turn failed:", failed.Detail)
	default:
		log.Fatal(err)
	}
}

type RunFailedError

type RunFailedError struct {
	RunID  string
	Status string // "error" | "cancelled"
	Detail string
}

RunFailedError is returned by Run.Wait when a run reaches a terminal state other than "done" (i.e. "error" or "cancelled"), unless the caller passed NoErrorOnFailure. Wait still returns the WaitResult alongside it, so a caller that wants the record can read both.

func (*RunFailedError) Error

func (e *RunFailedError) Error() string

type RunRecord

type RunRecord = session.Run

RunRecord is the durable, persisted turn record (id/chat/agent/status/…). A live Run handle wraps one; Run.Value / Run.Refresh return it.

type RunSnapshot

type RunSnapshot = orchestrator.RunSnapshot

Streaming events (the unified turn stream). See Run.Stream.

type SavedDesktop

type SavedDesktop = surface.SavedDesktop

type Scope

type Scope = agent.Scope

Capabilities + the dynamic settings schema.

type ScopedOption

type ScopedOption func(*scope)

ScopedOption tunes an agent-scoped call. The only option today is ForAgent.

func ForAgent

func ForAgent(agentType string) ScopedOption

ForAgent overrides the target agent type for a single scoped call, ignoring the client's default.

type SearchQuery

type SearchQuery = agent.SearchQuery

Deep tool normalization: the structured `Action` carried on both a streaming ToolEvent and a transcript ToolPart. Only the sub-object matching Kind is populated. See agent/toolaction.go.

type Section

type Section = agent.Section

Capabilities + the dynamic settings schema.

type SessionActivity

type SessionActivity = agent.SessionActivity

type SettingsSchema

type SettingsSchema = agent.SettingsSchema

Capabilities + the dynamic settings schema.

type SetupStatus

type SetupStatus = setup.Status

Durable records + setup/health reports.

type ShellCommand

type ShellCommand = agent.ShellCommand

Deep tool normalization: the structured `Action` carried on both a streaming ToolEvent and a transcript ToolPart. Only the sub-object matching Kind is populated. See agent/toolaction.go.

type Stats

type Stats struct {
	OS            string `json:"os"`
	Arch          string `json:"arch"`
	GoVersion     string `json:"goVersion"`
	NumCPU        int    `json:"numCpu"`
	NumGoroutine  int    `json:"numGoroutine"`
	MemAllocBytes uint64 `json:"memAllocBytes"`
	MemSysBytes   uint64 `json:"memSysBytes"`
	NumGC         uint32 `json:"numGc"`
	UptimeSeconds int64  `json:"uptimeSeconds"`
}

Stats is a cheap, on-demand snapshot of the daemon *process itself* — its Go runtime memory and scheduler counters, not machine-wide RAM/CPU (which pure stdlib can't read portably). It mirrors GET /stats and is meant to be read when someone's actually looking, never polled.

type StepResult

type StepResult = setup.StepResult

Durable records + setup/health reports.

type StreamOption

type StreamOption func(*streamConfig)

StreamOption tunes Stream.

func WithAfterSequence

func WithAfterSequence(sequence int64) StreamOption

WithAfterSequence subscribes only to events newer than a snapshot/event cursor.

func WithOpenSentinel

func WithOpenSentinel() StreamOption

WithOpenSentinel prepends a synthetic {type:"status", meta:{"stream":"open"}} event, reproducing the immediate open frame the SSE endpoint flushes before replay. Off by default (the raw hub stream has no such frame), matching the TS SDK, which filters it out unless asked.

type Subagent

type Subagent = agent.Subagent

Persistent prompt/memory surface: the agent's memory file (CLAUDE.md / AGENTS.md) and its saved prompt templates (slash-commands / saved prompts), each addressed by a canonical MemoryScope. See Client.Prompts and agent/memory.go, agent/prompts.go.

type SubagentMeta

type SubagentMeta = agent.SubagentMeta

Persistent prompt/memory surface: the agent's memory file (CLAUDE.md / AGENTS.md) and its saved prompt templates (slash-commands / saved prompts), each addressed by a canonical MemoryScope. See Client.Prompts and agent/memory.go, agent/prompts.go.

type Support

type Support = agent.Support

Capabilities + the dynamic settings schema.

type SurfaceAction

type SurfaceAction = surface.Action

type SurfaceActionRequest

type SurfaceActionRequest = surface.ActionRequest

type SurfaceBinding

type SurfaceBinding = surface.Binding

type SurfaceCapabilities

type SurfaceCapabilities = surface.Capabilities

type SurfaceCapture

type SurfaceCapture = surface.Capture

type SurfaceControlRequest

type SurfaceControlRequest = surface.ControlRequest

type SurfaceController

type SurfaceController = surface.Controller

type SurfaceCursor

type SurfaceCursor = surface.Cursor

type SurfaceError

type SurfaceError = surface.Error

type SurfaceGeometry

type SurfaceGeometry = surface.Geometry

type SurfaceOpenRequest

type SurfaceOpenRequest = surface.OpenRequest

type SurfaceReceipt

type SurfaceReceipt = surface.Receipt

type SurfaceSession

type SurfaceSession = surface.Session

type SurfaceSnapshot

type SurfaceSnapshot = surface.Snapshot

type Surfaces

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

Surfaces is workspace scoped. All WithAgent views share the same controller.

func (*Surfaces) Action

func (*Surfaces) Artifact

func (s *Surfaces) Artifact(id string) (ArtifactContent, error)

func (*Surfaces) Bind

func (s *Surfaces) Bind(ctx context.Context, binding SurfaceBinding) (SurfaceSnapshot, error)

func (*Surfaces) BindRuntime

func (s *Surfaces) BindRuntime(binding DesktopRuntimeBinding) error

func (*Surfaces) Capture

func (s *Surfaces) Capture(ctx context.Context, id string) (SurfaceCapture, error)

func (*Surfaces) Changes

func (s *Surfaces) Changes() <-chan struct{}

func (*Surfaces) Close

func (s *Surfaces) Close(id string) error

func (*Surfaces) ConfigureLocal

func (s *Surfaces) ConfigureLocal(ctx context.Context, settings LocalDesktopSettings) (SurfaceSnapshot, error)

ConfigureLocal is an in-process owner operation. HTTP clients must instead supply the separate local control credential through the Mac CLI.

func (*Surfaces) Control

func (*Surfaces) CreateDesktop

func (s *Surfaces) CreateDesktop(ctx context.Context, request CreateSavedDesktop) (SavedDesktop, error)

func (*Surfaces) DeleteDesktop

func (s *Surfaces) DeleteDesktop(ctx context.Context, id string) (DesktopResult, error)

func (*Surfaces) EnsureProjectDesktop

func (s *Surfaces) EnsureProjectDesktop(ctx context.Context, projectID string) (SavedDesktop, error)

func (*Surfaces) ForDesktop

func (s *Surfaces) ForDesktop(id string) (*Surfaces, error)

ForDesktop scopes status/events and receipts to a saved provider desktop.

func (*Surfaces) GetDesktop

func (s *Surfaces) GetDesktop(ctx context.Context, id string) (DesktopResult, error)

func (*Surfaces) List

func (s *Surfaces) List() []SurfaceSnapshot

func (*Surfaces) ListDesktops

func (s *Surfaces) ListDesktops(ctx context.Context, projectID string) (DesktopCatalog, error)

func (*Surfaces) LocalStatus

func (s *Surfaces) LocalStatus(ctx context.Context) (LocalDesktopInfo, error)

func (*Surfaces) Open

func (*Surfaces) Receipt

func (s *Surfaces) Receipt(id string) (SurfaceReceipt, error)

func (*Surfaces) StartDesktop

func (s *Surfaces) StartDesktop(ctx context.Context, id string) (DesktopResult, error)

func (*Surfaces) Status

func (s *Surfaces) Status(ctx context.Context, refresh bool) (SurfaceSnapshot, error)

func (*Surfaces) StopDesktop

func (s *Surfaces) StopDesktop(ctx context.Context, id string) (DesktopResult, error)

func (*Surfaces) UpdateDesktop

func (s *Surfaces) UpdateDesktop(ctx context.Context, id string, update UpdateSavedDesktop) (DesktopResult, error)

type Terminal

type Terminal = workspaceexec.Terminal

type TerminalEvent

type TerminalEvent = workspaceexec.TerminalEvent

type TerminalInput

type TerminalInput = workspaceexec.TerminalInput

type TerminalRequest

type TerminalRequest = workspaceexec.TerminalRequest

type TerminalState

type TerminalState = workspaceexec.TerminalState

type Terminals

type Terminals = workspaceexec.Terminals

type TodoItem

type TodoItem = agent.TodoItem

Mid-turn interactions the agent surfaces (a question, a plan to approve, todo progress).

type ToolAction

type ToolAction = agent.ToolAction

Deep tool normalization: the structured `Action` carried on both a streaming ToolEvent and a transcript ToolPart. Only the sub-object matching Kind is populated. See agent/toolaction.go.

type ToolEvent

type ToolEvent = agent.ToolEvent

Streaming events (the unified turn stream). See Run.Stream.

type ToolKind

type ToolKind = agent.ToolKind

Deep tool normalization: the structured `Action` carried on both a streaming ToolEvent and a transcript ToolPart. Only the sub-object matching Kind is populated. See agent/toolaction.go.

type ToolPart

type ToolPart = agent.ToolPart

Chat transcript shapes.

type TurnOptions

type TurnOptions = agent.TurnOptions

Turn inputs.

type TurnRequest

type TurnRequest struct {
	RequestID      string
	QueueIfRunning bool
	ChatID         string
	Message        string
	CWD            string
	Options        TurnOptions
	Agent          string
}

TurnRequest is one turn's parameters. Agent selects the target (empty = the client default); CWD overrides the working directory for this turn only; Options carries per-turn settings, prompts, and structured passthroughs.

type UpdateSavedDesktop

type UpdateSavedDesktop = surface.UpdateDesktopRequest

type UserInput

type UserInput = agent.UserInput

Streaming events (the unified turn stream). See Run.Stream.

type VoiceAudio

type VoiceAudio = agent.VoiceAudio

Streaming events (the unified turn stream). See Run.Stream.

type VoiceCapability

type VoiceCapability = agent.VoiceCapability

Streaming events (the unified turn stream). See Run.Stream.

type VoiceEvent

type VoiceEvent = agent.VoiceEvent

Streaming events (the unified turn stream). See Run.Stream.

type VoiceOptions

type VoiceOptions = agent.VoiceOptions

Streaming events (the unified turn stream). See Run.Stream.

type VoiceStatus

type VoiceStatus = agent.VoiceStatus

Streaming events (the unified turn stream). See Run.Stream.

type WaitOption

type WaitOption func(*waitConfig)

WaitOption tunes Wait.

func NoErrorOnFailure

func NoErrorOnFailure() WaitOption

NoErrorOnFailure makes Wait return the WaitResult with a nil error even when the run ends in a non-"done" terminal state, instead of a *RunFailedError. Use it when you'd rather branch on WaitResult.Run.Status yourself.

type WaitResult

type WaitResult struct {
	Run    RunRecord
	Result *ResultInfo
}

WaitResult is the outcome of Wait: the run's final record and the turn's result summary (nil if the turn produced no result event, e.g. it was cancelled or errored before finishing).

type WebSearch

type WebSearch = agent.WebSearch

Deep tool normalization: the structured `Action` carried on both a streaming ToolEvent and a transcript ToolPart. Only the sub-object matching Kind is populated. See agent/toolaction.go.

type Workspace

type Workspace struct {
	Agents     *WorkspaceCollection[WorkspaceAgent]
	Projects   *WorkspaceCollection[WorkspaceProject]
	Chats      *WorkspaceCollection[WorkspaceChat]
	Operations *ProjectOperations
	Sync       *ProjectSync
	// contains filtered or unexported fields
}

Workspace is workspace-wide metadata; selecting a different harness never changes its scope. Native harness configuration and transcripts remain in their existing stores.

func (*Workspace) Changes

func (w *Workspace) Changes(since int64, workspaceID string, options ...WorkspaceSyncOptions) (WorkspaceSnapshot, error)

Changes uses both fields of a prior snapshot's cursor. A replaced/restored database returns 409; recover by replacing the cache with Snapshot, never by re-importing an authoritative cache.

func (*Workspace) Conversations

func (w *Workspace) Conversations(ctx context.Context, query ConversationQuery) (ConversationPage, error)

Conversations lists native history across every folder, including folders not yet registered as projects. Browsing never changes workspace metadata.

func (*Workspace) CreateProject

func (w *Workspace) CreateProject(request ProjectRequest) (ProjectOperation, error)

CreateProject starts a daemon-owned folder import, new directory, or clone. Request.ID is a stable idempotency key; closing an observer never cancels the work.

func (*Workspace) EditLibrary

func (w *Workspace) EditLibrary(edit ProjectLibraryEdit) (ProjectLibrary, error)

func (*Workspace) EnsureAgent

func (w *Workspace) EnsureAgent(request EnsureAgentRequest) (EnsureAgentResult, error)

EnsureAgent reuses one workspace-owned profile for setup of this harness. Concurrent clients receive the same ID; existing names and chat links are kept.

func (*Workspace) Import

func (w *Workspace) Import(records WorkspaceImport) (WorkspaceSnapshot, error)

Import inserts missing legacy IDs. Existing records and tombstones always win.

func (*Workspace) Library

func (w *Workspace) Library() (ProjectLibrary, error)

func (*Workspace) OpenConversation

func (w *Workspace) OpenConversation(ctx context.Context, request ConversationOpenRequest) (ConversationOpenResult, error)

OpenConversation attaches a native reference to the normal chat protocol. The returned chat retains its original folder and native resume identity.

func (*Workspace) ProjectIcon

func (w *Workspace) ProjectIcon(projectID, path string) (ProjectIcon, error)

ProjectIcon reads a small image confined to the project's directory. An empty path uses the saved icon; an explicit relative path previews a candidate.

func (*Workspace) RemoveProjectFiles

func (w *Workspace) RemoveProjectFiles(id string, request ProjectRemoveRequest) (ProjectOperation, error)

RemoveProjectFiles deletes the confirmed project's directory and membership. Projects.Delete only removes membership and retains files/native transcripts.

func (*Workspace) SetProjectIcon

func (w *Workspace) SetProjectIcon(projectID string, path *string, expectedRevision int64) (WorkspaceSnapshot, error)

SetProjectIcon updates revisioned metadata without copying or changing project files. nil explicitly resets the icon; older Put calls that omit it preserve it.

func (*Workspace) Snapshot

func (w *Workspace) Snapshot(options ...WorkspaceSyncOptions) (WorkspaceSnapshot, error)

func (*Workspace) UploadProjectIcon

func (w *Workspace) UploadProjectIcon(projectID, name string, content []byte) (ProjectIcon, error)

UploadProjectIcon stores a validated image inside the project. Save its Path with SetProjectIcon to select it; uploading alone does not change metadata.

type WorkspaceAgent

type WorkspaceAgent = registry.Agent

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type WorkspaceChat

type WorkspaceChat = registry.Chat

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type WorkspaceCollection

type WorkspaceCollection[T any] struct {
	// contains filtered or unexported fields
}

func (*WorkspaceCollection[T]) Delete

func (collection *WorkspaceCollection[T]) Delete(id string, expected *int64) (WorkspaceSnapshot, error)

Delete removes membership and dependent chat links. Native files and transcripts are retained; use Client.DeleteChat when a transcript purge is intended. Running chats block parent deletion.

func (*WorkspaceCollection[T]) Put

func (collection *WorkspaceCollection[T]) Put(id string, record T, expected *int64) (WorkspaceSnapshot, error)

Put creates with a stable client-generated ID (expected=nil), or replaces the record only if expected matches its latest revision. Retrying an identical acknowledged write is idempotent.

type WorkspaceDeletion

type WorkspaceDeletion = registry.Deletion

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type WorkspaceExecRequest

type WorkspaceExecRequest = workspaceexec.ExecRequest

type WorkspaceExecResult

type WorkspaceExecResult = workspaceexec.ExecResult

type WorkspaceExecution

type WorkspaceExecution = workspaceexec.Service

Execution uses the exact native service behind /workspace/{host,files,exec,terminals}. All harness views share it; Close terminates its PTYs. No transport is needed in Go.

type WorkspaceFile

type WorkspaceFile = workspaceexec.File

type WorkspaceFileContent

type WorkspaceFileContent = workspaceexec.Content

type WorkspaceHost

type WorkspaceHost = workspaceexec.Info

type WorkspaceImport

type WorkspaceImport = registry.Import

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type WorkspaceProject

type WorkspaceProject = registry.Project

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type WorkspaceRecord

type WorkspaceRecord = registry.Record

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type WorkspaceSnapshot

type WorkspaceSnapshot = registry.Snapshot

Aliases keep the same records, revisions and deletion protocol across Go, HTTP, TypeScript and iOS.

type WorkspaceSyncOptions

type WorkspaceSyncOptions struct{ Refresh bool }

Jump to

Keyboard shortcuts

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