ai

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: AGPL-3.0, AGPL-3.0-or-later Imports: 35 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendConversationMessage

func AppendConversationMessage(ctx context.Context, db *sql.DB, msg MessageRecord) error

AppendConversationMessage assigns the next sequence inside the tenant's conversation so refreshes and multiple turns preserve transcript order. The Sequence field of msg is replaced by the assigned value.

func AppendMessage

func AppendMessage(ctx context.Context, db *sql.DB, msg MessageRecord) error

AppendMessage stores msg at its explicit Sequence.

func CancelRun

func CancelRun(ctx context.Context, db *sql.DB, runID, reason string) error

CancelRun marks a run and its conversation as cancelled.

func CleanupExpired

func CleanupExpired(ctx context.Context, db *sql.DB, now time.Time) (removed int64, err error)

CleanupExpired removes expired conversations, runs, messages, and steps in one transaction.

func ConversationSubjectKey

func ConversationSubjectKey(currentUser string, context ChatContext) string

ConversationSubjectKey scopes a durable chat thread to one user and UI context.

func EnsureAIRunTables

func EnsureAIRunTables(ctx context.Context, db *sql.DB, dialects ...kdb.Dialect) error

func EnsureApprovalPending

func EnsureApprovalPending(ctx context.Context, db *sql.DB, req ApprovalRequest) error

EnsureApprovalPending records req as awaiting approval.

func ExecuteTool

func ExecuteTool(tx *orm.TxManager, reg *doctype.Registry, req ToolRequest) string

ExecuteTool is the authenticated-adapter entry point. It keeps the existing tool catalog and confirmation policy while binding resulting kernel commands to the verified principal supplied by the authentication boundary.

func FinalizeBudget

func FinalizeBudget(ctx context.Context, db *sql.DB, res BudgetReservation, consumedTokens int) error

FinalizeBudget marks a reservation as consumed with the actual token count.

func HandleChat

func HandleChat(c *gin.Context, tx *orm.TxManager, reg *doctype.Registry, siteName, currentUser string)

HandleChat processes a chat message, calls the AI provider with function definitions, executes any tool calls via the ORM, and returns the AI's response.

func HasGrantedApproval

func HasGrantedApproval(ctx context.Context, db *sql.DB, target ApprovalTarget) (bool, error)

HasGrantedApproval reports whether target has a granted approval.

func ListRunSteps

func ListRunSteps(ctx context.Context, db *sql.DB, runID string) ([]string, error)

func MarkRunPendingApproval

func MarkRunPendingApproval(ctx context.Context, db *sql.DB, runID, stepID, reason string) error

func MarkTaskStatus

func MarkTaskStatus(ctx context.Context, db *sql.DB, taskID, status, notes string) error

func QueueFollowUpTasks

func QueueFollowUpTasks(ctx context.Context, db *sql.DB, scope RunScope, tasks []TaskRecord) error

QueueFollowUpTasks stores tasks under scope, defaulting an empty Status to "queued" and an empty Kind to "task".

func RecordAudit

func RecordAudit(ctx context.Context, db *sql.DB, ev AuditEvent) error

func RecordUsage

func RecordUsage(ctx context.Context, db *sql.DB, ev contract.UsageEvent) error

RecordUsage stores an immutable AI usage event.

func RefreshRunSummary

func RefreshRunSummary(ctx context.Context, db *sql.DB, runID string) error

RefreshRunSummary rolls the latest step and message content into the run and conversation summary.

func ReleaseBudget

func ReleaseBudget(ctx context.Context, db *sql.DB, res BudgetReservation) error

ReleaseBudget marks a reservation as released.

func SummarizeRun

func SummarizeRun(ctx context.Context, db *sql.DB, runID string) error

func ToContractCatalog

func ToContractCatalog(c ToolCatalog) contract.ToolCatalog

ToContractCatalog projects a ToolCatalog into the canonical shape.

func ToContractDescriptor

func ToContractDescriptor(d ToolDescriptor) contract.ToolDescriptor

ToContractDescriptor projects an api/ai ToolDescriptor into the canonical versioned wire shape (contract.ToolDescriptor). This is the contract-parity bridge required by RFC §10.4.5: BuildToolCatalog remains the registry projection, and every adapter renders the canonical contract shape.

The mapping preserves all shared, wire-visible fields. Safety levels are represented as strings in both packages so adapters can keep their existing vocabulary without changing the contract payload.

func UpdateStepStatus

func UpdateStepStatus(ctx context.Context, db *sql.DB, stepID string, upd StepUpdate) error

UpdateStepStatus applies the non-empty fields of upd to the step stepID.

func UpsertApproval

func UpsertApproval(ctx context.Context, db *sql.DB, rec ApprovalRecord) error

