external

package
v0.23.1 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package external implements the JSON-RPC stdio protocol for external piglet extensions. Extensions are child processes that communicate via newline-delimited JSON on stdin/stdout.

Index

Constants

View Source
const (
	FilterAll            = "all"
	FilterBackgroundSafe = "background_safe"
)

Tool filter constants for HostListToolsParams.

View Source
const (
	MethodInitialize                  = "initialize"
	MethodShutdown                    = "shutdown"
	MethodCancelRequest               = "$/cancelRequest"
	MethodRegisterTool                = "register/tool"
	MethodRegisterCommand             = "register/command"
	MethodRegisterPromptSection       = "register/promptSection"
	MethodRegisterInterceptor         = "register/interceptor"
	MethodRegisterEventHandler        = "register/eventHandler"
	MethodRegisterShortcut            = "register/shortcut"
	MethodRegisterMessageHook         = "register/messageHook"
	MethodRegisterCompactor           = "register/compactor"
	MethodRegisterProvider            = "register/provider"
	MethodProviderStream              = "provider/stream"
	MethodProviderDelta               = "provider/delta"
	MethodCompactExecute              = "compact/execute"
	MethodToolExecute                 = "tool/execute"
	MethodCommandExecute              = "command/execute"
	MethodInterceptorBefore           = "interceptor/before"
	MethodInterceptorAfter            = "interceptor/after"
	MethodEventDispatch               = "event/dispatch"
	MethodShortcutHandle              = "shortcut/handle"
	MethodMessageHookOnMessage        = "messageHook/onMessage"
	MethodHostListTools               = "host/listTools"
	MethodHostExecuteTool             = "host/executeTool"
	MethodHostConfigGet               = "host/config.get"
	MethodHostConfigReadExt           = "host/config.readExtension"
	MethodHostAuthGetKey              = "host/auth.getKey"
	MethodHostChat                    = "host/chat"
	MethodHostAgentRun                = "host/agent.run"
	MethodHostConversationMessages    = "host/conversationMessages"
	MethodHostLLMSnapshot             = "host/llmSnapshot"
	MethodHostSetConversationMessages = "host/setConversationMessages"
	MethodHostSessions                = "host/sessions"
	MethodHostLoadSession             = "host/loadSession"
	MethodHostForkSession             = "host/forkSession"
	MethodHostSetSessionTitle         = "host/setSessionTitle"
	MethodHostSyncModels              = "host/syncModels"
	MethodHostWriteModels             = "host/writeModels"
	MethodHostRunBackground           = "host/runBackground"
	MethodHostCancelBackground        = "host/cancelBackground"
	MethodHostIsBackgroundRunning     = "host/isBackgroundRunning"
	MethodHostExtInfos                = "host/extInfos"
	MethodHostExtensionsDir           = "host/extensionsDir"
	MethodHostUndoSnapshots           = "host/undoSnapshots"
	MethodHostUndoRestore             = "host/undoRestore"
	MethodHostLastAssistantText       = "host/lastAssistantText"
	MethodHostAppendSessionEntry      = "host/appendSessionEntry"
	MethodHostAppendCustomMessage     = "host/appendCustomMessage"
	MethodHostWaitForIdle             = "host/waitForIdle"
	MethodHostSetLabel                = "host/setLabel"
	MethodHostBranchSession           = "host/branchSession"
	MethodHostBranchSessionSummary    = "host/branchSessionWithSummary"
	MethodHostResetSessionLeaf        = "host/resetSessionLeaf"
	MethodHostSessionEntryInfos       = "host/sessionEntryInfos"
	MethodHostSessionFullTree         = "host/sessionFullTree"
	MethodHostSessionTitle            = "host/sessionTitle"
	MethodHostSessionStats            = "host/sessionStats"
	MethodHostShowPicker              = "host/showPicker"
	MethodHostAskUser                 = "host/askUser"
	MethodHostAvailableModels         = "host/availableModels"
	MethodHostSwitchModel             = "host/switchModel"
	MethodHostPublish                 = "host/publish"
	MethodHostSubscribe               = "host/subscribe"
	MethodHostActivateTool            = "host/activateTool"
	MethodHostSetToolFilter           = "host/setToolFilter"
	MethodHostToggleStepMode          = "host/toggleStepMode"
	MethodHostRequestQuit             = "host/requestQuit"
	MethodHostAbort                   = "host/abort"
	MethodHostHasCompactor            = "host/hasCompactor"
	MethodHostTriggerCompact          = "host/triggerCompact"
	MethodHostCommands                = "host/commands"
	MethodHostToolDefs                = "host/toolDefs"
	MethodHostShortcuts               = "host/shortcuts"
	MethodHostPromptSections          = "host/promptSections"
	MethodHostEventBusEvent           = "eventBus/event" // host → extension notification
	MethodRegisterInputTransformer    = "register/inputTransformer"
	MethodInputTransform              = "inputTransformer/transform" // host → extension callback
	MethodSetWidget                   = "setWidget"
	MethodShowOverlay                 = "showOverlay"
	MethodCloseOverlay                = "closeOverlay"
	MethodNotify                      = "notify"
	MethodLog                         = "log"
	MethodShowMessage                 = "showMessage"
	MethodSendMessage                 = "sendMessage"
	MethodSetInputText                = "setInputText"
	MethodSteer                       = "steer"
	MethodAbortWithMarker             = "abortWithMarker"
	MethodAbort                       = "abort"
)

Method names

View Source
const InterruptBehaviorBlock = "block"

InterruptBehaviorBlock is the wire value for InterruptBlock on external tools.

