Skip to content

Backend Reference

import "github.com/qtpi-automaton/pocketcoder/backend"

@pocketcoder-core: Main Orchestrator. Registers hooks, starts the relay, and boots PocketBase. @pocketcoder-core: Sovereign Relay. The orchestration layer that syncs OpenCode with the Sandbox.

func main()
import "github.com/qtpi-automaton/pocketcoder/backend/internal/agents"

@pocketcoder-core: Agent Bundler. Expands agent records into frontmatter-laden bundles.

func GetAgentBundle(app *pocketbase.PocketBase, agent *core.Record) (string, error)

GetAgentBundle converts an Agent record into a frontmatter-laden bundle.

func UpdateAgentConfig(app *pocketbase.PocketBase, agent *core.Record) error

UpdateAgentConfig re-assembles the bundle and saves it to the ‘config’ field if changed.

import "github.com/qtpi-automaton/pocketcoder/backend/internal/api"

@pocketcoder-core: Cron API. Endpoints for Poco to schedule, list, and cancel cron jobs.

@pocketcoder-core: Logs API. Native Docker log streaming via SSE.

@pocketcoder-core: MCP API. Handler for MCP server requests from Poco.

@pocketcoder-core: Authority Evaluator. The custom logic for determining tool permissions.

@pocketcoder-core: Proxy API. Reverse proxy for observability and log services.

@pocketcoder-core: SSH API. Handlers for public key registration and rotation.

func RegisterCronApi(app *pocketbase.PocketBase, e *core.ServeEvent)

RegisterCronApi registers the cron task management endpoints.

func RegisterLogsApi(app *pocketbase.PocketBase, e *core.ServeEvent)

RegisterLogsApi registers the native Docker log streaming endpoints.

func RegisterMcpApi(app *pocketbase.PocketBase, e *core.ServeEvent)

RegisterMcpApi registers the MCP server request endpoint.

func RegisterPermissionApi(app *pocketbase.PocketBase, e *core.ServeEvent)

RegisterPermissionApi registers the Sovereign Authority evaluation endpoint.

func RegisterProxyApi(app *pocketbase.PocketBase, e *core.ServeEvent)

RegisterProxyApi registers the reverse proxy endpoints for logs and observability.

func RegisterSSHApi(app *pocketbase.PocketBase, e *core.ServeEvent)

RegisterSSHApi registers the SSH public key sync endpoint.

func createProxyHandler(target string, prefix string) func(re *core.RequestEvent) error

createProxyHandler creates a standard reverse proxy handler that strips a prefix and forwards to a target.

func resolveHumanUser(app *pocketbase.PocketBase, sessionID string) (string, string, error)

resolveHumanUser finds the human user ID and chat ID from an OpenCode session ID.

import "github.com/qtpi-automaton/pocketcoder/backend/internal/filesystem"

@pocketcoder-core: Artifact API. Secure endpoint for accessing workspace artifacts.

func RegisterArtifactApi(app *pocketbase.PocketBase, e *core.ServeEvent)

RegisterArtifactApi provides a secure window into the /workspace using the PB Filesystem abstraction.

import "github.com/qtpi-automaton/pocketcoder/backend/internal/hooks"

@pocketcoder-core: Agent Hooks. Triggers re-bundling when agent records change.

@pocketcoder-core: Cron Hooks. Manages scheduled agent tasks via PocketBase’s built-in cron scheduler.

@pocketcoder-core: LLM Hooks. Handles API key persistence and OpenCode container restart.

@pocketcoder-core: MCP Hooks. Handles MCP server lifecycle, config rendering, and gateway restart.

@pocketcoder-core: Notification Dispatcher. Sends push notifications based on record events and user presence.

@pocketcoder-core: Permission Engine. Registers hooks for auditing and gating record creation.

@pocketcoder-core: SOP Hooks. Seals approved proposals into the governance ledger.

