Documentation
¶
Index ¶
- Constants
- Variables
- func RunStatusIsCancellable(status string) bool
- type AccountContext
- type AgentAccountStatusInfo
- type AgentAccountStatusRepo
- type AgentActionRepo
- type AgentArtifactRepo
- type AgentConfigRepo
- type AgentDefinitionInfo
- type AgentDefinitionRepo
- type AgentDefinitionSvc
- type AgentDefinitionToolInfo
- type AgentDefinitionToolRepo
- type AgentMemoryInfo
- type AgentMemoryRepo
- type AgentRunEventRepo
- type AgentRunRepo
- type AgentTokenRate
- type AgentTokenUsageRepo
- type AvailableToolInfo
- type BillingCustomerResolver
- type CancelRunParams
- type ChatHistoryMessage
- type ChatRunInput
- type ContinueRunParams
- type CoreClient
- type CreateAgentMemoryParams
- type CreateCustomAgentParams
- type DeleteAgentMemoryParams
- type DeleteCustomAgentParams
- type DeletedRecordRepo
- type GatewayClient
- type GatewayRequest
- type HandlerRunContext
- type IdempotencyKey
- type IdempotencyKeyRepo
- type IdempotencyMed
- type ListAgentDefinitionsParams
- type ListAgentDefinitionsResult
- type ListAvailableToolsParams
- type MediatorFactory
- type Mediators
- type ModelInfo
- type NotificationClient
- type PageInfo
- type PendingAction
- type PendingArtifact
- type PostReplyDraftRequest
- type RecoveryPoint
- type RepoFactory
- type RequestIdentity
- type RetryRunParams
- type RunContext
- type RunResult
- type RunnerSvc
- type SchedulerSvc
- type SendInboxReplyRequest
- type ToolGroupInfo
- type ToolHandlerFunc
- type ToolLinkParams
- type TriggerRunParams
- type UpdateAgentAccountStatusParams
- type UpdateAgentMemoryParams
- type UpdateCustomAgentParams
Constants ¶
const ( RunStatusPending = "pending" RunStatusRunning = "running" RunStatusCompleted = "completed" RunStatusFailed = "failed" RunStatusCancelled = "cancelled" RunStatusAwaitingInput = "awaiting_input" RunStatusAwaitingApproval = "awaiting_approval" )
Run statuses
const ( ActionStatusPendingReview = "pending_review" ActionStatusAutoApproved = "auto_approved" ActionStatusApproved = "approved" ActionStatusRejected = "rejected" ActionStatusExecuted = "executed" ActionStatusFailed = "failed" )
Action statuses
const ( AgentAccountStatusActive = "active" AgentAccountStatusInactive = "inactive" )
Agent account statuses
const DefaultModel = string(constants.ModelClaudeSonnet4)
DefaultModel is the model used when none is specified.
const MaxAutoRetries = 3
MaxAutoRetries bounds how many times the runner will transparently auto-retry a run that failed on a transient, whole-chain-unavailable error before it leaves side effects (runCtx.Actions empty). It shares the agent_run.retry_count budget with manual retries and is intentionally smaller than MaxManualRetries so an automatic retry storm cannot exhaust a user's ability to retry by hand.
const MaxManualRetries = 5
MaxManualRetries bounds how many times a failed run may be re-attempted (manual + automatic combined, tracked by agent_run.retry_count) before retry is refused.
const (
ServiceName = "agent-service"
)
Variables ¶
var AllowedModels = func() map[string]bool { allowed := make(map[string]bool, len(AvailableModels)) for _, m := range AvailableModels { allowed[string(m.Code)] = true } return allowed }()
AllowedModels is the strict allowlist of model codes agents may use, derived from AvailableModels.
var AvailableModels = func() []ModelInfo { out := make([]ModelInfo, len(constants.ModelCatalog)) for i, s := range constants.ModelCatalog { out[i] = ModelInfo{Code: s.ID, Name: s.Name, Provider: s.Provider} } return out }()
AvailableModels is the ordered catalog of LLM models agents may use, derived from the shared constants.ModelCatalog (the single source of truth) so the model-list endpoint and the AllowedModels validation set never drift from the create-agent enum.
Functions ¶
func RunStatusIsCancellable ¶
RunStatusIsCancellable reports whether a run in this status can still be stopped by a user. A run is cancellable while it is doing or waiting to do work — actively running/pending, or paused awaiting the user (a chat run between turns, or one blocked on tool approval). The terminal states (completed/failed/cancelled) have nothing left to stop.
Types ¶
type AccountContext ¶
type AccountContext struct {
IsSandbox bool
OwnerAccountID string
PlanCode string
AgentMonthlySpendingCapCents *int64
}
AccountContext holds billing-relevant metadata for an account.
type AgentAccountStatusInfo ¶
type AgentAccountStatusInfo struct {
ID string
AccountID string
AgentDefinitionID string
StatusCode string `audit:"status_code"`
CreatedAt time.Time
UpdatedAt time.Time
}
AgentAccountStatusInfo is the domain representation of a per-account status for an agent definition.
type AgentAccountStatusRepo ¶
type AgentAccountStatusRepo interface {
Upsert(ctx context.Context, params sqlc.UpsertAgentAccountStatusParams) *apierror.APIError
GetByAccountAndDefinition(ctx context.Context, accountID, agentDefinitionID string) (*sqlc.AgentAccountStatus, *apierror.APIError)
ListByAccount(ctx context.Context, accountID string) ([]sqlc.AgentAccountStatus, *apierror.APIError)
DeleteByAccountAndDefinition(ctx context.Context, accountID, agentDefinitionID string) *apierror.APIError
}
type AgentActionRepo ¶
type AgentActionRepo interface {
Insert(ctx context.Context, params sqlc.InsertAgentActionParams) *apierror.APIError
GetByID(ctx context.Context, id string) (*sqlc.AgentAction, *apierror.APIError)
ListByRun(ctx context.Context, runID string) ([]sqlc.AgentAction, *apierror.APIError)
UpdateStatus(ctx context.Context, params sqlc.UpdateAgentActionStatusParams) *apierror.APIError
// MarkReviewed records an approval/rejection decision on a pending action — its new status plus who reviewed it and when (for the audit trail). It does not touch executed_at; execution is separate.
MarkReviewed(ctx context.Context, params sqlc.MarkAgentActionReviewedParams) *apierror.APIError
}
type AgentArtifactRepo ¶
type AgentConfigRepo ¶
type AgentConfigRepo interface {
GetByID(ctx context.Context, id string) (*sqlc.AgentConfig, *apierror.APIError)
Insert(ctx context.Context, params sqlc.InsertAgentConfigParams) *apierror.APIError
ListByAccount(ctx context.Context, accountID string) ([]sqlc.AgentConfig, *apierror.APIError)
ListEnabledWithSchedule(ctx context.Context) ([]sqlc.ListEnabledConfigsWithScheduleRow, *apierror.APIError)
GetByAccountAndDefinition(ctx context.Context, accountID, definitionID string) (*sqlc.AgentConfig, *apierror.APIError)
}
type AgentDefinitionInfo ¶
type AgentDefinitionInfo struct {
ID string
Name string `audit:"name"`
Slug string `audit:"slug"`
Description *string `audit:"description"`
DefinitionType string `audit:"definition_type"`
CategoryCode string `audit:"category_code"`
TriggerType string `audit:"trigger_type"`
IsEditable bool
Config json.RawMessage `audit:"config"`
RoleID string `audit:"role_id"`
Tools []AgentDefinitionToolInfo
AccountStatus *AgentAccountStatusInfo
CreatedAt time.Time
UpdatedAt time.Time
}
AgentDefinitionInfo is the domain representation of an agent definition with its linked tools.
type AgentDefinitionRepo ¶
type AgentDefinitionRepo interface {
GetByID(ctx context.Context, id string) (*sqlc.AgentDefinition, *apierror.APIError)
GetBySlug(ctx context.Context, slug string) (*sqlc.AgentDefinition, *apierror.APIError)
ListActive(ctx context.Context) ([]sqlc.AgentDefinition, *apierror.APIError)
Insert(ctx context.Context, params sqlc.InsertAgentDefinitionParams) *apierror.APIError
Update(ctx context.Context, params sqlc.UpdateAgentDefinitionParams) *apierror.APIError
SoftDelete(ctx context.Context, id, accountID string) *apierror.APIError
ListByAccount(ctx context.Context, accountID string) ([]sqlc.AgentDefinition, *apierror.APIError)
ListByAccountFiltered(ctx context.Context, accountID string, definitionTypes, triggerTypes []string) ([]sqlc.AgentDefinition, *apierror.APIError)
ListByAccountCursor(ctx context.Context, params sqlc.ListAgentDefinitionsByAccountCursorParams) ([]sqlc.AgentDefinition, *apierror.APIError)
GetByAccountAndSlug(ctx context.Context, slug, accountID string) (*sqlc.AgentDefinition, *apierror.APIError)
}
type AgentDefinitionSvc ¶
type AgentDefinitionSvc interface {
// CreateCustomAgent creates a new custom agent definition with optional tool links.
//
// Preconditions:
// - All referenced tool IDs must exist.
//
// Side effects:
// - Persists a new agent_definition row and associated agent_definition_tool rows.
// - Caches the response in the service idempotency key.
CreateCustomAgent(ctx context.Context, params CreateCustomAgentParams) (*AgentDefinitionInfo, *apierror.APIError)
// UpdateCustomAgent updates a custom agent definition and replaces its tool links.
//
// Preconditions:
// - The definition must exist, be of type "custom", and belong to the caller's account.
// - All referenced tool IDs must exist.
//
// Side effects:
// - Updates the agent_definition row, deletes existing tool links, and re-creates them from the provided list.
// - Caches the response in the service idempotency key.
UpdateCustomAgent(ctx context.Context, params UpdateCustomAgentParams) (*AgentDefinitionInfo, *apierror.APIError)
// DeleteCustomAgent soft-deletes a custom agent definition.
//
// Preconditions:
// - The definition must exist, be of type "custom", and belong to the caller's account.
//
// Side effects:
// - Sets is_active = false on the agent_definition row.
// - Caches the response in the service idempotency key.
DeleteCustomAgent(ctx context.Context, params DeleteCustomAgentParams) *apierror.APIError
// GetAgentDefinition returns a single agent definition with its tools. System definitions are visible to all accounts; custom definitions are only visible to their owner.
GetAgentDefinition(ctx context.Context, agentDefinitionID string, includes []string) (*AgentDefinitionInfo, *apierror.APIError)
// ListAgentDefinitions returns all active agent definitions visible to the given account (system definitions plus the account's custom ones).
ListAgentDefinitions(ctx context.Context, params ListAgentDefinitionsParams) (*ListAgentDefinitionsResult, *apierror.APIError)
// ListAvailableTools returns platform tool definitions that can be attached to agent definitions, along with tool groups. Results are filtered by query and paginated by cursor/limit when provided.
ListAvailableTools(ctx context.Context, params ListAvailableToolsParams) ([]AvailableToolInfo, []ToolGroupInfo, *apierror.APIError)
// UpdateAgentAccountStatus upserts the per-account status for an agent definition.
UpdateAgentAccountStatus(ctx context.Context, params UpdateAgentAccountStatusParams) (*AgentAccountStatusInfo, *apierror.APIError)
// TriggerRun creates an agent run and publishes an outbox message to execute it.
TriggerRun(ctx context.Context, params TriggerRunParams) (string, *apierror.APIError)
// CreateChatRun creates a chat-linked agent run (conversation_id + trigger_message_id, trigger_type=chat, input=Message) for an agent definition and publishes the execute command.
// Service-internal — called by the chat-run consumer when notification-service signals that an agent participant's trigger fired.
CreateChatRun(ctx context.Context, in ChatRunInput) *apierror.APIError
// CancelRun cancels a pending or running agent run.
CancelRun(ctx context.Context, params CancelRunParams) *apierror.APIError
// ContinueRun continues an agent run that is awaiting input, with idempotency support.
//
// 1. Validate the run exists, belongs to the account, and is awaiting input.
// 2. Update status to running and create an outbox message atomically.
// 3. Cache the success response for idempotent replay.
ContinueRun(ctx context.Context, params ContinueRunParams) (string, *apierror.APIError)
// RetryRun re-attempts a failed run by resuming its existing transcript — no new user message is added, so the agent picks up with full knowledge of what it already did (including any tool results), minimizing duplicate side effects vs. a fresh re-run. The atomic status→running transition (guarded on status='failed' and bounded by retry_count) is the source of truth that prevents double-retry races.
RetryRun(ctx context.Context, params RetryRunParams) (string, *apierror.APIError)
// CreateAgentMemory creates a new agent memory record.
CreateAgentMemory(ctx context.Context, params CreateAgentMemoryParams) (*AgentMemoryInfo, *apierror.APIError)
// UpdateAgentMemory updates an existing agent memory record.
UpdateAgentMemory(ctx context.Context, params UpdateAgentMemoryParams) (*AgentMemoryInfo, *apierror.APIError)
// DeleteAgentMemory deletes an agent memory record.
DeleteAgentMemory(ctx context.Context, params DeleteAgentMemoryParams) *apierror.APIError
}
AgentDefinitionSvc handles business logic for agent definitions, including CRUD operations with idempotency and tool management.
type AgentDefinitionToolInfo ¶
type AgentDefinitionToolInfo struct {
ID string
ToolSlug string
DisplayName string
Description string
ConfigSchema json.RawMessage
Category string
Config json.RawMessage
SortOrder int32
RequireReview bool
GroupID string
GroupName string
RequiredPermissions []string
}
AgentDefinitionToolInfo is the domain representation of a tool linked to an agent definition. Display metadata (DisplayName, Description, group, permissions) is resolved from the code catalog (agents.BuiltinTools) by ToolSlug, not stored.
type AgentDefinitionToolRepo ¶
type AgentDefinitionToolRepo interface {
Insert(ctx context.Context, params sqlc.InsertAgentDefinitionToolParams) *apierror.APIError
DeleteByAgentID(ctx context.Context, agentDefinitionID string) *apierror.APIError
ListByAgentDefinitionID(ctx context.Context, agentDefinitionID string) ([]sqlc.ListToolsByAgentDefinitionIDRow, *apierror.APIError)
}
type AgentMemoryInfo ¶
type AgentMemoryInfo struct {
ID string
AccountID string
Category string `audit:"category"`
Content string `audit:"content"`
Metadata string `audit:"metadata"`
EntityType string `audit:"entity_type"`
EntityID string `audit:"entity_id"`
Importance float64 `audit:"importance"`
ExpiresAt string `audit:"expires_at"`
CreatedAt string
UpdatedAt string
}
AgentMemoryInfo is the domain representation of an agent memory.
type AgentMemoryRepo ¶
type AgentMemoryRepo interface {
Insert(ctx context.Context, params sqlc.InsertAgentMemoryParams) *apierror.APIError
GetByID(ctx context.Context, id string) (*sqlc.AgentMemory, *apierror.APIError)
GetByIDs(ctx context.Context, accountID string, ids []string) ([]sqlc.AgentMemory, *apierror.APIError)
ListByAccount(ctx context.Context, accountID string, limit int32) ([]sqlc.AgentMemory, *apierror.APIError)
ListByEntity(ctx context.Context, accountID, entityType, entityID string, limit int32) ([]sqlc.AgentMemory, *apierror.APIError)
ListAccountMemories(ctx context.Context, accountID, entityID string, limit int32) ([]sqlc.AgentMemory, *apierror.APIError)
Update(ctx context.Context, params sqlc.UpdateAgentMemoryParams) *apierror.APIError
Delete(ctx context.Context, id, accountID string) *apierror.APIError
ListByAccountCursor(ctx context.Context, params sqlc.ListAgentMemoriesByAccountCursorParams) ([]sqlc.AgentMemory, *apierror.APIError)
}
type AgentRunEventRepo ¶
type AgentRunRepo ¶
type AgentRunRepo interface {
Insert(ctx context.Context, params sqlc.InsertAgentRunParams) *apierror.APIError
GetByID(ctx context.Context, id string) (*sqlc.AgentRun, *apierror.APIError)
ListByAccountFiltered(ctx context.Context, params sqlc.ListAgentRunsByAccountFilteredParams) ([]sqlc.AgentRun, *apierror.APIError)
UpdateStatus(ctx context.Context, id, status string) *apierror.APIError
MarkCancelledByUser(ctx context.Context, id string) *apierror.APIError
MarkRetrying(ctx context.Context, id string) (int32, *apierror.APIError)
MarkAutoRetrying(ctx context.Context, id string) (int32, *apierror.APIError)
UpdateStarted(ctx context.Context, id string) (int64, *apierror.APIError)
UpdateCompleted(ctx context.Context, params sqlc.UpdateAgentRunCompletedParams) *apierror.APIError
UpdateCancelled(ctx context.Context, params sqlc.UpdateAgentRunCancelledParams) *apierror.APIError
UpdateFailed(ctx context.Context, params sqlc.UpdateAgentRunFailedParams) *apierror.APIError
MarkDivergedFromConversation(ctx context.Context, id string) *apierror.APIError
GetLastByConfigID(ctx context.Context, configID string) (*sqlc.AgentRun, *apierror.APIError)
// ReapStalledRuns fails every run stuck in 'running' since before cutoff (orphaned by a process kill mid-flight) and returns the reaped run ids.
ReapStalledRuns(ctx context.Context, cutoff time.Time, errorMessage string) ([]string, *apierror.APIError)
}
type AgentTokenRate ¶
type AgentTokenRate struct {
// Model is the gateway model name the rate applies to (e.g. "anthropic/claude-sonnet-4.6").
Model string
// TokenType is the token type: input, output, cached_input, or cached_output.
TokenType string
// UnitAmountCents is the price in cents per token, markup included.
UnitAmountCents float64
}
AgentTokenRate is a marked-up per-token price from the account's plan rate card.
type AgentTokenUsageRepo ¶
type AgentTokenUsageRepo interface {
Upsert(ctx context.Context, params sqlc.UpsertAgentTokenUsageParams) *apierror.APIError
GetByAccountAndDate(ctx context.Context, accountID string, date time.Time) (*sqlc.AgentTokenUsage, *apierror.APIError)
ListByAccount(ctx context.Context, params sqlc.ListAgentTokenUsageByAccountParams) ([]sqlc.AgentTokenUsage, *apierror.APIError)
GetMonthlyUsage(ctx context.Context, accountID string, sinceDate time.Time) (inputTokens, outputTokens int64, apiErr *apierror.APIError)
}
type AvailableToolInfo ¶
type AvailableToolInfo struct {
Slug string
DisplayName string
Description string
ConfigSchema json.RawMessage
Category string
GroupID string
GroupName string
RequiredPermissions []string
RequiredRoleType string
// Mutating reports whether the tool takes an externally-visible or irreversible action: any non-GET endpoint-tool, or a built-in tool flagged mutating in the catalog (e.g. send_email). Surfaced so the UI can default such tools to requiring human review.
Mutating bool
}
AvailableToolInfo is the domain representation of a platform tool that can be attached to an agent definition. Slug is the tool's stable identifier (e.g. "lookup_customer").
type BillingCustomerResolver ¶
type BillingCustomerResolver interface {
GetStripeCustomerID(ctx context.Context, accountID string) (string, error)
// GetAgentSpend returns the account's marked-up token spend for the current billing period (as Stripe will bill it) together with the plan's marked-up per-token rates, so a run can price its in-flight usage against the cap without a per-turn round trip. rates is empty when the plan has no rate card.
GetAgentSpend(ctx context.Context, accountID string) (spendCents int64, rates []AgentTokenRate, err error)
}
BillingCustomerResolver resolves the Stripe customer ID for an account and the account's current agent spend.
type CancelRunParams ¶
type CancelRunParams struct {
AgentRunID string
}
CancelRunParams holds the parameters for cancelling an agent run.
type ChatHistoryMessage ¶
type ChatHistoryMessage struct {
Role string `json:"role"`
Name string `json:"name,omitempty"`
AgentConfigID string `json:"agent_config_id,omitempty"`
Body string `json:"body"`
}
ChatHistoryMessage is one prior conversation turn for a chat-triggered run. Role is "assistant" for this agent's own earlier replies, "user" for everyone else; Name is the sender's display name when known (people), empty for agents. AgentConfigID is set when a different agent authored the turn — its Name is resolved from the agent definition when the run is created.
type ChatRunInput ¶
type ChatRunInput struct {
AccountID string
AgentDefinitionID string
ConversationID string
TriggerMessageID string
Message string
// History is the recent thread context preceding the trigger (oldest-first), seeded as prior turns so the agent can follow the conversation rather than seeing only the trigger message.
History []ChatHistoryMessage
// ContinueRunID, when set, is an existing run to continue (the user replied to that run's message) rather than starting a new one. Falls back to a new run if it isn't continuable.
ContinueRunID string
}
ChatRunInput starts a chat-triggered agent run. AgentDefinitionID is the participant's agent identifier; ConversationID/TriggerMessageID link the run to the conversation it replies into.
type ContinueRunParams ¶
type ContinueRunParams struct {
AgentRunID string
Message string
ApprovedToolSlugs []string
RejectedToolSlugs []string
// ApprovedToolCallIDs / RejectedToolCallIDs are per-call decisions: the tool_use_ids of individual
// blocked calls, so two calls of the same slug can be decided independently. See ContinueRunRequest.
ApprovedToolCallIDs []string
RejectedToolCallIDs []string
}
ContinueRunParams holds the parameters for continuing an agent run that is awaiting input.
type CoreClient ¶
type CoreClient interface {
GetRolePermissions(ctx context.Context, roleID string) (map[string]bool, error)
GetAccountContext(ctx context.Context, accountID string) (*AccountContext, error)
}
CoreClient provides access to core-service via gRPC.
type CreateAgentMemoryParams ¶
type CreateAgentMemoryParams struct {
Category string
Content string
MetadataJSON string
EntityType string
EntityID string
Importance float64
ExpiresAt string
}
CreateAgentMemoryParams holds the parameters for creating an agent memory.
type CreateCustomAgentParams ¶
type CreateCustomAgentParams struct {
Name string
Slug string
Description string
CategoryCode string
TriggerType string
ConfigJSON string
RoleID string
Tools []ToolLinkParams
Includes []string
}
CreateCustomAgentParams holds the parameters for creating a custom agent definition.
type DeleteAgentMemoryParams ¶
type DeleteAgentMemoryParams struct {
MemoryID string
}
DeleteAgentMemoryParams holds the parameters for deleting an agent memory.
type DeleteCustomAgentParams ¶
type DeleteCustomAgentParams struct {
AgentDefinitionID string
}
DeleteCustomAgentParams holds the parameters for deleting a custom agent definition.
type DeletedRecordRepo ¶
type GatewayClient ¶
type GatewayClient interface {
Do(ctx context.Context, req GatewayRequest) (string, error)
}
GatewayClient invokes api-gateway endpoints over the trusted internal listener, forwarding the agent identity. It is how generated endpoint-tools reach real API operations.
type GatewayRequest ¶
type GatewayRequest struct {
Method string
Path string
Query url.Values
Body json.RawMessage
Identity *types.Identity
// IdempotencyKey (optional) is forwarded as the Idempotency-Key header so the gateway dedupes a replayed mutating call. It is set for mutating endpoint-tool calls to a deterministic value derived from the agent run and tool-use IDs, making a re-delivered or re-issued tool call safe to retry without duplicating its side effect.
IdempotencyKey string
}
GatewayRequest is a single HTTP call into the api-gateway's internal listener, made on behalf of an agent identity. The Path is already resolved (path params substituted); Query and Body carry the remaining inputs.
type HandlerRunContext ¶
type HandlerRunContext struct {
AccountID string
RunID string
// ToolUseID is the LLM-assigned ID of the tool call currently being handled. The runner sets it per-call before dispatch so handlers (notably endpoint-tools) can derive a deterministic idempotency key from RunID+ToolUseID.
ToolUseID string
Definition *sqlc.AgentDefinition
Config *sqlc.AgentConfig
Repos RepoFactory
CoreClient CoreClient
GatewayClient GatewayClient
NotificationClient NotificationClient
// ConversationID is the chat conversation this run is linked to (empty for non-chat runs). The email tools use it to address the bound inbox.
ConversationID string
Identity *types.Identity
Actions []PendingAction
Artifacts []PendingArtifact
RequireReviewBySlug map[string]bool
AlwaysAllowedSlugs map[string]bool // reserved approval-bypass; always empty (no "always allow")
OneTimeApprovedSlugs map[string]bool // from approved_tool_slugs / "approve all": approves EVERY pending call of the slug. Consumed after execution.
RejectedSlugs map[string]bool // from rejected_tool_slugs: slugs the human denied this resume — answered with a "denied by user" result so the run continues without them (never paused)
// OneTimeApprovedKeys / RejectedKeys carry PER-CALL decisions keyed by ToolCallApprovalKey(slug, input),
// so two blocked calls of the same slug with different inputs can be approved or denied independently
// (the slug maps above cannot distinguish them). Populated from approved_tool_call_ids / rejected_tool_call_ids
// on resume; the gates check these alongside the slug maps. Consumed after execution like the slug approvals.
OneTimeApprovedKeys map[string]bool
RejectedKeys map[string]bool
// AllowedEndpointToolSlugs is the set of endpoint-tools this agent may use (resolved per-agent from config). search_api_tools only surfaces tools in this set, and execution is denied for anything outside it.
AllowedEndpointToolSlugs map[string]bool
// RevealedToolSlugs accumulates endpoint-tool slugs surfaced via search_api_tools during this run. The runner reads it to add those tools to the live tool list.
RevealedToolSlugs map[string]bool
}
HandlerRunContext provides tool handlers with access to repos and accumulated run state.
type IdempotencyKey ¶
type IdempotencyKey struct {
ID int64
TypeID string
ServiceName string
Handler string
IdempotencyKey string
ActorID *string
IdentityType string
ScopeHash string
ResponseCode *int
ResponseBody json.RawMessage
RecoveryPoint string
}
IdempotencyKey represents a service-level idempotency key.
func (*IdempotencyKey) HasResponse ¶
func (k *IdempotencyKey) HasResponse() bool
func (*IdempotencyKey) IsFinished ¶
func (k *IdempotencyKey) IsFinished() bool
type IdempotencyKeyRepo ¶
type IdempotencyKeyRepo interface {
GetByScopeHash(ctx context.Context, scopeHash string) (*IdempotencyKey, *apierror.APIError)
Create(ctx context.Context, key *IdempotencyKey) (*IdempotencyKey, *apierror.APIError)
AdvanceRecoveryPoint(ctx context.Context, typeID string, recoveryPoint RecoveryPoint) *apierror.APIError
GetRecoveryPoint(ctx context.Context, typeID string) (RecoveryPoint, *apierror.APIError)
SetResponse(ctx context.Context, typeID string, code int, body json.RawMessage, recoveryPoint RecoveryPoint) *apierror.APIError
}
IdempotencyKeyRepo manages service-level idempotency keys.
type IdempotencyMed ¶
type IdempotencyMed interface {
// UpsertIdempotencyKey upserts and returns the idempotency key for the request scope.
UpsertIdempotencyKey(ctx context.Context, identity *types.Identity) (*IdempotencyKey, *apierror.APIError)
// CacheErrorResponse caches a non-transient error response for the idempotency key.
//
// Behavior:
// - If the error is transient, it is returned without caching.
//
// Side effects:
// - Persists the error response for subsequent replays of the same idempotency key.
CacheErrorResponse(ctx context.Context, typeID string, apiErr *apierror.APIError) *apierror.APIError
// CacheSuccessResponse caches a successful response for the idempotency key.
//
// Side effects:
// - Persists the success response for subsequent replays of the same idempotency key.
CacheSuccessResponse(ctx context.Context, typeID string, data any) *apierror.APIError
}
IdempotencyMed provides idempotency logic for service operations.
type ListAgentDefinitionsParams ¶
type ListAgentDefinitionsParams struct {
Includes []string
Statuses []string
DefinitionTypes []string
TriggerTypes []string
Cursor *string
Limit int32
Query *string
}
ListAgentDefinitionsParams holds the parameters for listing agent definitions.
type ListAgentDefinitionsResult ¶
type ListAgentDefinitionsResult struct {
Items []AgentDefinitionInfo
PageInfo PageInfo
}
ListAgentDefinitionsResult holds the result of listing agent definitions.
type ListAvailableToolsParams ¶
type ListAvailableToolsParams struct {
Cursor *string
Limit int32
Query *string
PaginateResource string
}
ListAvailableToolsParams holds the parameters for listing available tools.
type MediatorFactory ¶
type MediatorFactory interface {
Build(repoFactory RepoFactory) Mediators
}
MediatorFactory builds mediator instances from a RepoFactory.
type Mediators ¶
type Mediators struct {
Idempotency IdempotencyMed
}
Mediators groups all mediator instances.
type ModelInfo ¶
type ModelInfo struct {
// Code is the stable identifier used to select the model (matches the Stripe AI Gateway naming convention, no date suffixes).
Code constants.Model
// Name is the human-readable display name.
Name string
// Provider is the display name of the company that makes the model.
Provider string
}
ModelInfo describes an LLM model agents can be configured to use.
type NotificationClient ¶
type NotificationClient interface {
SendInboxReply(ctx context.Context, in SendInboxReplyRequest) (messageID string, err error)
PostReplyDraft(ctx context.Context, in PostReplyDraftRequest) (messageID string, err error)
}
NotificationClient invokes the notification-service email-bridge RPCs an agent uses to reply by email (send) or stage a draft for review on an email-bridged conversation.
type PendingAction ¶
type PendingAction struct {
ToolSlug string
Label string
Description string
Input json.RawMessage
Output json.RawMessage
RequiresReview bool
EntityType string
EntityID string
}
PendingAction represents an action to be persisted after a run completes.
type PendingArtifact ¶
type PendingArtifact struct {
ActionIndex int
ArtifactType string
Name string
Content string
Metadata json.RawMessage
MimeType string
}
PendingArtifact represents an artifact to be persisted after a run completes.
type PostReplyDraftRequest ¶
type PostReplyDraftRequest struct {
ConversationID string
Body string
Subject string // used only on an email-bridged case (outbound subject); ignored otherwise
AgentConfigID string
AgentRunID string
// SourceThreadMessageID records the internal note the draft was composed from (provenance).
SourceThreadMessageID string
Identity *types.Identity
}
PostReplyDraftRequest proposes a customer reply as a real status=draft message held for human approval on a customer case (channel resolved server-side). The conversation is fixed by the run; the agent supplies only the content, so it never needs a conversation id.
type RecoveryPoint ¶
type RecoveryPoint string
RecoveryPoint tracks progress through idempotent operation execution.
const ( RecoveryPointStarted RecoveryPoint = "agent:started" RecoveryPointFinished RecoveryPoint = "agent:finished" )
func (RecoveryPoint) IsValid ¶
func (r RecoveryPoint) IsValid() bool
type RepoFactory ¶
type RepoFactory interface {
NewOutboxRepo() messaging.OutboxRepo
NewAgentDefinitionRepo() AgentDefinitionRepo
NewAgentConfigRepo() AgentConfigRepo
NewAgentRunRepo() AgentRunRepo
NewAgentActionRepo() AgentActionRepo
NewAgentArtifactRepo() AgentArtifactRepo
NewAgentMemoryRepo() AgentMemoryRepo
NewAgentTokenUsageRepo() AgentTokenUsageRepo
NewAgentDefinitionToolRepo() AgentDefinitionToolRepo
NewAgentAccountStatusRepo() AgentAccountStatusRepo
NewAgentRunEventRepo() AgentRunEventRepo
NewIdempotencyKeyRepo() IdempotencyKeyRepo
NewDeletedRecordRepo() DeletedRecordRepo
}
RepoFactory creates repository instances.
type RequestIdentity ¶
RequestIdentity contains the identity context for an idempotent operation.
type RetryRunParams ¶
type RetryRunParams struct {
AgentRunID string
}
RetryRunParams holds the parameters for retrying a failed run.
type RunContext ¶
type RunContext struct {
AccountID string
RunID string
Definition *sqlc.AgentDefinition
Config *sqlc.AgentConfig
Memories []sqlc.AgentMemory
}
RunContext holds the loaded context for an agent run.
type RunResult ¶
type RunResult struct {
Output json.RawMessage
Actions []PendingAction
Artifacts []PendingArtifact
InputTokens int
OutputTokens int
LLMProvider string
LLMModel string
AwaitingApproval bool
// Cancelled is true when the run was stopped mid-flight (via CancelRun) rather than finishing on its own. The caller finalizes the run as cancelled and skips the normal completed/awaiting_input transition so a stop request isn't silently overwritten.
Cancelled bool
}
RunResult holds the outputs of an agent run.
type RunnerSvc ¶
type RunnerSvc interface {
ExecuteRun(ctx context.Context, runID, configID, accountID, triggerType string) *apierror.APIError
ContinueRun(ctx context.Context, runID, accountID, message string, approvedToolSlugs []string, approveAllPending bool, rejectedToolSlugs []string, approvedToolCallIDs, rejectedToolCallIDs []string, actorID, actorType, actorName, replyToMessageID string) *apierror.APIError
}
RunnerSvc orchestrates agent run execution.
type SchedulerSvc ¶
SchedulerSvc manages periodic agent scheduling.
type SendInboxReplyRequest ¶
type SendInboxReplyRequest struct {
ConversationID string
Subject string
Body string
Cc []string
AgentConfigID string
AgentRunID string
Identity *types.Identity
}
SendInboxReplyRequest sends an agent's outbound email through the conversation's bound inbox.
type ToolGroupInfo ¶
type ToolGroupInfo struct {
ID string
Name string
Description string
Slug string
Icon string
SortOrder int32
}
ToolGroupInfo is the domain representation of a tool group.
type ToolHandlerFunc ¶
type ToolHandlerFunc func(ctx context.Context, input json.RawMessage, runCtx *HandlerRunContext) (string, error)
ToolHandlerFunc is the signature for a single tool's execution handler.
type ToolLinkParams ¶
ToolLinkParams holds the parameters for linking a built-in tool (by slug) to an agent definition.
type TriggerRunParams ¶
TriggerRunParams holds the parameters for triggering an agent run.
type UpdateAgentAccountStatusParams ¶
UpdateAgentAccountStatusParams holds the parameters for upserting a per-account agent status.
type UpdateAgentMemoryParams ¶
type UpdateAgentMemoryParams struct {
MemoryID string
Category *string
Content *string
MetadataJSON *string
EntityType *string
EntityID *string
Importance *float64
ExpiresAt *string
ClearEntity bool
ClearExpiresAt bool
}
UpdateAgentMemoryParams holds the parameters for updating an agent memory. UpdateAgentMemoryParams is a partial update: nil fields leave the column unchanged. ClearEntity nulls entity_type + entity_id (unscopes); ClearExpiresAt nulls expires_at (makes the memory permanent).
type UpdateCustomAgentParams ¶
type UpdateCustomAgentParams struct {
AgentDefinitionID string
Name *string
Slug *string
Description *string
CategoryCode *string
TriggerType *string
ConfigJSON *string
RoleID *string
// ClearDescription / ClearRoleID set the respective column to NULL (the value fields are ignored when set).
ClearDescription bool
ClearRoleID bool
Tools []ToolLinkParams
ToolsProvided bool
Includes []string
}
UpdateCustomAgentParams holds the parameters for updating a custom agent definition. Nil pointer fields indicate that the field should not be updated.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
mock
|
|
|
client
Package clientmock is a generated GoMock package.
|
Package clientmock is a generated GoMock package. |
|
factory
Package factorymock is a generated GoMock package.
|
Package factorymock is a generated GoMock package. |
|
mediator
Package mediatormock is a generated GoMock package.
|
Package mediatormock is a generated GoMock package. |
|
repository
Package repositorymock is a generated GoMock package.
|
Package repositorymock is a generated GoMock package. |
|
service
Package servicemock is a generated GoMock package.
|
Package servicemock is a generated GoMock package. |