extensionsdk

package
v2.0.4 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 33 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package extensionsdk is what the code of an icebath extension is written with. A Go program, or a WebAssembly module built with GOOS=wasip1, names the function icebath runs as it loads it with Register, and that function registers tools, hooks, slash commands, widgets, prompt sections, skills, event subscriptions, services, chat apps, helper tasks, video services, job schedulers, request middlewares, language packs, redaction patterns, and through Kind any other kind icebath takes, on the Host it is handed. Through the same Host the extension asks icebath for what the grants of its manifest allow: its settings, variables, files, the web, the agent's tools and sessions of its profile, the profile's helper models, questions to the person and side questions to the agent, the tools of MCP servers, subagents, what it does in chats, and the folders sessions work in

Index

Constants

View Source
const (
	ApprovalOnce    = "once"
	ApprovalSession = "session"
	ApprovalAlways  = "always"
	ApprovalDeny    = "deny"
)

Answers a prompt takes

View Source
const (
	ApprovalCommands = "commands"
	ApprovalCode     = "code"
	ApprovalActions  = "actions"
)

Kinds of approval: the agent's risky commands, code a tool runs that reaches past the command checks, and actions a tool flagged

View Source
const (
	ApprovalElsewhere = "elsewhere"
	ApprovalExpired   = "expired"
	ApprovalWithdrawn = "withdrawn"
)

Ways a prompt the transport did not answer ended: answered elsewhere first, out of time, or withdrawn as the turn stopped

View Source
const (
	// The person answered or skipped every question
	Submitted = "submitted"
	// The person dismissed the questions
	Cancelled = "cancelled"
	// No answer came in time
	TimedOut = "timed_out"
)

How a set of questions ended

View Source
const (
	ChatButtonGo   = "go"
	ChatButtonMain = "main"
	ChatButtonStop = "stop"
)

How a button looks where the app colours its buttons: an answer that lets something go ahead, one that goes further than the others, and one that refuses or ends something; a button of none of them is plain

View Source
const (
	ChatTaskRunning = "running"
	ChatTaskDone    = "done"
	ChatTaskFailed  = "failed"
)

How a task of a card of tasks stands

View Source
const (
	ChatProgressOff     = "off"
	ChatProgressNew     = "new"
	ChatProgressAll     = "all"
	ChatProgressVerbose = "verbose"
	ChatProgressLog     = "log"
)

What the chats of an app are shown of the tools a reply runs: nothing, a line each time the agent goes on to another tool, a line for every call, each call with its arguments, or nothing in the chat and every call in the log of the profile

View Source
const (
	ChatTierHigh    = "high"
	ChatTierMedium  = "medium"
	ChatTierLow     = "low"
	ChatTierMinimal = "minimal"
)

Tiers of the defaults of how the chats of an app show the work on a reply, from the most shown to the least

View Source
const (
	ChatDisplayProgress       = "tool_progress"
	ChatDisplayGrouping       = "tool_progress_grouping"
	ChatDisplayCleanup        = "cleanup_progress"
	ChatDisplayPreview        = "tool_preview_length"
	ChatDisplayStreaming      = "streaming"
	ChatDisplayInterim        = "interim_assistant_messages"
	ChatDisplayLongRunning    = "long_running_notifications"
	ChatDisplayBusyDetail     = "busy_ack_detail"
	ChatDisplaySteerAck       = "busy_steer_ack_enabled"
	ChatDisplayReasoning      = "show_reasoning"
	ChatDisplayReasoningStyle = "reasoning_style"
	ChatDisplayThinking       = "thinking_progress"
	ChatDisplayFriendly       = "friendly_tool_labels"
	ChatDisplayLiveStatus     = "live_status"
	ChatDisplayQuietWarnings  = "suppress_warning_notifications"
	ChatDisplayFooter         = "runtime_footer"
	ChatDisplayFooterFields   = "runtime_footer_fields"
	ChatDisplayTyping         = "typing_indicator"
	ChatDisplayTypingText     = "typing_status_text"
)

Settings of how the chats of an app show the work on a reply, by the leaf of each key, which the Display of a ChatApp gives defaults of: what shows of the tools at work (one of the ChatProgress values), whether their lines build up in one message (accumulate) or go apart (separate), whether they are taken away once the reply ended, the most characters of what a tool works on that show (a whole number), whether replies show live, whether what the agent writes on the way to its answer shows, the notice that a long reply runs (on, generic or off), what the answer to a message sent meanwhile says of the work, whether a message that steers the reply is answered, whether the model's thinking shows above an answer and how (code, blockquote or subtext), whether its thinking shows among the lines of the tools, whether tools are named by their titles, the line that says what the bot does (full, verb or off), whether warnings stay out of the chat, the line under each answer with its fields (model, served_model, context_pct, latency and cwd), whether the chat is shown the agent writes, and the words an app with Words shows while the agent thinks

View Source
const (
	ChatRoleAnswer   = "answer"
	ChatRoleInterim  = "interim"
	ChatRoleProgress = "progress"
)

What a message icebath posts is of the session's doing, as the Role of a ChatOutgoing says: the agent's answer, from the first post of a reply that grows, what it wrote on the way to one, the lines of the tools at work and a card of tasks shown as text, and something told beside the reply when empty

How far the work on a reply a chat hears got: the bot began it, it takes more than writing, or it ended

How a chat app shows text: Markdown as it is written, text without marks, the marks of a page, stars for bold with underscores for italic, Markdown with its tables set in blocks of code, Slack's marks, or Markdown as Discord shows it, with a line of small type after -#

How a chat app counts the characters of a message toward its limit: each as one, in UTF-16 units as Telegram does, or in bytes

View Source
const (
	// Same on every turn of every session
	TierStable = protocolv1.Tier_TIER_STABLE
	// Of the session's working folder
	TierProject = protocolv1.Tier_TIER_PROJECT
	// What the agent keeps across sessions and changes as it works
	TierKept = protocolv1.Tier_TIER_KEPT
	// Of the moment the prompt is built
	TierTurn = protocolv1.Tier_TIER_TURN
)
View Source
const (
	WireChatCompletions   = "chat_completions"
	WireAnthropicMessages = "anthropic_messages"
	WireCodexResponses    = "codex_responses"
	WireGeminiNative      = "gemini_native"
	WireBedrockConverse   = "bedrock_converse"
	WireExtension         = "extension"
)

Wires a provider's requests go out over, as icebath names them; WireExtension for requests the extension carries itself with Stream

View Source
const (
	AuthAPIKey = "api_key"
	AuthNone   = "none"
	AuthSignIn = "sign_in"
)

How the accounts of a provider sign in: with an API key, the default; with none, as a server of this computer takes none; or with a sign-in an extension brings, as a SignInMethod naming the provider gives

View Source
const (
	EventText      = "text"
	EventReasoning = "reasoning"
	EventToolStart = "tool_start"
	EventStatus    = "status"
	EventWait      = "wait"
	EventActivity  = "activity"
)

Kinds of the parts of a reply as it streams: its text, its reasoning, the start of a tool call with the tool's name, a line the person is shown, a line shown in place while the request waits, and activity that shows nothing but keeps the request alive

View Source
const (
	TaskSystem    = "system"
	TaskUser      = "user"
	TaskAssistant = "assistant"
)

Who says a message of a call of a helper task

View Source
const (
	// Beside the window
	ModeAmbient = protocolv1.Mode_MODE_AMBIENT
	// Over the windows, taking every key
	ModeModal = protocolv1.Mode_MODE_MODAL
)
View Source
const Protocol = wire.Version

Version of the protocol this library speaks

Variables

View Source
var ErrChatNoCard = errors.New("This chat has no place for a card of tasks.")

What Tasks returns for a chat it has no place for a card of tasks in, such as a chat outside a thread

View Source
var ErrChatTalkCut = errors.New("Someone talked over the reply, so the rest of it was not read aloud.")

What the Write of a ChatTalk returns once someone talked over the reply, so icebath reads the rest of it aloud no more

View Source
var ErrManagerLocked = errors.New("The password manager is locked.")

What a password manager answers for a session that ended or never began, which locks it again until the person unlocks it

Functions

func Denied

func Denied(err error) bool

Whether icebath refused what the extension asked because the grants of its manifest do not allow it, so asking again does no good

func Limited

func Limited(err error) bool

Whether icebath refused what the extension asked because it asked it more often, or more at once, than icebath answers it, so asking again a little later may do

func Main

func Main()

Serves icebath on the standard input and output until icebath closes them or asks the program to end, then unloads the extension and exits. What the extension prints goes to its standard error, which icebath writes to the extension's log

func Register

func Register(fn func(Host) error)

Names the function icebath runs as it loads the extension, which registers what the extension adds. Call it from an init function, which a module runs too, and call Main from main

func Unavailable

func Unavailable(err error) bool

Whether nothing can answer what the extension asked now, such as a question in a session nobody watches, so asking again may do once that changed

func Unknown

func Unknown(err error) bool

Whether icebath serves no such request, such as an icebath older than the extensionsdk the extension was built with, so the extension goes on without it

Types

type Action

type Action string

What a hook does with what fired it

const (
	Block    Action = "block"
	Modify   Action = "modify"
	Approve  Action = "approve"
	Continue Action = "continue"
)

type Answers

type Answers struct {
	// The picked choices or the typed text by question id, none for a question skipped; no entry for a question never answered
	Values map[string][]string
	// Submitted, Cancelled or TimedOut, the answers locked before kept either way
	Outcome string
}

How the person answered a set of questions

type ApprovalAnswer

type ApprovalAnswer struct {
	Choice string
	By     string
	Reason string
}

What a person answered: one of the prompt's choices, who answered as the extension knows them, such as a name or an address, and what they said denying it

type ApprovalChoice

type ApprovalChoice struct {
	Value string
	Label string
}

One answer a prompt takes: its value, one of the ApprovalOnce, ApprovalSession, ApprovalAlways and ApprovalDeny, and the words shown for it

type ApprovalEdit

type ApprovalEdit struct {
	Path          string
	Before, After *string
}

A change to a file an action makes: what it holds before, nil for a file not there, and what it would hold, nil for one that goes

type ApprovalPrompt

type ApprovalPrompt struct {
	ID string
	// Heading of a prompt that is no approval of a command, empty for the usual one; what would run or change; what it was flagged as
	Title       string
	Command     string
	Description string
	// Names a lasting answer is remembered under
	Keys []string
	// ApprovalCommands, ApprovalCode or ApprovalActions
	Kind string
	// Answers it takes, deny last, each with the words shown for it
	Choices []ApprovalChoice
	// When it stops waiting and counts as denied
	Deadline time.Time
	// The smart reviewer judged it dangerous, so allowing it overrides that verdict
	SmartDenied bool
	// Changes to files the action makes, none for an action that changes no file
	Edits []ApprovalEdit
	// Session it is asked in, its profile, and where the session runs, such as tui or telegram
	Session string
	Profile string
	Source  string
	// contains filtered or unexported fields
}

A prompt to show a person, with everything the session shows of it

type ApprovalSettlement

type ApprovalSettlement struct {
	How    string
	Choice string
	Where  string
}

What became of a prompt the transport did not answer: ApprovalElsewhere, with the answer given and where, ApprovalExpired, or ApprovalWithdrawn

type ApprovalTransport

type ApprovalTransport struct {
	// Value of the channel setting that picks it, in lower case, what a person calls it, and what it is, for the picker
	Name  string
	Title string
	About string
	// Shows the prompt to a person and waits for their answer, until ctx ends at the prompt's deadline or once it was answered elsewhere
	Present func(ctx context.Context, prompt ApprovalPrompt) (ApprovalAnswer, error)
	// Takes back what was shown of a prompt the transport did not answer; nil for a transport with nothing to take back
	Settled func(ctx context.Context, prompt ApprovalPrompt, settlement ApprovalSettlement) error
}

Way approval prompts reach a person and their answers come back, such as a push notification, a pager or a company's approval system, which a person picks as the channel of approvals in /approvals: in place of the session, or beside it with the first answer taken, and alone where nobody watches, such as a scheduled job whose setting is Ask the channel. A prompt comes with everything the session shows of it, and Present answers it with one of its choices and who answered. icebath takes an answer only for the prompt it was asked for, among its choices and before its deadline; it hands the channel only the kinds of approval the person lets through it, and an answer that lasts past that one time only where the person allows it. It can't tell whether a person or the extension itself gave an answer, so the manifest grants the kind approvals, which the person agrees to as the extension installs:

grants:
  kinds: [approvals]
  net: [approve.example]
needs: [APPROVE_TOKEN]

A prompt answered elsewhere first, out of time, or withdrawn as the turn stopped ends Present's context, and Settled is told which so the extension takes back what it showed. A whole extension that asks a company's approval service and waits for its answer:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		call := func(ctx context.Context, method, path string, body, out any) error {
			token, _, _ := host.Env(ctx, "APPROVE_TOKEN")
			data, _ := json.Marshal(body)
			response, err := host.Fetch(ctx, extensionsdk.Request{Method: method, URL: "https://approve.example" + path,
				Headers: map[string]string{"Authorization": "Bearer " + token}, Body: data})
			if err != nil {
				return err
			}
			if out == nil {
				return nil
			}
			return json.Unmarshal(response.Body, out)
		}
		_, err := host.Register(extensionsdk.ApprovalTransport{
			Name: "approve", Title: "Approve", About: "Asks the approvers of your company",
			Present: func(ctx context.Context, prompt extensionsdk.ApprovalPrompt) (extensionsdk.ApprovalAnswer, error) {
				if err := call(ctx, "POST", "/requests", map[string]any{"id": prompt.ID, "title": prompt.Command,
					"detail": prompt.Description, "choices": prompt.Choices, "until": prompt.Deadline}, nil); err != nil {
					return extensionsdk.ApprovalAnswer{}, err
				}
				for {
					var state struct{ Choice, Approver, Note string }
					if err := call(ctx, "GET", "/requests/"+prompt.ID+"?wait=30", nil, &state); err != nil {
						return extensionsdk.ApprovalAnswer{}, err
					}
					if state.Choice != "" {
						return extensionsdk.ApprovalAnswer{Choice: state.Choice, By: state.Approver, Reason: state.Note}, nil
					}
				}
			},
			Settled: func(ctx context.Context, prompt extensionsdk.ApprovalPrompt, settlement extensionsdk.ApprovalSettlement) error {
				return call(ctx, "DELETE", "/requests/"+prompt.ID, nil, nil)
			},
		})
		return err
	})
}

func main() { extensionsdk.Main() }

type AuxiliaryTask

type AuxiliaryTask struct {
	// Name its settings are kept under, auxiliary.<name>: lower case letters, digits, dashes and underscores, and no name of icebath's own
	// jobs or of another extension's
	Name  string
	Title string
	About string
	// Place of its settings among the helper models, lowest first; after icebath's own when zero
	Order int
	// How long a call may go without output when its time limit is not set, 30 seconds when zero; and the least a call gets whatever the
	// limit says
	Timeout, MinTimeout time.Duration
	// Job whose settings it takes for those it leaves unset, one of icebath's or another of the extension's
	Inherit string
	// It needs a model that sees images; a call that used its whole time falls back at once rather than trying the same provider again
	Vision, Critical bool
	// What its settings hold until the person sets them: how hard the model thinks (none, low, medium or high), a provider of the profile by
	// name, one of its models, and request fields as they are sent
	Effort, Provider, Model string
	Extra                   map[string]any
}

Side job of the extension that runs on a helper model of the profile, its settings under Helper models as icebath's own jobs have them: provider, model, effort, time limit, fallbacks and the rest. The extension runs it with Host.RunTask and never holds a key of a provider; running it spends the tokens of the profile's providers, so the manifest grants the request models, which the person agrees to as the extension installs:

grants:
  requests: [models]

The task's settings are listed while the extension runs and kept while it does not. A whole extension whose command sorts an issue:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		if _, err := host.Register(extensionsdk.AuxiliaryTask{Name: "triage", Title: "Issue triage",
			About: "Sorts issues into bug, feature or question", Effort: "none", Timeout: 20 * time.Second}); err != nil {
			return err
		}
		_, err := host.Register(extensionsdk.Command{Name: "triage", Usage: "<issue>", Help: "Sort an issue",
			Handler: func(ctx context.Context, call extensionsdk.CommandCall) (string, error) {
				reply, err := host.RunTask(ctx, "triage", extensionsdk.TaskCall{SessionID: call.SessionID,
					Messages: []extensionsdk.TaskMessage{
						{Role: extensionsdk.TaskSystem, Text: "Answer bug, feature or question, the word alone."},
						{Text: call.Argument},
					}, MaxTokens: 8})
				if err != nil {
					return "", err
				}
				return "This reads as a " + strings.TrimSpace(reply.Text) + ".", nil
			}})
		return err
	})
}

func main() { extensionsdk.Main() }

type Browser

type Browser struct {
	// Value of the browser location setting that picks it, in lower case, what a person calls it, and what it offers, for the picker
	Name  string
	Title string
	About string
	// Keys it reads, which a person sets on its page in /browser
	Keys []BrowserKey
	// Picked by its keys alone when the profile chose no place for pages, the lowest first; never when zero
	Detect int
	// What a person pays for its browsers, whole sentences, shown beside it in /browser; empty for nothing said
	Cost string
	// Opens a browser for the task, answering it with its DevTools address, and closes the browser of an id, whether it closed
	Create func(ctx context.Context, task string) (*BrowserSession, error)
	Close  func(ctx context.Context, id string) (bool, error)
	// Closes every browser it opened that is still open, run as the extension unloads too; nil for a service whose browsers end on their
	// own
	Cleanup func(ctx context.Context) error
	// How it stands, whether browsers can open there now and the address a person watches its browser at, such as the live view of the
	// session open now; nil for one that is ready whenever its keys are set
	State func(ctx context.Context) (BrowserState, error)
	// Browsers left open on its service that outlive icebath, for an uninstall, and what closes one of them; both nil for a service that
	// leaves none
	Left   func(ctx context.Context) ([]BrowserLeftover, error)
	Remove func(ctx context.Context, id string) error
	// For a browser that holds pages of its own, in place of Create and Close: whether it holds a live page for the task, never opening
	// one, and the value of a script run on that page, any value encoding/json writes. Secret says the script carries a secret, such as a
	// saved password the vault fills
	Has      func(ctx context.Context, task string) (bool, error)
	Evaluate func(ctx context.Context, task, script string, secret bool) (any, error)
}