View Source
const ProtocolVersion = "5"

Protocol version

Variables

This section is empty.

Functions

func ExtensionsDir

func ExtensionsDir() (string, error)

ExtensionsDir returns ~/.config/piglet/extensions/.

func LoadAll

func LoadAll(ctx context.Context, app *ext.App, undoFn UndoSnapshotsFn, disabled []string, projectDir string) (loaded int, cleanup func(), err error)

LoadAll discovers and starts all external extensions under supervisor management, registering their tools, commands, and prompt sections with the given ext.App. projectDir, if non-empty, is scanned for additional extensions (opt-in via config). Returns the number of loaded extensions and a cleanup function that stops all.

func ProjectExtensionsDir added in v0.18.0

func ProjectExtensionsDir(cwd string) string

ProjectExtensionsDir returns the project-local extensions directory: <cwd>/.piglet/extensions/. Returns empty string if cwd is empty.

Types

type AbortWithMarkerParams added in v0.21.0

type AbortWithMarkerParams struct {
	Reason string `json:"reason"`
}

AbortWithMarkerParams is the payload for aborting with a session marker.

type ActionResult added in v0.5.0

type ActionResult struct {
	Type    string          `json:"type"`              // "notify", "showMessage", "setSessionTitle", "quit"
	Payload json.RawMessage `json:"payload,omitempty"` // type-specific data
}

ActionResult is a JSON-serializable action returned by extensions. The host converts it to the appropriate ext.Action type.

type CancelParams added in v0.4.0

type CancelParams struct {
	ID int `json:"id"`
}

CancelParams tells the extension to abort the request with the given ID.

type ChatMessage added in v0.16.0

type ChatMessage struct {
	Role    string `json:"role"` // "user" or "assistant"
	Content string `json:"content"`
}

ChatMessage is a single message in a chat request.

type CloseOverlayParams added in v0.18.0

type CloseOverlayParams struct {
	Key string `json:"key"`
}

CloseOverlayParams removes a named overlay.

type CommandExecuteParams

type CommandExecuteParams struct {
	Name string `json:"name"`
	Args string `json:"args"`
}

CommandExecuteParams is sent when the user invokes a slash command owned by this extension.

type CommandExecuteResult

type CommandExecuteResult struct {
}

CommandExecuteResult is the extension's response.

type CompactExecuteParams added in v0.5.0

type CompactExecuteParams struct {
	Messages []CompactMessage `json:"messages"`
}

CompactExecuteParams is sent when the token threshold is exceeded.

type CompactExecuteResult added in v0.5.0

type CompactExecuteResult struct {
	Messages []CompactMessage `json:"messages"`
}

CompactExecuteResult is the extension's response.

type CompactMessage added in v0.5.0

type CompactMessage struct {
	Type string          `json:"type"` // "user", "assistant", "tool_result"
	Data json.RawMessage `json:"data"`
}

CompactMessage wraps a message with a type discriminator for JSON transport.

type ContentBlock

type ContentBlock struct {
	Type string `json:"type"` // "text" or "image"
	Text string `json:"text,omitempty"`
	Data string `json:"data,omitempty"`
	Mime string `json:"mime,omitempty"`
}

ContentBlock is a simplified content block for the wire protocol.

type DefaultFile added in v0.16.19

type DefaultFile struct {
	Src  string `yaml:"src"`
	Dest string `yaml:"dest"`
}

DefaultFile describes a config file to seed on first install.

type EventBusEventParams added in v0.18.0

type EventBusEventParams struct {
	Topic          string          `json:"topic"`
	SubscriptionID int             `json:"subscriptionId"`
	Data           json.RawMessage `json:"data"`
}

EventBusEventParams is a host → extension notification when subscribed topics fire.

type EventDispatchParams added in v0.5.0

type EventDispatchParams struct {
	Type string          `json:"type"` // e.g. "EventAgentEnd", "EventTurnEnd"
	Data json.RawMessage `json:"data,omitempty"`
}

EventDispatchParams is sent when an agent lifecycle event occurs.

type EventDispatchResult added in v0.5.0

type EventDispatchResult struct {
	Action *ActionResult `json:"action,omitempty"`
}

EventDispatchResult is the extension's response.

type Host

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

Host manages a single external extension process.

func NewHost

func NewHost(m *Manifest, cwd string) *Host

NewHost creates a host for the given manifest.

func (*Host) Closed added in v0.16.11

func (h *Host) Closed() <-chan struct{}

Closed returns a channel that is closed when the host process exits.

func (*Host) Commands

func (h *Host) Commands() []RegisterCommandParams

Commands returns the commands registered during handshake.

func (*Host) Compactor added in v0.5.0

func (h *Host) Compactor() *RegisterCompactorParams

Compactor returns the compactor registered during handshake, or nil.

func (*Host) DispatchEvent added in v0.5.0

func (h *Host) DispatchEvent(ctx context.Context, eventType string, data json.RawMessage) (*ActionResult, error)

DispatchEvent sends an event/dispatch request to the extension.

func (*Host) EventHandlers added in v0.5.0

func (h *Host) EventHandlers() []RegisterEventHandlerParams

EventHandlers returns the event handlers registered during handshake.

func (*Host) ExecuteCommand

func (h *Host) ExecuteCommand(ctx context.Context, name, args string) error

ExecuteCommand sends a command/execute request and waits for the response.

func (*Host) ExecuteCompact added in v0.5.0

func (h *Host) ExecuteCompact(ctx context.Context, messages []CompactMessage) ([]CompactMessage, error)

ExecuteCompact sends a compact/execute request with messages and waits for compacted result.

