resource

package
v1.12.0 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 8 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 resource holds the presentation-neutral resource document a terminal resource provider returns, and the validation and sanitization Sidecar runs before any provider-supplied byte reaches view state.

Nothing here knows about Jira, HTTP, subprocesses, or the protocol envelope. The wire shapes in wire.go are the JSON the protocol document specifies; the domain types are what the rest of Sidecar is allowed to see. Every path from wire to domain goes through Sanitize*, so a caller cannot accidentally hand unvalidated provider text to a renderer.

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

Index

Constants

View Source
const (
	// MaxResponseBytes caps one invocation's stdout.
	MaxResponseBytes = 256 * 1024
	// MaxBodyBytes caps the sanitized body text.
	MaxBodyBytes = 64 * 1024
	// MaxFields caps the ordered label/value grid.
	MaxFields = 24
	// MaxFieldLabelChars and MaxFieldValueChars bound one grid cell.
	MaxFieldLabelChars = 64
	MaxFieldValueChars = 512

	// MaxTitleChars and MaxSubtitleChars bound the header lines.
	MaxTitleChars    = 300
	MaxSubtitleChars = 120

	// MaxIdentityChars and MaxLocatorChars bound the two identifiers that can
	// reach persisted state.
	MaxIdentityChars = 200
	MaxLocatorChars  = 200

	// MaxURLChars bounds sourceUrl and docsUrl.
	MaxURLChars = 2048

	// MaxMatchersPerProvider, MaxPatternChars, MaxMatchesPerLine and
	// MaxProviders bound the scanner's exposure to configuration.
	MaxMatchersPerProvider = 32
	MaxPatternChars        = 512
	MaxMatchesPerLine      = 32
	MaxProviders           = 16
)

Bounds from the protocol document's "Limits" table. They are defaults the host owns: a provider must never assume anything larger. Character bounds count runes, not bytes, so a multi-byte title is truncated where a reader would expect.

View Source
const (
	// MaxStatusLabelChars bounds status.label, which renders as one pill.
	MaxStatusLabelChars = 64
	// MaxMessageChars bounds a typed error's display message.
	MaxMessageChars = 512
	// MaxSetupHintChars bounds the copyable setup hint.
	MaxSetupHintChars = 512
	// MaxProviderKindChars, MaxProviderNameChars and MaxProviderVersionChars
	// bound the informational describe strings.
	MaxProviderKindChars    = 64
	MaxProviderNameChars    = 64
	MaxProviderVersionChars = 64
	// MaxMatcherIDChars bounds a matcher ID, which is persisted in resource
	// references.
	MaxMatcherIDChars = 64
	// MaxInstanceIDChars bounds a configured provider instance ID, which is
	// also persisted.
	MaxInstanceIDChars = 64
)

The rest of the Limits table. These were host choices during the draft and are now published values the protocol document points back at, so changing one changes the contract.

View Source
const (
	DescribeTimeout       = 5 * time.Second
	DefaultResolveTimeout = 10 * time.Second
	MinResolveTimeout     = time.Second
	MaxResolveTimeout     = 60 * time.Second
)

Timeouts. describe is local and must be fast; resolve may cross a network.

View Source
const (
	DefaultFreshFor = 60 * time.Second
	MinFreshFor     = 10 * time.Second
	MaxFreshFor     = 15 * time.Minute
)

Freshness clamps for the provider's freshForSeconds hint. Absent or zero means "no hint" and takes the default; anything else is clamped into [MinFreshFor, MaxFreshFor].

View Source
const Protocol = "sidecar.terminal-resource/v1"

Protocol identifies the wire contract Sidecar speaks. A response that does not carry exactly this string is a transport failure, not a service failure.

Variables

This section is empty.

Functions

func ClampFreshFor

func ClampFreshFor(seconds float64) time.Duration

ClampFreshFor turns a provider's freshForSeconds hint into a duration the cache will honor. Negative and absurd values are not errors; they are hints the host declines to follow.

func ClampResolveTimeout

func ClampResolveTimeout(d time.Duration) time.Duration

ClampResolveTimeout brings a configured timeout into range. A non-positive value means "unset" and takes the default.

func DefaultRetryable

func DefaultRetryable(code Code) bool

DefaultRetryable is the protocol table's default for a code. It is only ever a fallback: a response's own `retryable` field is authoritative, and the host must not infer retryability from the code when the provider stated it.

func RenderSafeMarkdown

func RenderSafeMarkdown(r *markdown.Renderer, text string, width int) []string

RenderSafeMarkdown renders provider body text through the shared renderer with the resource sanitizer on both sides. The renderer is passed in so this package does not own renderer lifetime or caching.

func SafeMarkdownSource

func SafeMarkdownSource(text string) string

