extension

package
v1.14.2 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT, MIT Imports: 18 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package extension is the Go engine's implementation of SEP, the Smooth Extension Protocol.

An extension is a long-lived subprocess speaking JSON-RPC 2.0 over ndjson on its stdio (identical framing to MCP stdio). The canonical wire schemas live in the smooth-operator repo at spec/extension/; the types here are the Go host's view of that wire. Field names are snake_case to match the spec.

This package is purely additive: nothing here runs unless a caller builds an ExtensionHost and registers its tools into core.AgentOptions.Tools. With no host built the agent loop behaves exactly as before.

Layout mirrors the Rust reference (rust/smooth-operator-core/src/extension/):

  • protocol.go — JSON-RPC frames + typed method params/results.
  • manifest.go — extension.toml discovery, global+project merge, ${env:VAR}.
  • process.go — one subprocess: ndjson codec, pending map, generation guard.
  • host.go — ExtensionHost: hook chaining, event fanout, the delegate seam.
  • tool_proxy.go — ExtensionTool: an extension tool as a core.Tool.

Index

Constants

View Source
const (
	CodeParseError     = -32700
	CodeInvalidRequest = -32600
	CodeMethodNotFound = -32601
	CodeInvalidParams  = -32602
	CodeInternalError  = -32603

	// CodeBlocked — a hook or policy vetoed the operation.
	CodeBlocked = -32000
	// CodeNoUI — ui/request in a headless/uncapable frontend.
	CodeNoUI = -32001
	// CodeNotTrusted — extension acted beyond its granted trust.
	CodeNotTrusted = -32002
	// CodeContextViolation — command-tier action attempted from an event-tier context.
	CodeContextViolation = -32003
	// CodeCapabilityDisabled — method requires a capability the handshake did not enable.
	CodeCapabilityDisabled = -32004
	// CodeCancelled — request cancelled via $/cancel.
	CodeCancelled = -32800
)

JSON-RPC error codes. Standard range plus the SEP extensions documented in spec/extension/envelope.md.

View Source
const (
	MethodInitialize             = "initialize"
	MethodShutdown               = "shutdown"
	MethodPing                   = "ping"
	MethodEvent                  = "event"
	MethodHook                   = "hook"
	MethodToolExecute            = "tool/execute"
	MethodToolUpdate             = "tool/update"
	MethodCommandExecute         = "command/execute"
	MethodCommandComplete        = "command/complete"
	MethodCancel                 = "$/cancel"
	MethodRegistryUpdate         = "registry/update"
	MethodToolsSetActive         = "tools/set_active"
	MethodExecRun                = "exec/run"
	MethodUIRequest              = "ui/request"
	MethodLog                    = "log"
	MethodBusPublish             = "bus/publish"
	MethodSessionSendMessage     = "session/send_message"
	MethodSessionSendUserMessage = "session/send_user_message"
	MethodSessionAppendEntry     = "session/append_entry"
)

SEP method names, centralized so the host and tests never spell one wrong.

View Source
const ObserveQueueCap = 1024

ObserveQueueCap is the bounded depth of the per-connection observe (event) lane. When a slow extension lets events pile past this, the OLDEST are shed and an events_lost marker is delivered on recovery — observe events are lossy by contract. Requests (hook/tool/ping/shutdown) are NEVER shed; they ride the reliable control lane.

View Source
const PingIdle = 60 * time.Second

PingIdle is the idle interval after which the host should health-probe with ping.

View Source
const ProtocolVersion = 1

PROTOCOL_VERSION is the SEP protocol version this host implements.

Variables

View Source
var EnvPassthrough = []string{"PATH", "HOME", "LANG", "LC_ALL", "LC_CTYPE", "TMPDIR", "TERM", "SystemRoot"}

EnvPassthrough is the ONLY host environment variables passed through to an extension subprocess. Everything else is scrubbed (see buildChildEnv) so ambient secrets — cloud creds (AWS_SECRET_ACCESS_KEY), API tokens, GITHUB_TOKEN, … — can never leak into an extension via inherited env (the lethal-trifecta concern).

