agents

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewDBSessionStore

func NewDBSessionStore(app core.App) *dbSessionStore

NewDBSessionStore creates a DB-backed session store.

Types

type AgentAuditEntry

type AgentAuditEntry struct {
	Time     types.DateTime `json:"time"`
	Session  string         `json:"session"`
	Project  string         `json:"project"`
	Actor    string         `json:"actor,omitempty"`
	Tool     string         `json:"tool"`
	Category string         `json:"category"`
	Risk     string         `json:"risk"`
	Audit    string         `json:"auditCategory"`
	Decision string         `json:"decision"` // "allow" | "deny"
	Reason   string         `json:"reason,omitempty"`
	Status   string         `json:"status,omitempty"`
	Error    string         `json:"error,omitempty"`
}

AgentAuditEntry is a structured audit record for a single tool decision (proposal §8.2 step 6 / §8.1 audit category).

type AgentFileRef

type AgentFileRef struct {
	Collection string `json:"collection"`
	RecordId   string `json:"recordId"`
	Filename   string `json:"filename"`
}

AgentFileRef references an image stored in the file subsystem by record file field (proposal §6.2). The agent resolves it server-side to a content block, so the model never touches the filesystem directly.

type AgentImageInput

type AgentImageInput struct {
	MimeType string        `json:"mimeType"`
	Data     string        `json:"data"`
	FileRef  *AgentFileRef `json:"fileRef,omitempty"`
}

AgentImageInput is an image supplied with a user turn (proposal §6.1). Provide either inline base64 Data, or a FileRef to resolve from the file subsystem (proposal §6.2).

type ChartHint

type ChartHint struct {
	// Type is one of: table, line, bar, pie, metric.
	Type string `json:"type"`
	// XField is the field to use for the category/time axis.
	XField string `json:"xField,omitempty"`
	// YFields are the numeric series fields.
	YFields []string `json:"yFields,omitempty"`
}

ChartHint is a recommended visualization for a query result (proposal §10.1). The frontend uses it to render a chart alongside the raw table; the agent itself does not render charts.

type Model

type Model struct {
	Name             string `json:"name"`
	ProviderModelId  string `json:"providerModelId"`
	SupportsVision   bool   `json:"supportsVision"`
	SupportsToolUse  bool   `json:"supportsToolUse"`
	SupportsDocument bool   `json:"supportsDocument"`
	Enabled          bool   `json:"enabled"`
}

Model is a model-level view derived from stored settings.

type PendingApproval

type PendingApproval struct {
	Tool   string         `json:"tool"`
	Risk   string         `json:"risk"`
	Args   map[string]any `json:"args,omitempty"`
	Reason string         `json:"reason"`
}

PendingApproval describes a write operation that was blocked pending explicit authorization (proposal §8.3 pending state).

type ProjectConfig

type ProjectConfig struct {
	Project           string   `json:"project"`
	DefaultProvider   string   `json:"defaultProvider"`
	DefaultModel      string   `json:"defaultModel"`
	AllowedTools      []string `json:"allowedTools"`
	AllowSchemaChange string   `json:"allowSchemaChange"` // inherit|allow|deny
	ApprovalPolicy    string   `json:"approvalPolicy"`    // inherit|manual|auto
}

ProjectConfig is the API view of a per-project agent configuration (§9.1).

type Provider

type Provider struct {
	Id           string  `json:"id"`
	Vendor       string  `json:"vendor"`
	BaseUrl      string  `json:"baseUrl"`
	Enabled      bool    `json:"enabled"`
	DefaultModel string  `json:"defaultModel"`
	Models       []Model `json:"models"`
}

Provider is a provider-level view derived from stored settings.

type Registry

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

Registry exposes a static snapshot of agent runtime configuration.

func NewRegistry

func NewRegistry(cfg settings.AgentConfig) *Registry

NewRegistry builds a registry from app settings.

func (*Registry) Provider

func (r *Registry) Provider(id string) (Provider, error)

Provider returns a configured provider by id.

func (*Registry) Snapshot

func (r *Registry) Snapshot() Runtime

Snapshot returns the registry runtime snapshot.

type RunInput

type RunInput struct {
	Content string            `json:"content"`
	Images  []AgentImageInput `json:"images,omitempty"`
}

RunInput is the user turn fed to the agent: text plus optional images.

type RunOptions

type RunOptions struct {
	// AllowWrites authorizes every write/schema tool for this run.
	AllowWrites bool `json:"allowWrites"`
	// ApprovedTools is a fine-grained allow-list of dotted tool names that may
	// perform write operations for this run.
	ApprovedTools []string `json:"approvedTools"`
	// Actor identifies who initiated the run (for audit). Usually an admin id.
	Actor string `json:"actor"`
}