SafeMarkdownSource rewrites Markdown source so that parsing it cannot produce a link destination:

  • `<` is escaped, which removes raw HTML, HTML comments, and `<...>` autolinks in one move;
  • `![alt](dest)` and `![alt][ref]` collapse to their alt text;
  • `[label](dest)`, `[label][ref]` and `[label][]` collapse to their label;
  • link reference definitions are dropped, and a shortcut `[label]` whose definition was dropped loses its brackets;
  • fenced code blocks and inline code spans are copied verbatim, since code cannot create a link and rewriting it would corrupt what it shows.

A bare URL in running text is deliberately left alone: its visible form is the URL, so rewriting it would change what the user reads. The post-render StripOSC pass is what makes it inert.

One known cosmetic limit: an indented (four-space) code block is not detected, so bracket syntax inside one is rewritten like ordinary text. That is a display wart, never a safety hole.

func SanitizeBody

func SanitizeBody(s string, maxBytes int) string

SanitizeBody prepares multi-line provider text and discards the truncation flag. Use SanitizeBodyText when the caller needs to tell the user the body was cut.

func SanitizeBodyText

func SanitizeBodyText(s string, maxBytes int) (string, bool)

SanitizeBodyText prepares multi-line provider text: OSC removed, invalid UTF-8 replaced, CRLF normalized, every control character except newline and tab stripped, and the result bounded to maxBytes bytes on a rune boundary. It reports whether anything was cut.

func SanitizeDocument

func SanitizeDocument(w *WireDocument) (Document, *StructuralError)

SanitizeDocument enforces every bound in the Limits table and returns a document safe to hand to view state.

It truncates rather than refusing. A provider is not required to pre-truncate to the host's numbers, and the numbers are deliberately not sent in the request, so a slightly-too-long document still shows the user their ticket: body text is cut at a rune boundary and marked truncated, fields past the count limit are dropped, and over-long single-line strings are cut.

The only failures are structural: a resource with no identity or no title cannot be keyed or labelled, and no amount of truncation fixes that.

func SanitizeLine

func SanitizeLine(s string, maxChars int) string

SanitizeLine prepares a single-line provider string: OSC removed, invalid UTF-8 replaced, every control character stripped (including newlines and tabs, which have no meaning in a title or a field value), surrounding space trimmed, and the result bounded to maxChars runes.

func SanitizeURL

func SanitizeURL(raw string) string

SanitizeURL validates a provider-supplied URL. Only absolute http and https URLs with a host survive; everything else — file:, ssh:, data:, javascript:, scheme-relative, malformed, oversize, or control-bearing — becomes the empty string. An invalid URL is never an error: the resource simply has no source action.

func StripOSC

func StripOSC(s string) string

StripOSC removes every OSC sequence from a provider-supplied string, using the same routine that protects terminal text. It fails closed: a string that still contains an OSC introducer after removal becomes empty rather than reaching a renderer.

func StripRenderedOSC

func StripRenderedOSC(lines []string) []string

StripRenderedOSC removes every OSC sequence from already-rendered lines. It is the last gate before a provider body reaches a view.

Types

type Body

type Body struct {
	Format Format
	Text   string
	// Truncated reports that the provider's body exceeded MaxBodyBytes and was
	// cut at a rune boundary. The host shows the user what it kept and says so;
	// it does not refuse a document for being long.
	Truncated bool
}

Body is the optional long-form text of a resource.

type Code

type Code string

Code is a stable v1 protocol error code. It is control flow; the message beside it is not.

const (
	CodeNotFound      Code = "not_found"
	CodeUnauthorized  Code = "unauthorized"
	CodeForbidden     Code = "forbidden"
	CodeRateLimited   Code = "rate_limited"
	CodeInvalidConfig Code = "invalid_config"
	// CodeInvalidRequest is the host having sent something this provider cannot
	// process: an unsupported protocol, an unknown method, missing or malformed
	// params, an unknown matcher id. It stays distinct from CodeInternal
	// because it is the host's fault, not the provider's, and no retry of the
	// same request will ever work.
	CodeInvalidRequest Code = "invalid_request"
	CodeUnavailable    Code = "unavailable"
	CodeInternal       Code = "internal"
)

The stable v1 codes. Anything else coerces to CodeInternal.

func CoerceCode

func CoerceCode(v string) Code

CoerceCode maps an arbitrary provider string onto a known code. An empty or unrecognized code is CodeInternal: the host would rather say "something went wrong" than invent a meaning a provider did not commit to.

type Document

type Document struct {
	// Identity is the provider-stable canonical ID. It may differ from the
	// locator that produced the lookup; the host re-keys the tab when it does.
	Identity string
	Title    string
	Subtitle string
	// Status is nil when the provider supplied none.
	Status *Status
	Fields []Field
	// Body is nil when the provider supplied none.
	Body      *Body
	SourceURL string
	// UpdatedAt is the zero time when absent or unparseable. An unparseable
	// timestamp is dropped, never an error.
	UpdatedAt time.Time
	// FreshFor is the clamped freshness hint the cache honors.
	FreshFor time.Duration
}

Document is the whole of what a provider may put on screen. Every string in it has already been through Sanitize*: valid UTF-8, bounded, control-free, and OSC-free. SourceURL, when non-empty, is a validated http/https URL.