@pocketcoder-core: Timestamp Hooks. Manages created/updated/last_active fields globally.

@pocketcoder-core: Tool Permission Hooks. Renders opencode.json permission + agent blocks and restarts OpenCode.

const (
llmEnvPath = "/workspace/.opencode/llm.env"
llmEnvPathShared = "/llm_keys/llm.env"
openCodeContainer = "pocketcoder-opencode"
)

const (
mcpConfigPath = "/mcp_config/docker-mcp.yaml"
mcpSecretsPath = "/mcp_config/mcp.env"
gatewayContainer = "pocketcoder-mcp-gateway"
defaultDockerHost = "tcp://docker-socket-proxy-write:2375"
)

const cronJobPrefix = "pc_cron_"

const (
openCodeConfigPath = "/workspace/.opencode/opencode.json"
)

func IsUserOnline(app core.App, userID string) bool

IsUserOnline checks if the user has an active Realtime (SSE) connection.

func RegisterAgentHooks(app *pocketbase.PocketBase)

RegisterAgentHooks registers hooks that trigger agent re-bundling.

func RegisterCronHooks(app core.App)

RegisterCronHooks registers hooks for scheduled agent task management. When a user creates, updates, or deletes a cron job record, this hook syncs the PocketBase cron scheduler accordingly. When a job fires, it creates a message (in an existing or new chat) that the Interface event pump picks up and forwards to OpenCode.

func RegisterGlobalTimestamps(app *pocketbase.PocketBase)

RegisterGlobalTimestamps registers hooks for created, updated, and last_active timestamps.

func RegisterLlmHooks(app core.App)

RegisterLlmHooks registers hooks on the llm_keys collection. When a user saves, updates, or deletes an API key, this hook re-renders the llm.env file and restarts the OpenCode container.

func RegisterMcpHooks(app core.App, openCodeURL string)

RegisterMcpHooks registers hooks for MCP server lifecycle management. When a user approves or revokes an MCP server in the Flutter UI, this hook re-renders the gateway config and restarts the MCP gateway container.

func RegisterNotificationHooks(app *pocketbase.PocketBase)

RegisterNotificationHooks registers hooks for triggering push notifications and the /api/push custom endpoint.

func RegisterPermissionHooks(app *pocketbase.PocketBase)

RegisterPermissionHooks registers hooks for the permissions collection.

func RegisterPushApi(app *pocketbase.PocketBase, e *core.ServeEvent)

RegisterPushApi registers the POST /api/push endpoint. Called by the interface service to send push notifications for task_complete, task_error, and other notification types.

func RegisterSopHooks(app *pocketbase.PocketBase)

RegisterSopHooks manages the transition from proposal to sealed SOP

func RegisterToolPermissionHooks(app core.App)

RegisterToolPermissionHooks registers hooks that re-render the OpenCode config whenever tool_permissions or ai_agents change.

func SealProposal(app *pocketbase.PocketBase, proposal *core.Record) error

SealProposal takes a proposal record, hashes it, and promotes it to the sops ledger. This is the “Master of Signature” implementation where the backend handles integrity.

func SendPushNotification(app core.App, userID, title, message, notifType, chatID string)

SendPushNotification is the unified dispatch function. Flow: rules check -> presence check -> device dispatch

func buildPermissionBlock(perms []permEntry) map[string]interface{}

buildPermissionBlock converts a list of permission entries into the OpenCode permission format. Tools with only pattern=”*” get flat format (“tool”: “action”). Tools with multiple patterns get nested format (“tool”: {“pattern”: “action”, …}).

func createCronChat(app core.App, jobRecord *core.Record, userID string) (string, error)

createCronChat creates a new chat for a cron job execution.

func createCronMessage(app core.App, chatID string, prompt string) error

createCronMessage creates a user message in the target chat.

func dispatchToDevices(app core.App, userID, title, message, notifType, chatID string)

dispatchToDevices sends notifications to every active device registered to the user.

func executeCronJob(app core.App, jobRecordID string)

executeCronJob is the handler called when a cron job fires. It creates a message in an existing chat or creates a new chat + message, depending on the job’s session_mode.

func isNotificationTypeEnabled(app core.App, userID, notifType string) bool

isNotificationTypeEnabled checks the user’s notification_rules record. Returns true if the type is enabled or if no rules exist (opt-out model).

func notifyPoco(app core.App, openCodeURL string, serverName string, status string)

notifyPoco sends a system message to Poco about MCP server status changes.

func renderLlmEnv(app core.App) error

renderLlmEnv queries ALL llm_keys records and writes a flat env file.

func renderMcpConfig(app core.App) error

renderMcpConfig queries approved MCP servers and writes docker-mcp.yaml and mcp.env to the shared /mcp_config volume. The gateway reads these on startup.

func renderOpenCodeConfig(app core.App) error

renderOpenCodeConfig reads the existing opencode.json, patches the permission and agent blocks from PocketBase data, and writes it back.

func restartGateway() error

restartGateway sends a restart command to the MCP gateway container via the Docker Socket Proxy.

func restartOpenCode() error

restartOpenCode sends a restart command to the OpenCode container via the Docker Socket Proxy.

func syncAllCronJobs(app core.App)

syncAllCronJobs queries all enabled cron jobs and registers them with app.Cron().

func syncCronJob(app core.App, record *core.Record)

syncCronJob registers or removes a single cron job from the scheduler. If the job is enabled, it registers (or re-registers) the cron entry. If disabled, it removes any existing entry.

func updateCronJobStatus(app core.App, record *core.Record, status string, lastError string)

updateCronJobStatus updates the last_executed, last_status, and last_error fields.

FcmRelayProvider routes notifications through a Cloudflare Worker relay. The Worker handles subscription verification (RevenueCat), rate limiting (Supabase), and FCM v1 delivery — PocketBase just fires and forgets.

type FcmRelayProvider struct {
RelayURL string
UserID string
ChatID string
Type string
}

func (p *FcmRelayProvider) Send(token, title, body string) error

NtfyDirectProvider sends notifications directly to a UnifiedPush (ntfy) endpoint. This preserves the “Zero-Trust” sovereign architecture.

type NtfyDirectProvider struct {
ChatID string
Type string
}

func (p *NtfyDirectProvider) Send(endpoint, title, body string) error

PushProvider defines the interface for different notification services.

type PushProvider interface {
Send(token, title, body string) error
}

type permEntry struct {
tool string
pattern string
action string
}
import "github.com/qtpi-automaton/pocketcoder/backend/internal/permission"

@pocketcoder-core: Permission Evaluator. Checks requests against whitelisted action patterns.

func Evaluate(app core.App, input EvaluationInput) (bool, string)

Evaluate checks if a permission request is whitelisted based on actions.

EvaluationInput represents the data needed to evaluate a permission request.

type EvaluationInput struct {
Permission string
Patterns []string
Metadata map[string]any
}
import "github.com/qtpi-automaton/pocketcoder/backend/internal/provisioning"

func ProvisionSops(app *pocketbase.PocketBase)

ProvisionSops syncs filesystem SOPs into the ‘proposals’ collection. They must still be manually ‘Sealed’ in the ledger to be usable by Poco.

func extractMetadata(content string) (name, description string)

Simple metadata extractor for YAML frontmatter

func processSopProposal(app *pocketbase.PocketBase, path string)
import "github.com/qtpi-automaton/pocketcoder/backend/internal/utils"

@pocketcoder-core: Wildcard Matcher. Glob-to-regex pattern matching for permission paths.

func MatchWildcard(str string, pattern string) bool

MatchWildcard implements a simple glob-like pattern matching (e.g. /workspace/**). It converts internal wildcards (*, ?) into regex patterns.

Generated by gomarkdoc