core

package
v1.14.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 8, 2026 License: MIT, MIT Imports: 22 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Smoo AI license smoo.ai/th

pkg.go.dev Go engine


The agent brain you can point at production — right in your Go process.

Most agent frameworks hand the model a pile of tools and hope. This one gives you the loop and the brakes: draw hard lines the model can never cross, then let it run.

github.com/SmooAI/smooth-operator-core/go/core is the agent engine itself, in-process — an observe→think→act loop over any OpenAI-compatible client, with typed tools, streaming, checkpointing, cost budgets, and a permission gate you control. Not a client to a remote server: the agent is your process.

It's the native Go port of the Rust reference engine — one of five siblings (Rust, TypeScript, Python, Go, C#/.NET) that share one wire spec and one eval suite. The same agent brain, the same guarantees, wherever your stack already lives. Every surface is covered by fast, offline tests on a deterministic MockLlmProvider, so the loop is verified — not vibe-coded.

Install

go get github.com/SmooAI/smooth-operator-core/go/core

The engine is the core package; idiomatic alias core.

Quickstart

A complete agent — no credentials needed — using the deterministic mock provider the engine's own tests run on:

A complete agent with one tool — the mock is scripted to call the tool, then answer:

package main

import (
	"context"
	"fmt"

	core "github.com/SmooAI/smooth-operator-core/go/core"
)

func main() {
	weather := core.FuncTool{
		ToolName: "get_weather",
		Desc:     "Get the current weather for a city",
		Params: map[string]any{
			"type":       "object",
			"properties": map[string]any{"city": map[string]any{"type": "string"}},
			"required":   []string{"city"},
		},
		Fn: func(ctx context.Context, args map[string]any) (string, error) {
			return fmt.Sprintf("Weather in %v: 72F, sunny", args["city"]), nil
		},
	}

	provider := core.NewMockLlmProvider().
		PushToolCall("call_1", "get_weather", `{"city":"Tokyo"}`).
		PushText("It's 72F and sunny in Tokyo.")

	agent := core.NewSmoothAgent(provider, core.AgentOptions{
		Instructions: "You are a helpful assistant",
		Tools:        []core.Tool{weather},
	})

	res, err := agent.Run(context.Background(), "what's the weather in Tokyo?", nil)
	if err != nil {
		panic(err)
	}
	fmt.Println(res.Text)
}

NewSmoothAgent(client, options) takes a ChatClient (the MockLlmProvider implements it — swap in any OpenAI-compatible client) and an AgentOptions struct. FuncTool wraps a function as a Tool. Run(ctx, message, history) — pass nil history for a fresh turn — returns (AgentRunResponse, error); res.Text is the final answer.

Features

The full parity surface — every engine in the polyglot set ships it:

  • Agentic tool-calling loop — observe→think→act, looping until the model answers.
  • Typed tools — register tools the model can call, with parallel dispatch.
  • Knowledge / RAG + vectors — ground the turn in retrieved documents.
  • Memory — long-term entries recalled into context each turn.
  • Compaction — a sliding-window token budget keeps the prompt under a ceiling.
  • Cost / budget — per-model pricing, token + USD accounting, early stop on budget.
  • Checkpointing — persist/resume a conversation via a checkpoint store.
  • Rerank — rerank retrieved hits before injection (lexical reranker built in).
  • Sub-agents / delegation — spawn child agents for sub-tasks.
  • Cast + clearance — roles with per-role tool-access policy.
  • Permissions + deny-policy — a tool-call gate (AutoMode: ask / accept-edits / deny-unmatched / bypass) with hard circuit-breakers (rm -rf /, credential paths, pipe-to-shell, dangerous domains), a persisted allow-list, and a consumer DenyPolicy — declarative TOML rules plus semantic predicates for what strings can't express.
  • Human-in-the-loop gate — require approval before designated tool calls run.
  • Conversation thread — carry a conversation across multiple Run calls.
  • LlmProvider seam + MockLlmProvider — inject any OpenAI-compatible client; the record/replay mock drives the offline tests.
  • Deferred tools + tool_search — hide rarely-used tool schemas behind a meta-tool the model calls to promote the ones it needs.
  • Typed workflow graph — a generic Workflow[S] node/edge engine alongside the agent loop.
  • Parallel tool calls — dispatch ≥2 tool calls concurrently (transcript order preserved).
  • Retry / backoff — retry transient model-call failures with exponential backoff.
  • Streaming — stream incremental text, tool calls, and tool results as the turn runs.

Permissions & deny-policy — lines the agent can't cross

This is what makes an agent safe to point at real infrastructure: you decide what it can never do, and no prompt or model mistake talks it out of that. Every tool call passes through a gate. AutoMode sets the posture — read-only calls allow, mutating calls ask, dangerous calls deny — and hard circuit-breakers (rm -rf /, credential paths, pipe-to-shell, dangerous domains) fire in every mode, AutoModeBypass included. Attach a DenyPolicy on top: declarative TOML rules for the lines you can name, semantic predicates for the ones you can't. A match is a hard deny no stored grant and no mode can waive.

// A DenyPredicate for what strings can't express — return (reason, true) to deny.
type denyDbWriter struct{}

func (denyDbWriter) Evaluate(name string, args map[string]any) (core.DenyReason, bool) {
	if name == "db_query" && strings.Contains(fmt.Sprint(args), "writer") {
		return core.NewDenyReason("DB writer endpoint is off-limits — reads go to the replica"), true
	}
	return core.DenyReason{}, false
}

// Declarative rules (TOML): never the prod AWS profile, never a prod host.
policy, err := core.DenyPolicyFromTOML(`
	schema_version = 1
	[bash]
	deny_patterns = ["aws * --profile prod"]
	[network]
	deny_hosts = ["*.prod.internal"]
`)
if err != nil {
	panic(err)
}
policy = policy.WithPredicate(denyDbWriter{})

mode := core.AutoModeAsk
agent := core.NewSmoothAgent(provider, core.AgentOptions{
	Instructions:   "You are a careful assistant",
	Tools:          []core.Tool{weather},
	PermissionMode: &mode, // read allow · mutate ask · dangerous deny
	DenyPolicy:     policy,
})

Streaming

RunStream is the streaming variant of Run: it yields incremental events — text deltas as the model produces them, each tool call before dispatch, each tool result after it finishes, and a terminal done event carrying the same response Run would have returned.

Part of Smoo AI

smooth-operator-core is built and open-sourced by Smoo AI — the AI-powered business platform with AI built into every product: CRM, customer support, campaigns, field service, observability, and developer tools.

  • 🚀 Smooth on the platform — smoo.ai/th
  • 🧰 More open source from Smoo AI — smoo.ai/open-source
  • 🧩 Smoo-hosted — smooth-operator runs the Smoo AI platform in production

License

MIT — see LICENSE.


Built by Smoo AI — AI built into every product.

Documentation

Overview

Package core is the native Go smooth-operator engine — an in-process agentic tool-calling loop over an OpenAI-compatible chat client, with in-memory knowledge grounding. The Go sibling of the Rust reference engine, the C# core, the Python core, and the TypeScript core. See docs/Architecture/Go Core.md.

Index

Constants

View Source
const END = "__end__"

END is the sentinel a conditional router returns to signal termination.

View Source
const MemoryTopK = 5

MemoryTopK is how many memories are auto-recalled per turn when the caller does not set one. Matches MEMORY_TOP_K in every sibling core.

View Source
const PromptCacheBoundary = "__PROMPT_CACHE_BOUNDARY__"

PromptCacheBoundary splits a system prompt into a cacheable static portion and a frequently-changing dynamic portion.

View Source
const RecallFreshnessNote = "Note: 'the memory says X exists' is not the same as 'X exists now'. " +
	"Before recommending or acting on any function path, file, flag, or external " +
	"pointer named below, verify it's current by reading the file or grepping the " +
	"codebase. Project and Reference memories are time-sensitive; User and Feedback " +
	"are durable."

RecallFreshnessNote is the verify-before-recommend note (rule D6), emitted only when at least one recalled entry is time-sensitive (see NeedsFreshnessCheck).

A memory naming a function, file, or flag is a claim about the PAST, not a fact about now — without this line the model happily recommends a symbol that was deleted three releases ago.

View Source
const RecallHeader = "[Recalled memories]"

RecallHeader opens every auto-recall block, in every core.

Variables

View Source
var AllPresets = []PresetInfo{
	{"smooai-gateway", "Smoo AI Gateway (recommended)", "Hosted LiteLLM gateway run by Smoo AI — billing, moderation, governance, 100+ models. One key, one URL, no config."},
	{"openrouter-low-cost", "OpenRouter Low Cost", "GLM-5.1 thinking (#1 SWE-Bench Pro), MiniMax-M2.7 coding (56% SWE-Pro, 10B params), DeepSeek-V3.2 default"},
	{"llmgateway-low-cost", "LLM Gateway Low Cost", "GLM-5 thinking, MiniMax-M2.7 coding, DeepSeek-V3.2 default — unified billing, 224 models"},
	{"openai", "OpenAI", "GPT-6 Luna on every slot — OpenAI ecosystem"},
	{"anthropic", "Anthropic", "Claude Opus thinking, Sonnet coding — highest quality"},
}

AllPresets lists every preset. The first entry is the recommended default — `th auth login` shows them in this order.

View Source
var DefaultPricing = map[string]ModelPricing{
	"claude-haiku-4-5":  {InputPerMTok: 1.0, OutputPerMTok: 5.0},
	"claude-sonnet-4-5": {InputPerMTok: 3.0, OutputPerMTok: 15.0},
}

DefaultPricing is approximate (USD / 1M tokens). Override via AgentOptions.Pricing.

Functions

func AppendGrant

func AppendGrant(path string, query GrantQuery) error

AppendGrant loads the grant at path, adds query, and atomically saves. Creates the file if absent. Idempotent for a query that's already stored.

func BuildModelInfoURL added in v1.8.7

func BuildModelInfoURL(apiURL string) string

BuildModelInfoURL derives the `/model/info` URL from a provider's OpenAI-compat api_url (e.g. https://llm.smoo.ai/v1). Stripping `/v1` is safe: `/model/info` lives at the gateway root in every LiteLLM deployment seen.

func FetchModelInfo added in v1.8.7

func FetchModelInfo(ctx context.Context, apiURL, apiKey string) (map[string]ResolvedModel, error)

FetchModelInfo asks a LiteLLM gateway for its alias → upstream map.

A 401 means the provider's API key is missing or rejected; either way the caller cannot see the mapping.

func HasInjection added in v1.7.15

func HasInjection(text string) bool

HasInjection reports whether text contains any injection pattern.

func HasSecrets added in v1.7.15

func HasSecrets(text string) bool

HasSecrets reports whether text contains any secret pattern.

func LoadProjectContext added in v1.7.12

func LoadProjectContext(workingDir string) (string, bool)

LoadProjectContext loads the combined project + user context, user-level prepended, with file references in any AGENTS.md / SMOOTH.md resolved inline.

The bool is false only when NEITHER layer found anything — so a workspace with a bare CLAUDE.md and no user-level file still loads context.

func ParseModelInfo added in v1.8.7

func ParseModelInfo(body string) (map[string]ResolvedModel, error)

ParseModelInfo parses a `/model/info` response body into an alias→entry map. Split out from the HTTP call so it is testable without a live gateway.

func ProjectGrantsPath

func ProjectGrantsPath(workspace string) string

ProjectGrantsPath is the project-scope grants file: <workspace>/.smooth/wonk-allow.toml.

func QuirkKeys added in v1.8.7

func QuirkKeys() []string

QuirkKeys lists the table's canonical keys, for diagnostics.

func QuirksDebugSnapshot added in v1.8.7

func QuirksDebugSnapshot(upstream string) map[string]ModelQuirks

QuirksDebugSnapshot returns every quirk entry matching an upstream name. Usually one wins; the full set is kept so tests can assert coverage.

func RedactMatch added in v1.7.15

func RedactMatch(s string) string

RedactMatch redacts a matched string, showing only the first 4 and last 2 characters. Short matches (≤ 8 runes) are fully starred. Runes, not bytes — parity with the Rust reference's char-based redaction.

func RelevanceScore added in v1.13.6

func RelevanceScore(query, content string) float64

RelevanceScore is the fraction of the QUERY's distinct tokens that appear in content.

Normalised to 0-1 deliberately: a raw overlap count is comparable neither between entries nor between languages, and it is rendered into the prompt. Punctuation is a token separator — the Rust reference used to split on whitespace alone, so a query ending "…my name?" never matched a memory containing "name" and the entry was silently not recalled.

func RenderRecallBlock added in v1.13.6

func RenderRecallBlock(entries []MemoryEntry) string

RenderRecallBlock renders recalled entries as the context block injected into a turn. Byte-identical to the Rust reference's render_recall_block. Empty string for no entries, so a caller injects nothing rather than a bare header telling the model it remembered nothing.

func SortedAliases added in v1.8.7

func SortedAliases(models map[string]ResolvedModel) []string