Browsers the agent drives, which a person picks in /browser as the place web pages open: a hosted browser service whose sessions the browser tools drive over the DevTools protocol (Create and Close), or a browser that holds pages of its own (Has and Evaluate), such as one with tools of its own. Running the agent's browsers sees every page it opens and what is typed into them, so the manifest grants the kind browser, which the person agrees to as the extension installs:

grants:
  kinds: [browser]
  net: [api.hostedbrowsers.example]
needs: [HOSTED_BROWSERS_KEY]

The vault fills a saved account into a page that holds pages of its own only where the catalog lists the extension as official or verified. As the extension unloads, Cleanup closes every browser it still holds open. A whole extension:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		call := func(ctx context.Context, method, path string, out any) error {
			key, _, _ := host.Env(ctx, "HOSTED_BROWSERS_KEY")
			response, err := host.Fetch(ctx, extensionsdk.Request{Method: method, URL: "https://api.hostedbrowsers.example" + path,
				Headers: map[string]string{"Authorization": "Bearer " + key}})
			if err != nil {
				return err
			}
			if response.Status >= 300 {
				return fmt.Errorf("Hosted Browsers answered %d: %s", response.Status, response.Body)
			}
			if out == nil {
				return nil
			}
			return json.Unmarshal(response.Body, out)
		}
		_, err := host.Register(extensionsdk.Browser{
			Name: "hostedbrowsers", Title: "Hosted Browsers", About: "Cloud browsers with a live view",
			Keys: []extensionsdk.BrowserKey{{Variable: "HOSTED_BROWSERS_KEY", Prompt: "Hosted Browsers API key",
				URL: "https://hostedbrowsers.example/keys"}},
			Cost: "Browsers cost about $0.10 for each hour they run.",
			Create: func(ctx context.Context, task string) (*extensionsdk.BrowserSession, error) {
				var opened struct{ ID, WebSocket string }
				if err := call(ctx, "POST", "/sessions", &opened); err != nil {
					return nil, err
				}
				return &extensionsdk.BrowserSession{ID: opened.ID, DevTools: opened.WebSocket}, nil
			},
			Close: func(ctx context.Context, id string) (bool, error) {
				return true, call(ctx, "DELETE", "/sessions/"+id, nil)
			},
		})
		return err
	})
}

func main() { extensionsdk.Main() }

type BrowserKey

type BrowserKey struct {
	Variable string
	Prompt   string
	URL      string
	Setting  string
}

A key a browser service reads: the variable that holds it, what the person is asked it as, the address it is had at, and the key of a setting of the extension that keeps it, which the variable sets over, empty for none

type BrowserLeftover

type BrowserLeftover struct {
	ID    string
	Title string
	Where string
}

A browser left open on a service: what Remove closes it by, what it is and where

type BrowserSession

type BrowserSession struct {
	ID       string
	Name     string
	DevTools string
	Expires  time.Time
	Features map[string]bool
}

A browser opened for a task: the id it is closed by, its label in the logs, the DevTools address the browser tools drive it through, when the service ends it, zero for no set end, and what the service turned on for it, such as proxies or stealth

type BrowserState

type BrowserState struct {
	State string
	Ready bool
	Watch string
}

How a browser stands: in a few words, whether browsers can open there now, and the address a person watches it at

type ChatApp

type ChatApp struct {
	// Name its sessions record as their source and its settings sit under, in lower case, and what a person calls it
	Name  string
	Title string
	About string
	// Most a message holds, 0 for no limit, how the app counts the characters of a message toward it, and how the app shows text
	Limit  int
	Count  ChatCount
	Format ChatFormat
	// People can press choices under its messages
	Buttons bool
	// What the agent is told of writing there
	Hint string
	// Variables it needs set before it connects. An app that needs none stays off until the person turns it on, as turning it on is what
	// sets it up
	Needs []string
	// The ids of its chats hold colons, so an address names a chat whole, with no thread
	Colons bool
	// What of access it has: group chats, names people call the bot by, other bots, what an id of a person looks like, and that whoever
	// may write there at all is let in
	Groups   bool
	Mentions bool
	Bots     bool
	ID       string
	Trusted  bool
	// Connects the account and says who it is
	Connect func(ctx context.Context) (*ChatPerson, error)
	// What arrived since the last ask. It may wait for something to arrive where the extension can wait, and says how long icebath
	// waits before the next ask where it can't
	Poll func(ctx context.Context) (ChatEvents, error)
	// Posts a message and gives the ids of what was posted, and the thread the post started where it started one, such as the post of a
	// forum, which the rest of what is posted goes on in
	Send func(ctx context.Context, chat *ChatPlace, message *ChatOutgoing) (*ChatSent, error)
	// Changes a message it posted, and takes one back; nil for an app that can't
	Edit   func(ctx context.Context, chat *ChatPlace, target string, message *ChatOutgoing) error
	Delete func(ctx context.Context, chat *ChatPlace, target string) error
	// Shows that an answer is being written, with the words the profile set for an app with Words, its own when empty, and marks a
	// message with an emoji or takes the mark off; nil for an app without
	Typing func(ctx context.Context, chat *ChatPlace, words string) error
	React  func(ctx context.Context, chat *ChatPlace, target, emoji string, remove bool) error
	// Reads the bytes of a file a person sent that is named by an id; nil for an app whose files all have addresses or paths
	Fetch func(ctx context.Context, file *ChatFile) ([]byte, error)
	// Hears that the agent has nothing more to write in a chat; nil for an app that waits on no whole reply
	Finished func(ctx context.Context, chat *ChatPlace) error
	// A message there can be posted without a sound, as the silent of ChatOutgoing asks
	Silent bool
	// Starts a thread in a chat of several people, under the message of the id or on its own with none, and gives a thread another name,
	// From being the name icebath last gave it; nil for an app without threads. DirectThreads has a talk that begins in a chat of one
	// person go into a thread made for it too
	Thread        func(ctx context.Context, chat *ChatPlace, under, name string) (*ChatPlace, error)
	Rename        func(ctx context.Context, chat *ChatPlace, from, to string) error
	DirectThreads bool
	// The thread a name stands for in a chat, made when the chat has none of that name; nil for an app whose threads have no names
	Topic func(ctx context.Context, chat *ChatPlace, name string) (*ChatPlace, error)
	// What the app knows of the chat of an id, and the chats the account is in; nil for an app that tells neither
	Describe func(ctx context.Context, id string) (*ChatPlace, error)
	Chats    func(ctx context.Context) ([]*ChatPlace, error)
	// Messages written in a chat before, newest last, at most so many and only those before the message of the id, any when it is
	// empty; nil for an app that reads none
	History func(ctx context.Context, chat *ChatPlace, limit int, before string) ([]*ChatMessage, error)
	// Answers the press of a choice, the text shown to the one who pressed, empty for none; nil for an app that waits for no answer
	Acknowledge func(ctx context.Context, press *ChatPress, text string) error
	// Hears that a message that showed a reply took its last form; nil for an app that shows no message as still being written
	Settle func(ctx context.Context, chat *ChatPlace, target string) error
	// Answers a command of the app's own: what is posted in answer, and whether the command was the app's, which is then no message to
	// the agent; nil for an app without commands
	Command func(ctx context.Context, message *ChatMessage) (reply string, handled bool, err error)
	// Nobody hears a recording there, so no reply is read aloud into a file for it
	Soundless bool
	// How the name of a file the app plays as a voice message ends, ogg for Opus in Ogg, m4a or amr: icebath makes a voice message of
	// another kind into one of this kind before it is sent, where it is no longer than the longest the app plays, any length when
	// zero. Empty for an app that plays sound of any kind as a voice message, or has none
	VoiceFormat  string
	VoiceLongest time.Duration
	// Opens what plays the speech of one reply aloud to a chat, such as in a room people talk in; false while nothing plays speech for
	// the chat. Nil for an app that plays none
	Talk func(ctx context.Context, chat *ChatPlace) (ChatTalk, bool)
	// Rooms people talk in aloud, all three nil for an app without: joins the room the person is in, with what is said there arriving
	// as spoken messages of the chat, leaves the room of the chat and says whether the bot was in one, and tells of the room the bot is
	// in for the chat, nil for none
	Join  func(ctx context.Context, chat *ChatPlace, person *ChatPerson) (*ChatRoom, error)
	Leave func(ctx context.Context, chat *ChatPlace) (bool, error)
	Room  func(ctx context.Context, chat *ChatPlace) (*ChatRoom, error)
	// Hears how far the work on a reply the chat hears got, so the people listening can be let know; nil for an app that lets nobody know
	Working func(ctx context.Context, chat *ChatPlace, stage ChatWork) error
	// The marks of React are set unless the person turns them off, as the app's people are used to
	ReactionsOn bool
	// A message there can quote the message it answers, which a setting of the person's says for which messages of a reply
	Quotes bool
	// A message of a chat of several people can be shown to one person there alone: a private ChatOutgoing goes to the one its To names,
	// or as the answer to the private message its Reply names, and is posted in the chat where the app can't do either
	Private bool
	// Most buttons one message carries, no limit when zero. With Lists, more choices come as the List of a ChatOutgoing, a list a person
	// picks one of such as a select menu, whose pick comes back as a press
	MostButtons int
	Lists       bool
	// Most images one message carries, which the app shows together such as an album; every file goes alone when zero or one
	MostFiles int
	// In a chat of one person, the person's sessions are the chat's whatever thread of it, or none, they were written in
	SharedThreads bool
	// Variable of the profile that sets the most a message holds, which goes before Limit where the profile sets it
	LimitVariable string
	// Hears the commands a person may run in its chats, for its menu of commands, whenever they change; nil for an app without one. A
	// command picked there arrives as a message whose text is the command with its slash
	Menu func(ctx context.Context, commands []*ChatMenuItem) error
	// Shows the tool calls of the reply under way in a chat as a card of tasks, the whole card each time, and settles the card once the
	// reply ended; nil for an app without cards of tasks, which a person turns on in its settings
	Tasks     func(ctx context.Context, chat *ChatPlace, title string, tasks []*ChatTask) error
	TasksDone func(ctx context.Context, chat *ChatPlace) error
	// What the app asks of icebath while it is connected; nil for an app that asks nothing
	Asks *ChatAsks
	// The only emoji it takes as marks, such as the tapbacks of iMessage, which are all icebath sets and names under its prompts; any
	// emoji when none
	Marks []string
	// Tier of the defaults of how its chats show the work on a reply, one of the ChatTier values, the defaults every app has when empty;
	// and its own defaults over the tier's, each by the leaf of the setting's key, one of the ChatDisplay values, such as
	// ChatDisplayStreaming: false or ChatDisplayProgress: ChatProgressOff
	Tier    string
	Display map[string]any
	// Sets the line of a chat that says what the bot does, such as the status of a thread, as the profile's status line asks: empty text
	// takes it away; nil for an app without such a line
	Status func(ctx context.Context, chat *ChatPlace, text string) error
	// Variable of the profile that, set, lets people press the choices and pick from the lists there, such as the address the app posts
	// presses to; without it set they answer in words. Buttons and Lists for every profile when empty
	ChoicesVariable string
	// It shows words of its own while the agent thinks, such as the status of a thread: a person sets them in its settings, with a
	// default the Display gives under ChatDisplayTypingText, and Typing is handed them
	Words bool
	// Shows the person a draft of the reply being written, as it stands each time, which goes once the reply is posted; nil for an app
	// without drafts of its own
	Draft func(ctx context.Context, chat *ChatPlace, text string) error
	// Draws the Markdown of a whole reply itself where the app's markup would lose some of it, such as a table: posted, or in the place of
	// the message into, which showed the reply being written; message says what goes with it, such as the message it answers. Done and no
	// error: the app shows it. Done with an error: it may have, as when the answer to the post was lost, so nothing is shown in its place
	// now and the reply is posted whole later. Not done and no error: none of the app's to draw. Not done with an error: refused, nothing
	// shown. Nil for an app that draws no Markdown itself
	Rich func(ctx context.Context, chat *ChatPlace, into, markdown string, message *ChatOutgoing) (sent *ChatSent, done bool, err error)
	// Draws the Markdown of the reply being written in the chat's draft, whether it did; nil for an app whose drafts take text alone
	RichDraft func(ctx context.Context, chat *ChatPlace, markdown string) (bool, error)
	// Takes what the app posted over HTTP, as it arrived at the HTTP API of icebath (/api/platforms/<name>/events) or at the address of
	// Listen, and gives what icebath answers it with; nil for an app that posts nothing
	Posted func(ctx context.Context, post *ChatPost) (*ChatPosted, error)
	// Key of a setting of the extension holding an address icebath listens at for what the app posts, beside the HTTP API's own, such as
	// 0.0.0.0:8645; empty for none
	Listen string
	// The app's own sign-in at its provider, which another feature of the same organisation shares rather than keeping a second one, such
	// as the app registration of Microsoft that Microsoft Graph takes; its variables are read only when the manifest names them
	SignIn *ChatSignIn
	// Ends the connection; nil for one that holds nothing
	Close func(ctx context.Context) error
}

Chat app people write to the agent on, for an app icebath has no adapter of its own for. icebath connects it once for each profile that turns it on, asks it over and over what arrived, and has it post what the agent answers. A chat app reads every reply the agent writes there and says who wrote each message, which decides who the agent answers, so the manifest grants the kind chats, which the person agrees to as the extension installs:

grants:
  kinds: [chats]
  net: [api.pigeonpost.example]
needs: [PIGEON_TOKEN]

A connection that fails, or whose extension stops, is made again after a wait, by a new process of the extension where the old one ended. A whole extension, which waits for what arrives for up to a minute at a time and posts the agent's answers:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		token := func(ctx context.Context) string {
			value, _, _ := host.Env(ctx, "PIGEON_TOKEN")
			return value
		}
		call := func(ctx context.Context, method, path string, body any, out any) error {
			data, err := json.Marshal(body)
			if err != nil {
				return err
			}
			response, err := host.Fetch(ctx, extensionsdk.Request{Method: method, URL: "https://api.pigeonpost.example" + path,
				Headers: map[string]string{"Authorization": "Bearer " + token(ctx)}, Body: data, Timeout: 90 * time.Second})
			if err != nil {
				return err
			}
			if response.Status >= 300 {
				return fmt.Errorf("Pigeon Post answered %d: %s", response.Status, response.Body)
			}
			return json.Unmarshal(response.Body, out)
		}
		_, err := host.Register(extensionsdk.ChatApp{
			Name: "pigeonpost", Title: "Pigeon Post", About: "Letters carried by pigeons", Limit: 4000, Groups: true,
			Needs: []string{"PIGEON_TOKEN"},
			Connect: func(ctx context.Context) (*extensionsdk.ChatPerson, error) {
				var me struct{ ID, Name string }
				if err := call(ctx, "GET", "/me", nil, &me); err != nil {
					return nil, err
				}
				return &extensionsdk.ChatPerson{Id: me.ID, Name: me.Name}, nil
			},
			Poll: func(ctx context.Context) (extensionsdk.ChatEvents, error) {
				var letters []struct{ ID, Chat, From, Name, Text string }
				if err := call(ctx, "GET", "/letters?wait=60", nil, &letters); err != nil {
					return extensionsdk.ChatEvents{}, err
				}
				var out extensionsdk.ChatEvents
				for _, l := range letters {
					out.Messages = append(out.Messages, &extensionsdk.ChatMessage{Id: l.ID, Text: l.Text,
						Chat: &extensionsdk.ChatPlace{Id: l.Chat, Kind: "dm"}, From: &extensionsdk.ChatPerson{Id: l.From, Name: l.Name}})
				}
				return out, nil
			},
			Send: func(ctx context.Context, chat *extensionsdk.ChatPlace, message *extensionsdk.ChatOutgoing) (*extensionsdk.ChatSent, error) {
				var sent struct{ ID string }
				if err := call(ctx, "POST", "/letters", map[string]string{"chat": chat.GetId(), "text": message.GetText()}, &sent); err != nil {
					return nil, err
				}
				return &extensionsdk.ChatSent{Ids: []string{sent.ID}}, nil
			},
		})
		return err
	})
}

func main() { extensionsdk.Main() }

type ChatAsks

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

What a chat app asks of icebath while it is connected: whether the profile lets a person in a chat, and the sessions a person may take up in a chat as /resume would list them there. A ChatApp with Asks set takes each question with the answer to icebath's next ask of what arrived, ending a Poll that waits for something early for it, and hands the answer over with the ask after. Ask from any goroutine while the app is connected

func (*ChatAsks) Lets

func (q *ChatAsks) Lets(ctx context.Context, chat *ChatPlace, person *ChatPerson) (bool, error)

Whether the profile lets the person talk to the agent in the chat, as icebath weighs a message of theirs there, with nothing kept, counted or said: what an app asks before it does something for a person outside a message, such as taking up an invitation

func (*ChatAsks) Resumable

func (q *ChatAsks) Resumable(ctx context.Context, chat *ChatPlace, person *ChatPerson) ([]*ChatResumable, error)

The sessions the person may take up in the chat, the one written in last first, as /resume would list them there, for an app that lists them its own way

type ChatCount

type ChatCount = protocolv1.ChatCount

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatEvents

type ChatEvents struct {
	Messages []*ChatMessage
	// How long icebath waits before it asks again, none for at once, as after an ask that itself waited for something to arrive
	Wait time.Duration
	// The connection fell and does not come back on its own: why, and how long no try mends it, icebath's usual wait when zero
	Lost  string
	Retry time.Duration
	// What the connection needs of the person, such as a code to type on their phone; a space alone for nothing more
	Tell string
	// Chats whose room closed by itself since the last ask, such as after nobody spoke there for long
	Hung []*ChatPlace
	// Chats a person opened without writing, such as a thread of the app's own they started with the bot, whose session icebath readies
	// for what they write next
	Opened []*ChatOpened
}

What arrived on a chat app since icebath last asked

type ChatFile

type ChatFile = protocolv1.ChatFile

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatFormat

type ChatFormat = protocolv1.ChatFormat

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatLater

type ChatLater struct {
	Err  error
	Wait time.Duration
}

A failure of a chat app that no try mends for a while, such as an account the app banned for some hours: Connect returns it for a connection the app refused, and Poll for one that fell, and icebath tries again once the wait is over

func (*ChatLater) Error

func (l *ChatLater) Error() string

func (*ChatLater) Unwrap

func (l *ChatLater) Unwrap() error

type ChatMention

type ChatMention = protocolv1.ChatMention

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatMenuItem

type ChatMenuItem = protocolv1.ChatMenuItem

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatMessage

type ChatMessage = protocolv1.ChatMessage

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatOpened

type ChatOpened = protocolv1.ChatOpened

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatOutgoing

type ChatOutgoing = protocolv1.ChatOutgoing

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatPerson

type ChatPerson = protocolv1.ChatPerson

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatPlace

type ChatPlace = protocolv1.ChatPlace

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatPost

type ChatPost = protocolv1.ChatPost

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatPosted

type ChatPosted = protocolv1.ChatPosted

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatPress

type ChatPress = protocolv1.ChatPress

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatReaction

type ChatReaction = protocolv1.ChatReaction

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatResumable

type ChatResumable = protocolv1.ChatResumable

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatRoom

type ChatRoom = protocolv1.ChatRoom

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatSent

type ChatSent = protocolv1.ChatSent

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatSignIn

type ChatSignIn = protocolv1.ChatSignIn

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatTalk

type ChatTalk interface {
	Clip(format string, rate int) error
	Write(data []byte) error
	// Ends the speech once it played, or at once when cut
	Close(cut bool) error
}

What plays the speech of one reply aloud to a chat: each clip begins with its format, pcm at a rate for 16 bit mono samples or the kind of a whole file such as mp3, then its bytes

type ChatTask

type ChatTask = protocolv1.ChatTask

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type ChatWork

type ChatWork = protocolv1.ChatWork

What a chat app and icebath tell each other of: where people write, who they are, what they wrote and what icebath posts, the marks people set, the chats they open, the sessions they may take up, the commands of a menu, the tasks of a reply, what the app posts over HTTP with icebath's answer, and the app's sign-in at its provider

type Command

type Command struct {
	Name    string
	Aliases []string
	Usage   string
	Help    string
	Handler func(ctx context.Context, call CommandCall) (string, error)
}

Slash command of a session

type CommandCall

type CommandCall struct {
	Argument  string
	SessionID string
	Cwd       string
}

One run of a slash command: what followed it, the session it ran in and that session's working folder

type CompleteCall

type CompleteCall struct {
	System    string
	Prompt    string
	MaxTokens int
	Timeout   time.Duration
	// JSON schema the answer follows, nil for text, and the name the model is told it by
	Schema     map[string]any
	SchemaName string
	// Pictures the question is about, at most 16 and 20 MB in all
	Images []CompleteImage
	// Session of the profile the call is for, whose usage counts it; none for a call of the extension's own
	SessionID string
}

One question to a helper model of the profile: its system prompt and prompt, the most tokens of its answer, the model's own cap when zero, and the longest it may take, the helper task's own limit when zero and 10 minutes at most

type CompleteImage

type CompleteImage struct {
	Mime string
	Data []byte
	Path string
}

A picture of a question: its bytes and their type, such as image/png, told from the bytes when empty; or the path of a file the grants of the manifest let the extension read, its own data folder among them, in place of the bytes

type CompleteReply

type CompleteReply struct {
	Text                    string
	JSON                    any
	Finish, Provider, Model string
	Usage                   TaskUsage
	Cost                    *float64
}

What a helper model answered: its text, for a question with a schema the JSON alone and that JSON read into JSON as encoding/json reads it; why it stopped, the provider and model that answered, what it took, and the dollars it cost where the price of its model is known

type Completing

type Completing struct {
	Typed     string
	SessionID string
	// Folder the session works in
	Cwd string
	// The person types in a chat app
	Chat  bool
	Limit int
}

What is typed, as icebath asks what completes it or what it matches

type Completion

type Completion struct {
	Value, Display, Meta string
}

One value that completes what is typed after a prefix: what is written after its colon, what the row shows, what is shown beside it

type ContextEngine

type ContextEngine struct {
	// As the context engine setting names it, in lower case, and what a person calls it
	Name  string
	Title string
	About string
	// Makes the engine of a session icebath opens
	New func(ctx context.Context, env *EngineEnv) (Engine, error)
	// Tools it gives the model and slash commands it offers while it is the profile's engine
	Tools    []EngineTool
	Commands []Command
	// What its engines answer beyond what every one does, each asked of them only when set
	Maintains bool
	Selects   bool
	Prepares  bool
	Finishes  bool
	Salvages  bool
	Snapshots bool
	Prunes    bool
}

Engine that keeps a long session within the model's limit, which a person picks as the profile's context engine in /settings as icebath's own compressor is. It reads every session of the profile and rewrites it as it is compacted, so the manifest grants the kind context:

grants:
  kinds: [context]
  models: true

icebath opens an engine of it for each session with New and asks the engine through the session's life. A summary the engine writes can ask the profile's helper models with Host.Complete, for a manifest that grants models. An engine whose extension stopped is opened again with what the session last told it. A whole extension, an engine that keeps the newest messages within three quarters of the window and drops the oldest:

type window struct {
	extensionsdk.EngineBase
	env      *extensionsdk.EngineEnv
	prompt   int
	compacts int
}

func (w *window) Bind(_ context.Context, env *extensionsdk.EngineEnv) error { w.env = env; return nil }

func (w *window) Observe(_ context.Context, usage *extensionsdk.EngineUsage) (bool, error) {
	if usage != nil {
		w.prompt = int(usage.GetInput() + usage.GetCacheRead() + usage.GetCacheWrite())
	}
	return false, nil
}

func (w *window) Due(_ context.Context, tokens int) (bool, string, error) {
	return tokens > int(w.env.GetWindow())*3/4, "", nil
}

func (w *window) Compress(_ context.Context, _ *extensionsdk.EngineEnv, request *extensionsdk.EngineRequest) (*extensionsdk.EngineResult, error) {
	kept := request.GetMessages()
	if len(kept) > 20 {
		kept = kept[len(kept)-20:]
	}
	w.compacts++
	return &extensionsdk.EngineResult{Messages: kept}, nil
}

func (w *window) State() *extensionsdk.EngineState {
	return &extensionsdk.EngineState{Prompt: int32(w.prompt), Window: w.env.GetWindow(), Threshold: w.env.GetWindow() * 3 / 4,
		Percent: 0.75, Compressions: int32(w.compacts)}
}

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		_, err := host.Register(extensionsdk.ContextEngine{Name: "window", Title: "Newest messages",
			About: "Keep the newest messages and drop the oldest",
			New: func(_ context.Context, env *extensionsdk.EngineEnv) (extensionsdk.Engine, error) {
				return &window{env: env}, nil
			}})
		return err
	})
}

func main() { extensionsdk.Main() }

type Delegation

type Delegation struct {
	// Value of the delegation method setting that picks it, in lower case, what a person calls it, and a line describing it in pickers
	Name    string
	Title   string
	Summary string
	// What it adds to the description of delegate_task, and the parameters it adds to each task, each with the JSON schema object of its
	// value, whose enum bounds the values a task may give
	Description string
	Parameters  []DelegationParameter
	// Variables it needs set before it can run
	Needs []string
	// Where the subagent of a task runs; an error, or a place with Refused, refuses that task alone
	Route func(ctx context.Context, task DelegationTask) (DelegationPlace, error)
	// Runs one turn of a subagent whose place said Runs, telling what it does through sub as it goes; nil for a way that only routes
	Run func(ctx context.Context, turn SubagentTurn, sub *Subagent) (SubagentResult, error)
	// Compacts the messages the extension keeps for a subagent's session, saying what came of it in a sentence; nil for one that keeps
	// none, which is read whole from each turn's messages
	Compact func(ctx context.Context, session string) (string, error)
}

Way the agent's subagents run, which a person picks in /delegation as one of icebath's own. For each task the agent delegates it names where the subagent runs: a model or provider of the profile, an address of its own, an agent program of this computer that speaks the Agent Client Protocol (from an extension that runs as a program), or, with Runs, the extension itself, which then runs each turn of the subagent its own way, such as on another agent program or a fleet of machines: it is handed the session's messages, writes its answer, tells each step it takes and what the steps do, takes the guidance the person sends meanwhile, asks the person's leave and questions through the session, and ends with its answer and the tokens it took. Running the agent's subagents reads the tasks and context the agent hands them, so the manifest grants the kind subagents, which the person agrees to as the extension installs:

grants:
  kinds: [subagents]
  net: [fleet.example]
needs: [FLEET_TOKEN]

A turn whose extension stops answering fails as a provider's failure would, naming the extension; a turn the agent stops is stopped here, its context ended. As the extension unloads, every turn it runs is stopped. A whole extension that runs every subagent on a fleet:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		_, err := host.Register(extensionsdk.Delegation{
			Name: "fleet", Title: "Fleet", Summary: "Run subagents on the machines of your fleet", Needs: []string{"FLEET_TOKEN"},
			Route: func(ctx context.Context, task extensionsdk.DelegationTask) (extensionsdk.DelegationPlace, error) {
				return extensionsdk.DelegationPlace{Runs: true, Label: "fleet"}, nil
			},
			Run: func(ctx context.Context, turn extensionsdk.SubagentTurn, sub *extensionsdk.Subagent) (extensionsdk.SubagentResult, error) {
				last := turn.Messages[len(turn.Messages)-1].GetText()
				sub.Doing("Handing the task to the fleet")
				token, _, _ := host.Env(ctx, "FLEET_TOKEN")
				response, err := host.Fetch(ctx, extensionsdk.Request{Method: "POST", URL: "https://fleet.example/run",
					Headers: map[string]string{"Authorization": "Bearer " + token}, Body: []byte(last), Timeout: time.Hour})
				if err != nil {
					return extensionsdk.SubagentResult{}, err
				}
				sub.Write(string(response.Body))
				return extensionsdk.SubagentResult{Answer: string(response.Body)}, nil
			},
		})
		return err
	})
}

func main() { extensionsdk.Main() }

type DelegationParameter

type DelegationParameter struct {
	Name   string
	Schema map[string]any
}

A parameter a way adds to the tasks of delegate_task

type DelegationPlace

type DelegationPlace struct {
	// Model and provider of the profile, an address of its own with its key and request format, fields added to every request, how hard it
	// thinks, its speed tier, and the models it falls back to, each provider:model
	Model     string
	Provider  string
	BaseURL   string
	APIKey    string
	APIMode   string
	Overrides map[string]any
	Effort    string
	Tier      string
	Fallbacks []string
	// Name of the route in the results
	Label string
	// Program of this computer that answers for the subagent over the Agent Client Protocol and its arguments, for an extension that runs
	// as a program
	Command string
	Args    []string
	// The extension runs the subagent itself with Run
	Runs bool
	// Why the task was refused, its siblings still started; empty when it was not
	Refused string
}

Where a subagent runs, every field left empty taking what the agent that delegated runs on

type DelegationTask

type DelegationTask struct {
	Index   int
	Goal    string
	Context string
	Params  map[string]any
}

One task of a delegate_task call: its place in the call, what the subagent is to do, what it is told, and the values the model gave the parameters of the way

type Engine

type Engine interface {
	// Takes the session's model, window and settings as they change
	Bind(ctx context.Context, env *EngineEnv) error
	// Told a turn starts with the messages the model is sent
	Turn(ctx context.Context, messages []*Message) error
	// Takes what the newest call of the main model took, nil when the provider said nothing; whether it confirms a compression of the turn
	// cleared the trigger
	Observe(ctx context.Context, usage *EngineUsage) (bool, error)
	// Whether a request of that many tokens is to be compressed now, and when it should be but is held off, why
	Due(ctx context.Context, tokens int) (bool, string, error)
	// Whether a rough estimate over the trigger waits for the provider's own count of the next request before compressing
	Defer(ctx context.Context, tokens int) (bool, error)
	// Whether it asks for a compression below the trigger, for an engine that keeps a budget of its own: ContextEngine.Maintains
	Maintain(ctx context.Context, messages []*Message) (bool, error)
	// Whether the messages hold anything between what is always kept to compress
	Compressible(ctx context.Context, messages []*Message) (bool, error)
	// The messages compressed; nil stores nothing
	Compress(ctx context.Context, env *EngineEnv, request *EngineRequest) (*EngineResult, error)
	// The messages with old tool results cut down without summarizing, and how many were: ContextEngine.Prunes
	Prune(ctx context.Context, env *EngineEnv, messages []*Message, tokens int) ([]*Message, int, error)
	// Messages the request is to carry in place of those given, picked from the whole session within the budget, and whether to keep those
	// given: ContextEngine.Selects
	Select(ctx context.Context, request, conversation []*Message, incoming *Message, budget int) ([]*Message, bool, error)
	// Starts work ahead of the next compression as the session nears the trigger: ContextEngine.Prepares
	Prepare(ctx context.Context, env *EngineEnv, messages []*Message, origin string) error
	// Told a turn ended with the messages it left; a result to store in their place, nil for none: ContextEngine.Finishes
	Finished(ctx context.Context, env *EngineEnv, messages []*Message) (*EngineResult, error)
	// Status line shown while it compresses in the phase, from the default given; empty shows none
	Announce(ctx context.Context, phase, text string) (string, error)
	// Told how the result of its last compression came to an end
	Settled(ctx context.Context, outcome *EngineOutcome) error
	// Told its last compression was given up for want of progress or time, so the next waits longer
	TimedOut(ctx context.Context, failure, kind string, idle time.Duration) error
	// Told a compression was stored, the session going on as next
	Compressed(ctx context.Context, previous, next string) error
	// The session ended with the messages it was left with
	End(ctx context.Context, messages []*Message) error
	// A compression larger than what it replaces, shrunk toward the budget; nil keeps it: ContextEngine.Salvages
	Salvage(ctx context.Context, original, candidate []*Message, budget int) ([]*Message, error)
	// What puts the engine back as it is now, for an attempt given up before it was stored: ContextEngine.Snapshots
	Snapshot(ctx context.Context) (func(), error)
	// Its figures as they stand, which every answer carries to icebath
	State() *EngineState
}

Engine of one session, made by the New of a ContextEngine as icebath opens one. Embed EngineBase for every method an engine leaves to the defaults, and write Due, Compress and State, which every engine answers. Each method returning an error that icebath does not get in time is answered by icebath's own compressor, which the person is told of

type EngineBase

type EngineBase struct{}

What an engine leaves to the defaults, embedded by engines

func (EngineBase) Announce

func (EngineBase) Announce(_ context.Context, _, text string) (string, error)

func (EngineBase) Bind

func (EngineBase) Compressed

func (EngineBase) Compressed(context.Context, string, string) error

func (EngineBase) Compressible

func (EngineBase) Compressible(context.Context, []*Message) (bool, error)

func (EngineBase) Defer

func (EngineBase) Defer(context.Context, int) (bool, error)

func (EngineBase) End

func (EngineBase) Finished

func (EngineBase) Maintain

func (EngineBase) Maintain(context.Context, []*Message) (bool, error)

func (EngineBase) Observe

func (EngineBase) Prepare

func (EngineBase) Prune

func (EngineBase) Prune(_ context.Context, _ *EngineEnv, messages []*Message, _ int) ([]*Message, int, error)

func (EngineBase) Salvage

func (EngineBase) Salvage(context.Context, []*Message, []*Message, int) ([]*Message, error)

func (EngineBase) Select

func (EngineBase) Select(context.Context, []*Message, []*Message, *Message, int) ([]*Message, bool, error)

func (EngineBase) Settled

func (EngineBase) Snapshot

func (EngineBase) Snapshot(context.Context) (func(), error)

func (EngineBase) TimedOut

func (EngineBase) Turn

type EngineEnv

type EngineEnv = protocolv1.EngineEnv

What a context engine and icebath tell each other of: a message of a session as icebath keeps it, with its role, text, reasoning, tool calls and media; what an engine works with; the tokens a request took; its figures; a compression asked for, what it came to and how it ended

type EngineOutcome

type EngineOutcome = protocolv1.EngineOutcome

What a context engine and icebath tell each other of: a message of a session as icebath keeps it, with its role, text, reasoning, tool calls and media; what an engine works with; the tokens a request took; its figures; a compression asked for, what it came to and how it ended

type EngineRecord

type EngineRecord = protocolv1.EngineRecord

What a context engine and icebath tell each other of: a message of a session as icebath keeps it, with its role, text, reasoning, tool calls and media; what an engine works with; the tokens a request took; its figures; a compression asked for, what it came to and how it ended

type EngineRequest

type EngineRequest = protocolv1.EngineRequest

What a context engine and icebath tell each other of: a message of a session as icebath keeps it, with its role, text, reasoning, tool calls and media; what an engine works with; the tokens a request took; its figures; a compression asked for, what it came to and how it ended

type EngineResult

type EngineResult = protocolv1.EngineResult

What a context engine and icebath tell each other of: a message of a session as icebath keeps it, with its role, text, reasoning, tool calls and media; what an engine works with; the tokens a request took; its figures; a compression asked for, what it came to and how it ended

type EngineState

type EngineState = protocolv1.EngineState

What a context engine and icebath tell each other of: a message of a session as icebath keeps it, with its role, text, reasoning, tool calls and media; what an engine works with; the tokens a request took; its figures; a compression asked for, what it came to and how it ended

type EngineTool

type EngineTool struct {
	Tool
	Run func(ctx context.Context, engine Engine, call ToolCall) (string, error)
}

Tool a context engine gives the model while it is the profile's engine, its call handed the engine of the session that made it

type EngineUsage

type EngineUsage = protocolv1.EngineUsage

What a context engine and icebath tell each other of: a message of a session as icebath keeps it, with its role, text, reasoning, tool calls and media; what an engine works with; the tokens a request took; its figures; a compression asked for, what it came to and how it ended

type Event

type Event struct {
	Point     string
	SessionID string
	Payload   map[string]any
}

Firing of a hook point, its event as icebath's observers read it

type FolderEntry

type FolderEntry struct {
	Name string
	Dir  bool
	Size int64
}

One entry of a listed folder

type Handle

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

Registration icebath holds for the extension, removable before it unloads

func (*Handle) Dispose

func (h *Handle) Dispose(context.Context) error

Removes the registration, icebath told at once

type Hearing

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

Tells icebath what a live transcription hears as it hears it, from any goroutine

func (*Hearing) Final

func (h *Hearing) Final(text string)

Words heard that stand, kept as they are

func (*Hearing) Interim

func (h *Hearing) Interim(text string)

Words heard so far that may still change, replacing the interim words told before them

func (*Hearing) Stopped

func (h *Hearing) Stopped()

The speaker stopped, which ends the recording there, for a recognizer with Endpoints

type Hit

type Hit struct {
	Title       string
	URL         string
	Description string
}

One result of a search

type Hook

type Hook struct {
	Point string
	// On transform_llm_output the reply is held back from the screen while it streams
	Hold    bool
	Handler HookFunc
}

Callback on a hook point of the agent's lifecycle, such as pre_tool_call