These are launch essentials only, and none is secret:

  • PATH — resolve a bare-name interpreter (node, python3) and its own subprocess lookups. Without it a non-absolute Command won't even start.
  • HOME — interpreters read user config/caches from it; some abort without it.
  • LANG / LC_ALL / LC_CTYPE — locale; python3 errors on non-ASCII I/O unset.
  • TMPDIR — where the child writes temp files (macOS/BSD).
  • TERM — interpreters that probe for a tty degrade gracefully with it.
  • SystemRoot — Windows: node.exe/python.exe fail to start without it.

SEP-protocol vars and anything else an extension legitimately needs come through its manifest [run] env (carried in SpawnSpec.Env), NOT from here — so adding a var is a deliberate, per-extension act, never ambient.

View Source
var RestartBackoffs = [3]time.Duration{1 * time.Second, 5 * time.Second, 25 * time.Second}

RestartBackoffs is the backoff schedule for restart attempts. After the third failed attempt the host marks the extension failed and stops trying.

Functions

func BackoffFor

func BackoffFor(attempt int) (time.Duration, bool)

BackoffFor returns the backoff for restart attempt (0-indexed) and whether attempts remain. When false, the caller transitions the extension to failed.

func DefaultGlobalDir

func DefaultGlobalDir() string

DefaultGlobalDir is the default global extensions directory: $SMOOTH_HOME/extensions if set, else ~/.smooth/extensions. Returns "" if no home dir can be resolved.

func Discover

func Discover(globalDir, projectDir string) ([]DiscoveredExtension, []DiscoveryFailure)

Discover finds every extension under globalDir and projectDir, merging by name with PROJECT winning. Either directory may be "" or missing (treated as empty). Returns the chosen extensions (sorted by name for deterministic load order) plus a list of failures for manifests that failed to parse — a single bad manifest never aborts discovery.

func EffectiveSubscriptions

func EffectiveSubscriptions(declared, requested []string) map[string]struct{}

EffectiveSubscriptions is what the extension asked for at handshake, clamped to what its manifest [capabilities] events declared. An empty declared list means "no declared filter" → trust the handshake as-is; a non-empty list is the outer bound the extension can never widen past.

func Load

func Load(ctx context.Context, discovered []DiscoveredExtension, host HostInfo, workspace WorkspaceInfo, mode string, uiCapabilities []string, delegate HostDelegate) (*ExtensionHost, []LoadFailure)

Load loads and initializes each discovered extension. Per-extension failures (spawn, handshake) are tolerated and returned alongside the host. In an untrusted workspace, project-scoped extensions are skipped.

func NewAgentBridge added in v1.7.6

func NewAgentBridge(host *ExtensionHost) core.ExtensionHooks

NewAgentBridge wires host into an agent. Returns nil for a nil host, so `Extensions: extension.NewAgentBridge(nil)` is the same no-op as leaving the option unset rather than a nil-pointer panic mid-turn.

func ProjectDir

func ProjectDir(workspaceRoot string) string

ProjectDir is the project extensions directory for a workspace root.

Types

type AgentBridge added in v1.7.6

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

AgentBridge adapts an ExtensionHost onto core.ExtensionHooks so a host can be wired into the agent loop:

host, _ := extension.Load(ctx, ...)
agent := core.NewSmoothAgent(client, core.AgentOptions{
    Extensions: extension.NewAgentBridge(host),
})

The adapter exists because the dependency runs extension → core (an ExtensionTool is a core.Tool), so core cannot import this package back. Every method here translates between this package's types (FoldedHook, *ExtensionTool) and the core-expressible signatures the seam declares.

func (*AgentBridge) DispatchEvent added in v1.7.6

func (b *AgentBridge) DispatchEvent(event string, payload json.RawMessage)

DispatchEvent fans a turn event out to subscribed extensions.

func (*AgentBridge) ExtensionDeferredTools added in v1.7.6

func (b *AgentBridge) ExtensionDeferredTools() []core.Tool

ExtensionDeferredTools returns the host's deferred tools as core.Tools.

func (*AgentBridge) ExtensionTools added in v1.7.6

func (b *AgentBridge) ExtensionTools() []core.Tool

ExtensionTools returns the host's eager tools as core.Tools.

func (*AgentBridge) RunToolCallHook added in v1.7.6

func (b *AgentBridge) RunToolCallHook(ctx context.Context, tool string, arguments string) (bool, string, string)

RunToolCallHook folds the tool_call chain over one pending call, flattening FoldedHook into the (blocked, reason, patched) triple the seam speaks.

