Skip to content

Go API Reference

Internal Go packages for contributors and plugin developers. All packages live under internal/ and are not importable by external modules.

cli

CLI entry point and command registration.

SymbolDescription
VersionBuild version, set via -ldflags at compile time
Execute()Runs the root Cobra command. Calls os.Exit(1) on error

worker

Worker configuration, Docker lifecycle, registry, secrets, and health checking.

Types

TypeDescription
WorkerWorker definition parsed from YAML. If Docker is non-nil, managed; if Adapter is non-nil, adapter; otherwise unmanaged
DockerConfigDocker container settings (image, cwd, resources, env, token, lifecycle)
AdapterConfigIn-process LLM adapter settings (type, upstream, model, api_key)
ResourceConfigContainer CPU, memory, and PID limits
EventRuleDefines when a worker handles an event (source, on, filter, prompt)
DockerClientWraps the moby Docker SDK for container lifecycle operations
ContainerCfgParameters for creating a Docker container (name, image, env, mounts, resources)
MountCfgBind mount from host to container (source, target, read-only)
SecretsTokens loaded from ~/.mecha/secrets.yml
RegistryManages worker state with mutex-protected in-memory map and SQLite persistence
EntryCombines a worker definition with its runtime state
StateWorker lifecycle state
StateOfflineDefinition exists, container stopped or absent
StateOnlineContainer running, health check passing
StateBusyExecuting a task (returns 429)
StateErrorHealth check failed or container exited

Worker Methods

MethodDescription
IsManaged() boolTrue if worker has a Docker section
IsAdapter() boolTrue if worker uses an in-process adapter
TypeLabel() stringReturns "managed", "adapter", or "live"

Entry Methods

MethodDescription
Sanitized() EntryReturn a deep copy with env vars, token, and API key fields redacted. Use for API responses and logs

EventRule Methods

MethodDescription
IsAuto() boolWhether this rule dispatches automatically (default: true)

Config Functions

FunctionDescription
LoadFile(path) (*Worker, error)Read YAML, interpolate env vars, validate, apply defaults
LoadDir(dir) ([]*Worker, error)Load all .yml/.yaml files in a directory

Validation

FunctionDescription
DockerConfig.Validate() errorChecks image required, lifecycle values, expose/api_key coupling, cwd path safety, resource specs
AdapterConfig.Validate() errorChecks type is ollama or openai, upstream and model required
IsSensitivePath(absPath) boolReports whether a path is a protected system or credential path (/etc, ~/.ssh, etc.)

Docker Client

MethodDescription
NewDockerClient(host) (*DockerClient, error)Create client. Empty host uses DOCKER_HOST env var
Pull(ctx, image) errorDownload a Docker image
Create(ctx, cfg) (containerID, error)Build and create a container
Start(ctx, id) errorStart a created container
Stop(ctx, id, timeout) errorGracefully stop a container
Remove(ctx, id) errorForce-remove a container
Endpoint(ctx, id) (url, error)Inspect container and return its mapped HTTP URL
Ping(ctx) (apiVersion, error)Check if Docker daemon is reachable
ImageExists(ctx, image) (bool, error)Check if an image is available locally
Close() errorRelease the Docker client connection

Container Assembly

FunctionDescription
BuildContainerEnv(dc, validate) (map, error)Assemble env vars: resolve token from secrets, merge docker.env, set HOME
ResolveCwd(cwd) (string, error)Canonicalize cwd: resolve symlinks, make absolute, verify dir exists
BuildContainerMounts(dc) ([]MountCfg, error)Resolve docker.cwd into a bind mount at /workspace
CurrentUser() (string, error)Returns "uid:gid" for the container --user flag

Registry

MethodDescription
NewRegistry(db) (*Registry, error)Create registry backed by SQLite. Loads existing workers
Add(w) errorRegister a new worker in offline state
Remove(name) errorDelete a worker (must be offline)
Start(name) errorTransition offline to online (unmanaged workers)
Stop(name) errorTransition online/error to offline
Get(name) (Entry, bool)Return a deep copy of the named entry
List() []EntryReturn deep copies of all entries sorted by name
Reload() errorRe-read all workers from SQLite into the in-memory cache
SetRuntime(name, containerID, endpoint) errorRecord container runtime info, transition to online
StopRuntime(name) errorTransition to offline, clear endpoint (keep container ID)
ClearRuntime(name) errorTransition to offline, clear all runtime fields
SetBusy(name) errorTransition online to busy (task dispatched)
SetOnline(name) errorTransition busy to online (task completed)
SetError(name, errMsg) errorTransition to error state with redacted message

Secrets