func UpsertConversation

func UpsertConversation(ctx context.Context, db *sql.DB, rec ConversationRecord) error

func UpsertRun

func UpsertRun(ctx context.Context, db *sql.DB, rec RunRecord) error

func UpsertStep

func UpsertStep(ctx context.Context, db *sql.DB, step StepRecord) error

UpsertStep inserts step or updates the stored row with the same ID.

func UpsertTask

func UpsertTask(ctx context.Context, db *sql.DB, rec TaskRecord) error

func ValidateProviderProfile

func ValidateProviderProfile(p ProviderProfile) error

ValidateProviderProfile rejects incomplete or mismatched provider settings before the first provider request is made.

func WithDialect

func WithDialect(ctx context.Context, dialect kdb.Dialect) context.Context

WithDialect binds AI persistence to the dialect of the current tenant.

Types

type AIConfig

type AIConfig struct {
	MaxRounds           int     // Max tool-calling rounds (safety cap)
	TokenBudget         int     // Context window budget in tokens
	CompactionThreshold float64 // 0.0-1.0, when to start compacting history
	MaxToolResultChars  int     // Cap on a single tool result string
	StallThreshold      int     // Consecutive identical tool calls before nudge
	MaxToolErrors       int     // Total tool errors before circuit breaker
	MaxTokensPerCall    int     // max_tokens per AI API call
	HTTPTimeoutSec      int     // Timeout in seconds for AI provider HTTP calls
	MaxRetries          int     // Retries on transient AI errors (429, 503)
	RetryBackoffMs      int     // Base backoff in milliseconds
	HistoryLimit        int     // Max incoming history messages from client
}

AIConfig holds all configurable thresholds for the AI chat pipeline. Every value has a sensible default; site-level overrides are loaded from the secret store with an "ai." key prefix.

func DefaultAIConfig

func DefaultAIConfig() AIConfig

DefaultAIConfig returns sane defaults that work for most models.

func LoadAIConfig

func LoadAIConfig(store *secret.Store, siteName, model string) AIConfig

LoadAIConfig returns the effective AIConfig for the given model and site. Resolution order: DefaultAIConfig → model-specific defaults → site-level overrides from the secret store (keys prefixed with "ai.").

type ApprovalRecord

type ApprovalRecord struct {
	ID                 string
	Site               string
	OperationID        string
	ActorPrincipalID   string
	ActorPrincipalType string
	ToolName           string
	State              string
	TargetFingerprint  string
	ArgumentHash       string
	RecordVersion      int
	RequestedAt        time.Time
	ExpiresAt          time.Time
	GrantedAt          time.Time
	GrantedBy          string
	AuthSessionID      string
}

func GrantApproval

func GrantApproval(ctx context.Context, db *sql.DB, approvalID, grantedBy string) (ApprovalRecord, error)

func GrantApprovalForOperation

func GrantApprovalForOperation(ctx context.Context, db *sql.DB, target ApprovalTarget, grantedBy string) (ApprovalRecord, error)

GrantApprovalForOperation grants the newest pending approval for target.

func GrantApprovalForOwner

func GrantApprovalForOwner(ctx context.Context, db *sql.DB, site, approvalID, ownerID string) (ApprovalRecord, error)

GrantApprovalForOwner atomically grants a pending AI execution approval only when it belongs to the verified owner in the current tenant. The conditional update avoids a read/modify/write race and prevents a caller who learns an approval ID from granting another owner's execution.

func LoadApproval

func LoadApproval(ctx context.Context, db *sql.DB, approvalID string) (ApprovalRecord, error)

type ApprovalRequest

type ApprovalRequest struct {
	Target        ApprovalTarget
	ActorID       string
	ActorType     string
	RecordVersion int
}

ApprovalRequest asks for a durable approval of Target on behalf of an actor.

type ApprovalTarget

type ApprovalTarget struct {
	Site        string
	OperationID string
	ToolName    string
	Args        map[string]any
}

ApprovalTarget identifies one tool call, by its arguments, within an operation (an AI run) of a tenant.

type AuditEvent

type AuditEvent struct {
	ID             string
	Site           string
	RunID          string
	StepID         string
	ConversationID string
	Kind           string
	Name           string
	Status         string
	UserID         string
	SessionID      string
	CorrelationID  string
	IdempotencyKey string
	Details        map[string]any
	CreatedAt      time.Time
}

type BudgetRequest

type BudgetRequest struct {
	Site            string
	Model           string
	RequestedTokens int
	Budget          int
	Note            string
}

BudgetRequest asks ReserveBudget for RequestedTokens out of Budget. A non-positive RequestedTokens counts as 1 and a non-positive Budget means no limit.