A Modify outcome replaces the whole `{tool, arguments}` hook input, so the patched arguments are lifted back out of it. The host's cross-tool guard has already rejected any rewrite of a tool the extension does not own.

type Capabilities

type Capabilities struct {
	Events   []string `toml:"events"`
	Tools    bool     `toml:"tools"`
	Commands bool     `toml:"commands"`
	UI       bool     `toml:"ui"`
	Exec     bool     `toml:"exec"`
	KV       bool     `toml:"kv"`
	Bus      bool     `toml:"bus"`
	Session  bool     `toml:"session"`
}

Capabilities declares what the extension can do. The Events list doubles as the host's dispatch filter — an extension only receives events it names here.

type CommandCompleteParams

type CommandCompleteParams struct {
	Command string  `json:"command"`
	Context Context `json:"context"`
	Partial string  `json:"partial,omitempty"`
}

CommandCompleteParams asks an extension for argument completions.

type CommandCompleteResult

type CommandCompleteResult struct {
	Completions []Completion `json:"completions,omitempty"`
}

CommandCompleteResult is the ext→host reply to command/complete.

type CommandExecuteParams

type CommandExecuteParams struct {
	Command   string          `json:"command"`
	Context   Context         `json:"context"`
	Arguments json.RawMessage `json:"arguments,omitempty"`
}

CommandExecuteParams is the host→ext dispatch of a registered slash-command.

type CommandExecuteResult

type CommandExecuteResult struct {
	Content string `json:"content,omitempty"`
}

CommandExecuteResult is the ext→host reply to command/execute.

type CommandRegistration

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

CommandRegistration declares a slash-command the extension exposes.

type Completion

type Completion struct {
	Value       string `json:"value"`
	Description string `json:"description,omitempty"`
}

Completion is one argument-completion suggestion.

type Context

type Context struct {
	Token string `json:"token"`
	Tier  Tier   `json:"tier"`
}

Context is the dispatch context carried by every host→ext event/hook/tool/command.

type DefaultHostDelegate

type DefaultHostDelegate struct{}

DefaultHostDelegate is the engine's headless delegate: NoUI, JSON-file kv, exec denied, session actions unavailable.

func (DefaultHostDelegate) ExecRun

func (DefaultHostDelegate) KVGet

func (DefaultHostDelegate) KVGet(ext, key string) (json.RawMessage, *RpcError)

func (DefaultHostDelegate) KVSet

func (DefaultHostDelegate) KVSet(ext, key string, value json.RawMessage) *RpcError

func (DefaultHostDelegate) SessionAppendEntry

func (DefaultHostDelegate) SessionSendMessage

func (DefaultHostDelegate) SessionSendUserMessage

func (DefaultHostDelegate) SessionSendUserMessage(string, json.RawMessage) (json.RawMessage, *RpcError)

func (DefaultHostDelegate) ToolUpdate

func (DefaultHostDelegate) UIRequest

type DefaultInboundHandler

type DefaultInboundHandler struct{}

DefaultInboundHandler answers ping and rejects everything else with MethodNotFound. Used when the host wires nothing richer.

func (DefaultInboundHandler) HandleNotification

func (DefaultInboundHandler) HandleNotification(string, json.RawMessage)

func (DefaultInboundHandler) HandleRequest

func (DefaultInboundHandler) HandleRequest(method string, _ json.RawMessage) (json.RawMessage, *RpcError)

type DiscoveredExtension

type DiscoveredExtension struct {
	Manifest ExtensionManifest
	Root     string
	Scope    Scope
}

DiscoveredExtension is a discovered extension: its manifest plus the directory it was found in (relative resources and args resolve against this root) and its scope.

type DiscoveryFailure

type DiscoveryFailure struct {
	Source string
	Err    string
}

DiscoveryFailure records a manifest that failed to parse.

type EventParams

type EventParams struct {
	Event string `json:"event"`
	// Seq is the per-connection monotonic sequence. Absent (a nil pointer) on the
	// out-of-band events_lost marker.
	Seq     *uint64         `json:"seq,omitempty"`
	Context Context         `json:"context"`
	Payload json.RawMessage `json:"payload,omitempty"`
}

EventParams is a fire-and-forget lifecycle/turn event delivered to a subscribed extension.