FunctionDescription
LoadSecrets(path) (*Secrets, error)Read YAML secrets file. Returns empty for missing file. Errors on bad permissions (want 0600)
DefaultSecretsPath() (string, error)Returns ~/.mecha/secrets.yml
Resolve(ref) (string, error)Look up token by "backend.name" reference (e.g. "claude.xiaolaidev")
DetectTokenEnvVar(token) (envKey, token)Map token value to env var name by prefix (sk-ant-oat -> CLAUDE_CODE_OAUTH_TOKEN, etc.)

Health & Redaction

FunctionDescription
CheckHealth(endpoint, timeout) errorSend GET <endpoint>/health, return nil on HTTP 200
RedactSecrets(s) stringReplace known credential patterns with [REDACTED] (13 patterns)

event

Event types and SQLite persistence.

Types

TypeDescription
EventSomething that happened from an external source. Provider-neutral: Actor, Subject, Attrs
AttrsMap of provider-specific fields available to prompt templates
StateEvent lifecycle state
StoreManages event persistence in SQLite

State Constants

ConstantValueDescription
StateReceived"received"Event arrived, not yet matched
StateMatched"matched"Matched to a worker by event rules
StateDispatched"dispatched"Task created and sent to worker
StateCompleted"completed"Worker returned a result
StateFailed"failed"Processing errored or timed out
StateSkipped"skipped"No matching worker found

Store Methods

MethodDescription
NewStore(db) *StoreCreate an event store
Create(ctx, ev) errorPersist a new event in received state
Get(ctx, id) (*Event, error)Retrieve an event by ID
List(ctx, state) ([]Event, error)List events, optionally filtered by state
DeliveryExists(ctx, deliveryID) (bool, error)Check if a delivery ID has been processed (dedup)
SetMatched(ctx, id, workerName) errorTransition received -> matched
SetDispatched(ctx, id, taskID) errorTransition matched -> dispatched
SetCompleted(ctx, id) errorTransition dispatched -> completed
SetFailed(ctx, id) errorMark as failed from any active state
SetSkipped(ctx, id) errorTransition received -> skipped
UpdateAttrs(ctx, id, attrs) errorPersist hydrated attrs back to the database
Received(ctx) ([]string, error)Return IDs of events stuck in received state (crash recovery)
DedupKeyActive(ctx, dedupKey) (bool, error)Check if an active event (received, matched, or dispatched) with the given dedup key exists. Terminal states (completed, failed, skipped) do not block

Dedup Errors

SymbolDescription
ErrDuplicateDedupSentinel error returned by Create when an event with the same DedupKey is already active

task

Task types and SQLite persistence.

Types

TypeDescription
TaskA unit of work sent to a worker
StateTask lifecycle state
StoreManages task persistence in SQLite

State Constants

ConstantValueDescription
StatePending"pending"Queued but not yet sent
StateDispatched"dispatched"Sent to a worker
StateCompleted"completed"Worker returned a result
StateFailed"failed"Errored or timed out

Store Methods

MethodDescription
NewStore(db) *StoreCreate a task store
Create(ctx, workerName, prompt) (*Task, error)Insert a task in pending state
CreateWithEvent(ctx, workerName, prompt, context, eventID) (*Task, error)Insert a task with event context
Get(ctx, id) (*Task, error)Retrieve a task by ID
List(ctx, state) ([]Task, error)List tasks, optionally filtered by state
SetDispatched(ctx, id) errorMark as dispatched
Complete(ctx, id, result) errorMark as completed with result
Fail(ctx, id, errMsg) errorMark as failed with error
Pending(ctx) ([]string, error)Return IDs of pending/dispatched tasks (for recovery)
RetryOrFail(ctx, id, errMsg) (bool, error)Increment attempt counter and either re-queue for retry (with exponential backoff) or mark as permanently failed (dead-letter). Returns true if re-queued
ReadyForRetry(ctx) ([]string, error)Return IDs of pending tasks whose retry delay has elapsed (next_retry_at <= now)
HasCompletedDedup(ctx, dedupKey) (bool, error)Check if a task with the given dedup key has already completed (prevents duplicate dispatch during crash recovery)

Retry Constants

ConstantValueDescription
DefaultMaxRetries3Default number of retry attempts before dead-letter
RetryBaseDelay30sBase delay for exponential backoff (30s, 60s, 120s)

policy

Policy filtering for write-back results.

Types

