resourceprovider

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 20 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 resourceprovider runs terminal resource providers: it owns the process boundary, the protocol envelope, the compiled matcher snapshot, and the host-side cache and concurrency policy.

Two seams, each narrow on purpose:

  • Provider is the in-process adapter the Manager consumes. CommandProvider is the default implementation; tests use an in-memory fake; a future resident transport implements the same two methods.
  • The executable protocol is the language-agnostic boundary. It returns match declarations and resource data, never a Sidecar interface.

A process boundary is crash isolation, not a sandbox. Enabling a provider trusts that executable with the user's full OS privileges.

See docs/reference/terminal-resource-provider-protocol.md.

Index

Constants

View Source
const (
	DefaultMaxConcurrent            = 4
	DefaultMaxConcurrentPerProvider = 2
)

Default concurrency caps. They are small on purpose: a provider invocation is a process spawn, and on a machine with an endpoint security agent every spawn carries a large fixed tax. Excess work queues and stays cancellable.

View Source
const (
	MethodDescribe = "describe"
	MethodResolve  = "resolve"
)

Method names. An unknown method must return an internal error rather than crash the provider; the host never sends one.

Variables

View Source
var HostVersion = "0.0.0"

HostVersion identifies Sidecar to providers. The app sets it once at startup; until then providers see the placeholder the protocol examples use.

Functions

func AsResourceError

func AsResourceError(err error) *resource.Error

AsResourceError turns any error from a Provider into the typed error a view can render. A provider's own typed failure passes through unchanged; a transport failure is mapped; anything else is internal.

func BuildEnv

func BuildEnv(passEnv []string, host []string) []string

BuildEnv returns the complete environment for one invocation: the documented base, plus the current values of the names in passEnv, and nothing else.

host is an os.Environ()-shaped slice, so a test can build an environment without touching the process's own and without a magic sentinel.

A passEnv entry is a name only. Sidecar never accepts an inline secret value in configuration, never logs a passed value, and never renders one — which is also why an entry containing "=" is refused rather than split.

The base set wins on conflict: naming PATH in passEnv cannot change the child's PATH. That falls out of adding the base first and add() being first-write-wins, which is the documented rule.

func OutcomeCode

func OutcomeCode(err error) string

OutcomeCode is the single token a log line records for an invocation. It is either "ok", a typed error code, or a transport reason — never a message.

Types

type CommandConfig

type CommandConfig struct {
	Instance string
	Argv     []string
	// Dir is the neutral working directory — a Sidecar config directory, never
	// a selected repository.
	Dir string
	// PassEnv names variables whose current values are inherited on top of the
	// documented base environment.
	PassEnv []string
	// ClaimHosts is the instance configuration's claimed hostnames, already
	// validated and lowercased by internal/config. It is host-side data: it
	// never reaches the child process or the protocol.
	ClaimHosts []string
	// HostEnv is the os.Environ()-shaped environment to draw from.
	HostEnv []string
	// ResolveTimeout is clamped; zero takes the default.
	ResolveTimeout time.Duration
	// Runner defaults to ExecRunner.
	Runner Runner
	// Host identifies Sidecar to the provider.
	Host HostInfo
	// Log receives metadata-only invocation records. Nil discards them.
	Log *slog.Logger
}

CommandConfig is everything a CommandProvider needs. It is resolved once, at construction, so no invocation reads configuration or the environment.

type CommandProvider

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

CommandProvider is the default Provider: a short-lived child process per request, one JSON object in, one JSON object out. It also carries the instance configuration's claimed hosts, which are host-side data a provider process never sees.

func NewCommandProvider

func NewCommandProvider(cfg CommandConfig) (*CommandProvider, error)

NewCommandProvider builds a provider over a configured argv.

func (*CommandProvider) Argv

func (p *CommandProvider) Argv() []string

Argv exposes the resolved command for diagnostics. It is a copy.

func (*CommandProvider) ClaimHosts added in v1.3.0

func (p *CommandProvider) ClaimHosts() []string

ClaimHosts reports the instance's claimed hostnames. It is a copy.

func (*CommandProvider) Describe

func (p *CommandProvider) Describe(ctx context.Context) (Description, error)

Describe runs the describe method and validates the result.

func (*CommandProvider) Env

func (p *CommandProvider) Env() []string

Env exposes the computed child environment for diagnostics. Values are real, so a caller that prints this must redact — `terminal-links check` reports names only.

func (*CommandProvider) Instance