type ExtensionHost

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

ExtensionHost orchestrates the set of loaded extensions in load order.

func NewEmptyHost

func NewEmptyHost() *ExtensionHost

NewEmptyHost returns a host with no extensions — the zero-cost default when no extensions are configured. Every hook is a passthrough.

func (*ExtensionHost) BeforeAgentStart

func (h *ExtensionHost) BeforeAgentStart(ctx context.Context, systemPrompt string) string

BeforeAgentStart runs the before_agent_start hook on a system prompt, returning the possibly-rewritten prompt. Fail-open: a blocked/failed hook leaves it unchanged.

func (*ExtensionHost) BumpEpoch

func (h *ExtensionHost) BumpEpoch()

BumpEpoch bumps the epoch, invalidating every previously minted context token.

func (*ExtensionHost) Commands

func (h *ExtensionHost) Commands() []OwnedCommand

Commands returns every registered slash-command across all extensions.

func (*ExtensionHost) CompleteCommand

func (h *ExtensionHost) CompleteCommand(ctx context.Context, extName, command, partial string) []Completion

CompleteCommand asks the extension that owns command for argument completions given the partial text typed so far. Best-effort: returns nil on any error.

func (*ExtensionHost) Context

func (h *ExtensionHost) Context(tier Tier) Context

Context builds a fresh dispatch context. Session-mutating actions need TierCommand. The token embeds the current epoch so it is invalidated across reloads.

func (*ExtensionHost) DeferredTools

func (h *ExtensionHost) DeferredTools() []*ExtensionTool

DeferredTools returns deferred tool proxies.

func (*ExtensionHost) DispatchEvent

func (h *ExtensionHost) DispatchEvent(event string, payload json.RawMessage)

DispatchEvent is a fire-and-forget event fanout to every subscribed extension. Non-blocking: a slow or dead extension never stalls the caller.

func (*ExtensionHost) HasSubscriber

func (h *ExtensionHost) HasSubscriber(event string) bool

HasSubscriber reports whether any loaded extension subscribed to event.

func (*ExtensionHost) IsEmpty

func (h *ExtensionHost) IsEmpty() bool

IsEmpty reports whether no extensions loaded.

func (*ExtensionHost) Len

func (h *ExtensionHost) Len() int

Len is the number of successfully loaded extensions.

func (*ExtensionHost) Names

func (h *ExtensionHost) Names() []string

Names returns the loaded extension names, in load order.

func (*ExtensionHost) Reload

func (h *ExtensionHost) Reload(ctx context.Context, name string) error

Reload hot-reloads a single extension by name: notify it (session_shutdown reason reload), bump the epoch so every context token it still holds is invalidated, respawn its subprocess, re-run initialize to pick up its new registrations, then notify it (session_start reason reload). The caller re-registers the extension's tools via ToolsFor.

func (*ExtensionHost) RunCommand

func (h *ExtensionHost) RunCommand(ctx context.Context, extName, command string, arguments json.RawMessage) (CommandExecuteResult, *RpcError)

RunCommand dispatches a registered slash-command to its owning extension with a COMMAND-tier context. Pass extName to disambiguate a command registered by more than one extension; "" picks the first match in load order.

func (*ExtensionHost) RunHook

func (h *ExtensionHost) RunHook(ctx context.Context, hook HookType, input json.RawMessage) FoldedHook

RunHook runs a hook across every extension in load order, folding the chain. Each extension sees the prior extension's patch. Fail-open/closed per HookType.

func (*ExtensionHost) RunToolCallHook

func (h *ExtensionHost) RunToolCallHook(ctx context.Context, tool string, arguments json.RawMessage) FoldedHook

RunToolCallHook runs the tool_call hook (fail-closed) on a pending call.

func (*ExtensionHost) Shortcuts

func (h *ExtensionHost) Shortcuts() []OwnedShortcut

Shortcuts returns every keyboard shortcut across all extensions.

func (*ExtensionHost) ShutdownAll

func (h *ExtensionHost) ShutdownAll(ctx context.Context)

ShutdownAll gracefully shuts down every extension (5s grace each, then SIGKILL).

func (*ExtensionHost) Tools

func (h *ExtensionHost) Tools() []*ExtensionTool

Tools returns tool proxies for every eager tool every extension registered. Names are dotted <ext>.<tool>. Deferred tools are returned by DeferredTools.

