Documentation
¶
Overview ¶
Package engine abstracts text generation over interchangeable backends:
- Session providers (Claude, Codex, Gemini, Copilot, Cursor, Amp, Crush, Goose, Grok, Qwen, ...), each driven through its own CLI in headless mode using the user's already-authenticated session — no API token.
- Ollama, the local HTTP server, used offline or when no session CLI is available.
Callers depend only on the Engine interface, so the pipeline is identical regardless of which backend actually runs.
Index ¶
- Constants
- Variables
- func APIProviderNames() []string
- func EnsureOllamaRunning(host string) error
- func IsAvailable(name string) bool
- func IsOllamaRunning(host string) bool
- func NameFor(cfg config.Config, kind Kind) string
- func OllamaParallelism() int
- func ProviderNames() []string
- func Register(p Provider) error
- func ResetProviders()
- func ResolveModel(cfg config.Config, e Engine) string
- func SupportsSchema(e Engine) bool
- func Validate(cfg config.Config) error
- type ACP
- type API
- type Engine
- type Kind
- type Ollama
- type Provider
- type Request
- type Result
- type SchemaCapable
- type Session
- type Usage
Examples ¶
Constants ¶
const APIPrefix = "api:"
APIPrefix marks an engine name as the direct-API escape hatch: "api:anthropic", "api:openai". It is opt-in and never chosen by auto mode — draft's default drives an agent CLI's logged-in session and reads no key. This exists only for users who have no agent CLI installed and would rather supply an API key of their own.
Variables ¶
var ErrRefused = errors.New("the model declined to answer this prompt")
ErrRefused reports that the model declined to answer a prompt. It is a verdict on the text, not on the backend: the provider is up, logged in and answering, and it will answer the next prompt. Callers must not treat it as an outage. The pipeline keeps the engine and, for claim extraction, records the section as having no claims.
var ErrToolUse = errors.New("the agent ran a tool, which draft does not allow; its answer was discarded")
ErrToolUse reports that an agent ran a tool during a call. draft grants none, and declines every permission request, but an agent can still run a tool its own configuration auto-approves. Its answer is discarded rather than trusted: a tool that read the disk could have put anything in it.
var IsOnline = func() bool { conn, err := dialTimeout("tcp", "1.1.1.1:53", 300*time.Millisecond) if err == nil { _ = conn.Close() return true } conn2, err2 := dialTimeout("tcp", "8.8.8.8:53", 300*time.Millisecond) if err2 == nil { _ = conn2.Close() return true } return false }
IsOnline probes public DNS endpoints with a short timeout to check for network connectivity.
Functions ¶
func APIProviderNames ¶ added in v0.0.36
func APIProviderNames() []string
APIProviderNames lists the supported direct-API provider short names, sorted, for help and error messages.
func EnsureOllamaRunning ¶
EnsureOllamaRunning checks if Ollama is running at host. If not, it attempts to launch `ollama serve` in the background and waits up to ollamaStartWait for it to become responsive. A server it starts that never answers is stopped again, so a wrong host cannot leave an orphaned server behind every run.
func IsAvailable ¶
IsAvailable reports whether the provider binary for name (or ollama) is installed on PATH.
func IsOllamaRunning ¶
IsOllamaRunning reports whether a local Ollama server is responding at host.
func NameFor ¶
NameFor reports which configured engine serves a request kind, before any chain is built. Callers use it to tell whether two kinds resolve to the same backend, and to display the routing.
func OllamaParallelism ¶ added in v0.0.52
func OllamaParallelism() int
OllamaParallelism is how many generations draft keeps in flight against one Ollama server: OLLAMA_NUM_PARALLEL from draft's environment when it is a positive number, and one otherwise.
One is the default because draft cannot see the server's setting (a server started by launchd or another shell has its own environment), and sending more than the server runs is not harmless queueing. Ollama sends no response headers until it starts a request, so a request queued behind a long one sits out the header timeout: on an 8 GB machine with OLLAMA_NUM_PARALLEL=1, a second extraction worker failed with "timeout awaiting response headers" while the first spent 6 min 38 s on its section. Export OLLAMA_NUM_PARALLEL to draft as well as the server to run more.
func ProviderNames ¶
func ProviderNames() []string
ProviderNames returns every registered provider name in preference order.
Example ¶
package main
import (
"fmt"
"github.com/sebastienrousseau/draft/engine"
)
func main() {
fmt.Println(engine.ProviderNames()[0])
}
Output: claude
func Register ¶
Register adds a provider, or replaces the entry with the same name. A provider needs at least a name and a binary to be runnable; anything less would fail later, at the point of a generation call, with a far worse message.
func ResetProviders ¶
func ResetProviders()
ResetProviders restores the built-in table, discarding anything registered. It exists so a test that registers a provider can undo it.
func ResolveModel ¶
ResolveModel returns the model label the given engine will use, for display.
func SupportsSchema ¶ added in v0.0.51
SupportsSchema reports whether e constrains its output to Request.Schema.
Types ¶
type ACP ¶
type ACP struct {
// contains filtered or unexported fields
}
ACP drives an agent over the Agent Client Protocol: JSON-RPC 2.0 on the agent's stdio, one long-lived process for the life of the engine, and one fresh session per Generate call.
One process, many sessions, is the shape that matters. A session carries conversation state, and claim extraction needs the opposite: every section must be read on its own, or a fact from section 3 leaks into the claims for section 9 and the ledger stops being grounded in the section it names. So the process is reused and the session never is.
The protocol is also the first place a declined prompt is a first-class outcome rather than an exit status: session/prompt answers with a stopReason, and "refusal" maps straight onto ErrRefused.
What ACP does not buy is wall clock. Measured against claude-code-acp 0.16, a warm second session costs about what a cold `claude -p` costs, because the adapter starts an agent per session underneath. The win is a standard transport with typed outcomes, not a faster one.
func NewACP ¶
NewACP builds an ACP engine for a provider registered with ACP set. It returns false if the name is unknown or the provider is not an ACP agent.
func (*ACP) Close ¶
Close stops the agent process. The engine can be used again afterwards; the next Generate starts a fresh one.
type API ¶ added in v0.0.36
type API struct {
// contains filtered or unexported fields
}
API generates text through a hosted chat API using the user's own API key.
func NewAPIEngine ¶ added in v0.0.36
NewAPIEngine builds a direct-API engine from a name like "api:anthropic". It returns false for a name that is not an api: reference to a known provider. A missing API key is not an error here — the name is valid — but surfaces at call time, so an unavailable key degrades the chain to Ollama rather than failing configuration.
type Engine ¶
type Engine interface {
// Name is a short human label shown in the UI (e.g. "claude" or "ollama").
Name() string
// Generate runs one request, honouring ctx for cancellation and timeout.
Generate(ctx context.Context, req Request) (Result, error)
}
Engine is a text-generation backend.
func Chain ¶
Chain resolves the ordered list of engines to try for a run, honouring the configured mode. The pipeline uses the first that succeeds and sticks with it.
- "ollama": just the local backend.
- a provider name: that session provider, then Ollama.
- "auto" (default): every installed session provider in preference order, then Ollama.
It deliberately does not probe the network up front: a flaky connectivity check must never be what downgrades an online machine to the local model. Instead, if a session call fails (the provider is offline or not logged in), the pipeline advances to the next engine in the chain and stays there.
func ChainFor ¶
ChainFor resolves the chain for one request kind, honouring that kind's override and falling back to cfg.Engine when it is unset.
The workload is lopsided: extraction is one cheap, mechanical call per section, while writing is a single quality-critical call. Routing them separately lets a local model do the dozen extractions — free, offline, and no session quota — while the article itself is written by the best backend available.
type Kind ¶
type Kind int
Kind identifies the pipeline stage a request belongs to, letting a backend pick an appropriate model (Ollama uses a small model to extract and a larger one to write; a session provider uses one model throughout).
type Ollama ¶
type Ollama struct {
// contains filtered or unexported fields
}
Ollama generates text through a local Ollama server's /api/generate endpoint.
func (*Ollama) Generate ¶
Generate streams a single completion and reports whether the model stopped on a length limit (done_reason == "length"), which the pipeline uses to continue generation rather than fail on a mid-sentence cut.
func (*Ollama) SupportsSchema ¶ added in v0.0.51
SupportsSchema implements SchemaCapable. Whether Ollama can hold output to a JSON Schema depends on the model and the runtime serving it, not on the server version: some runtimes answer any format with 501 "structured output is unavailable". So the first call asks the server once, with a one-token request carrying a format, and every later call reuses the answer. Any failure reads as "no", which keeps the text prompt that worked before structured output was wired in.
type Provider ¶
type Provider struct {
// Name is the stable identifier used on the command line and in the UI.
Name string
// Bin is the executable looked up on PATH.
Bin string
// Args are fixed arguments placed before the model flag and prompt.
Args []string
// ModelFlag, when non-empty, is the flag used to pass a model (e.g.
// "--model"). Providers without it always use their session's default model.
ModelFlag string
// DefaultModel is applied when the user does not override the model and the
// provider supports ModelFlag.
DefaultModel string
// PromptViaStdin sends the prompt on stdin instead of as a positional
// argument. When false, StdinPlaceholder (if set) is still appended.
PromptViaStdin bool
// PromptFileFlag, when non-empty, writes the prompt to a private file
// inside the call's sandbox directory and passes its path with this flag
// (e.g. "--prompt-file"). It is the second-best delivery after stdin, and
// far better than argv: a positional prompt carries the verbatim source
// text into the process listing, where any local user can read it.
PromptFileFlag string
// StdinPlaceholder is appended as a positional argument when the prompt is
// delivered on stdin and the CLI needs a marker (e.g. "-").
StdinPlaceholder string
// Experimental marks a provider whose headless invocation is derived from
// its --help but whose article output has not been verified end to end. Such
// providers are skipped by auto-selection unless the user opts in with
// --experimental; they can always be forced with --engine <name>.
Experimental bool
// StreamJSON parses the Claude Code stream-json event format instead of raw
// text, forwarding token deltas as they arrive for a smooth live preview.
StreamJSON bool
// ACP drives the agent over the Agent Client Protocol instead of a
// one-shot headless invocation: one long-lived process, a fresh session
// per call, and a typed stop reason instead of an exit status. Bin and
// Args start the agent; the prompt fields are ignored.
ACP bool
// StreamJSONInput delivers the prompt as a single NDJSON user event on
// stdin (the "agy" turn protocol) and parses the NDJSON result event back.
// Like PromptViaStdin it keeps the prompt out of argv, but the provider's
// stream drives the turn rather than reading a raw prompt.
StreamJSONInput bool
// SchemaFlag, when non-empty, is the flag that holds the answer to a
// JSON Schema, which makes the provider SchemaCapable. With SchemaFile
// the flag takes the path of a file in the call's sandbox directory
// (Codex --output-schema); without it, the schema itself (Claude
// --json-schema).
SchemaFlag string
SchemaFile bool
// Credentials are the environment variables the provider may sign in
// with, in the pattern syntax of credentialPatterns. Every other token in
// the user's environment is withheld from it.
Credentials []string
}
Provider describes how to drive one token-free AI coding-agent CLI in headless mode. Every provider authenticates through its own already-logged-in session, so draft never handles an API key. A provider is turned into a runnable backend by NewSession.
func FirstAvailableProvider ¶
FirstAvailableProvider returns the first registered provider whose CLI is installed, in preference order. Experimental providers are considered only when includeExperimental is true.
func LookupProvider ¶
LookupProvider returns the provider spec for name and whether it exists.
It scans rather than consulting an index built at init: the registry is extensible, and an index would silently disagree with it the moment a caller registered a provider. Ten entries make the scan free.
type Request ¶
type Request struct {
Kind Kind
Prompt string
Temperature float64
// NumPredict caps the output tokens for this call (0 = the engine's default).
// The pipeline sizes it to the article's word budget so a sparse claim ledger
// cannot pad a local model toward its token ceiling. Session providers, which
// manage their own generation, ignore it.
NumPredict int
// Schema, if non-nil, constrains the model's output to a JSON Schema
// (passed as format to Ollama and compiled to a GBNF grammar via
// internal/gbnf).
Schema map[string]any
// OnChunk, if set, receives streamed text as it arrives for live preview.
OnChunk func(string)
}
Request is a single generation call.
type Result ¶
type Result struct {
Text string
// Truncated is true when the backend stopped because it hit a length limit
// rather than finishing, signalling the pipeline to continue generation.
Truncated bool
// Usage is what the call cost, when the backend reports it.
Usage Usage
}
Result is the outcome of a generation call.
type SchemaCapable ¶ added in v0.0.51
type SchemaCapable interface {
SupportsSchema() bool
}
SchemaCapable is implemented by an engine that holds its output to Request.Schema, rather than ignoring the field. The pipeline sends a schema, and the JSON form of a prompt, only to an engine that reports true.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session generates text by driving a token-free agent CLI (Claude, Codex, Gemini, Copilot, Cursor, Amp, Crush, Goose, Grok, Qwen, ...) in headless mode. Authentication comes entirely from the CLI's own logged-in session.
func NewSession ¶
NewSession builds a Session for a named provider, applying the configured model override (falling back to the provider's default). It returns false if the provider name is unknown.
func (*Session) Generate ¶
Generate runs the provider CLI once and returns its assistant text, streaming output to req.OnChunk as it arrives. The large grounded prompt is delivered on stdin when the provider supports it (avoiding ARG_MAX limits) and as a positional argument otherwise.
func (*Session) SupportsSchema ¶ added in v0.0.52
SupportsSchema implements SchemaCapable for a provider whose CLI can hold its answer to a JSON Schema (see Provider.SchemaFlag).
type Usage ¶
type Usage struct {
InputTokens int
OutputTokens int
// CostUSD is the provider's own charge for the call in US dollars, when it
// reports one. Local models leave it zero.
CostUSD float64
// Reported records whether the backend gave any usage at all, so a run
// that summed only silent calls can say "not reported" instead of "0".
Reported bool
}
Usage is what a generation call cost, as far as the backend reports it. A local model reports tokens and no price; a session provider may report both or neither. Zero means "not reported", never "free" — the pipeline sums what it is given and says so, rather than implying a total it cannot stand behind.