func (p *CommandProvider) Instance() string

Instance reports the configured instance ID.

func (*CommandProvider) Resolve

Resolve runs the resolve method and sanitizes the document.

func (*CommandProvider) ResolveTimeout

func (p *CommandProvider) ResolveTimeout() time.Duration

ResolveTimeout reports the clamped per-invocation timeout.

type CompiledMatcher

type CompiledMatcher struct {
	// Instance is the configured provider instance ID.
	Instance string
	// ID is the provider-stable matcher ID stored in resource references.
	ID string
	// Pattern is the RE2 source, kept for diagnostics.
	Pattern string
	// Priority orders matchers within one provider; higher runs earlier.
	Priority int
	// Order is the instance's position in configuration, which is the outer
	// precedence key.
	Order int
	// contains filtered or unexported fields

} // Regexp returns the compiled expression. The whole match is the locator.

CompiledMatcher is one live external matcher. It is immutable once built and carries its compiled RE2 so the scanner never compiles anything on a frame.

func (CompiledMatcher) Regexp

func (m CompiledMatcher) Regexp() *regexp.Regexp

type DescribedSet

type DescribedSet struct {
	Instance string
	Order    int
	Matchers []Matcher
	// ClaimHosts is the instance configuration's claimed hostnames. It travels
	// with the described matchers so a claimed URL is only ever reclassified by
	// a matcher from this same set.
	ClaimHosts []string
}

DescribedSet is one instance's contribution to a snapshot, in configured order.

type Description

type Description struct {
	Info     Info
	Matchers []Matcher
}

Description is a validated describe result. Reaching this type means every pattern compiled, every ID was unique, and every bound held.

func ValidateDescription

func ValidateDescription(instance string, info *Info, matchers []Matcher) (Description, error)

ValidateDescription sanitizes and checks a describe response. It is all-or-nothing on purpose: a provider that declares one uncompilable pattern has a bug the user needs to see, and silently publishing its other matchers would hide it while changing what the scanner recognizes.

The returned Description is safe to publish; the returned error, when non-nil, is a *TransportError with ReasonInvalidDescribe.

type ExecRunner

type ExecRunner struct{}

ExecRunner runs a real child process in its own process group.

func (ExecRunner) Run

func (ExecRunner) Run(ctx context.Context, spec RunSpec) (RunResult, error)

Run starts the command, writes stdin, drains stdout and stderr concurrently into bounded sinks, and waits. On timeout or cancellation it kills the whole process group — so a forked descendant dies with it — then finishes draining and reaps.

Deliberately not exec.CommandContext: that kills only the direct child, which leaves a descendant holding the stdout pipe and hangs the drain forever.

type HostInfo

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

HostInfo identifies Sidecar to a provider. It carries no user, no project, no repository, and no environment.

type Info

type Info struct {
	Kind    string `json:"kind,omitempty"`
	Name    string `json:"name,omitempty"`
	Version string `json:"version,omitempty"`
	// DocsURL is the only executable-declared Setup action Sidecar will
	// follow, and only after user confirmation. It passes the same http/https
	// validation as a resource's sourceUrl.
	DocsURL string `json:"docsUrl,omitempty"`
}

Info is the informational identity a provider declares. None of it can rename or collide with a configured instance ID.

type Manager

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

Manager is the host-owned, long-lived owner of provider process policy: it describes instances, publishes the matcher snapshot, caches successful resolves, deduplicates identical in-flight resolves, and bounds concurrency.

It is not a Sidecar plugin. It has no tab, no View, and no independent lifecycle; the app injects its read-only snapshot and its Resolve method into whichever surface needs them, so the project Workspace and the global Workspaces browser share one status, cache, and process policy.

func NewManager

func NewManager(opts ManagerOptions) *Manager

NewManager builds a manager with no providers.

func (*Manager) DescribeAll

func (m *Manager) DescribeAll(ctx context.Context) []Status

DescribeAll describes every enabled instance concurrently, publishes a new matcher snapshot from the results, and returns each instance's status.

It never runs on the first-frame path. The app starts it from a cancellable command that waits on the ready-frame latch.

func (*Manager) Resolve

func (m *Manager) Resolve(ctx context.Context, ref resource.Reference, refresh bool) (resource.Document, error)

Resolve turns a reference into a document. Successful results are cached and identical in-flight requests share one invocation.

refresh bypasses freshness for this call and re-caches the result. It does not drop the previous entry up front: a failed refresh must leave the last good document available to whoever still holds it.

