systemchat

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2026 License: AGPL-3.0 Imports: 23 Imported by: 0

Documentation

Overview

Package systemchat owns system conversation admission and durable execution state.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AsyncPrincipal

func AsyncPrincipal(ctx context.Context, q *dbq.Queries, originID pgtype.UUID) (authz.Principal, error)

AsyncPrincipal resolves a system-originated operation through its persisted initiating run. The caller must also authorize the operation's target resource.

func CaptureAsyncOrigin

func CaptureAsyncOrigin(ctx context.Context, q *dbq.Queries, p authz.Principal, agentID uuid.UUID, conversation string) (pgtype.UUID, error)

CaptureAsyncOrigin persists the server-installed system run before async dispatch. A request's conversation field is a consistency check, not authority.

func CaptureHostedAsyncOrigin

func CaptureHostedAsyncOrigin(ctx context.Context, q *dbq.Queries, agentID, runID uuid.UUID) (pgtype.UUID, error)

CaptureHostedAsyncOrigin receives a host-resolved runtime run, not the builder's codegen correlation UUID or a client-supplied sourceRunId.

func FreshPrincipal

func FreshPrincipal(ctx context.Context, q *dbq.Queries, p authz.Principal) (authz.Principal, error)

FreshPrincipal accepts only an admission proof and resolves its live authority.

func OriginRunID

func OriginRunID(ctx context.Context) uuid.UUID

OriginRunID is zero for operations that do not originate in system chat.

func Platform

func Platform(p authz.Principal) string

func ToolAvailable

func ToolAvailable(ctx context.Context, q *dbq.Queries, p authz.Principal, action authz.Action) bool

ToolAvailable is catalogue filtering, not the target resource's invocation gate.

Types

type ConversationDetail

type ConversationDetail struct {
	Conversation dbq.SystemConversation
	Messages     []dbq.SystemMessage
}