func (*Host) ExecuteTool

func (h *Host) ExecuteTool(ctx context.Context, callID, name string, args map[string]any) (*ToolExecuteResult, error)

ExecuteTool sends a tool/execute request and waits for the response.

func (*Host) HandleShortcut added in v0.5.0

func (h *Host) HandleShortcut(ctx context.Context, key string) (*ActionResult, error)

HandleShortcut sends a shortcut/handle request to the extension.

func (*Host) InputTransformers added in v0.18.0

func (h *Host) InputTransformers() []RegisterInputTransformerParams

InputTransformers returns the input transformers registered during handshake.

func (*Host) InterceptAfter added in v0.5.0

func (h *Host) InterceptAfter(ctx context.Context, name, toolName string, details any) (any, error)

InterceptAfter sends an interceptor/after request to the extension.

func (*Host) InterceptBefore added in v0.5.0

func (h *Host) InterceptBefore(ctx context.Context, name, toolName string, args map[string]any) (bool, map[string]any, string, error)

InterceptBefore sends an interceptor/before request to the extension.

func (*Host) Interceptors added in v0.5.0

func (h *Host) Interceptors() []RegisterInterceptorParams

Interceptors returns the interceptors registered during handshake.

func (*Host) MessageHooks added in v0.5.0

func (h *Host) MessageHooks() []RegisterMessageHookParams

MessageHooks returns the message hooks registered during handshake.

func (*Host) Name

func (h *Host) Name() string

Name returns the extension name from the manifest.

func (*Host) OnMessage added in v0.5.0

func (h *Host) OnMessage(ctx context.Context, msg string) (string, error)

OnMessage sends a messageHook/onMessage request to the extension.

func (*Host) PromptSections

func (h *Host) PromptSections() []RegisterPromptSectionParams

PromptSections returns the prompt sections registered during handshake.

func (*Host) Providers added in v0.16.11

func (h *Host) Providers() []RegisterProviderParams

Providers returns the providers registered during handshake.

func (*Host) SetApp added in v0.4.0

func (h *Host) SetApp(app *ext.App)

SetApp wires the host to the main application for runtime notifications.

func (*Host) SetProviderResolver added in v0.16.8

func (h *Host) SetProviderResolver(fn providerResolverFn)

SetProviderResolver sets the function used to resolve a model to a StreamProvider.

func (*Host) SetUndoSnapshots added in v0.16.11

func (h *Host) SetUndoSnapshots(fn func() (map[string][]byte, error))

SetUndoSnapshots sets the function used to retrieve undo snapshots.

func (*Host) Shortcuts added in v0.5.0

func (h *Host) Shortcuts() []RegisterShortcutParams

Shortcuts returns the shortcuts registered during handshake.

func (*Host) Start

func (h *Host) Start(ctx context.Context) error

Start spawns the extension process, performs the initialize handshake, and collects registrations. Returns after the extension sends initialize result.

func (*Host) Stop

func (h *Host) Stop()

Stop performs an ordered shutdown of the extension process:

  1. Send shutdown notification (best-effort)
  2. Close write pipe (host→ext) — extension gets EOF on FD 3
  3. Give extension a moment to exit cleanly
  4. Force-kill if it doesn't exit, then reap (cmd.Wait releases I/O goroutines)
  5. readLoop sees EOF from closed write end → exits → signals readDone
  6. Close read pipe after readLoop is done

func (*Host) Tools

func (h *Host) Tools() []RegisterToolParams

Tools returns the tools registered during handshake.

func (*Host) TransformInput added in v0.18.0

func (h *Host) TransformInput(ctx context.Context, input string) (string, bool, error)

TransformInput sends an inputTransformer/transform request to the extension.

type HostActivateToolParams added in v0.22.0

type HostActivateToolParams struct {
	Name string `json:"name"`
}

HostActivateToolParams promotes a deferred tool to full schema.

type HostActivateToolResult added in v0.22.0

type HostActivateToolResult struct{}

HostActivateToolResult is the host's response after activating a tool.

type HostAgentRunParams added in v0.16.0

type HostAgentRunParams struct {
	System   string `json:"system,omitempty"`
	Task     string `json:"task"`
	Tools    string `json:"tools,omitempty"` // "background_safe" (default) or "all"
	Model    string `json:"model,omitempty"` // "small", "default", or explicit model ID
	MaxTurns int    `json:"maxTurns,omitempty"`
}

HostAgentRunParams asks the host to run a full agent loop.

type HostAgentRunResult added in v0.16.0

type HostAgentRunResult struct {
	Text  string         `json:"text"`
	Turns int            `json:"turns"`
	Usage HostTokenUsage `json:"usage"`
}

HostAgentRunResult is the host's response.

type HostAppendCustomMessageParams added in v0.18.0

type HostAppendCustomMessageParams struct {
	Role    string `json:"role"` // "user" or "assistant"
	Content string `json:"content"`
}

HostAppendCustomMessageParams writes a custom message to the session.

type HostAppendSessionEntryParams added in v0.18.0

type HostAppendSessionEntryParams struct {
	Kind string `json:"kind"` // namespaced, e.g. "ext:memory:facts"
	Data any    `json:"data"`
}

HostAppendSessionEntryParams appends a custom entry to the current session.

type HostAskUserParams added in v0.23.1

type HostAskUserParams struct {
	Prompt  string   `json:"prompt"`
	Choices []string `json:"choices"`
}

HostAskUserParams is the request for host/askUser.

type HostAskUserResult added in v0.23.1