SortedAliases returns a parsed map's aliases in sorted order, so diagnostics print the same order every run (Rust returns a BTreeMap; Go maps are unordered).

func UserGrantsPath

func UserGrantsPath() string

UserGrantsPath is the user-scope grants file: ~/.smooth/wonk-allow.toml. Empty when there is no home dir (minimal CI / broken containers).

Types

type APIFormat added in v1.8.7

type APIFormat string

APIFormat is the wire dialect a provider speaks. The JSON encoding matches the Rust reference's serde output so `providers.json` round-trips between engines.

const (
	// APIFormatOpenAICompat is the OpenAI `/chat/completions` dialect.
	APIFormatOpenAICompat APIFormat = "OpenAiCompat"
	// APIFormatAnthropic is Anthropic's native `/messages` dialect.
	APIFormatAnthropic APIFormat = "Anthropic"
)

type Activity added in v1.8.7

type Activity string

Activity selects which model slot a call routes through. Six semantic slots: the legacy Thinking + Planning split collapsed into Reasoning, and the legacy "default" alias is served by Coding.

const (
	// ActivityCoding is the outer coding loop — the workhorse slot, which also
	// serves the legacy "default" call path.
	ActivityCoding Activity = "Coding"
	// ActivityReasoning is deep reasoning / planning / chain-of-thought.
	ActivityReasoning Activity = "Reasoning"
	// ActivityReviewing is code review, critique, adversarial checks.
	ActivityReviewing Activity = "Reviewing"
	// ActivityJudge is LLM-as-a-judge: yes/no verdicts, low latency, used by
	// Narc guardrails and bench scoring.
	ActivityJudge Activity = "Judge"
	// ActivitySummarize is context compression during long agent runs.
	ActivitySummarize Activity = "Summarize"
	// ActivityFast is small, latency-sensitive utility calls: session
	// auto-naming, short titles, one-liner summaries, autocomplete. Sub-second
	// first token, short output, no tool use — don't pay Sonnet-plus prices to
	// name a session.
	ActivityFast Activity = "Fast"
)

type AgentActivities added in v1.8.3

type AgentActivities interface {
	// ModelCall invokes the model with the given context window and the tool
	// specs currently visible to it. It propagates a fatal model-call error
	// (network, upstream rejection); a durable backend turns transient failures
	// into activity retries before they surface here.
	ModelCall(ctx context.Context, messages []ChatMessage, tools []ToolSpec) (ChatResponse, error)

	// ToolInvoke executes a single tool call and returns its result. Tool
	// *business* failures — unknown tool, bad arguments, a tool that returned an
	// error — are reported on ToolResult.IsError, NOT as a returned error, exactly
	// as the agent's own dispatch does; only a fatal dispatch error is an error.
	// That distinction matters for a durable backend: an error is retried as a
	// failed activity, while an IsError result is a completed activity whose
	// content goes back to the model.
	ToolInvoke(ctx context.Context, call ToolCall) (ToolResult, error)
}

AgentActivities is the side-effecting boundary of an agent turn: the model call and each tool invocation. These are exactly the steps a durable backend runs as Temporal activities (retried, memoized in workflow history); the in-process backend runs them inline.

Inputs and outputs are owned, serializable values (not views into agent state) so an implementation may marshal them across an activity boundary unchanged.

type AgentExecutor added in v1.8.3

type AgentExecutor interface {
	// Execute runs a single turn for message, with history as the prior
	// conversation. Behaviorally equivalent to SmoothAgent.Run for the in-process
	// backend. It propagates any fatal error from the underlying turn (model call
	// or — for durable backends — the workflow engine).
	Execute(ctx context.Context, agent *SmoothAgent, message string, history []ChatMessage) (AgentRunResponse, error)

	// ExecuteStreaming runs a single turn, delivering StreamEvents (text deltas,
	// tool call/result, the terminal StreamDone) on the returned Stream.
	// Behaviorally equivalent to SmoothAgent.RunStream for the in-process backend,
	// including its error contract: a mid-turn failure closes the event channel
	// without a StreamDone and is reported by Stream.Err.
	ExecuteStreaming(ctx context.Context, agent *SmoothAgent, message string, thread *SmoothAgentThread) (*Stream, error)
}

AgentExecutor is a backend that executes one SmoothAgent turn.

Implementations decide *how* the turn is driven (inline, or on a durable workflow engine); the agent passed in owns *what* the turn does. Both methods take the agent as an argument so an executor never owns it — it borrows it for the duration of the turn, exactly like calling Run directly.

type AgentOptions

type AgentOptions struct {
	// Extensions wires a SEP extension host into this agent — the Go sibling of
	// Rust's `Agent::with_extension_host`. Supply it with
	// `extension.NewAgentBridge(host)`. Its tools are merged into the agent's
	// tool set, and its hook lanes run at the same points Rust runs them.
	// nil (the default) leaves the loop exactly as it was before extensions.
	Extensions ExtensionHooks

	// NextUserImages attaches image(s) to the CURRENT turn's user message. A
	// host sets it when a chat turn carried image attachments; the agent emits
	// them as OpenAI `image_url` content parts on that one turn. Empty (the
	// default) leaves every text-only turn byte-identical. Mirrors Rust's
	// `AgentConfig::with_user_images`. Pearl th-25ce5c.
	NextUserImages []ImageContent

	Instructions  string
	Model         string
	MaxIterations int
	MaxTokens     int
	// ModelMaxOutput is the active model's hard output ceiling (its
	// max_output_tokens). When set, every request's MaxTokens is clamped to
	// min(MaxTokens, *ModelMaxOutput) so a budget/policy MaxTokens (which may be
	// tuned high) can never exceed what the model can physically emit — otherwise a
	// reasoning model burns its budget on reasoning and returns empty, or the
	// upstream 400s (e.g. groq-compound caps output at 8192). nil (the default)
	// leaves MaxTokens unclamped. Source it from the gateway's /model/info
	// (model_info.max_output_tokens). Mirror of the Rust engine's
	// LlmClient.with_model_ceiling (EPIC th-1cc9fa).
	ModelMaxOutput *int
	Temperature    float64
	Knowledge      Knowledge
	KnowledgeTopK  int
	// Reranker reorders retrieved hits before injection (nil = passthrough).
	Reranker Reranker
	// KnowledgeCandidateK is the pool size retrieved before reranking; when greater
	// than KnowledgeTopK, more docs are fetched, reranked, then trimmed to TopK.
	KnowledgeCandidateK int
	// Memory, if set, recalls relevant facts into context each turn.
	Memory Memory
	// MemoryTopK is how many memory entries to recall per turn (0 = default 4).
	MemoryTopK int
	Tools      []Tool
	// ParallelToolCalls, when true and an assistant turn returns >=2 tool calls,
	// dispatches them concurrently (goroutines + sync.WaitGroup) instead of
	// sequentially. Tool-result messages are still appended in the original
	// ToolCalls order, so the transcript stays deterministic regardless of
	// completion order. Default false preserves the sequential behaviour. Per-tool
	// semantics (clearance, human-gate approval, tool_search promotion, JSON
	// parsing, error handling) are unchanged — only the dispatch loop runs in parallel.
	ParallelToolCalls bool
	// DeferredTools are registered but with their schemas HIDDEN from the model.
	// When any are present, a built-in tool_search meta-tool is advertised in their
	// place; the model calls it to fuzzy-match and promote the ones it needs, which
	// then become visible + dispatchable on subsequent turns. Keeps the tool schema
	// payload small when there are many rarely-used tools. An unpromoted deferred
	// tool is NOT dispatchable.
	DeferredTools []Tool
	// MaxContextTokens is the approximate token budget for the context window.
	// Before each model call, older non-system messages are dropped (sliding
	// window) to stay under it. 0 uses the default (8000); negative disables.
	MaxContextTokens int
	// Budget, if set, stops the turn early once accumulated usage/cost hits it.
	Budget *CostBudget
	// Pricing overrides the per-model cost table (defaults to DefaultPricing).
	Pricing map[string]ModelPricing
	// CheckpointStore, with ConversationID, persists/resumes the conversation.
	CheckpointStore CheckpointStore
	// ConversationID keys the checkpoint store (required to use checkpointing).
	ConversationID string
	// Clearance, if set, gates which tools may be dispatched. A tool the clearance
	// forbids is not executed — a "tool not permitted" result is returned to the
	// model instead. Nil allows every tool (the prior behaviour).
	Clearance *Clearance
	// HumanGate, when set, is asked for approval before running any tool call for
	// which RequiresApproval returns true. A denied call is not executed; the model
	// is told it was denied and can adapt.
	HumanGate HumanGate
	// RequiresApproval reports which tool calls need human approval (e.g. writes /
	// destructive actions), given the tool name and parsed arguments. nil = none.
	// Only consulted when HumanGate is set. Example:
	//
	//	func(name string, _ map[string]any) bool { return name == "delete_record" }
	RequiresApproval func(name string, args map[string]any) bool
	// PermissionMode, when non-nil, enables the native permission engine (the Go
	// port of the Rust PermissionHook — see permission.go / permission_gate.go):
	// every tool call is classified by Decide and gated before it runs. A hard
	// circuit-breaker (rm -rf /, credential paths, pipe-to-shell, dangerous
	// domains, env dumps) is always denied; a mutating/network call Asks (routed
	// to HumanGate, or fails closed with no gate); read-only calls Allow. nil (the
	// default) disables the engine entirely — dispatch is byte-for-byte unchanged.
	// Setting DenyPolicy without PermissionMode enables the engine at
	// AutoModeAsk. The HumanGate seam doubles as the Ask approver (an
	// ApproveAlways response persists a grant to PermissionGrantsPath).
	PermissionMode *AutoMode
	// DenyPolicy is a consumer-supplied deny policy (declarative TOML rules +
	// predicates) evaluated FIRST on every gated call — a match is a
	// circuit-breaker no grant or mode can waive. nil = none. Enables the
	// permission engine even when PermissionMode is nil.
	DenyPolicy *DenyPolicy
	// PermissionGrants is the live allow-list consulted on an Ask before
	// prompting; a matching grant auto-approves silently. nil disables persistence.
	PermissionGrants *SharedGrants
	// PermissionGrantsPath is where an ApproveAlways answer persists a new grant
	// (the user-scope wonk-allow.toml). Empty degrades approve-always to approve-once.
	PermissionGrantsPath string
	// MaxRetries is the number of ADDITIONAL attempts after the first if the model
	// call returns a transient error (rate-limit, 5xx, dropped connection). 0 (the
	// default) preserves today's behaviour: a single attempt, error returned
	// immediately. Only the model call is retried — never tool execution.
	MaxRetries int
	// RetryBackoff is the base delay for exponential backoff between retries. The
	// wait before retry attempt n (1-indexed) is RetryBackoff * 2^(n-1). The zero
	// value means no real delay (retries fire immediately) — which is what tests use
	// so they don't sleep; production should set a small base such as 200ms.
	RetryBackoff time.Duration
	// Hooks are ToolHooks run in registration order around every dispatched tool
	// call: each PreCall runs before the tool (any error blocks it), each PostCall
	// runs after with a mutable *ToolResult it may redact. Nil (the default) → no
	// hooks, behaviour unchanged. Mirrors the Rust engine's ToolRegistry hook chain.
	Hooks []ToolHook
	// Metadata is forwarded verbatim as every model request's top-level
	// `metadata` object (LiteLLM spend-log attribution — e.g. an agent slug so
	// per-agent LLM spend is queryable at the gateway). A nil or empty map
	// sends nothing: the wire stays byte-identical when unset. Mirrors the
	// Rust engine's AgentConfig.with_metadata.
	Metadata map[string]any
}

AgentOptions configures a SmoothAgent turn. Mirrors the sibling cores' options.

type AgentRunResponse

type AgentRunResponse struct {
	Text       string
	Iterations int
	ToolCalls  int
	Usage      Usage
	CostUSD    float64
	// BudgetExceeded is true if the turn stopped because the cost/token budget was hit.
	BudgetExceeded bool
}

AgentRunResponse is the result of a turn.

type AutoMode

type AutoMode int

AutoMode is how aggressively the gate enforces. Mirrors smooth's `AutoMode` (a trimmed Claude Code `auto-mode` set). Selected via the SMOOTH_AUTO_MODE env var (see AutoModeFromEnv).

const (
	// AutoModeAsk is read-only allow, mutating ask, dangerous deny. Default.
	AutoModeAsk AutoMode = iota
	// AutoModeAcceptEdits is like AutoModeAsk but filesystem-edit tools (the
	// Write category) auto-approve instead of asking. Everything else still
	// follows the full engine, and the hard circuit-breakers still block.
	// Mirrors Claude Code's acceptEdits.
	AutoModeAcceptEdits
	// AutoModeDenyUnmatched is like AutoModeAsk but never asks — an unmatched
	// verdict is a deny (fail-closed). The headless / CI posture (Claude Code's
	// dontAsk).
	AutoModeDenyUnmatched
	// AutoModeBypass allows everything except the hard circuit-breakers
	// (rm -rf /, dangerous domains, credential paths, pipe-to-shell, fork bombs,
	// env dumps). Escape hatch equivalent to Claude Code's bypassPermissions,
	// which keeps its circuit-breakers.
	AutoModeBypass
)