RunOptions carries per-run authorization context (proposal §8.3).

Read operations are always permitted within the project boundary. Write operations are denied by default and must be explicitly authorized either globally for the run (AllowWrites) or per tool (ApprovedTools).

type RunResult

type RunResult struct {
	SessionId        string            `json:"sessionId"`
	SessionName      string            `json:"sessionName,omitempty"`
	Reply            string            `json:"reply"`
	Provider         string            `json:"provider"`
	Model            string            `json:"model"`
	Traces           []RunTrace        `json:"traces,omitempty"`
	PendingApprovals []PendingApproval `json:"pendingApprovals,omitempty"`
	Audit            []AgentAuditEntry `json:"audit,omitempty"`
	Messages         []SessionMessage  `json:"messages"`
}

RunResult is the normalized outcome of an agent run.

type RunStreamEvent

type RunStreamEvent struct {
	Type             RunStreamEventType `json:"type"`
	SessionId        string             `json:"sessionId,omitempty"`
	Provider         string             `json:"provider,omitempty"`
	Model            string             `json:"model,omitempty"`
	Tool             string             `json:"tool,omitempty"`
	Args             map[string]any     `json:"args,omitempty"`
	Text             string             `json:"text,omitempty"`
	Thought          string             `json:"thought,omitempty"`
	Status           string             `json:"status,omitempty"`
	Trace            *RunTrace          `json:"trace,omitempty"`
	PendingApprovals []PendingApproval  `json:"pendingApprovals,omitempty"`
	Result           *RunResult         `json:"result,omitempty"`
	Error            string             `json:"error,omitempty"`
}

RunStreamEvent is emitted while an agent run is still in progress.

type RunStreamEventType

type RunStreamEventType string

RunStreamEventType identifies a streamed agent event.

const (
	RunStreamEventStart      RunStreamEventType = "start"
	RunStreamEventTextDelta  RunStreamEventType = "text_delta"
	RunStreamEventThinkDelta RunStreamEventType = "think_delta"
	RunStreamEventToolCall   RunStreamEventType = "tool_call"
	RunStreamEventToolResult RunStreamEventType = "tool_result"
	RunStreamEventStatus     RunStreamEventType = "status"
	RunStreamEventFinal      RunStreamEventType = "final"
	RunStreamEventError      RunStreamEventType = "error"
)

type RunStreamHandler

type RunStreamHandler func(RunStreamEvent) bool

RunStreamHandler receives progress events for a single agent run. Returning false stops the run, usually because the HTTP client disconnected.

type RunTrace

type RunTrace struct {
	Tool   string `json:"tool"`
	Args   string `json:"args,omitempty"`
	Result string `json:"result,omitempty"`
	Error  string `json:"error,omitempty"`
}

RunTrace records a single tool execution performed during an agent run.

type Runtime

type Runtime struct {
	Enabled           bool       `json:"enabled"`
	DefaultProvider   string     `json:"defaultProvider"`
	DefaultModel      string     `json:"defaultModel"`
	AllowSchemaChange bool       `json:"allowSchemaChange"`
	AllowedTools      []string   `json:"allowedTools"`
	Providers         []Provider `json:"providers"`
}

Runtime describes the embedded agent surface exposed by PostgreBase.

type Service

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

Service exposes embedded agent runtime views derived from app settings.

func NewService

func NewService(app core.App) *Service

NewService creates a new agent service.

func (*Service) AppendMessage

func (s *Service) AppendMessage(id, role, content string) (*Session, []SessionMessage, error)

AppendMessage adds a message to a session.

func (*Service) CreateSession

func (s *Service) CreateSession(project, name, provider, model string) *Session

CreateSession creates a new in-memory project session.

func (*Service) ExecuteTool

func (s *Service) ExecuteTool(name string, args map[string]any) (*ToolExecutionResult, error)

ExecuteTool runs a tool call using the configured registry.

func (*Service) ExecuteToolInSession

func (s *Service) ExecuteToolInSession(sessionID, name string, args map[string]any) (*ToolExecutionResult, error)

ExecuteToolInSession runs a tool call and stores a trace in the session history.

func (*Service) GetProjectConfig

func (s *Service) GetProjectConfig(project string) ProjectConfig

GetProjectConfig returns the stored per-project config or an inherit default.

func (*Service) GetSession

func (s *Service) GetSession(id string) (*Session, error)

GetSession returns a session by id.

func (*Service) ListSessions

func (s *Service) ListSessions(project string) []*Session

ListSessions returns all sessions for a project.

func (*Service) Models

func (s *Service) Models() []Model

