Documentation
¶
Overview ¶
Package assistantrequest is everything a person and the dispatch worker do with an AI connection's cache-clear request once the connection has asked: the queue, approve and decline, the worker that sends an approved request to the site, and the sweeper and reconciler that close whatever is left open.
Creation, the status tool and the revoke cascade live in internal/mcp. This package imports mcp and never the reverse.
No automation approves anything here. Approve and decline are refused to every principal except a person signed in to the dashboard, and the worker sends only a row a person approved.
Index ¶
- Constants
- func QueueForTenant(tenantID uuid.UUID) string
- func Queues() map[string]river.QueueConfig
- func WriteToolsFromEnv(value string) (bool, error)
- type ApproveBody
- type DispatchArgs
- type DispatchWorker
- type Enqueuer
- type GrantAuthorizer
- type GrantVerdicts
- type Handler
- type ListResponse
- type PurgeSender
- type Queue
- type ReconcileArgs
- type ReconcileWorker
- type Repo
- type Request
- type RequestDTO
- type RiverEnqueuer
- type ScanArgs
- type ScanWorker
- type Service
- func (s *Service) Approve(ctx context.Context, approver domain.Principal, siteID, requestID uuid.UUID, ...) (Request, error)
- func (s *Service) Decline(ctx context.Context, decider domain.Principal, siteID, requestID uuid.UUID) (Request, error)
- func (s *Service) List(ctx context.Context, p domain.Principal, siteID *uuid.UUID, ...) (Queue, error)
- func (s *Service) Render(ctx context.Context, p domain.Principal, ...) ([]Request, error)
- func (s *Service) SetSender(sender PurgeSender, store SiteCacheStore)
- func (s *Service) SetWriteToolsEnabled(on bool)
- type SiteCacheStore
- type SweepArgs
- type SweepWorker
Constants ¶
const ( StatePending = "pending" StateApproved = "approved_undispatched" StateDispatched = "dispatched" StateRejected = "rejected" StateWithdrawn = "withdrawn" StateExpired = "expired" )
Request states (assistant_cache_purge_requests.state).
const ( OutcomePurged = "purged" OutcomeSiteReportedFailure = "site_reported_failure" OutcomeAgentFailed = "agent_failed" OutcomeUnknown = "outcome_unknown" OutcomeNotSent = "not_sent" )
Outcomes of a dispatched request.
const ( ReasonGrantInactive = "grant_inactive" ReasonAssistantPaused = "assistant_paused" ReasonOrganisationDeleted = "organisation_deleted" ReasonCapabilityNotHeld = "capability_not_held" ReasonSiteAbsent = "site_absent" ReasonForbiddenByContext = "forbidden_by_context" ReasonAgentOutdated = "agent_outdated" ReasonDispatchDeadlinePassed = "dispatch_deadline_passed" ReasonTransportPreSend = "transport_pre_send" )
Reasons a request closed without being sent.
const ( AttemptSiteUnreachable = "site_unreachable" AttemptSiteCooldown = "site_cooldown" AttemptSiteHourlyCap = "site_hourly_cap" AttemptSiteBusy = "site_busy" AttemptOrgBusy = "org_busy" AttemptWriteToolsDisabled = "write_tools_disabled" )
Transient reasons an approved request has not started yet. The row stays approved and the worker tries again.
const ( // DispatchDeadline is how long after approval a request may still start. // The worker enforces it, and the sweeper closes anything past it. DispatchDeadline = time.Hour // WholeSiteCooldown is the minimum gap after any whole-site clear on a // site, whoever made it, before an approved AI whole-site clear runs. WholeSiteCooldown = 5 * time.Minute // SiteHourlyCap is the most AI clears one site takes in an hour. SiteHourlyCap = 12 // StaleDispatchAfter is how long a sent request may wait for its outcome // before the reconciler records that the outcome is unknown. StaleDispatchAfter = 10 * time.Minute // ScanInterval is how often the worker looks for approved requests. ScanInterval = 15 * time.Second // SweepInterval is how often the sweeper and the reconciler run. SweepInterval = time.Minute // BackoffBase and BackoffCap bound how soon a request that could not start // is tried again: BackoffBase, doubling per attempt, capped. BackoffBase = 30 * time.Second BackoffCap = 5 * time.Minute // CardCopyVersion names the wording of the approval card a person // approved. It is recorded on assistant.request.approved, and it is the // same constant the creation rail puts in the request's digest. CardCopyVersion = mcp.CacheRequestCardCopyVersion )
Timing and limits. Every window is measured by the database clock; these are passed to it as whole seconds.
const ( CodeRequestChanged = "assistant_request_changed" CodeAssistantPaused = "assistant_paused" CodeWriteToolsDisabled = "assistant_write_tools_disabled" CodeConnectionInactive = "assistant_connection_inactive" CodeSiteLeftScope = "assistant_site_left_scope" CodeCapabilityNotHeld = "assistant_capability_not_held" CodeForbiddenByContext = "assistant_forbidden_by_context" CodeAgentOutdated = "assistant_agent_outdated" CodeSiteAbsent = "assistant_site_absent" CodeSessionRequired = "assistant_session_required" CodeLedgerFailed = "assistant_ledger_failed" )
Variables ¶
This section is empty.
Functions ¶
func QueueForTenant ¶
QueueForTenant is the dispatch queue a tenant's jobs run on.
func Queues ¶
func Queues() map[string]river.QueueConfig
Queues is the River queue configuration the dispatch jobs need.
func WriteToolsFromEnv ¶
WriteToolsFromEnv parses WPMGR_MCP_WRITE_TOOLS. Unset or "off" is off; "on" is on; anything else is an error, so a typo fails boot rather than silently choosing a side.
Types ¶
type ApproveBody ¶
type ApproveBody struct {
PresentedDigest string `json:"presented_digest"`
}
ApproveBody is the approve request body.
type DispatchArgs ¶
type DispatchArgs struct {
TenantID uuid.UUID `json:"tenant_id"`
RequestID uuid.UUID `json:"request_id"`
SiteID uuid.UUID `json:"site_id"`
GrantID uuid.UUID `json:"grant_id"`
}
DispatchArgs is one approved request to try. It carries ids only; the worker re-reads everything it acts on.
func (DispatchArgs) InsertOpts ¶
func (a DispatchArgs) InsertOpts() river.InsertOpts
InsertOpts pins the job to its tenant's shard and keeps at most one live job per request, so a scan every few seconds never stacks duplicates.
type DispatchWorker ¶
type DispatchWorker struct {
river.WorkerDefaults[DispatchArgs]
// contains filtered or unexported fields
}
DispatchWorker tries one approved request.
func NewDispatchWorker ¶
func NewDispatchWorker(svc *Service) *DispatchWorker
NewDispatchWorker builds the dispatch worker.
func (*DispatchWorker) Timeout ¶
func (w *DispatchWorker) Timeout(*river.Job[DispatchArgs]) time.Duration
Timeout bounds one dispatch: the send is bounded well below it.
func (*DispatchWorker) Work ¶
func (w *DispatchWorker) Work(ctx context.Context, job *river.Job[DispatchArgs]) error
Work tries one approved request.
type Enqueuer ¶
type Enqueuer interface {
EnqueueDispatch(ctx context.Context, args DispatchArgs) error
}
Enqueuer inserts dispatch jobs. The River client satisfies it through RiverEnqueuer.
type GrantAuthorizer ¶
type GrantAuthorizer interface {
AuthorizeGrant(ctx context.Context, tenantID uuid.UUID, v mcp.GrantVerdict) (mcp.AuthorizedRequest, error)
ForbiddenByContext(ctx context.Context, tenantID, siteID uuid.UUID, tool string) (matchedEntry string, forbidden bool, err error)
}
GrantAuthorizer derives what a verdict confers and reads the operator's AI rules. *mcp.Service satisfies it.
type GrantVerdicts ¶
type GrantVerdicts interface {
ReCheckGrantAuthorization(ctx context.Context, tenantID, grantID uuid.UUID) (mcp.GrantVerdict, error)
}
GrantVerdicts reads a connection's grant-level verdict with no token in hand. *mcp.Repo satisfies it.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler serves the AI request queue and the approve and decline routes.
func (*Handler) Register ¶
func (h *Handler) Register(r *gin.RouterGroup)
Register mounts the routes on the authenticated /api/v1 group:
GET /ai/requests GET /sites/:siteId/ai/requests POST /sites/:siteId/ai/requests/:requestId/approve POST /sites/:siteId/ai/requests/:requestId/decline
Every route needs site.cache.purge. The by-site routes also pass the site-access gate, and approve and decline take JSON only, which is the CSRF guard for a cookie-authenticated change.
type ListResponse ¶
type ListResponse struct {
Requests []RequestDTO `json:"requests"`
PendingCount int64 `json:"pending_count"`
Limit int32 `json:"limit"`
Offset int32 `json:"offset"`
}
ListResponse is a page of the queue.
type PurgeSender ¶
type PurgeSender interface {
SendAssistantPurge(ctx context.Context, siteID uuid.UUID, siteURL string, cdn perf.CDNCiphertext, req perf.AssistantPurge) (perf.AssistantPurgeResult, error)
PublishAssistantPurge(ctx context.Context, tenantID, siteID uuid.UUID, scope string)
}
PurgeSender sends an approved clear and announces it. *perf.Service satisfies it. Neither method touches the database.
type ReconcileArgs ¶
type ReconcileArgs struct{}
ReconcileArgs is the periodic reconciler: a sent request with no outcome after StaleDispatchAfter is recorded as outcome unknown.
type ReconcileWorker ¶
type ReconcileWorker struct {
river.WorkerDefaults[ReconcileArgs]
// contains filtered or unexported fields
}
ReconcileWorker runs the reconciler.
func NewReconcileWorker ¶
func NewReconcileWorker(svc *Service) *ReconcileWorker
NewReconcileWorker builds the reconciler.
func (*ReconcileWorker) Work ¶
func (w *ReconcileWorker) Work(ctx context.Context, _ *river.Job[ReconcileArgs]) error
Work runs one reconcile pass.
type Repo ¶
type Repo struct {
// contains filtered or unexported fields
}
Repo opens the transactions this package runs in. It never sets a GUC itself; every transaction comes from a db helper chosen by principal.
Which helper, per path (the principal invariant):
- the queue, approve and decline run under the calling person's own principal (runAsCaller);
- every read or write of site data on the approve and dispatch paths, and every worker write to a request row, runs under a single-site principal from mcp.SingleSitePrincipal, opened with mcp.AssertSingleSiteTx (runSiteTx);
- the three cross-tenant scans are plain reads under the agent context (runAgentScan);
- the only tenant transactions are closeWithoutSite, the sweeper and the reconciler, which call the pool directly and touch nothing but the request row and the audit log.
type Request ¶
type Request struct {
ID uuid.UUID
SiteID uuid.UUID
Scope string
URL *string
SiteLabel string
SiteHost string
GrantLabel string
GrantVia string
SetupClient *string
PresentedDigest *string
State string
CreatedAt time.Time
ExpiresAt time.Time
DecidedAt *time.Time
DecidedByUserID *uuid.UUID
DecidedByName *string
DecidedByDeleted bool
WithdrawnAt *time.Time
ClaimedAt *time.Time
DispatchAttempts int32
LastAttemptAt *time.Time
LastAttemptCode *string
Outcome *string
NotSentReason *string
OutcomeAt *time.Time
HostingCachesCleared []string
HostingCachesSkipped []string
OriginOnlyConfirmed *bool
WpmgrCDN *string
SiteReportedText *string
}
Request is one request as the queue shows it to a person.
type RequestDTO ¶
type RequestDTO struct {
ID uuid.UUID `json:"id"`
SiteID uuid.UUID `json:"site_id"`
Scope string `json:"scope"`
URL *string `json:"url"`
SiteLabel string `json:"site_label"`
SiteHost string `json:"site_host"`
GrantLabel string `json:"grant_label"`
GrantVia string `json:"grant_via"`
SetupClient *string `json:"setup_client"`
PresentedDigest *string `json:"presented_digest,omitempty"`
State string `json:"state"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
DecidedAt *time.Time `json:"decided_at"`
DecidedByUserID *uuid.UUID `json:"decided_by_user_id"`
DecidedByName *string `json:"decided_by_name"`
DecidedByAccountDelete bool `json:"decided_by_account_deleted"`
WithdrawnAt *time.Time `json:"withdrawn_at"`
ClaimedAt *time.Time `json:"claimed_at"`
DispatchAttempts int32 `json:"dispatch_attempts"`
LastAttemptAt *time.Time `json:"last_attempt_at"`
LastAttemptCode *string `json:"last_attempt_code"`
Outcome *string `json:"outcome"`
NotSentReason *string `json:"not_sent_reason"`
OutcomeAt *time.Time `json:"outcome_at"`
HostingCachesCleared []string `json:"hosting_caches_cleared"`
HostingCachesSkipped []string `json:"hosting_caches_skipped"`
OriginOnlyConfirmed *bool `json:"origin_only_confirmed"`
WpmgrCDN *string `json:"wpmgr_cdn"`
SiteReportedText *string `json:"site_reported_text"`
}
RequestDTO is one request on the wire. Every text field that came from a site or an AI connection (site_label, site_host, grant_label, url, site_reported_text) is text to render as a text node, never markup, a link or a tooltip. presented_digest is present only for a signed-in person; digest_nonce is never returned.
type RiverEnqueuer ¶
type RiverEnqueuer struct {
// contains filtered or unexported fields
}
RiverEnqueuer inserts dispatch jobs on a started River client.
func NewRiverEnqueuer ¶
func NewRiverEnqueuer(client *river.Client[pgx.Tx]) *RiverEnqueuer
NewRiverEnqueuer wraps a started River client.
func (*RiverEnqueuer) EnqueueDispatch ¶
func (e *RiverEnqueuer) EnqueueDispatch(ctx context.Context, args DispatchArgs) error
EnqueueDispatch inserts one dispatch job.
type ScanArgs ¶
type ScanArgs struct{}
ScanArgs is the periodic scan for approved requests that are due.
type ScanWorker ¶
type ScanWorker struct {
river.WorkerDefaults[ScanArgs]
// contains filtered or unexported fields
}
ScanWorker runs the scan. It runs whether or not write tools are on, so a switched-off server still records why each approved row is waiting.
func NewScanWorker ¶
func NewScanWorker(svc *Service) *ScanWorker
NewScanWorker builds the scan worker. Wire the enqueuer after River starts.
func (*ScanWorker) SetEnqueuer ¶
func (w *ScanWorker) SetEnqueuer(e Enqueuer)
SetEnqueuer wires the River enqueuer.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the queue, approve and decline, and the dispatch worker's logic.
func NewService ¶
func NewService(repo *Repo, grants GrantVerdicts, authz GrantAuthorizer, rec *audit.Recorder, logger *slog.Logger) *Service
NewService builds the service. The write-tools switch starts OFF; call SetWriteToolsEnabled.
func (*Service) Approve ¶
func (s *Service) Approve(ctx context.Context, approver domain.Principal, siteID, requestID uuid.UUID, presentedDigest string) (Request, error)
Approve records one person's approval of one request. The grant checks run first and are advisory: the worker re-runs every one of them before sending. The approval and its audit row commit together or not at all.
func (*Service) Decline ¶
func (s *Service) Decline(ctx context.Context, decider domain.Principal, siteID, requestID uuid.UUID) (Request, error)
Decline records one person's refusal. There are no grant checks, so declining always works while the request is waiting.
func (*Service) List ¶
func (s *Service) List(ctx context.Context, p domain.Principal, siteID *uuid.UUID, limit, offset int32) (Queue, error)
List returns a page of this organisation's requests visible to p, newest first, and the number waiting. Row security narrows a site collaborator to their own sites. The digest is included only for a signed-in person.
func (*Service) Render ¶
func (s *Service) Render(ctx context.Context, p domain.Principal, rows []sqlc.AssistantCachePurgeRequest) ([]Request, error)
Render maps rows the caller already read to requests as the queue returns them, naming each deciding person under the caller's principal.
func (*Service) SetSender ¶
func (s *Service) SetSender(sender PurgeSender, store SiteCacheStore)
SetSender wires the send path. Without it nothing is ever sent: approve is refused as switched off and the worker records write_tools_disabled.
func (*Service) SetWriteToolsEnabled ¶
SetWriteToolsEnabled is the server-wide switch. Off: approve is refused and the worker records write_tools_disabled on every approved row, which the sweeper then closes at its deadline. The sweeper, the reconciler and decline keep working either way.
type SiteCacheStore ¶
type SiteCacheStore interface {
GetCDNCredentialsCiphertextTx(ctx context.Context, tx pgx.Tx, tenantID, siteID uuid.UUID) (perf.CDNCiphertext, error)
MarkCachePurgedTx(ctx context.Context, tx pgx.Tx, tenantID, siteID uuid.UUID, kind string) error
}
SiteCacheStore reads and writes the site's cache settings on a transaction the caller holds. *perf.Repo satisfies it.
type SweepArgs ¶
type SweepArgs struct{}
SweepArgs is the periodic sweeper: waiting requests past their window become expired, and approved requests past their dispatch deadline close.
type SweepWorker ¶
type SweepWorker struct {
river.WorkerDefaults[SweepArgs]
// contains filtered or unexported fields
}
SweepWorker runs the sweeper.
func NewSweepWorker ¶
func NewSweepWorker(svc *Service) *SweepWorker
NewSweepWorker builds the sweeper.