func AutoModeFromEnvValue

func AutoModeFromEnvValue(v string) AutoMode

AutoModeFromEnvValue parses a SMOOTH_AUTO_MODE value. Unknown/empty → AutoModeAsk.

type BashDeny

type BashDeny struct {
	DenyPatterns []string `toml:"deny_patterns,omitempty"`
}

BashDeny is `[bash]` — deny bash command prefixes / globs.

type BashSection

type BashSection struct {
	AllowPatterns []string `toml:"allow_patterns,omitempty"`
}

BashSection holds command prefixes approved without asking. "cargo " matches `cargo test`, `cargo build`, … — the trailing space guards against `cargonaut`.

type Cast

type Cast struct {
	// contains filtered or unexported fields
}

Cast is the registered set of roles a lead can dispatch to. Mirrors the reference engines' Cast.

func NewCast

func NewCast() *Cast

NewCast returns an empty cast.

func (*Cast) Count

func (c *Cast) Count() int

Count is the number of registered roles.

func (*Cast) Get

func (c *Cast) Get(name string) (OperatorRole, bool)

Get returns the role by name and whether it was found.

func (*Cast) IsEmpty

func (c *Cast) IsEmpty() bool

IsEmpty reports whether no roles are registered.

func (*Cast) List

func (c *Cast) List() []OperatorRole

List returns all roles in registration order.

func (*Cast) ListVisible

func (c *Cast) ListVisible() []OperatorRole

ListVisible returns the non-hidden roles in registration order.

func (*Cast) Register

func (c *Cast) Register(role OperatorRole) *Cast

Register adds (or replaces) a role and returns the cast for chaining.

func (*Cast) Sidekicks

func (c *Cast) Sidekicks() []OperatorRole

Sidekicks returns the sidekick roles in registration order.

type ChatChunk

type ChatChunk struct {
	// ContentDelta is an incremental piece of assistant text ("" when this chunk
	// carries no text).
	ContentDelta string
	// ToolCallDeltas are incremental tool-call fragments in this chunk.
	ToolCallDeltas []ToolCallDelta
	// Usage, when non-nil, reports cumulative token usage (gateways send it last).
	Usage *Usage
	// CostUSD, when non-nil, is the gateway's authoritative cost for the whole
	// request, read from the response headers before the body was consumed. It
	// arrives on the FIRST chunk, not the last.
	CostUSD *float64
	// Err, when non-nil, reports that the stream FAILED mid-flight (torn body,
	// idle/overall timeout, malformed frame). It is the Go analogue of the
	// reference engine's `Result<StreamEvent>` channel item: a stream that ends
	// this way is truncated, not finished. The chunk carries no other payload and
	// is the last one; the agent aborts the turn rather than emitting StreamDone,
	// so a partial answer can never be checkpointed as a complete one.
	Err error
}

ChatChunk is one streamed chunk from a streaming chat completion — the standard OpenAI streaming chunk shape (the slice the agent reads). Content deltas concatenate into the assistant text; tool-call fragments are assembled by their Index (ID + Function.Name appear when a call first opens, Function.Arguments arrives in fragments). Usage is non-nil on (typically) the final chunk.

type ChatClient

type ChatClient interface {
	Chat(ctx context.Context, req ChatRequest) (ChatResponse, error)
}

ChatClient is the minimal OpenAI-compatible surface the agent needs. The GatewayClient implements it against a live endpoint; tests inject a fake.

type ChatMessage

type ChatMessage struct {
	Role       string
	Content    string
	ToolCalls  []ToolCall
	ToolCallID string // set on role=="tool" messages
	// Images are attachments on a USER message (multimodal turns), emitted as
	// OpenAI `image_url` content parts. Empty for the text-only common case,
	// which keeps the wire byte-identical to before this field existed.
	Images []ImageContent
}

ChatMessage is one message in the OpenAI-shaped conversation.

func DriveTurn added in v1.8.3

func DriveTurn(ctx context.Context, activities AgentActivities, messages []ChatMessage, tools []ToolSpec, policy TurnPolicy) ([]ChatMessage, error)

DriveTurn drives one agent turn deterministically over the supplied activity surface, returning the conversation with this turn's assistant and tool messages appended.

messages must already be seeded with the system prompt, any prior turns, and the current user message — exactly the state SmoothAgent.run holds when it enters its loop. The input slice is never mutated in place.

This function performs NO I/O, wall-clock reads, or randomness of its own — all of that is delegated to activities — so it is replay-safe: a durable workflow can run this very function, and the in-process path runs it too. One loop, two backends, which is what keeps the durable path from diverging from the inline one.