type Error

type Error struct {
	Code      Code
	Message   string
	Retryable bool
	// SetupHint is copyable text only.
	SetupHint string
}

Error is a typed failure a provider reported, or one the host synthesized on its behalf. It is displayed, not interpreted: Message and SetupHint are text the user reads and may copy, and Sidecar never executes SetupHint.

func Errorf

func Errorf(code Code, format string, args ...any) *Error

Errorf builds a host-synthesized typed error with the code's default retryability.

func SanitizeError

func SanitizeError(w *WireError) *Error

SanitizeError turns a provider's typed failure into a host one. It never fails: an empty or unknown code becomes internal.

func (*Error) Error

func (e *Error) Error() string

type Field

type Field struct {
	Label string
	Value string
	// Kind is a presentation hint. M1 owns what it does with it; M0's job is
	// only to carry and bound it, never to lose it.
	Kind FieldKind
}

Field is one ordered label/value pair in the bounded grid.

type FieldKind

type FieldKind string

FieldKind tells the host how to present a field value. It never changes validation: a timestamp that does not parse is still shown as the text the provider sent, because the alternative is silently hiding a value the user can see in the service itself.

const (
	FieldKindText      FieldKind = "text"
	FieldKindTimestamp FieldKind = "timestamp"
	FieldKindUser      FieldKind = "user"
)

Stable v1 field kinds. Anything else coerces to FieldKindText.

func CoerceFieldKind

func CoerceFieldKind(v string) FieldKind

CoerceFieldKind maps an arbitrary provider string onto a known kind.

type Format

type Format string

Format is how a body's text should be interpreted.

const (
	FormatText     Format = "text"
	FormatMarkdown Format = "markdown"
)

Stable v1 formats. Anything else coerces to FormatText, which is the safer of the two: unknown markup is shown, never interpreted.

func CoerceFormat

func CoerceFormat(v string) Format

CoerceFormat maps an arbitrary provider string onto a known format.

type Reference

type Reference struct {
	Instance string
	Matcher  string
	Locator  string
}

Reference is {provider instance, matcher, locator}: what a match produces and what a resolve consumes. It is the only provider-shaped value that reaches persisted state, and it carries no secret.

func (Reference) Valid

func (r Reference) Valid() bool

Valid reports whether a reference is well-formed enough to send to a provider. It is a bounds check, not an existence check.

type Status

type Status struct {
	Label string
	Tone  Tone
}

Status is the optional single-line state of a resource.

type StructuralError

type StructuralError struct {
	Detail string
}

StructuralError is a response that violates the protocol's shape rules — something the host can neither render nor truncate its way out of, such as a resource with no identity or no title.

It is deliberately not a *Error: the protocol classifies these as transport failures attributed to the provider's implementation, not as typed service failures the user can act on. The transport layer wraps it.

func (*StructuralError) Error

func (e *StructuralError) Error() string

type Tone

type Tone string

Tone is the coarse severity of a status pill. It is presentation-neutral on purpose: the host maps it to a palette, the provider does not choose colors.

const (
	ToneNeutral Tone = "neutral"
	ToneInfo    Tone = "info"
	ToneSuccess Tone = "success"
	ToneWarning Tone = "warning"
	ToneDanger  Tone = "danger"
)

Stable v1 tones. Anything else coerces to ToneNeutral.

func CoerceTone

func CoerceTone(v string) Tone

CoerceTone maps an arbitrary provider string onto a known tone.

type WireBody

type WireBody struct {
	Format string `json:"format,omitempty"`
	Text   string `json:"text"`
}

WireBody is `{format, text}`.

type WireDocument

type WireDocument struct {
	Identity        string      `json:"identity"`
	Title           string      `json:"title"`
	Subtitle        string      `json:"subtitle,omitempty"`
	Status          *WireStatus `json:"status,omitempty"`
	Fields          []WireField `json:"fields,omitempty"`
	Body            *WireBody   `json:"body,omitempty"`
	SourceURL       string      `json:"sourceUrl,omitempty"`
	UpdatedAt       string      `json:"updatedAt,omitempty"`
	FreshForSeconds float64     `json:"freshForSeconds,omitempty"`
}

WireDocument is the `resource` object of a success response.

type WireError

type WireError struct {
	Code      string `json:"code"`
	Message   string `json:"message,omitempty"`
	Retryable *bool  `json:"retryable,omitempty"`
	SetupHint string `json:"setupHint,omitempty"`
}

WireError is the `error` object of a typed failure response. Retryable is a pointer so an omitted value takes the code's documented default rather than silently reading as false.

type WireField

type WireField struct {
	Label string `json:"label"`
	Value string `json:"value"`
	Kind  string `json:"kind,omitempty"`
}

WireField is one `{label, value, kind}` triple.

type WireStatus

type WireStatus struct {
	Label string `json:"label"`
	Tone  string `json:"tone,omitempty"`
}

WireStatus is `{label, tone}`.

Jump to

Keyboard shortcuts

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