func (*ExtensionHost) ToolsFor

func (h *ExtensionHost) ToolsFor(extName string) []*ExtensionTool

ToolsFor returns eager tool proxies for a single extension, minted at the CURRENT epoch. The frontend calls this after a Reload to re-register the reloaded extension's tools (old proxies carry a stale context).

type ExtensionInfo

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

ExtensionInfo identifies the extension in its handshake reply.

type ExtensionManifest

type ExtensionManifest struct {
	Name    string `toml:"name"`
	Version string `toml:"version"`
	// Protocol is the highest SEP protocol version the extension declares (default 1).
	Protocol     int          `toml:"protocol"`
	Run          RunSpec      `toml:"run"`
	Capabilities Capabilities `toml:"capabilities"`
	Resources    Resources    `toml:"resources"`
	// HookTimeoutMS is a per-extension hook timeout override, in milliseconds (0 = default).
	HookTimeoutMS int64 `toml:"hook_timeout_ms"`
	// Disabled skips the extension without deleting its manifest.
	Disabled bool `toml:"disabled"`
}

ExtensionManifest is a parsed extension.toml.

func ParseManifest

func ParseManifest(tomlText string) (ExtensionManifest, error)

ParseManifest parses a manifest from TOML text. It enforces the required fields (name, version, run.command) so a malformed manifest is rejected rather than silently defaulting.

func (ExtensionManifest) ResolvedEnv

func (m ExtensionManifest) ResolvedEnv() map[string]string

ResolvedEnv returns the [run] env map with ${env:VAR} references expanded against the host's current environment. Unset variables expand to empty strings.

type ExtensionProcess

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

ExtensionProcess is one extension subprocess.

func Spawn

func Spawn(spec SpawnSpec, handler InboundHandler) (*ExtensionProcess, error)

Spawn spawns the subprocess and starts its reader/writer goroutines.

func (*ExtensionProcess) Close

func (p *ExtensionProcess) Close()

Close tears down the current connection (kills the child, stops goroutines). Idempotent; safe to defer in callers/tests.

func (*ExtensionProcess) Generation

func (p *ExtensionProcess) Generation() uint64

Generation returns the current generation (increments on every Respawn).

func (*ExtensionProcess) IsAlive

func (p *ExtensionProcess) IsAlive() bool

IsAlive reports whether the connection is currently believed alive.

func (*ExtensionProcess) Notify

func (p *ExtensionProcess) Notify(method string, params json.RawMessage)

Notify sends a fire-and-forget notification.

func (*ExtensionProcess) PingHealth

func (p *ExtensionProcess) PingHealth(ctx context.Context, timeout time.Duration) bool

PingHealth health-probes with ping. Returns true if the extension answered within timeout.

func (*ExtensionProcess) Request

func (p *ExtensionProcess) Request(ctx context.Context, method string, params json.RawMessage, timeout time.Duration) (json.RawMessage, error)

Request sends a request and awaits its response, bounded by timeout and ctx.

func (*ExtensionProcess) Respawn

func (p *ExtensionProcess) Respawn() error

Respawn kills and re-spawns the child in place. Bumps the generation (invalidating any stale reader and failing every in-flight request), then starts a fresh connection. nextID is NOT reset, so ids never collide across generations.

func (*ExtensionProcess) SendEvent

func (p *ExtensionProcess) SendEvent(event string, ctx, payload json.RawMessage)

SendEvent enqueues an observe event on the bounded, lossy lane. Never fails — a shed event is the contract, not an error.

func (*ExtensionProcess) Shutdown

func (p *ExtensionProcess) Shutdown(ctx context.Context, grace time.Duration)

Shutdown gracefully stops the extension: send shutdown, wait up to grace for the reply, then force-kill. Always leaves the process dead.

type ExtensionTool

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

ExtensionTool is a tool exposed by an extension.

func NewExtensionTool

func NewExtensionTool(extName string, reg ToolRegistration, process *ExtensionProcess, toolCtx Context) *ExtensionTool

NewExtensionTool builds a proxy for one registered tool.

func (*ExtensionTool) Description

func (t *ExtensionTool) Description() string

Description returns the tool's description.

func (*ExtensionTool) Execute