ConversationDetail bundles a conversation with its full message history. The caller decides whether to also request paginated tails separately for very long conversations (we don't paginate on the initial Get because chat conversations rarely grow beyond a few dozen messages — agent chat pages from the same shape).

type ListRunsResult

type ListRunsResult struct {
	Runs       []RunSummary
	NextCursor time.Time
}

ListRunsResult bundles a page of runs with the cursor for the next page (zero StartedAt when no further pages exist).

type PromptInput

type PromptInput struct {
	Message string
	// Platform is display-only. Admission derives the channel from Identity.
	Platform    string
	Approved    *bool
	ResumeRunID string
}

type RunSummary

type RunSummary struct {
	ID                uuid.UUID
	ConversationID    uuid.UUID
	ConversationTitle string
	Status            string // 'running' | 'suspended' | 'complete' | 'error' | 'cancelled'
	TriggerType       string // 'prompt' | 'bridge' | 'event'
	MessagePreview    string // first linked message for the turn (” when no message is bound)
	ErrorMessage      string
	CostEstimate      float64
	StartedAt         time.Time
	FinishedAt        *time.Time
}

RunSummary is one row from the caller's sysagent activity view — run lifecycle (status + timestamps) plus the parent conversation's title so the UI can render without a per-row fetch.

type Service

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

func New

func New(d *db.DB, logger *zap.Logger) *Service

func (*Service) AgentAccess

func (s *Service) AgentAccess(ctx context.Context, p authz.Principal, agentID uuid.UUID) (string, error)

func (*Service) AppendNotification

func (s *Service) AppendNotification(ctx context.Context, agentID, conversationID, originRunID uuid.UUID, source, content string) (dbq.SystemConversation, error)

func (*Service) CancelRun

func (s *Service) CancelRun(ctx context.Context, p authz.Principal, runID uuid.UUID) (bool, error)

CancelRun serializes with admission and suspension on the conversation row.

func (*Service) CheckRun

func (s *Service) CheckRun(ctx context.Context, p authz.Principal, runID uuid.UUID) error

CheckRun rechecks the original credential and durable cancellation before work.

func (*Service) Control

func (s *Service) Control(ctx context.Context, p authz.Principal, conversationID uuid.UUID, command, args string) (bool, error)

Control serializes conversation controls with run admission and history writes.

func (*Service) CreateConversation

func (s *Service) CreateConversation(ctx context.Context, p authz.Principal, title string) (dbq.SystemConversation, error)

CreateConversation inserts a fresh conversation for the caller. title is optional; the DB default is "New chat".

func (*Service) DeleteConversation

func (s *Service) DeleteConversation(ctx context.Context, p authz.Principal, conversationID uuid.UUID) error

DeleteConversation removes a conversation (and via ON DELETE CASCADE its messages, runs, and any pending checkpoint state). audit rows for the conversation stay (ON DELETE SET NULL preserves forensics — what happened in a now-deleted conversation is still recoverable).

func (*Service) EnsureBridgeConversation

func (s *Service) EnsureBridgeConversation(ctx context.Context, p authz.Principal) (dbq.SystemConversation, error)

EnsureBridgeConversation derives every routing coordinate from the poller's live admission proof. No user ID, bridge ID or chat ID is accepted separately.

func (*Service) FinishRun

func (s *Service) FinishRun(ctx context.Context, runID uuid.UUID, status, message string) error

func (*Service) GetConversation

func (s *Service) GetConversation(ctx context.Context, p authz.Principal, conversationID uuid.UUID) (ConversationDetail, error)

GetConversation returns the conversation + its full message history (including pre-checkpoint rows + checkpoint markers — the UI's full timeline, not the LLM context filter). 404 for a missing conversation, 404 (not 403) for someone else's — exposing existence to non-owners would leak metadata.

func (*Service) ListConversations

func (s *Service) ListConversations(ctx context.Context, p authz.Principal) ([]dbq.SystemConversation, error)

ListConversations returns the caller's own conversations, newest-active first. Ownership is enforced at the query level — conversations aren't shared.

func (*Service) ListRuns

func (s *Service) ListRuns(ctx context.Context, p authz.Principal, cursor time.Time, limit int32) (ListRunsResult, error)

ListRuns returns the caller's recent sysagent runs across all their conversations, newest first. Cursor is the started_at of the last row from the previous page; zero fetches the newest page. Caller must be authenticated; the query is owner-scoped (user_id = p.UserID) so no cross-user leak is possible.

func (*Service) ObserveRun

func (s *Service) ObserveRun(ctx context.Context, p authz.Principal, runID uuid.UUID, cancel context.CancelFunc)

ObserveRun makes cancellations and credential revocations visible on every replica. Database failures stop execution rather than letting an unvalidated turn continue.

func (*Service) PersistSuspension

func (s *Service) PersistSuspension(ctx context.Context, conversationID, runID uuid.UUID, checkpoint []byte) error

func (*Service) RecordSystemRunUsage

func (s *Service) RecordSystemRunUsage(runID, userID uuid.UUID, providerCatalogID, providerSlug, model string, usage stream.Usage, errored bool)

recordSystemRunUsage writes this turn's accumulated model spend to the shared llm_usage ledger and refreshes the system run's cost aggregate.

The sysagent runs the model loop in-process, so there is one accumulated stream.Usage per turn (not one per round-trip like the runtime proxy) — recorded as a single ledger row attributed to the operator (UserID) and this system run (SystemRunID), call_kind "system". agent_id is left null: the system agent has no agent row. Cost is computed from the same sol/provider catalog every other ledger writer uses.

Best-effort: accounting must never break a turn that already ran. Uses a fresh bounded ctx so a cancelled turn still records the tokens it burned.

func (*Service) ResumePrincipal

func (s *Service) ResumePrincipal(ctx context.Context, conversationID, originRunID uuid.UUID) (authz.Principal, error)

func (*Service) RunContext

func (s *Service) RunContext(ctx context.Context, p authz.Principal, runID uuid.UUID) (context.Context, error)

RunContext binds downstream build/bot admission to this verified system run. Those services persist OriginRunID alongside their asynchronous work record.

func (*Service) RunPrincipal

func (s *Service) RunPrincipal(ctx context.Context, runID uuid.UUID) (authz.Principal, error)

RunPrincipal restores the exact original admission, including for follow-ups.

func (*Service) SessionStore

func (s *Service) SessionStore(ctx context.Context, p authz.Principal, conversationID, runID uuid.UUID) (*sessionStore, error)

func (*Service) Settings

func (s *Service) Settings(ctx context.Context, p authz.Principal) (dbq.SystemSetting, error)

func (*Service) StartRun

func (s *Service) StartRun(ctx context.Context, p authz.Principal, conversationID uuid.UUID, input PromptInput) (uuid.UUID, dbq.SystemConversation, error)

func (*Service) User

func (s *Service) User(ctx context.Context, p authz.Principal) (dbq.User, error)

func (*Service) UserAgentGrants

func (s *Service) UserAgentGrants(ctx context.Context, p authz.Principal) ([]dbq.ListUserAgentGrantsRow, error)

Jump to

Keyboard shortcuts

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