type BudgetReservation

type BudgetReservation struct {
	ID              string
	Site            string
	Model           string
	RequestedTokens int
	Note            string
}

BudgetReservation is a durable reservation against a site's AI token budget.

func ReserveBudget

func ReserveBudget(ctx context.Context, db *sql.DB, req BudgetRequest) (BudgetReservation, error)

ReserveBudget records a token reservation if enough unreserved budget remains.

type ChatContext

type ChatContext struct {
	Pathname     string `json:"pathname,omitempty"`
	ShellMode    string `json:"shellMode,omitempty"`
	Doctype      string `json:"doctype,omitempty"`
	DocumentName string `json:"documentName,omitempty"`
	ThreadID     string `json:"threadId,omitempty"`
}

ChatContext carries lightweight UI context from the workspace shell.

type ChatMessage

type ChatMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

ChatMessage is a single turn in the conversation.

func ListConversationMessages

func ListConversationMessages(ctx context.Context, db *sql.DB, site, conversationID string) ([]ChatMessage, error)

ListConversationMessages returns the durable user-visible transcript in order.

type ChatRequest

type ChatRequest struct {
	Message      string      `json:"message"`
	Model        string      `json:"model,omitempty"` // override default model
	Context      ChatContext `json:"context,omitempty"`
	DisableTools bool        `json:"disable_tools,omitempty"` // allow safe planning without workspace mutations
}

ChatRequest is the JSON body for POST /api/v1/ai/chat.

type ChatResponse

type ChatResponse struct {
	Reply  string `json:"reply"`
	Action string `json:"action,omitempty"` // what the AI did (e.g., "listed 3 customers")
	RunID  string `json:"run_id,omitempty"`
}

ChatResponse is the data payload for POST /api/v1/ai/chat.

type ConversationRecord

type ConversationRecord struct {
	ID                 string
	Site               string
	Channel            string
	SubjectKey         string
	Title              string
	Summary            string
	Status             string
	LastRunID          string
	LastMessageAt      time.Time
	RetentionExpiresAt time.Time
	CreatedAt          time.Time
	UpdatedAt          time.Time
}

ConversationRecord is the durable server-side chat conversation state.

func LoadConversation

func LoadConversation(ctx context.Context, db *sql.DB, site, subjectKey string) (ConversationRecord, error)

func LoadConversationByID

func LoadConversationByID(ctx context.Context, db *sql.DB, conversationID string) (ConversationRecord, error)

type FieldHint

type FieldHint struct {
	Name           string               `json:"name"`
	Label          string               `json:"label,omitempty"`
	Fieldtype      string               `json:"fieldtype"`
	Type           string               `json:"type,omitempty"`
	Format         string               `json:"format,omitempty"`
	Options        []string             `json:"options,omitempty"`
	LinkTarget     string               `json:"link_target,omitempty"`
	TableTarget    string               `json:"table_target,omitempty"`
	Required       bool                 `json:"required,omitempty"`
	ReadOnly       bool                 `json:"read_only,omitempty"`
	Computed       bool                 `json:"computed,omitempty"`
	Writable       bool                 `json:"writable"`
	StandardFilter bool                 `json:"standard_filter,omitempty"`
	SearchIndex    bool                 `json:"search_index,omitempty"`
	InListView     bool                 `json:"in_list_view,omitempty"`
	Unique         bool                 `json:"unique,omitempty"`
	Description    string               `json:"description,omitempty"`
	Constraints    []doctype.Constraint `json:"constraints,omitempty"`
}

type MessageRecord

type MessageRecord struct {
	Site           string
	ConversationID string
	RunID          string
	Role           string
	Content        string
	Kind           string
	StepID         string
	Sequence       int
}

MessageRecord is one durable transcript entry. A zero Kind means "message" and a non-positive Sequence means 1.

type ProviderProfile

type ProviderProfile struct {
	ProviderKey    string
	BaseURL        string
	Model          string
	HTTPTimeoutSec int
}

ProviderProfile is the normalized provider/model selection used by the chat pipeline before any network I/O occurs.

type RunRecord

type RunRecord struct {
	ID                 string
	Site               string
	ConversationID     string
	Channel            string
	Status             string
	Model              string
	Provider           string
	CurrentStepID      string
	Summary            string
	InputMessage       string
	OutputMessage      string
	ErrorMessage       string
	CancelReason       string
	ResumeToken        string
	CreatedAt          time.Time
	UpdatedAt          time.Time
	CompletedAt        time.Time
	CancelledAt        time.Time
	RetentionExpiresAt time.Time
}

RunRecord is the durable state of one AI run.

func LoadRun

func LoadRun(ctx context.Context, db *sql.DB, runID string) (RunRecord, error)