type HostAskUserResult struct {
	Selected  string `json:"selected"`
	Cancelled bool   `json:"cancelled"`
}

HostAskUserResult is the response for host/askUser. Cancelled=true indicates the user dismissed the dialog without selecting.

type HostAuthGetKeyParams added in v0.16.0

type HostAuthGetKeyParams struct {
	Provider string `json:"provider"`
}

HostAuthGetKeyParams requests an API key for a provider.

type HostAuthGetKeyResult added in v0.16.0

type HostAuthGetKeyResult struct {
	Key string `json:"key"`
}

HostAuthGetKeyResult is the host's response.

type HostAvailableModelsResult added in v0.23.0

type HostAvailableModelsResult struct {
	Models []WireModelInfo `json:"models"`
}

HostAvailableModelsResult is the host's response to host/availableModels.

type HostBranchSessionParams added in v0.18.0

type HostBranchSessionParams struct {
	EntryID string `json:"entryId"`
}

HostBranchSessionParams branches the session at a specific entry.

type HostBranchSessionSummaryParams added in v0.18.0

type HostBranchSessionSummaryParams struct {
	EntryID string `json:"entryId"`
	Summary string `json:"summary"`
}

HostBranchSessionSummaryParams branches with a summary annotation.

type HostChatParams added in v0.16.0

type HostChatParams struct {
	System    string        `json:"system,omitempty"`
	Messages  []ChatMessage `json:"messages"`
	Model     string        `json:"model,omitempty"` // "small", "default", or explicit model ID
	MaxTokens int           `json:"maxTokens,omitempty"`
}

HostChatParams asks the host to make a single-turn LLM call.

type HostChatResult added in v0.16.0

type HostChatResult struct {
	Text  string         `json:"text"`
	Usage HostTokenUsage `json:"usage"`
}

HostChatResult is the host's response.

type HostCommandInfo added in v0.23.1

type HostCommandInfo struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

HostCommandInfo is the wire representation of one registered command.

type HostCommandsResult added in v0.23.1

type HostCommandsResult struct {
	Commands []HostCommandInfo `json:"commands"`
}

HostCommandsResult is the host's response to host/commands.

type HostConfigGetParams added in v0.16.0

type HostConfigGetParams struct {
	Keys []string `json:"keys"`
}

HostConfigGetParams requests configuration values.

type HostConfigGetResult added in v0.16.0

type HostConfigGetResult struct {
	Values map[string]any `json:"values"`
}

HostConfigGetResult is the host's response.

type HostConfigReadExtParams added in v0.16.0

type HostConfigReadExtParams struct {
	Name string `json:"name"`
}

HostConfigReadExtParams requests an extension's markdown config.

type HostConfigReadExtResult added in v0.16.0

type HostConfigReadExtResult struct {
	Content string `json:"content"`
}

HostConfigReadExtResult is the host's response.

type HostConversationMessagesResult added in v0.16.8

type HostConversationMessagesResult struct {
	Messages json.RawMessage `json:"messages"`
}

HostConversationMessagesResult is the host's response with raw message JSON.

type HostExecuteToolParams added in v0.5.0

type HostExecuteToolParams struct {
	Name   string         `json:"name"`
	Args   map[string]any `json:"args"`
	CallID string         `json:"callId,omitzero"`
}

HostExecuteToolParams is sent by the extension to execute a host-registered tool.

type HostExecuteToolResult added in v0.5.0

type HostExecuteToolResult struct {
	Content   []ContentBlock `json:"content"`
	IsError   bool           `json:"isError,omitempty"`
	ErrorCode string         `json:"errorCode,omitempty"` // machine-readable code (e.g. "FILE_STALE"); empty on success
	ErrorHint string         `json:"errorHint,omitempty"` // actionable hint; empty if not applicable
}

HostExecuteToolResult is the host's response.

type HostExtInfosResult added in v0.16.8

type HostExtInfosResult struct {
	Extensions []WireExtInfo `json:"extensions"`
}

HostExtInfosResult is the host's response with loaded extension metadata.

type HostExtensionsDirResult added in v0.16.8

type HostExtensionsDirResult struct {
	Path string `json:"path"`
}

HostExtensionsDirResult is the host's response with the extensions directory.

type HostForkSessionResult added in v0.16.8

type HostForkSessionResult struct {
	ParentID     string `json:"parentID"`
	MessageCount int    `json:"messageCount"`
}

HostForkSessionResult is the host's response after forking.

type HostIsBackgroundRunningResult added in v0.16.8

type HostIsBackgroundRunningResult struct {
	Running bool `json:"running"`
}

HostIsBackgroundRunningResult is the host's response.

type HostLastAssistantTextResult added in v0.18.0

type HostLastAssistantTextResult struct {
	Text string `json:"text"`
}

HostLastAssistantTextResult is the host's response.

type HostListToolsParams added in v0.5.0

type HostListToolsParams struct {
	Filter string `json:"filter,omitempty"` // FilterAll or FilterBackgroundSafe (default: FilterAll)
}

HostListToolsParams requests the list of available host tools.

type HostListToolsResult added in v0.5.0

type HostListToolsResult struct {
	Tools []HostToolInfo `json:"tools"`
}

HostListToolsResult is the host's response.

type HostLoadSessionParams added in v0.16.8

type HostLoadSessionParams struct {
	Path string `json:"path"`
}

HostLoadSessionParams requests loading a session by path.

type HostModelOverride added in v0.20.0

type HostModelOverride struct {
	Name          string `json:"name,omitempty"`
	ContextWindow int    `json:"contextWindow,omitempty"`
	MaxTokens     int    `json:"maxTokens,omitempty"`
}

