chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
package operations
import (
"sync"
docs "academy/docs"
)
var (
builtinOnce sync.Once
builtinCatalog *Catalog
builtinErr error
)
// Builtin returns the catalog compiled from the Swagger document embedded in
// the binary: every operation annotated with x-agent. It panics on an invalid
// declaration, which tests catch before release.
func Builtin() *Catalog {
builtinOnce.Do(func() {
var ops []Operation
ops, builtinErr = FromSpec([]byte(docs.SwaggerInfo.ReadDoc()))
if builtinErr == nil {
builtinCatalog, builtinErr = NewCatalog(ops...)
}
})
if builtinErr != nil {
panic(builtinErr)
}
return builtinCatalog
}
+787
View File
@@ -0,0 +1,787 @@
// Package operations is the catalog of Academy HTTP API operations an agent
// may run on behalf of the signed-in user.
//
// The catalog is the allow-list: nothing outside it is reachable. Entries are
// declared with x-agent annotations on the handlers and compiled from the
// Swagger document (see FromSpec). An operation names a registered route, its
// risk, the parameters the model may supply and the slice of the response the
// model gets back. Execution goes through the real router (see Dispatcher), so
// authentication, RBAC guards, KB sharing and audit behave exactly as they do
// for the web UI; the catalog only narrows what is reachable.
package operations
import (
"fmt"
"net/http"
"regexp"
"sort"
"strings"
"unicode"
"academy/internal/agent/policy"
"academy/internal/types"
)
// Risk classifies an operation by its effect on user data.
type Risk = policy.Risk
// A probe operation runs without approval within a per-run budget, and uses
// POST because the API does.
const (
RiskRead = policy.RiskRead
RiskProbe = policy.RiskProbe
RiskWrite = policy.RiskWrite
RiskDestructive = policy.RiskDestructive
)
// Location is where a parameter goes in the HTTP request.
type Location string
// Parameter locations.
const (
InPath Location = "path"
InQuery Location = "query"
InBody Location = "body"
)
// ParamType is the JSON type the model must supply.
type ParamType string
// Parameter types.
const (
TypeString ParamType = "string"
TypeInteger ParamType = "integer"
TypeNumber ParamType = "number"
TypeBoolean ParamType = "boolean"
TypeStringList ParamType = "string_list"
TypeIntegerList ParamType = "integer_list"
)
// Param is one model-facing parameter.
//
// Names are chosen for the model, not copied from the route: identifiers use
// the canonical keys (knowledge_base_id, knowledge_id, issue_id, ...) that the
// model-context handle policy recognizes, so handles the model saw elsewhere
// (b1, d3, i2) decode to real IDs before the request is built.
type Param struct {
Name string
In Location
// Key is the wire name: the route segment, query key or body field.
// Defaults to Name.
Key string
Type ParamType
Required bool
// AllowEmpty separates an agent-required field from an API nonempty constraint.
AllowEmpty bool
Description string
Enum []string
// Minimum and Maximum bound integers when Maximum > 0.
Minimum int
Maximum int
// MaxItems bounds lists; defaults to defaultMaxListItems.
MaxItems int
// MaxBytes overrides maxStringParamBytes for this string. Zero keeps the
// default. It cannot exceed maxAgentStringBytes.
MaxBytes int
}
func (p Param) wireKey() string {
if p.Key != "" {
return p.Key
}
return p.Name
}
// Field copies one value from the response into the model-visible result.
type Field struct {
// From is a dotted path inside the source object.
From string
// MapKey selects one literal key within From, including keys containing dots.
// Used for explicitly allow-listed keys of free-form maps.
MapKey string
// As is the output key; defaults to the last segment of From. Identifiers
// should be renamed to the canonical handle keys so the model-context
// policy turns them into handles.
As string
// MaxRunes overrides the projected string length for this field. Zero
// keeps maxProjectedStringRunes.
MaxRunes int
// Items projects each element of a list of objects. Element fields are
// relative to the element and cannot declare Items themselves.
Items []Field
}
func (f Field) outputKey() string {
if f.As != "" {
return f.As
}
if i := strings.LastIndexByte(f.From, '.'); i >= 0 {
return f.From[i+1:]
}
return f.From
}
// Result is the projection of a response body. Anything not listed is
// dropped, so new fields added to a handler never reach the model unless
// they are added here.
type Result struct {
// Root is a dotted path to the object or array to project, relative to
// the response body. Empty means the body itself.
Root string
// List projects each element of the array at Root with Fields.
List bool
// Fields are relative to the object at Root, or to each element.
Fields []Field
// Meta fields are relative to the response body (e.g. a total count).
Meta []Field
// MaxItems caps List results; defaults to defaultMaxResultItems.
MaxItems int
}
// Operation is one catalog entry.
type Operation struct {
// ID is the stable model-facing name, "<domain>.<verb>".
ID string
Summary string
Description string
Risk Risk
Method string
// Route is the full path as registered on the router, with :param and
// *param segments.
Route string
Params []Param
Result Result
// Target, for mutating operations, is a read operation that resolves
// what the call acts on. It runs first, through the same authorization,
// and its result labels the approval prompt. Its parameters must be a
// subset of this operation's.
Target *Target
// LabelParam, for a creation with nothing existing to act on, names the
// required string parameter (the new name) that labels the approval in
// place of a Target.
LabelParam string
// Role is the lowest workspace role the route's guards let through;
// empty takes the default for Risk. It only decides what a caller is
// offered: the router still authorizes every call, and a router test
// keeps the two in step.
Role types.TenantRole
// SystemAdmin requires the independent platform administrator permission.
SystemAdmin bool
// AlwaysConfirm makes a write ask every time, whatever the access level
// and session grants: installing a skill runs fetched code as root in
// the image every later session boots, so it is never pre-approved.
AlwaysConfirm bool
}
// defaultRole is the role the route guards usually ask of an operation:
// reading or probing needs a viewer, changing content a contributor.
func defaultRole(risk Risk) types.TenantRole {
if !risk.Mutates() {
return types.TenantRoleViewer
}
return types.TenantRoleContributor
}
// Access is what one run may do with the catalog.
type Access struct {
// Role is the caller's workspace role. It filters only when EnforceRole
// is set, matching the router, which skips role checks otherwise.
Role types.TenantRole
EnforceRole bool
SystemAdmin bool
// Level is the user's assistant access level.
Level types.AssistantAccessLevel
}
// NeedsApproval reports whether running op must wait for the user. An
// operation the level denies is withheld before it gets here.
func (a Access) NeedsApproval(op Operation) bool {
return policy.Decide(policy.Action{Risk: op.Risk, Always: op.AlwaysConfirm}, a.Rules()) != policy.Allow
}
// Rules are the execution rules this access gives a run.
func (a Access) Rules() policy.Rules {
return policy.Rules{Level: a.Level}
}
// Withholding says why an access leaves an operation out.
type Withholding struct {
// ReadOnly: the user set the assistant to read-only.
ReadOnly bool
SystemAdmin bool
// Role is the workspace role the operation needs when the caller's falls
// short.
Role types.TenantRole
}
// Withheld reports why a leaves op out of c, if it does. A mutation whose
// approval target is withheld is withheld for the same reason, so every
// offered mutation can still show the user what it acts on.
func (c *Catalog) Withheld(a Access, op Operation) (Withholding, bool) {
if !policy.Offered(a.Level, op.Risk) {
return Withholding{ReadOnly: true}, true
}
if op.SystemAdmin && !a.SystemAdmin {
return Withholding{SystemAdmin: true}, true
}
if !op.SystemAdmin && a.EnforceRole && !a.Role.HasPermission(op.Role) {
return Withholding{Role: op.Role}, true
}
if t := op.Target; t != nil {
targets := []string{t.Operation}
if t.Items != nil {
targets = append(targets, t.Items.Operation)
}
for _, id := range targets {
target, ok := c.Get(id)
if !ok {
return Withholding{}, true
}
if w, withheld := c.Withheld(a, target); withheld {
return w, true
}
}
}
return Withholding{}, false
}
// For returns the operations a allows; see Withheld.
func (c *Catalog) For(a Access) *Catalog {
if c == nil {
return nil
}
out := &Catalog{byID: map[string]int{}}
for _, op := range c.ops {
if _, withheld := c.Withheld(a, op); withheld {
continue
}
out.byID[op.ID] = len(out.ops)
out.ops = append(out.ops, op)
}
return out
}
// Target names the read operation that describes a mutation's subject.
type Target struct {
Operation string
// Label is the result field shown to the user (e.g. "title").
Label string
// Items, for a batch mutation, also resolves every item it acts on.
Items *ItemTarget
// RequireComplete blocks a full replacement when the target read loses data.
RequireComplete bool
}
// ItemTarget runs a read once per item of a list parameter, so the approval
// names each item rather than showing IDs.
type ItemTarget struct {
// Param is the mutation's list parameter; at most MaxApprovalItems long.
Param string
Operation string
// As is the target parameter that receives each item.
As string
Label string
}
// MaxApprovalItems bounds a batch whose items the approval resolves, so the
// user sees every item they approve.
const MaxApprovalItems = 20
// Param returns the parameter declared under name.
func (op Operation) Param(name string) (Param, bool) {
for _, p := range op.Params {
if p.Name == name {
return p, true
}
}
return Param{}, false
}
const (
defaultMaxListItems = 100
defaultMaxResultItems = 50
// maxDeclaredResultItems is the largest max_items an operation may
// declare. Unpaginated lists raise their cap explicitly; anything larger
// belongs behind a page parameter.
maxDeclaredResultItems = 500
)
var (
operationIDPattern = regexp.MustCompile(`^[a-z][a-z_]*\.[a-z][a-z_]*$`)
paramNamePattern = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
routeParamPattern = regexp.MustCompile(`^[:*][A-Za-z_][A-Za-z0-9_]*$`)
)
// allowedRouteAreas are the first path segments under /api/v1 an operation
// may live in: the user's knowledge content, their agents, the models and
// MCP services an agent can be bound to, and their own conversations. Every
// other area is refused,
// so an API added later (credentials, integrations, identity, the agent's
// own approval and prompt endpoints) stays unreachable until it is listed
// here on purpose. Catalog construction fails otherwise, so a careless
// annotation is caught by tests rather than review.
var allowedRouteAreas = map[string]bool{
"knowledge-bases": true,
"shared-knowledge-bases": true,
"knowledge": true,
"knowledgebase": true, // Wiki
"chunks": true,
"faq": true,
"agents": true,
"skills": true,
// The caller's own automations. Runs, grants and notifications live
// in other areas or behind routes left unannotated: the owner approves
// standing grants themselves.
"automations": true,
// Model and MCP responses carry endpoints and headers next to the
// names; only fields tagged x-agent are projected, so annotate the
// identifying ones and nothing else.
"models": true,
"mcp-services": true,
"web-search-providers": true,
// Saved data sources: status, connection tests, sync settings and control.
"datasource": true,
// Sandbox configs hold provider credentials; see sandboxSkillsRoute.
"sandbox-configs": true,
// The caller's own conversations, read-only; see readOnlyRouteAreas.
"sessions": true,
"messages": true,
}
// readOnlyRouteAreas admit only operations that change nothing. Deleting,
// stopping, rewinding or steering a conversation is the user's to do in the
// chat itself, and content the assistant reads (documents, past answers)
// must never be able to talk it into erasing history.
var readOnlyRouteAreas = map[string]bool{
"sessions": true,
"messages": true,
"system": true, // Only info and parser-engines are reachable; see parseRoute.
}
// forbiddenRouteSegments are refused anywhere inside an allowed area:
// sharing and publishing change who can reach a knowledge base or agent,
// credentials never pass through the model, and a skill install's installer
// conversation (its guidance, transcript and event stream) belongs to the
// user watching it; the user handles these themselves.
var forbiddenRouteSegments = map[string]bool{
"shares": true,
"embed-channels": true,
"im-channels": true,
"credentials": true,
"validate-credentials": true,
"oauth": true,
"guidance": true,
"transcript": true,
"install-events": true,
}
// sandboxSkillsRoute reports whether a route in the sandbox-configs area
// stays within one config's installed skills. The config itself, its
// sandboxes and the workspace policy are never reachable.
func sandboxSkillsRoute(rest string) bool {
segments := strings.Split(rest, "/")
return len(segments) >= 3 && segments[0] == "sandbox-configs" &&
strings.HasPrefix(segments[1], ":") && segments[2] == "skills"
}
var allowedMethods = map[string]bool{
http.MethodGet: true, http.MethodPost: true, http.MethodPut: true,
http.MethodPatch: true, http.MethodDelete: true,
}
// Catalog is an immutable, validated set of operations.
type Catalog struct {
ops []Operation
byID map[string]int
}
// NewCatalog validates ops and returns a catalog sorted by ID.
func NewCatalog(ops ...Operation) (*Catalog, error) {
c := &Catalog{ops: append([]Operation(nil), ops...), byID: make(map[string]int, len(ops))}
sort.Slice(c.ops, func(i, j int) bool { return c.ops[i].ID < c.ops[j].ID })
for i := range c.ops {
if c.ops[i].Role == "" {
c.ops[i].Role = defaultRole(c.ops[i].Risk)
}
}
for i, op := range c.ops {
if _, dup := c.byID[op.ID]; dup {
return nil, fmt.Errorf("operation %q declared twice", op.ID)
}
if err := validateOperation(op); err != nil {
return nil, fmt.Errorf("operation %q: %w", op.ID, err)
}
c.byID[op.ID] = i
}
for _, op := range c.ops {
if err := c.validateTarget(op); err != nil {
return nil, fmt.Errorf("operation %q: %w", op.ID, err)
}
}
return c, nil
}
// Get returns the operation with id.
func (c *Catalog) Get(id string) (Operation, bool) {
if c == nil {
return Operation{}, false
}
i, ok := c.byID[id]
if !ok {
return Operation{}, false
}
return c.ops[i], true
}
// All returns every operation, sorted by ID.
func (c *Catalog) All() []Operation {
if c == nil {
return nil
}
return append([]Operation(nil), c.ops...)
}
// Find returns operations matching every whitespace-separated term of query
// (case-insensitive, against ID, summary and description), optionally limited
// to one domain. An empty query matches everything.
func (c *Catalog) Find(query, domain string) []Operation {
if c == nil {
return nil
}
terms := strings.Fields(strings.ToLower(query))
domain = strings.ToLower(strings.TrimSpace(domain))
var out []Operation
for _, op := range c.ops {
if domain != "" && op.Domain() != domain {
continue
}
haystack := strings.ToLower(op.ID + " " + op.Summary + " " + op.Description)
matched := true
for _, term := range terms {
if !strings.Contains(haystack, term) {
matched = false
break
}
}
if matched {
out = append(out, op)
}
}
return out
}
// Domains lists the distinct operation domains.
func (c *Catalog) Domains() []string {
if c == nil {
return nil
}
seen := map[string]bool{}
var out []string
for _, op := range c.ops {
if d := op.Domain(); !seen[d] {
seen[d] = true
out = append(out, d)
}
}
return out
}
// Domain is the part of the ID before the dot.
func (op Operation) Domain() string {
domain, _, _ := strings.Cut(op.ID, ".")
return domain
}
func validateOperation(op Operation) error {
if !operationIDPattern.MatchString(op.ID) {
return fmt.Errorf("id must look like domain.verb")
}
if strings.TrimSpace(op.Summary) == "" {
return fmt.Errorf("summary is required")
}
if !op.Risk.Valid() {
return fmt.Errorf("invalid risk %q", op.Risk)
}
if !allowedMethods[op.Method] {
return fmt.Errorf("unsupported method %q", op.Method)
}
if op.Risk == RiskRead && op.Method != http.MethodGet {
return fmt.Errorf("read operations must use GET")
}
if op.Risk == RiskProbe && op.Method != http.MethodPost {
return fmt.Errorf("probe operations must use POST")
}
if op.Risk == RiskProbe && (op.Target != nil || op.LabelParam != "") {
return fmt.Errorf("probe operations change nothing, so they take no approval target")
}
if op.Risk != RiskRead && op.Method == http.MethodGet {
return fmt.Errorf("GET operations must be read-only")
}
if op.Method == http.MethodDelete && op.Risk != RiskDestructive {
return fmt.Errorf("DELETE operations must be destructive")
}
if op.Risk.Mutates() && op.Target == nil && op.LabelParam == "" {
return fmt.Errorf("mutating operations must declare a target")
}
if op.LabelParam != "" {
if op.Target != nil || op.Risk != RiskWrite || op.Method != http.MethodPost {
return fmt.Errorf("label_param is for a POST write without a target")
}
p, ok := op.Param(op.LabelParam)
if !ok || p.Type != TypeString || !p.Required {
return fmt.Errorf("label_param %q must be a required string param", op.LabelParam)
}
}
if op.AlwaysConfirm && op.Risk != RiskWrite {
return fmt.Errorf("always_confirm is for writes; destructive operations always ask")
}
if !op.Role.IsValid() {
return fmt.Errorf("invalid role %q", op.Role)
}
routeParams, area, err := parseRoute(op.Route)
if err != nil {
return err
}
if systemAdminReadRoute(strings.TrimPrefix(op.Route, "/api/v1/")) != op.SystemAdmin {
return fmt.Errorf("route %q requires matching system_admin declaration", op.Route)
}
if op.SystemAdmin && (op.Risk != RiskRead || op.Method != http.MethodGet) {
return fmt.Errorf("system administrator operations must be read-only GET requests")
}
if readOnlyRouteAreas[area] && op.Risk.Mutates() {
return fmt.Errorf("route %q is in an area an agent may only read", op.Route)
}
if area == "tenants" && op.Method != http.MethodGet &&
(op.Route != "/api/v1/tenants/current" || op.Method != http.MethodPatch || op.Risk != RiskWrite) {
return fmt.Errorf("route %q only permits current workspace reads and profile patches", op.Route)
}
seenNames := map[string]bool{}
seenWire := map[Location]map[string]bool{}
pathParams := map[string]bool{}
for _, p := range op.Params {
if !paramNamePattern.MatchString(p.Name) {
return fmt.Errorf("param %q: invalid name", p.Name)
}
if seenNames[p.Name] {
return fmt.Errorf("param %q declared twice", p.Name)
}
seenNames[p.Name] = true
if strings.TrimSpace(p.Description) == "" {
return fmt.Errorf("param %q: description is required", p.Name)
}
switch p.Type {
case TypeString, TypeInteger, TypeNumber, TypeBoolean, TypeStringList, TypeIntegerList:
default:
return fmt.Errorf("param %q: invalid type %q", p.Name, p.Type)
}
if len(p.Enum) > 0 && p.Type != TypeString && p.Type != TypeStringList {
return fmt.Errorf("param %q: enum requires a string type", p.Name)
}
if p.Maximum > 0 && (p.Type != TypeInteger || p.Minimum > p.Maximum) {
return fmt.Errorf("param %q: invalid integer bounds", p.Name)
}
if p.MaxBytes != 0 && (p.Type != TypeString && p.Type != TypeStringList ||
p.MaxBytes < 1 || p.MaxBytes > maxAgentStringBytes) {
return fmt.Errorf("param %q: invalid string length", p.Name)
}
switch p.In {
case InPath:
if (p.Type != TypeString && p.Type != TypeInteger) || !p.Required {
return fmt.Errorf("path param %q must be a required string or integer", p.Name)
}
if p.Type == TypeInteger && strings.HasSuffix(op.Route, "/*"+p.wireKey()) {
return fmt.Errorf("path param %q: a catch-all must be a string", p.Name)
}
if _, ok := routeParams[p.wireKey()]; !ok {
return fmt.Errorf("path param %q has no route segment %q", p.Name, p.wireKey())
}
pathParams[p.wireKey()] = true
case InQuery:
case InBody:
if op.Method == http.MethodGet {
return fmt.Errorf("param %q: %s requests carry no body", p.Name, op.Method)
}
default:
return fmt.Errorf("param %q: invalid location %q", p.Name, p.In)
}
if seenWire[p.In] == nil {
seenWire[p.In] = map[string]bool{}
}
if seenWire[p.In][p.wireKey()] {
return fmt.Errorf("param %q: %s key %q declared twice", p.Name, p.In, p.wireKey())
}
seenWire[p.In][p.wireKey()] = true
}
for name := range routeParams {
if !pathParams[name] {
return fmt.Errorf("route segment %q has no param", name)
}
}
if op.Result.MaxItems < 0 || op.Result.MaxItems > maxDeclaredResultItems {
return fmt.Errorf("max_items must be between 0 and %d", maxDeclaredResultItems)
}
if op.Result.List && op.Result.Root == "" && len(op.Result.Meta) > 0 {
return fmt.Errorf("a list result at the body root cannot have meta fields")
}
seenOut := map[string]bool{}
for _, f := range append(append([]Field(nil), op.Result.Fields...), op.Result.Meta...) {
if f.From == "" {
return fmt.Errorf("result field with empty path")
}
key := f.outputKey()
if seenOut[key] {
return fmt.Errorf("result key %q declared twice", key)
}
seenOut[key] = true
if err := validateItemFields(key, f.Items); err != nil {
return err
}
}
return nil
}
func validateItemFields(parent string, items []Field) error {
seen := map[string]bool{}
for _, f := range items {
if f.From == "" {
return fmt.Errorf("result field %q has an item with empty path", parent)
}
if len(f.Items) > 0 {
return fmt.Errorf("result field %q: items cannot hold lists of objects", parent)
}
key := f.outputKey()
if seen[key] {
return fmt.Errorf("result field %q: item key %q declared twice", parent, key)
}
seen[key] = true
}
return nil
}
func (c *Catalog) validateTarget(op Operation) error {
if op.Target == nil {
return nil
}
if err := c.validateRead(op, op.Target.Operation, op.Target.Label, "", ""); err != nil {
return err
}
items := op.Target.Items
if items == nil {
return nil
}
list, ok := op.Param(items.Param)
if !ok || !list.Required || (list.Type != TypeStringList && list.Type != TypeIntegerList) {
return fmt.Errorf("target items %q must be a required list", items.Param)
}
if list.MaxItems <= 0 || list.MaxItems > MaxApprovalItems {
return fmt.Errorf("target items %q must be capped at %d or fewer", items.Param, MaxApprovalItems)
}
return c.validateRead(op, items.Operation, items.Label, items.As, list.itemType())
}
// itemType is the type of one element of a list param.
func (p Param) itemType() ParamType {
if p.Type == TypeIntegerList {
return TypeInteger
}
return TypeString
}
// validateRead checks a target read of op: a single-object read whose
// parameters op supplies (item, if set, is filled per item instead, with
// itemType) and whose result has label.
func (c *Catalog) validateRead(op Operation, id, label, item string, itemType ParamType) error {
target, ok := c.Get(id)
if !ok {
return fmt.Errorf("target %q is not in the catalog", id)
}
if target.Risk != RiskRead {
return fmt.Errorf("target %q must be a read operation", target.ID)
}
if target.Result.List {
return fmt.Errorf("target %q must return a single object", target.ID)
}
if item != "" {
p, ok := target.Param(item)
if !ok || p.Type != itemType || !p.Required {
return fmt.Errorf("target %q has no required %s param %q for each item", target.ID, itemType, item)
}
if _, clash := op.Param(item); clash {
return fmt.Errorf("target item param %q is also a param of %q", item, op.ID)
}
}
for _, p := range target.Params {
if p.Name == item {
continue
}
own, ok := op.Param(p.Name)
if !ok || own.Type != p.Type {
return fmt.Errorf("target param %q is not declared with the same type", p.Name)
}
if p.Required && !own.Required {
return fmt.Errorf("target param %q is required by the target", p.Name)
}
}
for _, f := range target.Result.Fields {
if f.outputKey() == label {
return nil
}
}
return fmt.Errorf("target label %q is not a result field of %q", label, target.ID)
}
// systemAdminReadRoute is deliberately exact: no other platform routes are exposed.
func systemAdminReadRoute(rest string) bool {
switch rest {
case "system/admin/list", "system/admin/users", "system/admin/settings-summary",
"system/admin/runtime/queues", "system/admin/runtime/queues/:queue/tasks":
return true
default:
return false
}
}
// parseRoute checks that route is a clean absolute path in an allowed area
// under /api/v1, returning its parameter segment names and its area.
func parseRoute(route string) (map[string]bool, string, error) {
const base = "/api/v1/"
if !strings.HasPrefix(route, base) {
return nil, "", fmt.Errorf("route %q must be under /api/v1", route)
}
rest := strings.TrimPrefix(route, base)
area, _, _ := strings.Cut(rest, "/")
currentWorkspace := rest == "tenants/current" || rest == "tenants/current/members"
allowed := allowedRouteAreas[area] || rest == "system/parser-engines" || rest == "system/info" ||
currentWorkspace || systemAdminReadRoute(rest)
if !allowed || (area == "sandbox-configs" && !sandboxSkillsRoute(rest)) {
return nil, "", fmt.Errorf("route %q is outside the areas an agent may reach", route)
}
params := map[string]bool{}
segments := strings.Split(strings.TrimPrefix(route, "/"), "/")
for i, seg := range segments {
if seg == "" {
return nil, "", fmt.Errorf("route %q has an empty segment", route)
}
if forbiddenRouteSegments[seg] {
return nil, "", fmt.Errorf("route %q reaches %q, which an agent may not", route, seg)
}
if seg[0] == ':' || seg[0] == '*' {
if !routeParamPattern.MatchString(seg) {
return nil, "", fmt.Errorf("route %q has an invalid parameter %q", route, seg)
}
if seg[0] == '*' && i != len(segments)-1 {
return nil, "", fmt.Errorf("route %q: catch-all must be last", route)
}
params[seg[1:]] = true
continue
}
for _, r := range seg {
if !unicode.IsLower(r) && !unicode.IsDigit(r) && r != '-' && r != '_' {
return nil, "", fmt.Errorf("route %q has an invalid segment %q", route, seg)
}
}
}
return params, area, nil
}
+857
View File
@@ -0,0 +1,857 @@
package operations
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"testing"
"time"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestBuiltinCatalogIsValid(t *testing.T) {
catalog := Builtin()
require.NotEmpty(t, catalog.All())
for _, op := range catalog.All() {
if op.Risk.Mutates() && op.LabelParam == "" {
require.NotNil(t, op.Target, op.ID)
}
}
}
func readOp(id, route string, params ...Param) Operation {
return Operation{
ID: id, Summary: "s", Risk: RiskRead, Method: http.MethodGet, Route: route, Params: params,
Result: Result{Root: "data", Fields: []Field{{From: "title"}}},
}
}
func TestNewCatalogRejectsUnsafeDeclarations(t *testing.T) {
kb := Param{Name: "knowledge_base_id", In: InPath, Key: "id", Type: TypeString, Required: true, Description: "d"}
cases := map[string]Operation{
"forbidden area": readOp("auth.get", "/api/v1/auth/me"),
"api keys": readOp("keys.list", "/api/v1/api-keys"),
"outside v1": readOp("x.get", "/health"),
// Areas whose names extend a sensitive one, or that no list named.
"sandbox configs": readOp("x.get", "/api/v1/sandbox-configs"),
"storage backends": readOp("x.get", "/api/v1/storage-backends"),
"web search credentials": readOp("x.get", "/api/v1/web-search-providers/:id/credentials", kb),
"im channels": readOp("x.get", "/api/v1/im-channels"),
"agent approvals": readOp("x.get", "/api/v1/agent/tool-approvals"),
"memory": readOp("x.get", "/api/v1/memory/items"),
"a new area": readOp("x.get", "/api/v1/something-new"),
"kb shares": readOp("x.get", "/api/v1/knowledge-bases/:id/shares", kb),
"kb prefix lookalike": readOp("x.get", "/api/v1/knowledge-bases-admin"),
"agent shares": readOp("x.get", "/api/v1/agents/:id/shares", kb),
"agent embed channels": readOp("x.get", "/api/v1/agents/:id/embed-channels", kb),
"agent im channels": readOp("x.get", "/api/v1/agents/:id/im-channels", kb),
"model credentials": readOp("x.get", "/api/v1/models/:id/credentials", kb),
"data source credentials": readOp("x.get", "/api/v1/datasource/:id/credentials", kb),
"raw data source credentials": {
ID: "x.test", Summary: "s", Risk: RiskProbe, Method: http.MethodPost,
Route: "/api/v1/datasource/validate-credentials",
},
"mcp oauth": readOp("x.get", "/api/v1/mcp-services/:id/oauth/status", kb),
"read as POST": {
ID: "x.get", Summary: "s", Risk: RiskRead, Method: http.MethodPost,
Route: "/api/v1/knowledge-bases",
},
"write as GET": {
ID: "x.set", Summary: "s", Risk: RiskWrite, Method: http.MethodGet,
Route: "/api/v1/knowledge-bases", Target: &Target{Operation: "x.get", Label: "title"},
},
"delete not destructive": {
ID: "x.del", Summary: "s", Risk: RiskWrite, Method: http.MethodDelete,
Route: "/api/v1/knowledge-bases", Target: &Target{Operation: "x.get", Label: "title"},
},
"mutation without target": {
ID: "x.del", Summary: "s", Risk: RiskDestructive, Method: http.MethodDelete,
Route: "/api/v1/knowledge-bases",
},
"route segment without param": readOp("x.get", "/api/v1/knowledge-bases/:id"),
"param without route segment": readOp("x.get", "/api/v1/knowledge-bases", kb),
"probe as GET": {
ID: "x.check", Summary: "s", Risk: RiskProbe, Method: http.MethodGet,
Route: "/api/v1/knowledge-bases",
},
"probe as PUT": {
ID: "x.check", Summary: "s", Risk: RiskProbe, Method: http.MethodPut,
Route: "/api/v1/knowledge-bases",
},
"probe with an approval target": {
ID: "x.check", Summary: "s", Risk: RiskProbe, Method: http.MethodPost,
Route: "/api/v1/knowledge-bases", Target: &Target{Operation: "x.get", Label: "title"},
},
// Conversations are read-only: no deleting, stopping or rewinding.
"delete a session": {
ID: "session.delete", Summary: "s", Risk: RiskDestructive, Method: http.MethodDelete,
Route: "/api/v1/sessions/:id", Params: routeParams("/api/v1/sessions/:id"),
Target: &Target{Operation: "session.get", Label: "title"},
},
"stop a session": {
ID: "session.stop", Summary: "s", Risk: RiskWrite, Method: http.MethodPost,
Route: "/api/v1/sessions/:session_id/stop", Params: routeParams("/api/v1/sessions/:session_id/stop"),
Target: &Target{Operation: "session.get", Label: "title"},
},
"delete a message": {
ID: "message.delete", Summary: "s", Risk: RiskDestructive, Method: http.MethodDelete,
Route: "/api/v1/messages/:session_id/:id",
Params: routeParams("/api/v1/messages/:session_id/:id"),
Target: &Target{Operation: "session.get", Label: "title"},
},
}
reasons := map[string]string{
"delete a session": "may only read",
"stop a session": "may only read",
"delete a message": "may only read",
}
// A sandbox config is reachable only for its installed skills, and never
// the installer conversation a user is watching.
for _, route := range []struct{ method, path, reason string }{
{http.MethodGet, "/api/v1/sandbox-configs/:id", "outside the areas"},
{http.MethodPut, "/api/v1/sandbox-configs/:id", "outside the areas"},
{http.MethodGet, "/api/v1/sandbox-configs/:id/sandboxes", "outside the areas"},
{http.MethodPut, "/api/v1/sandbox-configs/workspace-policy", "outside the areas"},
{http.MethodPost, "/api/v1/sandbox-configs/templates/query", "outside the areas"},
{http.MethodGet, "/api/v1/sandbox-configs/:id/skills/:skillId/guidance", `reaches "guidance"`},
{http.MethodPost, "/api/v1/sandbox-configs/:id/skills/:skillId/guidance", `reaches "guidance"`},
{http.MethodGet, "/api/v1/sandbox-configs/:id/skills/:skillId/install-events", `reaches "install-events"`},
{http.MethodGet, "/api/v1/sandbox-configs/:id/skills/:skillId/transcript", `reaches "transcript"`},
} {
op := readOp("skill.admin", route.path, routeParams(route.path)...)
op.Method = route.method
if route.method != http.MethodGet {
op.Risk = RiskWrite
op.Target = &Target{Operation: "skill.get", Label: "name"}
}
cases[route.method+" "+route.path] = op
reasons[route.method+" "+route.path] = route.reason
}
for name, op := range cases {
t.Run(name, func(t *testing.T) {
_, err := NewCatalog(op)
require.Error(t, err)
if reason := reasons[name]; reason != "" {
assert.Contains(t, err.Error(), reason)
}
})
}
}
// routeParams declares a string path param for every :name segment.
func routeParams(route string) []Param {
var params []Param
for _, seg := range strings.Split(route, "/") {
if strings.HasPrefix(seg, ":") {
params = append(params, Param{
Name: strings.ToLower(seg[1:]), In: InPath, Key: seg[1:], Type: TypeString,
Required: true, Description: "d",
})
}
}
return params
}
func TestNewCatalogAdmitsInstalledSkillRoutes(t *testing.T) {
routes := []struct{ method, path string }{
{http.MethodGet, "/api/v1/sandbox-configs/:id/skills"},
{http.MethodGet, "/api/v1/sandbox-configs/:id/skills/:skillId"},
{http.MethodPatch, "/api/v1/sandbox-configs/:id/skills/:skillId"},
{http.MethodGet, "/api/v1/skills/catalog/:id"},
}
for _, route := range routes {
t.Run(route.method+" "+route.path, func(t *testing.T) {
op := readOp("skill.x", route.path, routeParams(route.path)...)
op.Method = route.method
if route.method != http.MethodGet {
op.Risk = RiskWrite
op.Target = &Target{Operation: "skill.get", Label: "title"}
}
get := readOp("skill.get", "/api/v1/sandbox-configs/:id/skills/:skillId",
routeParams("/api/v1/sandbox-configs/:id/skills/:skillId")...)
if op.ID == get.ID {
op.ID = "skill.other"
}
_, err := NewCatalog(op, get)
assert.NoError(t, err)
})
}
}
func TestAlwaysConfirmAsksAtEveryLevel(t *testing.T) {
install := Operation{ID: "skill.install", Risk: RiskWrite, AlwaysConfirm: true}
update := Operation{ID: "agent.update", Risk: RiskWrite}
auto := Access{Level: types.AssistantAccessAutoWrite}
assert.True(t, auto.NeedsApproval(install))
assert.False(t, auto.NeedsApproval(update))
op := Operation{
ID: "skill.uninstall", Summary: "s", Risk: RiskDestructive, Method: http.MethodPost,
Route: "/api/v1/knowledge-bases", LabelParam: "", AlwaysConfirm: true,
Target: &Target{Operation: "x.get", Label: "title"},
}
_, err := NewCatalog(op, readOp("x.get", "/api/v1/knowledge-bases"))
assert.ErrorContains(t, err, "always_confirm is for writes")
}
func TestNewCatalogChecksTargets(t *testing.T) {
doc := Param{Name: "knowledge_id", In: InPath, Key: "id", Type: TypeString, Required: true, Description: "d"}
get := readOp("knowledge.get", "/api/v1/knowledge/:id", doc)
del := Operation{
ID: "knowledge.delete", Summary: "s", Risk: RiskDestructive, Method: http.MethodDelete,
Route: "/api/v1/knowledge/:id", Params: []Param{doc},
Target: &Target{Operation: "knowledge.get", Label: "title"},
}
_, err := NewCatalog(get, del)
require.NoError(t, err)
missingLabel := del
missingLabel.Target = &Target{Operation: "knowledge.get", Label: "name"}
_, err = NewCatalog(get, missingLabel)
assert.Error(t, err)
noParam := del
noParam.Route = "/api/v1/knowledge"
noParam.Params = nil
_, err = NewCatalog(get, noParam)
assert.Error(t, err, "target needs a param the mutation does not declare")
}
func TestNewCatalogChecksLabelParam(t *testing.T) {
name := Param{Name: "name", In: InBody, Type: TypeString, Required: true, Description: "d"}
create := Operation{
ID: "agent.create", Summary: "s", Risk: RiskWrite, Method: http.MethodPost,
Route: "/api/v1/agents", Params: []Param{name}, LabelParam: "name",
}
_, err := NewCatalog(create)
require.NoError(t, err)
cases := map[string]func(*Operation){
"unknown param": func(op *Operation) { op.LabelParam = "title" },
"optional param": func(op *Operation) {
op.Params = []Param{{Name: "name", In: InBody, Type: TypeString, Description: "d"}}
},
"destructive": func(op *Operation) { op.Risk = RiskDestructive },
"not a POST": func(op *Operation) { op.Method = http.MethodPut },
"with a target": func(op *Operation) { op.Target = &Target{Operation: "x.get", Label: "title"} },
"read with label": func(op *Operation) { op.Risk, op.Method = RiskRead, http.MethodGet },
}
for name, mut := range cases {
t.Run(name, func(t *testing.T) {
op := create
op.Params = append([]Param(nil), create.Params...)
mut(&op)
_, err := NewCatalog(op, readOp("x.get", "/api/v1/agents"))
assert.Error(t, err)
})
}
}
func TestNewCatalogChecksItemTargets(t *testing.T) {
kb := Param{Name: "knowledge_base_id", In: InPath, Key: "id", Type: TypeString, Required: true, Description: "d"}
doc := Param{Name: "knowledge_id", In: InPath, Key: "id", Type: TypeString, Required: true, Description: "d"}
ids := Param{
Name: "knowledge_ids", In: InBody, Key: "ids", Type: TypeStringList, Required: true,
Description: "d", MaxItems: MaxApprovalItems,
}
getKB := readOp("knowledge_base.get", "/api/v1/knowledge-bases/:id", kb)
getDoc := readOp("knowledge.get", "/api/v1/knowledge/:id", doc)
batch := func(mut func(*Operation)) Operation {
kbBody := kb
kbBody.In, kbBody.Key = InBody, "kb_id"
op := Operation{
ID: "knowledge.batch_delete", Summary: "s", Risk: RiskDestructive, Method: http.MethodPost,
Route: "/api/v1/knowledge/batch-delete", Params: []Param{kbBody, ids},
Target: &Target{Operation: "knowledge_base.get", Label: "title", Items: &ItemTarget{
Param: "knowledge_ids", Operation: "knowledge.get", As: "knowledge_id", Label: "title",
}},
}
if mut != nil {
mut(&op)
}
return op
}
_, err := NewCatalog(getKB, getDoc, batch(nil))
require.NoError(t, err)
cases := map[string]func(*Operation){
"uncapped list": func(op *Operation) { op.Params[1].MaxItems = 0 },
"list longer than an approval shows": func(op *Operation) {
op.Params[1].MaxItems = MaxApprovalItems + 1
},
"items param is not a list": func(op *Operation) { op.Target.Items.Param = "knowledge_base_id" },
"item param the target lacks": func(op *Operation) { op.Target.Items.As = "chunk_id" },
"item param shadows a param": func(op *Operation) {
op.Params = append(op.Params, Param{Name: "knowledge_id", In: InBody, Type: TypeString, Description: "d"})
},
"item label not projected": func(op *Operation) { op.Target.Items.Label = "name" },
"item target is a mutation": func(op *Operation) { op.Target.Items.Operation = "knowledge.batch_delete" },
}
for name, mut := range cases {
t.Run(name, func(t *testing.T) {
_, err := NewCatalog(getKB, getDoc, batch(mut))
assert.Error(t, err)
})
}
}
func raw(v any) json.RawMessage {
b, _ := json.Marshal(v)
return b
}
func TestBuildValidatesAndEscapes(t *testing.T) {
op, ok := Builtin().Get("knowledge.list")
require.True(t, ok)
call, err := op.Build(map[string]json.RawMessage{
"knowledge_base_id": raw("kb-1"),
"parse_status": raw("failed"),
"page_size": raw(20),
})
require.NoError(t, err)
assert.Equal(t, http.MethodGet, call.Method)
assert.Equal(t, "/api/v1/knowledge-bases/kb-1/knowledge?page_size=20&parse_status=failed", call.URI())
assert.Nil(t, call.Body)
_, err = op.Build(map[string]json.RawMessage{"knowledge_base_id": raw("kb-1"), "tenant_id": raw(2)})
assert.ErrorContains(t, err, "unknown parameter")
_, err = op.Build(map[string]json.RawMessage{})
assert.ErrorContains(t, err, "is required")
_, err = op.Build(map[string]json.RawMessage{"knowledge_base_id": raw("kb-1"), "parse_status": raw("archived")})
assert.ErrorContains(t, err, "must be one of")
_, err = op.Build(map[string]json.RawMessage{"knowledge_base_id": raw("kb-1"), "page_size": raw(500)})
assert.ErrorContains(t, err, "between")
_, err = op.Build(map[string]json.RawMessage{"knowledge_base_id": raw("kb-1"), "page": raw("1")})
assert.ErrorContains(t, err, "integer")
for _, bad := range []string{"..", "a/b", "a?x=1", "a#b", "a\\b"} {
_, err = op.Build(map[string]json.RawMessage{"knowledge_base_id": raw(bad)})
assert.Error(t, err, bad)
}
call, err = op.Build(map[string]json.RawMessage{"knowledge_base_id": raw("kb 1%")})
require.NoError(t, err)
assert.Equal(t, "/api/v1/knowledge-bases/kb%201%25/knowledge", call.Path)
}
func TestBuildIntegerPathAndList(t *testing.T) {
kb := Param{Name: "knowledge_base_id", In: InPath, Key: "id", Type: TypeString, Required: true, Description: "d"}
entry := Param{Name: "entry_id", In: InPath, Type: TypeInteger, Required: true, Description: "d"}
get := readOp("faq.get_entry", "/api/v1/knowledge-bases/:id/faq/entries/:entry_id", kb, entry)
del := Operation{
ID: "faq.delete_entries", Summary: "s", Risk: RiskDestructive, Method: http.MethodDelete,
Route: "/api/v1/knowledge-bases/:id/faq/entries",
Params: []Param{kb, {
Name: "entry_ids", In: InBody, Key: "ids", Type: TypeIntegerList, Required: true,
Description: "d", MaxItems: 2,
}},
Target: &Target{Operation: "knowledge_base.get", Label: "title", Items: &ItemTarget{
Param: "entry_ids", Operation: "faq.get_entry", As: "entry_id", Label: "title",
}},
}
getKB := readOp("knowledge_base.get", "/api/v1/knowledge-bases/:id", kb)
_, err := NewCatalog(getKB, get, del)
require.NoError(t, err, "a DELETE may carry a body, and integer items resolve an integer param")
call, err := get.Build(map[string]json.RawMessage{"knowledge_base_id": raw("kb"), "entry_id": raw(42)})
require.NoError(t, err)
assert.Equal(t, "/api/v1/knowledge-bases/kb/faq/entries/42", call.Path)
_, err = get.Build(map[string]json.RawMessage{"knowledge_base_id": raw("kb"), "entry_id": raw("42/../x")})
assert.Error(t, err, "an integer path param takes integers only")
call, err = del.Build(map[string]json.RawMessage{"knowledge_base_id": raw("kb"), "entry_ids": raw([]int{1, 2})})
require.NoError(t, err)
assert.JSONEq(t, `{"ids":[1,2]}`, string(call.Body))
for _, bad := range []any{[]int{1, 2, 3}, []string{"1"}, []float64{1.5}, []int{}} {
_, err = del.Build(map[string]json.RawMessage{"knowledge_base_id": raw("kb"), "entry_ids": raw(bad)})
assert.Error(t, err, bad)
}
stringItem := del
stringItem.Target = &Target{Operation: "knowledge_base.get", Label: "title", Items: &ItemTarget{
Param: "entry_ids", Operation: "knowledge.get", As: "knowledge_id", Label: "title",
}}
doc := Param{Name: "knowledge_id", In: InPath, Key: "id", Type: TypeString, Required: true, Description: "d"}
_, err = NewCatalog(getKB, get, readOp("knowledge.get", "/api/v1/knowledge/:id", doc), stringItem)
assert.Error(t, err, "integer items cannot fill a string param")
}
func TestBuildCatchAllPath(t *testing.T) {
slug := Param{Name: "slug", In: InPath, Type: TypeString, Required: true, Description: "d"}
op := readOp(
"wiki.get_page",
"/api/v1/knowledgebase/:kb_id/wiki/pages/*slug",
Param{
Name: "knowledge_base_id",
In: InPath,
Key: "kb_id",
Type: TypeString,
Required: true,
Description: "d",
},
slug,
)
_, err := NewCatalog(op)
require.NoError(t, err)
call, err := op.Build(map[string]json.RawMessage{"knowledge_base_id": raw("kb"), "slug": raw("concept/a b")})
require.NoError(t, err)
assert.Equal(t, "/api/v1/knowledgebase/kb/wiki/pages/concept/a%20b", call.Path)
for _, bad := range []string{"concept/../x", "/abs", "a//b", "."} {
_, err = op.Build(map[string]json.RawMessage{"knowledge_base_id": raw("kb"), "slug": raw(bad)})
assert.Error(t, err, bad)
}
}
func TestProjectKeepsOnlyDeclaredFields(t *testing.T) {
op, _ := Builtin().Get("knowledge.list")
body := `{"success":true,"total":3,"page":1,"page_size":2,"data":[
{"id":"k1","title":"A","parse_status":"failed","error_message":"bad pdf",
"file_path":"s3://secret","tenant_id":9,"metadata":{"x":1},
"tags":[{"id":"t1","seq_id":7,"name":"Ops","color":"#f00","tenant_id":9}]},
{"id":"k2","title":"B","parse_status":"completed","tags":null}]}`
projected, err := op.Project([]byte(body))
require.NoError(t, err)
out, _ := json.Marshal(projected)
assert.JSONEq(t, `{"data":[
{"knowledge_id":"k1","title":"A","parse_status":"failed","error_message":"bad pdf",
"tags":[{"tag_id":"t1","tag_seq_id":7,"name":"Ops"}]},
{"knowledge_id":"k2","title":"B","parse_status":"completed","tags":[]}],
"meta":{"total":3,"page":1,"page_size":2}}`, string(out))
}
func TestProjectModelEndpointAndCatalog(t *testing.T) {
get, ok := Builtin().Get("model.get")
require.True(t, ok)
model := []byte(`{"data":{"id":"m1","name":"hy4","type":"KnowledgeQA",
"parameters":{"base_url":"http://127.0.0.1:3425/v1","provider":"magpie",
"custom_headers":{"Authorization":"x"},"extra_config":{"k":"v","remote_model_name":"hy4-preview"},
"spec":{"compat":{"extra_body":{"token":"x"}}}},
"capabilities":{"provider":"magpie","api":"openai-responses","context_window":960000,
"max_output_tokens":64000,"input":["text","image"],"thinking_format":"x"}}}`)
projected, err := get.Project(model)
require.NoError(t, err)
data := projected.Data.(map[string]any)
assert.Equal(t, "http://127.0.0.1:3425/v1", data["base_url"])
assert.Equal(t, "magpie", data["provider"])
assert.Equal(t, "hy4-preview", data["remote_model_name"])
assert.Equal(t, "openai-responses", data["api"])
assert.Equal(t, json.Number("960000"), data["context_window"])
assert.Equal(t, []any{"text", "image"}, data["input"])
for _, hidden := range []string{"custom_headers", "extra_config", "k", "spec", "compat", "thinking_format"} {
assert.NotContains(t, data, hidden)
}
models, ok := Builtin().Get("model.list")
require.True(t, ok)
modelObject := strings.TrimSuffix(strings.TrimPrefix(string(model), `{"data":`), `}`)
projected, err = models.Project([]byte(`{"data":[` + modelObject + `]}`))
require.NoError(t, err)
row := projected.Data.([]any)[0].(map[string]any)
assert.Equal(t, "magpie", row["provider"])
assert.NotContains(t, row, "context_window", "the list leaves capabilities to model.get")
assert.NotContains(t, row, "remote_model_name")
list, ok := Builtin().Get("model.list_providers")
require.True(t, ok)
body := `{"data":[{"value":"magpie","label":"Magpie","description":"d","icon":"data:x",
"modelTypes":["chat"],"models":[{"id":"a","name":"A"}]}]}`
projected, err = list.Project([]byte(body))
require.NoError(t, err)
out, _ := json.Marshal(projected.Data)
assert.JSONEq(t, `[{"provider":"magpie","label":"Magpie","model_types":["chat"]}]`, string(out),
"the list leaves models and descriptions to model.get_provider")
one, ok := Builtin().Get("model.get_provider")
require.True(t, ok)
projected, err = one.Project([]byte(`{"data":{"value":"magpie","label":"Magpie","models":[
{"id":"codex/gpt","name":"GPT","type":"chat","reasoning":true,"context_window":272000,"cost":{"input":1}}]}}`))
require.NoError(t, err)
entries := projected.Data.(map[string]any)["models"].([]any)
assert.Equal(t, map[string]any{
"model_name": "codex/gpt", "display_name": "GPT", "type": "chat", "reasoning": true,
"context_window": json.Number("272000"),
}, entries[0])
}
func TestProjectKnowledgeGetReportsTags(t *testing.T) {
op, ok := Builtin().Get("knowledge.get")
require.True(t, ok)
tags := make([]map[string]any, defaultMaxListItems+1)
for i := range tags {
tags[i] = map[string]any{"id": fmt.Sprintf("t%d", i), "name": "n", "color": "#000"}
}
body, _ := json.Marshal(map[string]any{"data": map[string]any{"id": "k1", "tags": tags}})
projected, err := op.Project(body)
require.NoError(t, err)
assert.True(t, projected.Truncated)
got := projected.Data.(map[string]any)["tags"].([]any)
require.Len(t, got, defaultMaxListItems)
assert.Equal(t, map[string]any{"tag_id": "t0", "name": "n"}, got[0])
}
func TestProjectTruncatesLists(t *testing.T) {
op, _ := Builtin().Get("wiki.list_issues")
items := make([]map[string]any, defaultMaxResultItems+5)
for i := range items {
items[i] = map[string]any{"id": "x", "description": strings.Repeat("长", maxProjectedStringRunes+10)}
}
body, _ := json.Marshal(items)
projected, err := op.Project(body)
require.NoError(t, err)
assert.True(t, projected.Truncated)
list := projected.Data.([]any)
assert.Len(t, list, defaultMaxResultItems)
desc := list[0].(map[string]any)["description"].(string)
assert.Equal(t, maxProjectedStringRunes+1, len([]rune(desc)))
}
type ctxKey struct{}
func TestDispatchDetachesContextAndCarriesIdentity(t *testing.T) {
var got *http.Request
var gotBody string
d := NewHandlerDispatcher()
_, err := d.Dispatch(
context.Background(),
Identity{UserID: "u", TenantID: 1},
Call{Method: http.MethodGet, Path: "/x"},
)
assert.ErrorIs(t, err, ErrDispatcherUnavailable)
d.Bind(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r
b, _ := io.ReadAll(r.Body)
gotBody = string(b)
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte(`{"ok":true}`))
}))
parent, cancel := context.WithTimeout(context.WithValue(context.Background(), ctxKey{}, "leak"), time.Minute)
defer cancel()
parent = context.WithValue(parent, types.TenantIDContextKey, uint64(99))
resp, err := d.Dispatch(parent, Identity{
UserID: "u1", TenantID: 7, Language: "zh-CN",
Agent: types.AuditAgentAction{SessionID: "s1", Operation: "knowledge.delete"},
}, Call{Method: http.MethodPost, Path: "/api/v1/x", Body: []byte(`{"a":1}`)})
require.NoError(t, err)
assert.Equal(t, http.StatusAccepted, resp.Status)
assert.JSONEq(t, `{"ok":true}`, string(resp.Body))
ctx := got.Context()
assert.Nil(t, ctx.Value(ctxKey{}), "agent run values must not reach the handler")
assert.Nil(t, ctx.Value(types.TenantIDContextKey))
_, hasDeadline := ctx.Deadline()
assert.True(t, hasDeadline, "cancellation still propagates")
dispatch, ok := types.InternalDispatchFromContext(ctx)
require.True(t, ok)
assert.Equal(t, types.InternalDispatch{UserID: "u1", TenantID: 7}, dispatch)
agent, ok := types.AuditAgentActionFromContext(ctx)
require.True(t, ok)
assert.Equal(t, "knowledge.delete", agent.Operation)
assert.Empty(t, got.Header.Get("Authorization"))
assert.Equal(t, "zh-CN", got.Header.Get("Accept-Language"))
assert.Equal(t, "application/json", got.Header.Get("Content-Type"))
assert.Equal(t, `{"a":1}`, gotBody)
_, err = d.Dispatch(parent, Identity{UserID: "", TenantID: 7}, Call{Method: http.MethodGet, Path: "/x"})
assert.Error(t, err, "an incomplete identity is never dispatched")
}
func TestDispatchRejectsOversizedResponses(t *testing.T) {
d := NewHandlerDispatcher()
d.Bind(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write(make([]byte, maxResponseBytes+1))
}))
_, err := d.Dispatch(
context.Background(),
Identity{UserID: "u", TenantID: 1},
Call{Method: http.MethodGet, Path: "/x"},
)
assert.ErrorIs(t, err, ErrResponseTooLarge)
}
func TestCatalogForFiltersByRoleAndLevel(t *testing.T) {
id := Param{Name: "knowledge_id", In: InPath, Key: "id", Type: TypeString, Required: true, Description: "d"}
get := readOp("knowledge.get", "/api/v1/knowledge/:id", id)
audit := readOp("knowledge.audit", "/api/v1/knowledge/:id/audit", id)
audit.Role = types.TenantRoleAdmin
write := func(opID, route string, target string) Operation {
return Operation{
ID: opID, Summary: "s", Risk: RiskWrite, Method: http.MethodPost, Route: route, Params: []Param{id},
Target: &Target{Operation: target, Label: "title"},
Result: Result{Root: "data", Fields: []Field{{From: "title"}}},
}
}
catalog, err := NewCatalog(
get, audit,
write("knowledge.reparse", "/api/v1/knowledge/:id/reparse", "knowledge.get"),
write("knowledge.seal", "/api/v1/knowledge/:id/seal", "knowledge.audit"),
)
require.NoError(t, err)
ids := func(c *Catalog) []string {
var out []string
for _, op := range c.All() {
out = append(out, op.ID)
}
return out
}
assert.Equal(t, []string{"knowledge.get"},
ids(catalog.For(Access{Role: types.TenantRoleViewer, EnforceRole: true})))
assert.Equal(t, []string{"knowledge.get", "knowledge.reparse"},
ids(catalog.For(Access{Role: types.TenantRoleContributor, EnforceRole: true})),
"a mutation is dropped with the target it could not show")
assert.Equal(t, ids(catalog),
ids(catalog.For(Access{Role: types.TenantRoleViewer})), "roles filter only when RBAC is enforced")
assert.Equal(t, []string{"knowledge.audit", "knowledge.get"},
ids(catalog.For(Access{Role: types.TenantRoleOwner, EnforceRole: true, Level: types.AssistantAccessReadOnly})))
}
func TestProbeRunsWithoutApprovalAtEveryLevel(t *testing.T) {
kb := Param{Name: "knowledge_base_id", In: InPath, Key: "id", Type: TypeString, Required: true, Description: "d"}
probe := Operation{
ID: "knowledge_base.search", Summary: "s", Risk: RiskProbe, Method: http.MethodPost,
Route: "/api/v1/knowledge-bases/:id/hybrid-search", Params: []Param{kb},
Result: Result{Root: "data", List: true, Fields: []Field{{From: "content"}}},
}
catalog, err := NewCatalog(probe)
require.NoError(t, err)
op, _ := catalog.Get(probe.ID)
assert.Equal(t, types.TenantRoleViewer, op.Role, "a probe needs only a viewer by default")
assert.False(t, op.Risk.Mutates())
for _, level := range []types.AssistantAccessLevel{
types.AssistantAccessReadOnly, types.AssistantAccessConfirm, types.AssistantAccessAutoWrite,
} {
access := Access{Level: level, Role: types.TenantRoleViewer, EnforceRole: true}
_, withheld := catalog.Withheld(access, op)
assert.False(t, withheld, level)
assert.False(t, access.NeedsApproval(op), level)
}
}
func TestBuiltinProbeOperations(t *testing.T) {
catalog := Builtin()
project := func(op Operation, body string) string {
t.Helper()
projected, err := op.Project([]byte(body))
require.NoError(t, err)
out, err := json.Marshal(projected)
require.NoError(t, err)
return string(out)
}
search, ok := catalog.Get("knowledge_base.search")
require.True(t, ok)
assert.Equal(t, RiskProbe, search.Risk)
assert.Equal(t, http.MethodPost, search.Method, "the legacy GET route is not compiled")
assert.Equal(t, types.TenantRoleViewer, search.Role)
var names []string
for _, p := range search.Params {
names = append(names, p.Name)
}
assert.ElementsMatch(t, []string{
"knowledge_base_id", "query_text", "vector_threshold", "keyword_threshold", "match_count",
"disable_keywords_match", "disable_vector_match", "knowledge_ids",
}, names)
query, _ := search.Param("query_text")
assert.True(t, query.Required)
threshold, _ := search.Param("vector_threshold")
assert.Equal(t, TypeNumber, threshold.Type)
count, _ := search.Param("match_count")
assert.Equal(t, 30, count.Maximum)
assert.JSONEq(t, `{"data":[{"chunk_id":"c1","content":"hello","knowledge_id":"k1","chunk_index":2,
"knowledge_title":"Q3","score":0.8,"match_type":1,"chunk_type":"text"}]}`,
project(search, `{"success":true,"data":[{"id":"c1","content":"hello","knowledge_id":"k1",
"chunk_index":2,"knowledge_title":"Q3","score":0.8,"match_type":1,"chunk_type":"text",
"metadata":{"k":"v"},"image_info":"local://secret","knowledge_filename":"q3.pdf"}]}`))
test, ok := catalog.Get("mcp_service.test")
require.True(t, ok)
assert.Equal(t, RiskProbe, test.Risk)
assert.Equal(t, types.TenantRoleAdmin, test.Role)
assert.JSONEq(t, `{"data":{"success":false,"message":"Connection failed: 401","oauth_required":true}}`,
project(test, `{"success":true,"data":{"success":false,"message":"Connection failed: 401",
"oauth_required":true,"description":"server","tools":[{"name":"t"}]}}`))
tools, ok := catalog.Get("mcp_service.list_tools")
require.True(t, ok)
assert.Equal(t, RiskRead, tools.Risk)
assert.JSONEq(t, `{"data":[{"name":"maps_weather","description":"Weather by city","require_approval":true}]}`,
project(tools, `{"success":true,"data":[{"name":"maps_weather","description":"Weather by city",
"inputSchema":{"type":"object"},"require_approval":true}]}`))
}
func TestBuildNumberParams(t *testing.T) {
threshold := Param{Name: "vector_threshold", In: InBody, Type: TypeNumber, Description: "d"}
op := Operation{
ID: "x.check", Summary: "s", Risk: RiskProbe, Method: http.MethodPost,
Route: "/api/v1/knowledge-bases", Params: []Param{threshold},
Result: Result{Fields: []Field{{From: "title"}}},
}
_, err := NewCatalog(op)
require.NoError(t, err)
call, err := op.Build(map[string]json.RawMessage{"vector_threshold": json.RawMessage(`0.35`)})
require.NoError(t, err)
assert.JSONEq(t, `{"vector_threshold":0.35}`, string(call.Body))
for _, bad := range []string{`"0.35"`, `true`, `[1]`} {
_, err := op.Build(map[string]json.RawMessage{"vector_threshold": json.RawMessage(bad)})
assert.Error(t, err, bad)
}
}
func TestBuiltinSkillList(t *testing.T) {
op, ok := Builtin().Get("skill.list")
require.True(t, ok)
assert.Equal(t, types.TenantRoleViewer, op.Role)
require.Len(t, op.Params, 1)
param, ok := op.Param("sandbox_config_id")
require.True(t, ok)
assert.Equal(t, InQuery, param.In)
assert.True(t, param.Required)
assert.True(t, param.AllowEmpty)
_, err := op.Build(nil)
require.Error(t, err)
for _, id := range []string{`"cfg-1"`, `"host"`, `""`} {
_, err = op.Build(map[string]json.RawMessage{"sandbox_config_id": json.RawMessage(id)})
require.NoError(t, err)
}
for _, hidden := range []string{"agent_id", "agent_source_tenant_id"} {
_, err = op.Build(map[string]json.RawMessage{
"sandbox_config_id": json.RawMessage(`"cfg-1"`),
hidden: json.RawMessage(`"secret"`),
})
require.Error(t, err)
}
assert.Equal(t, []Field{{From: "description", As: "description"}, {From: "name", As: "name"}}, op.Result.Fields)
assert.Equal(t, []Field{{From: "skills_available", As: "skills_available"}}, op.Result.Meta)
for _, tc := range []struct{ body, want string }{
{
`{"success":true,"data":[{"id":"row-1","name":"ppt-generator","description":"Make slides",
"env_values":{"TOKEN":"secret"},"source":"https://private","headers":{"Authorization":"secret"}}],
"skills_available":true,"tenant_id":1}`,
`{"data":[{"name":"ppt-generator","description":"Make slides"}],"meta":{"skills_available":true}}`,
},
{`{"success":true,"data":[],"skills_available":false}`, `{"data":[],"meta":{"skills_available":false}}`},
} {
projected, err := op.Project([]byte(tc.body))
require.NoError(t, err)
out, err := json.Marshal(projected)
require.NoError(t, err)
assert.JSONEq(t, tc.want, string(out))
}
_, ok = Builtin().Get("skill.get")
assert.False(t, ok)
}
func TestBuiltinAgentSandboxProjection(t *testing.T) {
for _, id := range []string{"agent.get", "agent.list"} {
op, ok := Builtin().Get(id)
require.True(t, ok)
data := `{"id":"a1","config":{"sandbox_config_id":"cfg-1","api_key":"secret",
"headers":{"Authorization":"secret"},"extensions":{"url":"https://private"}}}`
want := `{"agent_id":"a1","sandbox_config_id":"cfg-1"}`
if id == "agent.list" {
data = "[" + data + "]"
want = `[{"agent_id":"a1"}]`
}
projected, err := op.Project([]byte(`{"data":` + data + `}`))
require.NoError(t, err)
out, err := json.Marshal(projected)
require.NoError(t, err)
assert.JSONEq(t, `{"data":`+want+`}`, string(out))
}
}
func TestBuiltinAgentSkillParams(t *testing.T) {
op, ok := Builtin().Get("agent.update")
require.True(t, ok)
mode, ok := op.Param("agent_mode")
require.True(t, ok)
assert.Equal(t, []string{"quick-answer", "smart-reasoning"}, mode.Enum)
skills, ok := op.Param("skills_selection_mode")
require.True(t, ok)
assert.Equal(t, []string{"all", "selected", "none"}, skills.Enum)
names, ok := op.Param("selected_skills")
require.True(t, ok)
assert.Equal(t, TypeStringList, names.Type)
assert.Equal(t, 50, names.MaxItems)
for _, value := range []any{"not-a-list", make([]string, 51)} {
raw, err := json.Marshal(value)
require.NoError(t, err)
_, err = op.Build(map[string]json.RawMessage{"agent_id": json.RawMessage(`"a1"`), "selected_skills": raw})
require.Error(t, err)
}
}
func TestBuiltinKnowledgeBaseLifecycle(t *testing.T) {
catalog := Builtin()
create, ok := catalog.Get("knowledge_base.create")
require.True(t, ok)
assert.Equal(t, "name", create.LabelParam)
name, ok := create.Param("name")
require.True(t, ok)
assert.True(t, name.Required)
_, ok = create.Param("knowledge_base_id")
assert.False(t, ok)
_, ok = create.Param("indexing_strategy")
assert.False(t, ok)
vector, ok := create.Param("vector_enabled")
require.True(t, ok)
assert.Equal(t, TypeBoolean, vector.Type)
_, ok = create.Param("embedding_model_id")
assert.True(t, ok)
_, ok = create.Param("chunk_size")
assert.True(t, ok)
_, ok = create.Param("vector_store_id")
assert.True(t, ok)
kind, ok := create.Param("type")
require.True(t, ok)
assert.Equal(t, []string{"document", "faq", "wiki"}, kind.Enum)
update, ok := catalog.Get("knowledge_base.update")
require.True(t, ok)
assert.Equal(t, http.MethodPatch, update.Method)
_, ok = update.Param("name")
assert.True(t, ok)
_, ok = update.Param("description")
assert.True(t, ok)
_, ok = update.Param("vector_enabled")
assert.True(t, ok)
_, ok = update.Param("embedding_model_id")
assert.True(t, ok)
_, ok = update.Param("chunk_size")
assert.True(t, ok)
_, ok = update.Param("vector_store_id")
assert.False(t, ok, "the vector store is chosen when the knowledge base is created")
del, ok := catalog.Get("knowledge_base.delete")
require.True(t, ok)
assert.Equal(t, RiskDestructive, del.Risk)
setTags, ok := catalog.Get("knowledge.set_tags")
require.True(t, ok)
docs, ok := setTags.Param("knowledge_ids")
require.True(t, ok)
assert.Equal(t, TypeStringList, docs.Type)
assert.Equal(t, 20, docs.MaxItems)
tags, ok := setTags.Param("tag_ids")
require.True(t, ok)
assert.Equal(t, 50, tags.MaxItems)
require.NotNil(t, setTags.Target)
require.NotNil(t, setTags.Target.Items)
assert.Equal(t, "knowledge_ids", setTags.Target.Items.Param)
manual, ok := catalog.Get("knowledge.update_manual")
require.True(t, ok)
content, ok := manual.Param("content")
require.True(t, ok)
assert.True(t, content.Required)
}
@@ -0,0 +1,296 @@
package operations
import (
"encoding/json"
"net/http"
"strings"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDataSourceOperationsExposeSavedStateOnly(t *testing.T) {
for _, name := range []string{"list", "get", "test", "sync", "pause", "resume", "list_sync_logs", "get_sync_log"} {
op, ok := Builtin().Get("data_source." + name)
require.True(t, ok, name)
wantRole := types.TenantRoleViewer
if name == "test" || name == "sync" || name == "pause" || name == "resume" {
wantRole = types.TenantRoleAdmin
}
assert.Equal(t, wantRole, op.Role, name)
assert.Equal(t, name == "sync" || name == "pause" || name == "resume", op.Risk.Mutates(), name)
if op.Risk.Mutates() {
assert.Equal(t, &Target{Operation: "data_source.get", Label: "name"}, op.Target)
}
_, err := op.Build(map[string]json.RawMessage{"credentials": raw(map[string]string{"token": "secret"})})
require.ErrorContains(t, err, "unknown parameter")
}
sync, _ := Builtin().Get("data_source.sync")
assert.Equal(t, RiskDestructive, sync.Risk, "saved sync policy can delete documents")
assert.True(t, (Access{Level: types.AssistantAccessAutoWrite}).NeedsApproval(sync))
testOp, _ := Builtin().Get("data_source.test")
assert.Equal(t, RiskProbe, testOp.Risk)
for _, name := range []string{"create", "update", "delete"} {
_, ok := Builtin().Get("data_source." + name)
assert.False(t, ok)
}
payload := `{
"id": "ds1",
"knowledge_base_id": "kb1",
"name": "Docs",
"type": "notion",
"status": "active",
"sync_deletions": true,
"tenant_id": 7,
"config": {
"credentials": {
"token": "secret"
},
"settings": {
"token": "secret"
}
},
"credentials": {
"token": "secret"
},
"last_sync_cursor": {
"token": "secret"
},
"last_sync_result": {
"token": "secret"
},
"latest_sync_log": {
"id": "log1",
"status": "failed",
"items_failed": 2,
"error_message": "timeout",
"result": {
"token": "secret"
}
}
}`
get, _ := Builtin().Get("data_source.get")
out := projectJSON(t, get, payload)
assert.Contains(t, out, `"data_source_id":"ds1"`)
assert.Contains(t, out, `"knowledge_base_id":"kb1"`)
assert.NotContains(t, out, `"sync_log_id":"log1"`)
assert.NotContains(t, out, `"latest_sync_log"`)
for _, hidden := range []string{
"secret",
"credentials",
"tenant_id",
"config",
"last_sync_cursor",
"last_sync_result",
} {
assert.NotContains(t, out, hidden)
}
list, _ := Builtin().Get("data_source.list")
assert.True(t, list.Result.List)
assert.Contains(t, projectJSON(t, list, "["+payload+"]"), `"data_source_id":"ds1"`)
call, err := list.Build(map[string]json.RawMessage{"knowledge_base_id": raw("kb1")})
require.NoError(t, err)
assert.Equal(t, "/api/v1/datasource?kb_id=kb1", call.URI())
}
func TestDataSourceSyncLogsAreBoundedAndFollowable(t *testing.T) {
logs, _ := Builtin().Get("data_source.list_sync_logs")
call, err := logs.Build(
map[string]json.RawMessage{"data_source_id": raw("ds1"), "limit": raw(20), "offset": raw(20)},
)
require.NoError(t, err)
assert.Equal(t, "/api/v1/datasource/ds1/logs?limit=20&offset=20", call.URI())
for _, limit := range []int{0, 51} {
_, err = logs.Build(map[string]json.RawMessage{"data_source_id": raw("ds1"), "limit": raw(limit)})
require.Error(t, err)
}
for _, name := range []string{"data_source.sync", "data_source.get_sync_log"} {
op, _ := Builtin().Get(name)
assert.JSONEq(t, `{
"data": {
"sync_log_id": "log1",
"data_source_id": "ds1",
"status": "running",
"items_created": 3
}
}`, projectJSON(t, op, `{
"id": "log1",
"data_source_id": "ds1",
"status": "running",
"items_created": 3,
"tenant_id": 7,
"result": {
"credentials": "secret"
}
}`))
}
for _, name := range []string{"test", "pause", "resume"} {
op, _ := Builtin().Get("data_source." + name)
assert.JSONEq(t, `{"data":{"status":"active"}}`, projectJSON(t, op, `{"status":"active"}`))
}
}
func TestChunkEditRequiresRevisionAndCompleteContent(t *testing.T) {
get, _ := Builtin().Get("chunk.get")
update, _ := Builtin().Get("chunk.update")
require.True(t, update.Target.RequireComplete)
assert.Equal(t, "chunk.get", update.Target.Operation)
assert.ElementsMatch(
t,
[]string{"knowledge_id", "chunk_id", "content", "is_enabled", "expected_revision"},
paramNames(update),
)
content := strings.Repeat("文", 3000)
projected, err := get.Project(
raw(
map[string]any{
"data": map[string]any{
"id": "c1",
"knowledge_id": "k1",
"knowledge_base_id": "kb1",
"content": content,
"content_revision": 0,
"index_status": "ready",
},
},
),
)
require.NoError(t, err)
require.False(t, projected.Truncated)
assert.Equal(t, content, projected.Data.(map[string]any)["content"])
params := map[string]json.RawMessage{
"knowledge_id": raw("k1"),
"chunk_id": raw("c1"),
"content": raw(content),
"expected_revision": raw(0),
"is_enabled": raw(false),
}
call, err := update.Build(params)
require.NoError(t, err)
assert.Equal(t, http.MethodPut, call.Method)
assert.Equal(t, "/api/v1/chunks/k1/c1", call.URI())
var body map[string]any
require.NoError(t, json.Unmarshal(call.Body, &body))
assert.Equal(t, content, body["content"])
assert.Equal(t, false, body["is_enabled"])
delete(params, "expected_revision")
_, err = update.Build(params)
require.ErrorContains(t, err, "expected_revision: is required")
params["expected_revision"] = raw(-1)
_, err = update.Build(params)
require.Error(t, err)
projected, err = get.Project(raw(map[string]any{"data": map[string]any{"content": strings.Repeat("x", 8001)}}))
require.NoError(t, err)
assert.True(t, projected.Truncated)
list, _ := Builtin().Get("chunk.list")
projected, err = list.Project(raw(map[string]any{"data": []any{map[string]any{"content": content}}}))
require.NoError(t, err)
assert.True(t, projected.Truncated, "list previews stay compact")
}
func TestChunkRevertUsesSavedRevision(t *testing.T) {
revisions, _ := Builtin().Get("chunk.list_revisions")
assert.Equal(t, RiskRead, revisions.Risk)
out := projectJSON(t, revisions, `{
"data": [
{
"chunk_id": "c1",
"revision": 0,
"content": "original",
"is_enabled": false,
"edit_source": "manual",
"edited_at": "2026-10-17",
"editor_id": "private",
"tenant_id": 7
}
]
}`)
assert.Contains(t, out, `"revision":0`)
assert.NotContains(t, out, "editor_id")
revert, _ := Builtin().Get("chunk.revert")
call, err := revert.Build(
map[string]json.RawMessage{
"knowledge_id": raw("k1"),
"chunk_id": raw("c1"),
"revision": raw(0),
"expected_revision": raw(2),
},
)
require.NoError(t, err)
assert.JSONEq(t, `{"revision":0,"expected_revision":2}`, string(call.Body))
assert.Equal(t, "/api/v1/chunks/k1/c1/revert", call.URI())
}
func TestKnowledgeBaseCopyCannotOverwriteAnExistingDestination(t *testing.T) {
op, ok := Builtin().Get("knowledge_base.copy")
require.True(t, ok)
assert.ElementsMatch(t, []string{"knowledge_base_id"}, paramNames(op))
call, err := op.Build(map[string]json.RawMessage{"knowledge_base_id": raw("source")})
require.NoError(t, err)
assert.JSONEq(t, `{"source_id":"source"}`, string(call.Body))
for _, hidden := range []string{"target_id", "task_id", "target_knowledge_base_id"} {
_, err := op.Build(map[string]json.RawMessage{"knowledge_base_id": raw("source"), hidden: raw("existing")})
require.ErrorContains(t, err, "unknown parameter")
}
assert.JSONEq(t, `{
"data": {
"task_id": "task1",
"source_knowledge_base_id": "source",
"knowledge_base_id": "new"
}
}`, projectJSON(t, op, `{"data":{"task_id":"task1","source_id":"source","target_id":"new"}}`))
duplicate, _ := Builtin().Get("knowledge_base.duplicate")
assert.Contains(t, duplicate.Description, "settings only")
assert.Contains(t, projectJSON(t, duplicate, `{
"data": {
"source_id": "source",
"target_id": "new",
"knowledge_base": {
"api_key": "secret"
}
}
}`), `"knowledge_base_id":"new"`)
progress, _ := Builtin().Get("knowledge_base.get_copy_progress")
assert.JSONEq(t, `{
"data": {
"task_id": "task1",
"knowledge_base_id": "new",
"status": "failed",
"progress": 40,
"error": "quota exceeded"
}
}`, projectJSON(t, progress, `{
"data": {
"task_id": "task1",
"target_id": "new",
"status": "failed",
"progress": 40,
"error": "quota exceeded"
}
}`))
}
func TestDataSourceOperationsOmitRawUpstreamErrors(t *testing.T) {
failure := `Get "https://feeds.example.org/private?token=saved-secret": context deadline exceeded`
for _, id := range []string{
"data_source.get", "data_source.list", "data_source.update_sync",
"data_source.sync", "data_source.get_sync_log", "data_source.list_sync_logs",
} {
t.Run(id, func(t *testing.T) {
op, ok := Builtin().Get(id)
require.True(t, ok)
row := map[string]any{"id": "item", "status": "failed", "error_message": failure, "items_failed": 1}
var payload any = row
if op.Result.List {
payload = []any{row}
}
out := projectJSON(t, op, string(raw(payload)))
assert.Contains(t, out, `"status":"failed"`)
assert.NotContains(t, out, "saved-secret")
assert.NotContains(t, out, "error_message")
})
}
}
@@ -0,0 +1,127 @@
package operations
import (
"encoding/json"
"net/http"
"strings"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func projectJSON(t *testing.T, op Operation, body string) string {
t.Helper()
projected, err := op.Project([]byte(body))
require.NoError(t, err)
out, err := json.Marshal(projected)
require.NoError(t, err)
return string(out)
}
func TestBuiltinConversationOperationsAreReadOnly(t *testing.T) {
for _, op := range Builtin().All() {
if op.Domain() != "session" && op.Domain() != "message" {
continue
}
assert.False(t, op.Risk.Mutates(), op.ID)
assert.Equal(t, types.TenantRoleViewer, op.Role, op.ID)
}
}
func TestBuiltinSessionList(t *testing.T) {
op, ok := Builtin().Get("session.list")
require.True(t, ok)
assert.Equal(t, RiskRead, op.Risk)
assert.Equal(t, "/api/v1/sessions", op.Route)
assert.ElementsMatch(t, []string{"page", "page_size", "kind", "keyword"}, paramNames(op))
size, _ := op.Param("page_size")
assert.Equal(t, 20, size.Maximum)
// source and agent_id switch an admin to every member's channel
// conversations, so the model cannot set them.
for _, hidden := range []string{"source", "agent_id"} {
_, err := op.Build(map[string]json.RawMessage{hidden: json.RawMessage(`"feishu"`)})
require.Error(t, err, hidden)
}
call, err := op.Build(map[string]json.RawMessage{
"keyword": json.RawMessage(`"部署"`), "page_size": json.RawMessage(`10`),
})
require.NoError(t, err)
assert.Equal(t, http.MethodGet, call.Method)
assert.Contains(t, call.URI(), "page_size=10")
assert.JSONEq(t, `{"data":[{"session_id":"s1","title":"部署问题","is_pinned":true,
"created_at":"2026-10-01T08:00:00Z","updated_at":"2026-10-15T08:00:00Z"}],
"meta":{"total":1,"page":1,"page_size":10}}`,
projectJSON(t, op, `{"success":true,"total":1,"page":1,"page_size":10,"data":[{"id":"s1",
"title":"部署问题","user_id":"u1","tenant_id":7,"is_pinned":true,"kind":"",
"last_request_state":{"agent_id":"a1"},"im_platform":"feishu","im_user_id":"ou_1",
"created_at":"2026-10-01T08:00:00Z","updated_at":"2026-10-15T08:00:00Z"}]}`))
}
func TestBuiltinMessageList(t *testing.T) {
op, ok := Builtin().Get("message.list")
require.True(t, ok)
assert.Equal(t, RiskRead, op.Risk)
assert.ElementsMatch(t, []string{"session_id", "limit", "before_time"}, paramNames(op))
limit, _ := op.Param("limit")
assert.Equal(t, 20, limit.Maximum)
_, err := op.Build(map[string]json.RawMessage{
"session_id": json.RawMessage(`"s1"`), "resource_urls": json.RawMessage(`"public"`),
})
require.Error(t, err, "file links stay handles")
long := strings.Repeat("长", 1600)
projected, err := op.Project([]byte(`{"success":true,"data":[{"id":"m1","session_id":"s1",
"request_id":"r1","role":"assistant","content":"` + long + `",
"knowledge_references":[{"id":"c1"}],"agent_steps":[{"thought":"x"}],
"created_at":"2026-10-15T08:00:00Z"}]}`))
require.NoError(t, err)
assert.True(t, projected.Truncated)
out, err := json.Marshal(projected.Data)
require.NoError(t, err)
assert.NotContains(t, string(out), "knowledge_references")
assert.NotContains(t, string(out), "agent_steps")
var rows []map[string]any
require.NoError(t, json.Unmarshal(out, &rows))
require.Len(t, rows, 1)
assert.Equal(t, "m1", rows[0]["message_id"])
assert.Equal(t, "assistant", rows[0]["role"])
assert.LessOrEqual(t, len([]rune(rows[0]["content"].(string))), 1501)
}
func TestBuiltinMessageSearch(t *testing.T) {
op, ok := Builtin().Get("message.search")
require.True(t, ok)
assert.Equal(t, RiskProbe, op.Risk)
assert.Equal(t, http.MethodPost, op.Method)
assert.ElementsMatch(t, []string{"query", "limit"}, paramNames(op))
query, _ := op.Param("query")
assert.True(t, query.Required)
limit, _ := op.Param("limit")
assert.Equal(t, 20, limit.Maximum)
call, err := op.Build(map[string]json.RawMessage{"query": json.RawMessage(`"上次的配置"`)})
require.NoError(t, err)
assert.JSONEq(t, `{"query":"上次的配置"}`, string(call.Body))
assert.JSONEq(t, `{"data":[{"request_id":"r1","session_id":"s1","session_title":"部署",
"query_content":"怎么配置","answer_content":"这样配置","match_type":"keyword",
"created_at":"2026-10-15T08:00:00Z"}],"meta":{"total":1}}`,
projectJSON(t, op, `{"success":true,"data":{"total":1,"items":[{"request_id":"r1",
"session_id":"s1","session_title":"部署","query_content":"怎么配置","answer_content":"这样配置",
"score":0.42,"match_type":"keyword","created_at":"2026-10-15T08:00:00Z"}]}}`))
}
func TestBuiltinChatHistoryStats(t *testing.T) {
op, ok := Builtin().Get("message.chat_history_stats")
require.True(t, ok)
assert.Equal(t, RiskRead, op.Risk)
assert.Empty(t, op.Params)
assert.JSONEq(t, `{"data":{"enabled":true,"embedding_model_id":"emb-1","indexed_message_count":12}}`,
projectJSON(t, op, `{"success":true,"data":{"enabled":true,"embedding_model_id":"emb-1",
"knowledge_base_id":"kb-hidden","knowledge_base_name":"__chat_history__",
"indexed_message_count":12,"has_indexed_messages":true}}`))
}
+151
View File
@@ -0,0 +1,151 @@
package operations
import (
"bytes"
"context"
"errors"
"net/http"
"sync"
"time"
"academy/internal/types"
)
const maxResponseBytes = 2 << 20
// Identity is who an operation runs as. Only a signed-in web user can be
// dispatched: API-key, embed and IM principals carry narrower grants than the
// user record behind them, and replaying a call as that user would widen them.
type Identity struct {
UserID string
TenantID uint64
Language string
Agent types.AuditAgentAction
}
// Response is a captured HTTP response.
type Response struct {
Status int
Body []byte
}
// Dispatcher executes a built call as identity.
type Dispatcher interface {
Dispatch(ctx context.Context, identity Identity, call Call) (*Response, error)
}
// ErrDispatcherUnavailable means the router has not been bound yet.
var ErrDispatcherUnavailable = errors.New("operation dispatcher is not available")
// ErrResponseTooLarge means the handler wrote more than the capture limit.
var ErrResponseTooLarge = errors.New("operation response is too large")
// HandlerDispatcher sends calls through an http.Handler, normally the gin
// engine. The engine is built after the services that hold this dispatcher,
// so it is bound late.
type HandlerDispatcher struct {
mu sync.RWMutex
handler http.Handler
}
// NewHandlerDispatcher returns a dispatcher that fails until Bind is called.
func NewHandlerDispatcher() *HandlerDispatcher { return &HandlerDispatcher{} }
// Bind sets the handler calls are dispatched to.
func (d *HandlerDispatcher) Bind(h http.Handler) {
d.mu.Lock()
d.handler = h
d.mu.Unlock()
}
// Dispatch serves call through the bound handler as identity, detached from
// ctx's values but cancelled with it.
func (d *HandlerDispatcher) Dispatch(ctx context.Context, identity Identity, call Call) (*Response, error) {
d.mu.RLock()
h := d.handler
d.mu.RUnlock()
if h == nil {
return nil, ErrDispatcherUnavailable
}
// The request must not inherit the agent run's context values (KB grants,
// tenant overrides, caller): handlers would treat them as already
// authorized. Only cancellation crosses over; Auth rebuilds the rest.
reqCtx := types.WithInternalDispatch(detachValues(ctx), types.InternalDispatch{
UserID: identity.UserID, TenantID: identity.TenantID,
})
if _, ok := types.InternalDispatchFromContext(reqCtx); !ok {
return nil, errors.New("operation identity is incomplete")
}
reqCtx = types.WithAuditAgentAction(reqCtx, identity.Agent)
req, err := http.NewRequestWithContext(reqCtx, call.Method, call.URI(), bytes.NewReader(call.Body))
if err != nil {
return nil, err
}
// TEST-NET-1 peer address: never loopback or a private network, so no
// local-trust shortcut can apply to a dispatched request.
req.RemoteAddr = "192.0.2.1:0"
req.Header.Set("Accept", "application/json")
if call.Body != nil {
req.Header.Set("Content-Type", "application/json")
}
if identity.Language != "" {
req.Header.Set("Accept-Language", identity.Language)
}
w := newCaptureWriter()
h.ServeHTTP(w, req)
if w.overflow {
return nil, ErrResponseTooLarge
}
return &Response{Status: w.status(), Body: w.body.Bytes()}, nil
}
// detachValues keeps ctx's deadline and cancellation but none of its values.
func detachValues(ctx context.Context) context.Context { return valuelessContext{ctx} }
type valuelessContext struct{ parent context.Context }
func (c valuelessContext) Deadline() (time.Time, bool) { return c.parent.Deadline() }
func (c valuelessContext) Done() <-chan struct{} { return c.parent.Done() }
func (c valuelessContext) Err() error { return c.parent.Err() }
func (c valuelessContext) Value(any) any { return nil }
type captureWriter struct {
header http.Header
code int
body bytes.Buffer
overflow bool
}
func newCaptureWriter() *captureWriter { return &captureWriter{header: http.Header{}} }
func (w *captureWriter) Header() http.Header { return w.header }
func (w *captureWriter) WriteHeader(code int) {
if w.code == 0 {
w.code = code
}
}
func (w *captureWriter) Write(p []byte) (int, error) {
if w.code == 0 {
w.code = http.StatusOK
}
if w.body.Len()+len(p) > maxResponseBytes {
w.overflow = true
return 0, ErrResponseTooLarge
}
return w.body.Write(p)
}
// Flush satisfies http.Flusher for handlers that flush; nothing is streamed.
func (w *captureWriter) Flush() {}
func (w *captureWriter) status() int {
if w.code == 0 {
return http.StatusOK
}
return w.code
}
+118
View File
@@ -0,0 +1,118 @@
package operations
import (
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func faqParams() map[string]json.RawMessage {
return map[string]json.RawMessage{
"knowledge_base_id": raw("kb1"), "standard_question": raw("Question"),
"similar_questions": raw([]string{}), "negative_questions": raw([]string{}),
"answers": raw([]string{"Answer"}), "answer_strategy": raw("all"), "tag_seq_id": raw(0),
}
}
func TestFAQRequiredListsAllowEmptyButNotOmitted(t *testing.T) {
for _, name := range []string{"faq.create_entry", "faq.update_entry"} {
t.Run(name, func(t *testing.T) {
op, ok := Builtin().Get(name)
require.True(t, ok)
params := faqParams()
if name == "faq.update_entry" {
params["entry_id"] = raw(7)
}
call, err := op.Build(params)
require.NoError(t, err)
var body map[string]json.RawMessage
require.NoError(t, json.Unmarshal(call.Body, &body))
for _, field := range []string{"similar_questions", "negative_questions"} {
assert.JSONEq(t, `[]`, string(body[field]))
delete(params, field)
_, err = op.Build(params)
require.ErrorContains(t, err, field+": is required")
params[field] = raw(nil)
_, err = op.Build(params)
require.ErrorContains(t, err, field+": is required")
params[field] = raw([]string{})
}
params["standard_question"] = raw("")
_, err = op.Build(params)
require.ErrorContains(t, err, "must not be empty")
})
}
for _, tc := range []struct{ name, field string }{
{"knowledge.batch_delete", "knowledge_ids"},
{"faq.delete_entries", "entry_ids"},
{"faq.add_similar_questions", "similar_questions"},
} {
op, _ := Builtin().Get(tc.name)
params := map[string]json.RawMessage{"knowledge_base_id": raw("kb1"), tc.field: raw([]string{})}
if tc.name == "faq.add_similar_questions" {
params["entry_id"] = raw(7)
}
_, err := op.Build(params)
require.ErrorContains(t, err, "must not be empty", tc.name)
}
}
func TestFAQReadThenRenamePreservesFullAnswers(t *testing.T) {
get, _ := Builtin().Get("faq.get_entry")
update, _ := Builtin().Get("faq.update_entry")
require.True(t, update.Target.RequireComplete)
for _, answer := range []string{strings.Repeat("a", 3000), strings.Repeat("文", 8000), strings.Repeat("😀", 8000)} {
body := raw(map[string]any{"data": map[string]any{
"id": 7, "standard_question": "Question", "similar_questions": []string{},
"negative_questions": []string{}, "answers": []string{answer}, "answer_strategy": "all", "tag_id": 0,
}})
projected, err := get.Project(body)
require.NoError(t, err)
require.False(t, projected.Truncated)
params := map[string]json.RawMessage{"knowledge_base_id": raw("kb1")}
for k, v := range projected.Data.(map[string]any) {
if _, ok := update.Param(k); ok {
params[k] = raw(v)
}
}
params["standard_question"] = raw("Renamed")
call, err := update.Build(params)
require.NoError(t, err)
var stored struct {
Answers []string `json:"answers"`
}
require.NoError(t, json.Unmarshal(call.Body, &stored))
assert.Equal(t, []string{answer}, stored.Answers)
}
}
func TestProjectionReportsTruncatedFieldsAndNestedLists(t *testing.T) {
for _, tc := range []struct {
name string
value any
truncated bool
}{
{"exact string limit", strings.Repeat("文", 2000), false},
{"long string", strings.Repeat("文", 2001), true},
{"long list item", []string{strings.Repeat("a", 2001)}, true},
{"too many list items", make([]string, 101), true},
{"exact list limit", make([]string, 100), false},
} {
t.Run(tc.name, func(t *testing.T) {
for _, result := range []Result{
{Fields: []Field{{From: "value"}}},
{Root: "rows", List: true, Fields: []Field{{From: "value"}}},
{Root: "rows", List: true, Meta: []Field{{From: "value"}}},
} {
op := Operation{Result: result}
body := raw(map[string]any{"value": tc.value, "rows": []any{map[string]any{"value": tc.value}}})
projected, err := op.Project(body)
require.NoError(t, err)
assert.Equal(t, tc.truncated, projected.Truncated)
}
})
}
}
+140
View File
@@ -0,0 +1,140 @@
package operations
import (
"encoding/json"
"net/http"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// MCP, model and skill writes are admin-only, and none of them can carry a
// credential: secrets stay on the pages where the user types them.
func TestBuiltinInfrastructureWrites(t *testing.T) {
catalog := Builtin()
cases := []struct {
id string
risk Risk
method string
params []string
}{
{
"mcp_service.create", RiskWrite, http.MethodPost,
[]string{"name", "usage_instructions", "transport_type", "url", "auth_type", "api_key_header"},
},
{
"mcp_service.update", RiskWrite, http.MethodPut,
[]string{"mcp_service_id", "name", "usage_instructions", "enabled", "transport_type", "url"},
},
{"mcp_service.delete", RiskDestructive, http.MethodDelete, []string{"mcp_service_id"}},
{"model.copy", RiskWrite, http.MethodPost, []string{"model_id", "display_name"}},
{"model.update", RiskWrite, http.MethodPatch, []string{"model_id", "display_name", "description"}},
{"model.delete", RiskDestructive, http.MethodDelete, []string{"model_id"}},
{"skill.install", RiskWrite, http.MethodPost, []string{"sandbox_config_id", "source"}},
{"skill.install_catalog", RiskWrite, http.MethodPost, []string{"catalog_skill_id", "sandbox_config_ids"}},
{"skill.set_enabled", RiskWrite, http.MethodPatch, []string{"sandbox_config_id", "skill_id", "enabled"}},
{"skill.uninstall", RiskDestructive, http.MethodDelete, []string{"sandbox_config_id", "skill_id"}},
}
for _, tc := range cases {
t.Run(tc.id, func(t *testing.T) {
op, ok := catalog.Get(tc.id)
require.True(t, ok)
assert.Equal(t, tc.risk, op.Risk)
assert.Equal(t, tc.method, op.Method)
assert.Equal(t, types.TenantRoleAdmin, op.Role)
assert.ElementsMatch(t, tc.params, paramNames(op))
for _, p := range op.Params {
secrets := []string{"api_key", "token", "client_secret", "headers", "custom_headers", "envs"}
assert.NotContains(t, secrets, p.Name)
}
})
}
create, _ := catalog.Get("mcp_service.create")
transport, _ := create.Param("transport_type")
assert.ElementsMatch(t, []string{"sse", "http-streamable"}, transport.Enum, "stdio is never offered")
auth, _ := create.Param("auth_type")
assert.Equal(t, "auth_config.auth_type", auth.Key)
enabled, _ := catalog.Get("skill.set_enabled")
toggle, _ := enabled.Param("enabled")
assert.True(t, toggle.Required, "a toggle without enabled would be an env write")
}
func TestBuiltinInstallsAlwaysAsk(t *testing.T) {
catalog := Builtin()
for _, id := range []string{"skill.install", "skill.install_catalog", "mcp_service.create"} {
op, ok := catalog.Get(id)
require.True(t, ok, id)
assert.True(t, op.AlwaysConfirm, id)
assert.True(t, Access{Level: types.AssistantAccessAutoWrite}.NeedsApproval(op), id)
}
install, _ := catalog.Get("skill.install")
source, _ := install.Param("source")
assert.True(t, source.Required)
assert.Equal(t, "source", install.LabelParam)
call, err := install.Build(map[string]json.RawMessage{
"sandbox_config_id": json.RawMessage(`"cfg-1"`),
"source": json.RawMessage(`"https://github.com/acme/skills/tree/main/pdf"`),
})
require.NoError(t, err)
assert.Equal(t, "/api/v1/sandbox-configs/cfg-1/skills", call.Path)
assert.JSONEq(t, `{"source":"https://github.com/acme/skills/tree/main/pdf"}`, string(call.Body))
}
func TestBuiltinInfrastructureProjections(t *testing.T) {
catalog := Builtin()
project := func(id, body string) string {
t.Helper()
op, ok := catalog.Get(id)
require.True(t, ok, id)
projected, err := op.Project([]byte(body))
require.NoError(t, err)
out, err := json.Marshal(projected.Data)
require.NoError(t, err)
return string(out)
}
assert.JSONEq(t, `{"mcp_service_id":"m1","name":"Docs","description":"","enabled":true,
"transport_type":"sse","is_builtin":false,"auth_type":"api_key"}`,
project("mcp_service.get", `{"data":{"id":"m1","name":"Docs","description":"","enabled":true,
"transport_type":"sse","is_builtin":false,"url":"https://mcp.example/sse",
"auth_config":{"auth_type":"api_key","api_key_header":"X-Key","custom_headers":{"Authorization":"x"}},
"credentials":{"api_key":{"configured":true}}}}`))
assert.JSONEq(t, `[{"skill_id":"s1","name":"pdf","enabled":true,"status":"ready","missing_envs":["API_TOKEN"]}]`,
project("skill.list_installed", `{"data":[{"id":"s1","name":"pdf","enabled":true,"status":"ready",
"bundle_sha256":"abc","install_session_id":"sess","missing_envs":["API_TOKEN"],
"envs":[{"name":"API_TOKEN","required":true,"is_set":false}]}]}`))
assert.JSONEq(t, `[{"catalog_skill_id":"c1","name":"pdf","installed_on":["cfg-1"]}]`,
project("skill.list_catalog", `{"data":[{"id":"c1","name":"pdf","installed_on":["cfg-1"],
"installations":[{"skill_id":"s1","sandbox_config_id":"cfg-1"}]}]}`))
assert.JSONEq(t, `{"success":false,"started":["cfg-1"],"failed":["cfg-2: not found"]}`,
project("skill.install_catalog", `{"success":false,"data":{"installs":{"cfg-1":"s1"},
"errors":{"cfg-2":"not found"},"started":["cfg-1"],"failed":["cfg-2: not found"]}}`))
}
func TestModelCopyOnlyAcceptsSourceAndNewDisplayName(t *testing.T) {
op, ok := Builtin().Get("model.copy")
require.True(t, ok)
require.Equal(t, "model.get", op.Target.Operation)
call, err := op.Build(map[string]json.RawMessage{"model_id": raw("source"), "display_name": raw("Experiment")})
require.NoError(t, err)
assert.Equal(t, "/api/v1/models/source/copy", call.URI())
assert.JSONEq(t, `{"display_name":"Experiment"}`, string(call.Body))
for _, params := range []map[string]json.RawMessage{
{"model_id": raw("source")},
{"model_id": raw("source"), "display_name": raw("")},
{"model_id": raw("source"), "display_name": raw("Experiment"), "api_key": raw("secret")},
{"model_id": raw("source"), "display_name": raw("Experiment"), "name": raw("another-model")},
{"model_id": raw("source"), "display_name": raw("Experiment"), "is_default": raw(true)},
} {
_, err = op.Build(params)
require.Error(t, err)
}
}
@@ -0,0 +1,84 @@
package operations
import (
"encoding/json"
"fmt"
"net/http"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestMCPMetadataOperations(t *testing.T) {
for _, id := range []string{"mcp_service.get_metadata", "mcp_service.refresh_metadata"} {
op, ok := Builtin().Get(id)
require.True(t, ok)
assert.Equal(t, types.TenantRoleViewer, op.Role)
assert.Equal(t, []string{"mcp_service_id"}, paramNames(op))
call, err := op.Build(map[string]json.RawMessage{"mcp_service_id": raw("svc")})
require.NoError(t, err)
if id == "mcp_service.get_metadata" {
assert.Equal(t, RiskRead, op.Risk)
assert.Equal(t, http.MethodGet, call.Method)
assert.Equal(t, "/api/v1/mcp-services/svc/metadata", call.URI())
} else {
assert.Equal(t, RiskWrite, op.Risk)
assert.Equal(t, http.MethodPost, call.Method)
assert.Equal(t, "/api/v1/mcp-services/svc/metadata/refresh", call.URI())
assert.Equal(t, "mcp_service.get", op.Target.Operation)
assert.Equal(t, "name", op.Target.Label)
}
assert.JSONEq(
t,
`{"data":{},"meta":{"synced":false,"tool_count":0}}`,
projectJSON(t, op, `{"success":true,"synced":false,"tool_count":0,"data":null}`),
)
out := projectJSON(t, op, `{"synced":true,"tool_count":0,"data":{"service_id":"svc","tools":[],"stale":false}}`)
assert.Contains(t, out, `"synced":true`)
assert.Contains(t, out, `"tools":[]`)
assert.Contains(t, out, `"mcp_service_id":"svc"`)
out = projectJSON(t, op, `{
"synced": true,
"tool_count": 1,
"data": {
"stale": true,
"tools": [
{
"name": "search",
"description": "Search documents",
"inputSchema": {
"token": "SECRET"
}
}
],
"instructions": "DO NOT EXPOSE",
"principal": "PRIVATE",
"config_fingerprint": "PRIVATE"
}
}`)
assert.Contains(t, out, `"stale":true`)
assert.Contains(t, out, `"name":"search"`)
assert.NotContains(t, out, "SECRET")
assert.NotContains(t, out, "PRIVATE")
assert.NotContains(t, out, "DO NOT EXPOSE")
}
}
func TestMCPMetadataProjectionReportsIncompleteDirectory(t *testing.T) {
tools := make([]map[string]any, 250)
for i := range tools {
tools[i] = map[string]any{"name": fmt.Sprintf("tool_%d", i), "description": "reference"}
}
body, err := json.Marshal(
map[string]any{"synced": true, "tool_count": len(tools), "data": map[string]any{"tools": tools}},
)
require.NoError(t, err)
op, _ := Builtin().Get("mcp_service.get_metadata")
out, err := op.Project(body)
require.NoError(t, err)
assert.True(t, out.Truncated)
assert.Equal(t, json.Number("250"), out.Meta["tool_count"])
assert.Len(t, out.Data.(map[string]any)["tools"], defaultMaxListItems)
}
@@ -0,0 +1,152 @@
package operations
import (
"encoding/json"
"net/http"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestParserEngineDiscoveryUsesActualWireCaseAndHidesConnectionDetails(t *testing.T) {
op, ok := Builtin().Get("knowledge_base.list_parser_engines")
require.True(t, ok)
body, err := json.Marshal(
map[string]any{
"data": []types.ParserEngineInfo{
{Name: "builtin", Available: true, FileTypes: []string{"pdf"}},
{Name: "mineru", Available: false, UnavailableReason: "not configured"},
},
"docreader_addr": "private:50051",
"connected": true,
},
)
require.NoError(t, err)
out := projectJSON(t, op, string(body))
assert.Contains(t, out, `"engine":"builtin"`)
assert.Contains(t, out, `"available":false`)
assert.Contains(t, out, `"file_types":["pdf"]`)
assert.NotContains(t, out, "private")
assert.NotContains(t, out, "docreader_addr")
for _, route := range []string{"/api/v1/system/parser-engines/check", "/api/v1/system/admin/settings/key"} {
_, err := NewCatalog(readOp("system.get", route))
require.Error(t, err, route)
}
}
func TestKnowledgeBaseParsingParamsAndProjection(t *testing.T) {
op, _ := Builtin().Get("knowledge_base.update")
params := map[string]json.RawMessage{
"knowledge_base_id": raw(
"kb1",
), "enable_parent_child": raw(true), "parent_chunk_size": raw(4096), "child_chunk_size": raw(384),
"parser_file_types": raw(
[]string{"pdf"},
), "parser_engine": raw("builtin"), "image_pipeline": raw("default"), "image_ocr_enabled": raw(false),
"question_generation_enabled": raw(true), "question_count": raw(5),
}
call, err := op.Build(params)
require.NoError(t, err)
assert.JSONEq(t, `{
"chunking_config": {
"enable_parent_child": true,
"parent_chunk_size": 4096,
"child_chunk_size": 384
},
"image_processing_config": {
"image_pipeline": "default"
},
"parser_file_types": [
"pdf"
],
"parser_engine": "builtin",
"image_ocr_enabled": false,
"question_generation_config": {
"enabled": true,
"question_count": 5
}
}`, string(call.Body))
params["parser_engine"] = raw("")
_, err = op.Build(params)
require.NoError(t, err, "empty engine restores defaults")
params["question_count"] = raw(11)
_, err = op.Build(params)
require.Error(t, err)
read, _ := Builtin().Get("knowledge_base.get")
out := projectJSON(t, read, `{
"data": {
"id": "kb1",
"chunking_config": {
"parser_engine_rules": [
{
"file_types": [
"pdf"
],
"engine": "builtin"
}
]
},
"image_processing_config": {
"image_pipeline": "default",
"image_pipeline_params": {
"default.ocr_enabled": false,
"default.caption_enabled": true,
"default.enable_ocr": true,
"enable_ocr": true,
"private_token": "secret",
"default": {
"ocr_enabled": true
}
}
}
}
}`)
assert.Contains(t, out, `"engine":"builtin"`)
assert.Contains(t, out, `"default.ocr_enabled":false`, "literal map keys must not resolve as nested paths")
assert.Contains(t, out, `"default.caption_enabled":true`)
assert.NotContains(t, out, "enable_ocr", "obsolete keys must not report stale switch values")
assert.NotContains(t, out, "secret")
assert.NotContains(t, out, `"default":`)
_, exposed := op.Param("parser_engine_rules")
assert.False(t, exposed, "only the targeted routing patch is writable")
_, exposed = op.Param("image_pipeline_params")
assert.False(t, exposed, "free-form parameters are not writable")
}
func TestFAQBatchUpdateIsBoundedAndTargetsEachEntry(t *testing.T) {
op, ok := Builtin().Get("faq.batch_update")
require.True(t, ok)
assert.Equal(t, RiskWrite, op.Risk)
assert.Equal(t, http.MethodPatch, op.Method)
assert.Equal(t, "faq.get_entry", op.Target.Items.Operation)
assert.Equal(t, "entry_ids", op.Target.Items.Param)
assert.ElementsMatch(
t,
[]string{"knowledge_base_id", "entry_ids", "is_enabled", "is_recommended", "tag_seq_id"},
paramNames(op),
)
call, err := op.Build(
map[string]json.RawMessage{
"knowledge_base_id": raw("kb1"),
"entry_ids": raw([]int64{1, 2}),
"is_enabled": raw(false),
"is_recommended": raw(true),
"tag_seq_id": raw(0),
},
)
require.NoError(t, err)
assert.JSONEq(t, `{"entry_ids":[1,2],"is_enabled":false,"is_recommended":true,"tag_id":0}`, string(call.Body))
assert.Equal(t, "/api/v1/knowledge-bases/kb1/faq/entries", call.URI())
for _, ids := range [][]int64{{}, make([]int64, 21)} {
_, err := op.Build(
map[string]json.RawMessage{
"knowledge_base_id": raw("kb1"),
"entry_ids": raw(ids),
"is_enabled": raw(false),
},
)
require.Error(t, err)
}
}
+205
View File
@@ -0,0 +1,205 @@
package operations
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"unicode/utf8"
)
const (
maxProjectedStringRunes = 2000
// maxAgentFieldRunes is the largest x-agent-max-runes value. Revision
// content uses it so a revert can be read; ordinary fields stay at
// maxProjectedStringRunes.
maxAgentFieldRunes = 8000
)
// Projected is the model-visible slice of a response.
type Projected struct {
// Data is an object, or a list of objects for list results.
Data any `json:"data"`
// Meta holds Result.Meta fields, when declared.
Meta map[string]any `json:"meta,omitempty"`
// Truncated reports any loss of string content or list items in the projection.
Truncated bool `json:"truncated,omitempty"`
}
// Project extracts the declared fields from a JSON response body.
func (op Operation) Project(body []byte) (Projected, error) {
var doc any
dec := json.NewDecoder(bytes.NewReader(body))
dec.UseNumber()
if err := dec.Decode(&doc); err != nil {
return Projected{}, fmt.Errorf("response is not JSON: %w", err)
}
out := Projected{}
if len(op.Result.Meta) > 0 {
if obj, ok := doc.(map[string]any); ok {
out.Meta, out.Truncated = projectObject(obj, op.Result.Meta)
}
}
root, ok := lookup(doc, op.Result.Root)
if !ok || root == nil {
if op.Result.List {
out.Data = []any{}
} else {
out.Data = map[string]any{}
}
return out, nil
}
if !op.Result.List {
obj, ok := root.(map[string]any)
if !ok {
return Projected{}, fmt.Errorf("response %q is not an object", op.Result.Root)
}
data, truncated := projectObject(obj, op.Result.Fields)
out.Data = data
out.Truncated = out.Truncated || truncated
return out, nil
}
items, ok := root.([]any)
if !ok {
return Projected{}, fmt.Errorf("response %q is not a list", op.Result.Root)
}
limit := op.Result.MaxItems
if limit <= 0 {
limit = defaultMaxResultItems
}
if len(items) > limit {
items = items[:limit]
out.Truncated = true
}
list := make([]any, 0, len(items))
for _, item := range items {
if obj, ok := item.(map[string]any); ok {
data, truncated := projectObject(obj, op.Result.Fields)
list = append(list, data)
out.Truncated = out.Truncated || truncated
}
}
out.Data = list
return out, nil
}
// Label returns the projected string field key, if present.
func (p Projected) Label(key string) string {
obj, ok := p.Data.(map[string]any)
if !ok {
return ""
}
s, _ := obj[key].(string)
return strings.TrimSpace(s)
}
func projectObject(obj map[string]any, fields []Field) (map[string]any, bool) {
out := make(map[string]any, len(fields))
truncated := false
for _, f := range fields {
v, ok := lookup(obj, f.From)
if ok && f.MapKey != "" {
m, isMap := v.(map[string]any)
if !isMap {
continue
}
v, ok = m[f.MapKey]
}
if !ok {
continue
}
if len(f.Items) > 0 {
list, cut := projectItems(v, f.Items)
truncated = truncated || cut
out[f.outputKey()] = list
continue
}
limit := f.MaxRunes
if limit <= 0 {
limit = maxProjectedStringRunes
}
bounded, cut := boundValue(v, limit)
truncated = truncated || cut
if bounded != nil {
out[f.outputKey()] = bounded
}
}
return out, truncated
}
// projectItems projects a list of objects element by element. A null list
// becomes an empty one so the model can tell "none" from "not reported".
func projectItems(v any, fields []Field) ([]any, bool) {
items, _ := v.([]any)
out := make([]any, 0, min(len(items), defaultMaxListItems))
truncated := len(items) > defaultMaxListItems
for _, item := range items {
if len(out) == defaultMaxListItems {
break
}
if obj, ok := item.(map[string]any); ok {
data, cut := projectObject(obj, fields)
out = append(out, data)
truncated = truncated || cut
}
}
return out, truncated
}
func lookup(doc any, path string) (any, bool) {
if path == "" {
return doc, true
}
cur := doc
for _, key := range strings.Split(path, ".") {
obj, ok := cur.(map[string]any)
if !ok {
return nil, false
}
if cur, ok = obj[key]; !ok {
return nil, false
}
}
return cur, true
}
// boundValue keeps scalar fields, and lists of scalars, within a size the
// model context can afford. Nested objects are not projected implicitly;
// declare their fields instead.
func boundValue(v any, maxRunes int) (any, bool) {
switch t := v.(type) {
case string:
return truncateRunes(t, maxRunes), utf8.RuneCountInString(t) > maxRunes
case []any:
out := make([]any, 0, min(len(t), defaultMaxListItems))
truncated := len(t) > defaultMaxListItems
for _, item := range t {
if len(out) == defaultMaxListItems {
break
}
switch s := item.(type) {
case string:
out = append(out, truncateRunes(s, maxRunes))
truncated = truncated || utf8.RuneCountInString(s) > maxRunes
case json.Number, bool:
out = append(out, s)
}
}
return out, truncated
case map[string]any:
return nil, false
default:
return t, false
}
}
func truncateRunes(s string, limit int) string {
if utf8.RuneCountInString(s) <= limit {
return s
}
runes := []rune(s)
return string(runes[:limit]) + "…"
}
+375
View File
@@ -0,0 +1,375 @@
package operations
import (
"bytes"
"encoding/json"
"fmt"
"math"
"net/url"
"sort"
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
const (
// maxStringParamBytes is the default cap for a string parameter. Document
// bodies opt into maxAgentStringBytes instead; that matches the manual
// knowledge API limit of 200000 runes at the longest UTF-8 encoding.
maxStringParamBytes = 4096
maxAgentStringBytes = 200000 * 4
)
// Call is a fully validated HTTP request for one operation.
type Call struct {
Method string
// Path is escaped and ready to use as a request URI path.
Path string
Query url.Values
// Body is a JSON object, or nil when the operation has no body params.
Body []byte
}
// URI is Path plus the encoded query.
func (c Call) URI() string {
if len(c.Query) == 0 {
return c.Path
}
return c.Path + "?" + c.Query.Encode()
}
// ParamError is a validation failure the model can correct.
type ParamError struct {
Param string
Message string
}
func (e *ParamError) Error() string {
if e.Param == "" {
return e.Message
}
return fmt.Sprintf("%s: %s", e.Param, e.Message)
}
func paramErr(name, format string, args ...any) error {
return &ParamError{Param: name, Message: fmt.Sprintf(format, args...)}
}
// Build validates params against the operation and assembles the request.
// Unknown parameters are rejected rather than ignored, so a model that
// guessed a name learns about it instead of silently getting other behavior.
func (op Operation) Build(params map[string]json.RawMessage) (Call, error) {
for name := range params {
if _, ok := op.Param(name); !ok {
return Call{}, paramErr(name, "unknown parameter; allowed: %s", strings.Join(op.paramNames(), ", "))
}
}
pathValues := map[string]string{}
query := url.Values{}
body := map[string]any{}
for _, p := range op.Params {
raw, present := params[p.Name]
if present && isJSONNull(raw) {
present = false
}
if !present {
if p.Required {
return Call{}, paramErr(p.Name, "is required")
}
continue
}
value, err := decodeParam(p, raw)
if err != nil {
return Call{}, err
}
switch p.In {
case InPath:
if n, ok := value.(int64); ok {
pathValues[p.wireKey()] = strconv.FormatInt(n, 10)
break
}
s := value.(string)
if err := validatePathValue(p, s, strings.HasSuffix(op.Route, "/*"+p.wireKey())); err != nil {
return Call{}, err
}
pathValues[p.wireKey()] = s
case InQuery:
switch v := value.(type) {
case []string:
for _, item := range v {
query.Add(p.wireKey(), item)
}
case []int64:
for _, item := range v {
query.Add(p.wireKey(), strconv.FormatInt(item, 10))
}
case string:
query.Set(p.wireKey(), v)
case int64:
query.Set(p.wireKey(), strconv.FormatInt(v, 10))
case float64:
query.Set(p.wireKey(), strconv.FormatFloat(v, 'f', -1, 64))
case bool:
query.Set(p.wireKey(), strconv.FormatBool(v))
}
case InBody:
if err := assignBody(body, p.wireKey(), value); err != nil {
return Call{}, err
}
}
}
call := Call{Method: op.Method, Path: renderPath(op.Route, pathValues)}
if len(query) > 0 {
call.Query = query
}
if op.hasBody() {
encoded, err := json.Marshal(body)
if err != nil {
return Call{}, fmt.Errorf("encode body: %w", err)
}
call.Body = encoded
}
return call, nil
}
// assignBody writes value at a dotted JSON path, creating objects along the way.
func assignBody(body map[string]any, key string, value any) error {
parts := strings.Split(key, ".")
cursor := body
for _, part := range parts[:len(parts)-1] {
if part == "" {
return fmt.Errorf("body field %q has an empty path segment", key)
}
existing, ok := cursor[part]
if !ok {
next := map[string]any{}
cursor[part] = next
cursor = next
continue
}
next, ok := existing.(map[string]any)
if !ok {
return fmt.Errorf("body field %q conflicts with another field", key)
}
cursor = next
}
leaf := parts[len(parts)-1]
if leaf == "" {
return fmt.Errorf("body field %q has an empty path segment", key)
}
cursor[leaf] = value
return nil
}
// SelectParams keeps the parameters op accepts.
func SelectParams(op Operation, params map[string]json.RawMessage) map[string]json.RawMessage {
out := make(map[string]json.RawMessage, len(op.Params))
for _, p := range op.Params {
if raw, ok := params[p.Name]; ok {
out[p.Name] = raw
}
}
return out
}
func (op Operation) hasBody() bool {
for _, p := range op.Params {
if p.In == InBody {
return true
}
}
return false
}
func (op Operation) paramNames() []string {
names := make([]string, 0, len(op.Params))
for _, p := range op.Params {
names = append(names, p.Name)
}
sort.Strings(names)
if len(names) == 0 {
return []string{"(none)"}
}
return names
}
func isJSONNull(raw json.RawMessage) bool {
return bytes.Equal(bytes.TrimSpace(raw), []byte("null"))
}
func decodeParam(p Param, raw json.RawMessage) (any, error) {
switch p.Type {
case TypeString:
var s string
if err := json.Unmarshal(raw, &s); err != nil {
return nil, paramErr(p.Name, "must be a string")
}
s = strings.TrimSpace(s)
if err := validateString(p, s); err != nil {
return nil, err
}
if s == "" && p.Required && !p.AllowEmpty {
return nil, paramErr(p.Name, "must not be empty")
}
return s, nil
case TypeStringList:
var list []string
if err := json.Unmarshal(raw, &list); err != nil {
return nil, paramErr(p.Name, "must be an array of strings")
}
limit := p.MaxItems
if limit <= 0 {
limit = defaultMaxListItems
}
if len(list) > limit {
return nil, paramErr(p.Name, "accepts at most %d items", limit)
}
if p.Required && !p.AllowEmpty && len(list) == 0 {
return nil, paramErr(p.Name, "must not be empty")
}
out := make([]string, 0, len(list))
for _, item := range list {
item = strings.TrimSpace(item)
if item == "" {
return nil, paramErr(p.Name, "must not contain empty items")
}
if err := validateString(p, item); err != nil {
return nil, err
}
out = append(out, item)
}
return out, nil
case TypeIntegerList:
var list []json.RawMessage
if err := json.Unmarshal(raw, &list); err != nil {
return nil, paramErr(p.Name, "must be an array of integers")
}
limit := p.MaxItems
if limit <= 0 {
limit = defaultMaxListItems
}
if len(list) > limit {
return nil, paramErr(p.Name, "accepts at most %d items", limit)
}
if p.Required && !p.AllowEmpty && len(list) == 0 {
return nil, paramErr(p.Name, "must not be empty")
}
out := make([]int64, 0, len(list))
for _, item := range list {
v, err := decodeInteger(p, item)
if err != nil {
return nil, paramErr(p.Name, "must be an array of integers")
}
out = append(out, v)
}
return out, nil
case TypeInteger:
return decodeInteger(p, raw)
case TypeNumber:
if trimmed := bytes.TrimSpace(raw); len(trimmed) == 0 || trimmed[0] == '"' {
return nil, paramErr(p.Name, "must be a number")
}
var f float64
if err := json.Unmarshal(raw, &f); err != nil || math.IsNaN(f) || math.IsInf(f, 0) {
return nil, paramErr(p.Name, "must be a number")
}
return f, nil
case TypeBoolean:
var b bool
if err := json.Unmarshal(raw, &b); err != nil {
return nil, paramErr(p.Name, "must be a boolean")
}
return b, nil
}
return nil, paramErr(p.Name, "unsupported type")
}
func decodeInteger(p Param, raw json.RawMessage) (int64, error) {
if trimmed := bytes.TrimSpace(raw); len(trimmed) == 0 || trimmed[0] == '"' {
return 0, paramErr(p.Name, "must be an integer")
}
var n json.Number
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
if err := dec.Decode(&n); err != nil {
return 0, paramErr(p.Name, "must be an integer")
}
v, err := n.Int64()
if err != nil {
return 0, paramErr(p.Name, "must be an integer")
}
if p.Maximum > 0 && (v < int64(p.Minimum) || v > int64(p.Maximum)) {
return 0, paramErr(p.Name, "must be between %d and %d", p.Minimum, p.Maximum)
}
return v, nil
}
func validateString(p Param, s string) error {
limit := p.MaxBytes
if limit <= 0 {
limit = maxStringParamBytes
}
if len(s) > limit {
return paramErr(p.Name, "is too long")
}
if !utf8.ValidString(s) {
return paramErr(p.Name, "must be valid UTF-8")
}
for _, r := range s {
if unicode.IsControl(r) && r != '\n' && r != '\t' {
return paramErr(p.Name, "must not contain control characters")
}
}
if len(p.Enum) > 0 {
for _, allowed := range p.Enum {
if s == allowed {
return nil
}
}
return paramErr(p.Name, "must be one of: %s", strings.Join(p.Enum, ", "))
}
return nil
}
// validatePathValue keeps a value inside its route segment. A catch-all may
// span segments, but none of them may be empty or a dot segment.
func validatePathValue(p Param, s string, catchAll bool) error {
if strings.ContainsAny(s, "\\?#\n\t") {
return paramErr(p.Name, "contains characters not allowed in a path")
}
if catchAll {
for _, seg := range strings.Split(s, "/") {
if seg == "" || seg == "." || seg == ".." {
return paramErr(p.Name, "is not a valid path")
}
}
return nil
}
if strings.Contains(s, "/") || s == "." || s == ".." {
return paramErr(p.Name, "must be a single path segment")
}
return nil
}
func renderPath(route string, values map[string]string) string {
segments := strings.Split(route, "/")
for i, seg := range segments {
if seg == "" {
continue
}
switch seg[0] {
case ':':
segments[i] = url.PathEscape(values[seg[1:]])
case '*':
parts := strings.Split(values[seg[1:]], "/")
for j, part := range parts {
parts[j] = url.PathEscape(part)
}
segments[i] = strings.Join(parts, "/")
}
}
return strings.Join(segments, "/")
}
+167
View File
@@ -0,0 +1,167 @@
package operations
import (
"encoding/json"
"net/http"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSearchProviderOperationsAreScopedAndExcludeSecrets(t *testing.T) {
for _, name := range []string{"list", "get", "list_types", "test", "update", "delete"} {
op, ok := Builtin().Get("web_search_provider." + name)
require.True(t, ok, name)
role := types.TenantRoleViewer
if name == "update" || name == "delete" || name == "test" {
role = types.TenantRoleAdmin
}
assert.Equal(t, role, op.Role)
}
get, _ := Builtin().Get("web_search_provider.get")
out := projectJSON(t, get, `{
"data": {
"id": "p1",
"name": "Search",
"provider": "google",
"is_default": true,
"parameters": {
"api_key": "secret",
"proxy_url": "secret"
},
"credentials": {
"api_key": {
"configured": true
}
},
"tenant_id": 9
}
}`)
assert.JSONEq(t, `{
"data": {
"web_search_provider_id": "p1",
"name": "Search",
"provider": "google",
"is_default": true
}
}`, out)
update, _ := Builtin().Get("web_search_provider.update")
call, err := update.Build(
map[string]json.RawMessage{
"web_search_provider_id": raw("p1"),
"is_default": raw(false),
"description": raw(""),
},
)
require.NoError(t, err)
assert.Equal(t, http.MethodPatch, call.Method)
assert.JSONEq(t, `{"is_default":false,"description":""}`, string(call.Body))
for _, key := range []string{"parameters", "api_key", "base_url", "enabled", "tenant_id"} {
_, err = update.Build(map[string]json.RawMessage{"web_search_provider_id": raw("p1"), key: raw("bad")})
require.Error(t, err, key)
}
probe, _ := Builtin().Get("web_search_provider.test")
assert.Equal(t, RiskProbe, probe.Risk)
assert.JSONEq(
t,
`{"data":{"success":false,"error":"Connection failed"}}`,
projectJSON(t, probe, `{"success":false,"error":"Connection failed"}`),
)
remove, _ := Builtin().Get("web_search_provider.delete")
assert.Equal(t, RiskDestructive, remove.Risk)
}
func TestSyncSettingsCatalogPreservesExplicitValuesAndLimitsSelection(t *testing.T) {
op, ok := Builtin().Get("data_source.update_sync")
require.True(t, ok)
assert.Equal(t, types.TenantRoleAdmin, op.Role)
assert.Equal(t, RiskWrite, op.Risk)
call, err := op.Build(
map[string]json.RawMessage{
"data_source_id": raw("ds1"),
"sync_schedule": raw(""),
"sync_deletions": raw(false),
"resource_ids": raw([]string{"a"}),
},
)
require.NoError(t, err)
assert.Equal(t, "/api/v1/datasource/ds1/sync-settings", call.URI())
assert.JSONEq(t, `{"sync_schedule":"","sync_deletions":false,"resource_ids":["a"]}`, string(call.Body))
for _, params := range []map[string]json.RawMessage{
{
"sync_mode": raw(
"bad",
),
}, {
"conflict_strategy": raw(
"bad",
),
}, {
"resource_ids": raw(
make(
[]string,
51,
),
),
}, {
"credentials": raw(
"secret",
),
}, {
"status": raw(
"active",
),
},
} {
params["data_source_id"] = raw("ds1")
_, err = op.Build(params)
require.Error(t, err)
}
get, _ := Builtin().Get("data_source.get")
assert.JSONEq(t, `{"data":{"resource_ids":["a","b"]}}`, projectJSON(t, get, `{
"config": {
"resource_ids": [
"a",
"b"
],
"credentials": {
"token": "secret"
},
"settings": {
"key": "secret"
}
}
}`))
resources, _ := Builtin().Get("data_source.list_resources")
call, err = resources.Build(map[string]json.RawMessage{"data_source_id": raw("ds1"), "parent_id": raw("folder")})
require.NoError(t, err)
assert.Equal(t, "/api/v1/datasource/ds1/resources?parent_id=folder", call.URI())
out := projectJSON(t, resources, `[
{
"external_id": "a",
"name": "Docs",
"has_children": true,
"url": "secret",
"metadata": {
"token": "secret"
}
}
]`)
assert.Contains(t, out, `"external_id":"a"`)
assert.NotContains(t, out, "secret")
}
func TestAgentSearchProviderCanReturnToDefault(t *testing.T) {
op, _ := Builtin().Get("agent.update")
call, err := op.Build(
map[string]json.RawMessage{
"agent_id": raw("a"),
"web_search_provider_id": raw(""),
"web_search_enabled": raw(false),
},
)
require.NoError(t, err)
assert.JSONEq(t, `{"web_search_provider_id":"","web_search_enabled":false}`, string(call.Body))
}
+870
View File
@@ -0,0 +1,870 @@
package operations
import (
"bytes"
"encoding/json"
"fmt"
"math"
"slices"
"sort"
"strconv"
"strings"
"academy/internal/types"
)
// Swagger extensions that put an operation in the catalog. They are written
// as swag annotations next to the handler, so the route, parameters and
// response shape come from the same document the HTTP API is described by:
//
// // @x-agent {"id":"knowledge.delete","risk":"destructive","target":"knowledge.get","label":"title"}
// // @x-agent-hint "Cannot be undone."
// // @Param id path string true "知识ID" extensions(x-agent=knowledge_id)
//
// Exposure is opt-in at every level. An operation without x-agent is not in
// the catalog; a parameter without x-agent cannot be set by the model; a
// response field without x-agent (set with an `extensions:"x-agent"` struct
// tag) never reaches the model. x-agent-hint on an operation is guidance for
// the model; it replaces the human-facing description in the catalog.
const (
// extAgent marks an operation, parameter or response field. On a
// parameter or field its value may be a string: the model-facing name.
extAgent = "x-agent"
// extAgentMaximum caps an integer parameter below what the API allows,
// to keep results within what the model context can use, or the length
// of a string list.
extAgentMaximum = "x-agent-maximum"
// extAgentMaxBytes raises the string-parameter byte cap up to
// maxAgentStringBytes. The default stays maxStringParamBytes.
extAgentMaxBytes = "x-agent-max-bytes"
// extAgentMaxRunes raises how much of one response string is projected,
// up to maxAgentFieldRunes. The default stays maxProjectedStringRunes.
extAgentMaxRunes = "x-agent-max-runes"
// extAgentKeys lists the keys of a free-form object field that are
// projected, separated by "|".
extAgentKeys = "x-agent-keys"
// extAgentDetail limits a response field to operations that return a
// single object, so a long field (a prompt, say) does not repeat on
// every item of a list.
extAgentDetail = "x-agent-detail"
// extAgentResponse keeps a field in responses and out of request
// parameters. Identifiers and computed counts are projected when the
// model reads an object, and are not something it may set on create.
extAgentResponse = "x-agent-response"
)
// agentItems is ItemTarget as written in x-agent:
// {"param":"knowledge_ids","target":"knowledge.get","as":"knowledge_id","label":"title"}.
type agentItems struct {
Param string `json:"param"`
Target string `json:"target"`
As string `json:"as"`
Label string `json:"label"`
}
// agentOperation is the value of x-agent on an operation.
type agentOperation struct {
ID string `json:"id"`
Risk Risk `json:"risk"`
// Target and Label declare the approval target of a mutation.
Target string `json:"target"`
Label string `json:"label"`
RequireCompleteTarget bool `json:"require_complete_target,omitempty"`
// LabelParam labels the approval of a creation that has no target.
LabelParam string `json:"label_param,omitempty"`
// Items also resolves each item of a batch for the approval.
Items *agentItems `json:"items,omitempty"`
// Root overrides the projected part of the response. By default it is
// "data" when the body has that envelope and the body itself otherwise.
Root *string `json:"root"`
MaxItems int `json:"max_items"`
// CatchAll names the last path segment that the router registers as a
// catch-all (*slug), which Swagger cannot express.
CatchAll string `json:"catch_all"`
// Role is the lowest workspace role the route accepts, when it differs
// from the default for the risk.
Role types.TenantRole `json:"role,omitempty"`
SystemAdmin bool `json:"system_admin,omitempty"`
// AlwaysConfirm asks before every call of a write; see Operation.
AlwaysConfirm bool `json:"always_confirm,omitempty"`
// Method picks one route when the handler's doc lists several (a legacy
// GET next to the POST, say); the others stay out of the catalog.
Method string `json:"method,omitempty"`
}
type specDocument struct {
BasePath string `json:"basePath"`
Paths map[string]map[string]json.RawMessage `json:"paths"`
Definitions map[string]*specSchema `json:"definitions"`
}
type specOperation struct {
Summary string `json:"summary"`
Description string `json:"description"`
Parameters []specParameter `json:"parameters"`
Responses map[string]specResponse `json:"responses"`
Agent json.RawMessage `json:"x-agent"`
Hint string `json:"x-agent-hint"`
}
type specParameter struct {
Name string `json:"name"`
In string `json:"in"`
Type string `json:"type"`
Description string `json:"description"`
Required bool `json:"required"`
Enum []any `json:"enum"`
Minimum *float64 `json:"minimum"`
Maximum *float64 `json:"maximum"`
Items *specSchema `json:"items"`
Schema *specSchema `json:"schema"`
Agent any `json:"x-agent"`
AgentMax string `json:"x-agent-maximum"`
AgentMaxBytes string `json:"x-agent-max-bytes"`
// AgentRequired makes an API-optional field mandatory for the model.
AgentRequired bool `json:"x-agent-required"`
}
type specResponse struct {
Schema *specSchema `json:"schema"`
}
type specSchema struct {
Ref string `json:"$ref"`
Type string `json:"type"`
Description string `json:"description"`
Items *specSchema `json:"items"`
Properties map[string]*specSchema `json:"properties"`
Required []string `json:"required"`
AllOf []*specSchema `json:"allOf"`
Enum []any `json:"enum"`
Minimum *float64 `json:"minimum"`
Maximum *float64 `json:"maximum"`
Agent any `json:"x-agent"`
AgentKeys string `json:"x-agent-keys"`
AgentMax string `json:"x-agent-maximum"`
AgentMaxBytes string `json:"x-agent-max-bytes"`
AgentMaxRunes string `json:"x-agent-max-runes"`
AgentDetail bool `json:"x-agent-detail"`
// AgentResponse projects the field and does not accept it as a parameter.
AgentResponse bool `json:"x-agent-response"`
// AgentRequired makes an API-optional field mandatory for the model.
AgentRequired bool `json:"x-agent-required"`
}
var specMethods = []string{"get", "post", "put", "patch", "delete"}
// FromSpec compiles the operations a Swagger 2.0 document marks with
// x-agent. The result still has to pass NewCatalog, which owns the safety
// rules (allowed API areas, risk versus method, approval targets).
func FromSpec(document []byte) ([]Operation, error) {
var doc specDocument
if err := json.Unmarshal(document, &doc); err != nil {
return nil, fmt.Errorf("parse swagger document: %w", err)
}
paths := make([]string, 0, len(doc.Paths))
for path := range doc.Paths {
paths = append(paths, path)
}
sort.Strings(paths)
var ops []Operation
for _, path := range paths {
for _, method := range specMethods {
raw, ok := doc.Paths[path][method]
if !ok {
continue
}
var sop specOperation
if err := json.Unmarshal(raw, &sop); err != nil {
return nil, fmt.Errorf("%s %s: %w", strings.ToUpper(method), path, err)
}
if len(sop.Agent) == 0 {
continue
}
op, skip, err := doc.compile(strings.ToUpper(method), path, sop)
if err != nil {
return nil, fmt.Errorf("%s %s: %w", strings.ToUpper(method), path, err)
}
if !skip {
ops = append(ops, op)
}
}
}
return ops, nil
}
// compile builds the operation for one route, or reports skip when the
// annotation names another of the handler's methods.
func (doc *specDocument) compile(method, path string, sop specOperation) (Operation, bool, error) {
var meta agentOperation
dec := json.NewDecoder(bytes.NewReader(sop.Agent))
dec.DisallowUnknownFields()
if err := dec.Decode(&meta); err != nil {
return Operation{}, false, fmt.Errorf("%s: %w", extAgent, err)
}
if meta.Method != "" {
if !slices.Contains(specMethods, strings.ToLower(meta.Method)) {
return Operation{}, false, fmt.Errorf("%s: unknown method %q", extAgent, meta.Method)
}
if !strings.EqualFold(meta.Method, method) {
return Operation{}, true, nil
}
}
op, err := doc.compileOperation(method, path, sop, meta)
return op, false, err
}
func (doc *specDocument) compileOperation(
method, path string, sop specOperation, meta agentOperation,
) (Operation, error) {
route, err := ginRoute(doc.BasePath, path, meta.CatchAll)
if err != nil {
return Operation{}, fmt.Errorf("%s: %w", extAgent, err)
}
op := Operation{
ID: meta.ID,
Summary: strings.TrimSpace(sop.Summary),
Description: strings.TrimSpace(sop.Hint),
Risk: meta.Risk,
Method: method,
Route: route,
Role: meta.Role,
SystemAdmin: meta.SystemAdmin,
LabelParam: meta.LabelParam,
AlwaysConfirm: meta.AlwaysConfirm,
}
if op.Description == "" {
op.Description = strings.TrimSpace(sop.Description)
}
if meta.Target != "" || meta.Label != "" || meta.RequireCompleteTarget {
if meta.Target == "" || meta.Label == "" {
return Operation{}, fmt.Errorf("%s: target and label go together", extAgent)
}
op.Target = &Target{Operation: meta.Target, Label: meta.Label, RequireComplete: meta.RequireCompleteTarget}
}
if items := meta.Items; items != nil {
if op.Target == nil {
return Operation{}, fmt.Errorf("%s: items needs a target", extAgent)
}
if items.Param == "" || items.Target == "" || items.As == "" || items.Label == "" {
return Operation{}, fmt.Errorf("%s: items needs param, target, as and label", extAgent)
}
op.Target.Items = &ItemTarget{Param: items.Param, Operation: items.Target, As: items.As, Label: items.Label}
}
for _, sp := range sop.Parameters {
params, err := doc.params(sp)
if err != nil {
return Operation{}, fmt.Errorf("param %q: %w", sp.Name, err)
}
op.Params = append(op.Params, params...)
}
result, err := doc.result(sop.Responses, meta)
if err != nil {
return Operation{}, err
}
op.Result = result
return op, nil
}
// ginRoute turns "/knowledge/{id}" under basePath into "/api/v1/knowledge/:id".
// catchAll, when set, names the last segment, which becomes "*name".
func ginRoute(basePath, path, catchAll string) (string, error) {
segments := strings.Split(path, "/")
for i, seg := range segments {
if strings.HasPrefix(seg, "{") && strings.HasSuffix(seg, "}") {
name := seg[1 : len(seg)-1]
if name == catchAll {
if i != len(segments)-1 {
return "", fmt.Errorf("catch_all %q must be the last path segment", catchAll)
}
segments[i] = "*" + name
continue
}
segments[i] = ":" + name
}
}
route := strings.TrimRight(basePath, "/") + strings.Join(segments, "/")
if catchAll != "" && !strings.HasSuffix(route, "/*"+catchAll) {
return "", fmt.Errorf("catch_all %q is not a path segment", catchAll)
}
return route, nil
}
// agentName reports whether ext exposes an element and under which name.
func agentName(ext any, fallback string) (string, bool, error) {
switch v := ext.(type) {
case nil:
return "", false, nil
case bool:
return fallback, v, nil
case string:
if v == "" {
return "", false, fmt.Errorf("%s needs a name", extAgent)
}
return v, true, nil
default:
return "", false, fmt.Errorf("%s must be true or a name", extAgent)
}
}
func (doc *specDocument) params(sp specParameter) ([]Param, error) {
if sp.In == string(InBody) {
return doc.bodyParams(sp)
}
name, exposed, err := agentName(sp.Agent, sp.Name)
if err != nil {
return nil, err
}
if !exposed {
if sp.Required {
return nil, fmt.Errorf("required by the API but not exposed with %s", extAgent)
}
return nil, nil
}
if sp.In != string(InPath) && sp.In != string(InQuery) {
return nil, fmt.Errorf("%s parameters are not supported", sp.In)
}
p := Param{
Name: name,
In: Location(sp.In),
Key: sp.Name,
Required: sp.Required || sp.AgentRequired,
AllowEmpty: sp.AgentRequired && !sp.Required,
Description: strings.TrimSpace(sp.Description),
}
shape := &specSchema{Type: sp.Type, Items: sp.Items, Enum: sp.Enum, Minimum: sp.Minimum, Maximum: sp.Maximum}
if err := doc.typeParam(&p, shape, sp.AgentMax, sp.AgentMaxBytes); err != nil {
return nil, err
}
return []Param{p}, nil
}
// bodyParams exposes the top-level fields of a JSON body that carry
// x-agent; the model sets them as flat parameters.
func (doc *specDocument) bodyParams(sp specParameter) ([]Param, error) {
if sp.Schema == nil {
return nil, nil
}
obj, err := doc.object(sp.Schema)
if err != nil {
return nil, err
}
required := map[string]bool{}
for _, key := range obj.Required {
required[key] = true
}
var out []Param
for _, key := range sortedKeys(obj.Properties) {
prop := obj.Properties[key]
shape, err := doc.resolve(prop)
if err != nil {
return nil, err
}
// An object is not one parameter. Its tagged scalars are, and the
// wire key keeps the path so the request nests them again.
if shape != nil && shape.Type != "array" && (shape.Type == "object" || len(shape.Properties) > 0) {
nested, err := doc.flattenBodyObject(shape, key, sp.Required)
if err != nil {
return nil, err
}
if len(nested) > 0 {
out = append(out, nested...)
continue
}
}
if prop.AgentResponse {
if sp.Required && required[key] {
return nil, fmt.Errorf("body field %q is required but marked %s", key, extAgentResponse)
}
continue
}
name, exposed, err := agentName(prop.Agent, key)
if err != nil {
return nil, fmt.Errorf("body field %q: %w", key, err)
}
if !exposed {
if sp.Required && required[key] {
return nil, fmt.Errorf("body field %q is required but not exposed with %s", key, extAgent)
}
continue
}
p := Param{
Name: name,
In: InBody,
Key: key,
Required: (sp.Required && required[key]) || prop.AgentRequired,
AllowEmpty: prop.AgentRequired && !required[key],
Description: strings.TrimSpace(prop.Description),
}
if err := doc.typeParam(&p, shape, prop.AgentMax, prop.AgentMaxBytes); err != nil {
return nil, fmt.Errorf("body field %q: %w", key, err)
}
out = append(out, p)
}
return out, nil
}
// flattenBodyObject turns the tagged scalars inside an object into body
// parameters. The wire key is the dotted JSON path.
func (doc *specDocument) flattenBodyObject(obj *specSchema, prefix string, bodyRequired bool) ([]Param, error) {
required := map[string]bool{}
for _, key := range obj.Required {
required[key] = true
}
var out []Param
for _, key := range sortedKeys(obj.Properties) {
prop := obj.Properties[key]
path := prefix + "." + key
shape, err := doc.resolve(prop)
if err != nil {
return nil, err
}
if shape != nil && shape.Type != "array" && (shape.Type == "object" || len(shape.Properties) > 0) {
nested, err := doc.flattenBodyObject(shape, path, bodyRequired)
if err != nil {
return nil, err
}
if len(nested) > 0 {
out = append(out, nested...)
continue
}
}
if prop.AgentResponse {
if bodyRequired && required[key] {
return nil, fmt.Errorf("body field %q is required but marked %s", path, extAgentResponse)
}
continue
}
name, exposed, err := agentName(prop.Agent, key)
if err != nil {
return nil, fmt.Errorf("body field %q: %w", path, err)
}
if !exposed {
if bodyRequired && required[key] {
return nil, fmt.Errorf("body field %q is required but not exposed with %s", path, extAgent)
}
continue
}
p := Param{
Name: name,
In: InBody,
Key: path,
Required: (bodyRequired && required[key]) || prop.AgentRequired,
AllowEmpty: prop.AgentRequired && !required[key],
Description: strings.TrimSpace(prop.Description),
}
if err := doc.typeParam(&p, shape, prop.AgentMax, prop.AgentMaxBytes); err != nil {
return nil, fmt.Errorf("body field %q: %w", path, err)
}
out = append(out, p)
}
return out, nil
}
func (doc *specDocument) typeParam(p *Param, shape *specSchema, agentMax, agentMaxBytes string) error {
switch shape.Type {
case "string":
p.Type = TypeString
p.Enum = enumStrings(shape.Enum)
case "integer":
p.Type = TypeInteger
case "number":
p.Type = TypeNumber
case "boolean":
p.Type = TypeBoolean
case "array":
items, err := doc.resolve(shape.Items)
if err != nil {
return err
}
switch {
case items != nil && items.Type == "string":
p.Type = TypeStringList
p.Enum = enumStrings(items.Enum)
case items != nil && items.Type == "integer":
p.Type = TypeIntegerList
default:
return fmt.Errorf("only arrays of strings or integers are supported")
}
default:
return fmt.Errorf("unsupported type %q", shape.Type)
}
if p.Type == TypeString || p.Type == TypeStringList {
if err := boundString(p, agentMaxBytes); err != nil {
return err
}
} else if agentMaxBytes != "" {
return fmt.Errorf("%s applies to strings only", extAgentMaxBytes)
}
switch p.Type {
case TypeInteger:
return boundInteger(p, shape.Minimum, shape.Maximum, agentMax)
case TypeStringList, TypeIntegerList:
if agentMax == "" {
return nil
}
limit, err := strconv.Atoi(agentMax)
if err != nil || limit < 1 || limit > defaultMaxListItems {
return fmt.Errorf("%s %q must be between 1 and %d items", extAgentMaximum, agentMax, defaultMaxListItems)
}
p.MaxItems = limit
return nil
}
if agentMax != "" {
return fmt.Errorf("%s applies to integers and lists only", extAgentMaximum)
}
return nil
}
func boundString(p *Param, agentMaxBytes string) error {
if agentMaxBytes == "" {
return nil
}
limit, err := strconv.Atoi(agentMaxBytes)
if err != nil || limit < 1 || limit > maxAgentStringBytes {
return fmt.Errorf("%s %q must be an integer from 1 to %d", extAgentMaxBytes, agentMaxBytes, maxAgentStringBytes)
}
p.MaxBytes = limit
return nil
}
func boundInteger(p *Param, minimum, maximum *float64, agentMax string) error {
if minimum == nil && maximum == nil && agentMax == "" {
return nil
}
lower, upper := 0, math.MaxInt32
if minimum != nil {
lower = int(*minimum)
}
if maximum != nil {
upper = int(*maximum)
}
if agentMax != "" {
limit, err := strconv.Atoi(agentMax)
if err != nil || limit < lower || limit > upper {
return fmt.Errorf("%s %q must be an integer within the API bounds", extAgentMaximum, agentMax)
}
upper = limit
}
p.Minimum, p.Maximum = lower, upper
return nil
}
func enumStrings(values []any) []string {
if len(values) == 0 {
return nil
}
out := make([]string, 0, len(values))
for _, v := range values {
out = append(out, fmt.Sprint(v))
}
return out
}
func (doc *specDocument) result(responses map[string]specResponse, meta agentOperation) (Result, error) {
var body *specSchema
for _, code := range []string{"200", "201", "202"} {
if r, ok := responses[code]; ok && r.Schema != nil {
body = r.Schema
break
}
}
if body == nil {
return Result{}, fmt.Errorf("no success response schema")
}
top, err := doc.resolve(body)
if err != nil {
return Result{}, err
}
root := ""
switch {
case meta.Root != nil:
root = *meta.Root
case top.Type == "object" && top.Properties["data"] != nil:
root = "data"
}
out := Result{Root: root, MaxItems: meta.MaxItems}
// Meta is the x-agent siblings of the value at root, including when root
// is nested (data.data). Their From paths stay relative to the body.
parent := top
prefix := ""
segments := splitPath(root)
target := top
for i, key := range segments {
if target.Type != "object" || target.Properties[key] == nil {
return Result{}, fmt.Errorf("response has no %q", root)
}
if i == len(segments)-1 {
parent = target
break
}
if prefix != "" {
prefix += "."
}
prefix += key
if target, err = doc.resolve(target.Properties[key]); err != nil {
return Result{}, err
}
}
if len(segments) > 0 {
if target, err = doc.resolve(parent.Properties[segments[len(segments)-1]]); err != nil {
return Result{}, err
}
}
if target.Type == "array" {
out.List = true
if target, err = doc.resolve(target.Items); err != nil {
return Result{}, err
}
}
if target == nil || target.Type != "object" {
return Result{}, fmt.Errorf("response %q is not an object or a list of objects", root)
}
if out.Fields, err = doc.fields(target, "", out.List); err != nil {
return Result{}, err
}
if len(out.Fields) == 0 {
return Result{}, fmt.Errorf("response %q exposes no fields; tag them with %s", root, extAgent)
}
if root != "" {
envelope := *parent
envelope.Properties = map[string]*specSchema{}
last := segments[len(segments)-1]
for key, prop := range parent.Properties {
if key != last {
envelope.Properties[key] = prop
}
}
metaPrefix := ""
if prefix != "" {
metaPrefix = prefix + "."
}
if out.Meta, err = doc.fields(&envelope, metaPrefix, false); err != nil {
return Result{}, err
}
}
return out, nil
}
// fields lists the projected fields of obj. Nested objects marked with
// x-agent are flattened: their marked fields are named on their own. A list of
// objects keeps each element's marked fields under the list's name. list
// drops fields marked x-agent-detail.
func (doc *specDocument) fields(obj *specSchema, prefix string, list bool) ([]Field, error) {
var out []Field
for _, key := range sortedKeys(obj.Properties) {
raw := obj.Properties[key]
name, exposed, err := agentName(raw.Agent, key)
if err != nil {
return nil, fmt.Errorf("field %q: %w", prefix+key, err)
}
if !exposed {
if raw.AgentDetail {
return nil, fmt.Errorf("field %q: %s needs %s", prefix+key, extAgentDetail, extAgent)
}
continue
}
if list && raw.AgentDetail {
continue
}
from := prefix + key
runes, err := fieldRunes(raw)
if err != nil {
return nil, fmt.Errorf("field %q: %w", from, err)
}
prop, err := doc.resolve(raw)
if err != nil {
return nil, err
}
switch {
case isScalar(prop.Type):
if runes > 0 && prop.Type != "string" {
return nil, fmt.Errorf("field %q: %s applies to strings", from, extAgentMaxRunes)
}
out = append(out, Field{From: from, As: name, MaxRunes: runes})
case prop.Type == "array":
items, err := doc.resolve(prop.Items)
if err != nil {
return nil, err
}
if items != nil && len(items.Properties) > 0 {
if runes > 0 {
return nil, fmt.Errorf("field %q: %s applies to strings", from, extAgentMaxRunes)
}
elem, err := doc.fields(items, "", list)
if err != nil {
return nil, fmt.Errorf("field %q: %w", from, err)
}
if len(elem) == 0 {
return nil, fmt.Errorf("field %q: list items expose no fields", from)
}
for _, f := range elem {
if len(f.Items) > 0 {
return nil, fmt.Errorf("field %q: list items cannot hold lists of objects", from)
}
}
out = append(out, Field{From: from, As: name, Items: elem})
continue
}
if items == nil || !isScalar(items.Type) {
return nil, fmt.Errorf("field %q: only lists of scalars or of objects with %s fields are projected",
from, extAgent)
}
if runes > 0 && items.Type != "string" {
return nil, fmt.Errorf("field %q: %s applies to strings", from, extAgentMaxRunes)
}
out = append(out, Field{From: from, As: name, MaxRunes: runes})
case len(prop.Properties) > 0:
if runes > 0 {
return nil, fmt.Errorf("field %q: %s applies to strings", from, extAgentMaxRunes)
}
if name != key {
return nil, fmt.Errorf("field %q: objects are flattened, so name their fields instead", from)
}
nested, err := doc.fields(prop, from+".", list)
if err != nil {
return nil, err
}
if len(nested) == 0 {
return nil, fmt.Errorf("field %q: object exposes no fields", from)
}
out = append(out, nested...)
case raw.AgentKeys != "":
for _, sub := range strings.Split(raw.AgentKeys, "|") {
if sub = strings.TrimSpace(sub); sub != "" {
if strings.Contains(sub, ".") {
out = append(out, Field{From: from, MapKey: sub, As: sub})
} else {
out = append(out, Field{From: from + "." + sub, As: sub})
}
}
}
default:
return nil, fmt.Errorf("field %q: free-form object needs %s", from, extAgentKeys)
}
}
return out, nil
}
func fieldRunes(raw *specSchema) (int, error) {
if raw == nil || raw.AgentMaxRunes == "" {
return 0, nil
}
n, err := strconv.Atoi(raw.AgentMaxRunes)
if err != nil || n < 1 || n > maxAgentFieldRunes {
return 0, fmt.Errorf("%s %q must be an integer from 1 to %d",
extAgentMaxRunes, raw.AgentMaxRunes, maxAgentFieldRunes)
}
return n, nil
}
func isScalar(t string) bool {
return t == "string" || t == "integer" || t == "number" || t == "boolean"
}
// resolve follows $ref and merges allOf into one schema. Extensions on the
// referencing schema stay with the caller; the merged result carries the
// structure only.
func (doc *specDocument) resolve(s *specSchema) (*specSchema, error) {
return doc.resolveDepth(s, 0)
}
const maxSchemaDepth = 32
func (doc *specDocument) resolveDepth(s *specSchema, depth int) (*specSchema, error) {
if s == nil {
return nil, nil
}
if depth > maxSchemaDepth {
return nil, fmt.Errorf("schema nesting is too deep")
}
if s.Ref != "" {
name := strings.TrimPrefix(s.Ref, "#/definitions/")
def, ok := doc.Definitions[name]
if !ok {
return nil, fmt.Errorf("undefined schema %q", s.Ref)
}
return doc.resolveDepth(def, depth+1)
}
if len(s.AllOf) == 0 {
return s, nil
}
merged := &specSchema{Type: s.Type, Description: s.Description, Properties: map[string]*specSchema{}}
for key, prop := range s.Properties {
merged.Properties[key] = prop
}
for _, part := range s.AllOf {
r, err := doc.resolveDepth(part, depth+1)
if err != nil {
return nil, err
}
if r == nil {
continue
}
if merged.Type == "" || (merged.Type == "object" && r.Type != "") {
merged.Type = r.Type
}
if r.Items != nil {
merged.Items = r.Items
}
if r.Enum != nil {
merged.Enum = r.Enum
}
merged.Required = append(merged.Required, r.Required...)
for key, prop := range r.Properties {
merged.Properties[key] = overlay(merged.Properties[key], prop)
}
}
if len(merged.Properties) == 0 {
merged.Properties = nil
}
return merged, nil
}
// overlay lets a composed property (DataResponse{data=X}) replace the base
// property's type while keeping the base's extensions.
func overlay(base, override *specSchema) *specSchema {
if base == nil {
return override
}
out := *override
if out.Agent == nil {
out.Agent = base.Agent
}
if out.AgentKeys == "" {
out.AgentKeys = base.AgentKeys
}
out.AgentDetail = out.AgentDetail || base.AgentDetail
return &out
}
func splitPath(path string) []string {
if path == "" {
return nil
}
return strings.Split(path, ".")
}
func sortedKeys(m map[string]*specSchema) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
func (doc *specDocument) object(s *specSchema) (*specSchema, error) {
obj, err := doc.resolve(s)
if err != nil {
return nil, err
}
if obj == nil || obj.Type != "object" {
return nil, fmt.Errorf("body is not an object")
}
return obj, nil
}
+656
View File
@@ -0,0 +1,656 @@
package operations
import (
"encoding/json"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// testSpec is a trimmed swag document: an envelope, a domain type with
// tagged and untagged fields, and three annotated operations.
const testSpec = `{
"basePath": "/api/v1",
"definitions": {
"handler.PageResponse": {"type": "object", "properties": {
"success": {"type": "boolean"},
"data": {},
"total": {"type": "integer", "x-agent": true}
}},
"handler.DataResponse": {"type": "object", "properties": {
"success": {"type": "boolean"}, "data": {}
}},
"types.Status": {"type": "string", "enum": ["ok", "failed"]},
"types.Strategy": {"type": "object", "properties": {
"vector_enabled": {"type": "boolean", "x-agent": true},
"secret_mode": {"type": "string"}
}},
"types.Doc": {"type": "object", "properties": {
"id": {"type": "string", "x-agent": "knowledge_id"},
"title": {"type": "string", "x-agent": true},
"status": {"allOf": [{"$ref": "#/definitions/types.Status"}], "x-agent": true},
"strategy": {"allOf": [{"$ref": "#/definitions/types.Strategy"}], "x-agent": true},
"details": {"type": "object", "x-agent": true, "x-agent-keys": "via|trigger"},
"tags": {"type": "array", "items": {"type": "string"}, "x-agent": true},
"file_path": {"type": "string"},
"tenant_id": {"type": "integer"}
}}
},
"paths": {
"/knowledge-bases/{id}/docs": {"get": {
"summary": "List documents",
"description": "Human-facing text.",
"x-agent": {"id": "doc.list", "risk": "read"},
"x-agent-hint": "Model-facing text.",
"parameters": [
{"name": "id", "in": "path", "type": "string", "required": true, "description": "KB",
"x-agent": "knowledge_base_id"},
{"name": "status", "in": "query", "type": "string", "enum": ["ok", "failed"], "description": "S",
"x-agent": true},
{"name": "page_size", "in": "query", "type": "integer", "minimum": 1, "maximum": 1000,
"description": "N", "x-agent": true, "x-agent-maximum": "50"},
{"name": "agent_id", "in": "query", "type": "string", "description": "not for the model"}
],
"responses": {"200": {"schema": {"allOf": [
{"$ref": "#/definitions/handler.PageResponse"},
{"type": "object", "properties": {"data": {"type": "array", "items": {"$ref": "#/definitions/types.Doc"}}}}
]}}}
}},
"/knowledge/{id}": {
"get": {
"summary": "Get a document",
"x-agent": {"id": "doc.get", "risk": "read"},
"parameters": [{"name": "id", "in": "path", "type": "string", "required": true, "description": "D",
"x-agent": "knowledge_id"}],
"responses": {"200": {"schema": {"allOf": [
{"$ref": "#/definitions/handler.DataResponse"},
{"type": "object", "properties": {"data": {"$ref": "#/definitions/types.Doc"}}}
]}}}
},
"delete": {
"summary": "Delete a document",
"x-agent": {"id": "doc.delete", "risk": "destructive", "target": "doc.get", "label": "title"},
"parameters": [{"name": "id", "in": "path", "type": "string", "required": true, "description": "D",
"x-agent": "knowledge_id"}],
"responses": {"200": {"schema": {"type": "object", "properties": {
"message": {"type": "string", "x-agent": true}
}}}}
}
},
"/knowledge/{id}/raw": {"get": {
"summary": "Not for agents",
"parameters": [{"name": "id", "in": "path", "type": "string", "required": true}],
"responses": {"200": {"schema": {"type": "string"}}}
}}
}
}`
func compileTestSpec(t *testing.T) *Catalog {
t.Helper()
ops, err := FromSpec([]byte(testSpec))
require.NoError(t, err)
catalog, err := NewCatalog(ops...)
require.NoError(t, err)
return catalog
}
func TestFromSpecCompilesAnnotatedOperations(t *testing.T) {
catalog := compileTestSpec(t)
require.Len(t, catalog.All(), 3, "operations without x-agent stay out")
list, ok := catalog.Get("doc.list")
require.True(t, ok)
assert.Equal(t, http.MethodGet, list.Method)
assert.Equal(t, "/api/v1/knowledge-bases/:id/docs", list.Route)
assert.Equal(t, "List documents", list.Summary)
assert.Equal(t, "Model-facing text.", list.Description, "the hint replaces the human description")
require.Len(t, list.Params, 3, "agent_id is not exposed")
kb, _ := list.Param("knowledge_base_id")
assert.Equal(t, Param{
Name: "knowledge_base_id", In: InPath, Key: "id", Type: TypeString, Required: true, Description: "KB",
}, kb)
status, _ := list.Param("status")
assert.Equal(t, []string{"ok", "failed"}, status.Enum)
size, _ := list.Param("page_size")
assert.Equal(t, 1, size.Minimum)
assert.Equal(t, 50, size.Maximum, "x-agent-maximum caps the API bound")
assert.Equal(t, "data", list.Result.Root)
assert.True(t, list.Result.List)
assert.ElementsMatch(t, []Field{
{From: "details.trigger", As: "trigger"},
{From: "details.via", As: "via"},
{From: "id", As: "knowledge_id"},
{From: "status", As: "status"},
{From: "strategy.vector_enabled", As: "vector_enabled"},
{From: "tags", As: "tags"},
{From: "title", As: "title"},
}, list.Result.Fields)
assert.Equal(t, []Field{{From: "total", As: "total"}}, list.Result.Meta)
get, _ := catalog.Get("doc.get")
assert.False(t, get.Result.List)
assert.Empty(t, get.Result.Meta, "the plain envelope marks nothing")
del, _ := catalog.Get("doc.delete")
assert.Equal(t, &Target{Operation: "doc.get", Label: "title"}, del.Target)
assert.Equal(t, "", del.Result.Root, "no data envelope projects the body")
}
func TestFromSpecProjectsOnlyTaggedFields(t *testing.T) {
list, _ := compileTestSpec(t).Get("doc.list")
body := `{"success":true,"total":1,"data":[{"id":"k1","title":"A","status":"failed",
"strategy":{"vector_enabled":true,"secret_mode":"x"},"details":{"via":"agent","token":"t"},
"file_path":"s3://secret","tenant_id":9}]}`
projected, err := list.Project([]byte(body))
require.NoError(t, err)
out, _ := json.Marshal(projected)
assert.JSONEq(t, `{"data":[{"knowledge_id":"k1","title":"A","status":"failed",
"vector_enabled":true,"via":"agent"}],"meta":{"total":1}}`, string(out))
}
func TestFromSpecRejectsBadAnnotations(t *testing.T) {
cases := map[string]struct{ from, to string }{
"unknown x-agent key": {
`{"id": "doc.get", "risk": "read"}`, `{"id": "doc.get", "risk": "read", "rsik": "write"}`,
},
"target without label": {
`"target": "doc.get", "label": "title"`, `"target": "doc.get"`,
},
"required param not exposed": {
`"description": "D",
"x-agent": "knowledge_id"}],
"responses": {"200": {"schema": {"allOf"`,
`"description": "D"}],
"responses": {"200": {"schema": {"allOf"`,
},
"agent maximum above the API maximum": {`"x-agent-maximum": "50"`, `"x-agent-maximum": "5000"`},
"free-form object without keys": {`"x-agent": true, "x-agent-keys": "via|trigger"`, `"x-agent": true`},
"renamed object": {
`"strategy": {"allOf": [{"$ref": "#/definitions/types.Strategy"}], "x-agent": true}`,
`"strategy": {"allOf": [{"$ref": "#/definitions/types.Strategy"}], "x-agent": "strategy_flags"}`,
},
"list of objects without exposed fields": {
`"tags": {"type": "array", "items": {"type": "string"}, "x-agent": true}`,
`"tags": {"type": "array", "items": {"type": "object", ` +
`"properties": {"secret": {"type": "string"}}}, "x-agent": true}`,
},
"length cap on a list of objects": {
`"tags": {"type": "array", "items": {"type": "string"}, "x-agent": true}`,
`"tags": {"type": "array", "items": {"$ref": "#/definitions/types.Strategy"}, ` +
`"x-agent": true, "x-agent-max-runes": "10"}`,
},
"nothing exposed": {
`"message": {"type": "string", "x-agent": true}`, `"message": {"type": "string"}`,
},
"undefined schema": {`"$ref": "#/definitions/types.Status"`, `"$ref": "#/definitions/types.Missing"`},
"catch-all before the last segment": {
`{"id": "doc.list", "risk": "read"}`, `{"id": "doc.list", "risk": "read", "catch_all": "id"}`,
},
"items without a target": {
`{"id": "doc.get", "risk": "read"}`,
`{"id": "doc.get", "risk": "read", "items": {"param": "a", "target": "b", "as": "c", "label": "d"}}`,
},
"items missing a key": {
`"target": "doc.get", "label": "title"`,
`"target": "doc.get", "label": "title", "items": {"param": "knowledge_ids", "target": "doc.get"}`,
},
"catch-all naming no segment": {
`{"id": "doc.get", "risk": "read"}`, `{"id": "doc.get", "risk": "read", "catch_all": "slug"}`,
},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
require.Equal(t, 1, strings.Count(testSpec, tc.from), "fixture edit must be unambiguous")
_, err := FromSpec([]byte(strings.Replace(testSpec, tc.from, tc.to, 1)))
assert.Error(t, err)
})
}
}
func TestFromSpecMethodPicksOneOfTheHandlersRoutes(t *testing.T) {
route := func(method string) string {
return `"` + method + `": {
"summary": "Search",
"x-agent": {"id": "kb.search", "risk": "probe", "method": "post"},
"parameters": [
{"name": "id", "in": "path", "type": "string", "required": true, "description": "KB",
"x-agent": "knowledge_base_id"},
{"name": "request", "in": "body", "required": true, "schema": {"type": "object", "properties": {
"query_text": {"type": "string", "description": "Q", "x-agent": true, "x-agent-required": true},
"vector_threshold": {"type": "number", "description": "T", "x-agent": true}
}}}
],
"responses": {"200": {"schema": {"type": "object", "properties": {
"data": {"type": "array", "items": {"type": "object", "properties": {
"content": {"type": "string", "x-agent": true}
}}}
}}}}
}`
}
spec := `{"basePath": "/api/v1", "paths": {"/knowledge-bases/{id}/hybrid-search": {` +
route("post") + `, ` + route("get") + `}}}`
ops, err := FromSpec([]byte(spec))
require.NoError(t, err)
require.Len(t, ops, 1, "the GET route that shares the doc stays out")
assert.Equal(t, http.MethodPost, ops[0].Method)
threshold, ok := ops[0].Param("vector_threshold")
require.True(t, ok)
assert.Equal(t, TypeNumber, threshold.Type)
_, err = NewCatalog(ops...)
require.NoError(t, err)
_, err = FromSpec([]byte(strings.ReplaceAll(spec, `"method": "post"`, `"method": "fetch"`)))
assert.ErrorContains(t, err, "unknown method")
}
func TestFromSpecAgentRequired(t *testing.T) {
spec := strings.Replace(testSpec,
`"description": "S",
"x-agent": true}`,
`"description": "S",
"x-agent": true, "x-agent-required": true}`, 1)
ops, err := FromSpec([]byte(spec))
require.NoError(t, err)
for _, op := range ops {
if op.ID == "doc.list" {
status, _ := op.Param("status")
assert.True(t, status.Required, "x-agent-required makes an optional param mandatory for the model")
}
}
}
func TestFromSpecSkipsResponseOnlyBodyFields(t *testing.T) {
spec := `{
"paths": {
"/api/v1/knowledge-bases": {
"post": {
"summary": "Create",
"parameters": [{"name": "body", "in": "body", "required": true, "schema": {"$ref": "#/definitions/KB"}}],
"responses": {"201": {"schema": {"$ref": "#/definitions/KB"}}},
"x-agent": {"id": "knowledge_base.create", "risk": "write", "label_param": "name"},
"x-agent-hint": "Creates one."
}
}
},
"definitions": {
"KB": {
"type": "object",
"required": ["name"],
"properties": {
"name": {"type": "string", "description": "Name", "x-agent": true},
"id": {"type": "string", "description": "ID", "x-agent": "knowledge_base_id", "x-agent-response": true},
"indexing_strategy": {
"type": "object",
"description": "Indexing",
"x-agent": true,
"x-agent-response": true,
"properties": {"vector": {"type": "boolean", "description": "Vector", "x-agent": true}}
}
}
}
}
}`
ops, err := FromSpec([]byte(spec))
require.NoError(t, err)
require.Len(t, ops, 1)
assert.ElementsMatch(t, []string{"name", "vector"}, paramNames(ops[0]))
_, ok := ops[0].Param("knowledge_base_id")
assert.False(t, ok, "a response-only identifier is not a create parameter")
_, ok = ops[0].Param("indexing_strategy")
assert.False(t, ok, "the indexing object itself is not a parameter")
vector, ok := ops[0].Param("vector")
require.True(t, ok)
assert.Equal(t, "indexing_strategy.vector", vector.Key)
call, err := ops[0].Build(map[string]json.RawMessage{
"name": json.RawMessage(`"产品文档"`),
"vector": json.RawMessage(`true`),
})
require.NoError(t, err)
assert.JSONEq(t, `{"name":"产品文档","indexing_strategy":{"vector":true}}`, string(call.Body))
id, ok := fieldByFrom(ops[0].Result.Fields, "id")
require.True(t, ok)
assert.Equal(t, "knowledge_base_id", id.As)
}
func paramNames(op Operation) []string {
names := make([]string, 0, len(op.Params))
for _, p := range op.Params {
names = append(names, p.Name)
}
return names
}
func fieldByFrom(fields []Field, from string) (Field, bool) {
for _, field := range fields {
if field.From == from {
return field, true
}
}
return Field{}, false
}
func TestFromSpecMarksCatchAllSegment(t *testing.T) {
spec := strings.Replace(testSpec,
`{"id": "doc.get", "risk": "read"}`, `{"id": "doc.get", "risk": "read", "catch_all": "id"}`, 1)
ops, err := FromSpec([]byte(spec))
require.NoError(t, err)
catalog, err := NewCatalog(ops...)
require.NoError(t, err)
get, _ := catalog.Get("doc.get")
assert.Equal(t, "/api/v1/knowledge/*id", get.Route)
call, err := get.Build(map[string]json.RawMessage{"knowledge_id": json.RawMessage(`"a/b"`)})
require.NoError(t, err)
assert.Equal(t, "/api/v1/knowledge/a/b", call.Path, "a catch-all keeps its slashes")
del, _ := catalog.Get("doc.delete")
assert.Equal(t, "/api/v1/knowledge/:id", del.Route, "the mark is per operation")
}
func TestFromSpecKeepsCatalogSafetyRules(t *testing.T) {
forbidden := strings.Replace(testSpec, `"/knowledge/{id}": {`, `"/api-keys/{id}": {`, 1)
ops, err := FromSpec([]byte(forbidden))
require.NoError(t, err)
_, err = NewCatalog(ops...)
assert.ErrorContains(t, err, "outside the areas an agent may reach")
readAsDelete := strings.Replace(testSpec, `"risk": "destructive"`, `"risk": "read"`, 1)
ops, err = FromSpec([]byte(readAsDelete))
require.NoError(t, err)
_, err = NewCatalog(ops...)
assert.Error(t, err)
}
var agentAnnotation = regexp.MustCompile(`^\s*//\s*@x-agent\s+(\{.*\})\s*$`)
// TestBuiltinMatchesHandlerAnnotations catches an annotation edited without
// regenerating the Swagger document (make docs).
func TestBuiltinMatchesHandlerAnnotations(t *testing.T) {
declared := map[string]agentOperation{}
root := filepath.Join("..", "..", "handler")
err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return err
}
src, err := os.ReadFile(path)
if err != nil {
return err
}
for _, line := range strings.Split(string(src), "\n") {
m := agentAnnotation.FindStringSubmatch(line)
if m == nil {
continue
}
var meta agentOperation
require.NoError(t, json.Unmarshal([]byte(m[1]), &meta), path)
declared[meta.ID] = meta
}
return nil
})
require.NoError(t, err)
require.NotEmpty(t, declared)
built := map[string]agentOperation{}
methods := map[string]string{}
for _, op := range Builtin().All() {
methods[op.ID] = op.Method
meta := agentOperation{
ID: op.ID,
Risk: op.Risk,
LabelParam: op.LabelParam,
AlwaysConfirm: op.AlwaysConfirm,
SystemAdmin: op.SystemAdmin,
}
if op.Target != nil {
meta.Target, meta.Label = op.Target.Operation, op.Target.Label
meta.RequireCompleteTarget = op.Target.RequireComplete
if it := op.Target.Items; it != nil {
meta.Items = &agentItems{Param: it.Param, Target: it.Operation, As: it.As, Label: it.Label}
}
}
if i := strings.LastIndex(op.Route, "/*"); i >= 0 {
meta.CatchAll = op.Route[i+2:]
}
if op.Role != defaultRole(op.Risk) {
meta.Role = op.Role
}
built[op.ID] = meta
}
for id, meta := range declared {
if meta.Method != "" {
assert.True(t, strings.EqualFold(meta.Method, methods[id]),
"%s names method %s but was built from %s", id, meta.Method, methods[id])
}
meta.Root, meta.MaxItems, meta.Method = nil, 0, ""
declared[id] = meta
}
assert.Equal(t, declared, built, "docs/swagger.json is stale; run make docs")
}
func TestFromSpecDropsDetailFieldsFromLists(t *testing.T) {
const spec = `{
"basePath": "/api/v1",
"definitions": {
"Agent": {"type": "object", "properties": {
"id": {"type": "string", "x-agent": "agent_id"},
"config": {"type": "object", "x-agent": true, "properties": {
"mode": {"type": "string", "x-agent": true},
"prompt": {"type": "string", "x-agent": true, "x-agent-detail": true}
}}
}}
},
"paths": {
"/agents": {"get": {"summary": "list", "x-agent": {"id": "agent.list", "risk": "read"},
"responses": {"200": {"schema": {"type": "object", "properties": {
"data": {"type": "array", "items": {"$ref": "#/definitions/Agent"}}}}}}}},
"/agents/{id}": {"get": {"summary": "get", "x-agent": {"id": "agent.get", "risk": "read"},
"parameters": [{"name": "id", "in": "path", "type": "string", "required": true,
"description": "d", "x-agent": "agent_id"}],
"responses": {"200": {"schema": {"type": "object", "properties": {
"data": {"$ref": "#/definitions/Agent"}}}}}}}
}
}`
ops, err := FromSpec([]byte(spec))
require.NoError(t, err)
fields := map[string][]string{}
for _, op := range ops {
for _, f := range op.Result.Fields {
fields[op.ID] = append(fields[op.ID], f.outputKey())
}
}
assert.ElementsMatch(t, []string{"agent_id", "mode"}, fields["agent.list"])
assert.ElementsMatch(t, []string{"agent_id", "mode", "prompt"}, fields["agent.get"])
const exposed = `"prompt": {"type": "string", "x-agent": true,`
unexposed := strings.Replace(spec, exposed, `"prompt": {"type": "string",`, 1)
_, err = FromSpec([]byte(unexposed))
assert.ErrorContains(t, err, "x-agent-detail needs x-agent")
}
func TestFromSpecProjectsNestedListMeta(t *testing.T) {
const spec = `{
"basePath": "/api/v1",
"definitions": {
"Page": {"type": "object", "properties": {
"total": {"type": "integer", "x-agent": true},
"data": {"type": "array", "items": {"type": "object", "properties": {
"name": {"type": "string", "x-agent": true}
}}}
}}
},
"paths": {
"/knowledge-bases/{id}/tags": {"get": {
"summary": "Tags",
"x-agent": {"id": "tag.list", "risk": "read", "root": "data.data"},
"parameters": [
{"name": "id", "in": "path", "type": "string", "required": true, "description": "KB",
"x-agent": "knowledge_base_id"}
],
"responses": {"200": {"schema": {"type": "object", "properties": {
"success": {"type": "boolean"},
"data": {"$ref": "#/definitions/Page"}
}}}}
}}
}
}`
ops, err := FromSpec([]byte(spec))
require.NoError(t, err)
catalog, err := NewCatalog(ops...)
require.NoError(t, err)
list, _ := catalog.Get("tag.list")
assert.Equal(t, []Field{{From: "data.total", As: "total"}}, list.Result.Meta)
projected, err := list.Project([]byte(`{"success":true,"data":{"total":3,"page":1,"data":[{"name":"a"}]}}`))
require.NoError(t, err)
out, _ := json.Marshal(projected)
assert.JSONEq(t, `{"data":[{"name":"a"}],"meta":{"total":3}}`, string(out))
}
func TestFromSpecProjectsListsOfObjects(t *testing.T) {
const spec = `{
"basePath": "/api/v1",
"definitions": {
"Tag": {"type": "object", "properties": {
"id": {"type": "string", "x-agent": "tag_id"},
"color": {"type": "string"},
"note": {"type": "string", "x-agent": true, "x-agent-detail": true}
}},
"Doc": {"type": "object", "properties": {
"id": {"type": "string", "x-agent": "knowledge_id"},
"tags": {"type": "array", "x-agent": true, "items": {"$ref": "#/definitions/Tag"}}
}}
},
"paths": {
"/knowledge": {"get": {"summary": "list", "x-agent": {"id": "doc.list", "risk": "read"},
"responses": {"200": {"schema": {"type": "object", "properties": {
"data": {"type": "array", "items": {"$ref": "#/definitions/Doc"}}}}}}}},
"/knowledge/{id}": {"get": {"summary": "get", "x-agent": {"id": "doc.get", "risk": "read"},
"parameters": [{"name": "id", "in": "path", "type": "string", "required": true,
"description": "d", "x-agent": "knowledge_id"}],
"responses": {"200": {"schema": {"type": "object", "properties": {
"data": {"$ref": "#/definitions/Doc"}}}}}}}
}
}`
ops, err := FromSpec([]byte(spec))
require.NoError(t, err)
catalog, err := NewCatalog(ops...)
require.NoError(t, err)
list, _ := catalog.Get("doc.list")
tags, ok := fieldByFrom(list.Result.Fields, "tags")
require.True(t, ok)
assert.Equal(t, []Field{{From: "id", As: "tag_id"}}, tags.Items, "lists drop detail fields of items too")
get, _ := catalog.Get("doc.get")
tags, _ = fieldByFrom(get.Result.Fields, "tags")
assert.Equal(t, []Field{{From: "id", As: "tag_id"}, {From: "note", As: "note"}}, tags.Items)
nested := strings.Replace(spec, `"color": {"type": "string"},`,
`"color": {"type": "array", "x-agent": true, "items": {"type": "object", "properties": {
"hex": {"type": "string", "x-agent": true}}}},`, 1)
_, err = FromSpec([]byte(nested))
assert.ErrorContains(t, err, "cannot hold lists of objects")
bare := strings.Replace(spec, `"id": {"type": "string", "x-agent": "tag_id"},`, `"id": {"type": "string"},`, 1)
bare = strings.Replace(bare,
`"note": {"type": "string", "x-agent": true, "x-agent-detail": true}`, `"note": {"type": "string"}`, 1)
_, err = FromSpec([]byte(bare))
assert.ErrorContains(t, err, "list items expose no fields")
}
func TestBuildAllowsDeclaredLongStrings(t *testing.T) {
op := Operation{
Method: http.MethodPost,
Params: []Param{{
Name: "content", In: InBody, Key: "content", Type: TypeString,
Description: "body", MaxBytes: maxAgentStringBytes,
}},
}
body := strings.Repeat("文", 5000)
raw, err := json.Marshal(body)
require.NoError(t, err)
call, err := op.Build(map[string]json.RawMessage{"content": raw})
require.NoError(t, err)
assert.Greater(t, len(call.Body), maxStringParamBytes)
op.Params[0].MaxBytes = 0
_, err = op.Build(map[string]json.RawMessage{"content": raw})
assert.Error(t, err)
}
func TestBuiltinListAndDocumentLimits(t *testing.T) {
catalog := Builtin()
manual, ok := catalog.Get("knowledge.create_manual")
require.True(t, ok)
content, ok := manual.Param("content")
require.True(t, ok)
assert.Equal(t, maxAgentStringBytes, content.MaxBytes)
list, ok := catalog.Get("knowledge_base.list")
require.True(t, ok)
assert.Equal(t, 200, list.Result.MaxItems)
shared, _ := catalog.Get("knowledge_base.list_shared")
assert.Equal(t, 200, shared.Result.MaxItems)
folders, _ := catalog.Get("knowledge.list_folders")
assert.Equal(t, 200, folders.Result.MaxItems)
assert.Contains(t, folders.Result.Meta, Field{From: "data.root_document_count", As: "root_document_count"})
wikiFolders, _ := catalog.Get("wiki.list_folders")
assert.Equal(t, 200, wikiFolders.Result.MaxItems)
tags, ok := catalog.Get("knowledge_base.list_tags")
require.True(t, ok)
assert.Equal(t, 50, tags.Result.MaxItems)
pageSize, ok := tags.Param("page_size")
require.True(t, ok)
assert.Equal(t, 50, pageSize.Maximum)
assert.Contains(t, tags.Result.Meta, Field{From: "data.total", As: "total"})
revisions, ok := catalog.Get("wiki.list_revisions")
require.True(t, ok)
version, ok := revisions.Param("content_version")
require.True(t, ok)
assert.Equal(t, 1, version.Minimum)
revert, ok := catalog.Get("wiki.revert")
require.True(t, ok)
revertVersion, ok := revert.Param("version")
require.True(t, ok)
assert.Equal(t, 1, revertVersion.Minimum)
var contentField Field
for _, f := range revisions.Result.Fields {
if f.As == "content" {
contentField = f
}
}
assert.Equal(t, Field{From: "content", As: "content", MaxRunes: 8000}, contentField)
}
func TestTypeParamCombinesListAndStringBounds(t *testing.T) {
doc := &specDocument{}
shape := &specSchema{Type: "array", Items: &specSchema{Type: "string"}}
var p Param
require.NoError(t, doc.typeParam(&p, shape, "2", "5"))
op := Operation{Method: http.MethodPost, Params: []Param{p}}
op.Params[0].Name = "titles"
op.Params[0].In = InBody
_, err := op.Build(map[string]json.RawMessage{"titles": raw([]string{"one", "two"})})
require.NoError(t, err)
_, err = op.Build(map[string]json.RawMessage{"titles": raw([]string{"one", "two", "three"})})
require.Error(t, err, "the item count remains bounded")
_, err = op.Build(map[string]json.RawMessage{"titles": raw([]string{"too long"})})
require.Error(t, err, "each string remains bounded")
for _, kind := range []string{"integer", "boolean"} {
assert.Error(t, doc.typeParam(&Param{}, &specSchema{Type: kind}, "", "5"))
}
for _, kind := range []string{"string", "boolean"} {
assert.Error(t, doc.typeParam(&Param{}, &specSchema{Type: kind}, "2", ""))
}
}
@@ -0,0 +1,164 @@
package operations
import (
"encoding/json"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSystemAdminOperationsRequireIndependentPermission(t *testing.T) {
for _, id := range []string{"list_admins", "list_users", "list_settings", "get_queues", "list_tasks"} {
op, ok := Builtin().Get("system_admin." + id)
require.True(t, ok)
require.True(t, op.SystemAdmin)
assert.Equal(t, "GET", op.Method)
assert.Equal(t, RiskRead, op.Risk)
for _, enforce := range []bool{false, true} {
for _, role := range []types.TenantRole{
types.TenantRoleViewer,
types.TenantRoleAdmin,
types.TenantRoleOwner,
} {
access := Access{Role: role, EnforceRole: enforce, Level: types.AssistantAccessReadOnly}
why, denied := Builtin().Withheld(access, op)
assert.True(t, denied)
assert.True(t, why.SystemAdmin)
access.SystemAdmin = true
_, denied = Builtin().Withheld(access, op)
assert.False(t, denied)
}
}
withoutPermission := op
withoutPermission.SystemAdmin = false
_, err := NewCatalog(withoutPermission)
require.Error(t, err, "platform routes must opt into system-admin gating")
}
for _, route := range []string{
"/api/v1/system/admin/settings",
"/api/v1/system/admin/settings/:key",
"/api/v1/system/admin/api-keys",
"/api/v1/system/admin/promote",
"/api/v1/system/admin/users/status",
} {
op := readOp("system_admin.forbidden", route)
op.SystemAdmin = true
_, err := NewCatalog(op)
require.Error(t, err, route)
}
}
func TestSystemAdminPaginationAndSafeProjections(t *testing.T) {
users, _ := Builtin().Get("system_admin.list_users")
call, err := users.Build(map[string]json.RawMessage{"offset": raw(50), "limit": raw(50)})
require.NoError(t, err)
assert.Contains(t, call.URI(), "offset=50")
_, err = users.Build(map[string]json.RawMessage{"limit": raw(51)})
require.Error(t, err)
out, err := users.Project([]byte(`{
"users": [
{
"id": "u1",
"username": "Name",
"email": "a@example.com",
"is_active": false,
"is_system_admin": true,
"password": "secret",
"preferences": {
"hidden": "secret"
},
"avatar": "secret"
}
],
"has_more": true,
"limit": 50,
"offset": 50
}`))
require.NoError(t, err)
blob, _ := json.Marshal(out)
assert.Contains(t, string(blob), `"has_more":true`)
assert.Contains(t, string(blob), `"is_active":false`)
assert.NotContains(t, string(blob), "secret")
tasks, _ := Builtin().Get("system_admin.list_tasks")
params := map[string]json.RawMessage{
"queue": raw("default"),
"state": raw("archived"),
"cursor": raw("opaque=+/"),
"page_size": raw(20),
}
call, err = tasks.Build(params)
require.NoError(t, err)
assert.Contains(t, call.URI(), "cursor=opaque%3D%2B%2F")
params["state"] = raw("failed")
_, err = tasks.Build(params)
require.Error(t, err)
out, err = tasks.Project([]byte(`{
"available": true,
"tasks": [
{
"id": "t1",
"state": "archived",
"error_category": "timeout",
"last_error": "secret",
"payload": "secret",
"worker": "secret",
"tenant_id": 9,
"knowledge_id": "k1"
}
],
"has_more": true,
"next_cursor": "opaque"
}`))
require.NoError(t, err)
blob, _ = json.Marshal(out)
assert.Contains(t, string(blob), `"next_cursor":"opaque"`)
assert.Contains(t, string(blob), `"error_category":"timeout"`)
assert.NotContains(t, string(blob), "secret")
queues, _ := Builtin().Get("system_admin.get_queues")
text := projectJSON(t, queues, `{
"available": false,
"queues_error": true,
"workers_error": true,
"models_error": true,
"queues": [],
"pools": [
{
"name": "core",
"concurrency": 8,
"cluster_capacity": 16,
"active": 2
}
],
"models": [
{
"model_id": "m1",
"name": "Model",
"active": 1,
"waiting": 3,
"limit": 4
}
]
}`)
assert.Contains(t, text, `"available":false`)
assert.Contains(t, text, `"queues_error":true`)
assert.Contains(t, text, `"cluster_capacity":16`)
assert.Contains(t, text, `"waiting":3`)
}
func TestSystemAdminOperationsDiscoverableInChinese(t *testing.T) {
for query, id := range map[string]string{
"系统管理员": "system_admin.list_admins",
"平台用户": "system_admin.list_users",
"失败": "system_admin.list_tasks",
} {
found := false
for _, op := range Builtin().Find(query, "") {
if op.ID == id {
found = true
}
}
assert.True(t, found, query)
}
}
+162
View File
@@ -0,0 +1,162 @@
package operations
import (
"encoding/json"
"net/http"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestWorkspaceOperationsScopeAndParameters(t *testing.T) {
for _, tc := range []struct {
id, method, route string
role types.TenantRole
params []string
}{
{"workspace.get", "GET", "/api/v1/tenants/current", types.TenantRoleViewer, nil},
{
"workspace.update",
"PATCH",
"/api/v1/tenants/current",
types.TenantRoleOwner,
[]string{
"name",
"description",
},
},
{
"workspace.list_members",
"GET",
"/api/v1/tenants/current/members",
types.TenantRoleViewer,
[]string{
"q",
"page",
"page_size",
},
},
{"system.get_info", "GET", "/api/v1/system/info", types.TenantRoleViewer, nil},
} {
op, ok := Builtin().Get(tc.id)
require.True(t, ok, tc.id)
assert.Equal(t, tc.method, op.Method)
assert.Equal(t, tc.route, op.Route)
assert.Equal(t, tc.role, op.Role)
assert.ElementsMatch(t, tc.params, paramNames(op))
_, err := op.Build(map[string]json.RawMessage{"tenant_id": raw(99)})
require.Error(t, err, "caller cannot select another workspace")
}
op, _ := Builtin().Get("workspace.update")
assert.Equal(t, "workspace.get", op.Target.Operation)
call, err := op.Build(map[string]json.RawMessage{"description": raw("")})
require.NoError(t, err)
assert.JSONEq(t, `{"description":""}`, string(call.Body))
for _, forbidden := range []string{"status", "storage_quota", "credentials", "api_key", "role"} {
_, err := op.Build(map[string]json.RawMessage{"name": raw("New"), forbidden: raw("injected")})
require.Error(t, err, forbidden)
}
members, _ := Builtin().Get("workspace.list_members")
call, err = members.Build(
map[string]json.RawMessage{"q": raw("demo@example.com"), "page": raw(2), "page_size": raw(50)},
)
require.NoError(t, err)
assert.Contains(t, call.URI(), "page=2")
for _, params := range []map[string]json.RawMessage{{"page": raw(0)}, {"page_size": raw(51)}} {
_, err := members.Build(params)
require.Error(t, err)
}
}
func TestWorkspaceAndSystemProjectionsExcludeInternalData(t *testing.T) {
for _, id := range []string{"workspace.get", "workspace.update"} {
op, _ := Builtin().Get(id)
out := projectJSON(t, op, `{
"data": {
"id": 7,
"name": "Team",
"description": "",
"status": "active",
"storage_quota": 1024,
"storage_used": 100,
"credentials": {
"app_secret": "hidden"
},
"assistant_config": {
"system_prompt": "hidden"
},
"api_key": "hidden"
}
}`)
assert.Contains(t, out, `"workspace_id":7`)
assert.Contains(t, out, `"storage_used":100`)
assert.Contains(t, out, `"description":""`)
assert.NotContains(t, out, "hidden")
}
members, _ := Builtin().Get("workspace.list_members")
out, err := members.Project([]byte(`{
"data": {
"members": [
{
"user_id": "u1",
"username": "Alice",
"email": "a@example.com",
"role": "admin",
"status": "active",
"password": "hidden",
"avatar": "hidden",
"is_system_admin": true
}
],
"total": 51,
"page": 2,
"page_size": 50
}
}`))
require.NoError(t, err)
blob, err := json.Marshal(out)
require.NoError(t, err)
assert.Contains(t, string(blob), `"total":51`)
assert.Contains(t, string(blob), `"email":"a@example.com"`)
assert.NotContains(t, string(blob), "is_system_admin")
assert.NotContains(t, string(blob), "hidden")
system, _ := Builtin().Get("system.get_info")
info := projectJSON(t, system, `{
"data": {
"version": "v1",
"edition": "lite",
"uptime_seconds": 90,
"db_version": "12 (failed)",
"db_migration_failed": true,
"db_migration_error": "postgres://hidden",
"graph_database_engine": "disabled"
}
}`)
assert.Contains(t, info, `"db_migration_failed":true`)
assert.Contains(t, info, `"version":"v1"`)
assert.NotContains(t, info, "hidden")
}
func TestWorkspaceCatalogKeepsPrivilegedRoutesClosed(t *testing.T) {
for _, route := range []string{
"/api/v1/tenants",
"/api/v1/tenants/:id",
"/api/v1/tenants/all",
"/api/v1/tenants/current/api-keys",
"/api/v1/tenants/kv/:key",
"/api/v1/system/admin/users",
"/api/v1/tenants/current/invitations",
} {
_, err := NewCatalog(readOp("workspace.read", route))
require.Error(t, err, route)
}
for _, id := range []string{"workspace.get", "workspace.list_members", "system.get_info"} {
op, _ := Builtin().Get(id)
op.Method, op.Risk = http.MethodDelete, RiskDestructive
op.Target = &Target{Operation: "workspace.get", Label: "name"}
_, err := NewCatalog(op)
require.Error(t, err, id)
}
}