Models returns all configured models across providers.

func (*Service) Providers

func (s *Service) Providers() []Provider

Providers returns all configured providers.

func (*Service) Refresh

func (s *Service) Refresh()

Refresh reloads the service registry from current app settings.

func (*Service) RegisterExecutors

func (s *Service) RegisterExecutors()

RegisterExecutors wires context-aware tool executors.

func (*Service) RenameSession

func (s *Service) RenameSession(id, name string) (*Session, error)

RenameSession explicitly renames a session and locks the name (proposal §9.2).

func (*Service) RunSession

func (s *Service) RunSession(ctx context.Context, sessionID string, input RunInput, opts RunOptions) (*RunResult, error)

RunSession stores the user message, drives the vibecoding agent runtime and returns the final accumulated result.

func (*Service) RunSessionStream

func (s *Service) RunSessionStream(ctx context.Context, sessionID string, input RunInput, opts RunOptions, emit RunStreamHandler) (*RunResult, error)

RunSessionStream stores the user message, drives the vibecoding agent runtime (model + tool loop), streams progress events and persists the final assistant and tool messages.

func (*Service) Runtime

func (s *Service) Runtime() Runtime

Runtime returns the current runtime snapshot.

func (*Service) SaveProjectConfig

func (s *Service) SaveProjectConfig(in ProjectConfig) (ProjectConfig, error)

SaveProjectConfig persists a per-project agent config (upsert by project).

func (*Service) SessionAudit

func (s *Service) SessionAudit(id string) ([]*models.AgentAuditRecord, error)

SessionAudit returns the persisted audit trail for a session (proposal §8.2/§8.4).

func (*Service) SessionMessages

func (s *Service) SessionMessages(id string) ([]SessionMessage, error)

SessionMessages returns all stored messages for a session.

func (*Service) Tools

func (s *Service) Tools() []ToolSpec

Tools returns the static tool registry.

type Session

type Session struct {
	Id          string         `json:"id"`
	Project     string         `json:"project"`
	Name        string         `json:"name"`
	Model       string         `json:"model"`
	Provider    string         `json:"provider"`
	Created     types.DateTime `json:"created"`
	Updated     types.DateTime `json:"updated"`
	LastMessage string         `json:"lastMessage"`
	// NameLocked is true when the name was explicitly set by the user (on
	// create or via rename) and must not be auto-generated (proposal §9.2).
	NameLocked bool `json:"-"`
}

Session represents a project-scoped agent session.

type SessionImage

type SessionImage struct {
	MimeType string `json:"mimeType"`
	// Data is the base64-encoded image payload.
	Data string `json:"data"`
}

SessionImage is an image attachment carried by a user message (proposal §6).

type SessionMessage

type SessionMessage struct {
	Role    string         `json:"role"`
	Content string         `json:"content"`
	Images  []SessionImage `json:"images,omitempty"`
	Created types.DateTime `json:"created"`
}

SessionMessage represents an in-memory conversation item.

type SessionStore

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

SessionStore holds in-memory sessions for the embedded agent surface.

func NewSessionStore

func NewSessionStore() *SessionStore

NewSessionStore creates a new in-memory session store.

func (*SessionStore) AddMessage

func (s *SessionStore) AddMessage(id, role, content string) (*Session, []SessionMessage, error)

AddMessage appends a text message to a session.

func (*SessionStore) AddMessageWithImages

func (s *SessionStore) AddMessageWithImages(id, role, content string, images []SessionImage) (*Session, []SessionMessage, error)

AddMessageWithImages appends a message that may carry image attachments.

func (*SessionStore) Create

func (s *SessionStore) Create(project, name, provider, model string) *Session

Create creates a new session for a project.

func (*SessionStore) Get

func (s *SessionStore) Get(id string) (*Session, error)

Get returns a session by id.

func (*SessionStore) List

func (s *SessionStore) List(project string) []*Session

List returns sessions sorted by newest first.

func (*SessionStore) Messages

func (s *SessionStore) Messages(id string) ([]SessionMessage, error)

Messages returns the stored messages for a session.

func (*SessionStore) NeedsAutoName

func (s *SessionStore) NeedsAutoName(id string) bool

NeedsAutoName reports whether the session should receive an LLM-generated name: the name is not user-locked, is still a placeholder, and the session already has at least one user message (proposal §9.2).

func (*SessionStore) Rename

func (s *SessionStore) Rename(id, name string) (*Session, error)

Rename explicitly sets a user-provided name and locks it against future auto-generation (proposal §9.2 "除非用户显式重命名").

func (*SessionStore) SetGeneratedName

func (s *SessionStore) SetGeneratedName(id, name string) (*Session, error)