HostModelOverride holds values that replace curated defaults for one model.

type HostPromptSectionInfo added in v0.23.1

type HostPromptSectionInfo struct {
	Title     string `json:"title"`
	TokenHint int    `json:"tokenHint,omitzero"`
}

HostPromptSectionInfo is the wire representation of one registered prompt section (title + token hint only — Content is omitted; consumers care about budget, not text).

type HostPromptSectionsResult added in v0.23.1

type HostPromptSectionsResult struct {
	Sections []HostPromptSectionInfo `json:"sections"`
}

HostPromptSectionsResult is the host's response to host/promptSections.

type HostPublishParams added in v0.18.0

type HostPublishParams struct {
	Topic string `json:"topic"`
	Data  any    `json:"data"`
}

HostPublishParams publishes data to the inter-extension event bus.

type HostResetSessionLeafParams added in v0.23.1

type HostResetSessionLeafParams struct{}

HostResetSessionLeafParams is empty; the method takes no arguments.

type HostRunBackgroundParams added in v0.16.8

type HostRunBackgroundParams struct {
	Prompt string `json:"prompt"`
}

HostRunBackgroundParams starts a background agent.

type HostSessionEntryInfosResult added in v0.23.0

type HostSessionEntryInfosResult struct {
	Entries []WireEntryInfo `json:"entries"`
}

HostSessionEntryInfosResult is the host's response to host/sessionEntryInfos.

type HostSessionFullTreeResult added in v0.23.0

type HostSessionFullTreeResult struct {
	Nodes []WireTreeNode `json:"nodes"`
}

HostSessionFullTreeResult is the host's response to host/sessionFullTree.

type HostSessionTitleResult added in v0.23.0

type HostSessionTitleResult struct {
	Title string `json:"title"`
}

HostSessionTitleResult is the host's response to host/sessionTitle.

type HostSessionsResult added in v0.16.8

type HostSessionsResult struct {
	Sessions []WireSessionInfo `json:"sessions"`
}

HostSessionsResult is the host's response with session summaries.

type HostSetConversationMessagesParams added in v0.16.26

type HostSetConversationMessagesParams struct {
	Messages []CompactMessage `json:"messages"`
}

HostSetConversationMessagesParams is the extension's request to replace messages.

type HostSetLabelParams added in v0.18.0

type HostSetLabelParams struct {
	TargetID string `json:"targetId"`
	Label    string `json:"label"`
}

HostSetLabelParams sets or clears a bookmark label on a session entry.

type HostSetSessionTitleParams added in v0.16.8

type HostSetSessionTitleParams struct {
	Title string `json:"title"`
}

HostSetSessionTitleParams sets the current session's title.

type HostSetToolFilterParams added in v0.22.7

type HostSetToolFilterParams struct {
	Names []string `json:"names"` // empty = clear filter (include all)
}

HostSetToolFilterParams sets a per-turn tool filter by name allowlist.

type HostShortcutInfo added in v0.23.1

type HostShortcutInfo struct {
	Description string `json:"description"`
}

HostShortcutInfo is the wire representation of one registered shortcut.

type HostShortcutsResult added in v0.23.1

type HostShortcutsResult struct {
	Shortcuts map[string]HostShortcutInfo `json:"shortcuts"`
}

HostShortcutsResult is the host's response to host/shortcuts. Key is the keybind string (e.g. "ctrl+g").

type HostShowPickerParams added in v0.23.0

type HostShowPickerParams struct {
	Title string           `json:"title"`
	Items []WirePickerItem `json:"items"`
}

HostShowPickerParams is the extension's request to display a picker.

type HostShowPickerResult added in v0.23.0

type HostShowPickerResult struct {
	Selected string `json:"selected"`
}

HostShowPickerResult is the host's response after the user selects an item. Selected is the ID of the chosen item. If the user dismisses the picker, the RPC call blocks until hostRequestTimeout (the OnSelect callback in ActionShowPicker is never invoked for dismissal in the current TUI).

type HostSubscribeParams added in v0.18.0

type HostSubscribeParams struct {
	Topic string `json:"topic"`
}

HostSubscribeParams subscribes to an event bus topic.

type HostSubscribeResult added in v0.18.0

type HostSubscribeResult struct {
	SubscriptionID int `json:"subscriptionId"`
}

HostSubscribeResult returns a subscription ID for unsubscribing.

type HostSwitchModelParams added in v0.23.0

type HostSwitchModelParams struct {
	ModelID        string `json:"modelId"`
	PersistDefault bool   `json:"persistDefault,omitempty"`
}

HostSwitchModelParams is the extension's request to switch the active model.

type HostSyncModelsResult added in v0.16.8

type HostSyncModelsResult struct {
	Updated int `json:"updated"`
}

HostSyncModelsResult is the host's response after syncing models.

type HostTokenUsage added in v0.16.0

type HostTokenUsage struct {
	Input  int `json:"input"`
	Output int `json:"output"`
}

HostTokenUsage reports token consumption.

type HostToolDefInfo added in v0.23.1

type HostToolDefInfo struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

HostToolDefInfo is the wire representation of one registered tool definition (name + description only — input schema is omitted for lightweight /help use).

type HostToolDefsResult added in v0.23.1

type HostToolDefsResult struct {
	Tools []HostToolDefInfo `json:"tools"`
}

HostToolDefsResult is the host's response to host/toolDefs.

type HostToolInfo added in v0.5.0

type HostToolInfo struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Parameters  any    `json:"parameters"` // JSON Schema
	Deferred    bool   `json:"deferred,omitempty"`
}