TypeDescription
ResultShared worker result contract (output, comment, labels, status, commit, metadata)
CommentActionPosts a comment to a PR or issue
LabelActionAdds or removes labels
StatusActionSets a commit status
CommitActionSuggests code changes
FilterInterface for policy filters (Apply method)
RuleFilterPer-worker policy rules parsed from YAML
DenyAllBlocks all write-back actions (used for invalid policy config)
AllowAllPasses everything through (used when no policy is configured)
CommentPolicyControls comment write-back (allow, max_length)
LabelPolicyControls label write-back (allow, blocked list, Allowed allowlist for restrictive filtering)
StatusPolicyControls commit status write-back (allow)
CommitPolicyControls code change suggestions (allow, MaxSize max diff bytes)
MetadataPolicyControls whether metadata is included in the result (allow). When denied, metadata is redacted
DecisionRecords what the policy allowed and denied
ValidStatusStatesmap[string]bool — canonical set: error, failure, pending, success

Functions

FunctionDescription
ParseRules(raw) (Filter, error)Convert a raw YAML map into a RuleFilter. Returns AllowAll if empty
RuleFilter.Apply(ctx, ev, result) (Result, Decision, error)Filter result according to configured rules
AllowAll.Apply(ctx, ev, result) (Result, Decision, error)Passes all actions through unchanged
DenyAll.Apply(ctx, ev, result) (Result, Decision, error)Returns empty result with all actions denied

source

Webhook source parsing (GitHub, GitLab, generic).

Types

TypeDescription
SourceInterface: parses incoming webhooks into normalized events (Name, Parse)
TriggerInterface: generates events actively — cron, polling, subscriptions (Name, Start)
HydratorInterface: enriches events with additional data (e.g. fetching diffs)
VerifierInterface: handles webhook verification challenges (Meta, Slack)
AuthenticatedMarker interface: sources that validate webhooks themselves (HMAC, token)
ResponderInterface: writes task results back to an external platform (Name, Respond)
RegistryHolds registered sources, triggers, and responders by name
GitHubSourceParses GitHub webhook payloads. Validates HMAC-SHA256. Implements Authenticated
GitLabSourceParses GitLab webhook payloads. Validates X-Gitlab-Token. Implements Authenticated
SlackSourceParses Slack webhook payloads. Validates HMAC-SHA256 (v0= scheme) with 5-minute replay protection. Implements Authenticated
TelegramSourceParses Telegram Bot API webhook payloads. Validates X-Telegram-Bot-Api-Secret-Token (constant-time comparison). Implements Authenticated
CronTriggerActive trigger that emits tick events on a fixed interval. Implements Trigger
GitLabResponderWrites task results back to GitLab MRs and issues (comments, status, labels, commit suggestions). Implements Responder
GenericSourceParses arbitrary JSON webhooks. Event type from configurable header. No built-in auth
ErrSlackChallengeSentinel error returned by SlackSource.Parse when the payload is a url_verification challenge

Constructors

FunctionDescription
NewRegistry() *RegistryCreate an empty source registry
NewGitHubSource(secret, token) *GitHubSourceCreate GitHub webhook source
NewGitLabSource(secret) *GitLabSourceCreate GitLab webhook source
NewSlackSource(signingSecret) *SlackSourceCreate Slack webhook source with HMAC-SHA256 verification
NewTelegramSource(secretToken) *TelegramSourceCreate Telegram webhook source with secret token verification
NewCronTrigger(name, interval, subject) *CronTriggerCreate a cron trigger that fires every interval
NewGitLabResponder(apiBase, token) *GitLabResponderCreate a GitLab write-back responder (requires PAT with api scope)
NewGenericSource(name, typeHeader) *GenericSourceCreate generic webhook source

Registry Methods

MethodDescription
Register(s Source)Add a webhook source to the registry
RegisterTrigger(t Trigger)Add an active trigger to the registry
RegisterResponder(resp Responder)Add a write-back responder to the registry
Get(name) (Source, bool)Look up a source by name
GetTrigger(name) (Trigger, bool)Look up a trigger by name
GetResponder(name) (Responder, bool)Look up a responder by name
Triggers() map[string]TriggerReturn a copy of all registered triggers
Len() intNumber of registered sources

Source Methods

MethodDescription
GitHubSource.Hydrate(ctx, ev) errorEnrich a GitHub event with diff and file data
VerifyChallenge(body) ([]byte, bool)Extract Slack url_verification challenge response from a webhook payload. Returns the JSON response and true if the payload is a challenge, false otherwise

adapter

In-process LLM adapters translating native APIs to the worker contract.

Types

TypeDescription
AdapterInterface: Name(), Health(ctx), SendTask(ctx, prompt)
RunnerWraps an Adapter with an HTTP server (GET /health, POST /task)
OllamaAdapterTranslates Ollama /api/chat into the worker contract
OpenAIAdapterTranslates OpenAI-compatible /v1/chat/completions into the worker contract

