Documentation
¶
Overview ¶
Package resource holds the shared scaffolding every read/list command is built from: obtaining an authenticated client, fetching + error-mapping a raw JSON response, and rendering it through the output engine. A new resource command needs only its endpoint path and a column spec — see docs/adding-commands.md.
Index ¶
- Constants
- func AddFilterFlags(cmd *cobra.Command, f *ListFilters)
- func AddLabelFlags(cmd *cobra.Command, f *LabelFlags, update bool)
- func AddMetadataFlags(cmd *cobra.Command, f *MetadataFlags, update bool)
- func AddRelationsFlag(cmd *cobra.Command) *bool
- func Client(ctx context.Context, rt *config.Runtime, resolve CredResolver, ...) (*api.RawClient, error)
- func ConfirmDeletion(cmd *cobra.Command, what string, assumeYes bool) (bool, error)
- func Do(ctx context.Context, client *api.RawClient, method, path string, body []byte) ([]byte, int, error)
- func ExtractItems(raw []byte) ([]json.RawMessage, bool)
- func FetchAllPages(ctx context.Context, client *api.RawClient, path, sizeParam string, ...) (items []json.RawMessage, notList []byte, err error)
- func FetchJSON(ctx context.Context, client *api.RawClient, method, path string) ([]byte, error)
- func FreshnessColumn() output.Column
- func FreshnessDetailColumns() []output.Column
- func GetItem(cmd *cobra.Command, resolve CredResolver, getenv config.Getenv, path string, ...) error
- func ListRows(keys ...string) string
- func LockColumn() output.Column
- func LockDetailColumns() []output.Column
- func NewListCommand(resolve CredResolver, getenv config.Getenv, short string, cfg ListConfig) *cobra.Command
- func NewLockCommand(noun string, resolve CredResolver, getenv config.Getenv, itemPath ItemPathFunc, ...) *cobra.Command
- func NewNamedListCommand(use string, resolve CredResolver, getenv config.Getenv, short string, ...) *cobra.Command
- func NewUnlockCommand(noun string, resolve CredResolver, getenv config.Getenv, itemPath ItemPathFunc, ...) *cobra.Command
- func Render(cmd *cobra.Command, rt *config.Runtime, getenv config.Getenv, body []byte, ...) error
- func RenderRelationsSummary(cmd *cobra.Command, body []byte)
- func RenderWithRelations(cmd *cobra.Command, rt *config.Runtime, getenv config.Getenv, body []byte, ...) error
- func RunList(cmd *cobra.Command, resolve CredResolver, getenv config.Getenv, cfg ListConfig, ...) error
- func Runtime(ctx context.Context) (*config.Runtime, error)
- func RuntimeAndClient(cmd *cobra.Command, resolve CredResolver, getenv config.Getenv) (context.Context, *config.Runtime, *api.RawClient, error)
- func SendItem(ctx context.Context, cmd *cobra.Command, rt *config.Runtime, ...) error
- func UsageOnBadRequest(err error) error
- func WarnIfPartial(w io.Writer, raw []byte, how string)
- func WithFreshnessDetail(head, tail []output.Column) []output.Column
- func WithProjectFilter(path string, rt *config.Runtime) (string, error)
- func WriteChannelDetailColumns() []output.Column
- type CredResolver
- type ItemPathFunc
- type LabelFlags
- type ListConfig
- type ListFilters
- type MetadataFlags
- func (f *MetadataFlags) AddMerged(ctx context.Context, client *api.RawClient, itemPath string, ...) error
- func (f *MetadataFlags) AddTo(payload map[string]any) error
- func (f *MetadataFlags) Build(in io.Reader) (map[string]any, error)
- func (f *MetadataFlags) ForUpdate(ctx context.Context, client *api.RawClient, itemPath string, in io.Reader) (map[string]any, error)
- func (f *MetadataFlags) Set() bool
- type PageMeta
- type Pagination
Constants ¶
const ( MaxLabels = 10 MaxLabelLength = 50 )
The platform's per-resource label limits (v0.13.0 shared labels): a resource carries at most MaxLabels labels of at most MaxLabelLength characters each. They are checked as the flag is parsed, so an oversized list is a usage error before anything is read or sent, not a round trip ending in a 400.
const DefaultPageLimit = 50
DefaultPageLimit is the per-page size a page walk uses when the path sets none.
const DefaultPageSizeParam = "limit"
DefaultPageSizeParam is the query param most list endpoints read their page size from.
const LimitHelp = "maximum items per page (server max " + ServerMaxLimit + ")"
LimitHelp is the --limit help shared by every paginated command. The server is authoritative on the maximum (it differs per endpoint), so it is documented here rather than enforced locally.
const MetadataHelp = "Metadata is set with --metadata key=value (repeatable; values are\n" +
"strings) and/or --metadata-json '<object>' (inline JSON, @file, or '-' for\n" +
"stdin) for numbers, bools, arrays and nested objects; --metadata wins on a\n" +
"key conflict. On memories, a \"tags\" key holding a JSON string array is\n" +
"turned by the server into labels (replacing the memory's existing labels)\n" +
"and is not stored as metadata; a plain --metadata tags=x stays a string key."
MetadataHelp is the shared Long-help paragraph for every command that binds the metadata write flags. The memory tags caveat is stated for every noun: it is harmless where it does not apply and it keeps the three helps aligned.
const MetadataUpdateHelp = MetadataHelp + "\n\n" +
"On update the given keys are merged into the existing metadata (the\n" +
"resource is read first; a concurrent write between that read and this\n" +
"update is lost). --unset-metadata <key> removes a key; --replace-metadata\n" +
"sends only the given keys, replacing the whole object without a read."
MetadataUpdateHelp adds the update-only semantics to MetadataHelp.
const ServerMaxLimit = "100"
ServerMaxLimit is the per-page maximum the platform enforces on resource lists and search, as it appears in help and hints.
Variables ¶
This section is empty.
Functions ¶
func AddFilterFlags ¶
func AddFilterFlags(cmd *cobra.Command, f *ListFilters)
AddFilterFlags binds the flags f opted into onto cmd.
func AddLabelFlags ¶
func AddLabelFlags(cmd *cobra.Command, f *LabelFlags, update bool)
AddLabelFlags binds --label onto cmd. On update the given labels replace the resource's existing ones.
func AddMetadataFlags ¶
func AddMetadataFlags(cmd *cobra.Command, f *MetadataFlags, update bool)
AddMetadataFlags binds --metadata and --metadata-json onto cmd, plus --unset-metadata and --replace-metadata when update is true.
func AddRelationsFlag ¶
AddRelationsFlag binds --show-relations to a `get` command and returns the bound pointer. When set, the command prints a compact related/similar summary (the v0.8.0 read-time neighborhood) to stderr after rendering the resource. The full arrays always remain available via --format=json.
func Client ¶
func Client(ctx context.Context, rt *config.Runtime, resolve CredResolver, getenv config.Getenv) (*api.RawClient, error)
Client builds an authenticated raw client for the runtime.
func ConfirmDeletion ¶
ConfirmDeletion asks the user to confirm a destructive action. It is the shared gate for every destructive verb (reused by memory/blueprint/etc.).
- assumeYes (from --yes): proceed without prompting.
- non-interactive (stdin not a TTY) without --yes: refuse with a usage error (exit 2), so scripts must opt in explicitly.
- interactive: prompt y/N; proceed only on "y"/"yes".
It returns (proceed, err). A false proceed with a nil err is a clean user abort — the caller should stop without treating it as a failure.
func Do ¶
func Do(ctx context.Context, client *api.RawClient, method, path string, body []byte) ([]byte, int, error)
Do performs a request and returns the raw response body and status, mapping any non-2xx into an *api.Error (RFC 7807 detail + request_id + exit code). body may be nil.
func ExtractItems ¶
func ExtractItems(raw []byte) ([]json.RawMessage, bool)
ExtractItems returns the list items in a page response: a top-level array, or an object's `items`/`data` field, or (deterministically) its first array-valued field. An object-valued `data` envelope with no array beside it (listPrompts) is searched the same way one level down.
func FetchAllPages ¶
func FetchAllPages(ctx context.Context, client *api.RawClient, path, sizeParam string, hdr http.Header) (items []json.RawMessage, notList []byte, err error)
FetchAllPages walks a page-based GET list endpoint, incrementing `page` until a short/empty page or the response's own total_pages, and returns the union of every page's items in order. It is the one page walk behind both `vibexp api --paginate` and the resource `list --all` flag.
sizeParam is the query param the endpoint reads its page size from (DefaultPageSizeParam, or "page_size" for listTeams).
When the first page has no recognizable list field, items is nil and notList carries that page's raw body, so the caller can render it as-is.
func FreshnessColumn ¶
FreshnessColumn is the compact list-view flag: "stale", or empty when fresh. Place it immediately before the UPDATED column, which it qualifies.
func FreshnessDetailColumns ¶
FreshnessDetailColumns is the full state for single-object views: the flag plus when it was first flagged, why, and how many rules matched. The raw matched_rule_ids stay available through --format=json; there is no CLI-side rule lookup to resolve them to names.
func GetItem ¶
func GetItem(cmd *cobra.Command, resolve CredResolver, getenv config.Getenv, path string, spec output.TableSpec) error
GetItem is the one-line helper a single-object command (e.g. whoami) uses: fetch a path and render it with a spec.
func ListRows ¶
ListRows builds the row expression for a list view from the endpoint's array key(s), e.g. ListRows("memories") matches both {"memories":[…]} and {"data":{"memories":[…]}}. Extra keys are tried in the order given, for the endpoints that spell the array more than one way. The generic `items` alias is always appended last.
Use this for every multi-row list spec; do not hand-write the expression.
func LockColumn ¶
LockColumn is the compact list-view flag: "locked", or empty when unlocked. It goes after UPDATED so the TSV field positions scripts rely on stay put.
func LockDetailColumns ¶
LockDetailColumns is the full lock for single-object views: the flag plus who holds it, since when, and why.
func NewListCommand ¶
func NewListCommand(resolve CredResolver, getenv config.Getenv, short string, cfg ListConfig) *cobra.Command
NewListCommand builds a ready `list` subcommand from a ListConfig: it binds the pagination flags and wires RunE to RunList, so a noun package only supplies its path and columns.
func NewLockCommand ¶
func NewLockCommand(noun string, resolve CredResolver, getenv config.Getenv, itemPath ItemPathFunc, spec output.TableSpec) *cobra.Command
NewLockCommand builds `<noun> lock <slug> --comment "<why>"`: POST …/{slug}/lock, rendering the locked resource with spec.
func NewNamedListCommand ¶
func NewNamedListCommand(use string, resolve CredResolver, getenv config.Getenv, short string, cfg ListConfig) *cobra.Command
NewNamedListCommand is NewListCommand under a verb other than `list`, for a noun that exposes more than one paginated collection (e.g. `team audit` alongside `team list`). Everything else — pagination, filters, output contract — is identical.
func NewUnlockCommand ¶
func NewUnlockCommand(noun string, resolve CredResolver, getenv config.Getenv, itemPath ItemPathFunc, spec output.TableSpec) *cobra.Command
NewUnlockCommand builds `<noun> unlock <slug>`: DELETE …/{slug}/lock, rendering the unlocked resource with spec.
func Render ¶
func Render(cmd *cobra.Command, rt *config.Runtime, getenv config.Getenv, body []byte, spec *output.TableSpec) error
Render writes a raw response body to stdout through the output engine, using the runtime's format/jq/tty settings and the given column spec (nil for pure passthrough).
func RenderRelationsSummary ¶
RenderRelationsSummary parses the optional v0.8.0 `related`/`similar` arrays from a resource GET body and writes a compact, human summary to stderr — so stdout stays data-only. It is a no-op when both arrays are absent or empty, and never fails the command: a body that does not parse is simply skipped, since these arrays are best-effort read-time context, not the resource itself.
func RenderWithRelations ¶
func RenderWithRelations(cmd *cobra.Command, rt *config.Runtime, getenv config.Getenv, body []byte, spec *output.TableSpec, showRelations bool) error
RenderWithRelations renders a single-resource body through the output engine, then — when showRelations is set — prints the v0.8.0 related/similar summary to stderr. It is the shared tail of every resource `get` command.
func RunList ¶
func RunList(cmd *cobra.Command, resolve CredResolver, getenv config.Getenv, cfg ListConfig, p *Pagination) error
RunList is the shared runner for a list command: resolve runtime, build the path, apply pagination, fetch, and render. A list command's RunE is just a call to this with its ListConfig and Pagination. A nil Pagination means the endpoint does not paginate (GET /attachments): no page params, no --all walk and no partial-page hint.
func RuntimeAndClient ¶
func RuntimeAndClient(cmd *cobra.Command, resolve CredResolver, getenv config.Getenv) (context.Context, *config.Runtime, *api.RawClient, error)
RuntimeAndClient resolves the runtime and an authenticated client in one step — the common preamble for every command RunE.
func SendItem ¶
func SendItem(ctx context.Context, cmd *cobra.Command, rt *config.Runtime, getenv config.Getenv, client *api.RawClient, method, path string, payload any, spec *output.TableSpec) error
SendItem marshals a JSON payload, sends it, and renders the response with a spec. It is the shared write path for create/update verbs.
func UsageOnBadRequest ¶
UsageOnBadRequest turns a 400 from a list/search request into a usage error (exit 2): the request is built from the user's flags (--limit, --page, filters), so the server rejecting it is a usage problem. The server's own message and request_id are kept verbatim. Any other error passes through.
func WarnIfPartial ¶
WarnIfPartial writes a one-line stderr hint when a list response is only one page of several, so a silently partial result becomes visible. stdout is never touched. how names the flags that reach the rest (e.g. "--page, --limit (max 100) or --all"). Nothing is written when everything fit or the response carries no page metadata.
func WithFreshnessDetail ¶
WithFreshnessDetail splices the freshness detail columns between head and tail, so a noun's detail spec reads as its own fields with the shared freshness block dropped in at the right position.
func WithProjectFilter ¶
WithProjectFilter appends ?project_id=<uuid> to a list path when a project is set (--project / env / context), resolving a slug first.
func WriteChannelDetailColumns ¶
WriteChannelDetailColumns is the write provenance for single-object views: the channel of the last write (web, cli, mcp or api) and, for MCP writes only, the name the MCP client reported. They go last in a detail spec, so the columns before them keep their positions for scripts. List views leave them out; they are not worth the width there.
Types ¶
type CredResolver ¶
CredResolver returns the effective credential store.
type ItemPathFunc ¶
ItemPathFunc builds a lockable noun's single-item path for a slug, resolving the team (and, for project-scoped nouns, the project; missing → exit 2).
type LabelFlags ¶
type LabelFlags struct {
// contains filtered or unexported fields
}
LabelFlags binds the repeatable --label write flag of a memory, artifact or blueprint create/update. Labels are sent only when --label was given, so an update without it never touches (let alone clears) the resource's labels.
func (*LabelFlags) AddTo ¶
func (f *LabelFlags) AddTo(payload map[string]any)
AddTo sets payload["labels"] when --label was given; --label "" alone sends an empty list, which clears the labels on update.
func (*LabelFlags) Set ¶
func (f *LabelFlags) Set() bool
Set reports whether --label was given, even as "".
type ListConfig ¶
type ListConfig struct {
// PathFor returns the server-relative list path for the runtime. It returns
// a usage error (exit 2) when a required scope (e.g. team) is unset.
PathFor func(rt *config.Runtime) (string, error)
// Spec is the table/TSV column spec applied on a terminal or with
// --format=table|text.
Spec output.TableSpec
// Filters, when non-nil, binds the filter flags it opts into on the command
// and merges them into the query. Opt in only to filters the endpoint
// actually accepts — see ListFilters.
Filters *ListFilters
// PageSizeParam names the query param the endpoint reads its page size
// from; empty means "limit". listTeams reads "page_size" and ignores limit.
PageSizeParam string
// NoOffset leaves --offset unbound, for an endpoint that takes only
// page and page size (listTeams).
NoOffset bool
}
ListConfig declares a list endpoint: how to build its path (resolving team scope when needed) and how to tabulate it.
type ListFilters ¶
type ListFilters struct {
// Metadata exposes --metadata (every noun whose endpoint takes it — not
// prompts, whose listPrompts has no metadata param).
Metadata bool
// Tags exposes --tags (memory list only). Implies Metadata: --tags is sugar
// over the same containment param, so it cannot be offered on an endpoint
// that does not accept metadata.
Tags bool
// Stale exposes --stale.
Stale bool
// Labels exposes --labels (every curated noun's list endpoint takes it).
Labels bool
// Locked exposes --locked (the three lockable nouns only).
Locked bool
// contains filtered or unexported fields
}
ListFilters is the opt-in server-side filter set for a list command. Each exported field turns one flag on, because the four curated nouns wrap endpoints that accept different filters — binding a flag the endpoint ignores would let a user narrow a list and get the full one back, which reads like a legitimate answer.
- Metadata → --metadata key=value (repeatable), merged into the server's JSON containment param: keys ANDed, values within a key ORed.
- Tags → --tags <tag> (repeatable), sugar for metadata.tags=<tag>. Memories only; the platform stores tags at metadata.tags (v0.9.0, epic #519).
- Stale → --stale, mapping to freshness=stale (v0.11.0, epic #726).
- Labels → --labels <label> (repeatable), sent comma-joined as labels=; a resource matches when it carries any of them (v0.13.0, vibexp#938).
- Locked → --locked, mapping to locked=true (v0.15.0, epic #1285). Prompts, blueprints and artifacts only; memories are not lockable.
func (*ListFilters) ApplyToPath ¶
func (f *ListFilters) ApplyToPath(path string) (string, error)
ApplyToPath merges every set filter into a path's query string; a no-op when none is set, so an unfiltered list keeps its path byte-for-byte (in particular it never grows an empty freshness=).
func (*ListFilters) Query ¶
func (f *ListFilters) Query() (string, error)
Query returns the metadata containment value as JSON, or "" when unset. Keys are sorted for a deterministic query string. An empty value (--metadata key=) means "the key exists".
type MetadataFlags ¶
type MetadataFlags struct {
// contains filtered or unexported fields
}
MetadataFlags binds the metadata write flags of a create/update command. The server replaces the whole metadata object whenever one is sent, so update merges into the current object unless --replace-metadata says otherwise.
func (*MetadataFlags) AddMerged ¶
func (f *MetadataFlags) AddMerged(ctx context.Context, client *api.RawClient, itemPath string, payload map[string]any) error
AddMerged sets payload["metadata"] for an update when a metadata flag was given, merging into the item at itemPath (see ForUpdate).
func (*MetadataFlags) AddTo ¶
func (f *MetadataFlags) AddTo(payload map[string]any) error
AddTo sets payload["metadata"] for a create when a metadata flag was given; stdin is the bound command's.
func (*MetadataFlags) Build ¶
Build returns the metadata object the flags describe: --metadata-json first, then the --metadata pairs overlaid on it. in is read when --metadata-json is '-'. Every malformed input is a usage error.
func (*MetadataFlags) ForUpdate ¶
func (f *MetadataFlags) ForUpdate(ctx context.Context, client *api.RawClient, itemPath string, in io.Reader) (map[string]any, error)
ForUpdate returns the metadata object an update should send, reading the resource at itemPath first unless --replace-metadata is given. The flags are validated before any request, so malformed input never reaches the server.
func (*MetadataFlags) Set ¶
func (f *MetadataFlags) Set() bool
Set reports whether any metadata flag was given.
type PageMeta ¶
type PageMeta struct {
Page int
TotalPages int
// TotalCount is -1 when the response does not report it.
TotalCount int
}
PageMeta is the pagination metadata a list response carries.
func ReadPageMeta ¶
ReadPageMeta returns a response's page/total_pages/total_count metadata, read from the top level or, for an enveloped list (listPrompts: {"data":{"prompts":[…],"page":…}}), from under `data`. total_pages is derived from total_count and the page size when the response omits it (listTeams). ok is false when neither is available.
type Pagination ¶
type Pagination struct {
Limit int
Page int
Offset int
// All walks every page and renders the merged items (see FetchAllPages).
All bool
}
Pagination holds the shared list pagination flags.
func AddPaginationFlags ¶
func AddPaginationFlags(cmd *cobra.Command) *Pagination
AddPaginationFlags binds --limit/--page/--offset/--all to a Pagination and returns it. A zero value means "unset" (the flag is omitted from the request).
func (*Pagination) ApplyToPath ¶
func (p *Pagination) ApplyToPath(path, sizeParam string) (string, error)
ApplyToPath merges the set pagination params into a path's query string, sending --limit as sizeParam (the endpoint's page-size param, e.g. "limit" or listTeams' "page_size").
func (*Pagination) Validate ¶
func (p *Pagination) Validate() error
Validate rejects flag combinations the page walk cannot honour: --all walks from page 1 itself, so a fixed --page or --offset contradicts it.