func (*Manager) SetProviders

func (m *Manager) SetProviders(providers []Provider, disabled []string)

SetProviders replaces the configured set, in configuration order — which is matcher precedence. disabled names instances that are configured but turned off; they keep a status and contribute no matchers.

An instance that disappears becomes StateRemoved rather than vanishing, so a diagnostic surface can still explain why a saved reference is not resolving.

func (*Manager) Snapshot

func (m *Manager) Snapshot() *Snapshot

Snapshot returns the live matcher snapshot. It never returns nil.

func (*Manager) SnapshotError

func (m *Manager) SnapshotError() error

SnapshotError reports the most recent failed snapshot replacement.

func (*Manager) Status

func (m *Manager) Status(instance string) (Status, bool)

Status returns one instance's diagnostic state.

func (*Manager) Statuses

func (m *Manager) Statuses() []Status

Statuses returns every known instance's diagnostic state, in configuration order followed by removed instances.

type ManagerOptions

type ManagerOptions struct {
	MaxConcurrent            int
	MaxConcurrentPerProvider int
	Log                      *slog.Logger
	// Now is injectable for cache-expiry tests.
	Now func() time.Time
}

ManagerOptions configure a Manager. The zero value is usable.

type Matcher

type Matcher struct {
	ID       string `json:"id"`
	Pattern  string `json:"pattern"`
	Priority int    `json:"priority,omitempty"`
}

Matcher is one declared resource-key shape. The pattern is Go/RE2 and the whole match is the locator: there are no capture-group templates and no provider code runs in the scanner.

type Options

type Options struct {
	// Dir is the neutral working directory every child gets — a Sidecar config
	// directory, never a selected repository.
	Dir string
	// HostEnv is the os.Environ()-shaped environment to draw the documented
	// base from. Nil means the current process environment.
	HostEnv []string
	// Runner overrides the process adapter. Nil means ExecRunner.
	Runner Runner
	// Log receives metadata-only invocation records.
	Log *slog.Logger
}

Options carries the host context a set of providers is built with. Everything in it is resolved before any child runs.

type Provider

type Provider interface {
	// Instance is the configured provider instance ID. It is host-owned: a
	// provider cannot rename itself, and a response never changes it.
	Instance() string

	// Describe reports what the provider is and what it can recognize. It must
	// be local, fast, and non-interactive: no credential prompt, no network.
	Describe(ctx context.Context) (Description, error)

	// Resolve turns one locator into one document. It may perform network I/O.
	Resolve(ctx context.Context, ref resource.Reference) (resource.Document, error)
}

Provider is the whole of what the Manager may ask an implementation to do. Both methods must be safe for concurrent use and must honor ctx.

func FromConfig

func FromConfig(cfg config.TerminalResourcesConfig, opts Options) ([]Provider, []string, error)

FromConfig builds one CommandProvider per enabled configured instance, in configuration order — which is matcher precedence — and returns the IDs of the instances that are configured but disabled.

It performs no I/O: it does not look up the command on PATH, does not stat anything, and does not start a process. That is what makes it safe to call from a command after the first frame without having done anything before it.

type Request

type Request struct {
	Protocol   string         `json:"protocol"`
	Method     string         `json:"method"`
	Instance   string         `json:"instance"`
	DeadlineMs int64          `json:"deadlineMs"`
	Host       *HostInfo      `json:"host,omitempty"`
	Params     *ResolveParams `json:"params,omitempty"`
}

Request is the single JSON object written to a provider's stdin.

DeadlineMs is advisory but accurate: it is exactly the timeout the host is about to enforce. A provider that budgets its own I/O inside it can return a typed `unavailable` — which gives the user a real error card and a working Retry — instead of being SIGKILLed, which gives them an opaque transport failure.

type ResolveParams

type ResolveParams struct {
	Matcher string `json:"matcher"`
	Locator string `json:"locator"`
}

ResolveParams is the whole of what a resolve request carries. Widening it requires a named capability and an explicit per-instance permission, not a silent field addition.

type Response

type Response struct {
	Protocol string                 `json:"protocol"`
	Provider *Info                  `json:"provider,omitempty"`
	Matchers []Matcher              `json:"matchers,omitempty"`
	Resource *resource.WireDocument `json:"resource,omitempty"`
	Error    *resource.WireError    `json:"error,omitempty"`
}

