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 ACPMCPServers(mcp map[string]any) (out []any, needHTTP, needSSE bool, err error)
- func BuildSettings(in SettingsInput) (map[string]any, error)
- func CodexMCPArgs(mcp map[string]any) ([]string, error)
- func CopilotMCPPayload(mcp map[string]any) ([]byte, error)
- func EnvPrefix(env map[string]string, sandbox bool) (string, error)
- func GeminiMCPServers(mcp map[string]any) (map[string]any, error)
- func GeminiWorkspaceMCPCommand(workdir string, sessionID int64, owned bool, servers map[string]any) string
- 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 OpenCodeMCPPayload(mcp map[string]any) ([]byte, error)
- func PrivateMCPPath(output string) (string, error)
- func PrivateMCPRel(id int64, nonce string) string
- func ProjectSlug(path string) string
- func QwenMCPPayload(mcp map[string]any) ([]byte, error)
- func RuntimeDir(worktree string) string
- func TaskMCPRel(attemptID int64, nonce string) string
- type ACPDefinition
- type Event
- type GeminiWorkspaceMCPResult
- type LaunchSpec
- type Launcher
- type MCPAdapter
- 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 ACPMCPServers ¶ added in v2.4.0
ACPMCPServers translates the declaration into ACP session/new mcpServers entries (agentclientprotocol.com, "Session Setup"): stdio servers carry no type and list env as name/value pairs; http and sse servers carry type and name/value headers. needHTTP/needSSE tell the caller which optional transports the agent must advertise in mcpCapabilities.
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 CopilotMCPPayload ¶ added in v2.4.0
CopilotMCPPayload validates the declaration and writes the Claude-format document, which Copilot CLI's --additional-mcp-config reads directly.
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 GeminiMCPServers ¶ added in v2.4.0
GeminiMCPServers translates the project declaration into Gemini CLI's mcpServers entries: stdio keeps command/args/env; http and sse use url plus type, the form Gemini documents in place of the deprecated httpUrl.
func GeminiWorkspaceMCPCommand ¶ added in v2.4.0
func GeminiWorkspaceMCPCommand(workdir string, sessionID int64, owned bool, servers map[string]any) string
GeminiWorkspaceMCPCommand builds the target-side install (servers != nil) or remove (servers == nil) command for one session. owned is true when Lectern knows it created workdir (an interactive worktree); otherwise the helper accepts workdir only inside the target's scratch root.
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 OpenCodeMCPPayload ¶ added in v2.4.0
OpenCodeMCPPayload writes an OpenCode config containing only "mcp".
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 QwenMCPPayload ¶ added in v2.4.0
QwenMCPPayload writes a Qwen Code settings file containing only mcpServers. Qwen reads streamable HTTP from httpUrl and SSE from url.
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 ACPDefinition ¶ added in v2.4.0
type ACPDefinition struct {
Command string `json:"command"`
Args []string `json:"args,omitempty"`
Env map[string]string `json:"env,omitempty"`
}
ACPDefinition is a custom agent's ACP invocation: the command to spawn (an ACP agent speaks JSON-RPC over its own stdio, same as codex app-server), e.g. Command:"npx" Args:["-y","@zed-industries/claude-code-acp"].
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 GeminiWorkspaceMCPResult ¶ added in v2.4.0
type GeminiWorkspaceMCPResult struct {
// Skipped names why nothing was written: "not-owned" (not a Lectern
// workspace), "tracked" (the repository commits .gemini/settings.json).
Skipped string `json:"skipped,omitempty"`
Path string `json:"path,omitempty"`
Added []string `json:"added,omitempty"`
// Kept lists declared servers the file already defined differently; the
// workspace's own definition wins.
Kept []string `json:"kept,omitempty"`
Removed []string `json:"removed,omitempty"`
Error string `json:"error,omitempty"`
}
GeminiWorkspaceMCPResult is the helper's reply.
func ParseGeminiWorkspaceMCP ¶ added in v2.4.0
func ParseGeminiWorkspaceMCP(stdout string) (*GeminiWorkspaceMCPResult, error)
ParseGeminiWorkspaceMCP decodes the helper's reply.
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
// Isolation runs the agent inside a bwrap/docker sandbox — see
// internal/isolation. Ignored (never applied) when Sandbox is true: a
// cloned container is already the isolation boundary, and wrapping it
// again buys nothing.
Isolation isolation.Config
// IsolationOpts carries what Isolation needs beyond the fields above
// (the proxy socket for network=deny).
IsolationOpts isolation.WrapOpts
}
LaunchSpec is one attempt's launch parameters.
type MCPAdapter ¶ added in v2.4.0
type MCPAdapter struct {
// Payload translates the Claude-format declaration into the file the
// CLI reads.
Payload func(mcp map[string]any) ([]byte, error)
// EnvVar, when set, is the environment variable that names the file.
EnvVar string
// Args, when set, are launch arguments naming the file ({path} replaced).
Args []string
}
MCPAdapter says how a project's MCP declaration reaches an interactive agent other than Claude and Codex. Each writes a private runtime file (see MCPInstallCommand) that the CLI reads in addition to the user's own config, so strict_mcp cannot be expressed and is rejected.
func MCPAdapterFor ¶ added in v2.4.0
func MCPAdapterFor(agent string) (MCPAdapter, bool)
MCPAdapterFor returns the translation for agent, by Lectern agent name. Each was checked against the CLI itself (docs/context-parity.md):
- opencode: OPENCODE_CONFIG names an extra config file merged between the global and project configs; servers live under "mcp".
- qwen: QWEN_CODE_SYSTEM_DEFAULTS_PATH names the lowest-precedence settings file; mcpServers is shallow-merged with the user's own.
- copilot: --additional-mcp-config @file augments ~/.copilot/mcp-config.json for the session and reads the Claude document as is.
Gemini CLI has no equivalent: its system settings files are ignored unless their directory is owned by root, so a per-session file is not possible.
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"`
// ACP, when set, means this agent's non-interactive invocation is an
// Agent Client Protocol (agentclientprotocol.com) process rather than a
// plain-text/JSONL CLI: internal/drivers.KindACP drives it instead of
// the generic task path, and PromptTemplate/OutputMode/PermissionArgs
// above are ignored (the protocol carries the prompt and permission
// decisions itself). See internal/drivers/acp.go.
ACP *ACPDefinition `json:"acp,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.