type HookFunc

type HookFunc func(ctx context.Context, event Event) (*HookResult, error)

Runs on every firing of a hook point, answering nil for no directive

type HookResult

type HookResult struct {
	Action  Action
	Message string
	// Arguments of a tool call it modifies
	Args    map[string]any
	Rule    string
	Context string
	// Text that takes the place of what fired it, nil to keep that
	Replace *string
	Set     map[string]string
}

Directive of a hook and what its action takes

type Host

type Host interface {
	Info() Info

	// Adds a registration, such as a Tool, which icebath is told of at once after it loaded the extension
	Register(r Registration) (*Handle, error)
	// Runs fn as the extension unloads, the last added first
	OnUnload(fn func() error)
	// Publishes an event as <extension>:<event> for the extensions of the profile that subscribed to it, answering how many it went to. The
	// payload goes as JSON
	Emit(ctx context.Context, event string, payload any) (int, error)

	// Value of one setting of the extension read into the type of def, def when it is not set. A length of time is kept in seconds, as
	// SetSetting keeps one
	Setting(ctx context.Context, key string, def any) (any, error)
	// Keeps one setting of the extension, a nil value clearing it
	SetSetting(ctx context.Context, key string, value any) error
	// Value of a variable the manifest grants or names as one it needs, ok false when it is not set
	Env(ctx context.Context, name string) (value string, ok bool, err error)
	// Files and folders the grants of the manifest allow, its own folder read and its data folder read and written besides
	ReadFile(ctx context.Context, path string) ([]byte, error)
	WriteFile(ctx context.Context, path string, data []byte) error
	ListFolder(ctx context.Context, path string) ([]FolderEntry, error)
	Remove(ctx context.Context, path string) error
	// HTTP request to a host the grants name, made by icebath
	Fetch(ctx context.Context, request Request) (*Response, error)
	// Runs a tool of the agent for a session of the profile, none when the id is empty, and answers its text, for a manifest whose requests
	// name tools. The session's approvals and rules decide as for the agent's own call, a command they would ask about refused where nobody
	// can answer. The folder is the session's working folder as a ToolCall, CommandCall or Turn tells it, the session's own when empty, the
	// extension's data folder with no session
	RunTool(ctx context.Context, sessionID, cwd, name string, args map[string]any) (string, error)
	// Sends text to a session of the profile as the person's next message, for a manifest whose requests name messages
	Send(ctx context.Context, sessionID, text string) error
	// Answer of a helper model of the profile, for a manifest whose requests name models, as long as the model allows when maxTokens is zero
	Complete(ctx context.Context, system, prompt string, maxTokens int) (string, error)
	// Answer of a helper model of the profile to a question as Completion takes it, for a manifest whose requests name models: with a schema
	// the answer is one JSON value that follows it, asked of the model by its provider's own structured output where the route takes one and
	// in words where not, checked against the schema before it is answered, a refusal of the model or an answer cut before its JSON ended
	// an error in words; with images it goes to the helper model of Extensions with images, one that sees them, and is refused with an
	// error Unavailable tells when none is set up. Its tokens count to the extension and to the session named, never a key held:
	//
	//	screenshot, err := host.ReadFile(ctx, "$EXTENSION_DATA/screen.png")
	//	if err != nil {
	//		return "", err
	//	}
	//	reply, err := host.Completion(ctx, extensionsdk.CompleteCall{SessionID: call.SessionID,
	//		Prompt: "Is there an error dialog on this screen? Say what it says.",
	//		Images: []extensionsdk.CompleteImage{{Mime: "image/png", Data: screenshot}},
	//		Schema: map[string]any{"type": "object", "required": []any{"dialog", "text"}, "properties": map[string]any{
	//			"dialog": map[string]any{"type": "boolean"}, "text": map[string]any{"type": "string"}}}})
	//	switch {
	//	case extensionsdk.Unavailable(err):
	//		return "No helper model that sees images is set up.", nil
	//	case err != nil:
	//		return "", err
	//	}
	//	seen := reply.JSON.(map[string]any)
	//	if seen["dialog"] == true {
	//		return "The screen shows an error: " + seen["text"].(string), nil
	//	}
	//	return "No error is shown.", nil
	Completion(ctx context.Context, call CompleteCall) (CompleteReply, error)
	// Runs a helper task the extension registered, by its name, on the helper models of the profile as the task's settings route it, for a
	// manifest whose requests name models: the extension hands the messages and gets the answer with what it took, never a key, and the
	// tokens count to the task and to the session named:
	//
	//	reply, err := host.RunTask(ctx, "triage", extensionsdk.TaskCall{SessionID: call.SessionID, Messages: []extensionsdk.TaskMessage{
	//		{Role: extensionsdk.TaskSystem, Text: "Sort the issue into bug, feature or question. Answer with the word alone."},
	//		{Text: issue},
	//	}, MaxTokens: 16})
	//	if err != nil {
	//		return "", err
	//	}
	//	return strings.TrimSpace(reply.Text), nil
	RunTask(ctx context.Context, task string, call TaskCall) (TaskReply, error)
	// Asks the person of a session of the profile the questions at once, for a manifest whose requests name questions, and waits for the
	// answers at most the timeout, 5 minutes when zero and an hour at most. They are shown as asked by the extension wherever the session is:
	// the terminal app, a chat app, an editor or a run of the HTTP API; a secret's answer comes back to the extension alone. Where nobody can
	// answer, such as a run nobody watches, the error is one Unavailable tells:
	//
	//	answers, err := host.AskUser(ctx, call.Session, []extensionsdk.Question{
	//		{ID: "target", Header: "Deploy", Text: "Deploy to which environment?", Choices: []string{"staging", "production"}},
	//		{ID: "token", Text: "The deploy token", Secret: true},
	//	}, 10*time.Minute)
	//	switch {
	//	case extensionsdk.Unavailable(err):
	//		return "Nobody can answer here, so nothing was deployed.", nil
	//	case err != nil:
	//		return "", err
	//	case answers.Outcome != extensionsdk.Submitted:
	//		return "The deploy was left for later.", nil
	//	}
	//	deploy(answers.Values["target"][0], answers.Values["token"][0])
	AskUser(ctx context.Context, sessionID string, questions []Question, timeout time.Duration) (Answers, error)
	// Asks the agent of a session of the profile a question about the session as it stands, for a manifest whose requests name
	// side_questions, the session and what waits to be sent to it left as they are: over the session's own last request, which keeps
	// the provider's prompt cache, tools refused, else by the helper model of side questions over a transcript of it, whose answer is
	// maxTokens long at most (2048 when zero). It waits at most the timeout, a minute when zero and 3 minutes at most, and its tokens count to
	// the session as a side question of the extension:
	//
	//	answer, err := host.SideQuestion(ctx, turn.SessionID, "Which files did we change, and is anything left undone?", 0, 0)
	//	if err != nil {
	//		return err
	//	}
	//	host.Log(extensionsdk.LevelInfo, "Session summary: "+answer.Text)
	SideQuestion(ctx context.Context, sessionID, question string, maxTokens int, timeout time.Duration) (SideAnswer, error)
	// Calls a tool of an MCP server of the profile, by the tool's own name, as the agent calls it, for a manifest whose requests name mcp and
	// only for a server, or a server/tool, the person allows the extension under Allowed in its settings. The server's trust and spending
	// limit ask the person of the session named; with no session nobody is asked, so a call that needs asking is refused. It waits at most
	// the timeout, 30 seconds when zero, from 1 second to 10 minutes. A tool that failed answers with Failed and why in Text:
	//
	//	result, err := host.CallMCP(ctx, call.SessionID, "github", "search_issues", map[string]any{"query": "is:open label:bug"}, 0)
	//	switch {
	//	case extensionsdk.Denied(err):
	//		return "Allow the github server for this extension under Allowed in /extensions.", nil
	//	case err != nil:
	//		return "", err
	//	case result.Failed:
	//		return "The search failed: " + result.Text, nil
	//	}
	//	return result.Text, nil
	CallMCP(ctx context.Context, sessionID, server, tool string, args map[string]any, timeout time.Duration) (MCPResult, error)
	// The tools of the MCP servers the person allows the extension, as the servers offer them now, for a manifest whose requests name mcp:
	//
	//	tools, err := host.MCPTools(ctx)
	//	for _, tool := range tools {
	//		host.Log(extensionsdk.LevelDebug, tool.Server+"/"+tool.Name+": "+tool.About)
	//	}
	MCPTools(ctx context.Context) ([]MCPTool, error)
	// Starts a subagent for a session of the profile in the background, for a manifest whose requests name subagents, through the agent's own
	// delegation: its limits, the session's approvals and rules, never a tool the session is not offered. Its result stays with the extension,
	// and goes into the session too when Report asks. The extension follows it with SubagentStatus, AwaitSubagent, SteerSubagent and
	// StopSubagent by its id; the life of every subagent of a session is heard by a Hook on subagent_start, subagent_progress and
	// subagent_stop:
	//
	//	sub, err := host.SpawnSubagent(ctx, call.SessionID, extensionsdk.Spawn{Goal: "Find every TODO in the repository and group them by file",
	//		Toolsets: []string{"files"}})
	//	if err != nil {
	//		return "", err
	//	}
	//	done, err := host.AwaitSubagent(ctx, call.SessionID, sub.ID, 10*time.Minute)
	//	switch {
	//	case err != nil:
	//		return "", err
	//	case !done.Done:
	//		host.StopSubagent(ctx, call.SessionID, sub.ID)
	//		return "The search took too long and was stopped.", nil
	//	}
	//	return done.Summary, nil
	SpawnSubagent(ctx context.Context, sessionID string, spawn Spawn) (Spawned, error)
	// A subagent the extension started in the session, as it stands
	SubagentStatus(ctx context.Context, sessionID, id string) (Spawned, error)
	// Waits until a subagent the extension started ended, at most the timeout, a minute when zero and an hour at most; Done false when the
	// time ran out first
	AwaitSubagent(ctx context.Context, sessionID, id string, timeout time.Duration) (Spawned, error)
	// Guidance a subagent the extension started reads at its next step; false and why when it was not taken
	SteerSubagent(ctx context.Context, sessionID, id, text string) (bool, string, error)
	// Stops a subagent the extension started, what it did so far kept as its result
	StopSubagent(ctx context.Context, sessionID, id string) (Spawned, error)
	// Acts in a chat of a chat app the profile is connected to, as the bot, for a manifest whose requests name chats and only in the chats
	// the person allows the extension under Allowed in its settings: post (text, files the grants let it read, a voice message), edit,
	// delete, react, unreact, typing, pin, unpin, thread, rename, topic, describe, history; abilities says which of them the app of the chat
	// has, places lists the chats it may act in. An app with no way to do it is refused with an error Unknown tells, naming the app:
	//
	//	done, err := host.PlatformAct(ctx, extensionsdk.PlatformAct{Place: "telegram", Action: "post", Text: "The deploy finished."})
	//	if err != nil {
	//		return err
	//	}
	//	_, err = host.PlatformAct(ctx, extensionsdk.PlatformAct{Place: done.Place.Place, Action: "pin", Message: done.Messages[0]})
	//	if extensionsdk.Unknown(err) {
	//		host.Log(extensionsdk.LevelInfo, "This chat app has no pins: "+err.Error())
	//	}
	PlatformAct(ctx context.Context, act PlatformAct) (PlatformActed, error)
	// Puts a message into the session of a chat as if the person who last wrote there had sent it, so the agent answers it there, for a
	// manifest whose requests name inject, only in the chats the person allows the extension; a strong right the person is warned of:
	//
	//	place, err := host.InjectMessage(ctx, "slack:C0123ABC", "The nightly build failed. Look at the log and tell the channel what broke.")
	InjectMessage(ctx context.Context, place, text string) (PlatformPlace, error)
	// Where a session of the profile works, for a manifest whose requests name folders: its folder, the git repository and branch there,
	// the worktree it is and the project the folder lies in. A Hook on on_session_move hears each move of a session's folder:
	//
	//	where, err := host.SessionFolder(ctx, turn.SessionID)
	//	if err == nil && where.Worktree {
	//		host.Log(extensionsdk.LevelInfo, "Working in a worktree of "+where.Repository+" on "+where.GitBranch)
	//	}
	SessionFolder(ctx context.Context, sessionID string) (SessionWhere, error)
	// Moves a session of the profile to work in another folder, whole or relative to its own, for a manifest whose requests name cd, under
	// the rules of a person's /cd from a chat app: inside the folder the session works in or a folder of a project, one the profile's guard of
	// the tools lets be read; its commands follow:
	//
	//	where, err := host.MoveSession(ctx, call.SessionID, "web")
	//	if err != nil {
	//		return "", err
	//	}
	//	return strings.Join(where.Lines, "\n"), nil
	MoveSession(ctx context.Context, sessionID, folder string) (SessionWhere, error)
	// Whether another extension of the name is installed and on in the profile
	On(ctx context.Context, name string) (bool, error)
	// Writes a line to icebath's log
	Log(level Level, message string)
}

What the code of an extension registers on icebath and asks of it

type Hotword

type Hotword interface {
	// Samples of each frame it hears
	FrameLength() int
	// Whether the frame completes the wake word, and the phrase and profile it heard when it does
	Process(frame []int16) (fired bool, phrase, profile string, err error)
	// Forgets what it heard
	Reset() error
	Close()
}

Detector of a wake word over frames of 16 kHz samples

type ImageModel

type ImageModel struct {
	ID    string
	Title string
	About string
}

Model of an image service: its id, the name a person knows it by, and what it is good at

type ImageRequest

type ImageRequest struct {
	Prompt string
	// landscape, square or portrait
	Aspect string
	// Picture to change, empty for a new one, and the pictures after it that guide it
	Image      string
	References []string
	// Model picked, empty for the default
	Model string
	// The high resolution pass asked for, nil for the service's own default
	Upscale *bool
	// Creative controls the call gave of those it takes, and its own arguments, the call's over the person's, each fitting its schema
	Controls  map[string]any
	Arguments map[string]any
}

One picture to draw

type ImageService

type ImageService struct {
	Name  string
	Title string
	About string
	Needs []string
	// It changes the pictures it is handed besides drawing from text, and takes this many pictures at most, the main one and its references
	Edits      bool
	References int
	// Models a person can pick, and the one it draws with when none is picked
	Models  []ImageModel
	Default string
	// It takes the high resolution pass of image_generate's upscale, and these of icebath's creative controls: creativity, thinking,
	// resolution, intensity, complexity, movement
	Pass     bool
	Controls []string
	// The pictures it is handed give the look only, they are not edited
	Style bool
	// Lines its page and image_generate say of it
	Notes []string
	// Arguments of its own as a JSON schema of an object, nil for none; a property of a name every service shares is left out
	Arguments map[string]any
	// The picture made
	Generate func(ctx context.Context, request ImageRequest) (Picture, error)
	// Factors it enlarges a picture by, the first taken when a call names none, and the upscale, telling how far it got through progress, a
	// percent from 0 to 100 or below 0 when not known, and what it does now; none for a service that upscales nothing
	Factors []int
	Upscale func(ctx context.Context, request UpscaleRequest, progress func(percent float64, status string)) (Picture, error)
}

Service that draws pictures for the agent beside icebath's own, picked under Images. It may take arguments of its own beyond those every service shares, declared as a JSON schema of an object: image_generate offers each to the model, its page under Images offers each to a person, and a call is checked against the schema before it reaches Generate, so what Generate is handed fits it. With Factors and Upscale it enlarges pictures, which image_upscale offers: an upscale takes a while, so icebath starts it, asks how it stands every second or two and stops it by ending the context Upscale is handed. A picture it is handed is an address, a data URL, or for one larger than 20 MB a path of the extension's data folder, read with Host.ReadFile and removed once it answered. A whole extension:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		_, err := host.Register(extensionsdk.ImageService{Name: "painter", Title: "Painter", Needs: []string{"PAINTER_KEY"},
			Arguments: map[string]any{"type": "object", "properties": map[string]any{
				"steps": map[string]any{"type": "integer", "minimum": 1, "maximum": 50, "description": "Steps the model takes, more for detail."},
				"style": map[string]any{"type": "string", "enum": []any{"ink", "oil", "pixel"}, "description": "The painter's own style."},
			}},
			Factors: []int{2, 4},
			Generate: func(ctx context.Context, request extensionsdk.ImageRequest) (extensionsdk.Picture, error) {
				address, cost, err := paint(ctx, host, request.Prompt, request.Arguments["steps"], request.Arguments["style"])
				return extensionsdk.Picture{Image: address, Cost: &cost}, err
			},
			Upscale: func(ctx context.Context, request extensionsdk.UpscaleRequest,
				progress func(percent float64, status string)) (extensionsdk.Picture, error) {
				job, err := enlarge(ctx, host, request.Image, request.Factor)
				for err == nil && !job.Done {
					progress(job.Percent, "Painter is enlarging the picture")
					time.Sleep(2 * time.Second)
					job, err = check(ctx, host, job.ID)
				}
				return extensionsdk.Picture{Image: job.URL}, err
			}})
		return err
	})
}

func main() { extensionsdk.Main() }

type Info

type Info struct {
	Name    string
	Version string
	// Folder it is installed in, its own data folder, and the profile it runs for
	Dir     string
	Data    string
	Profile string
}

What the extension is, as icebath loaded it

type JobFire

type JobFire struct {
	Job           string
	Manual, Force bool
}

A fire of a job: the occurrence due now, any time when Manual, and one of a job paused or done too when Force

type JobFired

type JobFired struct {
	Fired bool
	Why   string
	At    time.Time
}

What came of a fire: claimed and running, with the occurrence it fired, zero for one fired by hand; or why not, such as another claim holding it or its occurrence fired already

type JobScheduler

type JobScheduler struct {
	// As Scheduler names it, and as a person knows it
	Name, Title, About string
	// Variables it needs set before it can decide
	Needs []string
	// Decides for the profile until ctx ends: handed the jobs as they stand and fire, which fires one through icebath and waits for what came
	// of it. Returning is giving up, which leaves the jobs to icebath's own clock until icebath starts it again
	Run func(ctx context.Context, jobs []ScheduledJob, fire func(ctx context.Context, f JobFire) (JobFired, error)) error
	// Told the jobs changed, the whole set again; nil for a scheduler that keeps nothing of them
	Changed func(ctx context.Context, jobs []ScheduledJob) error
	// Told a job is about to be saved, an error refusing the save in its words; nil for one that keeps no trigger for each job
	Register func(ctx context.Context, job ScheduledJob) error
	// Closes what fires of a process that ended left half done, answering how many; nil for one that keeps none
	Recover func(ctx context.Context) (int, error)
	// Whether it can decide now, a check that costs nothing; nil for always
	Check func(ctx context.Context) bool
}

Scheduler outside icebath that decides when the jobs of the profile run, such as a service of triggers, which a person picks as Scheduler under Jobs. Deciding when jobs run is a matter of trust, so the manifest grants the kind scheduler, which the person agrees to as the extension installs:

grants:
  kinds: [scheduler]
  net: [triggers.example]

icebath claims each fire, so no two icebaths run one occurrence of a job, and fires a job itself once it passed its grace unfired. A whole extension that fires what a service of triggers says is due:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		_, err := host.Register(extensionsdk.JobScheduler{Name: "triggers", Title: "Triggers",
			Run: func(ctx context.Context, jobs []extensionsdk.ScheduledJob,
				fire func(context.Context, extensionsdk.JobFire) (extensionsdk.JobFired, error)) error {
				for ctx.Err() == nil {
					due, err := host.Fetch(ctx, extensionsdk.Request{URL: "https://triggers.example/due"})
					if err != nil {
						return err
					}
					for _, id := range strings.Fields(string(due.Body)) {
						fire(ctx, extensionsdk.JobFire{Job: id})
					}
					time.Sleep(30 * time.Second)
				}
				return nil
			}})
		return err
	})
}

func main() { extensionsdk.Main() }

type Key

type Key struct {
	// Text it typed, and its name such as esc, enter or up without its modifiers
	Text  string
	Name  string
	Ctrl  bool
	Alt   bool
	Shift bool
}

Key pressed or text typed in a modal widget

type Kind

type Kind struct {
	// What a person calls one, such as board, for the failures of registering it
	Noun string
	Key  string
	Spec proto.Message
	// Answers one request of icebath with a message the request names, nil for a kind that is asked nothing
	Serve func(ctx context.Context, request proto.Message) (proto.Message, error)
}

Registration of any kind icebath takes, such as one a plugin of icebath added that this library has no type of: its spec, a message whose type names the kind, its key among the registrations of its kind, and what answers the requests icebath asks of it

type Level

type Level = protocolv1.Level

Level of a line of the log

type Line

type Line []Span

One line of a widget, its spans side by side

func PictureLine

func PictureLine(data []byte) Line

A line that is a picture: the bytes of a PNG, JPEG, GIF, WebP, BMP, TIFF or ICO image, which the app draws from that line on in as many rows of the box as it needs, as its terminal draws pictures

type Listener

type Listener interface {
	// Takes the next piece of audio as it is spoken
	Push(pcm []byte) error
	// The audio ended: the whole transcript once it is heard, its text empty to take the final words told
	Finish(ctx context.Context) (Transcript, error)
	// Lets go of what it holds, icebath being done with it
	Close()
}

One live transcription a recognizer holds

type Listening

type Listening struct {
	Language, Prompt, Model string
	Rate                    int
}

What a live transcription hears with: the language, hint text and model asked for, and the samples a second of its audio, 16000

type LocalePack

type LocalePack struct {
	// Folder of the catalogs: inside the extension's folder, relative to it, or inside its data folder
	Dir string
	// What each language of the pack icebath does not speak calls itself, by its id, and the ids of those written right to left;
	// icebath's language data says when unset
	Endonyms map[string]string
	RTL      []string
}

Words for languages icebath speaks, of a folder the extension keeps: a folder of YAML catalogs for each language, or one YAML file named for the language, laid out as a profile's own catalogs and as the locales folder of a manifest, which needs no code at all. Each catalog gives the words of a text by its English, and the forms of a plural by name under its one and its other form apart by " ⟨plural⟩ ":

"Saved %d notes.": "%d notes gespeichert."
"One note ⟨plural⟩ %d notes":
  one: "Eine Notiz"
  other: "%d Notizen"

Words for a language icebath speaks are taken for texts icebath carries none for alone, such as the titles of the extension's settings; a language icebath does not speak is taken whole and spoken once a person picks it, which the manifest grants:

grants:
  kinds: [languages]

Words that keep other placeholders than their English, or other plural forms than their language takes, leave their language out: an install whose manifest brings them is refused, and the doctor says why of a pack the code registered. Registered from code, a pack always takes the grant, and can be a folder the extension fills as it runs, such as one of its data folder; icebath reads it again once its files change. A whole extension that keeps the words it carries in its data folder:

//go:embed words
var words embed.FS

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		dir := filepath.Join(host.Info().Data, "words")
		os.RemoveAll(dir)
		if err := os.CopyFS(dir, words); err != nil {
			return err
		}
		_, err := host.Register(extensionsdk.LocalePack{Dir: filepath.Join(dir, "words"),
			Endonyms: map[string]string{"sw": "Kiswahili"}})
		return err
	})
}

func main() { extensionsdk.Main() }

type Login

type Login struct {
	ID       string
	Title    string
	Created  string
	Username string
	URLs     []string
	OTP      bool
}

One account a password manager holds: its id there, title, when it was made, the name it signs in with, every address saved on it, and whether it keeps an authenticator key

type MCPResult

type MCPResult struct {
	// Text of its result, or why the call failed
	Text   string
	Failed bool
	// Structured content the tool gave, nil when it gave none
	Structured any
	// The result as icebath hands it the model, an object of JSON
	Raw string
}

What a tool of an MCP server gave

type MCPTool

type MCPTool struct {
	// Server and the tool's own name, which CallMCP names it by, and what a person calls it and what it does
	Server, Name, Title, About string
	// The server marks it read-only, so it changes nothing
	ReadOnly bool
}

A tool of an MCP server the extension may call

type MemoryAsk

type MemoryAsk struct {
	Message string
	Query   string
}

What memory is searched with for a turn: the message the person sent, and the question a helper model made of it, the message itself when none was made

type MemoryDelegation

type MemoryDelegation struct {
	Task   string
	Result string
	Child  string
}

The work of a subagent once it ended: the task it was handed, what it answered, and its own session

type MemoryExchange

type MemoryExchange struct {
	User      string
	Assistant string
}

One exchange of a turn: what the person sent and what the agent answered last

type MemoryProvider

type MemoryProvider struct {
	// As the memory service setting names it, in lower case, and what a person calls it
	Name  string
	Title string
	About string
	// Where an account or a key is had
	Site string
	// Variables it needs set before it can remember
	Needs []string
	// Keys of the settings of the extension, as its manifest names them, that the Memory screen shows on the service's page
	Settings []string
	// Tools it gives the model while it is the profile's memory, each handled by its Handler
	Tools []Tool
	// Text of the system prompt about the service and its tools; BuildPrompt makes it for each session as it starts in its place
	Prompt      string
	BuildPrompt func(ctx context.Context) (string, error)
	// Readies what it remembers with, as it is picked and before the first call of a process of the extension; nil for nothing to ready
	Open func(ctx context.Context) error
	// What it recalls for the message the person sent, which the turn's message carries; empty for nothing. The ask holds the message and
	// the question memory is searched with
	Recall func(ctx context.Context, session string, ask MemoryAsk) (string, error)
	// Told each turn of a session as the turn begins; nil for a service that has no use for it
	Turn func(ctx context.Context, session string, turn MemoryTurn) error
	// Recalls in the background after a turn for the session's next one, which its next Recall hands out at once; nil for none
	Queue func(ctx context.Context, session string, ask MemoryAsk) error
	// Told of the work of a subagent of a session once the subagent ended; nil for a service that has no use for it
	Delegated func(ctx context.Context, session string, delegation MemoryDelegation) error
	// Keeps one finished exchange of a session
	Sync func(ctx context.Context, session string, exchange MemoryExchange) error
	// Keeps what it wants of every message of a session that closed, and of one whose context was compacted
	Ended     func(ctx context.Context, session string, conversation []MemoryExchange) error
	Compacted func(ctx context.Context, session string, conversation []MemoryExchange) error
	// Handed what a compaction of a session is about to fold away, the exchanges of the person and the agent alone, so it keeps what
	// matters of it, answering what the summary is to keep, empty for nothing; with required the person's settings ask for a checkpoint
	// before every compaction, so a failure stops it. Nil for a service that keeps nothing of it
	Checkpoint func(ctx context.Context, session string, conversation []MemoryExchange, required bool) (string, error)
	// What Checkpoint keeps is kept durably whenever it answers, so it answers a person's Require a checkpoint; else it is asked as best it
	// can, its failure let be
	Checkpoints bool
	// Hears each change the memory tool made to the agent's own notes, which it may mirror
	Wrote func(ctx context.Context, session string, write MemoryWrite) error
	// Lets go of what it holds, its writes done, as the profile picks another service, icebath ends or the extension unloads
	Close func(ctx context.Context) error
}

Outside memory service the agent remembers with beside its notes, which a person picks as the profile's memory service in /memory as one of icebath's own. Being the agent's memory reads what the person and the agent say in every session of the profile, so the manifest grants the kind memory, which the person agrees to as the extension installs:

grants:
  kinds: [memory]
  net: [api.mymemory.example]
needs: [MYMEMORY_API_KEY]

icebath opens the service as it is picked and before the first call of a process of the extension, and asks it as the sessions of the profile go: each turn as it begins, what it recalls for each message, each finished exchange and the recall readied for the next turn, what a compaction is about to fold away, the work of each subagent once it ended, the whole session as it closes and as its context is compacted, and each change of the agent's notes. A subagent runs without the memory of the session that delegated: nothing of its turns reaches the service but its work once it ended. An extension that stops is started again by the next call, which Open readies first. A whole extension:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		_, err := host.Register(extensionsdk.MemoryProvider{
			Name: "mymemory", Title: "My Memory", About: "Remembers across sessions in My Memory",
			Needs: []string{"MYMEMORY_API_KEY"},
			Recall: func(ctx context.Context, session string, ask extensionsdk.MemoryAsk) (string, error) {
				key, _, err := host.Env(ctx, "MYMEMORY_API_KEY")
				if err != nil {
					return "", err
				}
				response, err := host.Fetch(ctx, extensionsdk.Request{Method: "POST", URL: "https://api.mymemory.example/search",
					Headers: map[string]string{"Authorization": "Bearer " + key}, Body: []byte(ask.Query)})
				if err != nil {
					return "", err
				}
				return string(response.Body), nil
			},
			Sync: func(ctx context.Context, session string, exchange extensionsdk.MemoryExchange) error {
				key, _, _ := host.Env(ctx, "MYMEMORY_API_KEY")
				body, _ := json.Marshal(exchange)
				_, err := host.Fetch(ctx, extensionsdk.Request{Method: "POST", URL: "https://api.mymemory.example/add",
					Headers: map[string]string{"Authorization": "Bearer " + key}, Body: body})
				return err
			},
		})
		return err
	})
}

func main() { extensionsdk.Main() }

type MemoryTurn

type MemoryTurn struct {
	Number     int
	Message    string
	AuthorID   string
	AuthorName string
	AuthorBot  bool
}

A turn of a session as it begins: its number among the session's turns, 1 for the first, the message, and who wrote it as a chat app tells it, empty where nobody says

type MemoryWrite

type MemoryWrite struct {
	Action  string
	Target  string
	Content string
}

A change the memory tool made to the agent's own notes: add, replace or remove, of memory or user, with the whole entry it made or removed

type Message

type Message = sessionsv1.Message

What a context engine and icebath tell each other of: a message of a session as icebath keeps it, with its role, text, reasoning, tool calls and media; what an engine works with; the tokens a request took; its figures; a compression asked for, what it came to and how it ended

type Middleware

type Middleware struct {
	Name, Title, About string
	// Place in the chain, lower first; middlewares of one place go in the order of their extensions' names
	Order int
	// Wires of the requests it takes, such as chat_completions, anthropic_messages, codex_responses, gemini_native or bedrock_converse,
	// every one when none; and the requests of helper models besides those of the agent's turns
	Wires   []string
	Helpers bool
	// Longest one ask may take, 5 seconds when zero and 30 at most
	Timeout time.Duration
	// A failure of it, or a request it took too long over, fails the request rather than letting it go on as the ones before it left it
	Closed bool
	// A request to the model before it goes out: its body is JSON as its wire writes it
	Request func(ctx context.Context, request ModelRequest) (RequestChange, error)
	// The whole answer of a request that is not streamed, as it came back from a provider that took it: a change of its Body puts another
	// in its place. Answers of failures, and streams of them, go back to the agent as they came
	Answer func(ctx context.Context, request ModelRequest, answer ModelAnswer) (RequestChange, error)
	// Pieces of a streamed answer as they come, each JSON as the wire carries it, answering those that go on in their place: the same
	// pieces to keep them, none to hold them back for later, more to add some. Done says the stream ended, with no pieces
	Stream func(ctx context.Context, stream ModelPieces) ([][]byte, error)
	// A tool call before it runs, and its result once it ran: answering other arguments, a refusal, or another result, nil to keep it
	Tool   func(ctx context.Context, call ToolUse) (ToolChange, error)
	Result func(ctx context.Context, call ToolUse, result string) (*string, error)
}

Middleware that stands in the path of every request the sessions of the profile send the model and of every tool call they run: it reads each and may change it, refuse it or answer it in its place, and reads and may change what comes back. Each function left nil is a phase it does not take. Standing in that path is a matter of trust, so the manifest grants the kind middleware, which the person agrees to as the extension installs and sees on its page, in Status and in the security audit:

grants:
  kinds: [middleware]

Several middlewares run in the order of their Order, each on what the one before left; one that fails or runs out of its time is passed over unless it is Closed, when the request fails in words. A middleware never sees a credential header, never sets one and never changes where a request goes. A whole extension that keeps a header on every request and masks a word in every result of a tool:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		_, err := host.Register(extensionsdk.Middleware{Name: "tagger", Title: "Tagger",
			Request: func(ctx context.Context, request extensionsdk.ModelRequest) (extensionsdk.RequestChange, error) {
				return extensionsdk.RequestChange{Headers: map[string]string{"X-Team": "research"}}, nil
			},
			Result: func(ctx context.Context, call extensionsdk.ToolUse, result string) (*string, error) {
				masked := strings.ReplaceAll(result, "Project Falcon", "the project")
				return &masked, nil
			}})
		return err
	})
}

func main() { extensionsdk.Main() }

type Mode

type Mode = protocolv1.Mode

How a widget shows

type ModelAnswer

type ModelAnswer struct {
	Status  int
	Headers map[string]string
	Body    []byte
}

The whole answer of a request: its status, headers with credentials left out, and body as the wire writes it

type ModelPieces

type ModelPieces struct {
	Wire, SessionID, Turn string
	Pieces                [][]byte
	Done                  bool
}

Pieces of a streamed answer as they came, of the wire, session and turn of the request; Done once the stream ended

type ModelProvider

type ModelProvider struct {
	// As a provider's kind names it, in lower case, and what a person calls it
	Name  string
	Title string
	About string
	// Where an account or a key is had, and other names a person may give the kind
	Site    string
	Aliases []string
	// Wire its requests go out over, one of the Wire values; WireExtension, or empty with Stream set, for requests it carries itself
	Wire string
	// Address a provider of the kind starts with, the variable that sets it for all of them, and the address of its models listing
	BaseURL    string
	BaseURLEnv string
	ModelsURL  string
	// Variables its API key is read from, the first set winning, and how its accounts sign in, one of the Auth values
	KeyEnv []string
	Auth   string
	// Headers every request carries
	Headers map[string]string
	// Model a provider of the kind starts with, and those tried after it
	DefaultModel   string
	FallbackModels []string
	// Models it offers, with what is known of each
	Models []*ProviderModel
	// It runs on this computer, routes to the models of several makers, or its models see images unless one says otherwise
	Local      bool
	Aggregator bool
	Vision     bool
	// Requests are sent with no temperature, and with this many output tokens at most when they ask none
	OmitTemperature  bool
	DefaultMaxTokens int
	// Model ids it takes under other names, by the name a person writes
	ModelAliases map[string]string
	// Tool names it keeps for its own tools, and whether it takes only nine character ids of tool calls
	ReservedTools []string
	ShortToolIDs  bool
	// Tokenizers its models count with
	Tokenizers []*ProviderTokenizer
	// Carries one request itself: each part of the reply handed to emit as it comes, then the whole reply; a *ProviderError says why the
	// provider refused it. The context ends once icebath stops waiting for the reply
	Stream func(ctx context.Context, request *ProviderRequest, emit func(*ProviderEvent)) (*ProviderResponse, error)
	// The models a route serves now; nil for the Models alone
	List func(ctx context.Context, route *ProviderRoute) ([]*ProviderModel, error)
	// Tokens of a request as the provider counts them; nil for none
	Count func(ctx context.Context, request *ProviderRequest) (int, error)
	// Readies what answers a request before it goes out, such as a token renewed, answering the address and key to send it with, none to
	// keep the route's, and lines the person is shown; nil for nothing to ready
	Prepare func(ctx context.Context, route *ProviderRoute, session string) (*ProviderPrepared, error)
	// Headers and fields of the body of one request, and its messages as the wire sends them rewritten for the provider; each nil for none
	RequestHeaders func(ctx context.Context, call *ProviderCall) (map[string]string, error)
	RequestBody    func(ctx context.Context, call *ProviderCall) (map[string]any, error)
	Rewrite        func(ctx context.Context, call *ProviderCall, messages []map[string]any) ([]map[string]any, error)
}

Kind of model provider a person adds to a profile in /providers as one of icebath's own: icebath sends its requests over one of its wires at the address it names with the quirks it declares, or the extension carries each one itself with Stream. Being a model provider sees every request sent to it, with the session's messages, the tools offered and the key of its accounts, so the manifest grants the kind provider:

grants:
  kinds: [provider]
  net: [api.mymodels.example]

A whole extension of a provider icebath reaches over the chat completions wire, its key read from MYMODELS_API_KEY or kept in an account:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		_, err := host.Register(extensionsdk.ModelProvider{
			Name: "mymodels", Title: "My Models", Wire: extensionsdk.WireChatCompletions,
			BaseURL: "https://api.mymodels.example/v1", KeyEnv: []string{"MYMODELS_API_KEY"}, DefaultModel: "my-large",
			Models: []*extensionsdk.ProviderModel{{Id: "my-large", Context: 200000, Efforts: []string{"low", "medium", "high"}}},
		})
		return err
	})
}

func main() { extensionsdk.Main() }

and one that carries each request itself, answering with the reply of a service of its own:

Stream: func(ctx context.Context, request *extensionsdk.ProviderRequest, emit func(*extensionsdk.ProviderEvent)) (*extensionsdk.ProviderResponse, error) {
	reply, err := ask(ctx, request.GetRoute().GetApiKey(), request.GetMessages())
	if err != nil {
		return nil, &extensionsdk.ProviderError{Status: 503, Message: err.Error(), Kind: "server"}
	}
	emit(&extensionsdk.ProviderEvent{Kind: extensionsdk.EventText, Text: reply})
	return &extensionsdk.ProviderResponse{Message: &extensionsdk.Message{Role: sessionsv1.Role_ROLE_ASSISTANT, Text: reply},
		FinishReason: "stop"}, nil
},

type ModelRequest

type ModelRequest struct {
	Wire, Provider, Model, SessionID, Turn, Helper string
	Headers                                        map[string]string
	Body                                           []byte
	Stream                                         bool
}

A request to the model: the wire it speaks, the provider and model it goes to, the session, turn and helper task it is for, its headers with credentials left out, its body as JSON as the wire writes it, and whether its answer streams

type Page

type Page struct {
	URL     string
	Title   string
	Content string
	Error   string
}

One page read, or why it could not be

type PasswordManager

type PasswordManager struct {
	// Name of its settings and of the handles of its accounts, in lower case letters, digits and underscores, and what a person calls it
	Name  string
	Title string
	About string
	// Variables it needs set before it counts as installed
	Needs []string
	// Signs in with the master password, answering the session token later calls carry; nil for a manager that works with no unlock
	Unlock func(ctx context.Context, master string) (string, error)
	// Accounts with a site; ErrManagerLocked for a session that ended
	Logins func(ctx context.Context, session string) ([]Login, error)
	// Password of an account, and its current one time code, empty for one with none; nil Code for a manager without codes
	Password func(ctx context.Context, session, id string) (string, error)
	Code     func(ctx context.Context, session, id string) (string, error)
}

Password manager the autofill vault reads website accounts from beside its own store, which a person turns on in the settings of the vault as one of icebath's own; the agent sees the handles of its accounts alone, never their passwords. It hands over every account of a person, so icebath takes it only from an extension the catalog lists as official or verified, whose manifest grants the kind logins:

grants:
  kinds: [logins]

A whole extension, a manager of a command line tool of this computer that needs its master password:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		_, err := host.Register(extensionsdk.PasswordManager{
			Name: "keeper", Title: "Keeper",
			Unlock: func(ctx context.Context, master string) (string, error) { return keeperLogin(ctx, master) },
			Logins: func(ctx context.Context, session string) ([]extensionsdk.Login, error) { return keeperList(ctx, session) },
			Password: func(ctx context.Context, session, id string) (string, error) { return keeperPassword(ctx, session, id) },
		})
		return err
	})
}

func main() { extensionsdk.Main() }

type Picture

type Picture struct {
	Image string
	Model string
	Cost  *float64
	Extra map[string]any
}

A picture made: a URL, a data URL or a path of this computer such as a file of the extension's data folder; the model that made it, the dollars it cost where known, and fields the agent reads, such as the prompt as the service revised it

type PlatformAct

type PlatformAct struct {
	// The chat: an app alone for its home chat, or app:chat by its id or name, with :thread after it; none for places
	Place string
	// abilities, places, post, edit, delete, react, unreact, typing, pin, unpin, thread, rename, topic, describe or history
	Action string
	// Message acted on: the one changed, taken back, marked or pinned, the one a thread starts under, the one history reads before; for
	// react and unreact the last one a person wrote in the chat when empty
	Message string
	// Text posted or put in place of a message, the emoji of a mark, the name of a thread or a topic
	Text string
	// Files posted, paths the grants of the manifest let the extension read; Voice posts one audio file as a voice message
	Files []string
	Voice bool
	// Messages history reads at most, 50 when zero and 200 at most
	Limit int
	// Longest it may take, 30 seconds when zero and 5 minutes at most
	Timeout time.Duration
}

What the extension does in a chat of a chat app

type PlatformActed

type PlatformActed struct {
	// The chat acted in, a thread or topic one started or found among them
	Place PlatformPlace
	// Ids of the messages posted, or of the message acted on
	Messages []string
	// What the app of the chat can do, as the actions name it, for abilities
	Abilities []string
	// Chats the extension may act in, for places
	Places []PlatformPlace
	// Messages written in the chat before, newest last, for history
	History []PlatformMessage
}

What came of it

type PlatformMessage

type PlatformMessage struct {
	ID string
	// Who wrote it, by name and by their id on the app, and whether a bot did
	From, FromID string
	Bot          bool
	Text         string
	Time         time.Time
}

A message written in a chat

type PlatformPlace

type PlatformPlace struct {
	// The app and what a person calls it, what names the chat in a request, its id and thread
	App, AppTitle, Place, Chat, Thread string
	// What the app calls it, and direct, group or channel where it tells
	Title, Kind string
	// It is the chat results go to when a delivery names the app alone
	Home bool
}

A chat of a chat app

type ProviderCall

type ProviderCall = protocolv1.ProviderCall

What a model provider and icebath tell each other of: a model it offers with its window, efforts and price; a tokenizer its models count with; the provider of a profile a request goes to; one request; the shape a reply must take; one part of a reply as it streams; the whole reply and the tokens it took; what readies a request; what one request is about

type ProviderError

type ProviderError struct {
	Status     int
	Message    string
	Kind       string
	RetryAfter time.Duration
	Type       string
	Code       string
}

Why a request failed as the provider said it, which icebath retries, falls back from or tells the person of as it does any provider's: its HTTP status, 0 for none; its words; what kind of failure it is, one of auth, rate_limit, quota, context_overflow, invalid_request, model_not_found, server, network, content_filter or empty_response, the status's when empty; the wait it asked for, and the type and code of its error

func (*ProviderError) Error

func (e *ProviderError) Error() string

type ProviderEvent

type ProviderEvent = protocolv1.ProviderEvent

What a model provider and icebath tell each other of: a model it offers with its window, efforts and price; a tokenizer its models count with; the provider of a profile a request goes to; one request; the shape a reply must take; one part of a reply as it streams; the whole reply and the tokens it took; what readies a request; what one request is about

type ProviderFormat

type ProviderFormat = protocolv1.ProviderFormat

What a model provider and icebath tell each other of: a model it offers with its window, efforts and price; a tokenizer its models count with; the provider of a profile a request goes to; one request; the shape a reply must take; one part of a reply as it streams; the whole reply and the tokens it took; what readies a request; what one request is about

type ProviderModel

type ProviderModel = protocolv1.ProviderModel

What a model provider and icebath tell each other of: a model it offers with its window, efforts and price; a tokenizer its models count with; the provider of a profile a request goes to; one request; the shape a reply must take; one part of a reply as it streams; the whole reply and the tokens it took; what readies a request; what one request is about

type ProviderPrepared

type ProviderPrepared = protocolv1.ProviderPrepared

What a model provider and icebath tell each other of: a model it offers with its window, efforts and price; a tokenizer its models count with; the provider of a profile a request goes to; one request; the shape a reply must take; one part of a reply as it streams; the whole reply and the tokens it took; what readies a request; what one request is about

type ProviderPrice

type ProviderPrice = protocolv1.ProviderPrice

What a model provider and icebath tell each other of: a model it offers with its window, efforts and price; a tokenizer its models count with; the provider of a profile a request goes to; one request; the shape a reply must take; one part of a reply as it streams; the whole reply and the tokens it took; what readies a request; what one request is about

type ProviderRequest

type ProviderRequest = protocolv1.ProviderRequest

What a model provider and icebath tell each other of: a model it offers with its window, efforts and price; a tokenizer its models count with; the provider of a profile a request goes to; one request; the shape a reply must take; one part of a reply as it streams; the whole reply and the tokens it took; what readies a request; what one request is about

type ProviderResponse

type ProviderResponse = protocolv1.ProviderResponse

What a model provider and icebath tell each other of: a model it offers with its window, efforts and price; a tokenizer its models count with; the provider of a profile a request goes to; one request; the shape a reply must take; one part of a reply as it streams; the whole reply and the tokens it took; what readies a request; what one request is about

type ProviderRoute

type ProviderRoute = protocolv1.ProviderRoute

What a model provider and icebath tell each other of: a model it offers with its window, efforts and price; a tokenizer its models count with; the provider of a profile a request goes to; one request; the shape a reply must take; one part of a reply as it streams; the whole reply and the tokens it took; what readies a request; what one request is about

type ProviderTokenizer

type ProviderTokenizer = protocolv1.ProviderTokenizer

What a model provider and icebath tell each other of: a model it offers with its window, efforts and price; a tokenizer its models count with; the provider of a profile a request goes to; one request; the shape a reply must take; one part of a reply as it streams; the whole reply and the tokens it took; what readies a request; what one request is about

type ProviderUsage

type ProviderUsage = protocolv1.ProviderUsage

What a model provider and icebath tell each other of: a model it offers with its window, efforts and price; a tokenizer its models count with; the provider of a profile a request goes to; one request; the shape a reply must take; one part of a reply as it streams; the whole reply and the tokens it took; what readies a request; what one request is about

type Question

type Question struct {
	// Key of its answer, stable within the set; its place in the set, from 1, when empty
	ID string
	// Short heading of the question, and the question itself
	Header, Text string
	// Choices to pick from as shown, the recommended one first; none for an open question, which takes typed text
	Choices []string
	// Any number of the choices may be picked
	Many bool
	// The answer is a secret, such as a password: masked as it is typed, never shown again, and never logged or kept by icebath
	Secret bool
}

A question to the person of a session, one of a set AskUser asks at once

type Recognizer

type Recognizer struct {
	Name  string
	Title string
	About string
	Needs []string
	// Languages it hears as BCP 47 codes, any when none, which a person picks from on its page
	Languages []string
	// Models a person can pick, and the one it hears with when none is picked
	Models  []SpeechModel
	Default string
	// It runs elsewhere, so silence is trimmed from a recording before it is sent
	Cloud bool
	// Most bytes and the longest audio one file it is sent holds, a longer recording cut at its pauses; 25 MB and any length when zero
	MaxBytes  int64
	MaxLength time.Duration
	// Text of one audio file
	Transcribe func(ctx context.Context, speech Speech) (Transcript, error)
	// Opens a live transcription of 16 kHz 16 bit little endian mono PCM, the words it hears told through hearing as they come; nil for a
	// recognizer that transcribes whole files only
	Listen func(ctx context.Context, listening Listening, hearing *Hearing) (Listener, error)
	// It hears where the speaker stopped and says so with Hearing.Stopped
	Endpoints bool
}

Service that turns speech into text beside icebath's own, picked as Speech to text under Voice and heard in voice mode and the voice messages of chat apps. It transcribes files whole with Transcribe; with Listen it hears speech as it is spoken, telling icebath the words as it hears them, interim ones replaced by final ones, and with Endpoints where the speaker stopped, which ends the recording there rather than at the silence the microphone hears. A whole extension:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		_, err := host.Register(extensionsdk.Recognizer{Name: "scribe", Title: "Scribe", Needs: []string{"SCRIBE_KEY"},
			Languages: []string{"en", "de"}, Cloud: true, MaxBytes: 50 << 20, Endpoints: true,
			Transcribe: func(ctx context.Context, speech extensionsdk.Speech) (extensionsdk.Transcript, error) {
				return transcribe(ctx, host, speech)
			},
			Listen: func(ctx context.Context, listening extensionsdk.Listening, hearing *extensionsdk.Hearing) (extensionsdk.Listener, error) {
				return &stream{model: load(listening.Language), hearing: hearing}, nil
			}})
		return err
	})
}

// Each piece of 16 kHz PCM is heard as it comes: the words so far as interim ones, a pause ending them as final ones
func (s *stream) Push(pcm []byte) error {
	words, paused := s.model.Accept(pcm)
	if !paused {
		s.hearing.Interim(words)
		return nil
	}
	s.hearing.Final(words)
	if s.model.Silent() {
		s.hearing.Stopped()
	}
	return nil
}

func (s *stream) Finish(context.Context) (extensionsdk.Transcript, error) {
	s.hearing.Final(s.model.Flush())
	return extensionsdk.Transcript{}, nil
}

func (s *stream) Close() { s.model.Free() }

func main() { extensionsdk.Main() }

A transcript of Finish with no text takes the final words told. icebath feeds the audio in order, one feed at a time, and gives a live transcription up by closing it; a module hears between icebath's feeds, as a program does

type RedactionPattern

type RedactionPattern struct {
	// Name of the pattern among those of the extension, and what it masks as a person reads it
	Name, Title string
	Expr        string
}

A pattern added to what icebath masks in its logs, its debug reports and what leaves this computer, such as the keys of a service only the extension knows. It runs after what icebath masks itself, so it only ever masks more, and stays in force while the extension is installed and on, from icebath's start on and through restarts of the extension's code. Adding one is a matter of trust, as it can hide parts of what icebath writes down, so the manifest grants the kind:

grants:
  kinds: [redaction]

Expr is a regular expression of Go's syntax at most 256 characters long, every match of which starts with the same 3 characters or more, which icebath looks for before it runs the pattern; a match is masked only from 8 to 512 bytes long and holding no space. A pattern icebath refuses is listed in the doctor with why. A whole extension that masks the keys of a build service:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		_, err := host.Register(extensionsdk.RedactionPattern{Name: "build-keys", Title: "Key of the build service",
			Expr: `bld_[A-Za-z0-9]{24,}`})
		return err
	})
}

func main() { extensionsdk.Main() }

type Reference

type Reference struct {
	// Word after the @: a lower case letter, then lower case letters, digits, dashes and underscores
	Prefix string
	// What a reference with it attaches, a short phrase completion shows beside it
	About string
	// The prefix as a person types it, such as @jira:PROJ-12; @prefix: when empty
	Example string
	// Written alone, with no value after a colon
	Bare bool
	// Takes a line range after its value, as @file:main.go:10-20 does, which Referenced carries
	Lines bool
	// Variables it needs set before its references attach anything
	Needs []string
	// What the block it attaches holds, which marks it as icebath's own are: file, folder, git or page; any other for none of those
	Sign string
	// The text the reference attaches for the model, empty for nothing; an error says why it attaches nothing, which the person is told. A
	// text longer than the Budget it is asked with is cut to it
	Expand func(ctx context.Context, asked Referenced) (string, error)
	// Values that complete what is typed after the prefix, at most the limit; nil for a prefix that completes none. Answered within three
	// seconds, as the composer waits on it
	Complete func(ctx context.Context, asked Completing) ([]Completion, error)
	// References a word typed after an @ with no prefix matches, such as the issues whose titles hold it, each by the value written after
	// the prefix; nil for none
	Match func(ctx context.Context, asked Completing) ([]Completion, error)
}

Prefix a person writes after an @ in a message, such as @jira:PROJ-12, which attaches what Expand gives for the value written after it. icebath reads the references of every message the person writes, sends the model what each attaches after the message and tells the person of each that attached nothing and why; in the composer, it completes a value typed after the prefix with Complete and offers the references a word typed after an @ alone matches with Match. A whole extension:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		_, err := host.Register(extensionsdk.Reference{
			Prefix: "jira", About: "An issue of Jira", Example: "@jira:PROJ-12", Needs: []string{"JIRA_TOKEN"},
			Expand: func(ctx context.Context, asked extensionsdk.Referenced) (string, error) {
				token, _, err := host.Env(ctx, "JIRA_TOKEN")
				if err != nil {
					return "", err
				}
				response, err := host.Fetch(ctx, extensionsdk.Request{URL: "https://example.atlassian.net/rest/api/2/issue/" + asked.Value,
					Headers: map[string]string{"Authorization": "Bearer " + token}})
				if err != nil {
					return "", err
				}
				if response.Status != 200 {
					return "", fmt.Errorf("Jira answered %d for %s", response.Status, asked.Value)
				}
				return string(response.Body), nil
			},
			Complete: func(ctx context.Context, asked extensionsdk.Completing) ([]extensionsdk.Completion, error) {
				return []extensionsdk.Completion{{Value: strings.ToUpper(asked.Typed), Meta: "issue"}}, nil
			},
		})
		return err
	})
}

func main() { extensionsdk.Main() }

with a manifest that grants the host it reads and names the variable it needs:

grants:
  net: [example.atlassian.net]
needs: [JIRA_TOKEN]

type Referenced

type Referenced struct {
	// What follows the prefix, its quotes taken off; empty for a bare prefix
	Value     string
	SessionID string
	// Folder the session works in, and the surface the person wrote on, such as tui or telegram
	Cwd, Surface string
	// The reference as the person wrote it
	Raw string
	// First and last line of the range it names, 0 for none, of a prefix with Lines
	Start, End int
	// A person wrote it in a chat app, so what it attaches is to be held to what that person may reach
	Chat bool
	// Tokens the session's model takes in at once, and the most the reference may attach
	Window, Budget int
}

A reference as icebath asks for what it attaches

type Registration

type Registration interface {
	// contains filtered or unexported methods
}

Something an extension registers on icebath, such as a Tool or a Widget

type Request

type Request struct {
	// GET when empty
	Method  string
	URL     string
	Headers map[string]string
	Body    []byte
	// Longest it may take, 30 seconds when zero
	Timeout time.Duration
}

HTTP request icebath makes for the extension

type RequestChange

type RequestChange struct {
	Body    []byte
	Headers map[string]string
	Refuse  string
	Answer  []byte
	Status  int
	Reason  string
}

What a middleware makes of a request or an answer, nothing set leaving it as it is: a body in its place, headers set over its own, a refusal in words, or, for a request, an answer in its place with its status (200 when zero), a stream for a streamed request; Reason is said in the log

type Response

type Response struct {
	Status  int
	Headers map[string]string
	Body    []byte
}

type Role

type Role = protocolv1.Role

Role of the theme a span takes its color from, so widgets follow the theme

type ScheduledJob

type ScheduledJob struct {
	ID, Name, Kind, Expr, Schedule, Zone string
	Next                                 time.Time
	On                                   bool
}

A job as a scheduler is told of it: how its schedule is written (cron, interval or once, with the expression, the length between runs or the time of its one run), the schedule as a person reads it, the zone it is read in, when it runs next, zero for none, and whether it runs at all

type SecretStore

type SecretStore struct {
	Name  string
	Title string
	About string
	// Values by variable of the names a profile asks for, every one it has when none are named
	Fetch func(ctx context.Context, names []string) (map[string]string, error)
}

Store the variables of a profile can come from

type Section

type Section struct {
	ID string
	// Part of the prompt it goes in, TierTurn when unset
	Tier Tier
	// Text that never changes, or Build to make it on each turn
	Text  string
	Build func(ctx context.Context, turn Turn) (string, error)
	// Longest the text may be, no bound when zero
	MaxChars int
}

Section of the agent's system prompt

type SessionWhere

type SessionWhere struct {
	Folder string
	// Root of the git repository the folder lies in and its branch, empty outside one
	GitRoot, GitBranch string
	// The folder is a worktree of the repository whose main checkout is named, rather than that checkout
	Worktree   bool
	Repository string
	// Project the folder lies in, by its id and name, and the project's main folder; empty for none
	ProjectID, Project, ProjectFolder string
	// What the person is told of a move, line by line, for MoveSession
	Lines []string
}

Where a session works

type SideAnswer

type SideAnswer struct {
	Text string
	// It was answered over the session's own request rather than a transcript of it
	Forked                               bool
	Input, Output, CacheRead, CacheWrite int64
}

What the agent answered to a side question, and the tokens it took

type SignInDetail

type SignInDetail struct {
	Name, Value string
}

One thing said of a sign-in, such as who it signs in as

type SignInFlow

type SignInFlow struct {
	// Kind of provider the account is of, the provider's settings by their names below it, and whether the person is on another computer
	// than icebath, whose browser can't come back to a loopback address of icebath's
	Provider string
	Settings map[string]string
	Remote   bool
	// contains filtered or unexported fields
}

One sign-in as it runs, handed to the Run of a SignInMethod: what it says and shows goes with the next step, and Ask, Browser and Code wait for the person or the browser

func (*SignInFlow) Ask

func (f *SignInFlow) Ask(ctx context.Context, question string, secret bool) (string, error)

Asks the person a question, masked when secret, and answers what they typed

func (*SignInFlow) Browser

func (f *SignInFlow) Browser(ctx context.Context, listen, state string) (string, error)

Has icebath listen for the browser at the loopback address, such as http://127.0.0.1:43827/callback, or http://127.0.0.1:0/callback for any port, and check it comes back carrying the state given; the address icebath listens at, which the address to open names as its redirect

func (*SignInFlow) Code

func (f *SignInFlow) Code(ctx context.Context) (string, error)

Waits for the browser to come back to the address Browser listens at, answering the code it came back with. Show the address to open before it

func (*SignInFlow) Say

func (f *SignInFlow) Say(lines ...string)

Says lines to the person with the next step

func (*SignInFlow) Show

func (f *SignInFlow) Show(link, code string)

Shows the address to open and the code to type there, empty for none, with the next step

type SignInGrant

type SignInGrant struct {
	APIKey   string
	Identity string
	Expires  time.Time
	Kept     map[string]string
	Refused  string
}

What a sign-in granted: the key the account's requests carry, who signed in, when the key stops working, zero for never, and what the extension keeps of it to renew it. Refused, on a renewal, is why it could not be renewed, so the person signs in again

type SignInHeld

type SignInHeld struct {
	APIKey   string
	Kept     map[string]string
	Provider string
	Settings map[string]string
}

A sign-in an account keeps: its key, what the extension kept of it, the kind of provider and the provider's settings

type SignInMethod

type SignInMethod struct {
	// Name among the sign-ins of the extension, and what a person calls it as a way to connect
	Name  string
	Title string
	About string
	// Kinds of provider whose accounts it signs in, by their names
	Providers []string
	// Signs an account in, the flow saying and asking what it needs; what it grants
	Run func(ctx context.Context, flow *SignInFlow) (*SignInGrant, error)
	// Renews what it granted before its key expires; a grant with Refused set for a sign-in that must be made again. Nil for none
	Renew func(ctx context.Context, held SignInHeld) (*SignInGrant, error)
	// Who a sign-in is and whether it still holds, as a person checks it: what it says of it, and why it ended, empty while it holds. Nil
	// for none
	Check func(ctx context.Context, held SignInHeld) ([]SignInDetail, string, error)
	// Ends a sign-in at the provider as its account goes; nil for none
	SignOut func(ctx context.Context, held SignInHeld) error
}

Way to sign the accounts of the providers it names in, which a person picks among the ways to connect an account in /providers. Its Run drives the sign-in one step at a time through the SignInFlow it is handed: what it says, the address to open and the code to type there, what it asks the person, and the loopback address icebath listens at for the browser to come back to. What it grants is kept by icebath in the account, never in the extension's files, and handed back to Renew, Check and SignOut. Holding the sign-ins of a person's accounts is a matter of trust, so the manifest grants the kind signin:

grants:
  kinds: [signin]
  net: [login.mycompany.example]

A whole extension, a sign-in by a device code that hands out keys of the provider mymodels:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		_, err := host.Register(extensionsdk.SignInMethod{
			Name: "sso", Title: "My Company sign-in", Providers: []string{"mymodels"},
			Run: func(ctx context.Context, flow *extensionsdk.SignInFlow) (*extensionsdk.SignInGrant, error) {
				device, err := startDevice(ctx, host)
				if err != nil {
					return nil, err
				}
				flow.Show(device.Link, device.Code)
				flow.Say("Approve the sign-in in your browser.")
				token, err := pollDevice(ctx, host, device)
				if err != nil {
					return nil, err
				}
				return &extensionsdk.SignInGrant{APIKey: token.Access, Identity: token.Email, Expires: token.Expires,
					Kept: map[string]string{"refresh": token.Refresh}}, nil
			},
			Renew: func(ctx context.Context, held extensionsdk.SignInHeld) (*extensionsdk.SignInGrant, error) {
				token, err := refresh(ctx, host, held.Kept["refresh"])
				if err != nil {
					return &extensionsdk.SignInGrant{Refused: "My Company refused to renew the sign-in."}, nil
				}
				return &extensionsdk.SignInGrant{APIKey: token.Access, Expires: token.Expires,
					Kept: map[string]string{"refresh": token.Refresh}}, nil
			},
		})
		return err
	})
}

func main() { extensionsdk.Main() }

type Skills

type Skills struct {
	Dir string
}

Folder of skills inside the extension's folder, each a folder holding a SKILL.md, loaded as <extension>:<skill>

type Span

type Span struct {
	Text      string
	Role      Role
	Bold      bool
	Dim       bool
	Italic    bool
	Underline bool
	Inverse   bool
	// contains filtered or unexported fields
}

Run of text in one role of the theme and one style, text when no role is set

type Spawn

type Spawn struct {
	// What it is to do, self-contained, and the background it needs
	Goal, Context string
	// Toolsets it may use, of those the session is offered; every one a subagent may use when none
	Toolsets []string
	// Provider of the profile and model it runs on, the delegation's own placement for neither
	Provider, Model string
	// leaf, or orchestrator to let it start subagents of its own where the settings allow; leaf when empty
	Role string
	// JSON Schema its final answer must satisfy, nil for free text
	Schema map[string]any
	// Its result goes into the session too, so the agent goes on from it; to the extension alone otherwise
	Report bool
}

A subagent the extension starts in a session

type Spawned

type Spawned struct {
	// Its id, the delegation it is of, its own session while it runs, its goal, role and model
	ID, Delegation, Session, Goal, Role, Model string
	// queued, running, completed, failed, error, timeout or interrupted
	State string
	// Tool calls it started, the one it runs now and what it does
	ToolCalls   int
	Tool, Doing string
	Started     time.Time
	// It ended, and what it came to: its own final report, or why it failed
	Done           bool
	Summary, Error string
	// Its model calls, how long it ran, its tokens, and the dollars it cost, nil when not known
	APICalls      int
	Duration      time.Duration
	Input, Output int64
	Cost          *float64
}

A subagent the extension started, as it stands

type SpeakRequest

type SpeakRequest struct {
	Text string
	// Format asked for, such as mp3, ogg or wav; empty for a stream, which is PCM
	Format string
	// From 0.25 to 4, the voice's own when zero
	Speed float64
	// How to speak, for a voice that takes directions; the voice the call picked, else the one the person picked, the voice's own when empty;
	// the model the person picked, the voice's own when empty
	Instructions string
	Voice        string
	Model        string
}

Text to speak and how

type Speech

type Speech struct {
	Audio    []byte
	Format   string
	Model    string
	Language string
	Prompt   string
}

What a recognizer transcribes: the bytes of an audio file in the format its extension names, and the model, language and hint text asked for

type SpeechModel

type SpeechModel struct {
	ID    string
	Title string
	About string
}

Model of a voice or a recognizer: its id, the name a person knows it by, and what it is good at

type Subagent

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

What a turn the extension runs tells icebath and asks of the person as it goes, safe to use from any goroutine of the turn

func (*Subagent) Approve

func (s *Subagent) Approve(ctx context.Context, action SubagentAction) error

Asks the person's leave for the action as the session's rules and approvals decide it, nil when it may go ahead, else why not as the subagent reads it

func (*Subagent) Ask

func (s *Subagent) Ask(ctx context.Context, questions []SubagentQuestion) (map[string][]string, error)

Asks the person the questions, answering what they picked or typed by the id of each, none for one skipped

func (*Subagent) Doing

func (s *Subagent) Doing(text string)

Tells what the turn is doing, which shows the person it is alive

func (*Subagent) Guidance

func (s *Subagent) Guidance() []string

Takes the guidance the person sent since it was last taken, each text as the subagent reads it; none when none waits

func (*Subagent) Progress

func (s *Subagent) Progress(step, tool, text string)

Tells what the step of the id does now, such as the last line a command printed

func (*Subagent) Step

func (s *Subagent) Step(id, tool, arguments string)

Tells a step the turn began, such as a command it runs, by an id of its own, the tool and its arguments as JSON

func (*Subagent) Stepped

func (s *Subagent) Stepped(id, tool, result string, failed bool)

Tells what came of the step of the id once it ended, and whether it failed

func (*Subagent) Think

func (s *Subagent) Think(text string)

Tells thinking of the turn as it comes

func (*Subagent) Write

func (s *Subagent) Write(text string)

Writes text of the turn's answer as it comes

type SubagentAction

type SubagentAction struct {
	Key         string
	Description string
	Target      string
	Edits       []SubagentEdit
}

An action a subagent asks the person's leave for: the name a lasting answer is remembered under, what it is, what would run or change, and the changes to files it makes

type SubagentEdit

type SubagentEdit struct {
	Path          string
	Before, After *string
}

A change to a file an action makes: what it holds before, nil for a file not there, and what it would hold, nil for one that goes

type SubagentQuestion

type SubagentQuestion struct {
	ID      string
	Header  string
	Text    string
	Choices []string
	Many    bool
	Secret  bool
}

A question a subagent asks the person: its id in the set, a short heading and the question, the choices to pick from, none for one that takes typed text, whether many may be picked, and whether the answer is a secret

type SubagentResult

type SubagentResult struct {
	Answer string
	Usage  SubagentUsage
	Model  string
}

What a turn ended with: its answer, the tokens it took and the model that served it

type SubagentTurn

type SubagentTurn struct {
	Route     string
	Session   string
	Model     string
	Messages  []*Message
	Folder    string
	MaxTokens int
}

One turn of a subagent the extension runs: the route of its own it runs on, as its place labelled it, the subagent's session, the model asked for, the messages so far, newest last, the folder of this computer the subagent works in, and the most tokens the reply may hold, none when zero

type SubagentUsage

type SubagentUsage struct {
	Input, CacheRead, CacheWrite, Output, Reasoning int64
}

Tokens a turn took

type Subscription

type Subscription struct {
	// Name of the extension that emits it and the event, as <extension>:<event>
	Event string
	// Runs for each delivery, the payload as the extension that emitted it encoded it, JSON for one written with this library
	Handler func(ctx context.Context, payload json.RawMessage) error
}

Event the extension hears from the extensions of its profile

type TaskCall

type TaskCall struct {
	// Session of the profile the call is for, whose usage counts it; none for a call of the extension's own
	SessionID string
	Messages  []TaskMessage
	// Most tokens of the answer, the model's own cap when zero
	MaxTokens int
	// How varied the answer is, from 0, the model's own when nil
	Temperature *float64
	// JSON schema object the answer follows, a structured answer; text when nil
	Schema map[string]any
	// How hard the model thinks over the task's own effort, such as none for an answer at once; the task's own when nil
	Effort *string
	// Longest the call may take, 2 minutes when zero and 10 at most
	Timeout time.Duration
}

One call of a helper task

type TaskImage

type TaskImage struct {
	Mime string
	Data []byte
}

A picture of a message: its type, such as image/png, and its bytes

type TaskMessage

type TaskMessage struct {
	Role   string
	Text   string
	Images []TaskImage
}

One message of a call: who says it, TaskSystem, TaskUser (when empty) or TaskAssistant, what it says, and the pictures it is about

type TaskReply

type TaskReply struct {
	Text, Finish, Provider, Model string
	Usage                         TaskUsage
	// Dollars the answer cost, nil where the price of its model is not known
	Cost *float64
	// Why the route tried first failed before another answered, empty when the first answered
	FellBack string
}

What a helper task answered: the text, why the model stopped, the provider and model that answered and what the call took

type TaskUsage

type TaskUsage struct {
	Input, CacheRead, CacheWrite, Output, Reasoning int64
}

Tokens a call took: those it was sent, those of them read from or written to the provider's cache, those it answered with, and those of the answer the model thought with

type Terminal

type Terminal struct {
	// Value of the place setting that picks it, in lower case, what a person calls it, and where commands run as the agent is told it,
	// such as "a Kubernetes pod (Linux)"
	Name  string
	Title string
	About string
	Where string
	// Commands run off this computer, its files are rooted away from this computer's, and it keeps commands away from this computer, so
	// the agent's risky commands run there without asking the person: a word the person relies on, given only of a place that holds it
	Remote    bool
	Container bool
	Isolated  bool
	// Where the place keeps the files of the profile it is handed, such as ~/.icebath, empty for a place that sees this computer's paths,
	// and the folder commands start in when the working folder names none
	Home string
	Cwd  string
	// Variables holding its own credentials, kept from every command of every place, and those it needs set before it can run
	Secrets []string
	Needs   []string
	// Where the place sees the session's folder mounted from this computer, for a place that runs on this computer; empty for none. A
	// place that mounts it keeps commands away from this computer no more, so risky ones need approval again
	Mount string
	// The sessions of a profile working in one folder share one environment rather than each having its own
	Shared bool
	// A folder under the home of this computer stands for the same one under the home there, as over SSH
	Remaps bool
	// Key of a setting of the extension naming the image its sandboxes start from, empty for a place of no image
	Image string
	// The place can't hand a process its stdin, so icebath puts stdin into the script; and sudo is tried there without a password before
	// the person is asked for one
	Heredoc bool
	Sudo    bool
	// What the environments of the place can do beside running commands, each declared here and implemented by every environment Create
	// makes: move files itself (TerminalFiles), give an argv of this computer that runs inside it (TerminalStreamer, for an extension
	// that runs as a program), tell from a command's output that its sandbox was removed and make it again (TerminalRecoverer), stop an
	// idle sandbox kept between sessions rather than remove it (TerminalIdler), and ready itself before each command (TerminalWaker)
	Files    bool
	Streams  bool
	Recovers bool
	Idles    bool
	Wakes    bool
	// Makes an environment for the key, finding again the one it keeps for the key where it keeps sandboxes between sessions
	Create func(ctx context.Context, spec TerminalSpec) (*TerminalMade, error)
	// Readies the place for the profile ahead of its first command, from the folder a window works in, saying how it goes line by line,
	// and what it does, a sentence; nil for a place with nothing to ready
	Prepare func(ctx context.Context, dir string, say func(line string)) error
	Readies string
	// What was checked of what the place needs, as its page in /sandbox lists it, and why it can't run, from the folder a window works
	// in; recent lets an answer a few seconds old do. Nil for a place whose needs are all there is to check
	Doctor func(ctx context.Context, dir string, recent bool) ([]TerminalCheck, error)
	// A default image that changed under sandboxes still running the one before, nil for none waiting; and what keeps them on the image
	// they run or with approve moves them to the new one, answering the image chosen. Both nil for a place of no image
	Switch func(ctx context.Context) (*TerminalChange, error)
	Decide func(ctx context.Context, change TerminalChange, approve bool) (string, error)
	// What the place left on its service that outlives icebath, for an uninstall, and what stops or removes one of them; both nil for a
	// place that leaves nothing. A sandbox that runs and keeps files is two: the one that runs, which Remove stops, and its files
	Left   func(ctx context.Context) ([]TerminalLeftover, error)
	Remove func(ctx context.Context, id string) error
	// Work left as icebath stops, once every environment is gone; nil for none
	Sweep func(ctx context.Context) error
}

Place the agent's commands run, such as a sandbox service or a machine of another network, which a person picks in /sandbox as one of icebath's own. icebath runs every command there through a shell of its own: it takes a snapshot of the login shell once, carries the folder and the exports from one command to the next, keeps the profile's files the commands need in the place's home, and runs the background jobs of the agent inside it, so the place only starts bash with a script and hands back what it writes. Running the agent's commands is a matter of trust, so the manifest grants the kind terminal, which the person agrees to as the extension installs:

grants:
  kinds: [terminal]
  net: [api.boxes.example]
needs: [BOXES_TOKEN]

An extension that stops while a command runs ends the command with words that say so, and an environment it no longer knows once it started again is made anew under its key, which a place that keeps sandboxes between sessions finds its sandbox again by. As the extension unloads, every environment it still holds is cleaned up and every command it runs is stopped. A whole extension, whose service answers a command once it ended:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		call := func(ctx context.Context, method, path string, body, out any) error {
			token, _, _ := host.Env(ctx, "BOXES_TOKEN")
			data, _ := json.Marshal(body)
			response, err := host.Fetch(ctx, extensionsdk.Request{Method: method, URL: "https://api.boxes.example" + path,
				Headers: map[string]string{"Authorization": "Bearer " + token}, Body: data, Timeout: 10 * time.Minute})
			if err != nil {
				return err
			}
			if response.Status >= 300 {
				return fmt.Errorf("Boxes answered %d: %s", response.Status, response.Body)
			}
			if out == nil {
				return nil
			}
			return json.Unmarshal(response.Body, out)
		}
		_, err := host.Register(extensionsdk.Terminal{
			Name: "boxes", Title: "Boxes", About: "A sandbox on your Boxes account", Where: "a Boxes sandbox (Linux)",
			Remote: true, Container: true, Isolated: true, Home: "~/.icebath", Needs: []string{"BOXES_TOKEN"},
			Create: func(ctx context.Context, spec extensionsdk.TerminalSpec) (*extensionsdk.TerminalMade, error) {
				var box struct{ ID, Home string }
				if err := call(ctx, "PUT", "/boxes/"+url.PathEscape(spec.Key), nil, &box); err != nil {
					return nil, err
				}
				return &extensionsdk.TerminalMade{Environment: boxEnv{id: box.ID, call: call}, Home: box.Home}, nil
			},
		})
		return err
	})
}