func (t *ExtensionTool) Execute(ctx context.Context, args map[string]any) (string, error)

Execute forwards the call to the extension over tool/execute and returns the content, or an error when the extension reports is_error or the call fails.

func (*ExtensionTool) IsConcurrentSafe

func (t *ExtensionTool) IsConcurrentSafe() bool

IsConcurrentSafe reports false: extensions run in their own process with a per-extension ordered stream, so the registry serializes their tools (conservative until an extension opts in). Present for parity with the Rust Tool trait; core.Tool does not require it, so it is advisory.

func (*ExtensionTool) Name

func (t *ExtensionTool) Name() string

Name returns the dotted <extension>.<tool> name.

func (*ExtensionTool) Parameters

func (t *ExtensionTool) Parameters() map[string]any

Parameters returns the tool's JSON-schema parameters as a map.

type FoldedHook

type FoldedHook struct {
	// Blocked is true when the operation was vetoed; Reason carries why.
	Blocked bool
	Reason  string
	// Value is the (possibly modified) input to proceed with (valid when !Blocked).
	Value json.RawMessage
}

FoldedHook is the folded result of a whole hook chain.

func FoldHookChain

func FoldHookChain(hook HookType, input json.RawMessage, steps []hookStep) FoldedHook

FoldHookChain folds a hook chain over input, in load order. steps are the per-extension results in that order. This is the security-critical policy:

  • continue → value unchanged, next extension sees it.
  • modify → value replaced by the patch, next extension sees the patch.
  • block → short-circuit; the operation is vetoed (honored for every hook).
  • failed → for a fail-closed hook, block; for a fail-open hook, proceed.

type HookAction

type HookAction string

HookAction is the discriminator of a HookOutcome.

const (
	ActionContinue HookAction = "continue"
	ActionBlock    HookAction = "block"
	ActionModify   HookAction = "modify"
)

type HookOutcome

type HookOutcome struct {
	Action HookAction
	// Reason is set only for a block outcome (optional on the wire).
	Reason string
	// Patch is set only for a modify outcome (required for modify).
	Patch json.RawMessage
}

HookOutcome is an extension's reply to a hook. It marshals tagged by action:

{ "action": "continue" }
{ "action": "block", "reason": "..." }
{ "action": "modify", "patch": { ... } }

func (HookOutcome) MarshalJSON

func (h HookOutcome) MarshalJSON() ([]byte, error)

MarshalJSON serializes a HookOutcome tagged by action.

func (*HookOutcome) UnmarshalJSON

func (h *HookOutcome) UnmarshalJSON(b []byte) error

UnmarshalJSON enforces the tagged-union constraints the Rust serde enum does: an unknown action is rejected, and a modify without a patch is rejected.

type HookParams

type HookParams struct {
	Hook    string          `json:"hook"`
	Context Context         `json:"context"`
	Input   json.RawMessage `json:"input"`
}

HookParams is the host→ext hook intercept.

type HookType

type HookType int

HookType classifies a hook by its failure policy and default timeout.

const (
	HookToolCall HookType = iota
	HookUserBash
	HookToolResult
	HookInput
	HookBeforeAgentStart
	HookContext
	HookBeforeProviderRequest
	HookMessageEnd
	HookSessionBeforeCompact
	HookSessionBeforeTree
)

func HookTypeFromName

func HookTypeFromName(name string) (HookType, bool)

HookTypeFromName maps a wire name to its HookType.

func (HookType) DefaultTimeout

func (h HookType) DefaultTimeout() time.Duration

DefaultTimeout is 60s for fail-closed hooks (they gate execution), 5s for fail-open. Manifest hook_timeout_ms overrides this.

func (HookType) FailClosed

func (h HookType) FailClosed() bool

FailClosed reports whether this hook blocks the operation when an extension times out or crashes. tool_call and user_bash gate execution; everything else fails open (proceeds).

func (HookType) String

func (h HookType) String() string

String returns the wire name of the hook.

type HostDelegate

type HostDelegate interface {
	UIRequest(ext string, params json.RawMessage) (json.RawMessage, *RpcError)
	KVGet(ext, key string) (json.RawMessage, *RpcError)
	KVSet(ext, key string, value json.RawMessage) *RpcError
	ExecRun(ext string, params json.RawMessage) (json.RawMessage, *RpcError)
	SessionSendMessage(ext string, params json.RawMessage) (json.RawMessage, *RpcError)
	SessionSendUserMessage(ext string, params json.RawMessage) (json.RawMessage, *RpcError)
	SessionAppendEntry(ext string, params json.RawMessage) (json.RawMessage, *RpcError)
	ToolUpdate(ext string, params json.RawMessage)
}