Functions

FunctionDescription
NewRunner(adapter, logger) (*Runner, error)Create a runner listening on a random localhost port
Runner.Start()Begin serving (non-blocking)
Runner.Stop(ctx) errorShutdown the HTTP server gracefully
Runner.Endpoint() stringReturn the HTTP URL the runner listens on
NewOllamaAdapter(upstream, model) *OllamaAdapterCreate adapter for a running Ollama instance
NewOpenAIAdapter(upstream, model, apiKey) *OpenAIAdapterCreate adapter for an OpenAI-compatible endpoint

serve

HTTP server, webhook dispatch, and task management.

Types

TypeDescription
ServerHTTP daemon that accepts tasks and dispatches to workers
ConfigServer startup parameters (registry, stores, sources, addr, api key)
RateLimiterPer-worker token bucket rate limiter. Cleanup runs every 5m, removes buckets unused for 10m

Functions

FunctionDescription
New(cfg Config) *ServerCreate a server (does not start it)
Start(ctx) errorBegin serving HTTP and the dispatch loop. Blocks until ctx is cancelled
NewRateLimiter(rate, burst) *RateLimiterCreate a per-worker rate limiter. rate is requests/second/worker, burst is max concurrent
RateLimiter.Allow(workerName) boolCheck if a request is allowed (consumes a token). Returns false if rate-limited
RateLimiter.Cleanup()Remove stale buckets not used in the last 10 minutes

worker (config)

Server configuration loaded from ~/.mecha/config.yml.

Types

TypeDescription
ServerConfigServer config with Addr (listen address) and APIKey fields, loaded from YAML

Functions

FunctionDescription
DefaultServerConfig() ServerConfigReturns config with defaults (Addr: "127.0.0.1:21212", empty APIKey)
LoadServerConfig() (ServerConfig, error)Read ~/.mecha/config.yml. Returns defaults if the file is missing

logs

Structured pipeline audit trail. Records observations at each pipeline stage.

Types

TypeDescription
EntrySingle log record: trace_id, action, outcome, event_id, task_id, worker, attempt, error, detail
FilterQuery constraints: TraceID, EventID, TaskID, Worker, Action (prefix match), Since, Until, Limit
LoggerInterface with single method Record(Entry)
StoreSQLite-backed log store implementing Logger

Functions

FunctionDescription
NewStore(db, logger) *StoreCreate a log store. Logger is used for write-error fallback
Store.Record(e Entry)Persist a log entry. Fire-and-forget: errors logged, never propagated
Store.Query(ctx, Filter) ([]Entry, error)Retrieve entries matching filter. Results ordered by ID desc, max 1000
Store.Prune(ctx, before time.Time) (int64, error)Delete entries older than before. Returns count deleted
MarshalDetail(v any) stringMarshal value to redacted JSON string for the Detail field

Action Constants

ConstantValuePipeline Phase
EventReceivedevent.receivedWebhook
EventDuplicateevent.duplicateWebhook
EventMatchedevent.matchedMatch
EventSkippedevent.skippedMatch
EventHydratedevent.hydratedMatch
TaskCreatedtask.createdDispatch
TaskSenttask.sentDispatch
TaskRateLimitedtask.rate_limitedDispatch
TaskRetrytask.retryDispatch
TaskDeadLettertask.dead_letterDispatch
PolicyAppliedpolicy.appliedPolicy
WritebackOKwriteback.okWrite-back
WritebackFailwriteback.failWrite-back
WorkerStateworker.stateWorker

Outcome Constants

ConstantValueMeaning
OKokSuccess
FailfailPermanent failure
SkipskipSkipped (no match, no action)
RetryretryTransient failure, will retry
DenydenyBlocked by policy

store

SQLite database management.

Functions

FunctionDescription
Open(path) (*sql.DB, error)Create or open a SQLite database with WAL mode and versioned migrations
DefaultDBPath() (string, error)Returns ~/.mecha/mecha.db

writeback

GitHub write-back integration.

Types

TypeDescription
ClientWrites task results back to GitHub. Implements source.Responder

Functions

FunctionDescription
NewClient(token, logger) *ClientCreate a write-back client
Name() stringReturns "github" (implements source.Responder)
Respond(ctx, event, result) errorWrite a policy-filtered result to GitHub (implements source.Responder)
WriteBackResult(ctx, event, result) errorWrite a policy-filtered result to GitHub
OverrideAPIBase(url) func()Test utility: replace GitHub API base URL, returns restore function

Released under the ISC License.