HostToolInfo describes a single host-registered tool.

type HostTriggerCompactResult added in v0.23.1

type HostTriggerCompactResult struct {
	Before int `json:"before"`
	After  int `json:"after"`
}

HostTriggerCompactResult is the response payload for host/triggerCompact.

type HostUndoRestoreParams added in v0.16.8

type HostUndoRestoreParams struct {
	Path string `json:"path"`
}

HostUndoRestoreParams requests restoring a file from its undo snapshot.

type HostUndoSnapshotsResult added in v0.16.8

type HostUndoSnapshotsResult struct {
	Snapshots map[string]int `json:"snapshots"` // path → size in bytes
}

HostUndoSnapshotsResult is the host's response with undo snapshot info.

type HostWriteModelsParams added in v0.20.0

type HostWriteModelsParams struct {
	Overrides map[string]HostModelOverride `json:"overrides"`
}

HostWriteModelsParams holds API-sourced overrides for regenerating models.yaml.

type HostWriteModelsResult added in v0.20.0

type HostWriteModelsResult struct {
	ModelsWritten int `json:"modelsWritten"`
}

HostWriteModelsResult is the host's response after writing models.

type InitializeParams

type InitializeParams struct {
	ProtocolVersion string `json:"protocolVersion"`
	CWD             string `json:"cwd"`
	ConfigDir       string `json:"configDir,omitempty"`
}

InitializeParams is sent by the host after spawning the extension.

type InitializeResult

type InitializeResult struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

InitializeResult is the extension's response to initialize.

type InputTransformParams added in v0.18.0

type InputTransformParams struct {
	Input string `json:"input"`
}

InputTransformParams is the host → extension callback when user input arrives.

type InputTransformResult added in v0.18.0

type InputTransformResult struct {
	Output  string `json:"output"`
	Handled bool   `json:"handled"` // true = input was consumed, stop processing
}

InputTransformResult is the extension's response.

type InterceptorAfterParams added in v0.5.0

type InterceptorAfterParams struct {
	Name     string `json:"name"` // interceptor discriminator
	ToolName string `json:"toolName"`
	Details  any    `json:"details,omitempty"`
}

InterceptorAfterParams is sent after tool execution.

type InterceptorAfterResult added in v0.5.0

type InterceptorAfterResult struct {
	Details any `json:"details,omitempty"`
}

InterceptorAfterResult is the extension's response.

type InterceptorBeforeParams added in v0.5.0

type InterceptorBeforeParams struct {
	Name     string         `json:"name"` // interceptor discriminator
	ToolName string         `json:"toolName"`
	Args     map[string]any `json:"args"`
}

InterceptorBeforeParams is sent when a tool is about to execute.

type InterceptorBeforeResult added in v0.5.0

type InterceptorBeforeResult struct {
	Allow   bool           `json:"allow"`
	Args    map[string]any `json:"args,omitempty"`
	Preview string         `json:"preview,omitempty"` // shown to LLM when allow=false
}

InterceptorBeforeResult is the extension's response.

type LogParams

type LogParams struct {
	Level   string `json:"level"` // "debug", "info", "warn", "error"
	Message string `json:"message"`
}

LogParams writes to the host's log.

type Manifest

type Manifest struct {
	Name         string        `yaml:"name"`
	Version      string        `yaml:"version,omitempty"`
	Runtime      string        `yaml:"runtime"`                // "bun", "node", "deno", "python", or absolute path
	Entry        string        `yaml:"entry"`                  // e.g. "index.ts", "main.py"
	Capabilities []string      `yaml:"capabilities,omitempty"` // "tools", "commands", "prompt"
	Defaults     []DefaultFile `yaml:"defaults,omitempty"`
	Dir          string        `yaml:"-"` // populated at load time
}

Manifest describes an external extension.

func DiscoverExtensions

func DiscoverExtensions(baseDir string) ([]*Manifest, error)

DiscoverExtensions finds all extension directories under the given base path. Each subdirectory must contain a manifest.yaml.

func LoadManifest

func LoadManifest(dir string) (*Manifest, error)

LoadManifest reads a manifest.yaml from the given directory.

func (*Manifest) RuntimeCommand

func (m *Manifest) RuntimeCommand() (string, []string)

RuntimeCommand returns the command and args to execute an extension.

type Message