HostDelegate is the host's side of ext→host requests. Embed DefaultHostDelegate to inherit the headless defaults and override only what a richer frontend needs.

type HostInfo

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

HostInfo identifies the engine host to the extension at handshake.

type InboundHandler

type InboundHandler interface {
	HandleRequest(method string, params json.RawMessage) (json.RawMessage, *RpcError)
	HandleNotification(method string, params json.RawMessage)
}

InboundHandler handles ext→host requests and notifications. HandleRequest may block (a ui/confirm bridge parks until a human answers); the process runs each inbound request in its own goroutine so a slow handler never stalls the reader.

type InitializeParams

type InitializeParams struct {
	ProtocolVersion int                        `json:"protocol_version"`
	Host            HostInfo                   `json:"host"`
	Workspace       WorkspaceInfo              `json:"workspace"`
	Session         *SessionInfo               `json:"session,omitempty"`
	Mode            string                     `json:"mode"`
	UICapabilities  []string                   `json:"ui_capabilities,omitempty"`
	Flags           map[string]json.RawMessage `json:"flags,omitempty"`
	// CapabilitiesEnabled is an opaque capability map the host may advertise.
	CapabilitiesEnabled json.RawMessage `json:"capabilities_enabled,omitempty"`
}

InitializeParams is the host→ext handshake.

func (InitializeParams) Validate

func (p InitializeParams) Validate() error

Validate enforces the required fields the JSON Schema marks required and that serde rejects in the Rust host: protocol_version must be present (>= 1).

type InitializeResult

type InitializeResult struct {
	ProtocolVersion int           `json:"protocol_version"`
	Extension       ExtensionInfo `json:"extension"`
	Registrations   Registrations `json:"registrations"`
}

InitializeResult is the extension's handshake reply.

type LoadFailure

type LoadFailure struct {
	Name string
	Err  string
}

LoadFailure records an extension that failed to load (spawn/handshake).

type LogParams

type LogParams struct {
	Level   string          `json:"level"`
	Message string          `json:"message"`
	Fields  json.RawMessage `json:"fields,omitempty"`
}

LogParams is a structured log line folded into host tracing.

type Message

type Message struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `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 the JSON-RPC 2.0 envelope. All four frame shapes share this struct; which fields are present determines the shape:

  • request: id + method (+ optional params)
  • notification: method, no id
  • success response: id + result
  • error response: id + error

omitempty keeps absent fields off the wire so a request never carries a result/error key. ID/Params/Result are json.RawMessage so an arbitrary inbound line round-trips (the id may be an int or a string).

func NewErrorResponse

func NewErrorResponse(id json.RawMessage, err *RpcError) Message

NewErrorResponse builds an error response frame echoing id (id may be nil).

func NewNotification

func NewNotification(method string, params json.RawMessage) Message

NewNotification builds a notification frame (no id, no reply expected).

func NewRequest

func NewRequest(id json.RawMessage, method string, params json.RawMessage) Message

NewRequest builds a request frame.

func NewSuccess

func NewSuccess(id json.RawMessage, result json.RawMessage) Message

NewSuccess builds a success response frame echoing id.

func (*Message) IsNotification

func (m *Message) IsNotification() bool

IsNotification reports whether this frame is a notification (method, no id).

func (*Message) IsRequest

func (m *Message) IsRequest() bool

IsRequest reports whether this frame is a request (has both id and method).

func (*Message) IsResponse

func (m *Message) IsResponse() bool

IsResponse reports whether this frame is a response (has id, no method).

type OwnedCommand

type OwnedCommand struct {
	Extension string
	Command   CommandRegistration
}

OwnedCommand pairs a registered command with the extension that owns it.

type OwnedShortcut

type OwnedShortcut struct {
	Extension string
	Shortcut  ShortcutRegistration
}

OwnedShortcut pairs a keyboard shortcut with the extension that owns it.

type Registrations

type Registrations struct {
	Tools         []ToolRegistration     `json:"tools,omitempty"`
	Commands      []CommandRegistration  `json:"commands,omitempty"`
	Flags         []string               `json:"flags,omitempty"`
	Shortcuts     []ShortcutRegistration `json:"shortcuts,omitempty"`
	Subscriptions []string               `json:"subscriptions,omitempty"`
}

Registrations is the set of things an extension registers at handshake (or later via registry/update).

type Resources

type Resources struct {
	Skills  string `toml:"skills"`
	Prompts string `toml:"prompts"`
	Themes  string `toml:"themes"`
}

Resources are directories the extension contributes (skills, prompts, themes).

type RpcError

type RpcError struct {
	Code    int             `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

