Documentation
¶
Overview ¶
Package trigger provides services that trigger agent containers in response to external events: webhooks, cron schedules, and channel messages.
Index ¶
- Constants
- Variables
- func AgentConfigHash(ag dbq.Agent) string
- func PostFilesManifest(ctx context.Context, q *dbq.Queries, convID pgtype.UUID, files []wire.FileInfo) error
- func ResolveEcho(settingsJSON []byte, driverDefault bool) bool
- func StreamNDJSONResponse(body io.Reader, runID string, events chan<- ResponseEvent) (string, []message.Message, *usageInfo, error)
- type AgentSlashConv
- func (a *AgentSlashConv) Cancel(ctx context.Context, convID pgtype.UUID) bool
- func (a *AgentSlashConv) Clear(ctx context.Context, convID pgtype.UUID) (bool, error)
- func (a *AgentSlashConv) Compact(_ context.Context, _ pgtype.UUID) (string, bool, error)
- func (a *AgentSlashConv) Echo(ctx context.Context, convID pgtype.UUID, args string) (bool, error)
- func (a *AgentSlashConv) Start(ctx context.Context, convID pgtype.UUID) string
- type BridgeCallback
- type BridgeDriver
- type BridgeEvent
- type BridgeFile
- type BridgeManager
- func (m *BridgeManager) AddBridge(bridgeID uuid.UUID)
- func (m *BridgeManager) AttachManagedBotIngest(...)
- func (m *BridgeManager) AttachSysagent(s SysagentRuntime)
- func (m *BridgeManager) BotTokenForBridge(ctx context.Context, agentID, bridgeID uuid.UUID) (string, error)
- func (m *BridgeManager) HandleEvent(ctx context.Context, event BridgeEvent) error
- func (m *BridgeManager) RemoveBridge(bridgeID uuid.UUID)
- func (m *BridgeManager) RemoveBridgesByOwner(ctx context.Context, ownerID uuid.UUID) error
- func (m *BridgeManager) ResumeSystemConversation(ctx context.Context, conversationID uuid.UUID) error
- func (m *BridgeManager) SendMessage(ctx context.Context, bridgeID uuid.UUID, externalID, text string) error
- func (m *BridgeManager) SendParts(ctx context.Context, bridgeID uuid.UUID, externalID string, ...) error
- func (m *BridgeManager) Start(ctx context.Context) error
- func (m *BridgeManager) Stop()
- func (m *BridgeManager) StreamToBridge(ctx context.Context, bridgeID uuid.UUID, externalID string, ...) error
- func (m *BridgeManager) TeardownBridge(bridgeID uuid.UUID)
- type BridgeReferencedMessage
- type CommandRegistrar
- type Dispatcher
- func (d *Dispatcher) CancelRun(runID uuid.UUID) bool
- func (d *Dispatcher) EnsureRunning(ctx context.Context, agentID uuid.UUID) (*container.Container, error)
- func (d *Dispatcher) ForwardA2APrompt(ctx context.Context, agentID uuid.UUID, parentRunID uuid.UUID, ...) (io.ReadCloser, uuid.UUID, error)
- func (d *Dispatcher) ForwardFire(ctx context.Context, agentID uuid.UUID, event wire.ScheduleFireRequest, ...) (wire.ScheduleFireResponse, uuid.UUID, error)
- func (d *Dispatcher) ForwardPrompt(ctx context.Context, agentID uuid.UUID, input wire.PromptInput, ...) (io.ReadCloser, uuid.UUID, error)
- func (d *Dispatcher) ForwardWebhook(ctx context.Context, agentID uuid.UUID, path string, body []byte, ...) (io.ReadCloser, uuid.UUID, error)
- func (d *Dispatcher) InFlightIDs() []uuid.UUID
- func (d *Dispatcher) RefreshAgent(ctx context.Context, agentID uuid.UUID) error
- type ManagedBotEvent
- type PromptProxy
- func (p *PromptProxy) HandleCallback(ctx context.Context, agentID, bridgeID, userID uuid.UUID, ...) (staleRun bool, err error)
- func (p *PromptProxy) HandleMessage(ctx context.Context, agentID, bridgeID, userID uuid.UUID, externalID string, ...) (string, error)
- func (p *PromptProxy) TranscribeVoicePlain(ctx context.Context, files []BridgeFile) (text string, hasVoice bool, hasNonVoice bool)
- type ResponseEvent
- type RunCanceler
- type Scheduler
- type SlashCommand
- type SlashCommandResult
- type SlashConv
- type SysagentRuntime
- type SysagentSlashConv
- func (s *SysagentSlashConv) Cancel(ctx context.Context, convID pgtype.UUID) bool
- func (s *SysagentSlashConv) Clear(ctx context.Context, convID pgtype.UUID) (bool, error)
- func (s *SysagentSlashConv) Compact(ctx context.Context, convID pgtype.UUID) (string, bool, error)
- func (s *SysagentSlashConv) Echo(ctx context.Context, convID pgtype.UUID, args string) (bool, error)
- func (s *SysagentSlashConv) Start(ctx context.Context, convID pgtype.UUID) string
- type TelegramChatInfo
- type TelegramDriver
- func (d *TelegramDriver) Activate(ctx context.Context, br dbq.Bridge) error
- func (d *TelegramDriver) AnswerCallbackQuery(ctx context.Context, token, callbackID, text string) error
- func (d *TelegramDriver) DefaultEcho() bool
- func (d *TelegramDriver) GetChat(ctx context.Context, token, chatID string) (TelegramChatInfo, error)
- func (d *TelegramDriver) GetManagedBotToken(ctx context.Context, managerToken string, botUserID int64) (string, error)
- func (d *TelegramDriver) GetMe(ctx context.Context, token string) (string, error)
- func (d *TelegramDriver) GetMeFull(ctx context.Context, token string) (username, name string, botUserID int64, canManageBots bool, err error)
- func (d *TelegramDriver) GetMenuButton(ctx context.Context, token string) (TelegramMenuButton, error)
- func (d *TelegramDriver) Init(ctx context.Context, br *dbq.Bridge) error
- func (d *TelegramDriver) Poll(ctx context.Context, br *dbq.Bridge) ([]BridgeEvent, error)
- func (d *TelegramDriver) RegisterCommands(ctx context.Context, br dbq.Bridge, cmds []SlashCommand) error
- func (d *TelegramDriver) RemoveButtons(ctx context.Context, br dbq.Bridge, externalID, messageID string) error
- func (d *TelegramDriver) SendMessage(ctx context.Context, token string, chatID int64, text string) error
- func (d *TelegramDriver) SendParts(ctx context.Context, token string, chatID int64, parts []wire.DisplayPart) error
- func (d *TelegramDriver) SendStream(ctx context.Context, br dbq.Bridge, externalID string, echo bool, ...) (string, error)
- func (d *TelegramDriver) SetMenuButton(ctx context.Context, token, url string) error
- func (d *TelegramDriver) Teardown(ctx context.Context, br dbq.Bridge) error
- type TelegramMenuButton
- type TranscriptionResolver
Constants ¶
const ( // BridgeReferenceReply — the user replied to another message // (Telegram reply_to_message). BridgeReferenceReply = "reply" // BridgeReferenceForward — the user forwarded a message authored // elsewhere (Telegram forward_origin). BridgeReferenceForward = "forward" )
BridgeReferenceKind distinguishes the platform mechanism that produced the reference so the prompt builder can label it for the LLM.
const CancelButtonAfter = 20 * time.Second
CancelButtonAfter is how long a bridge run can stream before the driver posts a "Still working… Tap to stop" message with a cancel button. The message is deleted when the run ends (naturally or via the user tap).
const FilesManifestSource = "llm"
FilesManifestSource tags the attached-files manifest message: a user-role message that IS sent to the model (non-ephemeral, so SessionStore.Load returns it) but is hidden from the human UI (the frontend drops source=="llm"). The human already sees the attachments via the separate upload echo / their chat platform, so rendering the manifest too would be noise.
const PromptHTTPCeiling = 30 * time.Minute
PromptHTTPCeiling is the absolute cap on a prompt run's outbound HTTP request. Generous on purpose: prompt runs may legitimately stream for many minutes (long tool chains, slow LLMs); the user cancels manually via DELETE /api/v1/runs/{runID} when they want to stop earlier. Cron and webhook callers pass their own (typically shorter) timeout to ForwardFire/Webhook.
Variables ¶
var ( // ErrAgentStopped — the agent is parked via /stop and only a manual // /start resumes it; EnsureRunning refuses to auto-start it. ErrAgentStopped = errors.New("agent is stopped") // ErrAgentNoImage — the agent has never finished a build, so there is // no container image to run. ErrAgentNoImage = errors.New("agent has no image") )
Sentinel errors from EnsureRunning for agents that exist but aren't in a runnable state. Callers map these to a surface-appropriate response (409 on HTTP, an in-chat notice on bridges, a JSON-RPC error on A2A) instead of a generic 500. Both are expected operator states, not faults.
var ErrTranscriptionNotConfigured = errors.New("transcription not configured")
ErrTranscriptionNotConfigured is returned when no system-wide transcription model is set. Callers handle this non-fatally (degrade to file-only delivery).
var Registry = []SlashCommand{ {Name: "auth", Description: "Link your Airlock account", Access: agentsdk.AccessPublic}, {Name: "cancel", Description: "Stop the current run", Access: agentsdk.AccessPublic}, {Name: "clear", Description: "Clear conversation context", Access: agentsdk.AccessUser}, {Name: "compact", Description: "Summarize and compact context", Access: agentsdk.AccessUser}, {Name: "echo", Description: "Toggle tool output bubbles (on / off / blank=flip)", Access: agentsdk.AccessUser}, }
Registry is the canonical list of commands. Order is preserved when rendered into platform command menus.
Functions ¶
func AgentConfigHash ¶ added in v0.4.0
AgentConfigHash fingerprints the subset of an agent's configuration that is a pure function of the agents row and feeds the sync-time PromptData the agent caches: the eight model slots (which drive Capabilities + SupportedModalities) and the slug (which drives the dashboard/route URLs). Airlock stamps this on every dispatched PromptInput.ExpectedSyncHash and returns it as SyncResponse.SyncStateHash; the agent compares the two and resyncs on drift, so a model or slug change self-heals even if it didn't fire an explicit /refresh. Computed on the fly from the row rather than stored, so the fingerprint itself can never go stale.
Relational prompt inputs — the sibling roster and MCP schemas — are NOT covered here: they aren't a function of the agents row, and they already have their own event-driven refresh broadcast.
func PostFilesManifest ¶ added in v0.4.0
func PostFilesManifest(ctx context.Context, q *dbq.Queries, convID pgtype.UUID, files []wire.FileInfo) error
PostFilesManifest writes the attached-files manifest as its own conversation message — the single, canonical way file attachments are described to the model. agentsdk no longer inlines a manifest into the prompt; every files-bearing ingress (web / bridge / A2A) calls this instead, BEFORE dispatch, so the row is in history when the agent's SessionStore loads. No-op when there are no files.
Persist-only (q.CreateMessage) — deliberately NOT postToConversation: the manifest is model-only and must never reach a human WS or bridge channel. Sol's same-role coalescer folds it together with the user's actual message for providers that reject consecutive user turns.
func ResolveEcho ¶
ResolveEcho returns the effective echo flag for a conversation given its raw settings JSON and the driver's default. Explicit conversation settings win over the driver default; missing JSON or missing key falls through to the default.
func StreamNDJSONResponse ¶
func StreamNDJSONResponse(body io.Reader, runID string, events chan<- ResponseEvent) (string, []message.Message, *usageInfo, error)
StreamNDJSONResponse reads NDJSON events from a response stream, forwards ResponseEvents to the events channel for real-time delivery, and collects the full text response. Closes the events channel when done. runID is stamped onto confirmation_required events so drivers can build callback-bound UI (e.g. Telegram inline keyboards).
Types ¶
type AgentSlashConv ¶ added in v0.4.0
type AgentSlashConv struct {
// contains filtered or unexported fields
}
AgentSlashConv is the SlashConv implementation for agent-bridge and web conversations stored in agent_conversations / agent_messages. /compact forwards to the agent container (sets ForwardAsCompact); every other command operates locally against the airlock DB.
func NewAgentSlashConv ¶ added in v0.4.0
func NewAgentSlashConv(q *dbq.Queries, canceler RunCanceler, logger *zap.Logger, agentID uuid.UUID, agentBaseURL func(string) string) *AgentSlashConv
NewAgentSlashConv builds an adapter for the agent-conversation path. canceler dispatches /cancel into the agent dispatcher; nil yields the "Nothing to cancel" path on restart (no live in-memory state). agentID identifies the bound agent so /start can name and link it even before any conversation exists (slash commands don't create one).
func (*AgentSlashConv) Cancel ¶ added in v0.4.0
Cancel — q.GetLatestRunningPromptRun then dispatcher.CancelRun. The HTTP-request abort is what flips the run row out of 'running' (via the agent's r.Complete or the stuck-run sweeper as a backstop).
func (*AgentSlashConv) Clear ¶ added in v0.4.0
Clear writes a checkpoint marker row and advances the conversation's context_checkpoint_message_id. Also best-effort resolves any suspended run for THIS conversation (not a sibling-delegated suspension that happens to be the agent's latest).
func (*AgentSlashConv) Compact ¶ added in v0.4.0
Compact is a no-op locally: the agent container runs the actual summarization via Sol.Runner.Compact, so we just signal "forward as compact" and let the proxy set ForceCompact=true on the forwarded request.
func (*AgentSlashConv) Echo ¶ added in v0.4.0
Echo flips the conversation's settings.echo flag. Toggle treats unset as off so the first /echo in a chat that's quiet by default always turns echo on.
type BridgeCallback ¶
type BridgeCallback struct {
Data string // opaque payload, e.g. "approve:<runID>"
AckID string // platform-specific ack handle (Telegram callback_query.id)
MessageID string // ID of the message the button is attached to (so we
}
BridgeCallback represents an interactive UI acknowledgement — a button tap on an inline keyboard or similar platform-native affordance. Drivers that don't support rich UI leave this nil.
type BridgeDriver ¶
type BridgeDriver interface {
// Init is called once when a bridge is first created.
// Uses pointer so the driver can set initial config (e.g. poll offset).
Init(ctx context.Context, br *dbq.Bridge) error
// Activate is called on every startup for active bridges.
Activate(ctx context.Context, br dbq.Bridge) error
// Teardown is called when a bridge is deleted or disabled.
Teardown(ctx context.Context, br dbq.Bridge) error
// Poll fetches new events from the platform.
// Uses pointer so the driver can update br.Config (e.g. poll offset).
Poll(ctx context.Context, br *dbq.Bridge) ([]BridgeEvent, error)
// SendStream delivers a response, streaming text deltas as they arrive.
// echo controls whether tool-call / tool-result bubbles are rendered;
// drivers that collapse tool output some other way may ignore it.
// Returns the final assembled text.
SendStream(ctx context.Context, br dbq.Bridge, externalID string, echo bool, events <-chan ResponseEvent) (string, error)
// DefaultEcho returns whether tool bubbles render by default on this
// platform. Drivers that display each tool-call/tool-result as its own
// chat message (Telegram) should return false; drivers whose UI can
// collapse tool output inline (web) should return true.
// Used when a conversation has no explicit settings.echo override.
DefaultEcho() bool
// RemoveButtons strips the inline keyboard / component buttons from a
// previously sent message, leaving its text intact. Called after the
// user taps an approve/deny button so the resolved confirmation can't
// be tapped again. Best-effort: errors are logged but not propagated.
RemoveButtons(ctx context.Context, br dbq.Bridge, externalID, messageID string) error
}
BridgeDriver handles platform-specific message parsing and delivery.
type BridgeEvent ¶
type BridgeEvent struct {
BridgeID uuid.UUID
ExternalID string // platform chat_id (Telegram chat ID, etc.)
SenderID string // platform user ID of sender (for identity lookup)
SenderName string
Text string
Files []BridgeFile // attached files (photos, documents)
Callback *BridgeCallback
ReferencedMessage *BridgeReferencedMessage // reply target / forward source (driver-populated)
ManagedBot *ManagedBotEvent // Telegram managed_bot_created service message (manager bridges only)
RawPayload []byte
}
BridgeEvent represents a normalized incoming event from any platform. Either Text/Files (new user message) or Callback (button tap) is populated.
type BridgeFile ¶
type BridgeFile struct {
FileID string // platform file ID (e.g. Telegram file_id)
Filename string
ContentType string
Size int64
Data []byte // file content (downloaded by driver)
// IsVoiceNote marks a short voice recording (e.g. Telegram "voice")
// that the bridge layer should auto-transcribe before forwarding to
// the agent. Plain audio/video/document attachments leave this false.
IsVoiceNote bool
}
BridgeFile is a file attached to a bridge message.
type BridgeManager ¶
type BridgeManager struct {
// contains filtered or unexported fields
}
BridgeManager manages bridge drivers and routes events to agents.
func NewBridgeManager ¶
func NewBridgeManager(drivers map[string]BridgeDriver, prompter *PromptProxy, database *db.DB, encryptor secrets.Store, hmacSecret, publicURL string, agentBaseURL func(slug string) string, logger *zap.Logger) *BridgeManager
NewBridgeManager creates a BridgeManager. agentBaseURL builds the external URL for an agent's subdomain ({scheme}://{slug}.{domain}[:port]); the Telegram driver needs it to register the web-app menu button.
func (*BridgeManager) AddBridge ¶
func (m *BridgeManager) AddBridge(bridgeID uuid.UUID)
AddBridge activates a newly created bridge and starts its poller. Idempotent: if a poller is already running for this bridge ID (e.g. the bridge was re-registered after a config change), the existing one is cancelled first so only one poller hits the platform at a time.
func (*BridgeManager) AttachManagedBotIngest ¶ added in v0.4.0
func (m *BridgeManager) AttachManagedBotIngest(fn func(ctx context.Context, managerToken string, botUserID int64, botUsername string) (string, error))
AttachManagedBotIngest wires the managed-bot ingest callback (see the field doc). Idempotent; the last set wins.
func (*BridgeManager) AttachSysagent ¶ added in v0.4.0
func (m *BridgeManager) AttachSysagent(s SysagentRuntime)
AttachSysagent wires the sysagent runtime after the router has built it. Idempotent; the last set wins.
func (*BridgeManager) BotTokenForBridge ¶ added in v0.4.0
func (m *BridgeManager) BotTokenForBridge(ctx context.Context, agentID, bridgeID uuid.UUID) (string, error)
BotTokenForBridge returns the decrypted Telegram bot token for (agentID, bridgeID) — only if the bridge belongs to that agent and is of type "telegram". The agent guard is the cross-agent boundary at the lookup layer; HMAC verification of the caller's initData then gates the actual auth. Returns an error on any mismatch so the caller can 401 without leaking which constraint failed.
Used by the airlock proxy's Telegram Web App auth handler.
func (*BridgeManager) HandleEvent ¶
func (m *BridgeManager) HandleEvent(ctx context.Context, event BridgeEvent) error
HandleEvent processes a parsed BridgeEvent — routes to agent via PromptProxy.
func (*BridgeManager) RemoveBridge ¶
func (m *BridgeManager) RemoveBridge(bridgeID uuid.UUID)
RemoveBridge stops the poller for a bridge. Safe to call for an unknown bridge ID — it's a no-op. The DB row is NOT touched here; callers that want full deletion do the DB work separately (typically by calling q.DeleteBridge alongside this).
func (*BridgeManager) RemoveBridgesByOwner ¶ added in v0.4.0
RemoveBridgesByOwner stops every poller for bridges owned by a specific user. Called from service/users.Delete BEFORE the DB CASCADE removes the bridge rows — otherwise the poller goroutines would keep calling getUpdates against now-deleted bridges until their next transient failure, racing on the bot token with any replacement bridge that happened to land on the same row id.
func (*BridgeManager) ResumeSystemConversation ¶ added in v0.4.0
func (m *BridgeManager) ResumeSystemConversation(ctx context.Context, conversationID uuid.UUID) error
ResumeSystemConversation runs a server-initiated auto-resume turn for a bridge-originated system conversation and streams it to the chat through the SAME bridgeSink + driver.SendStream the inbound poller uses. This is the delivery path for a build/upgrade completion follow-up: because it uses the real sink, a gated tool the resume chains into (e.g. create_tg_bot) renders Approve/Reject buttons in the chat — and the normal inbound callback path resumes the run on a tap — instead of silently suspending the way a text-only push would.
The conversation must already carry source="bridge" + bridge_id + external_id (EnsureSystemConversationForBridge refreshes external_id on every inbound turn). Invoked by sysagent's build/upgrade notifier via the BridgeResumer interface; it runs synchronously and the caller drives it from a goroutine.
func (*BridgeManager) SendMessage ¶
func (m *BridgeManager) SendMessage(ctx context.Context, bridgeID uuid.UUID, externalID, text string) error
SendMessage sends a text message to a bridge conversation. Convenience wrapper.
func (*BridgeManager) SendParts ¶
func (m *BridgeManager) SendParts(ctx context.Context, bridgeID uuid.UUID, externalID string, parts []wire.DisplayPart) error
SendParts sends display parts to a bridge conversation. Looks up the bridge, decrypts the token, and delegates to the driver.
func (*BridgeManager) Start ¶
func (m *BridgeManager) Start(ctx context.Context) error
Start sets up all active bridges and starts pollers.
func (*BridgeManager) StreamToBridge ¶ added in v0.4.0
func (m *BridgeManager) StreamToBridge(ctx context.Context, bridgeID uuid.UUID, externalID string, settingsJSON []byte, events <-chan ResponseEvent) error
StreamToBridge is the single bridge-delivery primitive the completion-resume paths share: it resolves the bridge's driver + echo setting and streams a ResponseEvent channel to the chat via SendStream. The caller produces the events from whatever run source it has and closes the channel — an in-process sysagent run via bridgeSink (BridgeManager.ResumeSystemConversation), or an agent NDJSON stream via StreamNDJSONResponse (api NotifyUpgradeComplete). Because both go through SendStream, text, tool calls, and — crucially — confirmation_required prompts render identically; a gated tool the resume chains into gets Approve/Reject buttons instead of being silently swallowed.
settingsJSON is the conversation's settings blob (drives the per-thread echo override). On a resolution error the channel is drained so the producer goroutine never blocks on a full buffer.
func (*BridgeManager) TeardownBridge ¶ added in v0.4.0
func (m *BridgeManager) TeardownBridge(bridgeID uuid.UUID)
TeardownBridge runs the driver's teardown for a bridge — for Telegram this clears the chat menu button so a deleted/disabled bridge doesn't leave a dead web-app "Open" button behind. Best-effort: it logs and returns on lookup/decrypt/teardown failure so it never blocks an agent or bridge deletion. Call it BEFORE the bridge row is deleted and before RemoveBridge, while the bot token is still resolvable. Uses the manager's own context so the platform API call isn't cut short when the deleting request returns.
type BridgeReferencedMessage ¶
type BridgeReferencedMessage struct {
Kind string // BridgeReferenceReply | BridgeReferenceForward
SenderName string // author of the referenced content
Text string
AuthoredAt time.Time
FromBot bool // true when the referenced message was authored by our bot (replies only)
}
BridgeReferencedMessage describes a message the current event points at — either a reply target or a forwarded message. Surfaced to the LLM as a wrapped context block regardless of session mode, so the model has the referenced content even when it's outside the active conversation history (or when there is no history at all).
type CommandRegistrar ¶
type CommandRegistrar interface {
RegisterCommands(ctx context.Context, br dbq.Bridge, cmds []SlashCommand) error
}
CommandRegistrar is an optional BridgeDriver capability: platforms with a native command menu (Telegram setMyCommands) implement it to receive the slash-command registry on activation. Drivers without such a menu simply don't implement it.
type Dispatcher ¶
type Dispatcher struct {
// contains filtered or unexported fields
}
Dispatcher ensures agent containers are running and forwards HTTP requests to them.
func NewDispatcher ¶
func NewDispatcher(cfg *config.Config, db *db.DB, containers container.ContainerManager, enc secrets.Store, logger *zap.Logger) *Dispatcher
NewDispatcher creates a Dispatcher.
func (*Dispatcher) CancelRun ¶
func (d *Dispatcher) CancelRun(runID uuid.UUID) bool
CancelRun aborts the in-flight outbound request for the given run, if any. Returns true if a cancel was fired. Idempotent — repeat calls and calls for runs that already finished are no-ops.
A2A cascade: the cancel also walks runs.parent_run_id downward and fires the cancel hook on every still-in-flight descendant. The HTTP disconnect chain already cascades cancels (parent's outbound HTTP closing → child's ctx.Done() → child's CancelRun), but this gives an explicit best-effort kick for runs on the same replica when the user cancels mid-chain.
func (*Dispatcher) EnsureRunning ¶
func (d *Dispatcher) EnsureRunning(ctx context.Context, agentID uuid.UUID) (*container.Container, error)
EnsureRunning looks up the agent, decrypts its DB credentials, and starts (or reconnects to) the agent container. Returns the running container.
func (*Dispatcher) ForwardA2APrompt ¶ added in v0.4.0
func (d *Dispatcher) ForwardA2APrompt(ctx context.Context, agentID uuid.UUID, parentRunID uuid.UUID, callerAccess agentsdk.Access, userID *uuid.UUID, input wire.PromptInput) (io.ReadCloser, uuid.UUID, error)
ForwardA2APrompt is ForwardPrompt for the sibling-agent code path: the caller is another agent's run, parentRunID is its run.id, and the new run's parent_run_id and trigger_type/_ref are wired accordingly. callerAccess is the access level Airlock pre-resolved against the target agent (see api/access.computeA2ACallerAccess). userID is the original user (the human at the top of the chain — propagated through every A2A hop via the conversation's user_id), used for both the new run's VisibleSiblings computation and audit.
func (*Dispatcher) ForwardFire ¶ added in v0.4.0
func (d *Dispatcher) ForwardFire(ctx context.Context, agentID uuid.UUID, event wire.ScheduleFireRequest, timeout time.Duration) (wire.ScheduleFireResponse, uuid.UUID, error)
ForwardFire creates one run attempt and returns the handler's typed acknowledgement after /fire/{slug} completes.
func (*Dispatcher) ForwardPrompt ¶
func (d *Dispatcher) ForwardPrompt(ctx context.Context, agentID uuid.UUID, input wire.PromptInput, bridgeID *uuid.UUID, userID *uuid.UUID) (io.ReadCloser, uuid.UUID, error)
ForwardPrompt ensures the agent is running, creates a run record, and POSTs the prompt input to the agent container. Returns the response body stream (NDJSON) and the run ID. userID is the prompting user (anchor for A2A VisibleSiblings); pass nil for anonymous/system runs.
func (*Dispatcher) ForwardWebhook ¶
func (d *Dispatcher) ForwardWebhook(ctx context.Context, agentID uuid.UUID, path string, body []byte, bridgeID *uuid.UUID, timeout time.Duration) (io.ReadCloser, uuid.UUID, error)
ForwardWebhook ensures the agent is running, creates a run record, and POSTs the webhook payload to the agent container. Returns the response body stream and the run ID. The timeout parameter controls the HTTP client timeout.
func (*Dispatcher) InFlightIDs ¶
func (d *Dispatcher) InFlightIDs() []uuid.UUID
InFlightIDs returns a snapshot of currently-tracked run IDs. Used by the stuck-run sweeper so it doesn't race the dispatcher and prematurely terminate a still-live run.
func (*Dispatcher) RefreshAgent ¶
RefreshAgent triggers a synchronous re-sync on the agent container. Used after server-side state changes the cached system prompt depends on (typically MCP OAuth completion) so the running agent picks up new tools without a restart. If the container isn't running, returns nil — there's nothing to refresh; the agent will sync fresh on its next startup.
type ManagedBotEvent ¶ added in v0.4.0
type ManagedBotEvent struct {
BotID int64
Username string
// ExternalID is the chat the creation happened in — the exact account +
// device whose client just went through the flow. It's the unambiguous
// reply target for the post-create deep link (no platform_identities
// lookup, so a user with multiple linked Telegram accounts is a non-issue).
ExternalID string
// SenderID is the Telegram user who created the bot (optional sanity check
// against the session owner's linked identities).
SenderID string
}
ManagedBotEvent carries a Telegram `managed_bot_created` service message — a new bot a user created via the manager bot's deep-link flow. Only a manager bridge (is_manager) produces these; HandleEvent turns it into a bridge for the freshly-created bot.
type PromptProxy ¶
type PromptProxy struct {
// contains filtered or unexported fields
}
PromptProxy manages conversation history and forwards prompts to agent containers.
func NewPromptProxy ¶
func NewPromptProxy(dispatcher *Dispatcher, database *db.DB, s3 *storage.S3Client, resolveTranscription TranscriptionResolver, agentBaseURL func(string) string, logger *zap.Logger) *PromptProxy
NewPromptProxy creates a PromptProxy. The resolver is invoked to obtain the admin-configured transcription model when a voice note arrives; pass nil to disable auto-transcription (voice notes flow through as plain attachments). agentBaseURL builds the canonical external web URL included in /start.
func (*PromptProxy) HandleCallback ¶
func (p *PromptProxy) HandleCallback( ctx context.Context, agentID, bridgeID, userID uuid.UUID, externalID, data string, events chan<- ResponseEvent, ) (staleRun bool, err error)
HandleCallback resolves a suspended run based on a bridge UI callback (inline-keyboard tap). data is the opaque platform payload — expected format:
"approve:<runID>" — resume with Approved=true, no prompt "deny:<runID>" — resume with Approved=false + a "Rejected by user." prompt
If the referenced run is no longer suspended or does not match the callback's bridge conversation identity, emits one "info" event and returns so the driver's AnswerCallbackQuery can clear the spinner.
func (*PromptProxy) HandleMessage ¶
func (p *PromptProxy) HandleMessage( ctx context.Context, agentID, bridgeID, userID uuid.UUID, externalID string, storeHistory bool, userMessage string, files []BridgeFile, referenced *BridgeReferencedMessage, events chan<- ResponseEvent, ) (string, error)
HandleMessage processes an incoming DM for an agent via a bridge. Manages conversation history, forwards to agent, streams response events to the provided channel, stores response when complete. The events channel is closed when streaming completes.
func (*PromptProxy) TranscribeVoicePlain ¶ added in v0.4.0
func (p *PromptProxy) TranscribeVoicePlain(ctx context.Context, files []BridgeFile) (text string, hasVoice bool, hasNonVoice bool)
TranscribeVoicePlain runs each voice-note file through the configured transcription model and returns the concatenated plain text — used by the sysagent-bridge path where there's no agent container, no per-file S3 key, and tagging transcripts with source keys would be meaningless. hasNonVoice signals that at least one non-voice file was attached so the caller can reject with a "files not supported" reply. Transcription failures degrade gracefully: the bool stays true if any voice file existed, the returned text just omits the failing entries.
type ResponseEvent ¶
type ResponseEvent struct {
Type string // "run_started", "text-delta", "tool-call", "tool-result", "confirmation_required", "compaction_started", "compaction_finished", "info"
Text string // for text-delta / info: the delta text or info message
ToolCallID string // for tool_call/tool_result
ToolName string // for tool_call/tool_result
ToolInput string // for tool_call: the tool arguments
ToolOutput string // for tool_result: the tool output
ToolError string // for tool_result: error message if failed
TokensFreed int // for compaction_finished
CompactionError string // for compaction_finished
Raw []byte // full NDJSON line (for non-text events drivers may need)
// Populated for run and compaction lifecycle events and confirmations.
RunID string
Permission string
Patterns []string
Code string
// Description is the plain-language summary a run_js confirmation carries;
// drivers lead with it instead of the permission name when present.
Description string
}
ResponseEvent represents an NDJSON event from the agent response stream, forwarded to the bridge driver for progressive delivery.
type RunCanceler ¶
RunCanceler is the slice of *Dispatcher that the agent-path slash conv adapter uses to fire /cancel. Defined as an interface so tests can stub without standing up containers / DB / encryptor.
type Scheduler ¶
type Scheduler struct {
// contains filtered or unexported fields
}
Scheduler leases immutable occurrences in PostgreSQL and acknowledges each attempt only after the agent returns a typed handler result.
func NewScheduler ¶
func (*Scheduler) ReconcileAgent ¶ added in v0.4.0
func (s *Scheduler) ReconcileAgent(ctx context.Context, agentID uuid.UUID, definitions []wire.ScheduleHandlerDef) error
ReconcileAgent transactionally retains matching cron occurrences, cancels stale ones, seeds missing occurrences, and orphans removed one-shot handlers.
type SlashCommand ¶
SlashCommand describes a user-typable command. Registry is the single source of truth: TrySlashCommand dispatches from it, and bridge drivers that support native command menus (Telegram setMyCommands, etc.) expose it verbatim. Name is stored without the leading slash.
type SlashCommandResult ¶
SlashCommandResult is the outcome of handling a slash command. Handled=false means the message was not a slash command — callers should forward it to the agent as usual. Handled=true means the command was recognized and processed. Reply is the short message to show the user, unless ForwardAsCompact is set — in that case the caller should invoke the agent with PromptInput.ForceCompact=true so Sol's summarization produces the user-visible text via a normal run. ForwardAsCompact is agent-path only; the sysagent path runs compact inline and returns the summary in Reply.
func TrySlashCommand ¶
func TrySlashCommand( ctx context.Context, conv SlashConv, convID pgtype.UUID, access agentsdk.Access, message string, ) (SlashCommandResult, error)
TrySlashCommand parses message for a leading slash command and, if recognized, dispatches it against conv. Returns Handled=false when the message is a plain user prompt — callers forward it to the agent (or sysagent) as usual.
access is the caller's resolved agent access; commands gate against SlashCommand.Access. /clear, /echo, /compact, /cancel route into SlashConv; /auth replies with the already-linked acknowledgement (the un-linked path is handled by the bridge before identity lookup).
type SlashConv ¶ added in v0.4.0
type SlashConv interface {
// Cancel aborts the latest live run on this conversation. Returns
// true if a cancel was dispatched, false if there was nothing in
// flight (or the cancel target couldn't be reached, e.g. process
// restart cleared the in-memory dispatcher state).
Cancel(ctx context.Context, convID pgtype.UUID) bool
// Clear advances the conversation's context checkpoint to a fresh
// marker message and resolves any lingering suspended run. Returns
// whether a suspension was cleared so the reply can mention it.
Clear(ctx context.Context, convID pgtype.UUID) (suspensionCleared bool, err error)
// Compact compacts the conversation's history. Agent path: returns
// (forward=true) so TrySlashCommand sets ForwardAsCompact and the
// agent container runs Sol.Runner.Compact, emitting the summary as
// a normal assistant message. Sysagent path: runs compaction
// in-process and returns (summary, forward=false).
Compact(ctx context.Context, convID pgtype.UUID) (reply string, forward bool, err error)
// Echo updates the "show tool output bubbles" setting and returns
// the resulting state. args is the raw post-/echo token ("on",
// "off", or empty for toggle).
Echo(ctx context.Context, convID pgtype.UUID, args string) (on bool, err error)
// Start returns the onboarding reply for /start — a greeting that names
// the bot's agent binding (agent bridge) or introduces the system
// assistant (system bridge). It does not gate on membership: a linked
// user at any access level (Public included) is welcome. Unlinked users
// never reach here — the bridge DMs a signed auth link upstream.
Start(ctx context.Context, convID pgtype.UUID) string
}
SlashConv is the per-conversation backing the slash-command dispatcher operates against. Two implementations: agentConvAdapter (agent bridges, web chat) and sysagentConvAdapter (system bridges → sysagent). Each method is the full compound operation the corresponding /command performs, not a primitive query — the per-conversation table choice stays inside the adapter.
type SysagentRuntime ¶ added in v0.4.0
type SysagentRuntime interface {
CancelRun(runID uuid.UUID) bool
Compact(ctx context.Context, p authz.Principal, conversationID uuid.UUID) (string, error)
// NotifyBotCreated injects a "bot ready" event into the sysagent
// conversation that requested the bot and resumes it, so the agent
// announces the new bot in-character (same shape as build/upgrade
// completion). Delivery to the bridge rides the resume's normal path.
NotifyBotCreated(ctx context.Context, conversationID uuid.UUID, botUsername string) error
RunPromptInline(
ctx context.Context,
p authz.Principal,
conversationID uuid.UUID,
text, platform string,
approved *bool,
resumeRunID string,
sink eventstream.Sink,
onStart func(runID uuid.UUID),
) (uuid.UUID, error)
}
SysagentRuntime is the narrow surface trigger uses from the sysagent package. Declared as an interface here so trigger doesn't import sysagent directly (sysagent → service/agents → trigger would cycle). *sysagent.Service satisfies this directly; api/router.go passes it in.
RunPromptInline handles three turn shapes — fresh user message (text non-empty), Approve/Reject of a previously-suspended run (approved non-nil + resumeRunID set), or auto-resume after a system event (all zero). Same shape as the web RunPrompt path.
type SysagentSlashConv ¶ added in v0.4.0
type SysagentSlashConv struct {
// contains filtered or unexported fields
}
SysagentSlashConv is the SlashConv implementation for system bridges, which route inbound DMs into the in-airlock sysagent. Each method operates against system_conversations / system_messages / system_runs instead of the agent_* tables. /compact runs sol.Runner.Compact locally and returns the summary text (there's no agent container to forward to).
func NewSysagentSlashConv ¶ added in v0.4.0
func NewSysagentSlashConv(svc SysagentRuntime, q *dbq.Queries, p authz.Principal, logger *zap.Logger) *SysagentSlashConv
NewSysagentSlashConv builds an adapter bound to a specific resolved caller. Per-request (not long-lived) because the principal changes per inbound DM.
func (*SysagentSlashConv) Cancel ¶ added in v0.4.0
Cancel — pick the latest running-or-suspended sysagent run on this conversation and ask the Service to interrupt its goroutine.
func (*SysagentSlashConv) Clear ¶ added in v0.4.0
Clear writes a sysagent checkpoint marker via AppendSystemMessage and advances system_conversations.context_checkpoint_message_id. Also flips any suspended sysagent run to cancelled so the pending- confirmation dialog doesn't linger past the clear.
func (*SysagentSlashConv) Compact ¶ added in v0.4.0
Compact runs sysagent's in-process summarize-and-checkpoint and returns the summary text. Unlike the agent path there's no container to forward to.
func (*SysagentSlashConv) Echo ¶ added in v0.4.0
func (s *SysagentSlashConv) Echo(ctx context.Context, convID pgtype.UUID, args string) (bool, error)
Echo flips system_conversations.settings.echo via the JSONB merge query. Toggle treats unset as off so the first /echo always turns it on. Mirrors the agent-path semantics.
type TelegramChatInfo ¶
TelegramChatInfo holds the subset of getChat fields we expose.
type TelegramDriver ¶
type TelegramDriver struct {
// contains filtered or unexported fields
}
TelegramDriver handles Telegram bridges via long-polling.
func NewTelegramDriver ¶
func NewTelegramDriver(logger *zap.Logger) *TelegramDriver
NewTelegramDriver creates a TelegramDriver. logger is used to surface Telegram API errors (notably the silent-failure Markdown/HTML parse rejections that otherwise vanish). Pass zap.NewNop() in tests.
The HTTP client's Timeout caps the entire request — connect, TLS, upload, server processing, response body read. Sized to comfortably cover the long-poll getUpdates window (timeout=30s server-side) plus TLS/network slack, while still releasing a goroutine if a connection stalls on a short call (sendMessage, getMe, …). Without a ceiling here those short calls can hang indefinitely on a half-open TCP socket — the kind of failure that happens on a local network blip (WG/VPN reconnect, NIC cycle) when the OS hasn't yet noticed the peer is gone.
func NewTelegramDriverWithBaseURL ¶
func NewTelegramDriverWithBaseURL(baseURL string, client *http.Client) *TelegramDriver
NewTelegramDriverWithBaseURL creates a TelegramDriver with a custom base URL and HTTP client (for testing).
func (*TelegramDriver) AnswerCallbackQuery ¶
func (d *TelegramDriver) AnswerCallbackQuery(ctx context.Context, token, callbackID, text string) error
AnswerCallbackQuery clears the loading spinner on a tapped inline-keyboard button. If text is non-empty, Telegram shows it as a transient toast.
func (*TelegramDriver) DefaultEcho ¶
func (d *TelegramDriver) DefaultEcho() bool
DefaultEcho reports that Telegram defaults to hiding tool bubbles: each tool-call / tool-result is rendered as its own chat message and a chatty agent quickly swamps the conversation. Users can opt in per-chat with `/echo on`.
func (*TelegramDriver) GetChat ¶
func (d *TelegramDriver) GetChat(ctx context.Context, token, chatID string) (TelegramChatInfo, error)
GetChat calls the Telegram getChat API for a private chat. Because private chat IDs equal the user ID, this resolves a telegram user's public username and display name as long as that user has DM'd the bot.
func (*TelegramDriver) GetManagedBotToken ¶ added in v0.4.0
func (d *TelegramDriver) GetManagedBotToken(ctx context.Context, managerToken string, botUserID int64) (string, error)
GetManagedBotToken fetches the bot token for a managed bot the manager bot just created. Bot API getManagedBotToken takes the new bot's user_id and returns the token directly under `result` (managerToken authenticates the call — it must have can_manage_bots).
func (*TelegramDriver) GetMeFull ¶ added in v0.4.0
func (d *TelegramDriver) GetMeFull(ctx context.Context, token string) (username, name string, botUserID int64, canManageBots bool, err error)
GetMeFull calls getMe and returns the bot's username, display name (first_name — the human-readable name that may contain spaces), stable user id, and can_manage_bots capability. Used where airlock needs the bot identity (to dedupe one-listener-per-bot), its display name (the bridge name shown in the UI), and the manager capability (to gate the is_manager behavior).
func (*TelegramDriver) GetMenuButton ¶ added in v0.4.0
func (d *TelegramDriver) GetMenuButton(ctx context.Context, token string) (TelegramMenuButton, error)
GetMenuButton reads the bot's default chat menu button. Airlock uses the default button rather than per-chat buttons, so chat_id is intentionally omitted.
func (*TelegramDriver) Poll ¶
func (d *TelegramDriver) Poll(ctx context.Context, br *dbq.Bridge) ([]BridgeEvent, error)
func (*TelegramDriver) RegisterCommands ¶
func (d *TelegramDriver) RegisterCommands(ctx context.Context, br dbq.Bridge, cmds []SlashCommand) error
RegisterCommands publishes the slash-command registry to Telegram's global command menu via setMyCommands. Telegram stores names without the leading slash.
func (*TelegramDriver) RemoveButtons ¶
func (d *TelegramDriver) RemoveButtons(ctx context.Context, br dbq.Bridge, externalID, messageID string) error
RemoveButtons strips the inline keyboard from a previously sent message via editMessageReplyMarkup. The message text is left intact so the conversation history still shows what was being confirmed.
func (*TelegramDriver) SendMessage ¶
func (d *TelegramDriver) SendMessage(ctx context.Context, token string, chatID int64, text string) error
SendMessage sends a text message to a Telegram chat.
func (*TelegramDriver) SendParts ¶
func (d *TelegramDriver) SendParts(ctx context.Context, token string, chatID int64, parts []wire.DisplayPart) error
SendParts sends display parts to a Telegram chat. Renders each part appropriately: text → sendMessage, image → sendPhoto, file → sendDocument.
func (*TelegramDriver) SendStream ¶
func (d *TelegramDriver) SendStream(ctx context.Context, br dbq.Bridge, externalID string, echo bool, events <-chan ResponseEvent) (string, error)
func (*TelegramDriver) SetMenuButton ¶ added in v0.4.0
func (d *TelegramDriver) SetMenuButton(ctx context.Context, token, url string) error
SetMenuButton configures the bot's default chat menu button to launch a Telegram Web App at the given URL. The button is persistent — it shows for every private chat the bot is in, opens the URL in Telegram's in-app browser, and exposes initData to the page so airlock can authenticate the user automatically.
Passing url=="" clears the bot back to Telegram's default menu (the commands list). Each call re-publishes the button at Telegram, but repeated writes of the same value are safe.
func (*TelegramDriver) Teardown ¶
Teardown clears the bot's chat menu button so a deleted or disabled bridge doesn't leave a dead web-app "Open" button in Telegram (setChatMenuButton is bot-global server-side state that otherwise persists). br.BotTokenRef must be the decrypted bot token — BridgeManager.TeardownBridge resolves it.
type TelegramMenuButton ¶ added in v0.4.0
TelegramMenuButton is the subset of Telegram's ChatMenuButton shape Airlock needs to converge the persistent Web App entrypoint.
type TranscriptionResolver ¶
type TranscriptionResolver func(ctx context.Context) (model.TranscriptionModel, error)
TranscriptionResolver returns the admin-configured transcription model or ErrTranscriptionNotConfigured when no model is set.
func NewTranscriptionResolver ¶
func NewTranscriptionResolver(database *db.DB, encryptor secrets.Store) TranscriptionResolver
NewTranscriptionResolver returns a resolver that reads system_settings.default_stt_provider_id + default_stt_model and looks up the associated provider row credentials.