Help us shape the future of Go! Take the 2026 Go Developer Survey

gqlcli

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 37 Imported by: 1

Documentation

Index

Constants

View Source
const (
	DefaultEmbeddingBaseURL = "https://z-ask.zasperhub.com/api/v1"
	DefaultEmbeddingModel   = "nomic-embed-text-v1.5"

	// DefaultEmbeddingMaxChars caps the text sent per embedding request. Type
	// SDL for a wide object can run long and the remote model truncates
	// silently; truncating here keeps the text_hash honest about what was
	// actually embedded.
	DefaultEmbeddingMaxChars = 8000
)

Embedding provider defaults. The Venu API is OpenAI-shaped for chat but takes a single "text" field for embeddings and returns one already L2-normalized vector per call.

View Source
const (
	OperationQuery        = "query"
	OperationMutation     = "mutation"
	OperationSubscription = "subscription"
)

GraphQL operation kinds, as reported by DocumentOperationKind and carried in RequestInfo.Type.

View Source
const DefaultSchemaCacheTTL = 10 * time.Minute

DefaultSchemaCacheTTL is how long the CLI reuses a cached introspection result before fetching the schema again.

View Source
const EmbeddingIndexVersion = 1

EmbeddingIndexVersion is the schema version written to index files. Search rejects files from a future version rather than misreading them.

View Source
const FullIntrospectionQuery = `` /* 1309-byte string literal not displayed */

FullIntrospectionQuery is the schema introspection document the clients use. Exported so an embedder issuing introspection through its own transport asks for the same shape the formatters expect.

It requests directive definitions and nests ofType deeply enough for stacked list types, both of which SchemaSDL needs to rebuild a loadable schema.

View Source
const MaxSchemaHintChars = 10000

MaxSchemaHintChars is the maximum number of characters returned in a schemaHint extension. Hints longer than this are truncated with a trailing "..." marker.

Variables

View Source
var ErrOperationBudget = errors.New("script exceeded its GraphQL operation budget")

ErrOperationBudget is returned to the script when WithMaxOperations is exceeded.

View Source
var ErrReadOnly = errors.New("mutations are disabled: script runner is read-only")

ErrReadOnly is returned to the script when WithReadOnly(true) blocks a mutation.

View Source
var ErrScriptInterrupted = errors.New("script interrupted")

ErrScriptInterrupted reports that a script was stopped by context cancellation or a WithTimeout deadline rather than by throwing. Hosts embedding ScriptRunner use errors.Is to tell a runaway script apart from a script bug.

Functions

func DocumentOperationKind added in v0.5.0

func DocumentOperationKind(document string) (string, error)

DocumentOperationKind reports what a GraphQL document actually does, by parsing it. A document holding several operations is reported by its most privileged one: any mutation makes the whole document a mutation.

Parsing matters when the document is untrusted — searching the text for the word "mutation" is wrong in both directions. It matches the word inside a string literal or comment, and it misses a document that never spells the keyword: a bare `{ ... }` is a query, and a mutation can arrive via a helper named for something else.

func EmbeddingIndexPath added in v0.6.0

func EmbeddingIndexPath(env string) string

EmbeddingIndexPath returns the default index file for an environment: .gqlcli-embeddings.json for the unnamed/default env, and .gqlcli-embeddings.<env>.json otherwise.

func FormatTypeSDL

func FormatTypeSDL(typeData map[string]interface{}, showArgs, noDescriptions bool) string

FormatTypeSDL returns a compact SDL-like string for a type from introspection data. showArgs controls whether field arguments are expanded. noDescriptions suppresses inline description comments.

func ReorderArgsForCommand added in v0.2.3

func ReorderArgsForCommand(args []string, flags []cli.Flag) []string

ReorderArgsForCommand moves recognized flag tokens (and, when applicable, their values) ahead of positional arguments in args, which is expected to be a single command's own argument slice (i.e. NOT including the program name or the command name itself).

This works around a real limitation of Go's stdlib flag package (which urfave/cli v2 wraps): flag parsing stops at the first non-flag token, so invocations like `gqlcli query '<query>' --variables '{...}'` silently drop --variables (and anything after it) instead of erroring — the query runs with no variables at all. Every documented example puts the query or mutation string first and flags after, so this reorder makes that documented usage actually work, while flags-first invocations are unaffected (reordering a slice that's already flags-then-positionals is a no-op).

func ReorderOSArgs added in v0.2.3

func ReorderOSArgs(args []string, commands []*cli.Command) []string

ReorderOSArgs reorders a full os.Args-style slice (args[0] is the program name) so that, for whichever top-level command is invoked, that command's own flags precede its positional arguments. Non-command tokens (e.g. no args, or top-level --help/--version) are returned unchanged. Commands that have their own Subcommands (e.g. "config", "op") are left untouched — their first positional token is a subcommand name that must stay in place, and reordering would misroute it behind hoisted flags.

func RequireOperationKind added in v0.5.0

func RequireOperationKind(document, want string) error

RequireOperationKind returns an error unless every operation in document is of the wanted kind. Use it to enforce that a tool advertised as read-only cannot be handed a mutation.

func RunApp added in v0.2.3

func RunApp(app *cli.App, args []string) error

RunApp is a drop-in replacement for app.Run(args) that applies ReorderOSArgs first. Every entrypoint that builds a *cli.App from this package's commands — the gqlcli binary itself (cmd/gqlcli) and any embedder using InlineCommandSet.Mount (see example/main.go) — should call gqlcli.RunApp(app, os.Args) instead of app.Run(os.Args) directly; otherwise flags placed after a command's positional argument (the documented usage shown by --help) are silently dropped, since Mount only appends commands and has no way to intercept args itself.

func SchemaFromIntrospection added in v0.8.0

func SchemaFromIntrospection(introspection map[string]interface{}) (*ast.Schema, error)

SchemaFromIntrospection rebuilds a schema from an introspection result so documents can be validated against it without contacting the server again.

func SchemaSDL added in v0.8.0

func SchemaSDL(introspection map[string]interface{}) (string, error)

SchemaSDL renders an introspection result as an SDL document.

The output is meant to be fed back to gqlparser: builtin scalars and directives are left out because the prelude already declares them, and introspection's own __-prefixed types are skipped because names beginning with __ are reserved. Unlike the compact SDL that describe emits for humans, this output is complete enough to rebuild a schema from.

It accepts either a full response envelope ({"data":{"__schema":...}}, what Client.Introspect returns) or a bare __schema map.

Types

type AuthConfig

type AuthConfig struct {
	Enabled bool
	Type    string // bearer, api-key
	Token   string
}

AuthConfig holds authentication configuration

type BatchRequest

type BatchRequest struct {
	Query         string                 `json:"query"`
	Variables     map[string]interface{} `json:"variables,omitempty"`
	OperationName string                 `json:"operationName,omitempty"`
	JQ            string                 `json:"jq,omitempty"`
}

BatchRequest is a single operation in a batch, with an optional jq filter.

type CLIBuilder

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

CLIBuilder creates CLI commands for GraphQL operations

func NewCLIBuilder

func NewCLIBuilder(cfg *Config) *CLIBuilder

NewCLIBuilder creates a new CLI command builder

func (*CLIBuilder) GetBatchCommand

func (b *CLIBuilder) GetBatchCommand() *cli.Command

GetBatchCommand returns the batch subcommand for CLIBuilder (HTTP mode).

func (*CLIBuilder) GetConfigCommand added in v0.2.0

func (b *CLIBuilder) GetConfigCommand() *cli.Command

GetConfigCommand returns the config subcommand for managing .gqlcli.json.

func (*CLIBuilder) GetDescribeCommand

func (b *CLIBuilder) GetDescribeCommand() *cli.Command

func (*CLIBuilder) GetEmbedCommand added in v0.6.0

func (b *CLIBuilder) GetEmbedCommand() *cli.Command

GetEmbedCommand returns the "embed" command group: build a semantic index of the schema's types, then search it with plain language.

func (*CLIBuilder) GetInstallSkillCommand

func (b *CLIBuilder) GetInstallSkillCommand() *cli.Command

GetInstallSkillCommand returns the install-skill subcommand.

func (*CLIBuilder) GetLoginCommand added in v0.2.0

func (b *CLIBuilder) GetLoginCommand() *cli.Command

GetLoginCommand returns the login command for HTTP-mode environments.

func (*CLIBuilder) GetLogoutCommand added in v0.2.0

func (b *CLIBuilder) GetLogoutCommand() *cli.Command

GetLogoutCommand returns the logout command, which clears the auth header from an env.

func (*CLIBuilder) GetMutationCommand

func (b *CLIBuilder) GetMutationCommand() *cli.Command

GetMutationCommand returns the mutation subcommand

func (*CLIBuilder) GetMutationsCommand

func (b *CLIBuilder) GetMutationsCommand() *cli.Command

GetMutationsCommand returns the mutations listing command

func (*CLIBuilder) GetOpCommand added in v0.2.0

func (b *CLIBuilder) GetOpCommand() *cli.Command

GetOpCommand returns the op subcommand for managing named operations in .gqlcli.json.

func (*CLIBuilder) GetQueriesCommand

func (b *CLIBuilder) GetQueriesCommand() *cli.Command

GetQueriesCommand returns the queries listing command

func (*CLIBuilder) GetQueryCommand

func (b *CLIBuilder) GetQueryCommand() *cli.Command

GetQueryCommand returns the query subcommand

func (*CLIBuilder) GetSchemaCommand added in v0.9.0

func (b *CLIBuilder) GetSchemaCommand() *cli.Command

GetSchemaCommand returns the schema command group, which manages the on-disk introspection cache that schema commands read from.

func (*CLIBuilder) GetScriptCommand added in v0.4.0

func (b *CLIBuilder) GetScriptCommand() *cli.Command

GetScriptCommand returns the JavaScript scripting command.

func (*CLIBuilder) GetSdlCommand added in v0.8.0

func (b *CLIBuilder) GetSdlCommand() *cli.Command

GetSdlCommand returns the sdl subcommand.

func (*CLIBuilder) GetSubscribeCommand added in v0.2.0

func (b *CLIBuilder) GetSubscribeCommand() *cli.Command

GetDescribeCommand returns the describe command GetSubscribeCommand returns the subscribe subcommand

func (*CLIBuilder) GetTypesCommand

func (b *CLIBuilder) GetTypesCommand() *cli.Command

GetTypesCommand returns the types listing command

func (*CLIBuilder) GetValidateCommand added in v0.8.0

func (b *CLIBuilder) GetValidateCommand() *cli.Command

GetValidateCommand returns the validate subcommand.

func (*CLIBuilder) RegisterCommands

func (b *CLIBuilder) RegisterCommands(app *cli.App)

RegisterCommands returns all CLI commands for the app

type Claims

type Claims struct {
	UserID string
	Email  string
	// Raw holds all parsed claims for custom extraction.
	Raw map[string]interface{}
}

Claims holds JWT token claims parsed from a saved token.

type Client

type Client interface {
	OperationExecutor
	Introspect(ctx context.Context) (map[string]interface{}, error)
	LastResponseMetadata() *ResponseMetadata
}

Client executes GraphQL operations and can describe the schema behind them. It is what the CLI commands need; ScriptRunner asks only for OperationExecutor.

type CommandSetOption

type CommandSetOption func(*InlineCommandSet)

CommandSetOption configures an InlineCommandSet.

func WithLogin

func WithLogin(cfg LoginConfig) CommandSetOption

WithLogin adds login, logout, and whoami commands to the command set.

func WithTokenStore

func WithTokenStore(ts *TokenStore) CommandSetOption

WithTokenStore attaches a TokenStore. The saved token is made available for the whoami and logout commands. To inject it into operations, use WithContextEnricher on the InlineExecutor.

type CompactFormatter

type CompactFormatter struct{}

CompactFormatter outputs data in compact form

func NewCompactFormatter

func NewCompactFormatter() *CompactFormatter

NewCompactFormatter creates a compact formatter

func (*CompactFormatter) Format

func (f *CompactFormatter) Format(data map[string]interface{}) (string, error)

func (*CompactFormatter) Name

func (f *CompactFormatter) Name() string

type Config

type Config struct {
	URL    string // GraphQL endpoint URL (default: http://localhost:8080/graphql)
	Format string // Output format: json, table, compact, toon, llm (default: toon)
	Pretty bool   // Pretty-print JSON output

	// Authentication
	Token string // Bearer token for requests
	Auth  AuthConfig

	// HTTP client settings
	Timeout    int               // Request timeout in seconds; 0 disables the timeout (default)
	RetryCount int               // Number of retries for transient request failures (default: 0)
	RetryDelay time.Duration     // Delay between retries (default: 1s when retries are enabled)
	Strict     bool              // Return an error when response.errors is present
	Debug      bool              // Enable debug logging (logs requests/responses)
	Insecure   bool              // Skip TLS certificate verification (default: false)
	Headers    map[string]string // Custom HTTP headers sent with every request

	// Schema cache: full introspection results reused across processes.
	SchemaCacheTTL time.Duration // How long a cached schema stays valid; 0 disables the cache (default)
	SchemaCacheDir string        // Cache directory (default: <user cache dir>/gqlcli)
	RefreshSchema  bool          // Ignore any cached schema, but still store the fresh one
}

Config holds the CLI configuration

type DefaultFormatterRegistry

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

DefaultFormatterRegistry manages available formatters

func NewFormatterRegistry

func NewFormatterRegistry() *DefaultFormatterRegistry

NewFormatterRegistry creates a new formatter registry with default formatters

func (*DefaultFormatterRegistry) Get

func (*DefaultFormatterRegistry) List

func (r *DefaultFormatterRegistry) List() []string

func (*DefaultFormatterRegistry) Register

func (r *DefaultFormatterRegistry) Register(name string, formatter Formatter) error

type DescribeOptions added in v0.5.0

type DescribeOptions struct {
	// FieldFilter keeps only members whose name contains it, case-insensitively,
	// across fields, input fields and enum values. Empty keeps everything.
	FieldFilter string
	// ShowArgs expands field argument signatures. Worth enabling for the Query
	// and Mutation roots, where the arguments are the call signature.
	ShowArgs bool
	// ShowDescriptions includes doc comments.
	ShowDescriptions bool
	// Depth recursively includes referenced non-scalar types, as DescribeWithDepth.
	Depth int
}

DescribeOptions controls DescribeWithOptions.

type Describer

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

Describer introspects a schema and returns compact SDL descriptions of types. Results are cached after the first introspection call for each type.

Use NewDescriber to create one from an InlineExecutor, or newSchemaHintDescriber internally when wiring the schema hint error presenter.

func NewDescriber

func NewDescriber(exec *InlineExecutor) *Describer

NewDescriber creates a Describer backed by an InlineExecutor. Useful for building a describe command or fetching type SDL programmatically.

func NewDescriberFromExecFunc added in v0.5.0

func NewDescriberFromExecFunc(exec func(ctx context.Context, query string, vars map[string]interface{}) (json.RawMessage, error)) *Describer

NewDescriberFromExecFunc creates a Describer backed by any function that can run a GraphQL operation. Use it to reach Describer — its per-type caching, depth recursion and field filtering — from an embedder's own HTTP stack, rather than reimplementing introspection around FormatTypeSDL.

exec must return the full GraphQL response envelope (the object with the "data" key), not just the data payload.

func NewDescriberFromHTTPClient

func NewDescriberFromHTTPClient(c *HTTPClient) *Describer

NewDescriberFromHTTPClient creates a Describer that fetches type information via introspection against the given HTTP client.

func (*Describer) Describe

func (d *Describer) Describe(ctx context.Context, typeName string) (string, error)

Describe returns a compact SDL string for the named type with default formatting (no field argument signatures, no descriptions). Results are cached. For custom formatting options use DescribeWith.

func (*Describer) DescribeWith

func (d *Describer) DescribeWith(ctx context.Context, typeName string, showArgs, showDescriptions bool) (string, error)

DescribeWith returns a formatted SDL string for the named type with explicit options. showArgs includes field argument signatures; showDescriptions includes doc comments. Results from the underlying introspection call are cached.

func (*Describer) DescribeWithDepth added in v0.2.1

func (d *Describer) DescribeWithDepth(ctx context.Context, typeName string, showArgs, showDescriptions bool, depth int) (string, error)

DescribeWithDepth returns SDL for typeName and, when depth > 0, recursively includes referenced non-scalar types up to the requested depth.

depth behavior:

  • 0: only the requested type
  • 1: requested type + directly referenced non-scalar types
  • N: recurse through non-scalar references N levels deep

When depth >= 1, reverse-reference sections are also appended, capped at 5 top-level operation references and 5 referencing schema types by default.

func (*Describer) DescribeWithDepthLimits added in v0.8.0

func (d *Describer) DescribeWithDepthLimits(ctx context.Context, typeName string, showArgs, showDescriptions bool, depth, maxOperationRefs, maxFieldRefs int) (string, error)

DescribeWithDepthLimits is like DescribeWithDepth, but lets callers override the caps for reverse-reference sections. maxOperationRefs and maxFieldRefs use 0 to mean unlimited.

typeName also accepts "Type.field" (e.g. "Query.smsCampaign") to describe a single field's call signature instead of a whole type — the same field a substring match on queries/mutations --filter could pick up, but selected exactly. Depth then expands only the types that field's args/return type reference; reverse-reference sections are skipped, since Query/Mutation fields are themselves the thing those sections would otherwise point back to.

func (*Describer) DescribeWithFieldFilter added in v0.2.1

func (d *Describer) DescribeWithFieldFilter(ctx context.Context, typeName, fieldFilter string) (string, error)

DescribeWithFieldFilter returns SDL for typeName with only fields whose names contain fieldFilter (case-insensitive). If no fields match, it returns "".

This is used by schema hint enrichment for unknown field errors, so users see the closest matching fields first. Callers should fall back to Describe when the returned hint is empty.

func (*Describer) DescribeWithOptions added in v0.5.0

func (d *Describer) DescribeWithOptions(ctx context.Context, typeName string, opts DescribeOptions) (string, error)

DescribeWithOptions returns SDL for typeName under opts. It returns an empty string when FieldFilter matches nothing, which lets a caller tell "no such field" apart from a type that has none.

Filtering happens before formatting, so a type with hundreds of fields can be inspected a slice at a time — handing all of them to a model is the context blowup that filtering exists to prevent. When Depth is set, recursion follows only the surviving fields.

type Embedder added in v0.6.0

type Embedder interface {
	Embed(ctx context.Context, text string) ([]float32, error)
	Model() string
}

Embedder turns text into a vector. Implement it to index and search with a provider other than Venu; Model is recorded in the index file so a search against vectors from a different model can be rejected.

type EmbeddingIndex added in v0.6.0

type EmbeddingIndex struct {
	Version int    `json:"version"`
	Env     string `json:"env,omitempty"`
	// Endpoint is the GraphQL URL the schema was introspected from.
	Endpoint string `json:"endpoint,omitempty"`
	// EmbeddingEndpoint and Model identify the vector space. Comparing a query
	// embedded by a different model against these vectors is meaningless, so
	// Search refuses it.
	EmbeddingEndpoint string    `json:"embedding_endpoint,omitempty"`
	Model             string    `json:"model"`
	Dim               int       `json:"dim"`
	CreatedAt         time.Time `json:"created_at"`
	// Queries and Mutations hold the root-level entry points, kept separate
	// from Types because "find me the operation for X" and "find me the type
	// for X" are different questions with different candidate pools.
	Queries   []OperationEmbedding `json:"queries,omitempty"`
	Mutations []OperationEmbedding `json:"mutations,omitempty"`
	Types     []TypeEmbedding      `json:"types"`
	// contains filtered or unexported fields
}

EmbeddingIndex is a searchable set of GraphQL embeddings, persisted as JSON. Entries are grouped into three categories: Queries and Mutations (fields of the respective root types — the schema's entry points) and Types (every other GraphQL type). Build one with BuildEmbeddingIndex, load one with LoadEmbeddingIndex.

func BuildEmbeddingIndex added in v0.6.0

func BuildEmbeddingIndex(ctx context.Context, introspection map[string]interface{}, e Embedder, opts EmbeddingIndexOptions) (*EmbeddingIndex, error)

BuildEmbeddingIndex embeds the types and root-level operations in a GraphQL introspection response. introspection is the full envelope returned by Client.Introspect (the map with a "data" key).

func BuildEmbeddingIndexFromClient added in v0.6.0

func BuildEmbeddingIndexFromClient(ctx context.Context, client Client, e Embedder, opts EmbeddingIndexOptions) (*EmbeddingIndex, error)

BuildEmbeddingIndexFromClient introspects through client and builds an index from the result.

func LoadEmbeddingIndex added in v0.6.0

func LoadEmbeddingIndex(path string) (*EmbeddingIndex, error)

LoadEmbeddingIndex reads an index file written by Save and normalizes its vectors for search.

func (*EmbeddingIndex) Embedder added in v0.6.0

func (ix *EmbeddingIndex) Embedder() Embedder

Embedder returns the attached embedder, or nil.

func (*EmbeddingIndex) Save added in v0.6.0

func (ix *EmbeddingIndex) Save(path string) error

Save writes the index as JSON, creating parent directories as needed.

func (*EmbeddingIndex) Search added in v0.6.0

func (ix *EmbeddingIndex) Search(ctx context.Context, query string, topN int) (*SearchResults, error)

Search embeds query once and ranks it against all three categories, returning up to topN hits per category. It fails if the attached embedder's model differs from the one that built the index — scores across vector spaces are meaningless.

func (*EmbeddingIndex) SearchVector added in v0.6.0

func (ix *EmbeddingIndex) SearchVector(vec []float32, topN int) (*SearchResults, error)

SearchVector ranks an already-computed query vector against all three categories. No network calls; useful when the caller embeds queries itself or reuses one vector across several indexes.

func (*EmbeddingIndex) SetEmbedder added in v0.6.0

func (ix *EmbeddingIndex) SetEmbedder(e Embedder)

SetEmbedder attaches the embedder used to embed search queries. Required before calling Search on a loaded index.

type EmbeddingIndexOptions added in v0.6.0

type EmbeddingIndexOptions struct {
	// Kinds restricts the Types category to these type kinds (OBJECT,
	// INPUT_OBJECT, ENUM, INTERFACE, UNION, SCALAR). Empty indexes every kind.
	// Does not affect the Queries/Mutations categories.
	Kinds []string
	// Include keeps only names (of types, query fields, and mutation fields)
	// matching one of these globs, when non-empty.
	Include []string
	// Exclude drops names matching any of these globs. Applied after Include.
	Exclude []string
	// ShowArgs includes field argument signatures in an indexed type's SDL.
	// Query and mutation field signatures always include their arguments,
	// regardless of this setting — arguments are the call signature.
	ShowArgs bool
	// SkipQueries excludes the Query root's fields from the index.
	SkipQueries bool
	// SkipMutations excludes the Mutation root's fields from the index.
	SkipMutations bool
	// MaxChars truncates the embedded text. Zero uses DefaultEmbeddingMaxChars.
	MaxChars int
	// Concurrency is the number of in-flight embedding requests. Zero uses 4.
	Concurrency int
	// Previous is an existing index whose vectors are reused for entries whose
	// text hash is unchanged, so a rebuild only pays for what moved.
	Previous *EmbeddingIndex
	// Force re-embeds every entry even when Previous has a matching hash.
	Force bool
	// Env and Endpoint are recorded in the index for mismatch warnings.
	Env      string
	Endpoint string
	// Progress, when set, is called as each entry completes. Calls are
	// serialized, so it needs no locking of its own.
	Progress func(done, total int, name string, reused bool)
}

EmbeddingIndexOptions controls BuildEmbeddingIndex.

type EnvConfig

type EnvConfig struct {
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"`
	Login   *EnvLoginConfig   `json:"login,omitempty"`
	// Embeddings pins the type-embedding index file for this environment,
	// overriding the default .gqlcli-embeddings[.<env>].json path.
	Embeddings string `json:"embeddings,omitempty"`
}

EnvConfig holds per-environment connection settings.

type EnvLoginConfig added in v0.2.0

type EnvLoginConfig struct {
	Mutation     string                 `json:"mutation"`
	TokenPath    string                 `json:"token_path"`
	Credentials  map[string]interface{} `json:"credentials,omitempty"`
	HeaderName   string                 `json:"header_name,omitempty"`
	HeaderPrefix string                 `json:"header_prefix,omitempty"`
}

EnvLoginConfig stores the login mutation and token path for an environment, so gqlcli login can re-authenticate without repeating the mutation string.

Credentials, HeaderName, and HeaderPrefix are only populated when `login --save-creds` is used; their presence is what lets an expired JWT trigger an automatic re-login (see CLIBuilder.autoReloginIfExpired). Credentials are written to .gqlcli.json in plaintext — only opt in on a trusted machine.

type ExecutionMode

type ExecutionMode int

ExecutionMode determines how the query is executed

const (
	ExecutionModeInline ExecutionMode = iota
	ExecutionModeHTTP
)

type Formatter

type Formatter interface {
	Format(data map[string]interface{}) (string, error)
	Name() string
}

Formatter formats query results

type FormatterRegistry

type FormatterRegistry interface {
	Register(name string, formatter Formatter) error
	Get(name string) (Formatter, error)
	List() []string
}

FormatterRegistry manages available formatters

type GraphQLError

type GraphQLError struct {
	Message    string                 `json:"message"`
	Path       []interface{}          `json:"path,omitempty"`
	Extensions map[string]interface{} `json:"extensions,omitempty"`
}

GraphQLError represents a GraphQL error

type GraphQLRequest

type GraphQLRequest struct {
	Query         string                 `json:"query"`
	Variables     map[string]interface{} `json:"variables,omitempty"`
	OperationName string                 `json:"operationName,omitempty"`
}

GraphQLRequest is the standard GraphQL request format

type GraphQLResponse

type GraphQLResponse struct {
	Data   map[string]interface{} `json:"data,omitempty"`
	Errors []GraphQLError         `json:"errors,omitempty"`
}

GraphQLResponse is the standard GraphQL response format

type GraphQLResponseError

type GraphQLResponseError struct {
	Response map[string]interface{}
	Query    string
}

GraphQLResponseError is returned by Execute when the server responds with GraphQL errors. The Response field holds the full response map with errors enriched with schema hints.

func (*GraphQLResponseError) Error

func (e *GraphQLResponseError) Error() string

type HTTPClient

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

HTTPClient is a GraphQL client that executes operations via HTTP.

It is safe to use from several goroutines. Note that LastResponseMetadata reports the most recent response across all of them, so it only carries a well-defined meaning when operations are issued serially.

func NewHTTPClient

func NewHTTPClient(cfg *Config) *HTTPClient

NewHTTPClient creates a new HTTP GraphQL client

func (*HTTPClient) Execute

func (c *HTTPClient) Execute(ctx context.Context, mode ExecutionMode, opts QueryOptions) (map[string]interface{}, error)

Execute runs a GraphQL query via HTTP

func (*HTTPClient) ExecuteMutation

func (c *HTTPClient) ExecuteMutation(ctx context.Context, mode ExecutionMode, opts MutationOptions) (map[string]interface{}, error)

ExecuteMutation runs a GraphQL mutation via HTTP

func (*HTTPClient) Introspect

func (c *HTTPClient) Introspect(ctx context.Context) (map[string]interface{}, error)

Introspect queries the GraphQL schema. When Config.SchemaCacheTTL is set, a result cached on disk within that TTL is returned without a request.

func (*HTTPClient) LastResponseMetadata added in v0.2.0

func (c *HTTPClient) LastResponseMetadata() *ResponseMetadata

LastResponseMetadata returns metadata from the most recent HTTP response.

func (*HTTPClient) Subscribe added in v0.2.0

func (c *HTTPClient) Subscribe(ctx context.Context, opts SubscriptionOptions, emit func(SubscriptionEvent) error) error

Subscribe executes a GraphQL subscription using the GraphQL over WebSocket protocol (graphql-transport-ws). It calls emit for each server event until the server sends complete, the context is cancelled, or an error occurs.

type InlineClient added in v0.5.0

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

InlineClient adapts an InlineExecutor to the Client interface, so anything built against Client — ScriptRunner most of all — can run in-process against a gqlgen schema instead of over HTTP.

func NewInlineClient added in v0.5.0

func NewInlineClient(exec *InlineExecutor) *InlineClient

NewInlineClient wraps an InlineExecutor as a Client.

func (*InlineClient) Describer added in v0.5.0

func (c *InlineClient) Describer() *Describer

Describer returns a Describer backed by this client's schema.

func (*InlineClient) Execute added in v0.5.0

func (c *InlineClient) Execute(ctx context.Context, _ ExecutionMode, opts QueryOptions) (map[string]interface{}, error)

Execute runs a query in-process.

The ExecutionMode argument is ignored. It exists to let a caller pick between gqlcli's HTTP and in-process transports, and an InlineClient is already one of those, so there is nothing left to select.

func (*InlineClient) ExecuteMutation added in v0.5.0

func (c *InlineClient) ExecuteMutation(ctx context.Context, _ ExecutionMode, opts MutationOptions) (map[string]interface{}, error)

ExecuteMutation runs a mutation in-process. As with HTTPClient, a non-nil Input is wrapped as {"input": ...}.

func (*InlineClient) Introspect added in v0.5.0

func (c *InlineClient) Introspect(ctx context.Context) (map[string]interface{}, error)

Introspect runs the full introspection query against the inline schema.

func (*InlineClient) LastResponseMetadata added in v0.5.0

func (c *InlineClient) LastResponseMetadata() *ResponseMetadata

LastResponseMetadata always returns nil: an in-process call has no HTTP response to report a status or headers from.

type InlineCommandSet

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

InlineCommandSet builds CLI commands backed by an InlineExecutor. It provides query, mutation, describe, and types commands that run in-process without needing an HTTP server.

func NewInlineCommandSet

func NewInlineCommandSet(exec *InlineExecutor, opts ...CommandSetOption) *InlineCommandSet

NewInlineCommandSet creates an InlineCommandSet backed by the given executor.

func (*InlineCommandSet) Commands

func (cs *InlineCommandSet) Commands() []*cli.Command

Commands returns the full command list.

func (*InlineCommandSet) Mount

func (cs *InlineCommandSet) Mount(app *cli.App)

Mount adds all commands to the app.

type InlineExecutor

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

InlineExecutor runs GraphQL operations in-process against a schema without an HTTP server. Create one with NewInlineExecutor; use Execute to run operations.

func NewInlineExecutor

func NewInlineExecutor(schema graphql.ExecutableSchema, opts ...Option) *InlineExecutor

NewInlineExecutor creates an InlineExecutor that runs GraphQL operations in-process. No HTTP server is required — operations execute directly against the schema.

func (*InlineExecutor) Execute

func (e *InlineExecutor) Execute(ctx context.Context, query string, variables map[string]interface{}) (json.RawMessage, error)

Execute runs a GraphQL query or mutation and returns the raw JSON response.

func (*InlineExecutor) ExecuteFunc

func (e *InlineExecutor) ExecuteFunc() func(context.Context, string, map[string]interface{}) (json.RawMessage, error)

ExecuteFunc returns Execute as a plain function value. Convenient for passing to builders or adapters that expect this signature.

func (*InlineExecutor) Schema added in v0.8.0

func (e *InlineExecutor) Schema() *ast.Schema

Schema returns the parsed schema behind this executor, or nil if there is none. An inline caller can hand it to NewSchemaValidator to validate documents without an introspection round trip.

type JSONFormatter

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

JSONFormatter outputs data as JSON

func NewJSONFormatter

func NewJSONFormatter(pretty bool) *JSONFormatter

NewJSONFormatter creates a JSON formatter

func (*JSONFormatter) Format

func (f *JSONFormatter) Format(data map[string]interface{}) (string, error)

func (*JSONFormatter) Name

func (f *JSONFormatter) Name() string

type LLMFormatter

type LLMFormatter struct{}

LLMFormatter outputs data in human and LLM-friendly markdown format

func NewLLMFormatter

func NewLLMFormatter() *LLMFormatter

NewLLMFormatter creates an LLM formatter

func (*LLMFormatter) Format

func (f *LLMFormatter) Format(data map[string]interface{}) (string, error)

func (*LLMFormatter) Name

func (f *LLMFormatter) Name() string

type LimitedWriter added in v0.5.0

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

LimitedWriter passes at most a fixed number of bytes through to an underlying writer and discards the rest, reporting whether anything was dropped. Build one with LimitWriter.

func LimitWriter added in v0.5.0

func LimitWriter(w io.Writer, limit int64) *LimitedWriter

LimitWriter caps what a script can write through WithStdout/WithStderr.

Capping at the writer, rather than trimming the buffer afterwards, is what actually bounds memory: a script that logs inside a loop produces its whole run's worth of output before anyone gets to trim it. A limit of zero or less discards everything.

It is not safe for concurrent use, which suits its purpose — script console output arrives on the runtime's single goroutine.

func (*LimitedWriter) Truncated added in v0.5.0

func (l *LimitedWriter) Truncated() bool

Truncated reports whether any output was discarded.

func (*LimitedWriter) Write added in v0.5.0

func (l *LimitedWriter) Write(p []byte) (int, error)

Write implements io.Writer. Short writes are never reported to the script: it returns len(p) even when part of p was dropped, since a discarded log line is not a script error.

func (*LimitedWriter) Written added in v0.5.0

func (l *LimitedWriter) Written() int64

Written reports how many bytes reached the underlying writer.

type LoginConfig

type LoginConfig struct {
	// Mutation is the GraphQL mutation to execute for login.
	// It must accept $email and $password string variables.
	Mutation string

	// ExtractToken extracts the JWT token from the mutation's response data map.
	ExtractToken func(data map[string]interface{}) (string, error)

	// Tokens is the store where the token will be persisted.
	// If nil, the InlineCommandSet's TokenStore is used.
	Tokens *TokenStore
}

LoginConfig configures the login/logout/whoami commands.

type MutationOptions

type MutationOptions struct {
	Mutation      string                 // GraphQL mutation string
	Variables     map[string]interface{} // Mutation variables
	OperationName string                 // Named operation to execute
	Input         interface{}            // Input object (auto-wrapped as {"input": {...}})
}

MutationOptions holds options for mutation execution

type NamedOperation added in v0.2.0

type NamedOperation struct {
	Type     string                 `json:"type"`               // "query", "mutation", or "subscription"
	Query    string                 `json:"query,omitempty"`    // set when Type == "query"; also accepted for Type == "subscription"
	Mutation string                 `json:"mutation,omitempty"` // set when Type == "mutation"
	Defaults map[string]interface{} `json:"defaults,omitempty"` // default variables; --variables overrides
}

NamedOperation is a saved GraphQL query, mutation, or subscription stored in .gqlcli.json. Execute with --op <name> on the query, mutation, or subscribe commands.

type NamedScript added in v0.5.0

type NamedScript struct {
	Lang        string                 `json:"lang,omitempty"`     // currently "javascript"
	Function    string                 `json:"function,omitempty"` // default function name; defaults to run
	Source      string                 `json:"source"`             // inline script source code
	Defaults    map[string]interface{} `json:"defaults,omitempty"` // default input object; --arg overrides
	Description string                 `json:"description,omitempty"`
}

NamedScript is an inline JavaScript workflow stored in .gqlcli.json.

func (*NamedScript) MergeInput added in v0.5.0

func (s *NamedScript) MergeInput(input map[string]interface{}) map[string]interface{}

MergeInput layers the caller's input over the script's Defaults, returning a new map. Keys present in input win.

type OperationEmbedding added in v0.6.0

type OperationEmbedding struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	// ReturnType is the field's GraphQL return type, e.g. "[User!]!".
	ReturnType string `json:"return_type"`
	// SDL is the field's call signature, e.g. "createUser(input: CreateUserInput!): User!".
	SDL       string    `json:"sdl"`
	TextHash  string    `json:"text_hash"`
	Embedding []float32 `json:"embedding"`
}

OperationEmbedding is one field of the Query or Mutation root type: its call signature, the hash of the text that was embedded, and the vector.

type OperationExecutor added in v0.5.0

type OperationExecutor interface {
	Execute(ctx context.Context, mode ExecutionMode, opts QueryOptions) (map[string]interface{}, error)
	ExecuteMutation(ctx context.Context, mode ExecutionMode, opts MutationOptions) (map[string]interface{}, error)
}

OperationExecutor runs GraphQL operations. It is the whole of what ScriptRunner needs, so an embedder adapting its own HTTP stack can satisfy it without writing stubs for schema introspection or response metadata.

type OperationMatch added in v0.6.0

type OperationMatch struct {
	Name        string  `json:"name"`
	ReturnType  string  `json:"return_type"`
	Description string  `json:"description,omitempty"`
	SDL         string  `json:"sdl"`
	Score       float64 `json:"score"`
}

OperationMatch is one query/mutation field search hit.

type Option

type Option func(*inlineConfig)

Option configures an InlineExecutor.

func WithContextEnricher

func WithContextEnricher(fn func(context.Context) context.Context) Option

WithContextEnricher sets a function called before each Execute to enrich the context. Use it to inject dataloaders, auth, or other request-scoped values.

func WithSchemaHints

func WithSchemaHints() Option

WithSchemaHints enables schemaHint extensions on GraphQL validation errors. When a field, argument, or type is not found, the error will include a schemaHint extension containing a compact SDL description of the referenced type.

type ProjectConfig

type ProjectConfig struct {
	Default      string                    `json:"default"`
	Environments map[string]EnvConfig      `json:"environments"`
	Operations   map[string]NamedOperation `json:"operations,omitempty"`
	Scripts      map[string]NamedScript    `json:"scripts,omitempty"`
}

ProjectConfig represents the .gqlcli.json configuration file.

Example:

{
  "default": "local",
  "environments": {
    "local": {
      "url": "http://localhost:8080/graphql",
      "headers": { "Authorization": "Bearer dev-token" }
    },
    "prod": {
      "url": "https://api.example.com/graphql",
      "headers": { "Authorization": "Bearer prod-token" }
    }
  }
}

func LoadProjectConfig

func LoadProjectConfig() (*ProjectConfig, error)

LoadProjectConfig reads .gqlcli.json from the current directory. Returns nil, nil if the file does not exist.

func (*ProjectConfig) Resolve

func (p *ProjectConfig) Resolve(envName string) (*EnvConfig, error)

Resolve returns the EnvConfig for the given environment name. If envName is empty, the default environment is used. Returns nil, nil when envName is empty and no default is configured.

func (*ProjectConfig) ResolveScript added in v0.5.0

func (p *ProjectConfig) ResolveScript(name string) (*NamedScript, error)

ResolveScript returns the named script from the "scripts" section, with Function defaulted to "run". It lets an embedder reuse scripts saved in .gqlcli.json without reimplementing lookup and validation.

type QueryEmbedder added in v0.6.0

type QueryEmbedder interface {
	EmbedQuery(ctx context.Context, text string) ([]float32, error)
}

QueryEmbedder is implemented by embedders that embed search queries differently from indexed documents. EmbeddingIndex.Search uses it when available and falls back to Embed otherwise.

type QueryOptions

type QueryOptions struct {
	Query         string                 // GraphQL query string
	Variables     map[string]interface{} // Query variables
	OperationName string                 // Named operation to execute
}

QueryOptions holds options for query execution

type RequestInfo added in v0.5.0

type RequestInfo struct {
	// Type is the operation kind the document actually declares —
	// OperationQuery, OperationMutation or OperationSubscription — not the
	// gql helper the script happened to call. It falls back to the helper's
	// own kind only when the document cannot be parsed.
	Type string
	// Operation is the GraphQL document text.
	Operation string
	// OperationName is the operation name, if the script supplied one.
	OperationName string
	// Variables are the operation variables. Callbacks receive a copy, so
	// mutating this map does not change what is sent.
	Variables map[string]interface{}
}

RequestInfo describes a single GraphQL operation a script is attempting.

type ResponseMetadata added in v0.2.0

type ResponseMetadata struct {
	Status     string
	StatusCode int
	Proto      string
	Headers    http.Header
}

ResponseMetadata captures HTTP response details from the most recent request.

type SchemaValidator added in v0.8.0

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

SchemaValidator checks documents against a schema without executing them.

Building one costs a single introspection round trip, so reuse it across documents. It holds no mutable state and is safe to share between goroutines.

func NewSchemaValidator added in v0.8.0

func NewSchemaValidator(schema *ast.Schema) *SchemaValidator

NewSchemaValidator validates against an already-parsed schema. Inline callers can pass InlineExecutor.Schema() and skip introspection entirely.

func NewSchemaValidatorFromClient added in v0.8.0

func NewSchemaValidatorFromClient(ctx context.Context, client Client) (*SchemaValidator, error)

NewSchemaValidatorFromClient introspects through client and rebuilds the schema. It works over either transport, since both the HTTP and inline clients satisfy Client.

func NewSchemaValidatorFromConfig added in v0.8.0

func NewSchemaValidatorFromConfig(ctx context.Context, cfg *Config) (*SchemaValidator, error)

NewSchemaValidatorFromConfig introspects the endpoint described by cfg, which carries the token, headers, timeout and TLS settings the request needs.

func NewSchemaValidatorFromIntrospection added in v0.8.0

func NewSchemaValidatorFromIntrospection(introspection map[string]interface{}) (*SchemaValidator, error)

NewSchemaValidatorFromIntrospection rebuilds the schema from an introspection result, accepting either a response envelope or a bare __schema map.

func NewSchemaValidatorFromSDL added in v0.8.0

func NewSchemaValidatorFromSDL(sdl string) (*SchemaValidator, error)

NewSchemaValidatorFromSDL validates against a schema read from SDL — a file on disk, or the output of SDL() saved from an earlier introspection.

func NewSchemaValidatorFromURL added in v0.8.0

func NewSchemaValidatorFromURL(ctx context.Context, url string) (*SchemaValidator, error)

NewSchemaValidatorFromURL introspects a public endpoint, for callers who have nothing but its URL. Use NewSchemaValidatorFromConfig when the endpoint needs auth.

func (*SchemaValidator) SDL added in v0.8.0

func (v *SchemaValidator) SDL() string

SDL returns the SDL the validator was built from, empty when it was built from an already-parsed schema. Persist it to rebuild the validator later without reaching the server again.

func (*SchemaValidator) Schema added in v0.8.0

func (v *SchemaValidator) Schema() *ast.Schema

Schema returns the schema documents are validated against.

func (*SchemaValidator) Validate added in v0.8.0

func (v *SchemaValidator) Validate(document string) *ValidationResult

Validate parses document and checks it against the schema without executing it. Variable values are not part of the document, so they are not checked here; a document declaring required variables validates on its own.

type ScriptOption added in v0.5.0

type ScriptOption func(*scriptConfig)

ScriptOption configures a ScriptRunner.

func WithApprover added in v0.5.0

func WithApprover(fn func(context.Context, RequestInfo) error) ScriptOption

WithApprover gates each operation after WithReadOnly and the operation budget. Returning a non-nil error aborts that one operation; the script may catch it and continue. Use it to prompt a human or apply a host policy.

It runs on the goroutine blocked inside RunSource, so an approver that waits on a human holds that script still while it waits — and only that script.

func WithMaxOperations added in v0.5.0

func WithMaxOperations(n int) ScriptOption

WithMaxOperations caps how many GraphQL operations one run may attempt. Operations blocked by WithReadOnly or WithApprover count against the budget, so a script cannot spin indefinitely against a rejecting policy. Zero or negative means unlimited.

func WithOnRequest added in v0.5.0

func WithOnRequest(fn func(RequestInfo)) ScriptOption

WithOnRequest registers a callback invoked for every operation a script attempts, before any policy check. Operations later blocked by WithReadOnly or WithApprover are reported here too; use WithOnResponse for the outcome.

Within one run the callback is invoked from a single goroutine — gql.each interleaves its workers inside one JavaScript runtime rather than spreading them across goroutines — so it needs no locking to observe a single run. Concurrent RunSource calls on a shared runner do run in parallel, so a callback accumulating state across runs must guard it.

func WithOnResponse added in v0.5.0

func WithOnResponse(fn func(RequestInfo, map[string]interface{}, error)) ScriptOption

WithOnResponse registers a callback invoked after each attempted operation settles, with the result or the error that blocked or failed it. It carries the same threading guarantee as WithOnRequest.

func WithReadOnly added in v0.5.0

func WithReadOnly(readOnly bool) ScriptOption

WithReadOnly rejects every mutation the script dispatches. The kind is taken from the parsed document, not from the helper the script called, so gql.query("mutation { ... }") is blocked too. A document that cannot be parsed is refused rather than sent, since an unclassifiable operation is exactly what a read-only policy must not wave through.

The rejection surfaces in JavaScript as a catchable throw.

func WithStderr added in v0.5.0

func WithStderr(w io.Writer) ScriptOption

WithStderr redirects script console.error output. Defaults to os.Stderr.

func WithStdout added in v0.5.0

func WithStdout(w io.Writer) ScriptOption

WithStdout redirects script console.log output. Defaults to os.Stdout. Hosts that reserve their own stdout for structured output must set this.

func WithTimeout added in v0.5.0

func WithTimeout(d time.Duration) ScriptOption

WithTimeout bounds a single run. It derives a deadline from the context passed to RunSource/RunFile; cancelling that context still works on its own.

type ScriptRunner added in v0.4.0

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

ScriptRunner executes JavaScript automation against a GraphQL client.

func NewScriptRunner added in v0.4.0

func NewScriptRunner(client OperationExecutor, opts ...ScriptOption) *ScriptRunner

NewScriptRunner builds a runner. With no options it writes console output to the process stdio and imposes no policy. Hosts embedding the runner should at minimum set WithStdout/WithStderr and run under a cancellable context.

func (*ScriptRunner) RunFile added in v0.4.0

func (r *ScriptRunner) RunFile(ctx context.Context, filePath, fnName string, input interface{}) (interface{}, error)

RunFile executes a JavaScript file and calls fnName(gql, input).

func (*ScriptRunner) RunSource added in v0.5.0

func (r *ScriptRunner) RunSource(ctx context.Context, sourceName, source, fnName string, input interface{}) (interface{}, error)

RunSource executes JavaScript source and calls fnName(gql, input). The gql argument exposes helpers: query, mutation, request, each.

type SearchResults added in v0.6.0

type SearchResults struct {
	Queries   []OperationMatch `json:"queries,omitempty"`
	Mutations []OperationMatch `json:"mutations,omitempty"`
	Types     []TypeMatch      `json:"types,omitempty"`
}

SearchResults groups a search's hits by category, each independently ranked and truncated to the requested topN.

type SubscriptionEvent added in v0.2.0

type SubscriptionEvent struct {
	Type    string      `json:"type"`
	Payload interface{} `json:"payload,omitempty"`
}

SubscriptionEvent is one stream event emitted by Subscribe.

type SubscriptionOptions added in v0.2.0

type SubscriptionOptions struct {
	Subscription  string                 // GraphQL subscription string
	Variables     map[string]interface{} // Subscription variables
	OperationName string                 // Named operation to execute
}

SubscriptionOptions holds options for GraphQL subscription execution.

type TOONFormatter

type TOONFormatter struct{}

TOONFormatter outputs data in TOON format (Token-Optimized Object Notation) Uses the official toon-go library: https://github.com/toon-format/toon-go Reduces token usage by 40-60% compared to standard JSON

func NewTOONFormatter

func NewTOONFormatter() *TOONFormatter

NewTOONFormatter creates a TOON formatter

func (*TOONFormatter) Format

func (f *TOONFormatter) Format(data map[string]interface{}) (string, error)

func (*TOONFormatter) Name

func (f *TOONFormatter) Name() string

type TableFormatter

type TableFormatter struct{}

TableFormatter outputs data as a formatted table

func NewTableFormatter

func NewTableFormatter() *TableFormatter

NewTableFormatter creates a table formatter

func (*TableFormatter) Format

func (f *TableFormatter) Format(data map[string]interface{}) (string, error)

func (*TableFormatter) Name

func (f *TableFormatter) Name() string

type TokenStore

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

TokenStore persists a JWT token on disk. Tokens are stored at {dir}/token with 0600 permissions. Create with NewTokenStore (uses ~/.{appName}/token) or NewTokenStoreAt for a custom path.

func NewTokenStore

func NewTokenStore(appName string) *TokenStore

NewTokenStore creates a TokenStore that stores tokens under ~/.{appName}/.

func NewTokenStoreAt

func NewTokenStoreAt(dir string) *TokenStore

NewTokenStoreAt creates a TokenStore that stores tokens in the given directory.

func (*TokenStore) Clear

func (s *TokenStore) Clear() error

Clear deletes the saved token file.

func (*TokenStore) Exists

func (s *TokenStore) Exists() bool

Exists reports whether a token file is present.

func (*TokenStore) FormatInfo

func (s *TokenStore) FormatInfo() string

FormatInfo returns a human-readable summary of the current token. Returns an empty string if no token is saved or it cannot be parsed.

func (*TokenStore) FormatInfoJSON

func (s *TokenStore) FormatInfoJSON() (string, error)

FormatInfoJSON returns token info as a JSON string.

func (*TokenStore) Load

func (s *TokenStore) Load() (string, error)

Load reads the token from disk. Returns an empty string (not an error) if no token file exists.

func (*TokenStore) ParseClaims

func (s *TokenStore) ParseClaims(tokenString string) (*Claims, error)

ParseClaims parses JWT claims from a token string without validating the signature. This is safe for reading tokens that your own application issued and saved.

func (*TokenStore) Save

func (s *TokenStore) Save(token string) error

Save writes the token to disk, creating the directory if needed.

type TypeEmbedding added in v0.6.0

type TypeEmbedding struct {
	Name        string `json:"name"`
	Kind        string `json:"kind"`
	Description string `json:"description,omitempty"`
	// SDL is the compact type definition, ready to paste into an LLM prompt.
	SDL string `json:"sdl"`
	// TextHash is sha256 of the exact text embedded. A rebuild reuses the
	// vector when the hash is unchanged.
	TextHash  string    `json:"text_hash"`
	Embedding []float32 `json:"embedding"`
}

TypeEmbedding is one GraphQL type in an embedding index: its SDL, the hash of the text that was embedded, and the vector.

type TypeMatch added in v0.6.0

type TypeMatch struct {
	Name        string  `json:"name"`
	Kind        string  `json:"kind"`
	Description string  `json:"description,omitempty"`
	SDL         string  `json:"sdl"`
	Score       float64 `json:"score"`
}

TypeMatch is one type search hit. Score is cosine similarity in [-1, 1]; higher is closer.

type ValidationError added in v0.8.0

type ValidationError struct {
	Message string `json:"message"`
	Line    int    `json:"line,omitempty"`
	Column  int    `json:"column,omitempty"`
	Rule    string `json:"rule,omitempty"`
	Path    string `json:"path,omitempty"`

	// SchemaHint is compact SDL for the type the message refers to, empty when
	// it names none. Map renders it under extensions, where the executed path
	// puts its own hint.
	SchemaHint string `json:"schemaHint,omitempty"`
}

ValidationError is one problem found in a document.

func (ValidationError) String added in v0.8.0

func (e ValidationError) String() string

String renders the error as "line:column: message", omitting the position when the error carries none.

type ValidationResult added in v0.8.0

type ValidationResult struct {
	Valid bool `json:"valid"`

	Errors []ValidationError `json:"errors,omitempty"`

	// OperationNames holds the name of each operation in the document, with an
	// empty string for an anonymous one. Both it and OperationKinds are empty
	// when the document could not be parsed.
	OperationNames []string `json:"operationNames,omitempty"`
	OperationKinds []string `json:"operationKinds,omitempty"`
}

ValidationResult is the verdict on a single document.

func (*ValidationResult) Map added in v0.8.0

func (r *ValidationResult) Map() map[string]interface{}

Map renders the result in the shape the output formatters consume, so validation output can be piped through --format and --jq like any response.

func (*ValidationResult) String added in v0.8.0

func (r *ValidationResult) String() string

String renders one error per line.

type VenuEmbedder added in v0.6.0

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

VenuEmbedder calls the Venu embeddings endpoint (POST {BaseURL}/embeddings) with an X-API-Key header. One request per text — the endpoint rejects arrays.

func NewVenuEmbedder added in v0.6.0

func NewVenuEmbedder(opts ...VenuEmbedderOption) (*VenuEmbedder, error)

NewVenuEmbedder creates a Venu-backed Embedder. The API key comes from WithEmbeddingAPIKey, else VENU_API_KEY; the base URL from WithEmbeddingBaseURL, else VENU_URL, else DefaultEmbeddingBaseURL.

func (*VenuEmbedder) Embed added in v0.6.0

func (e *VenuEmbedder) Embed(ctx context.Context, text string) ([]float32, error)

Embed returns the vector for indexed text, with the document task prefix applied. Text is not truncated here; callers that index long documents should truncate to DefaultEmbeddingMaxChars first so the hash they store matches what the model saw.

func (*VenuEmbedder) EmbedQuery added in v0.6.0

func (e *VenuEmbedder) EmbedQuery(ctx context.Context, text string) ([]float32, error)

EmbedQuery returns the vector for a search query, with the query task prefix applied.

func (*VenuEmbedder) Endpoint added in v0.6.0

func (e *VenuEmbedder) Endpoint() string

Endpoint returns the embeddings URL requests are sent to.

func (*VenuEmbedder) Model added in v0.6.0

func (e *VenuEmbedder) Model() string

Model returns the configured embedding model name.

type VenuEmbedderOption added in v0.6.0

type VenuEmbedderOption func(*VenuEmbedder)

VenuEmbedderOption configures NewVenuEmbedder.

func WithEmbeddingAPIKey added in v0.6.0

func WithEmbeddingAPIKey(key string) VenuEmbedderOption

WithEmbeddingAPIKey sets the X-API-Key value explicitly instead of reading VENU_API_KEY from the environment.

func WithEmbeddingBaseURL added in v0.6.0

func WithEmbeddingBaseURL(url string) VenuEmbedderOption

WithEmbeddingBaseURL overrides the API base URL (no trailing /embeddings).

func WithEmbeddingHTTPClient added in v0.6.0

func WithEmbeddingHTTPClient(c *http.Client) VenuEmbedderOption

WithEmbeddingHTTPClient supplies the HTTP client used for requests.

func WithEmbeddingModel added in v0.6.0

func WithEmbeddingModel(model string) VenuEmbedderOption

WithEmbeddingModel selects the embedding model (e.g. nomic-embed-text-v1.5).

func WithEmbeddingTaskPrefixes added in v0.6.0

func WithEmbeddingTaskPrefixes(document, query string) VenuEmbedderOption

WithEmbeddingTaskPrefixes sets the task prefixes prepended to document and query text. Pass empty strings to disable prefixing for a model that does not want it; the nomic-embed-text defaults apply when this option is not used.

Jump to

Keyboard shortcuts

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