Documentation
¶
Overview ¶
Package agents is the coding-agent adapter seam. Everything CLI-format specific lives here, so agent drift touches one package.
claude — first-class: stream-json events, hook approvals, session resume. codex — experimental: `codex exec --json` JSONL; no gated mode, no resume. gemini — experimental: plain-text output mapped to timeline lines.
The run protocol itself is agent-agnostic (worktree + tmux + events file + exit_code), so adapters only build the inner command and normalise output.
Index ¶
- Constants
- Variables
- func BuildSettings(in SettingsInput) (map[string]any, error)
- func CodexMCPArgs(mcp map[string]any) ([]string, error)
- func EnvPrefix(env map[string]string, sandbox bool) (string, error)
- func HookSettings(baseURL, token, matcher string, expireSeconds int) map[string]any
- func HostMCPServers(configPath string) []string
- func InteractiveMCPRel(sessionID int64, nonce string) string
- func MCPInstallCommand(rel string, payload []byte) string
- func MCPPayload(mcp map[string]any) ([]byte, error)
- func MCPStateEnvPrefix(env map[string]string) (string, error)
- func MemoryLinkCommand(worktree, memoryDir string) string
- func PrivateMCPPath(output string) (string, error)
- func PrivateMCPRel(id int64, nonce string) string
- func ProjectSlug(path string) string
- func RuntimeDir(worktree string) string
- func TaskMCPRel(attemptID int64, nonce string) string
- type Event
- type LaunchSpec
- type Launcher
- type Permissions
- type SettingsInput
- type TaskDefinition
- type TaskLaunchConfig
Constants ¶
const ( SettingsRel = ".lectern/settings.json" MCPRel = ".lectern/mcp.json" )
Paths of the runtime files every attempt gets, relative to its worktree.
const DefaultGateMatcher = "*"
DefaultGateMatcher is which tools the approval hook intercepts in gated mode.
'*' is the only value that makes gated mode usable: anything NOT matched falls through to the normal permission system, and headless `claude -p` has no way to ask — so an unmatched tool is silently DENIED. The old narrow matcher meant MCP tools, WebFetch and Task could never run in gated mode and never said why.
Variables ¶
var CapabilityProfiles = []string{"restricted", "parity"}
CapabilityProfiles are the two shapes a project's agent capability can take.
var GatedCapable = map[string]bool{"claude": true}
GatedCapable are the agents that support the hook-gated 'default' permission mode. codex and gemini have no PreToolUse equivalent, so a gated task on them is rejected before dispatch rather than silently running ungated.
var Names = []string{"claude", "codex", "gemini"}
Names are the agents lectern knows how to launch.
var NoiseLines = map[string]bool{"Reading additional input from stdin...": true}
NoiseLines is output an agent prints that is not an event and not worth a 'raw' card on the timeline (codex announces its stdin handling first).
var ParityTools = []string{"Bash", "Read", "Write", "Edit", "MultiEdit", "NotebookEdit",
"Glob", "Grep", "WebFetch", "WebSearch", "TodoWrite", "Task", "Skill"}
ParityTools are the tools an interactive session takes for granted.
Headless grants NONE of them: with no rules a dispatched agent cannot pipe a command, read a file outside its worktree, or call a single MCP tool — it just produces worse work and says nothing. 'Bash' is listed bare on purpose: a prefix rule like Bash(git*) makes Claude Code split compound commands and refuse the parts it cannot match, so `ls | head` dies with "This Bash command contains multiple operations".
var PermissionKeys = []string{"allow", "deny", "ask", "defaultMode", "additionalDirectories"}
PermissionKeys are the settings.json permission keys we pass through. Anything else is rejected so a typo fails loudly at config time instead of silently widening or narrowing access mid-run.
Functions ¶
func BuildSettings ¶
func BuildSettings(in SettingsInput) (map[string]any, error)
BuildSettings renders the settings.json every attempt gets: permission rules always, the approval hook when gated.
It is written unconditionally (it used to be gated-mode only) because without it an acceptEdits run cannot be granted Bash at all: headless has no prompt, so any tool needing permission is denied with no signal to the operator.
MemoryDir goes into additionalDirectories whenever it is set: the symlink that shares a memory store lands OUTSIDE the worktree, and the filesystem sandbox refuses paths outside it — so without this the store is linked and then unreadable, which is worse than not sharing it at all.
func CodexMCPArgs ¶
CodexMCPArgs returns additive -c overrides. It deliberately does not alter CODEX_HOME: that directory owns auth, history, instructions and plugins.
func EnvPrefix ¶
EnvPrefix renders the shell prefix of KEY=VAL pairs injected before the agent binary.
This is the any-model door: point a project at any Anthropic-compatible endpoint (Ollama >= 0.20 natively, LiteLLM, llama.cpp, vLLM gateways) via ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN, or set OPENAI_*/GEMINI_* for the other agents. Values are shell-quoted; keys are validated.
func HookSettings ¶
HookSettings is the PreToolUse gate; only used when permission mode is 'default'.
func HostMCPServers ¶
HostMCPServers lists the user-scope MCP server names the control plane's own Claude Code has.
An agent on a LOCAL target runs as the same user and inherits these servers already — it simply cannot call one without a matching permission rule, which is the whole gap the parity profile closes. Remote targets have none of them, and these definitions are NOT portable anyway: they point at local binaries and carry live secrets in their env blocks, so they are never copied.
func InteractiveMCPRel ¶
InteractiveMCPRel is private to one interactive session.
func MCPInstallCommand ¶
MCPInstallCommand performs the complete private runtime install in one target-side operation. The payload is base64-encoded so neither JSON bytes nor path values become shell syntax. It prints the resulting absolute path; the target's normal HOME/XDG state directory supplies the root.
func MCPPayload ¶
MCPPayload normalizes the project form into the standard Claude document.
func MCPStateEnvPrefix ¶
MCPStateEnvPrefix forwards only the state-directory selectors. Agent API credentials and model endpoints do not belong in the helper's environment.
func MemoryLinkCommand ¶
MemoryLinkCommand points this attempt's session memory at a shared store.
A fresh worktree per attempt starts memory-blind and everything an agent learns dies with the worktree. There is no CLI flag for this, so the only mechanism is symlinking the session's memory dir at a store the operator nominates.
Memory is keyed to the git MAIN worktree, not to cwd — verified against the CLI by running it inside a linked worktree under /tmp and asking for its own memory path, which came back as the parent repo's slug. Sessions are keyed by cwd, so the two diverge, and linking the cwd slug (what this did before) created a symlink the agent never opened. The main worktree is resolved on the target rather than guessed here, so worktrees, plain clones and sandbox checkouts all land on the same answer.
A real non-empty directory at the link path is left ALONE: that path can be a repo the operator also works in interactively, and silently deleting their memories to install a symlink is not a trade worth making.
func PrivateMCPPath ¶
PrivateMCPPath validates the helper's absolute-path result before it becomes part of a launch command.
func PrivateMCPRel ¶
PrivateMCPRel is private to one attempt/session and lives in Lectern's per-user state directory rather than the Git checkout. The nonce prevents collisions across restarts and across multiple control-plane instances.
func ProjectSlug ¶
ProjectSlug is Claude Code's per-cwd session directory name under ~/.claude/projects. Every non-alphanumeric character collapses to '-' (verified empirically against the running CLI). This mirrors an internal layout, not a public API — which is why memory sharing is opt-in per target.
func RuntimeDir ¶
RuntimeDir is where every attempt's staged files live inside its worktree.
func TaskMCPRel ¶
TaskMCPRel is private to one background attempt.
Types ¶
type Event ¶
Event is one normalised timeline entry, whatever agent produced it.
func NormalizeClaude ¶
NormalizeClaude maps one `claude --output-format stream-json` record.
func NormalizeGeneric ¶
NormalizeGeneric preserves the stable Lectern event types when a CLI emits them, and gives ordinary JSONL responses a useful text timeline.
func ParseStreamLines ¶
ParseStreamLines turns whatever an agent wrote into events, returning the trailing partial line so the caller can resume mid-record next poll.
func ParseTaskStreamLines ¶
ParseTaskStreamLines applies a configured task output mode. Custom CLIs do not have an adapter-specific parser: plain output is one text event per line, while JSONL accepts the common Lectern event envelope and maps other useful message-shaped records to text.
type LaunchSpec ¶
type LaunchSpec struct {
Agent string
Worktree string
TmuxSession string
PermissionMode string
Model string
ResumeSession string
Sandbox bool
Env map[string]string
SettingsPath string
MCPConfig string
StrictMCP bool
// Definition is set for a configured custom agent. Leaving it nil preserves
// the existing built-in adapter behavior and its provider-specific flags.
Definition *TaskDefinition
// ExtraArgs are provider-specific flags, already validated by the adapter.
ExtraArgs []string
}
LaunchSpec is one attempt's launch parameters.
type Permissions ¶
type Permissions struct {
Allow []string `json:"allow,omitempty"`
Deny []string `json:"deny,omitempty"`
Ask []string `json:"ask,omitempty"`
DefaultMode string `json:"defaultMode,omitempty"`
AdditionalDirectories []string `json:"additionalDirectories,omitempty"`
}
Permissions is the settings.json permissions block.
func MergePermissions ¶
func MergePermissions(base, override Permissions) Permissions
MergePermissions layers explicit project rules on top of a profile: lists are unioned, scalars overridden. The explicit rules win where they conflict, so a profile can never quietly re-grant something an operator denied.
func ParityPermissions ¶
func ParityPermissions(mcpServers, extraDirs []string) Permissions
ParityPermissions are the rules that put a dispatched agent on par with a terminal session.
MCP servers are enumerated rather than wildcarded because there is no wildcard: `mcp__*` is accepted into settings.json and still denies every call (verified against the CLI). Each server needs its own `mcp__<name>` rule.
func ParsePermissions ¶
func ParsePermissions(raw string) (Permissions, error)
ParsePermissions decodes a project's permissions_json, rejecting unknown keys.
type SettingsInput ¶
type SettingsInput struct {
BaseURL string
Token string
Gated bool
Permissions Permissions
Matcher string
Profile string
MCPServers []string
MemoryDir string
// ExpireSeconds sizes the hook's own timeout.
ExpireSeconds int
}
SettingsInput is everything build-settings needs to know about one attempt.
type TaskDefinition ¶
type TaskDefinition struct {
Name string `json:"name"`
Command string `json:"command"`
Args []string `json:"args,omitempty"`
ModelFlag string `json:"model_flag,omitempty"`
PromptArg bool `json:"prompt_arg,omitempty"`
PromptTemplate string `json:"prompt_template,omitempty"`
OutputMode string `json:"output_mode,omitempty"`
// PermissionArgs explicitly maps Lectern modes to this CLI's flags.
// acceptEdits may be omitted when the CLI's native default is acceptable;
// plan and bypassPermissions require an explicit mapping.
PermissionArgs map[string][]string `json:"permission_args,omitempty"`
ResumeArgs []string `json:"resume_args,omitempty"`
Env map[string]string `json:"env,omitempty"`
Builtin bool `json:"builtin,omitempty"`
}
TaskDefinition describes the non-interactive invocation for a configured agent. Built-in agents keep their dedicated adapters; custom definitions use this deliberately small contract so a CLI can be backed by any provider or local model through its environment.
type TaskLaunchConfig ¶
type TaskLaunchConfig struct {
Version int `json:"version"`
Agent string `json:"agent"`
Definition TaskDefinition `json:"definition"`
Env map[string]string `json:"env"`
}
TaskLaunchConfig is the immutable, private snapshot attached to a queued attempt. It keeps registry and project environment edits from changing work that was already accepted by the operator.