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 ¶
- Variables
- func EnsureOllamaRunning(host string) error
- func IsAvailable(name string) bool
- func IsOllamaRunning(host string) bool
- func NameFor(cfg config.Config, kind Kind) string
- func ProviderNames() []string
- func Register(p Provider) error
- func ResetProviders()
- func ResolveModel(cfg config.Config, e Engine) string
- func Validate(cfg config.Config) error
- type ACP
- type Engine
- type Kind
- type Ollama
- type Provider
- type Request
- type Result
- type Session
- type Usage
Examples ¶
Constants ¶
This section is empty.
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 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 EnsureOllamaRunning ¶
EnsureOllamaRunning checks if Ollama is running at host. If not, it attempts to launch `ollama serve` in the background and waits up to 3 seconds for it to become responsive.
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 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.
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 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.
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
}
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
// 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 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.
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.