It reproduces the core decision flow of SmoothAgent.run (snapshot context → model call → append assistant message → stop-or-run-tools → append tool results → loop to MaxIterations). It deliberately omits the inline-runtime concerns a durable backend models differently: event emission (a UI concern — durable backends surface progress from workflow history), checkpointing (Temporal's event history *is* the checkpoint), and the compaction / budget / parallel-dispatch / deferred-tool layers, which fold onto this loop without changing its shape.

type ChatRequest

type ChatRequest struct {
	Model       string
	Messages    []ChatMessage
	Tools       []ToolSpec
	Temperature float64
	MaxTokens   int
	// Metadata is an optional opaque object forwarded as the top-level
	// `metadata` field of the OpenAI-compatible request body (LiteLLM records
	// it on spend logs, giving per-caller cost attribution at the gateway).
	// nil means the field is omitted from the wire entirely; the agent
	// normalizes an empty map to nil so unset stays byte-identical. Mirrors
	// the Rust engine's ChatRequest.metadata (with_metadata).
	Metadata map[string]any
	// ResponseFormat constrains the reply to a JSON Schema — structured output
	// (see structured.go). nil omits the field from the wire entirely, so an
	// unset format leaves the request byte-identical. Mirrors the Rust engine's
	// chat_with_format(format).
	ResponseFormat *ResponseFormat
}

ChatRequest is a single model call.

type ChatResponse

type ChatResponse struct {
	Content   string
	ToolCalls []ToolCall
	Usage     Usage
	// GatewayCostUSD is the gateway's AUTHORITATIVE cost for this request, read
	// from its response header. nil means "unmeasured" — the caller falls back to
	// local ModelPricing. It is deliberately not 0: a real zero and an absent
	// header must stay distinct, or a gateway that reports no cost silently pins
	// spend at zero.
	GatewayCostUSD *float64
}

ChatResponse is the assistant's reply (content and/or tool calls).

func TextResponse

func TextResponse(content string) ChatResponse

TextResponse builds a plain-text ChatResponse (no tool calls). Handy for scripting the mock and for assertions.

func ToolCallResponse

func ToolCallResponse(id, name, arguments string) ChatResponse

ToolCallResponse builds a ChatResponse that requests a single tool call. arguments is the raw JSON-string the model emits for the call's arguments.

func WithUsage

func WithUsage(resp ChatResponse, promptTokens, completionTokens int) ChatResponse

WithUsage returns a copy of resp with the given token usage attached. Handy when scripting the mock so the streaming final chunk / non-streaming Usage is non-zero.

func (ChatResponse) DeserializeJSON added in v1.7.14

func (r ChatResponse) DeserializeJSON(target any) error

DeserializeJSON parses the response Content into target, which must be a non-nil pointer. Convenience over StructuredJSON for the common case of decoding straight into a typed struct.

func (ChatResponse) StructuredJSON added in v1.7.14

func (r ChatResponse) StructuredJSON() (any, error)

StructuredJSON parses the response Content as a JSON value. For a structured- output response this is the schema-conforming object the model produced.

Returns an error if Content is empty or is not valid JSON — the error carries a truncated snippet of the offending content so a model that ignored the schema can be diagnosed. It never silently returns an empty/nil value.

type Checkpoint

type Checkpoint struct {
	ConversationID string
	Messages       []ChatMessage
}

Checkpoint is a saved conversation: its id and the non-system messages so far.

type CheckpointStore

type CheckpointStore interface {
	Save(cp Checkpoint)
	Load(conversationID string) (Checkpoint, bool)
}

CheckpointStore persists and restores conversations by id.

type Clearance

type Clearance struct {
	// contains filtered or unexported fields
}

Clearance is a tool-access policy for a role. A deny always wins; a non-empty AllowTools is a whitelist; empty allow + empty deny means "all tools". DenyEverything blocks every tool regardless of the lists.

func AllowAllClearance

func AllowAllClearance() Clearance

AllowAllClearance permits every tool (the zero-value default).

func AllowClearance

func AllowClearance(tools ...string) Clearance

AllowClearance whitelists exactly the named tools.

func DenyAllClearance

func DenyAllClearance() Clearance

DenyAllClearance blocks every tool.

func DenyClearance

func DenyClearance(tools ...string) Clearance

DenyClearance blocks the named tools (everything else allowed).

func NewClearance

func NewClearance(allow, deny []string, denyEverything bool) Clearance

NewClearance builds a clearance from explicit allow/deny lists and the deny-everything flag.

func (Clearance) IsAllowed

func (c Clearance) IsAllowed(tool string) bool

IsAllowed reports whether tool is permitted under this clearance.

func (Clearance) IsDenyAll added in v1.13.0

func (c Clearance) IsDenyAll() bool

IsDenyAll reports whether this clearance denies every tool — either via the denyEverything flag or via a "*" entry in the deny list. Rust has no denyEverything flag: its Clearance::deny_all() is deny_tools = ["*"], so a role definition shared with or migrated from Rust spells deny-all that way.

type CostBudget

type CostBudget struct {
	MaxUSD    float64
	MaxTokens int
}

CostBudget is a ceiling for a turn. A zero field means "unset"; the first non-zero limit that is hit stops the turn.

type CostTracker

type CostTracker struct {
	Usage   Usage
	CostUSD float64
}

CostTracker accumulates usage + cost across a turn's model calls.

func (*CostTracker) Exceeds

func (t *CostTracker) Exceeds(b *CostBudget) bool

Exceeds reports whether the accumulated usage/cost has hit the budget.

func (*CostTracker) Record

func (t *CostTracker) Record(model string, u Usage, pricing map[string]ModelPricing)

Record adds a model call's usage (and its cost, if the model is priced).

func (*CostTracker) RecordWithGatewayCost added in v1.7.10

func (t *CostTracker) RecordWithGatewayCost(model string, u Usage, gatewayCostUSD *float64, pricing map[string]ModelPricing)

RecordWithGatewayCost records usage, preferring the gateway's authoritative per-request cost when it measured one. A nil cost means "unmeasured" and falls back to the local ModelPricing estimate — which is the whole reason the header parser returns nil rather than 0. Aliased models (smooth-*) price at $0 locally, so this is often the only real number available.

type DenyPolicy

type DenyPolicy struct {
	// contains filtered or unexported fields
}

DenyPolicy is a consumer-supplied deny policy: declarative rules + predicate checks. Attach to the gate via PermissionGate.DenyPolicy or the agent options. An empty policy is a no-op.

func DenyPolicyFromTOML

func DenyPolicyFromTOML(tomlText string) (*DenyPolicy, error)

DenyPolicyFromTOML builds the declarative half from a TOML string. Predicates are added separately via WithPredicate.

func NewDenyPolicy

func NewDenyPolicy() *DenyPolicy

NewDenyPolicy returns an empty policy — denies nothing (the additive no-op default).

func (*DenyPolicy) Evaluate

func (p *DenyPolicy) Evaluate(name string, args map[string]any) (string, bool)

Evaluate returns the deny reason for a call, or ("", false) to let it fall through to the rest of the permission engine. Declarative rules are checked first, then predicates; the first match wins.

func (*DenyPolicy) IsEmpty

func (p *DenyPolicy) IsEmpty() bool

IsEmpty reports whether there are no rules and no predicates.

func (*DenyPolicy) WithDeclarative

func (p *DenyPolicy) WithDeclarative(rules DenyRules) *DenyPolicy

WithDeclarative replaces the declarative rules. Chainable.

func (*DenyPolicy) WithPredicate

func (p *DenyPolicy) WithPredicate(predicate DenyPredicate) *DenyPolicy

WithPredicate adds a consumer predicate. Chainable.

type DenyPredicate

type DenyPredicate interface {
	// Evaluate returns (reason, true) to deny the call, or (_, false) to let it
	// fall through to the rest of the permission engine.
	Evaluate(name string, args map[string]any) (DenyReason, bool)
}

DenyPredicate is a consumer-supplied semantic deny check. Runs on every gated tool call; an ok=true return is a hard deny (circuit-breaker tier). Use it for checks the declarative rules can't express from strings alone — resolving an AWS call to its account, a DB URL to writer-vs-replica, etc.

type DenyReason

type DenyReason struct {
	Reason string
}

DenyReason is why a DenyPredicate blocks a call. A thin wrapper over string so the predicate contract is explicit and can grow structured fields later.

func NewDenyReason

func NewDenyReason(reason string) DenyReason

NewDenyReason builds a DenyReason.

type DenyRules

type DenyRules struct {
	SchemaVersion int         `toml:"schema_version"`
	Tools         ToolsDeny   `toml:"tools,omitempty"`
	Bash          BashDeny    `toml:"bash,omitempty"`
	Network       NetworkDeny `toml:"network,omitempty"`
	Paths         PathsDeny   `toml:"paths,omitempty"`
}

DenyRules is the declarative half of a DenyPolicy: four deny lists from TOML.

func NewDenyRules

func NewDenyRules() DenyRules

NewDenyRules returns empty rules pinned at the current schema version.

func ParseDenyRules

func ParseDenyRules(tomlText string) (DenyRules, error)

ParseDenyRules parses rules from a TOML string. Missing sections default empty.

func (DenyRules) IsEmpty

func (r DenyRules) IsEmpty() bool

IsEmpty reports whether no rules are set in any section.

func (DenyRules) ToTOMLString

func (r DenyRules) ToTOMLString() (string, error)

ToTOMLString serializes to TOML.

type Embedder

type Embedder interface {
	Embed(text string) []float64
}

Embedder turns text into a fixed-length vector.

type ExtensionHooks added in v1.7.6

type ExtensionHooks interface {
	// ExtensionTools are the host's eager tools, already namespaced
	// `<extension>.<tool>`. They are merged into the agent's tool set as
	// ORDINARY tools, so they are visible to the model, dispatched, and gated by
	// exactly the same permission machinery as native tools — no special casing.
	ExtensionTools() []Tool

	// ExtensionDeferredTools are the host's deferred tools: hidden from the model
	// until `tool_search` promotes them.
	ExtensionDeferredTools() []Tool

	// RunToolCallHook folds the `tool_call` hook chain over one pending call
	// BEFORE it executes. Returns whether the call is vetoed (with the reason),
	// and the possibly-rewritten arguments to run with.
	//
	// Rewrites are already scoped by the host's cross-tool guard: an extension
	// may only rewrite the arguments of a tool it owns, and may never redirect
	// the call to a different tool.
	RunToolCallHook(ctx context.Context, tool string, arguments string) (blocked bool, reason string, patched string)

	// DispatchEvent fans a turn event out to subscribed extensions. Fire and
	// forget: observe events are lossy by contract and never block the turn.
	DispatchEvent(event string, payload json.RawMessage)
}

ExtensionHooks is the seam through which a SEP extension host participates in the agent loop — the Go sibling of Rust's `Agent::with_extension_host`.

It is an INTERFACE rather than a concrete `*extension.ExtensionHost` because the dependency runs the other way: `go/core/extension` imports `go/core` (an `ExtensionTool` is a `core.Tool`), so `core` importing `extension` back would be a cycle. Every signature here is expressible in `core` + stdlib alone, and `extension.NewAgentBridge(host)` supplies the implementation.

Nil (the default) means the agent loop behaves exactly as it did before extensions existed — no dispatch, no hook calls, no allocation.

type FileRef added in v1.7.12

type FileRef struct {
	// Label is the display label from the markdown link text.
	Label string
	// Path is the relative file path (without fragment).
	Path string
	// Fragment optionally points at a heading within Path.
	Fragment *string
	// Description is the optional text after the ` — `.
	Description *string
}

FileRef is a parsed file reference from the `## File References` section. Fragment and Description are nil when absent (Rust's `Option<String>`).

func ParseFileReferences added in v1.7.12

func ParseFileReferences(content string) []FileRef

ParseFileReferences parses the `## File References` section out of AGENTS.md content. Expects markdown list items like:

  • [Label](path.md) — description
  • [Label](path.md#fragment) — description

type FuncTool

type FuncTool struct {
	ToolName string
	Desc     string
	Params   map[string]any
	Fn       func(ctx context.Context, args map[string]any) (string, error)
}

FuncTool wraps a function as a Tool (the AIFunctionFactory analogue).

func (FuncTool) Description

func (t FuncTool) Description() string

func (FuncTool) Execute

func (t FuncTool) Execute(ctx context.Context, args map[string]any) (string, error)

func (FuncTool) Name

func (t FuncTool) Name() string

func (FuncTool) Parameters

func (t FuncTool) Parameters() map[string]any

type GatewayClient

type GatewayClient struct {
	BaseURL    string // e.g. https://llm.smoo.ai/v1
	APIKey     string
	HTTPClient *http.Client
	// contains filtered or unexported fields
}

GatewayClient is an OpenAI-compatible ChatClient over HTTP — the Go analogue of the other cores' OpenAI SDK client. Points at any /chat/completions endpoint (e.g. the SmooAI gateway) with a Bearer API key.

(Phase 0 uses net/http directly, mirroring how the sibling cores' OpenAI SDKs do their own HTTP. Adopting @smooai/fetch's Go client is a tracked follow-up.)

func NewGatewayClient

func NewGatewayClient(baseURL, apiKey string) *GatewayClient

NewGatewayClient builds a client for the given base URL + key.

func (*GatewayClient) Chat

Chat implements ChatClient.

func (*GatewayClient) ChatStream

func (g *GatewayClient) ChatStream(ctx context.Context, req ChatRequest) (<-chan ChatChunk, error)

ChatStream implements StreamingChatClient: it opens an SSE streaming completion and translates each `data: {...}` line into a ChatChunk on the returned channel. Connect-time failures (request build / HTTP / non-2xx) come back as the error; the channel is closed when the SSE stream ends (`data: [DONE]` or EOF).

A stream that ends any way OTHER than cleanly — idle timeout, the overall requestTimeout expiring, a mid-stream connection reset, an over-long SSE line — delivers a final ChatChunk carrying Err before the channel closes. It NEVER closes as if the model had finished: a truncated stream is an error, because a half-sentence that looks like a clean completion gets appended to history and checkpointed as the assistant turn with nothing recording the loss.

Cancelling ctx tears down the request and releases the socket; the goroutine always exits, so an abandoning consumer leaks neither it nor the connection.

type GrantKind

type GrantKind int

GrantKind tags a GrantQuery.

const (
	// GrantNetwork is a network host (or *.suffix glob).
	GrantNetwork GrantKind = iota
	// GrantTool is an exact tool name (write / unknown tool).
	GrantTool
	// GrantBash is a bash command prefix, e.g. "npm ".
	GrantBash
)

type GrantQuery

type GrantQuery struct {
	Kind  GrantKind
	Value string
}

GrantQuery is the kind of resource a grant covers — one of the three grantable Ask shapes. (Deny circuit-breakers are never grantable.)

type HashEmbedder

type HashEmbedder struct {
	Dim int
}

HashEmbedder is a deterministic, offline feature-hashing embedder. It hashes each token into one of dim buckets (signed) and L2-normalizes. No learned semantics, but a real vector with cosine geometry — docs sharing tokens land near each other.

func NewHashEmbedder

func NewHashEmbedder(dim int) HashEmbedder

NewHashEmbedder returns a HashEmbedder with the given dimension (default 256).

func (HashEmbedder) Embed

func (e HashEmbedder) Embed(text string) []float64

Embed hashes tokens into a normalized vector.

type HumanApprovalRequest

type HumanApprovalRequest struct {
	ToolName  string
	Arguments map[string]any
	Prompt    string
}

HumanApprovalRequest is sent before the agent executes a sensitive/write tool. Mirrors the C# HumanApprovalRequest / the Rust engine's HumanRequest::Confirm.

type HumanApprovalResponse

type HumanApprovalResponse struct {
	Decision HumanDecision
	Reason   string
}

HumanApprovalResponse is the answer to a HumanApprovalRequest. Mirrors the C# HumanApprovalResponse.

func Approve

func Approve() HumanApprovalResponse

Approve builds an approval.

func ApproveAlways

func ApproveAlways() HumanApprovalResponse

ApproveAlways builds an approval that also persists a permission grant.

func Deny

func Deny(reason string) HumanApprovalResponse

Deny builds a denial carrying a reason the model will see.

func (HumanApprovalResponse) IsApproved

func (r HumanApprovalResponse) IsApproved() bool

IsApproved reports whether the decision lets the tool run (HumanApproved or HumanApprovedAlways).

func (HumanApprovalResponse) IsApprovedAlways

func (r HumanApprovalResponse) IsApprovedAlways() bool

IsApprovedAlways reports whether the human asked to persist a grant.

type HumanDecision

type HumanDecision int

HumanDecision is the human's verdict on a tool call that required approval.

const (
	// HumanApproved lets the tool run.
	HumanApproved HumanDecision = iota
	// HumanDenied blocks the tool; the reason is fed back to the model.
	HumanDenied
	// HumanApprovedAlways lets the tool run AND asks the permission gate to
	// persist a matching grant so identical future Asks auto-approve without
	// prompting (see permission_grants.go). Used only by the PermissionGate Ask
	// flow; the RequiresApproval path treats it exactly like HumanApproved.
	HumanApprovedAlways
)

type HumanGate

type HumanGate func(ctx context.Context, request HumanApprovalRequest) (HumanApprovalResponse, error)

HumanGate is the human-in-the-loop seam: the agent consults it before running any tool that AgentOptions.RequiresApproval flags. The implementation IS the pause point — wire it to a UI awaiting a real person, or decide programmatically. Mirrors the C# IHumanGate (here a func, the idiomatic Go seam).

type ImageContent added in v1.8.5

type ImageContent struct {
	URL    string
	Detail string
}

ImageContent is an image attachment on a user message (multimodal turns). URL is a `data:` URL (`data:image/png;base64,...`) or a remote `https` URL; the client emits it as an OpenAI `image_url` content part. Detail ("low"/"high"/"auto") is an optional OpenAI vision hint, omitted when empty. The Go sibling of Rust's `conversation::ImageContent`. Pearl th-25ce5c.

type InMemoryCheckpointStore

type InMemoryCheckpointStore struct {
	// contains filtered or unexported fields
}

InMemoryCheckpointStore is a process-local store backed by a map.

func NewInMemoryCheckpointStore

func NewInMemoryCheckpointStore() *InMemoryCheckpointStore

NewInMemoryCheckpointStore creates an empty in-memory store.

func (*InMemoryCheckpointStore) Load

func (s *InMemoryCheckpointStore) Load(conversationID string) (Checkpoint, bool)

Load returns the checkpoint for an id, and whether one was found.

func (*InMemoryCheckpointStore) Save

func (s *InMemoryCheckpointStore) Save(cp Checkpoint)

Save persists a copy of the checkpoint's messages.

type InMemoryKnowledge

type InMemoryKnowledge struct {
	// contains filtered or unexported fields
}

InMemoryKnowledge is a tiny lexical-overlap knowledge base — Phase-0 parity with the reference engines' in-memory lexical store (not a vector store).

func (*InMemoryKnowledge) Ingest

func (k *InMemoryKnowledge) Ingest(content, source string)

Ingest adds a document to the knowledge base.

func (*InMemoryKnowledge) Query

func (k *InMemoryKnowledge) Query(query string, topK int) []KnowledgeHit

Query returns up to topK documents, ranked by token overlap with the query. When nothing overlaps, the first topK documents are returned anyway so the agent still has context to ground (or honestly decline) against.

type InMemoryMemory

type InMemoryMemory struct {
	// contains filtered or unexported fields
}

InMemoryMemory is a process-local memory pool with lexical-overlap recall.

func (*InMemoryMemory) Recall

func (m *InMemoryMemory) Recall(query string, topK int) []MemoryEntry

Recall returns up to topK entries that share tokens with the query, best first.

func (*InMemoryMemory) Remember

func (m *InMemoryMemory) Remember(text string)

Remember adds a fact (blank entries are ignored).

func (*InMemoryMemory) RememberTyped added in v1.13.6

func (m *InMemoryMemory) RememberTyped(text string, memoryType MemoryType)

RememberTyped adds a fact of a given kind. Separate from Remember rather than a second parameter so the Memory interface — which host code implements — stays source-compatible.

type InProcessActivities added in v1.8.3

type InProcessActivities struct {
	// contains filtered or unexported fields
}

InProcessActivities is the default, zero-infra AgentActivities: it runs the model call through an LlmProvider and tool calls through the agent's tool set, inline in the calling goroutine.

func NewInProcessActivities added in v1.8.3

func NewInProcessActivities(llm LlmProvider, model string, tools []Tool) *InProcessActivities

NewInProcessActivities builds an in-process activity surface from a model provider, the model to call, and the tools available to it. An empty model falls back to the package default, matching the agent.

func (*InProcessActivities) ModelCall added in v1.8.3

func (a *InProcessActivities) ModelCall(ctx context.Context, messages []ChatMessage, tools []ToolSpec) (ChatResponse, error)

func (*InProcessActivities) ToolInvoke added in v1.8.3

func (a *InProcessActivities) ToolInvoke(ctx context.Context, call ToolCall) (ToolResult, error)

ToolInvoke resolves and runs one tool. Every failure mode is a completed invocation reported on ToolResult.IsError — the model is told what went wrong and can adapt — so this never returns a non-nil error, mirroring the agent's dispatchToolResult.

type InProcessExecutor added in v1.8.3

type InProcessExecutor struct{}

InProcessExecutor is the default, zero-infra executor: it drives the turn in the calling goroutine by delegating straight to SmoothAgent.Run / SmoothAgent.RunStream.

This is a verbatim pass-through — introducing it changes no behavior. It is the executor used unless a consumer explicitly opts into a durable backend.

func NewInProcessExecutor added in v1.8.3

func NewInProcessExecutor() *InProcessExecutor

NewInProcessExecutor constructs the in-process executor. (It is a zero-size struct; the constructor exists for symmetry with stateful executors.)

func (*InProcessExecutor) Execute added in v1.8.3

func (*InProcessExecutor) Execute(ctx context.Context, agent *SmoothAgent, message string, history []ChatMessage) (AgentRunResponse, error)

func (*InProcessExecutor) ExecuteStreaming added in v1.8.3

func (*InProcessExecutor) ExecuteStreaming(ctx context.Context, agent *SmoothAgent, message string, thread *SmoothAgentThread) (*Stream, error)

type Knowledge

type Knowledge interface {
	Query(query string, topK int) []KnowledgeHit
}

Knowledge is a retriever: returns the most relevant documents for a query. Both the lexical InMemoryKnowledge and the embedding-backed VectorKnowledge satisfy this, so the agent accepts either.

type KnowledgeHit

type KnowledgeHit struct {
	Content string
	Source  string
	Score   float64
}

KnowledgeHit is one retrieved document with its lexical-overlap score.

type LexicalReranker

type LexicalReranker struct{}

LexicalReranker reorders by query-term coverage normalized by document length: coverage / log2(2 + docTokenCount), so coverage is rewarded but long documents are penalized relative to concise ones with the same coverage. Stable for ties.

func (LexicalReranker) Rerank

func (LexicalReranker) Rerank(query string, hits []KnowledgeHit) []KnowledgeHit

Rerank reorders hits by the normalized-coverage score.

type LlmConfig added in v1.8.7

type LlmConfig struct {
	APIURL      string
	APIKey      string
	Model       string
	MaxTokens   int
	Temperature float64
	APIFormat   APIFormat
}

LlmConfig is a fully resolved route: the provider connection plus the model the activity picked. Feed APIURL/APIKey/Model to NewGatewayClient.

func (LlmConfig) String added in v1.8.7

func (c LlmConfig) String() string

String redacts the API key, same as ProviderConfig.String.

type LlmProvider

type LlmProvider = ChatClient

LlmProvider is the LLM-call seam the agent loop depends on. It is the existing ChatClient interface under a name that names the role — formalizing the seam so the agent loop is unit-testable deterministically, without a live model or network. The GatewayClient already implements it; tests inject a MockLlmProvider.

This keeps backward compatibility: NewSmoothAgent still takes a ChatClient, and any LlmProvider is a ChatClient (and vice versa) since they are the same shape.

type Memory

type Memory interface {
	Remember(text string)
	Recall(query string, topK int) []MemoryEntry
}

Memory is a pool of remembered facts, recalled by relevance to a query.

type MemoryEntry

type MemoryEntry struct {
	Text      string
	Type      MemoryType
	Relevance float64
}

MemoryEntry is one remembered fact. Type and Relevance are rendered into the recall block; a zero Type reads as LongTerm.

type MemoryType added in v1.13.6

type MemoryType string

MemoryType is what kind of fact a memory holds. The name is rendered into the recall block, so these spellings are part of the cross-language contract.

const (
	MemoryShortTerm MemoryType = "ShortTerm"
	MemoryLongTerm  MemoryType = "LongTerm"
	MemoryEntity    MemoryType = "Entity"
	MemoryUser      MemoryType = "User"
	MemoryFeedback  MemoryType = "Feedback"
	MemoryProject   MemoryType = "Project"
	MemoryReference MemoryType = "Reference"
)

The memory kinds, spelled as they appear in the rendered block.

func (MemoryType) NeedsFreshnessCheck added in v1.13.6

func (t MemoryType) NeedsFreshnessCheck() bool

NeedsFreshnessCheck reports whether this kind of memory can go stale. Project and Reference entries name things in a moving codebase or an external system; User and Feedback describe the person, which does not change when someone renames a file.

type MockLlmProvider

type MockLlmProvider struct {
	// contains filtered or unexported fields
}

MockLlmProvider is a deterministic LlmProvider for tests. Script the responses it should return (FIFO), drive your code, then assert on Calls. Build it up fluently with PushText / PushToolCall / PushError.

It replaces the ad-hoc fakeClient the tests rolled by hand, and mirrors the BEHAVIOR of the Rust reference's MockLlmClient (record + replay). It is not safe for concurrent use — a turn drives it serially, which is the intended use.

func NewMockLlmProvider

func NewMockLlmProvider() *MockLlmProvider

NewMockLlmProvider returns an empty mock. Script it with the Push* methods.

func (*MockLlmProvider) CallCount

func (m *MockLlmProvider) CallCount() int

CallCount returns the number of requests received.

func (*MockLlmProvider) Calls

func (m *MockLlmProvider) Calls() []ChatRequest

Calls returns every request the mock has received so far, in order.

func (*MockLlmProvider) Chat

Chat implements ChatClient / LlmProvider: it records the request, then replays the next scripted outcome. With an empty script it returns a benign empty text response so loops terminate cleanly.

func (*MockLlmProvider) ChatStream

func (m *MockLlmProvider) ChatStream(ctx context.Context, req ChatRequest) (<-chan ChatChunk, error)

ChatStream implements StreamingChatClient: it records the request, then replays the SAME next scripted outcome as Chat, but as chunked deltas. Text is split into a few content-delta chunks; each tool call is split into an opening chunk (ID + name + first half of arguments) and a second chunk with the rest of the arguments (exercising the agent's index-keyed accumulator); a final chunk carries usage. A scripted error is returned synchronously (connect-time), mirroring a failed open.

func (*MockLlmProvider) LastCall

func (m *MockLlmProvider) LastCall() (ChatRequest, bool)

LastCall returns the most recent request and true, or a zero request and false if none have been received.

func (*MockLlmProvider) PushError

func (m *MockLlmProvider) PushError(message string) *MockLlmProvider

PushError queues an error to be returned from the next Chat call.

func (*MockLlmProvider) PushResponse

func (m *MockLlmProvider) PushResponse(resp ChatResponse) *MockLlmProvider

PushResponse queues a raw ChatResponse for the next Chat call.

func (*MockLlmProvider) PushText

func (m *MockLlmProvider) PushText(content string) *MockLlmProvider

PushText queues a plain-text response for the next Chat call, reporting ScriptedUsage.

func (*MockLlmProvider) PushToolCall

func (m *MockLlmProvider) PushToolCall(id, name, arguments string) *MockLlmProvider

PushToolCall queues a single-tool-call response for the next Chat call, reporting ScriptedUsage.

type ModelPricing

type ModelPricing struct {
	InputPerMTok  float64
	OutputPerMTok float64
}

ModelPricing is USD per 1,000,000 tokens, input and output.

func (ModelPricing) Cost

func (p ModelPricing) Cost(u Usage) float64

Cost converts usage to USD at this pricing.

type ModelQuirks added in v1.8.7

type ModelQuirks struct {
	// AllowParallelTools, when non-nil and false, means the caller must force
	// `parallel_tool_calls` off even if the agent config requests it.
	AllowParallelTools *bool
	// StrictToolCallJSON asks the client to be extra careful about tool_call
	// echo shape — a few providers give obscure errors on borderline-malformed
	// echoes. Nothing reads this yet; it is the anchor for future tweaks.
	StrictToolCallJSON bool
}

ModelQuirks are per-model wire-format flags. Populate a field only when the quirk is worth the branch — every conditional is a place for drift.

When routing through a LiteLLM-style gateway the concrete upstream model only reveals itself in response headers (`x-litellm-model-name`), by which point the request is already sent. So prefer always-safe request shapes over per-model conditionals, and keep this table for the cases where the strict form does not work everywhere.

func QuirksForModel added in v1.8.7

func QuirksForModel(upstream string) ModelQuirks

QuirksForModel looks up quirks by concrete upstream name. Matching is case-insensitive and substring-based, so minor version drift (`qwen3-coder-plus-2025-04`) still hits the `qwen3-coder` entry. Returns the zero value when nothing matches, so defaults stay safe.

type ModelRouting added in v1.8.7

type ModelRouting struct {
	Coding ModelSlot `json:"coding"`
	// Reasoning is the merged deep-reasoning slot. Optional on disk: older
	// files carry `thinking` instead, and SlotFor falls back to Default when
	// it is absent entirely.
	Reasoning *ModelSlot `json:"reasoning,omitempty"`
	Reviewing ModelSlot  `json:"reviewing"`
	Judge     ModelSlot  `json:"judge"`
	Summarize ModelSlot  `json:"summarize"`
	Default   ModelSlot  `json:"default"`
	// Fast is optional on disk: pre-fast providers.json files deserialize with
	// Fast nil and the router falls back to Default.
	Fast *ModelSlot `json:"fast,omitempty"`
	// Planning is a legacy field held for wire compatibility. Deserialized but
	// ignored at lookup time — Reasoning absorbed the planning slot.
	Planning *ModelSlot `json:"planning,omitempty"`
}

ModelRouting is the per-activity routing table.

Six semantic slots plus a Default slot kept for wire compatibility: no Activity routes through Default directly (ActivityCoding serves the default path), but the field stays so pre-collapse configs load cleanly.

func DefaultModelRouting added in v1.8.7

func DefaultModelRouting() ModelRouting

DefaultModelRouting is the neutral, provider-agnostic routing every slot starts on: the well-known `openrouter` provider id with a placeholder `auto` model, so the library ships no opinion about a specific hosted gateway. Consumers opt into the Smoo AI gateway via PresetSmooaiGateway explicitly.

func (*ModelRouting) SlotFor added in v1.8.7

func (r *ModelRouting) SlotFor(activity Activity) *ModelSlot

SlotFor returns the slot for an activity. Reasoning and Fast fall back to Default when absent so partial configs stay functional.

func (*ModelRouting) UnmarshalJSON added in v1.8.7

func (r *ModelRouting) UnmarshalJSON(data []byte) error

UnmarshalJSON migrates a legacy `thinking` slot onto Reasoning. Rust does this with `#[serde(alias = "thinking")]`; an explicit shadow struct is the Go equivalent. An explicit `reasoning` always wins over `thinking`.

type ModelSlot added in v1.8.7

type ModelSlot struct {
	Provider string     `json:"provider"`
	Model    string     `json:"model"`
	Fallback *ModelSlot `json:"fallback,omitempty"`
}

ModelSlot binds a provider ID and model name, with an optional fallback used when the provider is not registered.

func NewModelSlot added in v1.8.7

func NewModelSlot(provider, model string) ModelSlot

NewModelSlot builds a slot with no fallback.

func (ModelSlot) WithFallback added in v1.8.7

func (s ModelSlot) WithFallback(fallback ModelSlot) ModelSlot

WithFallback returns a copy of the slot with fallback attached.

type NarcAlert added in v1.7.15

type NarcAlert struct {
	// Severity is how severe the finding is.
	Severity Severity
	// Category is the coarse bucket: "injection", "secret", "secret_leak", "injection_output".
	Category string
	// PatternName is the named pattern that matched.
	PatternName string
	// Redacted is a redacted view of the matched text (never the raw secret).
	Redacted string
	// ToolName is the tool whose args/result triggered the finding.
	ToolName string
}

NarcAlert is a single surveillance finding. Lean by design — the log line supplies the timestamp, so no uuid/timestamp fields are carried.

type NarcFinding added in v1.7.15

type NarcFinding struct {
	// PatternName is the named pattern that matched.
	PatternName string
	// Severity is the finding's severity.
	Severity Severity
	// Redacted is a redacted view of the matched text (safe to log).
	Redacted string
}

NarcFinding is a pattern match: which pattern, its severity, and a redacted view.

func ScanInjection added in v1.7.15

func ScanInjection(text string) []NarcFinding

ScanInjection scans text for prompt-injection patterns. Matched text is redacted.

func ScanSecrets added in v1.7.15

func ScanSecrets(text string) []NarcFinding

ScanSecrets scans text for hardcoded secrets. Every match is redacted.

type NarcHook added in v1.7.15

type NarcHook struct {
	// contains filtered or unexported fields
}

NarcHook is a ToolHook that scans tool-call arguments and results for secrets and prompt injection. Install it on AgentOptions.Hooks alongside the permission gate, AFTER it, so the permission gate decides allow/ask/deny first and Narc scans the calls that clear it.

  • PreCall blocks on a SeverityBlock injection pattern in the arguments (active exfiltration); every other finding (lower-severity injection, any secret) is recorded as a NarcAlert and logged, not blocked.
  • PostCall detects secrets/injection in the result, records + logs them, and REDACTS leaked secrets out of the content in place so the model never sees the raw credential.

Safe for concurrent use: with ParallelToolCalls the engine may run PreCall/PostCall from several goroutines at once.

func NewNarcHook added in v1.7.15

func NewNarcHook() *NarcHook

NewNarcHook builds a fresh hook with an empty alert log.

func (*NarcHook) Alerts added in v1.7.15

func (h *NarcHook) Alerts() []NarcAlert

Alerts snapshots every recorded alert.

func (*NarcHook) AlertsAbove added in v1.7.15

func (h *NarcHook) AlertsAbove(minSeverity Severity) []NarcAlert

AlertsAbove returns the recorded alerts at or above minSeverity.

func (*NarcHook) PostCall added in v1.7.15

func (h *NarcHook) PostCall(_ context.Context, call ToolCall, result *ToolResult) error

PostCall scans the tool result. A secret in a result is a leak: it raises a Block alert AND is redacted out of result.Content in place. Injection in the result is surveillance only — recorded, never rewritten.

func (*NarcHook) PreCall added in v1.7.15

func (h *NarcHook) PreCall(_ context.Context, call ToolCall) error

PreCall scans the tool arguments. A Block-severity injection pattern (active exfiltration) returns an error and the tool never runs; everything else is recorded and allowed.

type NetworkDeny

type NetworkDeny struct {
	DenyHosts []string `toml:"deny_hosts,omitempty"`
}

NetworkDeny is `[network]` — deny host suffixes / globs.

type NetworkSection

type NetworkSection struct {
	AllowHosts []string `toml:"allow_hosts,omitempty"`
}

NetworkSection holds hosts (or *.suffix globs) approved without asking.

type NodeFn

type NodeFn[S any] func(ctx context.Context, state S) (S, error)

NodeFn transforms state into a new state. It receives a context so nodes can do async/IO work, and may return an error to abort the run.

func SubWorkflowNode added in v1.8.0

func SubWorkflowNode[P, C any](child *Workflow[C], mapIn func(P) C, mapOut func(P, C) P) NodeFn[P]

SubWorkflowNode wraps a child Workflow as a single node of a parent workflow.

The child runs to completion — every node, its conditional edges and the END sentinel included — inside one parent step. That is the contrast with a conversational driver that advances the top-level graph one node per user turn: a sub-workflow node executes its whole sub-graph within that one turn, and the top level stays turn-gated.

The result is an ordinary NodeFn: AddEdge and AddConditionalEdge treat it exactly like a plain node, as an edge source and as an edge target alike. Plain nodes and sub-workflows are therefore interchangeable vertices of one composite graph, and they nest arbitrarily — a sub-workflow may itself contain sub-workflows.

mapIn projects parent state into the child's state type; mapOut folds the child's final state back into the parent's. An error from any child node propagates out of the parent's Run.

type NoopReranker

type NoopReranker struct{}

NoopReranker returns the hits unchanged — the zero-cost default.

func (NoopReranker) Rerank

func (NoopReranker) Rerank(_ string, hits []KnowledgeHit) []KnowledgeHit

Rerank returns hits unchanged.

type OperatorRole

type OperatorRole struct {
	Name          string
	Kind          RoleKind
	Instructions  string
	Permissions   Clearance
	MaxIterations int
	// Hidden roles are omitted from ListVisible (still dispatchable by name).
	Hidden bool
}

OperatorRole is a named role in the cast — its kind, instructions, tool clearance, and iteration budget. Mirrors the reference engines' OperatorRole.

func NewOperatorRole

func NewOperatorRole(name string, kind RoleKind, instructions string) OperatorRole

NewOperatorRole builds a role with the reference-engine defaults applied (allow-all clearance, 8 iterations).

type PathsDeny

type PathsDeny struct {
	Deny []string `toml:"deny,omitempty"`
}

PathsDeny is `[paths]` — deny file paths / globs (Write + Read tools).

type PermissionGate

type PermissionGate struct {
	// Mode is how aggressively Decide enforces.
	Mode AutoMode
	// Grants is the live merged allow-list consulted before prompting on an Ask.
	// nil disables persistence — every Ask prompts (approve-once).
	Grants *SharedGrants
	// PersistPath is where an ApprovedAlways grant is written (the user-scope
	// file). Empty means approve-always degrades to approve-once.
	PersistPath string
	// DenyPolicy is the consumer deny policy, evaluated first. nil = none.
	DenyPolicy *DenyPolicy
	// Approver routes an Ask verdict to a human. nil fails closed (Ask blocks).
	Approver HumanGate
}

PermissionGate enforces the permission engine on a single tool call.

func (*PermissionGate) Check

func (g *PermissionGate) Check(ctx context.Context, name string, args map[string]any) error

Check enforces the gate on one tool call. Returns nil to allow the call, or a non-nil error describing why it is blocked (the caller surfaces the message to the model as the tool result). name is the tool name; args are its parsed arguments.

type PermissionGrants

type PermissionGrants struct {
	SchemaVersion int            `toml:"schema_version"`
	Network       NetworkSection `toml:"network,omitempty"`
	Tools         ToolsSection   `toml:"tools,omitempty"`
	Bash          BashSection    `toml:"bash,omitempty"`
}

PermissionGrants is the in-memory snapshot of wonk-allow.toml.

func LoadLayeredGrants

func LoadLayeredGrants(userPath, projectPath string) (*PermissionGrants, error)

LoadLayeredGrants loads user + project files and merges them (project last so its schema_version wins; entries union either way). Either path empty is fine; a malformed file present is an error.

func LoadPermissionGrants

func LoadPermissionGrants(path string) (*PermissionGrants, error)

LoadPermissionGrants loads from path. A missing file yields an empty (v1) store — NOT an error. A malformed file surfaces the parse error.

func NewPermissionGrants

func NewPermissionGrants() *PermissionGrants

NewPermissionGrants returns grants pinned at the current schema version.

func ParsePermissionGrants

func ParsePermissionGrants(tomlText string) (*PermissionGrants, error)

ParsePermissionGrants parses grants from a TOML string. Missing sections default to empty.

func (*PermissionGrants) Add

func (g *PermissionGrants) Add(query GrantQuery)

Add adds a grant. Idempotent; keeps each section sorted+unique for stable output.

func (*PermissionGrants) Clone

func (g *PermissionGrants) Clone() *PermissionGrants

Clone returns a deep copy.

func (*PermissionGrants) Contains

func (g *PermissionGrants) Contains(query GrantQuery) bool

Contains reports whether query's exact entry is already stored.

func (*PermissionGrants) MatchesBash

func (g *PermissionGrants) MatchesBash(command string) bool

MatchesBash reports whether command starts with any [bash] allow prefix.

func (*PermissionGrants) MatchesHost

func (g *PermissionGrants) MatchesHost(host string) bool

MatchesHost reports whether host is covered by the [network] allow-list.

func (*PermissionGrants) MatchesTool

func (g *PermissionGrants) MatchesTool(toolName string) bool

MatchesTool reports whether toolName is in the [tools] allow-list (exact match).

func (*PermissionGrants) MergeWith

func (g *PermissionGrants) MergeWith(other *PermissionGrants)

MergeWith unions other into g.

func (*PermissionGrants) SaveToPath

func (g *PermissionGrants) SaveToPath(path string) error

SaveToPath atomically writes g to path (tempfile + rename), creating parent dirs.

func (*PermissionGrants) ToTOMLString

func (g *PermissionGrants) ToTOMLString() (string, error)

ToTOMLString serializes to TOML.

type Preset added in v1.8.7

type Preset string

Preset is a ready-made provider + routing configuration.

const (
	// PresetSmooaiGateway is the hosted Smoo AI gateway — the recommended default.
	PresetSmooaiGateway Preset = "SmoaiGateway"
	// PresetOpenRouterLowCost routes Chinese frontier models via OpenRouter — cheapest.
	PresetOpenRouterLowCost Preset = "OpenRouterLowCost"
	// PresetLlmGatewayLowCost routes Chinese frontier models via LLM Gateway.
	PresetLlmGatewayLowCost Preset = "LlmGatewayLowCost"
	// PresetOpenAI routes OpenAI models.
	PresetOpenAI Preset = "OpenAI"
	// PresetAnthropic routes Anthropic Claude models.
	PresetAnthropic Preset = "Anthropic"
)

func PresetFromName added in v1.8.7

func PresetFromName(name string) (Preset, bool)

PresetFromName parses a preset name or alias. Returns false for unknown names.

func (Preset) ProviderID added in v1.8.7

func (p Preset) ProviderID() string

ProviderID is the provider this preset requires.

type PresetInfo added in v1.8.7

type PresetInfo struct {
	Name        string
	Label       string
	Description string
}

PresetInfo is one row of AllPresets: CLI name, display label, description.

type PromptCache added in v1.8.1

type PromptCache struct {
	// contains filtered or unexported fields
}

PromptCache is a system prompt split at PromptCacheBoundary.

func NewPromptCache added in v1.8.1

func NewPromptCache(prompt string) *PromptCache

NewPromptCache splits a system prompt at the boundary marker. With no marker the entire prompt is treated as dynamic — nothing is claimed to be cacheable that the caller didn't mark.

func (*PromptCache) CachedTokens added in v1.8.1

func (p *PromptCache) CachedTokens() int

CachedTokens estimates the tokens the static portion saves on a cache hit.

func (*PromptCache) DynamicPortion added in v1.8.1

func (p *PromptCache) DynamicPortion() string

DynamicPortion is the frequently-changing half (below the marker).

func (*PromptCache) FullPrompt added in v1.8.1

func (p *PromptCache) FullPrompt() string

FullPrompt reassembles static + boundary + dynamic. With no static portion the dynamic half is returned alone, so a prompt that was never split round- trips unchanged rather than gaining a stray marker.

func (*PromptCache) StaticHash added in v1.8.1

func (p *PromptCache) StaticHash() string

StaticHash identifies the static portion for cache-key deduplication.

Process-local only: it is compared against other hashes from THIS engine, never sent on the wire, so it deliberately does not match the Rust reference's value (Rust uses DefaultHasher, which is not reproducible across languages — or even across Rust releases). The contract that is ported is the behavior: same static text hashes the same, different static text hashes differently, and UpdateDynamic never changes it.

func (*PromptCache) StaticPortion added in v1.8.1

func (p *PromptCache) StaticPortion() string

StaticPortion is the cacheable half (above the marker).

func (*PromptCache) UpdateDynamic added in v1.8.1

func (p *PromptCache) UpdateDynamic(dynamic string)

UpdateDynamic swaps the dynamic half, leaving the static half and its hash untouched — the whole point of the split.

type ProviderConfig added in v1.8.7

type ProviderConfig struct {
	ID           string    `json:"id"`
	APIURL       string    `json:"api_url"`
	APIKey       string    `json:"api_key"`
	APIFormat    APIFormat `json:"api_format"`
	DefaultModel string    `json:"default_model"`
}

ProviderConfig is the connection detail for a single LLM provider.

func AnthropicProvider added in v1.8.7

func AnthropicProvider(apiKey string) ProviderConfig

AnthropicProvider is the Anthropic native API.

func GoogleProvider added in v1.8.7

func GoogleProvider(apiKey string) ProviderConfig

GoogleProvider is the Google Gemini API (OpenAI-compatible surface).

func KimiCodeProvider added in v1.8.7

func KimiCodeProvider(apiKey string) ProviderConfig

KimiCodeProvider is Moonshot's coding-optimized API (Anthropic-compatible).

func KimiProvider added in v1.8.7

func KimiProvider(apiKey string) ProviderConfig

KimiProvider is Moonshot AI's general-purpose API (OpenAI-compatible).

func LlmGatewayProvider added in v1.8.7

func LlmGatewayProvider(apiKey string) ProviderConfig

LlmGatewayProvider is LLM Gateway — a unified API for 210+ models.

func OllamaProvider added in v1.8.7

func OllamaProvider() ProviderConfig

OllamaProvider is a local Ollama instance — no API key needed.

func OpenAIProvider added in v1.8.7

func OpenAIProvider(apiKey string) ProviderConfig

OpenAIProvider is the OpenAI direct API.

func OpenRouterProvider added in v1.8.7

func OpenRouterProvider(apiKey string) ProviderConfig

OpenRouterProvider is OpenRouter — an OpenAI-compatible proxy for many models.

func SmooaiGatewayProvider added in v1.8.7

func SmooaiGatewayProvider(apiKey string) ProviderConfig

SmooaiGatewayProvider is the hosted LiteLLM-backed gateway run by Smoo AI.

One API key, one URL, OpenAI-compatible. The gateway handles provider selection, billing, moderation and cost tracking server-side. It serves concrete model names (`gpt-6-luna`, `gpt-6-luna-fast`, `groq-gpt-oss-120b`, …); the old semantic `smooth-*` aliases were removed and are now rejected with HTTP 400 "Invalid model name", so moving a slot to a different model is a client/preset change, not a server-side one. The default model is `gpt-6-luna`.

SMOOAI_GATEWAY_URL overrides the base URL for self-hosted installs or dev.

func (ProviderConfig) String added in v1.8.7

func (p ProviderConfig) String() string

String redacts the API key so it never lands in logs or error chains. Everything else is printed verbatim. Mirrors the Rust reference's manual Debug impl.

type ProviderRegistry added in v1.8.7

type ProviderRegistry struct {

	// Routing is the per-activity table. Mutate it directly to re-point a slot.
	Routing ModelRouting
	// contains filtered or unexported fields
}

ProviderRegistry holds registered providers and the per-activity routing table.

func LoadRegistryFromFile added in v1.8.7

func LoadRegistryFromFile(path string) (*ProviderRegistry, error)

LoadRegistryFromFile reads a registry from a JSON file (e.g. ~/.smooth/providers.json).

func NewProviderRegistry added in v1.8.7

func NewProviderRegistry() *ProviderRegistry

NewProviderRegistry creates an empty registry with the neutral default routing.

func RegistryFromEnv added in v1.8.7

func RegistryFromEnv() (*ProviderRegistry, bool)

RegistryFromEnv builds a minimal registry from SMOOTH_API_KEY (required), SMOOTH_PROVIDER (defaults to "openrouter") and SMOOTH_MODEL (optional). Returns false when SMOOTH_API_KEY is unset.

func RegistryFromJSON added in v1.8.7

func RegistryFromJSON(data string) (*ProviderRegistry, error)

RegistryFromJSON deserializes a registry from the same JSON shape ProviderRegistry.SaveToFile writes — used when a parent process passes the routing config to a child via an env var instead of a file.

func RegistryFromPreset added in v1.8.7

func RegistryFromPreset(preset Preset, apiKey string) *ProviderRegistry

RegistryFromPreset creates a registry pre-configured with a preset: it registers the preset's provider and installs routing tuned for the preset's goals (cost, quality, latency).

func (*ProviderRegistry) ClientFor added in v1.8.7

func (r *ProviderRegistry) ClientFor(activity Activity) (*GatewayClient, LlmConfig, error)

ClientFor builds a gateway client for an activity's resolved route — the one line between "which model should this call use" and a client that speaks to it.

The client is OpenAI-compatible; an Anthropic-format provider (APIFormatAnthropic) is rejected rather than silently spoken to in the wrong dialect.

func (*ProviderRegistry) DefaultLlmConfig added in v1.8.7

func (r *ProviderRegistry) DefaultLlmConfig() (LlmConfig, error)

DefaultLlmConfig resolves the wire-compat `default` slot.

func (*ProviderRegistry) GetProvider added in v1.8.7

func (r *ProviderRegistry) GetProvider(id string) (ProviderConfig, bool)

GetProvider looks up a provider by ID.

func (*ProviderRegistry) ListProviders added in v1.8.7

func (r *ProviderRegistry) ListProviders() []string

ListProviders returns every registered provider ID, sorted.

func (*ProviderRegistry) LlmConfigFor added in v1.8.7

func (r *ProviderRegistry) LlmConfigFor(activity Activity) (LlmConfig, error)

LlmConfigFor resolves the route for an activity. It errors when the slot's provider — and every fallback — is unregistered, rather than silently substituting some other provider.

func (*ProviderRegistry) RegisterProvider added in v1.8.7

func (r *ProviderRegistry) RegisterProvider(config ProviderConfig)

RegisterProvider adds (or replaces) a provider configuration.

func (*ProviderRegistry) RemoveProvider added in v1.8.7

func (r *ProviderRegistry) RemoveProvider(id string)

RemoveProvider drops a provider by ID.

func (*ProviderRegistry) SaveToFile added in v1.8.7

func (r *ProviderRegistry) SaveToFile(path string) error

SaveToFile writes the registry as pretty-printed JSON, creating parent dirs.

func (*ProviderRegistry) SetDefaultProvider added in v1.8.7

func (r *ProviderRegistry) SetDefaultProvider(providerID string)

SetDefaultProvider points every routing slot at the given provider using its default model.

func (*ProviderRegistry) ToJSON added in v1.8.7

func (r *ProviderRegistry) ToJSON() (string, error)

ToJSON serializes the registry to the shape ProviderRegistry.SaveToFile writes.

func (*ProviderRegistry) WithRouting added in v1.8.7

func (r *ProviderRegistry) WithRouting(routing ModelRouting) *ProviderRegistry

WithRouting installs a custom routing table and returns the registry.

type Reranker

type Reranker interface {
	Rerank(query string, hits []KnowledgeHit) []KnowledgeHit
}

Reranker reorders retrieved hits by relevance to the query.

type ResolvedModel added in v1.8.7

type ResolvedModel struct {
	// Alias is the name callers use (e.g. `smooth-coding`).
	Alias string
	// Upstream is the concrete model (e.g. `moonshot/kimi-k2-thinking`), when
	// the gateway chose to surface it.
	Upstream string
	// ID is the stable id from `model_info.id`, when present — useful for
	// tracing a rename across the server-side model list.
	ID string
}

ResolvedModel is one routing entry returned by a gateway's `/model/info`.

type ResponseFormat added in v1.7.14

type ResponseFormat struct {
	// Name is a short identifier for the schema (e.g. "weather_report").
	Name string
	// Schema is the JSON Schema the response object must conform to.
	Schema map[string]any
	// Strict requests exact schema adherence (no extra keys). OpenAI/LiteLLM
	// enforce it.
	Strict bool
}

ResponseFormat constrains the shape of the model's response to a named JSON Schema. Rust models this as an enum with a single JsonSchema variant; Go uses a struct until a second variant exists.

func JSONSchemaFormat added in v1.7.14

func JSONSchemaFormat(name string, schema map[string]any) *ResponseFormat

JSONSchemaFormat builds a strict JSON-schema response format — the Go analogue of Rust's ResponseFormat::json_schema.

type RoleKind

type RoleKind int

RoleKind is a role's place in a multi-agent cast.

const (
	// RoleLead is the orchestrator that delegates to sidekicks.
	RoleLead RoleKind = iota
	// RoleSidekick is a focused specialist a lead can dispatch a sub-task to.
	RoleSidekick
	// RoleShadow is a passive observer (e.g. for logging/critique); not directly dispatchable.
	RoleShadow
)

type Router

type Router[S any] func(state S) string

Router inspects the current state and returns the next node name (or END).

type Severity added in v1.7.15

type Severity int

Severity is how severe a Narc finding is, ordered least → most severe. A SeverityBlock finding in PreCall blocks the tool call.

const (
	// SeverityInfo is informational — no action.
	SeverityInfo Severity = iota
	// SeverityWarn is suspicious but plausibly legitimate (e.g. a secret in an argument).
	SeverityWarn
	// SeverityAlert is a strong signal worth surfacing, but not auto-blocked.
	SeverityAlert
	// SeverityBlock is actively harmful — blocks the call when raised in PreCall.
	SeverityBlock
)

func (Severity) String added in v1.7.15

func (s Severity) String() string

String renders the severity as the shared wire label (INFO/WARN/ALERT/BLOCK).

type SharedGrants

type SharedGrants struct {
	// contains filtered or unexported fields
}

SharedGrants is a thread-safe, cheaply-shared handle to the live merged grants. Reads take a snapshot; approve-always merges the freshly-persisted grant back in.

func NewSharedGrants

func NewSharedGrants(grants *PermissionGrants) *SharedGrants

NewSharedGrants wraps grants for concurrent access.

func (*SharedGrants) MergeIn

func (s *SharedGrants) MergeIn(other *PermissionGrants)

MergeIn unions other into the live grants.

func (*SharedGrants) Snapshot

func (s *SharedGrants) Snapshot() *PermissionGrants

Snapshot returns a cloned-out copy for lock-free matching.

type SmoothAgent

type SmoothAgent struct {
	// contains filtered or unexported fields
}

SmoothAgent is a native, in-process agent.

func NewSmoothAgent

func NewSmoothAgent(client ChatClient, options AgentOptions) *SmoothAgent

NewSmoothAgent constructs an agent over an OpenAI-compatible ChatClient.

func (*SmoothAgent) Run

func (a *SmoothAgent) Run(ctx context.Context, message string, history []ChatMessage) (AgentRunResponse, error)

Run executes a single turn. history is prior conversation messages (multi-turn).

func (*SmoothAgent) RunStream

func (a *SmoothAgent) RunStream(ctx context.Context, message string, thread *SmoothAgentThread) (*Stream, error)

RunStream streams a single turn, delivering incremental StreamEvents on the returned channel. It drives the SAME agentic loop as Run (system/knowledge/memory build, seed messages, per-iteration compaction, cost tracking, budget early-stop, deferred-tool specs, clearance + human-gate on dispatch, checkpoint/thread persistence on exit) — but calls the model in STREAMING mode and emits events as work happens:

  • a StreamText event per non-empty content delta as it streams in;
  • a StreamToolCall event per requested tool call, after that iteration's model stream ends, BEFORE the call is dispatched;
  • a StreamToolResult event per tool, after it finishes (in original call order even when ParallelToolCalls runs them concurrently);
  • exactly one terminal StreamDone event carrying the same AgentRunResponse Run would return for the same script.

Error contract (idiomatic Go): the client must implement StreamingChatClient — if it does not, RunStream returns a nil channel and a non-nil error synchronously and runs nothing. Once the turn is running, a model-call error aborts it: the channel is closed WITHOUT a StreamDone and the error is stored, retrievable via the returned *Stream's Err() after the channel drains. So a caller ranges the channel to completion, then checks Err(); a clean turn ends with a StreamDone and Err()==nil.

That includes a stream that is TRUNCATED rather than finished — an idle or overall timeout, a torn connection (see ChatChunk.Err). Those abort the turn too: no StreamDone, non-nil Err(), and the partial assistant text is neither appended to the thread nor checkpointed. A half-answer must never be indistinguishable from a whole one.

SEP extension hooks run on this path exactly as they do on Run: `turn_start` at the top, the `tool_call` veto/rewrite fold before every dispatch, and `message_end`/`turn_end` before the terminal StreamDone.

A caller that stops consuming early must call Stream.Close (or cancel ctx) to release the turn goroutine and its model connection.

NOTE: retry-with-backoff (MaxRetries/RetryBackoff) is intentionally NOT applied to the streaming model call — re-running it after a mid-stream failure would re-emit already-yielded chunks. Retry stays scoped to non-streaming Run (see callModel); this mirrors the C# RunStreamingAsync decision.

func (*SmoothAgent) RunThread

func (a *SmoothAgent) RunThread(ctx context.Context, message string, thread *SmoothAgentThread) (AgentRunResponse, error)

RunThread executes a single turn carried by a SmoothAgentThread: the turn is seeded from the thread's messages, and this turn's new user + assistant (+ tool) messages are appended back to the thread before returning. The thread takes precedence over any history as the prior context. Run (single-shot/history) keeps working unchanged.

type SmoothAgentThread

type SmoothAgentThread struct {
	// ID is the stable id for this conversation (the key checkpoints store under).
	ID string
	// contains filtered or unexported fields
}

SmoothAgentThread is a conversation thread: a stable id plus the ordered non-system messages so far.

func NewThread

func NewThread() *SmoothAgentThread

NewThread creates a fresh thread with an auto-generated id.

func NewThreadWithID

func NewThreadWithID(id string) *SmoothAgentThread

NewThreadWithID resumes a thread under a known id (e.g. one recovered from a checkpoint). An empty id falls back to a fresh auto-generated one.

func (*SmoothAgentThread) Add

func (t *SmoothAgentThread) Add(m ChatMessage)

Add appends one message, skipping any system message (rebuilt per-run).

func (*SmoothAgentThread) Extend

func (t *SmoothAgentThread) Extend(msgs []ChatMessage)

Extend appends several messages, skipping any system messages.

func (*SmoothAgentThread) Len

func (t *SmoothAgentThread) Len() int

Len returns the number of messages currently in the thread.

func (*SmoothAgentThread) Messages

func (t *SmoothAgentThread) Messages() []ChatMessage

Messages returns the accumulated history, oldest first (no system prompt).

type Stream

type Stream struct {
	// contains filtered or unexported fields
}

Stream is the handle RunStream returns: range Events() to consume the turn's StreamEvents, then call Err() (after the channel drains) to see whether the turn aborted with a model error.

func (*Stream) Close added in v1.13.3

func (s *Stream) Close()

Close abandons the turn: the loop stops, the in-flight model request is torn down, and the events channel closes. It is safe to call more than once, and from a different goroutine than the consumer.

A consumer that drains Events() to completion need not call it. A consumer that stops early MUST — Go channels give the sender no way to notice a receiver has walked away (unlike the reference's `tx.send().is_err()`), so this is that signal. `defer stream.Close()` is the safe habit.

func (*Stream) Err

func (s *Stream) Err() error

Err returns the error that aborted the turn, or nil if it completed cleanly. Call it only after Events() has been fully drained (the channel closed).

func (*Stream) Events

func (s *Stream) Events() <-chan StreamEvent

Events returns the channel of streamed events. It is closed when the turn ends.

type StreamEvent

type StreamEvent struct {
	Kind      StreamEventKind
	Text      string // StreamText
	Name      string // StreamToolCall / StreamToolResult
	Arguments string // StreamToolCall
	Result    string // StreamToolResult
	// Details carries the structured, UI-facing payload a PostCall hook
	// attached to the ToolResult (nil when none) — forwarded verbatim and
	// un-truncated on StreamToolResult, never shown to the model. Mirrors the
	// Rust engine's AgentEvent::ToolCallComplete.details.
	Details  any              // StreamToolResult
	Response AgentRunResponse // StreamDone
}

StreamEvent is one event from RunStream. The Kind field selects which payload fields are populated, mirroring the C# RunStreamingAsync update sequence and the Rust reference engine's event stream:

  • StreamText: Text holds the content delta.
  • StreamToolCall: Name + Arguments hold the requested call.
  • StreamToolResult: Name + Result hold a finished tool's result.
  • StreamDone: Response holds the final AgentRunResponse (the same value Run would return for the same script). Exactly one StreamDone is emitted, last, UNLESS the turn ends in an error (see RunStream's error contract).

type StreamEventKind

type StreamEventKind int

StreamEventKind tags a StreamEvent.

const (
	// StreamText is an incremental assistant content delta as it streams in.
	StreamText StreamEventKind = iota
	// StreamToolCall is a tool call the model requested, emitted once before dispatch.
	StreamToolCall
	// StreamToolResult is a tool's result, emitted after it finishes.
	StreamToolResult
	// StreamDone is the single terminal event, carrying the final AgentRunResponse.
	StreamDone
)

type StreamingChatClient

type StreamingChatClient interface {
	ChatClient
	ChatStream(ctx context.Context, req ChatRequest) (<-chan ChatChunk, error)
}

StreamingChatClient is the OPTIONAL streaming surface. A ChatClient that also implements it can drive RunStream; the GatewayClient and MockLlmProvider both do. ChatStream opens a streaming model call and returns a receive-only channel of chunks. The channel is closed when the stream ends; a connect-time failure comes back as the returned error, and a MID-STREAM failure MUST arrive as a final chunk with Err set (see ChatChunk.Err) — closing the channel silently on a torn stream reports truncation as success. Implementations must also stop sending and release their transport once ctx is done. Production wires this to the OpenAI `create(..., stream=True)` surface.

type Tool

type Tool interface {
	Name() string
	Description() string
	Parameters() map[string]any
	Execute(ctx context.Context, args map[string]any) (string, error)
}

Tool is a callable the agent may invoke.

func DelegateTool

func DelegateTool(name, description string, child *SmoothAgent) Tool

DelegateTool builds a Tool that delegates a subtask to a child SmoothAgent.

A sub-agent is just a tool backed by another agent: the model calls this tool with a "task" argument, the child agent runs that task, and the child's final reply becomes the tool result — composing with the existing tool loop, no special wiring. The child can have its own instructions, tools, knowledge, etc.

type ToolCall

type ToolCall struct {
	ID        string
	Name      string
	Arguments string // raw JSON
}

ToolCall is a model-requested tool invocation.

type ToolCallDelta

type ToolCallDelta struct {
	Index        int    // which tool call this fragment belongs to
	ID           string // set when the call first opens ("" in later fragments)
	Name         string // set when the call first opens ("" in later fragments)
	ArgsFragment string // a fragment of the JSON arguments to append
}

ToolCallDelta is one tool-call fragment within a streamed chunk.

type ToolHook added in v1.7.1

type ToolHook interface {
	// PreCall runs before a tool executes. Returning a non-nil error blocks the
	// call: the tool never runs and the model is told it was blocked.
	PreCall(ctx context.Context, call ToolCall) error
	// PostCall runs after a tool executes, with a mutable *ToolResult it may
	// rewrite (the redaction seam). A returned error is ignored — the
	// (possibly redacted) result still reaches the model — matching the Rust
	// engine, where a post-hook failure is logged, not surfaced.
	PostCall(ctx context.Context, call ToolCall, result *ToolResult) error
}

ToolHook observes and can gate/redact tool calls, mirroring the Rust engine's ToolHook lifecycle (pre_call / post_call). Hooks are registered via AgentOptions.Hooks and run in registration order around every dispatched tool call. A hook must be safe for concurrent use: with ParallelToolCalls the engine may run PreCall/PostCall from multiple goroutines at once.

type ToolResult added in v1.7.1

type ToolResult struct {
	// ToolCallID is the id of the ToolCall this result answers.
	ToolCallID string
	// Content is the text the model sees. A PostCall hook may mutate it.
	Content string
	// IsError is true when the tool failed (or a PreCall hook blocked it).
	IsError bool
	// Details is optional structured, UI-facing data (diffs, tables, trace
	// ids) a PostCall hook may attach. It is forwarded verbatim on the
	// stream's StreamToolResult event and never reaches the model. Mirrors
	// the Rust engine's ToolResult.details.
	Details any
}

ToolResult is the outcome of a single tool call. It is handed to ToolHook.PostCall as a mutable pointer so a hook can rewrite Content before it reaches the model — the redaction seam (e.g. scrubbing a leaked secret from a tool's output). Mirrors the Rust engine's ToolResult.

type ToolSearch

type ToolSearch struct {
	// contains filtered or unexported fields
}

ToolSearch drives deferred-tool promotion for one agent run. It implements Tool so the agent can advertise + dispatch it like any other tool. It holds the deferred tools (by name) and the mutable set of promoted names; the agent consults PromotedTools each iteration to decide which deferred schemas are now visible/dispatchable.

func NewToolSearch

func NewToolSearch(deferred []Tool) *ToolSearch

NewToolSearch builds a ToolSearch over the given deferred tools.

func (*ToolSearch) Description

func (s *ToolSearch) Description() string

func (*ToolSearch) Execute

func (s *ToolSearch) Execute(_ context.Context, args map[string]any) (string, error)

Execute fuzzy-matches the query, promotes matches, and returns their schemas as JSON.

func (*ToolSearch) HasDeferred

func (s *ToolSearch) HasDeferred() bool

HasDeferred reports whether any tool was registered deferred (the meta-tool is advertised only then).

func (*ToolSearch) IsPromoted

func (s *ToolSearch) IsPromoted(name string) bool

IsPromoted reports whether a deferred tool has been promoted and is now dispatchable.

func (*ToolSearch) Name

func (s *ToolSearch) Name() string

func (*ToolSearch) Parameters

func (s *ToolSearch) Parameters() map[string]any

func (*ToolSearch) Promote

func (s *ToolSearch) Promote(name string) bool

Promote marks a deferred tool promoted. Returns false if no such deferred tool.

func (*ToolSearch) PromotedTools

func (s *ToolSearch) PromotedTools() []Tool

PromotedTools returns the deferred tools that have been promoted — their schemas join the visible set. Returned in registration order for determinism.

func (*ToolSearch) ToolByName

func (s *ToolSearch) ToolByName(name string) (Tool, bool)

ToolByName resolves a promoted deferred tool for dispatch. Unpromoted deferred tools are invisible (returns nil, false).

type ToolSpec

type ToolSpec struct {
	Name        string
	Description string
	Parameters  map[string]any // JSON Schema
}

ToolSpec is a tool advertised to the model.

type ToolsDeny

type ToolsDeny struct {
	Deny []string `toml:"deny,omitempty"`
}

ToolsDeny is `[tools]` — deny by tool name / glob.

type ToolsSection

type ToolsSection struct {
	Allow []string `toml:"allow,omitempty"`
}

ToolsSection holds tool names approved without asking. Exact match only.

type TurnPolicy added in v1.8.3

type TurnPolicy struct {
	// MaxIterations is the maximum number of model-call iterations before the
	// turn stops unconditionally.
	MaxIterations int
}

TurnPolicy is the loop policy for DriveTurn: the bound that keeps the orchestration terminating. Mirrors AgentOptions.MaxIterations.

func DefaultTurnPolicy added in v1.8.3

func DefaultTurnPolicy() TurnPolicy

DefaultTurnPolicy returns the policy the agent's own loop uses when AgentOptions.MaxIterations is unset. NOTE this is 20 here, not the Rust engine's 50 — each core keeps its own loop bound, and DriveTurn tracks the Go agent's so the two Go paths stay identical.

type Usage

type Usage struct {
	PromptTokens     int
	CompletionTokens int
}

Usage holds exact token counts reported by the model API.

func ScriptedUsage added in v1.7.15

func ScriptedUsage() Usage

ScriptedUsage is the token usage a SCRIPTED mock response reports. Fixed, and identical in all five engines' mocks (Rust · Go · Python · TypeScript · C#), so the shared server scenario corpus can assert eventual_response.usage as a real cross-language invariant instead of documenting five different answers (pearl th-4f1263).

Only the FIFO scripting helpers (PushText / PushToolCall) attach it. An unscripted response — the benign empty reply a drained script falls back to — still reports nothing, so "the script ran out" stays distinguishable from "the model answered". Pass an explicit WithUsage to PushResponse to override.

func (Usage) TotalTokens

func (u Usage) TotalTokens() int

TotalTokens is prompt + completion.

type VectorKnowledge

type VectorKnowledge struct {
	// contains filtered or unexported fields
}

VectorKnowledge is an embedding-backed knowledge store with cosine retrieval.

func NewVectorKnowledge

func NewVectorKnowledge(embedder Embedder) *VectorKnowledge

NewVectorKnowledge constructs a store with the given embedder (default HashEmbedder).

func (*VectorKnowledge) Ingest

func (v *VectorKnowledge) Ingest(content, source string)

Ingest embeds and stores a document.

func (*VectorKnowledge) Query

func (v *VectorKnowledge) Query(query string, topK int) []KnowledgeHit

Query embeds the query and returns up to topK docs by cosine similarity.

type Verdict

type Verdict struct {
	Kind   VerdictKind
	Reason string
}

Verdict is the pure result returned by Decide. Reason carries a human/LLM-readable explanation for Deny/Ask (empty for Allow).

func Decide

func Decide(mode AutoMode, toolName string, args map[string]any) Verdict

Decide is the pure, deterministic permission decision. No I/O — the security-critical core, tested exhaustively. args is the parsed tool-call argument object; the relevant field is pulled per category (cmd for bash, path for writes, url/host for network).

type VerdictKind

type VerdictKind int

VerdictKind tags a Verdict.

const (
	// VerdictAllow lets the call through.
	VerdictAllow VerdictKind = iota
	// VerdictDeny blocks the call outright.
	VerdictDeny
	// VerdictAsk pauses to ask a human. With no approver wired, the gate treats
	// this as fail-closed.
	VerdictAsk
)

type Workflow

type Workflow[S any] struct {
	// contains filtered or unexported fields
}

Workflow is a typed workflow graph: named nodes connected by static/conditional edges. Build with AddNode, AddEdge / AddConditionalEdge, SetEntry, and SetEnd; the builder methods return the receiver so they chain. Run executes the graph.

func NewWorkflow

func NewWorkflow[S any](maxSteps int) *Workflow[S]

NewWorkflow creates an empty workflow with the given max-steps cap (use a value <= 0 for the default of 100).

func (*Workflow[S]) AddConditionalEdge

func (w *Workflow[S]) AddConditionalEdge(from string, router Router[S]) *Workflow[S]

AddConditionalEdge adds a conditional edge whose router picks the next node at runtime. The router returns the target node name, or END to terminate.

func (*Workflow[S]) AddEdge

func (w *Workflow[S]) AddEdge(from, to string) *Workflow[S]

AddEdge adds a static edge from → to.

func (*Workflow[S]) AddNode

func (w *Workflow[S]) AddNode(name string, fn NodeFn[S]) *Workflow[S]

AddNode registers a node under name (used to reference it in edges).

func (*Workflow[S]) Run

func (w *Workflow[S]) Run(ctx context.Context, initialState S) (S, error)

Run executes the workflow from the entry node, returning the final state.

It returns an error if no entry node was set, a referenced node does not exist, a node fails, or the maxSteps cap is exceeded (e.g. an unbroken cycle).

func (*Workflow[S]) SetEnd

func (w *Workflow[S]) SetEnd(from string) *Workflow[S]

SetEnd marks from as terminal — reaching it ends the workflow.

func (*Workflow[S]) SetEntry

func (w *Workflow[S]) SetEntry(name string) *Workflow[S]

SetEntry sets the entry node (first node to execute).

Directories

Path Synopsis
Package extension is the Go engine's implementation of SEP, the Smooth Extension Protocol.
Package extension is the Go engine's implementation of SEP, the Smooth Extension Protocol.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL