Documentation
¶
Overview ¶
Package manage is a small client for the DocsGPT account-level ("management") API: identity, agents (list/export/plan/apply/delete), sources (list/upload/task status/delete), prompts and tools. Every request carries a personal access token as `Authorization: Bearer dgpt_pat_…`.
Failures reported by the server are returned as *APIError, which surfaces the server `message`, the machine-readable `error` code and, for insufficient_scope, the scope the token is missing.
Index ¶
- Constants
- func DeriveIdempotencyKey(name string, paths []string) (string, error)
- func IsInsufficientScope(err error) bool
- func IsNotFound(err error) bool
- func IsResourceNotAllowed(err error) bool
- func IsUnauthorized(err error) bool
- func SplitYAMLDocuments(text string) []string
- type APIError
- type Agent
- type ApplyResult
- type Blocker
- type Client
- func (c *Client) ApplyImport(ctx context.Context, yamlDoc string, res *Resolution) (*ApplyResult, error)
- func (c *Client) DeleteAgent(ctx context.Context, id string) error
- func (c *Client) DeleteSource(ctx context.Context, id string) error
- func (c *Client) ExportAgent(ctx context.Context, id string) ([]byte, error)
- func (c *Client) GetTaskStatus(ctx context.Context, taskID string) (*TaskStatus, error)
- func (c *Client) ListAgents(ctx context.Context) ([]Agent, json.RawMessage, error)
- func (c *Client) ListPrompts(ctx context.Context) ([]Prompt, json.RawMessage, error)
- func (c *Client) ListSources(ctx context.Context) ([]Source, json.RawMessage, error)
- func (c *Client) ListTools(ctx context.Context) ([]Tool, json.RawMessage, error)
- func (c *Client) Me(ctx context.Context) (*Identity, error)
- func (c *Client) PlanImport(ctx context.Context, yamlDoc string) (*Plan, error)
- func (c *Client) UploadSource(ctx context.Context, name string, paths []string, idempotencyKey string) (*UploadResult, error)
- func (c *Client) WaitTask(ctx context.Context, taskID string, opts WaitOptions) (*TaskStatus, error)
- type Decision
- type Document
- type Identity
- type ModelDecision
- type Plan
- type PlanModel
- type PlanPrompt
- type PlanSource
- type PlanTarget
- type PlanTool
- type PlanWorkflow
- type Prompt
- type Resolution
- type ResolveEntry
- type ResolveSet
- type Source
- type TaskFailedError
- type TaskStatus
- type TokenInfo
- type Tool
- type ToolDecision
- type UploadResult
- type WaitOptions
Constants ¶
const ( StatusMatched = "matched" // source / built-in model id resolved StatusMissing = "missing" // source name not found for this user StatusReuse = "reuse" // tool / prompt / custom model already exists StatusCreate = "create" // will be created from the file StatusBuiltin = "builtin" // built-in tool available on this instance StatusDefault = "default" // prompt: the agent uses the default prompt )
Plan statuses reported by POST /api/import_agent/plan.
const ( DefaultTimeout = 60 * time.Second // JSON requests DefaultUploadTimeout = 15 * time.Minute // multipart uploads )
Timeouts applied when the caller's context carries no earlier deadline.
const ( CodeInvalidToken = "invalid_token" CodeInsufficientScope = "insufficient_scope" CodeResourceNotAllowed = "resource_not_allowed" CodeNotForTokens = "not_available_to_tokens" // endpoint has no token scope at all )
Server error codes (the JSON `error` field).
const DeduplicatedTaskID = "deduplicated"
DeduplicatedTaskID is the task_id sentinel the server returns when an Idempotency-Key repeat matched a request whose task record is gone: the original ingest already ran, and there is nothing left to poll.
const DefaultUserAgent = "docsgpt-cli"
DefaultUserAgent is used when the caller does not stamp a version.
const IdempotencyKeyMaxLen = 256
IdempotencyKeyMaxLen mirrors the server's Idempotency-Key limit.
const KindAgent = "Agent"
KindAgent is the only document kind the import API accepts.
Variables ¶
This section is empty.
Functions ¶
func DeriveIdempotencyKey ¶
DeriveIdempotencyKey builds a deterministic Idempotency-Key from the source name and the SHA-256 of every file (paired with its base name, order independent). The same name + content always yields the same key, so a CI retry of an upload is deduplicated server-side; any change to the name, a filename or a byte of content yields a new key.
func IsInsufficientScope ¶
IsInsufficientScope reports whether err is a missing-scope rejection.
func IsResourceNotAllowed ¶
IsResourceNotAllowed reports whether err is a resource-restriction rejection.
func IsUnauthorized ¶
IsUnauthorized reports whether err is a 401 / invalid_token rejection.
func SplitYAMLDocuments ¶
SplitYAMLDocuments splits a YAML stream on its document markers, keeping each document's text verbatim (the server receives exactly what was written). A `---` line starts a document and a `...` line ends one; the YAML spec forbids both at column 0 inside any scalar, so a textual split is exact. Chunks that are entirely blank are dropped; chunks holding only comments are kept and discarded by ParseDocuments.
Types ¶
type APIError ¶
type APIError struct {
Method string
Path string
Status int
Code string // server `error` field, e.g. insufficient_scope
Message string // server `message` field
RequiredScope string // server `required_scope` (insufficient_scope only)
Body string // truncated raw body, for diagnostics
}
APIError is a failure reported by the server (any non-2xx response, or a 2xx body with success:false).
type Agent ¶
type Agent struct {
ID string `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Description string `json:"description"`
AgentType string `json:"agent_type"`
Status string `json:"status"`
Ownership string `json:"ownership"`
UpdatedAt any `json:"updated_at"`
}
Agent is the subset of an agent document the CLI renders. The full server document is available through the raw return of ListAgents.
type ApplyResult ¶
type ApplyResult struct {
AgentID string `json:"agent_id"`
Action string `json:"action"` // created | updated
Status string `json:"status"` // draft on create; unchanged on update
AgentType string `json:"agent_type"`
Slug string `json:"slug"`
Warnings []string `json:"warnings"`
}
ApplyResult is the POST /api/import_agent reply.
type Blocker ¶
type Blocker struct {
Kind string `json:"kind"` // source | tool | model
Ref string `json:"ref"` // source name, tool key, model id/name
Status string `json:"status"`
Hint string `json:"hint"`
}
Blocker is one unresolved reference that stops an apply.
type Client ¶
type Client struct {
BaseURL string
Token string
UserAgent string // "docsgpt-cli/<version>"
Timeout time.Duration // per JSON request; 0 = DefaultTimeout
UploadTimeout time.Duration // per upload; 0 = DefaultUploadTimeout
// HTTP is the underlying client. It deliberately has no Timeout of its
// own: every request is bounded by its context instead.
HTTP *http.Client
}
Client talks to one DocsGPT deployment with one personal access token.
func (*Client) ApplyImport ¶
func (c *Client) ApplyImport(ctx context.Context, yamlDoc string, res *Resolution) (*ApplyResult, error)
ApplyImport calls POST /api/import_agent with {"yaml": <document>, "resolution": {...}} (scope agents:write). A new agent is created as a draft; an update keeps the matched agent's status.
func (*Client) DeleteAgent ¶
DeleteAgent calls DELETE /api/delete_agent?id= (scope agents:write).
func (*Client) DeleteSource ¶
DeleteSource calls GET /api/delete_old?source_id= (scope sources:write). The server exposes the deletion as a GET.
func (*Client) ExportAgent ¶
ExportAgent calls GET /api/export_agent?id= and returns the YAML document (scope agents:read).
func (*Client) GetTaskStatus ¶
GetTaskStatus calls GET /api/task_status?task_id= (any of sources:read, sources:write or chat:run).
func (*Client) ListAgents ¶
ListAgents calls GET /api/get_agents (scope agents:read).
func (*Client) ListPrompts ¶
ListPrompts calls GET /api/get_prompts (scope prompts:read).
func (*Client) ListSources ¶
ListSources calls GET /api/sources (scope sources:read).
func (*Client) ListTools ¶
ListTools calls GET /api/get_tools (scope tools:read). raw is the server's `tools` array.
func (*Client) PlanImport ¶
PlanImport calls POST /api/import_agent/plan with {"yaml": <document>} (scope agents:write, like the apply itself). Nothing is written server-side.
func (*Client) UploadSource ¶
func (c *Client) UploadSource(ctx context.Context, name string, paths []string, idempotencyKey string) (*UploadResult, error)
UploadSource calls POST /api/upload (scope sources:write) with a multipart body: `user`, `name` and one `file` part per path. idempotencyKey, when non-empty, is sent as the Idempotency-Key header: a repeat within the server's dedup window returns the original task instead of re-ingesting. File contents are streamed, so large files are never buffered in memory.
func (*Client) WaitTask ¶
func (c *Client) WaitTask(ctx context.Context, taskID string, opts WaitOptions) (*TaskStatus, error)
WaitTask polls GET /api/task_status with exponential backoff until the task reaches SUCCESS (returned), FAILURE/REVOKED (*TaskFailedError) or ctx ends (the timeout). A 503 is transient and polling continues.
type Decision ¶
type Decision struct {
Resolution *Resolution // what to send with the apply (nil when empty)
Blockers []Blocker // missing / unavailable references left uncovered
Notices []string // non-blocking heads-ups
// Covered maps "kind:ref" to a short description of the covering entry,
// for the plan summary.
Covered map[string]string
}
Decision is the outcome of matching the --resolve entries against one document's plan.
type Document ¶
type Document struct {
Source string // "agents/support.yaml", "agents/all.yaml#2", or "<stdin>"
Index int // 1-based position within its file
Text string // the document text exactly as written (comments included)
Kind string
APIVersion string
Name string // spec.name
ID string // metadata.id
Slug string // metadata.slug
}
Document is one YAML document destined for the agent import API.
func LoadDocuments ¶
LoadDocuments expands -f arguments into agent documents, in order. Each argument is a file, a directory (its *.yaml / *.yml files, sorted by name, not recursive) or "-" for stdin. Multi-document files are split. A document whose kind is not Agent, or that is not valid YAML, is an error; nothing is returned in that case so a bad file never leads to a partial apply.
func ParseDocuments ¶
ParseDocuments splits data into its YAML documents and validates each one locally. Empty documents (blank, or comments only) are dropped.
type Identity ¶
type Identity struct {
Success bool `json:"success"`
UserID string `json:"user_id"`
Roles []string `json:"roles"`
Email string `json:"email,omitempty"`
Name string `json:"name,omitempty"`
AuthMethod string `json:"auth_method,omitempty"` // "pat" for a personal access token
Token *TokenInfo `json:"token,omitempty"`
Raw json.RawMessage `json:"-"` // server document, verbatim
}
Identity is the GET /api/user/me document. Token is set only when the caller authenticated with a personal access token.
type ModelDecision ¶
type ModelDecision struct {
APIKey string `json:"api_key,omitempty"`
}
ModelDecision is one entry of Resolution.Models: the API key used to create a custom model that does not exist yet.
type Plan ¶
type Plan struct {
Target PlanTarget `json:"target"`
Sources []PlanSource `json:"sources"`
Tools []PlanTool `json:"tools"`
Prompt PlanPrompt `json:"prompt"`
Models []PlanModel `json:"models"`
Workflow *PlanWorkflow `json:"workflow"`
Raw json.RawMessage `json:"-"` // the server `plan` object, verbatim
}
Plan is the dry-run resolution report for one agent document.
type PlanModel ¶
type PlanModel struct {
ID string `json:"id"`
DisplayName string `json:"display_name"`
Status string `json:"status"` // matched | unavailable | reuse | create
RequiresSecrets []string `json:"requires_secrets"`
}
PlanModel is one spec.model.available entry: a plain model id (ID set) or a custom model (DisplayName set).
type PlanPrompt ¶
type PlanPrompt struct {
Status string `json:"status"` // reuse | create | default
Name string `json:"name"`
}
PlanPrompt is the spec.prompt resolution.
type PlanSource ¶
type PlanSource struct {
Name string `json:"name"`
Type string `json:"type"`
Status string `json:"status"` // matched | missing
TargetID string `json:"target_id"`
}
PlanSource is one spec.sources entry.
type PlanTarget ¶
type PlanTarget struct {
Action string `json:"action"` // create | update
AgentID string `json:"agent_id"`
MatchedBy string `json:"matched_by"` // id | slug
Status string `json:"status"` // existing agent status (draft/published)
}
PlanTarget says whether the document creates an agent or updates one (matched by metadata.id, then metadata.slug).
type PlanTool ¶
type PlanTool struct {
Key string `json:"key"`
Type string `json:"type"`
Name string `json:"name"`
Builtin bool `json:"builtin"`
Status string `json:"status"` // builtin | reuse | create | unavailable
TargetID string `json:"target_id"`
RequiresSecrets []string `json:"requires_secrets"`
}
PlanTool is one spec.tools entry. Key ("tool-N", N = index in the file) is how the resolution map addresses it.
type PlanWorkflow ¶
type PlanWorkflow struct {
Action string `json:"action"` // create | update | delete
Nodes int `json:"nodes"`
Edges int `json:"edges"`
}
PlanWorkflow describes the workflow graph change of a workflow agent.
type Prompt ¶
Prompt is one GET /api/get_prompts entry. Type is "public" for the built-in prompts, "private" for the caller's own and "team" for shared ones.
type Resolution ¶
type Resolution struct {
Sources map[string]string `json:"sources,omitempty"` // spec source name -> existing source id
Tools map[string]ToolDecision `json:"tools,omitempty"` // "tool-N" -> decision
Models map[string]ModelDecision `json:"models,omitempty"` // custom model display_name -> api key
}
Resolution is the `resolution` object of POST /api/import_agent. Every section is optional.
func (*Resolution) Empty ¶
func (r *Resolution) Empty() bool
Empty reports whether no decision is present.
type ResolveEntry ¶
type ResolveEntry struct {
Raw string // the flag value with any secret redacted, for messages
Kind string // source | tool | model
Selector string
Secret string // tool secret field name ("" for a decision entry)
Value string
// contains filtered or unexported fields
}
ResolveEntry is one parsed --resolve flag.
type ResolveSet ¶
type ResolveSet struct {
// contains filtered or unexported fields
}
ResolveSet is the parsed --resolve flags for one command invocation.
func ParseResolve ¶
func ParseResolve(flags []string) (*ResolveSet, error)
ParseResolve parses --resolve flag values.
func (*ResolveSet) CheckDocumentCount ¶
func (s *ResolveSet) CheckDocumentCount(n int) error
CheckDocumentCount rejects positional tool keys when several documents are processed together: tool-0 would silently address a different tool in every document.
func (*ResolveSet) Decide ¶
func (s *ResolveSet) Decide(plan *Plan) (*Decision, error)
Decide matches the entries against plan. It builds the resolution to send and lists every `missing` / `unavailable` reference that no entry covers:
- a missing source is covered by source:<name>=<id> or =skip;
- an unavailable tool is covered by =skip, or (non-built-in only, since the server ignores decisions for built-ins) by =reuse:<tool-id>;
- an unavailable model id is covered by =skip.
An error means the entries are invalid for this plan (ambiguous selector).
func (*ResolveSet) Unused ¶
func (s *ResolveSet) Unused() []string
Unused lists the entries that matched nothing in any planned document.
type Source ¶
type Source struct {
ID string `json:"id"`
Name string `json:"name"`
Date any `json:"date"`
Tokens any `json:"tokens"`
Type string `json:"type"`
Retriever string `json:"retriever"`
Provider string `json:"provider"`
Ownership string `json:"ownership"`
}
Source is one GET /api/sources entry.
type TaskFailedError ¶
TaskFailedError is returned by WaitTask when the task ends in FAILURE or REVOKED.
func (*TaskFailedError) Error ¶
func (e *TaskFailedError) Error() string
type TaskStatus ¶
type TaskStatus struct {
Status string `json:"status"` // PENDING | STARTED | PROGRESS | RETRY | SUCCESS | FAILURE | REVOKED
Result json.RawMessage `json:"result"`
}
TaskStatus is the GET /api/task_status reply.
func (*TaskStatus) Progress ¶
func (t *TaskStatus) Progress() (int, bool)
Progress extracts a 0-100 completion figure from a PROGRESS result, when the worker reports one.
func (*TaskStatus) ResultText ¶
func (t *TaskStatus) ResultText() string
ResultText renders the task result for an error message.
type TokenInfo ¶
type TokenInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Scopes []string `json:"scopes"`
ResourceFilter map[string][]string `json:"resource_filter"` // family -> allowed ids; empty = unrestricted
}
TokenInfo describes the presented personal access token.
type Tool ¶
type Tool struct {
ID string `json:"id"`
Name string `json:"name"`
CustomName string `json:"customName"`
DisplayName string `json:"displayName"`
Status bool `json:"status"`
Builtin bool `json:"builtin"`
Default bool `json:"default"`
Ownership string `json:"ownership"`
}
Tool is the subset of a GET /api/get_tools entry the CLI renders. Name is the tool type (e.g. "brave"); CustomName is the user's label.
type ToolDecision ¶
type ToolDecision struct {
// Decision is "reuse" (link ToolID, which must be the caller's tool),
// "create" (create a new tool even if a (type, name) match exists),
// "skip" (leave the tool off the agent), or "" (server default: reuse a
// (type, name) match, otherwise create).
Decision string `json:"decision,omitempty"`
ToolID string `json:"tool_id,omitempty"`
// Secrets are merged into the tool config when the tool is created
// (config-requirement field name -> value).
Secrets map[string]string `json:"secrets,omitempty"`
}
ToolDecision is one entry of Resolution.Tools.
type UploadResult ¶
type UploadResult struct {
Success bool `json:"success"`
TaskID string `json:"task_id"`
SourceID string `json:"source_id,omitempty"`
}
UploadResult is the POST /api/upload reply.
type WaitOptions ¶
type WaitOptions struct {
Initial time.Duration // first delay; default 1s
Max time.Duration // backoff ceiling; default 10s
Factor float64 // backoff multiplier; default 1.5
// OnUpdate is called after every poll with the latest state. For a
// transient 503 (no idle worker answered the server's ping, typical while
// a solo worker is busy with this very task) status is "WAITING".
OnUpdate func(status string, task *TaskStatus)
}
WaitOptions tunes WaitTask. Zero values pick the defaults.