Response is the single JSON object read from a provider's stdout. Exactly one of Provider+Matchers (describe), Resource (resolve), or Error is meaningful.

type RunResult

type RunResult struct {
	Stdout          []byte
	StdoutBytes     int
	StdoutTruncated bool
	StderrBytes     int
	ExitCode        int
	Duration        time.Duration
	// TimedOut reports that the process group was killed because ctx expired
	// or was canceled, rather than the child exiting on its own.
	TimedOut bool
}

RunResult is what an invocation produced. Stderr content is never present: only its byte count, which is all the protocol allows Sidecar to keep.

type RunSpec

type RunSpec struct {
	// Argv is executed directly. No shell, ever. Argv[0] may be an absolute
	// path or resolve through PATH.
	Argv []string
	// Dir is a neutral Sidecar config directory, never a selected repository.
	Dir string
	// Env is the complete environment. Nothing is inherited implicitly.
	Env []string
	// Stdin is written once and then closed.
	Stdin []byte
	// MaxStdout bounds what is retained from stdout. The stream keeps being
	// drained past the bound so the child cannot block on a full pipe; the
	// excess is counted and discarded.
	//
	// There is no stderr equivalent, and that is the contract, not an
	// omission: stderr is never retained at all, and stopping its drain at a
	// byte bound would deadlock a chatty provider against a full pipe.
	MaxStdout int
}

RunSpec is one invocation of a provider executable. It is deliberately a value with no callbacks: everything the child sees is decided before it starts, and nothing about the host leaks in.

type Runner

type Runner interface {
	Run(ctx context.Context, spec RunSpec) (RunResult, error)
}

Runner is the process adapter. The default implementation spawns a real child; tests substitute a fake to exercise the protocol layer without a process, and the executable fixture tests exercise the real one.

type Snapshot

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

Snapshot is an immutable, ordered set of compiled matchers. The scanner holds one for the duration of a scan; a replacement never mutates one in place.

It also carries each instance's claimed hosts, keyed by instance ID. Claims ride on the same snapshot as the matchers so that a claimed URL can only be reclassified by a matcher that is live in exactly this generation — and so that a refused replacement keeps claims and matchers consistent with each other.

func (*Snapshot) ClaimHosts added in v1.3.0

func (s *Snapshot) ClaimHosts(instance string) []string

ClaimHosts reports an instance's claimed hostnames in their normalized, lowercase form. Unknown instances return nil.

func (*Snapshot) Generation

func (s *Snapshot) Generation() uint64

Generation identifies this snapshot. Cache entries and in-flight resolves are scoped to it, so a re-describe cannot serve a document keyed by a matcher set that no longer exists.

func (*Snapshot) Len

func (s *Snapshot) Len() int

Len reports how many matchers are live.

func (*Snapshot) Lookup

func (s *Snapshot) Lookup(instance, id string) (CompiledMatcher, bool)

Lookup finds a matcher by instance and ID.

func (*Snapshot) Matchers

func (s *Snapshot) Matchers() []CompiledMatcher

Matchers returns the ordered matchers. The slice is a copy; the compiled expressions inside it are shared and safe for concurrent use.

func (*Snapshot) TerminalMatchers

func (s *Snapshot) TerminalMatchers() []terminallink.ResourceMatcher

TerminalMatchers adapts the snapshot into the scanner's vocabulary, already in precedence order. It is the only crossing between provider machinery and the scanner: terminallink learns a pattern and a reference, never a process, a document, or this package.

Each matcher carries its instance's claimed hosts. That is how the URL-yield rule reaches the scanner without widening this crossing: the scanner sees a host list on the same value that already named the pattern and the reference, and it can only reclassify a built-in URL span when one of those hosts matches AND this matcher matches the entire URL.

type SnapshotStore

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

SnapshotStore holds the current snapshot and swaps it atomically.

A failed replacement keeps the previous snapshot for the remainder of the process and reports the new failure. That is deliberate: dropping working matchers because a later describe went wrong would turn a provider hiccup into terminal output silently losing links, and relaunch already starts clean.

func NewSnapshotStore

func NewSnapshotStore() *SnapshotStore

NewSnapshotStore returns a store holding an empty snapshot.

func (*SnapshotStore) Current

func (s *SnapshotStore) Current() *Snapshot

Current returns the live snapshot. It never returns nil.

func (*SnapshotStore) LastError

func (s *SnapshotStore) LastError() error

LastError reports the most recent failed replacement, or nil if the last replacement succeeded.

func (*SnapshotStore) Replace

func (s *SnapshotStore) Replace(sets []DescribedSet) error

Replace compiles every declared matcher and publishes a new snapshot. On any failure the previous snapshot stays live and the error is recorded.

type State

type State string

State is a provider instance's readiness. It is explicit rather than inferred, because "describe has not returned yet" and "this matcher was deleted" must never be the same value: restore has to be able to keep an armed resource tab through the first, and only the user's own close removes one.

const (
	// StateUnchecked is the starting state: configured, never described.
	StateUnchecked State = "unchecked"
	// StateReady means the last describe succeeded and its matchers are live.
	StateReady State = "ready"
	// StateTemporarilyFailed means describe failed in a way a retry might fix.
	StateTemporarilyFailed State = "temporarily-failed"
	// StateIncompatible means the provider answered but does not speak this
	// protocol version, or its describe result cannot be published.
	StateIncompatible State = "incompatible"
	// StateDisabled means configuration turned this instance off.
	StateDisabled State = "disabled"
	// StateRemoved means the instance is no longer in configuration. Armed
	// references to it are preserved, not pruned.
	StateRemoved State = "removed"
)

func (State) Live

func (s State) Live() bool

Live reports whether an instance's matchers should be in the snapshot. Only a ready provider contributes; every other state contributes nothing while preserving whatever is already saved.

type Status

type Status struct {
	Instance     string
	State        State
	Info         Info
	MatcherCount int
	LastChecked  time.Time
	// LastError is the typed error of the last failed describe, or nil.
	LastError *resource.Error
	// LastOutcome is the single-token outcome of the last describe.
	LastOutcome string
	Duration    time.Duration
}

Status is one instance's diagnostic state. It carries no locator, no document, and no provider output.

type TransportError

type TransportError struct {
	Instance string
	Method   string
	Reason   TransportReason
	Detail   string
	Err      error
}

TransportError is a failure of the process boundary rather than of the service. It deliberately carries no stdout, no stderr, and no locator: the Detail is host-authored text, so logging or rendering it cannot leak provider output.

func (*TransportError) Error

func (e *TransportError) Error() string

func (*TransportError) ResourceError

func (e *TransportError) ResourceError() *resource.Error

ResourceError maps a transport failure onto the typed code a card shows.

The mapping is deliberate: `unavailable` means "the thing on the other end did not answer in time", which is what a timeout is from the user's side; `invalid_config` means "this instance is not set up", which is what an unstartable command is; everything else is the provider misbehaving, which is `internal` and retryable because a retry is free and sometimes works.

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

type TransportReason

type TransportReason string

TransportReason names the ways an invocation can fail without the provider ever having told Sidecar anything typed. Every one of them is attributed to the provider, never to the service it talks to.

const (
	// ReasonSpawn is a command that could not be started at all: not on PATH,
	// not executable, no such directory.
	ReasonSpawn TransportReason = "spawn"
	// ReasonExit is a non-zero exit status.
	ReasonExit TransportReason = "exit"
	// ReasonTimeout is exceeding the configured timeout.
	ReasonTimeout TransportReason = "timeout"
	// ReasonCanceled is the caller withdrawing the request.
	ReasonCanceled TransportReason = "canceled"
	// ReasonMalformed is no JSON or unparseable JSON on stdout.
	ReasonMalformed TransportReason = "malformed"
	// ReasonExtraOutput is more than one top-level JSON value on stdout.
	ReasonExtraOutput TransportReason = "extra-output"
	// ReasonOversize is stdout past the response byte limit.
	ReasonOversize TransportReason = "oversize"
	// ReasonProtocol is a missing or mismatched protocol field.
	ReasonProtocol TransportReason = "protocol"
	// ReasonInvalidDescribe is a describe result that failed host validation:
	// an uncompilable pattern, a duplicate matcher ID, a bound exceeded.
	ReasonInvalidDescribe TransportReason = "invalid-describe"
	// ReasonInvalidRequest is a request the host refused to send.
	ReasonInvalidRequest TransportReason = "invalid-request"
	// ReasonShape is a response that is not exactly one of the three permitted
	// shapes: a describe result, a resource result, or a typed error.
	ReasonShape TransportReason = "shape"
	// ReasonInvalidResource is a resource object the host cannot render and
	// cannot truncate its way out of — one with no identity or no title.
	ReasonInvalidResource TransportReason = "invalid-resource"
)

Jump to

Keyboard shortcuts

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