SetGeneratedName sets an LLM-generated name once. It is a no-op if the name is already locked or no longer a placeholder, guaranteeing single generation.

type ToolExecutionResult

type ToolExecutionResult struct {
	Status  string     `json:"status"`
	Message string     `json:"message,omitempty"`
	Data    any        `json:"data,omitempty"`
	Chart   *ChartHint `json:"chart,omitempty"`
}

ToolExecutionResult is the normalized result returned by a tool executor.

type ToolExecutor

type ToolExecutor func(args map[string]any) (*ToolExecutionResult, error)

ToolExecutor executes a tool call.

func NewAddFieldExecutor

func NewAddFieldExecutor(app core.App) ToolExecutor

NewAddFieldExecutor updates a collection schema with a single new field.

func NewBulkInsertRecordExecutor

func NewBulkInsertRecordExecutor(app core.App) ToolExecutor

NewBulkInsertRecordExecutor creates a project-scoped record bulk insert executor.

func NewCreateIndexExecutor

func NewCreateIndexExecutor(app core.App) ToolExecutor

NewCreateIndexExecutor adds or replaces a collection index definition.

func NewCreateTableExecutor

func NewCreateTableExecutor(app core.App) ToolExecutor

NewCreateTableExecutor creates a project-scoped collection creation executor.

func NewDatasetPreviewExecutor

func NewDatasetPreviewExecutor(app core.App) ToolExecutor

NewDatasetPreviewExecutor returns a light-weight preview over the project's records.

func NewDeleteRecordExecutor

func NewDeleteRecordExecutor(app core.App) ToolExecutor

NewDeleteRecordExecutor creates a project-scoped record delete executor.

func NewDropFieldExecutor

func NewDropFieldExecutor(app core.App) ToolExecutor

NewDropFieldExecutor removes a field from an existing table definition.

func NewGetRecordExecutor

func NewGetRecordExecutor(app core.App) ToolExecutor

NewGetRecordExecutor fetches a single project-scoped record.

func NewInsertRecordExecutor

func NewInsertRecordExecutor(app core.App) ToolExecutor

NewInsertRecordExecutor creates a project-scoped record insert executor.

func NewListTablesExecutor

func NewListTablesExecutor(app core.App) ToolExecutor

NewListTablesExecutor returns the project table catalog available to the agent.

func NewQueryExecutor

func NewQueryExecutor(app core.App) ToolExecutor

NewQueryExecutor creates a project-scoped query tool executor.

func NewSetRelationExecutor

func NewSetRelationExecutor(app core.App) ToolExecutor

NewSetRelationExecutor creates or updates a relation field definition.

func NewUpdateFieldExecutor

func NewUpdateFieldExecutor(app core.App) ToolExecutor

NewUpdateFieldExecutor updates an existing field definition.

func NewUpdateRecordExecutor

func NewUpdateRecordExecutor(app core.App) ToolExecutor

NewUpdateRecordExecutor creates a project-scoped record update executor.

type ToolRegistry

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

ToolRegistry holds the static tool list exposed to the agent surface.

func NewToolRegistry

func NewToolRegistry() *ToolRegistry

NewToolRegistry creates a registry with the platform's initial tool set.

func (*ToolRegistry) Execute

func (r *ToolRegistry) Execute(name string, args map[string]any) (*ToolExecutionResult, error)

Execute runs a registered tool.

func (*ToolRegistry) Get

func (r *ToolRegistry) Get(name string) (ToolSpec, bool)

Get returns a tool by name.

func (*ToolRegistry) List

func (r *ToolRegistry) List() []ToolSpec

List returns tools sorted by name.

func (*ToolRegistry) SetExecutor

func (r *ToolRegistry) SetExecutor(name string, exec ToolExecutor)

SetExecutor registers an executor for the specified tool.

type ToolSpec

type ToolSpec struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	InputSchema map[string]any `json:"inputSchema"`

	// Category is either "read" or "write" (proposal §8.3).
	Category string `json:"category"`
	// Risk is one of "low", "medium", "high".
	Risk string `json:"risk"`
	// AuditCategory groups the tool for audit logging (e.g. "data", "schema").
	AuditCategory string `json:"auditCategory"`
	// RequiresApproval marks write operations that must be explicitly
	// authorized before execution.
	RequiresApproval bool `json:"requiresApproval"`
}

ToolSpec describes a registered embedded agent tool.

Per proposal §8.1, a registry entry carries at least: name, description, input schema, executor, required permissions and audit category. The executor is stored separately in the registry; the remaining control metadata (category/risk/audit/approval) lives here.

Jump to

Keyboard shortcuts

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