Documentation
¶
Index ¶
- func AppendConversationMessage(ctx context.Context, db *sql.DB, msg MessageRecord) error
- func AppendMessage(ctx context.Context, db *sql.DB, msg MessageRecord) error
- func CancelRun(ctx context.Context, db *sql.DB, runID, reason string) error
- func CleanupExpired(ctx context.Context, db *sql.DB, now time.Time) (removed int64, err error)
- func ConversationSubjectKey(currentUser string, context ChatContext) string
- func EnsureAIRunTables(ctx context.Context, db *sql.DB, dialects ...kdb.Dialect) error
- func EnsureApprovalPending(ctx context.Context, db *sql.DB, req ApprovalRequest) error
- func ExecuteTool(tx *orm.TxManager, reg *doctype.Registry, req ToolRequest) string
- func FinalizeBudget(ctx context.Context, db *sql.DB, res BudgetReservation, consumedTokens int) error
- func HandleChat(c *gin.Context, tx *orm.TxManager, reg *doctype.Registry, ...)
- func HasGrantedApproval(ctx context.Context, db *sql.DB, target ApprovalTarget) (bool, error)
- func ListRunSteps(ctx context.Context, db *sql.DB, runID string) ([]string, error)
- func MarkRunPendingApproval(ctx context.Context, db *sql.DB, runID, stepID, reason string) error
- func MarkTaskStatus(ctx context.Context, db *sql.DB, taskID, status, notes string) error
- func QueueFollowUpTasks(ctx context.Context, db *sql.DB, scope RunScope, tasks []TaskRecord) error
- func RecordAudit(ctx context.Context, db *sql.DB, ev AuditEvent) error
- func RecordUsage(ctx context.Context, db *sql.DB, ev contract.UsageEvent) error
- func RefreshRunSummary(ctx context.Context, db *sql.DB, runID string) error
- func ReleaseBudget(ctx context.Context, db *sql.DB, res BudgetReservation) error
- func SummarizeRun(ctx context.Context, db *sql.DB, runID string) error
- func ToContractCatalog(c ToolCatalog) contract.ToolCatalog
- func ToContractDescriptor(d ToolDescriptor) contract.ToolDescriptor
- func UpdateStepStatus(ctx context.Context, db *sql.DB, stepID string, upd StepUpdate) error
- func UpsertApproval(ctx context.Context, db *sql.DB, rec ApprovalRecord) error
- func UpsertConversation(ctx context.Context, db *sql.DB, rec ConversationRecord) error
- func UpsertRun(ctx context.Context, db *sql.DB, rec RunRecord) error
- func UpsertStep(ctx context.Context, db *sql.DB, step StepRecord) error
- func UpsertTask(ctx context.Context, db *sql.DB, rec TaskRecord) error
- func ValidateProviderProfile(p ProviderProfile) error
- func WithDialect(ctx context.Context, dialect kdb.Dialect) context.Context
- type AIConfig
- type ApprovalRecord
- func GrantApproval(ctx context.Context, db *sql.DB, approvalID, grantedBy string) (ApprovalRecord, error)
- func GrantApprovalForOperation(ctx context.Context, db *sql.DB, target ApprovalTarget, grantedBy string) (ApprovalRecord, error)
- func GrantApprovalForOwner(ctx context.Context, db *sql.DB, site, approvalID, ownerID string) (ApprovalRecord, error)
- func LoadApproval(ctx context.Context, db *sql.DB, approvalID string) (ApprovalRecord, error)
- type ApprovalRequest
- type ApprovalTarget
- type AuditEvent
- type BudgetRequest
- type BudgetReservation
- type ChatContext
- type ChatMessage
- type ChatRequest
- type ChatResponse
- type ConversationRecord
- type FieldHint
- type MessageRecord
- type ProviderProfile
- type RunRecord
- type RunScope
- type RunStatusCount
- type RunStatusInventory
- type StepRecord
- type StepUpdate
- type SystemFieldHint
- type TaskRecord
- type ToolCatalog
- type ToolDescriptor
- type ToolRequest
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AppendConversationMessage ¶
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 ¶
AppendMessage stores msg at its explicit Sequence.
func CleanupExpired ¶
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 EnsureApprovalPending ¶
EnsureApprovalPending records req as awaiting approval.
func ExecuteTool ¶
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 ¶
HasGrantedApproval reports whether target has a granted approval.
func ListRunSteps ¶
func MarkRunPendingApproval ¶
func MarkTaskStatus ¶
func QueueFollowUpTasks ¶
QueueFollowUpTasks stores tasks under scope, defaulting an empty Status to "queued" and an empty Kind to "task".
func RecordAudit ¶
func RecordUsage ¶
RecordUsage stores an immutable AI usage event.
func RefreshRunSummary ¶
RefreshRunSummary rolls the latest step and message content into the run and conversation summary.
func ReleaseBudget ¶
ReleaseBudget marks a reservation as released.
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 ¶
UpdateStepStatus applies the non-empty fields of upd to the step stepID.
func UpsertApproval ¶
func UpsertConversation ¶
func UpsertStep ¶
UpsertStep inserts step or updates the stored row with the same ID.
func UpsertTask ¶
func ValidateProviderProfile ¶
func ValidateProviderProfile(p ProviderProfile) error
ValidateProviderProfile rejects incomplete or mismatched provider settings before the first provider request is made.
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.
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 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 ¶
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 ¶
ApprovalTarget identifies one tool call, by its arguments, within an operation (an AI run) of a tenant.
type AuditEvent ¶
type BudgetRequest ¶
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 ¶
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 LoadConversationByID ¶
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 ¶
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 MarkRunPlanning ¶
type RunStatusCount ¶
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 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 ¶
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.