RpcError is a JSON-RPC error object. It implements error.

func NewRpcError

func NewRpcError(code int, message string) *RpcError

NewRpcError builds an RpcError with no data payload.

func (*RpcError) Error

func (e *RpcError) Error() string

type RunSpec

type RunSpec struct {
	// Command is the executable to spawn (e.g. node, python3, an absolute path).
	Command string   `toml:"command"`
	Args    []string `toml:"args"`
	// Env holds extra env vars; values may reference ${env:VAR}.
	Env map[string]string `toml:"env"`
}

RunSpec is how to launch the extension subprocess.

type Scope

type Scope int

Scope records where a manifest was discovered. Project extensions only load in trusted workspaces; the host uses this to apply that policy.

const (
	ScopeGlobal Scope = iota
	ScopeProject
)

func (Scope) String

func (s Scope) String() string

type SessionInfo

type SessionInfo struct {
	ID string `json:"id,omitempty"`
}

SessionInfo optionally identifies the active session at handshake.

type ShortcutRegistration

type ShortcutRegistration struct {
	Key         string `json:"key"`
	Command     string `json:"command"`
	Description string `json:"description,omitempty"`
}

ShortcutRegistration binds a keyboard chord to one of the extension's commands. Only frontends with a key surface (the TUI) honor these.

type SpawnSpec

type SpawnSpec struct {
	Command string
	Args    []string
	// Env is the extra env the extension legitimately needs (its manifest
	// [run] env, SEP-protocol vars). These are the ONLY env the child sees
	// beyond the small EnvPassthrough allow-list — the host's full environment
	// is scrubbed so ambient secrets can't leak in. See buildChildEnv.
	Env map[string]string
	// Cwd is the working directory for the child (the extension's root); "" inherits.
	Cwd string
}

SpawnSpec is how to launch the subprocess.

type Tier

type Tier string

Tier is whether a dispatch may only observe (event) or may mutate the session (command). Session-mutating ext→host actions require command.

const (
	TierEvent   Tier = "event"
	TierCommand Tier = "command"
)

type ToolExecuteParams

type ToolExecuteParams struct {
	CallID    string          `json:"call_id"`
	Tool      string          `json:"tool"`
	Arguments json.RawMessage `json:"arguments"`
	Context   Context         `json:"context"`
}

ToolExecuteParams is the host→ext dispatch of a registered tool.

func (ToolExecuteParams) Validate

func (p ToolExecuteParams) Validate() error

Validate enforces the required call_id the Rust host requires (serde rejects a missing call_id).

type ToolExecuteResult

type ToolExecuteResult struct {
	Content string          `json:"content"`
	IsError bool            `json:"is_error,omitempty"`
	Details json.RawMessage `json:"details,omitempty"`
}

ToolExecuteResult is the ext→host reply to tool/execute.

type ToolRegistration

type ToolRegistration struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Parameters  json.RawMessage `json:"parameters"`
	Deferred    bool            `json:"deferred,omitempty"`
}

ToolRegistration declares a tool the extension exposes.

type ToolUpdateParams

type ToolUpdateParams struct {
	CallID   string          `json:"call_id"`
	Message  string          `json:"message,omitempty"`
	Progress *float64        `json:"progress,omitempty"`
	Details  json.RawMessage `json:"details,omitempty"`
}

ToolUpdateParams is a progress notification for an in-flight tool/execute.

type WorkspaceInfo

type WorkspaceInfo struct {
	Root    string `json:"root"`
	Trusted bool   `json:"trusted"`
}

WorkspaceInfo describes the workspace root and whether it is trusted.

Jump to

Keyboard shortcuts

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