type boxEnv struct {
	id   string
	call func(ctx context.Context, method, path string, body, out any) error
}

func (b boxEnv) Run(ctx context.Context, run extensionsdk.TerminalRun) (extensionsdk.TerminalProcess, error) {
	var done struct {
		Output string
		Code   int
	}
	err := b.call(ctx, "POST", "/boxes/"+b.id+"/exec", map[string]any{"script": run.Script, "login": run.Login,
		"stdin": string(run.Stdin), "env": run.Env, "timeout": run.Timeout.Seconds()}, &done)
	if err != nil {
		return nil, err
	}
	return extensionsdk.TerminalEnded([]byte(done.Output), done.Code), nil
}

func (b boxEnv) Cleanup(ctx context.Context, force bool) error {
	return b.call(ctx, "DELETE", "/boxes/"+b.id, nil, nil)
}

func main() { extensionsdk.Main() }

type TerminalChange

type TerminalChange struct {
	Current   string
	Target    string
	Sandboxes []string
}

A default image that changed under sandboxes still running the one before: the image most of them run, the one they would move to, and the sandboxes running another

type TerminalCheck

type TerminalCheck struct {
	OK      bool
	Label   string
	State   string
	Detail  string
	Fix     string
	Setting string
}

One thing checked of what a place needs: whether it is fine, what was checked, how it stands in a word or two, what was found, what to do about it and the key of a setting of the extension that fixes it

type TerminalEnvironment

type TerminalEnvironment interface {
	// Starts bash with the script, as a login shell when the run says so, with its stdin and variables
	Run(ctx context.Context, run TerminalRun) (TerminalProcess, error)
	// Removes what it made, a sandbox kept between sessions too when force is set, and stops one kept otherwise
	Cleanup(ctx context.Context, force bool) error
}

One environment of a place: it runs bash with a script, and is cleaned up

type TerminalFiles

type TerminalFiles interface {
	Put(ctx context.Context, path string, data []byte, offset int64, mode fs.FileMode) error
	Get(ctx context.Context, path string, offset, limit int64) (data []byte, size int64, err error)
}

Environment of a place with Files, which moves files itself: writes the bytes into the file from the offset, made with the mode and the folders above it made, and reads at most limit bytes of a file from the offset, answering them with the size of the whole file

type TerminalIdler

type TerminalIdler interface {
	Idle(ctx context.Context) error
}

Environment of a place with Idles: stops its sandbox kept between sessions as it went idle, rather than removing it

type TerminalLeftover

type TerminalLeftover struct {
	ID    string
	Title string
	Where string
	Runs  bool
	Kept  string
}

One thing a place left on its service that outlives icebath: what Remove names it by, what it is and where, whether it runs and costs while it does, and why it stays whatever the uninstall, empty when it goes

type TerminalMade

type TerminalMade struct {
	Environment TerminalEnvironment
	// Folder commands start in, the home of its user, and its folder of temporary files, /tmp when empty
	Cwd  string
	Home string
	Temp string
	// It keeps its files between sessions, it is the session's own, and the file tools may read and write its files on this computer
	Persistent    bool
	SessionScoped bool
	HostFiles     bool
	// The argv its TerminalStreamer gives joins the rest into one line for a remote login shell
	Joined bool
}

An environment made, and what icebath is told of it

type TerminalProcess

type TerminalProcess interface {
	io.Reader
	// Its exit code, once it ended and its output was read to the end
	Wait() int
	// Stops it and what it started, at once with no grace when force is set
	Kill(force bool) error
}

A command that runs: what it writes, its standard output and error as one, read until io.EOF once it ended

func TerminalEnded

func TerminalEnded(output []byte, code int) TerminalProcess

A command that already ended, its whole output and its code, for a place whose service answers a command once it ended

type TerminalRecoverer

type TerminalRecoverer interface {
	Recover(ctx context.Context, output string) (bool, error)
}

Environment of a place with Recovers: whether the output of a command says the sandbox was removed behind the place's back, made again when it does

type TerminalRun

type TerminalRun struct {
	Script  string
	Login   bool
	Timeout time.Duration
	Stdin   []byte
	Env     map[string]string
}

One command: the script bash runs, as a login shell when Login is set, how long it may run, what it reads on its stdin, none when empty, and the variables handed it over those of the environment

type TerminalSpec

type TerminalSpec struct {
	// Key it is kept under, of a session or of every session of the profile, the same each time it is made for them, and the session
	Key     string
	Session string
	// Folder commands start in, the folder of this computer mounted into it, and the folder of this computer the session works in
	Cwd     string
	HostCwd string
	Folder  string
	// Longest a command runs when it names no time
	Timeout time.Duration
	// Made only to see where commands run, cleaned up right after
	Probe bool
	// What the sandbox settings ask for: cores, megabytes of memory and of disk, and files kept from one session to the next
	CPU        float64
	Memory     int
	Disk       int
	Persistent bool
	// Image its sandbox starts from as the settings of the run name it, the value of the setting Image names; empty for the place's own
	Image string
}

What an environment is made for

type TerminalStreamer

type TerminalStreamer interface {
	Prefix(ctx context.Context, user string, interactive bool) (argv []string, env map[string]string, err error)
}

Environment of a place with Streams: the argv of this computer that runs the rest inside it as the user, its stdin kept open when interactive, and the variables of the profile that argv's program reads beside those every command of the profile gets

type TerminalWaker

type TerminalWaker interface {
	Wake(ctx context.Context) (recreated bool, err error)
}

Environment of a place with Wakes: readies it before each command, such as starting a stopped sandbox again, whether it was gone and was made again

type Tier

type Tier = protocolv1.Tier

Part of the system prompt a section goes in, the parts joined in this order so what changes least comes first

type Tool

type Tool struct {
	Name    string
	Toolset string
	// Name the app shows, and what the tool lets the agent do in a phrase for a person
	Title string
	About string
	// What the model reads of the tool, and the JSON schema object of its arguments
	Description string
	Parameters  map[string]any
	// Variables that must be set for the tool to be offered
	Needs []string
	// Only reads, so a call stopped or run again changes nothing
	ReadOnly bool
	// What it returns comes from outside, such as a web page, so the model reads it as data
	Untrusted bool
	// It runs commands or code the model writes, such as a script, so a session is offered it only while it is offered the terminal
	RunsCode bool
	// Longest a call may take, the extension's call limit when zero
	Timeout time.Duration
	// Whether the tool can run now, asked before it is offered, nil for always
	Check   func(ctx context.Context) bool
	Handler func(ctx context.Context, call ToolCall) (string, error)
}

Tool the model can call

type ToolCall

type ToolCall struct {
	// Arguments as the model sent them
	Args      map[string]any
	CallID    string
	SessionID string
	// Working folder of the session
	Cwd string
}

One call of a tool

func (ToolCall) Decode

func (c ToolCall) Decode(into any) error

Reads the arguments into a value as encoding/json reads an object, such as a struct with json tags

type ToolChange

type ToolChange struct {
	Args           map[string]any
	Refuse, Reason string
}

What a middleware makes of a tool call, nothing set leaving it as it is: arguments in place of its own, or a refusal the model is told

type ToolUse

type ToolUse struct {
	Tool                    string
	Args                    map[string]any
	SessionID, CallID, Turn string
}

A tool call: the tool, the arguments it runs on, the session, the call and the turn it is of

type Transcript

type Transcript struct {
	Text     string
	NoSpeech bool
}

Text heard, NoSpeech set when nothing was said

type Turn

type Turn struct {
	SessionID string
	Cwd       string
	Provider  string
	Model     string
	Platform  string
}

The turn a prompt section is built for

type UpscaleRequest

type UpscaleRequest struct {
	Image  string
	Factor int
	Prompt string
	Model  string
}

One picture to enlarge by one of the service's factors, what it shows, which some upscalers sharpen by, and the model picked

type Video

type Video struct {
	URL, Path     string
	Data          []byte
	Mime          string
	Model, Aspect string
	Duration      int
	Cost          *float64
	Extra         map[string]any
}

A video made: at an address, at a path of this computer such as a file of the extension's data folder, or as its bytes of the type Mime; with the model and aspect it was made with, its length in seconds, what it cost in dollars where known and fields the agent reads

type VideoModel

type VideoModel struct {
	ID, Title, About, Speed, Price string
	Takes                          *VideoTakes
}

Model of a video service: its id, the name a person knows it by, what it is good at, how fast it is, what it costs, and what it takes when that differs from the service's own

type VideoRequest

type VideoRequest struct {
	Prompt, Model, Image         string
	References                   []string
	Duration                     *int
	Aspect, Resolution, Negative string
	Audio                        *bool
	Seed                         *int64
	Upscale                      *bool
}

One video to make: the prompt, the model picked (the default when empty), a still to animate and reference pictures, each an address or a data URL, and what the call asked of its length in seconds, shape and sound, nil where it asked nothing

type VideoService

type VideoService struct {
	Name  string
	Title string
	About string
	// Variables it needs set before it can make videos
	Needs []string
	// What its models take when a model says nothing of its own
	Takes VideoTakes
	// Models a person can pick, and the one it makes videos with when none is picked
	Models  []VideoModel
	Default string
	// Makes one video, telling how far it got through progress, a percent from 0 to 100 or below 0 when not known, and what it does now
	Generate func(ctx context.Context, request VideoRequest, progress func(percent float64, status string)) (Video, error)
}

Service that makes videos for the agent beside icebath's own, picked under Videos, the sibling of ImageService. A video takes minutes: icebath starts it, asks how it stands every few seconds and stops it by ending the context Generate is handed, which runs on in the extension between those asks. A whole extension:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		_, err := host.Register(extensionsdk.VideoService{Name: "clipper", Title: "Clipper", Needs: []string{"CLIPPER_KEY"},
			Takes: extensionsdk.VideoTakes{Modalities: []string{"text", "image"}, Aspects: []string{"16:9", "9:16"},
				MinDuration: 4, MaxDuration: 10},
			Generate: func(ctx context.Context, request extensionsdk.VideoRequest,
				progress func(percent float64, status string)) (extensionsdk.Video, error) {
				key, _, err := host.Env(ctx, "CLIPPER_KEY")
				if err != nil {
					return extensionsdk.Video{}, err
				}
				job, err := submit(ctx, host, key, request)
				for err == nil && !job.Done {
					progress(job.Percent, "Clipper is rendering the video")
					time.Sleep(5 * time.Second)
					job, err = check(ctx, host, key, job.ID)
				}
				if err != nil {
					return extensionsdk.Video{}, err
				}
				return extensionsdk.Video{URL: job.URL, Duration: job.Seconds}, nil
			}})
		return err
	})
}

func main() { extensionsdk.Main() }

The manifest names the hosts it reaches (grants.net) and the variables it needs; a video made is answered as an address icebath fetches it from, a file the extension wrote in its data folder, or its bytes

type VideoTakes

type VideoTakes struct {
	// What it makes videos from: text, image, reference; text alone when none
	Modalities []string
	// Aspect ratios such as 16:9 and resolutions such as 720p it makes, icebath's own when none
	Aspects, Resolutions []string
	// Shortest and longest video in seconds, not known when zero
	MinDuration, MaxDuration int
	// It takes the audio switch, makes audio with every video whatever is asked, takes a negative prompt, a seed and the upscale pass
	Audio, AudioAlways, Negative, Seed, Upscale bool
	// Most reference pictures it takes
	References int
	// Lines icebath's video tool and pickers add for it
	Notes []string
}

What a video model takes, which shapes the arguments icebath's video tool offers the model

type Voice

type Voice struct {
	Name  string
	Title string
	About string
	Needs []string
	// Most characters one request takes, which longer text is split under; icebath's own limit when zero
	Limit int
	// Formats of the files it writes, the first the one it writes when asked for one it does not; any format it is asked for when none
	Formats []string
	// Models a person can pick, and the one it speaks with when none is picked
	Models  []SpeechModel
	Default string
	// Speech of the text as one file, in the format asked for or another it names
	Speak func(ctx context.Context, request SpeakRequest) (audio []byte, format string, err error)
	// Speaks a sentence as 16 bit little endian mono PCM at Rate, each piece handed to send as it is made; nil for a voice that writes whole
	// files only. send waits while icebath holds as much as it plays ahead, and fails once icebath stopped listening
	Stream func(ctx context.Context, request SpeakRequest, send func(pcm []byte) error) error
	Rate   int
	// One page of the voices it speaks with that a search finds, nil for a voice that lists none; with Picks the model may pick one of them
	// for each call
	Voices func(ctx context.Context, search VoiceSearch) (VoicePage, error)
	Picks  bool
	// Loads what it keeps between requests as speech turns on, and lets go of it once nothing holds speech; nil for a voice that keeps nothing
	Warm, Release func(ctx context.Context) error
}

A voice that reads text aloud beside icebath's own, picked as Speech under Voice and heard in voice mode, the text_to_speech tool and the voice messages of chat apps. It writes whole files with Speak; with Stream it hands a sentence over as 16 bit little endian mono PCM in pieces as it makes them, so speech starts before the sentence is made; with Voices it lists the voices it speaks with, which a person picks from on its page and, with Picks, the model picks from for each call. A whole extension:

func init() {
	extensionsdk.Register(func(host extensionsdk.Host) error {
		_, err := host.Register(extensionsdk.Voice{Name: "narrator", Title: "Narrator", Needs: []string{"NARRATOR_KEY"},
			Formats: []string{"mp3"}, Rate: 24000, Picks: true,
			Speak: func(ctx context.Context, request extensionsdk.SpeakRequest) ([]byte, string, error) {
				audio, err := synthesize(ctx, host, request, "mp3")
				return audio, "mp3", err
			},
			Stream: func(ctx context.Context, request extensionsdk.SpeakRequest, send func(pcm []byte) error) error {
				response, err := host.Fetch(ctx, speechRequest(host, request, "pcm_24000"))
				if err != nil {
					return err
				}
				for audio := response.Body; len(audio) > 0; audio = audio[min(len(audio), 9600):] {
					if err := send(audio[:min(len(audio), 9600)]); err != nil {
						return err
					}
				}
				return nil
			},
			Voices: func(ctx context.Context, search extensionsdk.VoiceSearch) (extensionsdk.VoicePage, error) {
				return voicesOf(ctx, host, search)
			}})
		return err
	})
}

func main() { extensionsdk.Main() }

The manifest names the hosts it reaches (grants.net) and the variables it needs. A sentence icebath stops hearing, as the person cuts the speech, ends the context Stream is handed and fails send; a module goes on making pieces between icebath's asks for them, as a program does

type VoiceEntry

type VoiceEntry struct {
	ID, Name  string
	Languages []string
	Gender    string
	Styles    []string
	Rate      int
	About     string
	Preview   string
}

One voice: the id a request names it by, the name a person knows it by, the languages it speaks, its gender, the styles it speaks in, the samples a second of its audio, what it is, and the address of a sample of it

type VoicePage

type VoicePage struct {
	Voices []VoiceEntry
	Next   string
	Total  int
}

One page of voices, the cursor of the next page, empty after the last, and how many voices the search finds in all, 0 when not known

type VoiceSearch

type VoiceSearch struct {
	Query, Language, Gender, Cursor string
	Size                            int
}

A search of the voices a voice speaks with: words of a name or description, a language as a BCP 47 code, a gender, the cursor of the page asked for, empty for the first, and the most voices the page holds

type Wake

type Wake struct {
	Phrase string
	// From 0 to 1, higher catching more
	Sensitivity float64
	// Frames over threshold in a row that fire
	Frames int
	// Phrases of the other profiles that listen, each heard too
	Profiles []WakePhrase
}

Wake settings a detector is made with

type WakeEngine

type WakeEngine struct {
	Name  string
	Title string
	About string
	Needs []string
	// Hears any phrase it is given, rather than those of its own model files
	Open bool
	// Detector of the wake settings, closed when icebath closes it, the engine is disposed or the extension unloads
	New func(ctx context.Context, wake Wake) (Hotword, error)
}

Engine that hears a wake word in 16 kHz mono speech

type WakePhrase

type WakePhrase struct {
	Profile string
	Phrase  string
}

type WebBackend

type WebBackend struct {
	// As the web search setting names it
	Name  string
	Title string
	About string
	// Variables it needs set before it counts as set up
	Needs   []string
	Search  func(ctx context.Context, query string, limit int) ([]Hit, error)
	Extract func(ctx context.Context, urls []string, format string) ([]Page, error)
}

Service that answers web searches, reads pages, or both

type Widget

type Widget[S any] struct {
	// Name of its slash command
	ID string
	// What the slash list says of it, and what a refused argument prints
	Help  string
	Usage string
	// ModeAmbient when unset
	Mode Mode
	// Where an ambient widget sits, ZoneTopRight when unset
	Zone Zone
	// Columns of its box, the app's choice when zero
	Width int
	// Interval the app refreshes it at, running Tick when set and rendering again, zero for input only. Shortest 100 ms
	Refresh time.Duration
	// First state from what followed the command, open false printing the usage. Nil opens it with the zero state
	Open func(ctx context.Context, argument string) (state S, open bool, err error)
	// Next state after a key of a modal widget, open false closing it. Nil for esc, q and ctrl+c to close it
	Input func(ctx context.Context, state S, key Key) (next S, open bool, err error)
	// Next state at each refresh, nil for a widget that only renders again
	Tick   func(ctx context.Context, state S) (next S, err error)
	Render func(ctx context.Context, frame WidgetFrame[S]) ([]Line, error)
}

View the terminal app shows by its slash command, its state of type S kept by the app between calls as JSON

type WidgetFrame

type WidgetFrame[S any] struct {
	Cols  int
	Rows  int
	State S
}

Size and state a widget renders for

type Zone

type Zone = protocolv1.Zone

Where an ambient widget sits

Directories

Path Synopsis
Package wire is the link between icebath and the code of an extension: frames of the protocol, each the size of its message as a varint and the message in binary on a program's standard input and output, both sides asking and answering the other at once
Package wire is the link between icebath and the code of an extension: frames of the protocol, each the size of its message as a varint and the message in binary on a program's standard input and output, both sides asking and answering the other at once

Jump to

Keyboard shortcuts

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