func MarkRunPlanning

func MarkRunPlanning(ctx context.Context, db *sql.DB, runID string) (RunRecord, error)

func ResumeRun

func ResumeRun(ctx context.Context, db *sql.DB, runID, resumeToken string) (RunRecord, error)

ResumeRun returns a terminal-safe run snapshot and assigns a new resume token.

type RunScope

type RunScope struct {
	Site           string
	RunID          string
	ConversationID string
}

RunScope names the tenant, run and conversation that new rows belong to.

type RunStatusCount

type RunStatusCount struct {
	Status string `json:"status"`
	Rows   int64  `json:"rows"`
}

type RunStatusInventory

type RunStatusInventory struct {
	TablePresent bool             `json:"table_present"`
	Statuses     []RunStatusCount `json:"statuses,omitempty"`
}

func InspectRunStatusInventory

func InspectRunStatusInventory(ctx context.Context, database *sql.DB, dialect kdb.Dialect, siteID string) (RunStatusInventory, error)

InspectRunStatusInventory returns aggregate status counts only. It does not create the optional AI tables or read run IDs, messages, prompts, or outputs.

type StepRecord

type StepRecord struct {
	ID             string
	Site           string
	RunID          string
	ConversationID string
	StepKey        string
	Status         string
	Summary        string
	ToolName       string
	InputJSON      string
	OutputJSON     string
	ErrorMessage   string
}

StepRecord is one run step as stored by UpsertStep. An empty ID is replaced with a fresh ULID.

type StepUpdate

type StepUpdate struct {
	Status       string
	Summary      string
	ToolName     string
	InputJSON    string
	OutputJSON   string
	ErrorMessage string
}

StepUpdate carries the step fields UpdateStepStatus changes. An empty field leaves the stored value as it is.

type SystemFieldHint

type SystemFieldHint struct {
	Name      string `json:"name"`
	Fieldtype string `json:"fieldtype"`
	Writable  bool   `json:"writable"`
}

type TaskRecord

type TaskRecord struct {
	ID             string
	Site           string
	RunID          string
	ConversationID string
	ParentTaskID   string
	Kind           string
	Title          string
	Description    string
	Status         string
	SortOrder      int
	Notes          string
	CreatedAt      time.Time
	UpdatedAt      time.Time
	CompletedAt    time.Time
}

TaskRecord is one tracked unit of work inside an AI run.

func ListRunTasks

func ListRunTasks(ctx context.Context, db *sql.DB, runID string) ([]TaskRecord, error)

type ToolCatalog

type ToolCatalog struct {
	Version string           `json:"version"`
	Tools   []ToolDescriptor `json:"tools"`
}

func BuildToolCatalog

func BuildToolCatalog(reg *doctype.Registry) ToolCatalog

type ToolDescriptor

type ToolDescriptor struct {
	ID                      string            `json:"id"`
	Source                  string            `json:"source"`
	Name                    string            `json:"name"`
	Description             string            `json:"description"`
	InputSchema             map[string]any    `json:"input_schema"`
	SafetyLevel             string            `json:"safety_level"`
	RequiresConfirmation    bool              `json:"requires_confirmation"`
	RequiresRecentAuth      bool              `json:"requires_recent_auth"`
	ChannelAllowlist        []string          `json:"channel_allowlist"`
	ArgumentContractVersion string            `json:"argument_contract_version"`
	Operation               string            `json:"operation"`
	Doctype                 string            `json:"doctype,omitempty"`
	DoctypeLabel            string            `json:"doctype_label,omitempty"`
	TitleField              string            `json:"title_field,omitempty"`
	SearchFields            []string          `json:"search_fields,omitempty"`
	SortField               string            `json:"sort_field,omitempty"`
	SortOrder               string            `json:"sort_order,omitempty"`
	FieldHints              []FieldHint       `json:"field_hints,omitempty"`
	SystemFields            []SystemFieldHint `json:"system_fields,omitempty"`
}

type ToolRequest

type ToolRequest struct {
	Name  string
	Args  map[string]any
	Owner string
	Site  string
	// Confirmed marks a call whose tool catalog and explicit confirmation the
	// adapter already enforced at its boundary. Kernel authorization still
	// runs. A confirmed call must carry the client's Idempotency-Key in
	// IdempotencyKey so retried mutations replay safely; IdempotencyKey is
	// ignored when Confirmed is false.
	Confirmed      bool
	IdempotencyKey string
	// Execution is the verified principal the resulting kernel commands are
	// bound to. A zero value falls back to the transaction manager's own.
	Execution policy.Execution
}

ToolRequest is one tool call made by an authenticated adapter.

Jump to

Keyboard shortcuts

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