type Message struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      *int            `json:"id,omitempty"`
	Method  string          `json:"method,omitempty"`
	Params  json.RawMessage `json:"params,omitempty"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *RPCError       `json:"error,omitempty"`
}

Message is a JSON-RPC 2.0-ish envelope. We use a simplified variant: requests have Method+ID+Params, responses have ID+Result or ID+Error, notifications have Method+Params and no ID.

type MessageHookParams added in v0.5.0

type MessageHookParams struct {
	Message string `json:"message"`
}

MessageHookParams is sent before a user message reaches the LLM.

type MessageHookResult added in v0.5.0

type MessageHookResult struct {
	Injection string `json:"injection,omitempty"` // ephemeral context to inject
}

MessageHookResult is the extension's response.

type NotifyParams

type NotifyParams struct {
	Message string `json:"message"`
	Level   string `json:"level,omitempty"` // "", "info" → muted; "warn" → warning; "error" → error
}

NotifyParams sends a notification to the TUI.

type ProviderDeltaParams added in v0.16.11

type ProviderDeltaParams struct {
	RequestID int               `json:"requestId"`
	Type      string            `json:"type"`
	Index     int               `json:"index,omitempty"`
	Delta     string            `json:"delta,omitempty"`
	Tool      *ProviderToolCall `json:"tool,omitempty"`
}

ProviderDeltaParams is a streaming notification correlated by requestId.

type ProviderStreamParams added in v0.16.11

type ProviderStreamParams struct {
	RequestID int             `json:"requestId"`
	Model     json.RawMessage `json:"model"`
	System    string          `json:"system"`
	Messages  json.RawMessage `json:"messages"`
	Tools     json.RawMessage `json:"tools,omitempty"`
	Options   json.RawMessage `json:"options,omitempty"`
}

ProviderStreamParams is the request to stream an LLM call.

type ProviderStreamResult added in v0.16.11

type ProviderStreamResult struct {
	Message json.RawMessage `json:"message"`
	Error   string          `json:"error,omitempty"`
}

ProviderStreamResult is the final response after streaming completes.

type ProviderToolCall added in v0.16.11

type ProviderToolCall struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

ProviderToolCall is a tool call in a provider delta (toolcall_end event).

type RPCError

type RPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

RPCError is the error object in a JSON-RPC response.

type RegisterCommandParams

type RegisterCommandParams struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Immediate   bool   `json:"immediate,omitempty"`
}

RegisterCommandParams registers a slash command.

type RegisterCompactorParams added in v0.5.0

type RegisterCompactorParams struct {
	Name      string `json:"name"`
	Threshold int    `json:"threshold,omitempty"` // 0 = use config default
}

RegisterCompactorParams registers a conversation compactor.

type RegisterEventHandlerParams added in v0.5.0

type RegisterEventHandlerParams struct {
	Name     string   `json:"name"`
	Priority int      `json:"priority,omitempty"`
	Events   []string `json:"events,omitempty"` // nil = all events
}

RegisterEventHandlerParams registers an agent lifecycle event handler.

type RegisterInputTransformerParams added in v0.18.0

type RegisterInputTransformerParams struct {
	Name     string `json:"name"`
	Priority int    `json:"priority,omitempty"`
}

RegisterInputTransformerParams registers an input transformer.

type RegisterInterceptorParams added in v0.5.0

type RegisterInterceptorParams struct {
	Name     string `json:"name"`
	Priority int    `json:"priority,omitempty"`
}

RegisterInterceptorParams registers a before/after tool interceptor.

type RegisterMessageHookParams added in v0.5.0

type RegisterMessageHookParams struct {
	Name     string `json:"name"`
	Priority int    `json:"priority,omitempty"`
}

RegisterMessageHookParams registers a pre-message hook.

type RegisterPromptSectionParams

type RegisterPromptSectionParams struct {
	Title     string `json:"title"`
	Content   string `json:"content"`
	Order     int    `json:"order,omitempty"`
	TokenHint int    `json:"tokenHint,omitzero"`
}

RegisterPromptSectionParams adds a section to the system prompt.

type RegisterProviderParams added in v0.16.11

type RegisterProviderParams struct {
	API string `json:"api"` // "openai", "anthropic", "google"
}

RegisterProviderParams declares the extension can handle a provider API type.

type RegisterShortcutParams added in v0.5.0

type RegisterShortcutParams struct {
	Key         string `json:"key"` // e.g. "ctrl+g"
	Description string `json:"description"`
}

RegisterShortcutParams registers a keyboard shortcut.

type RegisterToolParams

type RegisterToolParams struct {
	Name              string `json:"name"`
	Description       string `json:"description"`
	Parameters        any    `json:"parameters"` // JSON Schema
	PromptHint        string `json:"promptHint,omitempty"`
	Deferred          bool   `json:"deferred,omitempty"`
	InterruptBehavior string `json:"interruptBehavior,omitempty"` // "cancel" (default) or "block"
}

RegisterToolParams registers a tool the LLM can call.

type SendMessageParams added in v0.16.8

type SendMessageParams struct {
	Content string `json:"content"`
}

SendMessageParams is the payload for a sendMessage notification.

type SetInputTextParams added in v0.23.1

type SetInputTextParams struct {
	Text string `json:"text"`
}

SetInputTextParams is the payload for a setInputText notification.

type SetWidgetParams added in v0.18.0

type SetWidgetParams struct {
	Key       string `json:"key"`
	Placement string `json:"placement"` // "above-input" or "below-status"
	Content   string `json:"content"`   // empty = remove
}

SetWidgetParams sets or clears a persistent widget in the TUI.

type ShortcutHandleParams added in v0.5.0

type ShortcutHandleParams struct {
	Key string `json:"key"` // which shortcut key was pressed
}

ShortcutHandleParams is sent when the user presses a registered shortcut.

type ShortcutHandleResult added in v0.5.0

type ShortcutHandleResult struct {
	Action *ActionResult `json:"action,omitempty"`
}

ShortcutHandleResult is the extension's response.

type ShowMessageParams

type ShowMessageParams struct {
	Text string `json:"text"`
}

ShowMessageParams displays a message in the conversation.

type ShowOverlayParams added in v0.18.0

type ShowOverlayParams struct {
	Key     string `json:"key"`
	Title   string `json:"title,omitempty"`
	Content string `json:"content"`
	Anchor  string `json:"anchor,omitempty"` // "center","left","right","top","bottom","top-left","top-right","bottom-left","bottom-right" (default: center)
	Width   string `json:"width,omitempty"`  // "50%", "80" (chars), "" (auto)
}

ShowOverlayParams creates or replaces a named overlay.

type ShutdownParams

type ShutdownParams struct{}

ShutdownParams asks the extension to shut down gracefully.

type SteerParams added in v0.16.11

type SteerParams struct {
	Content string `json:"content"`
}

SteerParams is the payload for a steer notification. Interrupts the current turn and injects a message.

type Supervisor added in v0.16.11

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

Supervisor wraps a Host with crash detection and automatic restart. When the extension process exits unexpectedly, the supervisor creates a new Host from the same Manifest, re-runs the handshake, and re-bridges registrations. Reload() triggers an intentional restart (e.g. binary changed on disk).

func NewSupervisor added in v0.16.11

func NewSupervisor(m *Manifest, cwd string, app *ext.App, resolver providerResolverFn, undoFn UndoSnapshotsFn) *Supervisor

NewSupervisor creates a supervisor for the given manifest.

func (*Supervisor) Name added in v0.16.11

func (s *Supervisor) Name() string

func (*Supervisor) Reload added in v0.18.0

func (s *Supervisor) Reload()

Reload triggers a graceful restart of the extension process. The watch goroutine handles the actual restart — this method just signals it. Safe for concurrent use; no-op if a reload is already pending.

func (*Supervisor) Start added in v0.16.11

func (s *Supervisor) Start(ctx context.Context) error

Start creates the initial host, performs the handshake, bridges registrations, and starts the crash-watch goroutine.

func (*Supervisor) Stop added in v0.16.11

func (s *Supervisor) Stop()

Stop terminates the supervised extension and disables auto-restart.

type ToolExecuteParams

type ToolExecuteParams struct {
	CallID string         `json:"callId"`
	Name   string         `json:"name"`
	Args   map[string]any `json:"args"`
}

ToolExecuteParams is sent when the LLM calls a tool owned by this extension.

type ToolExecuteResult

type ToolExecuteResult struct {
	Content   []ContentBlock `json:"content"`
	IsError   bool           `json:"isError,omitempty"`
	ErrorCode string         `json:"errorCode,omitempty"` // machine-readable code; empty on success
	ErrorHint string         `json:"errorHint,omitempty"` // actionable hint; empty if not applicable
}

ToolExecuteResult is the extension's response.

type UndoSnapshotsFn added in v0.16.11

type UndoSnapshotsFn func() (map[string][]byte, error)

UndoSnapshotsFn retrieves undo snapshots (injected to avoid importing tool/).

type Watcher added in v0.18.0

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

Watcher monitors extension directories for binary/manifest changes and triggers supervisor reloads. Debounces rapid changes (e.g. during build).

func (*Watcher) Stop added in v0.18.0

func (w *Watcher) Stop()

Stop shuts down the file watcher. Safe to call on nil.

type WireEntryInfo added in v0.23.0

type WireEntryInfo struct {
	ID        string `json:"id"`
	ParentID  string `json:"parentId,omitempty"`
	Type      string `json:"type"`
	Timestamp string `json:"timestamp"` // RFC3339
	Children  int    `json:"children"`
}

WireEntryInfo is the wire representation of ext.EntryInfo. Timestamp serialized as RFC3339 to match WireSessionInfo convention.

type WireExtInfo added in v0.16.8

type WireExtInfo struct {
	Name          string   `json:"name"`
	Version       string   `json:"version,omitempty"`
	Kind          string   `json:"kind"`
	Runtime       string   `json:"runtime,omitempty"`
	Tools         []string `json:"tools,omitempty"`
	Commands      []string `json:"commands,omitempty"`
	Interceptors  []string `json:"interceptors,omitempty"`
	EventHandlers []string `json:"eventHandlers,omitempty"`
	Shortcuts     []string `json:"shortcuts,omitempty"`
	MessageHooks  []string `json:"messageHooks,omitempty"`
	Compactor     string   `json:"compactor,omitempty"`
}

WireExtInfo is the wire representation of an extension's metadata.

type WireModelInfo added in v0.23.0

type WireModelInfo struct {
	ID            string  `json:"id"`
	API           string  `json:"api"`
	DisplayName   string  `json:"displayName"`
	Provider      string  `json:"provider"`
	ContextWindow int     `json:"contextWindow,omitempty"`
	MaxTokens     int     `json:"maxTokens,omitempty"`
	Reasoning     bool    `json:"reasoning,omitempty"`
	CostInput     float64 `json:"costInput,omitempty"`
	CostOutput    float64 `json:"costOutput,omitempty"`
	Current       bool    `json:"current"`
}

WireModelInfo is the wire representation of a configured model.

type WirePickerItem added in v0.23.0

type WirePickerItem struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	Desc  string `json:"desc,omitempty"`
}

WirePickerItem mirrors ext.PickerItem.

type WireSessionInfo added in v0.16.8

type WireSessionInfo struct {
	ID        string `json:"id"`
	Title     string `json:"title"`
	CWD       string `json:"cwd"`
	CreatedAt string `json:"createdAt"` // RFC3339
	ParentID  string `json:"parentId,omitempty"`
	Path      string `json:"path"`
}

WireSessionInfo is the wire representation of a session summary.

type WireTreeNode added in v0.23.0

type WireTreeNode struct {
	ID           string `json:"id"`
	ParentID     string `json:"parentId,omitempty"`
	Type         string `json:"type"`
	Timestamp    string `json:"timestamp"` // RFC3339
	Children     int    `json:"children"`
	OnActivePath bool   `json:"onActivePath"`
	Depth        int    `json:"depth"`
	Preview      string `json:"preview,omitempty"`
	Label        string `json:"label,omitempty"`
	TokensBefore int    `json:"tokensBefore,omitempty"` // tokens before compaction; only set on compact entries
}

WireTreeNode is the wire representation of ext.TreeNode.

Jump to

Keyboard shortcuts

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