agent

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: AGPL-3.0 Imports: 50 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.

Documentation

Overview

Package agent wires real LLM-driven planner and work agents (on top of the agent-core SDK) to the PostgreSQL graphs. See the architecture design documentation. §4.3 (planner) and §4.4 (work agent).

Provider configuration is read from the environment so the system runs with any Anthropic- or OpenAI-format endpoint. If no key is configured, FromEnv returns ok=false and the exploration engine stays idle (an LLM is required).

Index

Constants

View Source
const DeepSeekLocalOnlyMessage = WebSearchLocalOnlyMessage

DeepSeekLocalOnlyMessage remains an alias for callers using the former name.

View Source
const DefaultAssistantPrompt = "" /* 160-byte string literal not displayed */

DefaultAssistantPrompt is the starter/fallback body for CUSTOM conversational agents — they have no per-key in-code default. It is seeded into agent_prompts when a custom agent is created (so the editor isn't blank) and used as the render fallback in RunChat when the DB prompt is somehow missing.

View Source
const ReporterDefaultPrompt = "" /* 3646-byte string literal not displayed */

ReporterDefaultPrompt is the seeded prompt for the report-writing custom agent — triggered when report_finding fires. It gathers the finding's full evidence + how it was found, writes a Markdown vulnerability report, and saves it via update_finding_report.

View Source
const RetesterDefaultPrompt = "" /* 2160-byte string literal not displayed */

RetesterDefaultPrompt is seeded once as an editable conversation agent.

View Source
const WebSearchLocalOnlyMessage = "Web search is unavailable while local_llm_only is enabled"

DeepSeekLocalOnlyMessage is shared with the search connectivity probe.

Variables

View Source
var (
	// Task-level execution context.
	AbortPausedByUser = cause("paused_by_user", "User paused the task",
		"The user paused the task through POST /api/tasks/{id}/control with action=pause. This Planner/Worker run was cancelled; running intents return to frontier(open), and will be claimed and restarted from the beginning on resume.")
	AbortPausedByOrchestrator = cause("paused_by_orchestrator", "Orchestrator agent paused the task",
		"The orchestrator called pause_task. This Planner/Worker run was cancelled; running intents return to frontier(open) and execute again after resume.")
	AbortTaskDeleted = cause("task_deleted", "Task was deleted",
		"The task is being deleted through DELETE /api/tasks/{id}. The deletion barrier cancelled its active Planner, Worker, and main agent; this run's result will no longer be used.")
	AbortPausedOnReload = cause("paused_on_reload", "Backend restored the task's paused state",
		"At startup, the backend restored the persisted paused state from the database. This run was cancelled; normally no agent is running during restoration.")
	AbortGoalMet = cause("goal_met", "Planner marked task complete",
		"The planner marked the task done after confirming its objectives, then cancelled active workers. Their intents are marked stopped, not failed.")
	AbortSettleDrainTimeout = cause("settle_drain_timeout", "Task wrap-up drain expired",
		"After task timeout, workers were allowed to wrap up, but the 90-second drain grace expired. Hard cancellation marks intents exhausted; facts/assets already saved during wrap-up remain.")

	// Per-work context.
	AbortKilledByPlanner = cause("killed_by_planner", "Planner terminated this intent",
		"The planner used kill_work to terminate this intent, typically because it drifted or no longer justified further work. It is marked stopped and is not automatically reclaimed.")
	AbortWorkPausedByUser = cause("work_paused_by_user", "User paused this worker intent",
		"The user paused the running worker. This call was cancelled and the intent became paused. Registered intents, facts, findings, and activities remain; resuming restarts execution from the beginning.")
	AbortWorkCancelledByUser = cause("work_cancelled_by_user", "User deleted this worker intent",
		"The user deleted the running worker. This call was cancelled. After the worker leaves the write section, soft deletion marks the intent deleted and retains outputs; hard deletion removes it and downstream nodes supported only by it, according to the user's selected mode.")
	AbortWorkFinished = cause("work_finished", "Worker finished normally",
		"The worker finished normally and detachWork released its context resources. This is not an interruption; seeing it in an interruption message indicates a race between cancellation and completion events.")
	AbortPausedRaceGuard = cause("paused_race_guard", "New run blocked while paused",
		"The engine refused a new execution context while the task was paused, preventing a claim/pause race from starting a worker. Claimed intents return to frontier.")

	// Main Agent and standalone conversation contexts.
	AbortChatStoppedByUser = cause("chat_stopped_by_user", "User stopped this conversation turn",
		"The user clicked Stop to cancel this main-agent or conversation-agent turn. Existing activity records remain; another message can be sent.")
	AbortChatPausedWithTask = cause("chat_paused_with_task", "Task pause stopped main-agent chat",
		"Pausing the task also cancelled its active main-agent conversation. Existing activity records remain; resuming the task does not replay this message automatically.")
	AbortChatTurnFinished = cause("chat_turn_finished", "Conversation finished normally",
		"The conversation turn finished normally and the server released its context resources. This is not an interruption; seeing it in an interruption message indicates a cancellation/completion race.")

	// Process-level and per-run hard backstop.
	AbortShutdown = cause("shutdown", "Backend process is shutting down",
		"The backend received SIGINT or SIGTERM and is restarting, updating, or shutting down. Active agents are cancelled; leftover running intents reset to open and execute again after restart.")
	AbortRunHardTimeout = cause("run_hard_timeout", "Per-run hard timeout backstop triggered",
		"This run exceeded its soft wall-clock budget and grace period. A model request or tool likely failed to return, preventing normal turn-boundary wrap-up. Inspect the last unfinished tool call before interruption.")
)
View Source
var (
	WrapupTaskTimeoutOverride      func(agentKey string) (string, bool)
	WrapupTaskTimeoutTurnsOverride func(agentKey string) (int, bool)
)

WrapupTaskTimeoutOverride and its turn override are database-backed settings for worker/planner agents.task_timeout_wrapup_prompt and task_timeout_wrapup_max_turns.

View Source
var ErrChatPersistence = errors.New("chat transcript persistence is uncertain")

ErrChatPersistence means inference may have happened but its transcript cannot be acknowledged. The dispatcher must require recovery acknowledgement.

View Source
var FindingTrafficBindingEnabled func() bool

The server supplies the persisted setting. A missing setting/host is off. Consulted at assembly and again on writes so an already-running session cannot keep binding after the user switches the feature off.

View Source
var PromptOverride func(agentKey string) (string, bool)

PromptOverride, if set, returns the stored system-prompt template for an agent key and whether one exists. The server wires it to the PG agent_prompts table. When nil or no override exists, agents use their built-in default prompt — so behavior is identical until a user edits a prompt in the UI.

View Source
var ToolAugment func(ctx context.Context, agentKey string) (extra []actool.CoreTool, def DeferredInfo, cleanup func())

ToolAugment, if set, returns the EXTRA tools an agent should see beyond its built-in base set — the agent's visible skills (packed into one Skill meta-tool) and visible MCP servers (expanded to mcp__server__tool). It also returns the DeferredInfo describing how those MCP tools are deferred/gated. The server wires it to the PG agent_visibility table. cleanup releases any spawned MCP clients.

When nil, agents run with only their built-in tools — behavior is unchanged until a user assigns a skill/MCP to the agent in the UI.

View Source
var ToolResolve func(ctx context.Context, agentKey string, tools []actool.CoreTool) []actool.CoreTool

ToolResolve, if set, post-processes an agent's fully-assembled tool list against the DB tools table: it drops tools not bound to this agent (or globally disabled) and wraps the rest so the model sees the DB-overridden description/schema and Parameter defaults are injected. Tools without matching rows (MCP/skill/host tools like traffic) pass through untouched. nil = tools unchanged. Wired in server/assembly.go.

View Source
var WrapupMaxTurnsOverride func(agentKey string) (int, bool)

WrapupMaxTurnsOverride, if set, returns the admin-configured turn budget for the wrap-up phase of an agent and whether a positive one exists. Wired to the agents table. nil / ≤0 → the built-in per-agent default (wrapupTurnDefaults) is used.

View Source
var WrapupOverride func(agentKey string) (string, bool)

WrapupOverride, if set, returns the stored wrap-up prompt for an agent key and whether a non-empty one exists. Wired by the server to the agents table (like PromptOverride for system prompts). nil / empty → the built-in default is used.

Functions

func AbortReason

func AbortReason(ctx context.Context) (code, short, text string, ok bool)

AbortReason resolves the named cause attached to a cancelled run context.

func BuiltinPromptSeeds

func BuiltinPromptSeeds() map[string]string

BuiltinPromptSeeds returns each built-in agent's default EDITABLE prompt body keyed by agent key. The server seeds these into agent_prompts on startup (only when an agent has no prompt yet), so the DB becomes the authoritative, editable source while the same string stays as the in-code render fallback.

func BuiltinPromptText

func BuiltinPromptText(text string, lang locale.Lang) string

func CanonicalBuiltinPrompt

func CanonicalBuiltinPrompt(text string) string

CanonicalBuiltinPrompt returns canonical English only for an exact stock shipped-language/legacy template. All other text is returned byte-for-byte.

func DecorateTool

func DecorateTool(t actool.CoreTool, desc string, schema map[string]any) actool.CoreTool

DecorateTool wraps t so Description()/InputSchema() report the DB overrides and Call() injects scalar parameter defaults (from schema's "default" props) whenever the model omitted them. Name/Prompt/permission/scheduler flags delegate to t, so the tool's identity and handler are unchanged. Empty desc/schema fall back to t's.

func DeepSeekWebSearchProbe

func DeepSeekWebSearchProbe(ctx context.Context, cfg actool.WebSearchConfig, meter DeepSeekSearchMeter, query string, limit int) ([]actool.SearchResult, error)

DeepSeekWebSearchProbe bypasses tool permissions, as the settings test always has, and shares the exact request/parser/metering path with the live tool.

func EstimatedChatRequestTokens

func EstimatedChatRequestTokens(req llm.CompletionRequest) int

func HintTrafficSchema

func HintTrafficSchema(langs ...locale.Lang) map[string]any

HintTrafficSchema is shared by the task-local and cross-task hint tools.

func IsQuotaExhaustedMessage

func IsQuotaExhaustedMessage(message string) bool

func MeasureChatContext

func MeasureChatContext(req llm.CompletionRequest, profileID int64, model string, window, reserve int, p ContextProvenance) chatstate.ContextView

func NewDeepSeekWebSearch

func NewDeepSeekWebSearch(cfg actool.WebSearchConfig, meter DeepSeekSearchMeter) (actool.CoreTool, error)

NewDeepSeekWebSearch replaces only Call; Norma remains the permission authority.

func ObserveChatContext

func ObserveChatContext(ctx context.Context, view chatstate.ContextView) error

func PrepareChatCompaction

func PrepareChatCompaction(ctx context.Context, records []transcript.Record, req llm.CompletionRequest, opts chatstate.CompactOptions, summarize compaction.Summarizer, inputBudget int) ([]transcript.Record, chatstate.ContextView, error)

PrepareChatCompaction never writes the active transcript. The caller publishes a separately synced candidate under the same durable admission gate.

func RebudgetChatContext

func RebudgetChatContext(v chatstate.ContextView, profileID int64, model string, window, reserve int, identity string) chatstate.ContextView

func ResolveLegacyStockSchema

func ResolveLegacyStockSchema(name string, persisted, current map[string]any) map[string]any

ResolveLegacyStockSchema returns a copy of current when persisted exactly matches a registered prior-stock schema for name; otherwise it returns persisted unchanged. Neither input is mutated. Callers pass the persisted DB schema and the current factory schema for the same tool in the requested language, so a recognized stock row resolves to the corrected stock schema in the right language — exactly what a fresh install would advertise.

func TaskTimeoutWrapupDefault

func TaskTimeoutWrapupDefault(agentKey string) string

TaskTimeoutWrapupDefault supplies UI placeholders and reset-to-default values.

func TestConnection

func TestConnection(ctx context.Context, c Config) (time.Duration, string, error)

TestConnection makes a minimal real completion to verify the provider/model/ endpoint/key actually work. Returns the round-trip latency and the model's reply text.

func TranslateToolMetadata

func TranslateToolMetadata(current, source, target actool.CoreTool) actool.CoreTool

TranslateToolMetadata renders an API/runtime copy from the corresponding bundled source/target language tools. Only exact default description fields are eligible. JSON keys, enums, defaults, raw results, and handlers are untouched.

func TranslateToolVariants

func TranslateToolVariants(current actool.CoreTool, variants map[locale.Lang]actool.CoreTool, lang locale.Lang) actool.CoreTool

TranslateToolVariants recognizes exact stock metadata in every shipped source language. Only descriptions are eligible; handlers and edited fields survive.

func WithChatContextObserver

func WithChatContextObserver(ctx context.Context, save ChatContextObserver) context.Context

func WithChatRun

func WithChatRun(ctx context.Context, run chatstate.Run, control ChatRunControl) context.Context

func WithRunInfo

func WithRunInfo(ctx context.Context, ri RunInfo) context.Context

WithRunInfo attaches run attribution to ctx.

func WithTaskClock

func WithTaskClock(ctx context.Context, tc TaskClock) context.Context

WithTaskClock attaches a TaskClock to ctx for the run.

func WorkerSessionID

func WorkerSessionID(explorationID, intentID int64) string

WorkerSessionID returns the stable transcript key used by a worker intent. Worker slots are reusable, so the intent id (rather than work#N) is the session identity. Keep this helper public so the Worker message API and UI can refer to exactly the conversation that will be resumed.

func WrapupDefault

func WrapupDefault(agentKey string) string

WrapupDefault returns the built-in default wrap-up prompt for an agent key — used by the admin UI as the "restore default" value and empty-field placeholder.

func WrapupTurnsDefault

func WrapupTurnsDefault(agentKey string) int

WrapupTurnsDefault returns the built-in wrap-up turn budget for an agent key — used by the admin UI as the "0 = default N" hint.

Types

type AbortCause

type AbortCause struct {
	Code  string
	Short string
	Text  string
}

AbortCause names why an agent run's context was cancelled. Every cancellation site should attach one so the activity trace can report the real initiator.

func Causef

func Causef(code, short, format string, args ...any) *AbortCause

Causef builds a cause that includes runtime-specific detail.

func (*AbortCause) Error

func (c *AbortCause) Error() string

type ChatAgent

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

ChatAgent is the generic, task-independent conversational runner behind the chat page. It generalizes MainAgent.Chat: any agent (built-in OR a custom one, by key) can be chatted with, multi-turn history resumed from the transcript. It is built on SDK DefaultTools (Bash/Read/Write/Edit/LS/Glob/Grep) plus its visible skills/MCP and bound tools. Finding tools use a conversation-owned graph; task orchestration and its execution context remain separate.

func NewChatAgent

func NewChatAgent(prov llm.Provider, model, workDir string, tx *transcript.Store, window int) *ChatAgent

func (*ChatAgent) Chat

func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message string, maxTurns int, maxDuration time.Duration, webSearch bool, emit func(db.Activity)) (string, error)

Chat runs ONE turn of a conversation with the agent identified by agentKey, resuming prior history keyed by sessionID. maxTurns is the per-turn agent step budget (0 = unlimited). maxDuration is the wall-clock run budget per turn (0 = unlimited); the timer resets each time Chat is called, so a new user message always starts a fresh countdown. webSearch gates network search for THIS agent (the global backend/key still come from the chat agent's config, but each agent decides on/off). emit receives each execution step (thinking / tool_use / tool_result / text / result), tagged with the agent key as the worker lane.

func (*ChatAgent) SetGuard

func (c *ChatAgent) SetGuard(g *guard.Guard)

SetGuard attaches a guard (with user-configured intercept rules) to this chat agent. Must be called before Chat; safe to call multiple times.

func (*ChatAgent) SetMaxTokens

func (c *ChatAgent) SetMaxTokens(fn func() int)

SetMaxTokens wires a resolver for the per-reply output cap. nil/unset or 0 = send no cap and let the endpoint decide. Read per run, like nonStreaming.

func (*ChatAgent) SetNativeOllamaResolver

func (c *ChatAgent) SetNativeOllamaResolver(fn func() bool)

SetNativeOllamaResolver resolves whether the current run uses native Ollama.

func (*ChatAgent) SetNoaEnabled

func (c *ChatAgent) SetNoaEnabled(fn func() bool)

SetNoaEnabled wires a resolver deciding whether chat runs use the experimental noa context-compression mechanism. nil/unset = off (built-in compaction). Read per run so the settings toggle takes effect without rebuilding the agent.

func (*ChatAgent) SetNonStreaming

func (c *ChatAgent) SetNonStreaming(fn func() bool)

SetNonStreaming wires a resolver deciding whether chat runs use the non-streaming model path (true = non-streaming). nil/unset = streaming.

func (*ChatAgent) SetProxy

func (c *ChatAgent) SetProxy(addr, caCert string)

SetProxy points the chat agent's WebFetch/Bash at the recording proxy plus the CA cert it trusts (empty addr = direct). Kept for parity with the other agents.

func (*ChatAgent) SetWebSearch

func (c *ChatAgent) SetWebSearch(o WebSearchOpts)

SetWebSearch selects the web_search backend for the chat agent (off by default).

type ChatRunControl

type ChatRunControl interface {
	TakeSteer(context.Context, string) (*chatstate.Admission, error)
	SteerDelivered(context.Context, string, string) error
	RecordBoundary(context.Context, string, string, string) error
}

type Compactor

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

Compactor performs background cold-node compaction for many explorations.

func NewCompactor

func NewCompactor(prov llm.Provider, model string) *Compactor

NewCompactor builds a compactor. prov/model are used for the §4 body LLM call (same model the agent runs on, per §4). A nil Compactor is a safe no-op.

func (*Compactor) OnPlannerRound

func (c *Compactor) OnPlannerRound(ctx context.Context, ts *db.ExplorationStore)

OnPlannerRound is the single entry the planner calls each wake-up. It bumps the round, maintains the cold stamps synchronously, then (if a threshold is hit and no compaction is running / cooling down) launches a background compaction that outlives this planner round.

type Config

type Config struct {
	PolicyResolver func() (bool, []string)

	KeepAlive            string
	MaxConcurrent        int
	LocalLLMOnly         bool
	LocalLLMAllowedCIDRs []string
	JSONSchema           map[string]any
	JSONOutput           bool
	Format               llm.Format
	BaseURL              string
	APIKey               string
	Model                string
	// Proxy routes all LLM requests through the given proxy URL (http/https/socks5,
	// optionally with user:pass@ credentials). Empty means direct — it does NOT
	// fall back to the standard *_PROXY environment variables.
	Proxy string
	// RatePerSecond / RatePerMinute cap the shared request rate across ALL agents
	// using the provider (0 = that window unlimited).
	RatePerSecond float64
	RatePerMinute float64
	// ContextWindowK is the model's context window in K tokens (user-configured),
	// used to size compaction thresholds. 0 = default; see CompactionWindow.
	ContextWindowK int
	// ThinkingType independently controls thinking.type:
	// Empty omits the field for compatibility; disabled explicitly turns it off;
	// enabled turns it on. It is independent of ReasoningEffort because some endpoints
	// expose only an effort parameter, so either setting may be used on its own.
	ThinkingType string
	// ReasoningEffort independently controls reasoning intensity:
	// Empty omits it; low/medium/high/xhigh/max select the corresponding effort.
	// OpenAI uses reasoning_effort; Anthropic uses output_config.effort.
	ReasoningEffort string
	// Stream controls profile SSE usage: true (default) streams, false sends
	// stream:false and gets complete JSON through Provider.Complete. Non-streaming
	// avoids broken gateway SSE (empty frames or lost reasoning deltas), at the cost
	// of live progress/token counts. Maps to agentcore.Options.NonStreaming = !Stream.
	Stream bool
	// MaxTokens limits output tokens per reply, independently of ContextWindowK.
	// Zero becomes 32768 on agent harness turns. Direct Anthropic calls default
	// to 8192; direct native Ollama calls use their own default (4096).
	// Agent turns pass this value through agentcore.Options.MaxTokens.
	MaxTokens int
	// MaxTokensField chooses the request field for MaxTokens in openai format:
	// Empty uses max_tokens; max_completion_tokens selects the newer field.
	// OpenAI reasoning models reject max_tokens with unsupported_parameter, while
	// many compatible gateways require it. Let users choose per endpoint; do not infer.
	MaxTokensField string
	// Nonempty SessionHeaderKey adds a custom HTTP header to each LLM request,
	// carrying the current session ID (conv-<id>, exp<x>-worker-i<intent>, etc.;
	// see WorkerSessionID). Some gateways use it for prompt caching/sticky routing.
	// Empty omits it. transcript.WithSessionID attaches the value to context, and
	// RoundTripper reads it, so a shared provider can send different session values.
	SessionHeaderKey string
	// Retry holds resolved profile -> global -> built-in retry parameters, resolved
	// by the server. See RetryConfig for layers; zero values use built-in defaults.
	Retry RetryConfig
}

Config describes the LLM backend resolved from the environment.

func ConfigFrom

func ConfigFrom(provider, model, baseURL, apiKey, proxy string) Config

ConfigFrom builds a Config from UI-provided strings (provider defaults to anthropic; model defaults per provider). Inputs are trimmed and the base URL is normalized to the API base the provider expects (the provider appends the endpoint path itself), so a full endpoint URL is tolerated.

func FromEnv

func FromEnv() (Config, bool)

FromEnv resolves the LLM provider config:

ARTEX_LLM_PROVIDER = anthropic|openai|openai-responses|ollama|codex-cli
ARTEX_LLM_MODEL    = model id        (default: per provider)
ARTEX_LLM_BASE_URL = endpoint        (optional)
ARTEX_LLM_PROXY    = proxy URL        (optional; http/https/socks5)
ANTHROPIC_API_KEY / OPENAI_API_KEY         = credentials

func (Config) CompactionWindow

func (c Config) CompactionWindow() int

CompactionWindow returns the model context window in TOKENS for compaction thresholds, resolved from the user-configured size (ContextWindowK). 0/unset → a 200K default; otherwise clamped to [32K, 1M] so compaction stays effective.

func (Config) HTTPClient

func (c Config) HTTPClient() (*http.Client, error)

HTTPClient is shared by inference, metadata, diagnostics, and judge consumers.

func (Config) NewProvider

func (c Config) NewProvider() (llm.Provider, error)

NewProvider builds an llm.Provider from the config. When a rate is set, the limiter lives on the single provider instance — so planner + all workers + main agent (which share this provider) are bounded by one shared rate limit.

func (Config) Provider

func (c Config) Provider() string

Provider returns the supported profile format name.

func (Config) Ready

func (c Config) Ready() bool

Ready checks configuration; Codex executable/login readiness is checked on use.

type ContextProvenance

type ContextProvenance struct {
	SystemSegments map[int]string
	ToolCategories map[string]string
	MessageBlocks  map[string]string
}

Provenance is assigned while assembling the request, never inferred from arbitrary user text. A serialized block (including nested results) has one owner.

func RemapChatContextProvenance

func RemapChatContextProvenance(previous chatstate.ContextView, req llm.CompletionRequest) ContextProvenance

Rebase only attribution metadata. Unchanged retained blocks retain their sole category; newly synthesized prose is conversation, never raw prompt text.

type DeepSeekSearchMeter

type DeepSeekSearchMeter struct {
	Store       *db.DB
	ProfileName string
}

DeepSeekSearchMeter captures the global search profile, which may differ from the task's inference profile. Usage is written even when body recording is off.

type DeferredInfo

type DeferredInfo struct {
	FindingGuidance string            // derived from the final permitted tools, including DB overrides
	Deferred        []string          // all MCP tool names (schema withheld)
	GlobalNames     []string          // MCP names to list in the system-prompt block
	Unlock          *actool.UnlockSet // shared call-gate; nil when no MCP tools
	UnlockSkill     func(skillName string)
}

DeferredInfo carries the deferred-tools wiring an agent needs to build its Options: the MCP tool names whose schemas are withheld, the subset listed in the global system-prompt block (non-skill-gated), and the shared session unlock set. UnlockSkill unlocks a named skill's MCPs — hosts call it to rebuild the unlock set from history on a resumed session (design doc C2).

func AugmentTools

func AugmentTools(ctx context.Context, agentKey string, base []actool.CoreTool) ([]actool.CoreTool, DeferredInfo, func())

AugmentTools returns base plus the agent's visible skill/MCP tools, the DeferredInfo, and a cleanup func the caller must defer (closes MCP clients). Built-in base tools remain in code and are not filtered for visibility.

type EnrichTrigger

type EnrichTrigger interface {
	ResolveDomain(id int64, host string)
	ProbeSite(id int64, url string)
}

EnrichTrigger is the enrichment engine seen from the tool layer (see package enrich). Kept as an interface here to avoid coupling agent → enrich.

type FindingRecorder

type FindingRecorder interface {
	Record(context.Context, db.RecordFindingInput, []db.TrafficRef) (*db.RecordedFinding, error)
}

FindingRecorder is injected by the host; agents never synthesize or copy evidence bodies themselves. Its implementation owns the atomic write.

type GoalSpec

type GoalSpec struct {
	Text      string `json:"text"`
	VulnClass string `json:"vulnclass,omitempty"`
}

GoalSpec is one decomposed objective.

func DecomposeGoals

func DecomposeGoals(ctx context.Context, prov llm.Provider, dataDir, goalText, desc string, as *db.AssetStore, ts *db.ExplorationStore, taskID int64, emit func(db.Activity)) []GoalSpec

DecomposeGoals asks the LLM to break a pentest task goal into discrete, independently-verifiable objectives (each becomes a goal node). Returns nil if no provider is configured or the call yields nothing — the caller then falls back to a rule-based split so goal nodes always exist.

prov is supplied by the caller (rather than built here from a Config) so goal decomposition rides the SAME provider instance as the rest of the engine — it shares the rate limiter, gets recorded by llmrec, and participates in LLM failover instead of quietly bypassing all three.

desc is the task's free-text background: target scope, flag count, engagement instructions, etc. It is fed alongside the goal so the decomposer no longer splits blind — the prompt still forbids inventing anything the two texts don't state.

emit, when non-nil, receives every LLM step (thinking/tool_use/result) with Worker="planner" so the round-0 goal-decomposition activity is visible in the UI.

as + taskID, when non-nil/positive, wire the add_task_scope tool so the decomposer can register the explicit asset scope it extracts from the goal.

ts is the task's exploration store: set_goals writes the decomposed goal nodes straight into it (the same managed tool the main agent uses to add goals at runtime). The returned specs are read back from the store so callers can emit per-goal activity and detect the "LLM produced nothing" case for their fallback.

func DecomposeGoalsWithProvider

func DecomposeGoalsWithProvider(ctx context.Context, prov llm.Provider, dataDir, goalText, desc string, as *db.AssetStore, ts *db.ExplorationStore, taskID int64, nonStreaming bool, maxTokens int, emit func(db.Activity), policies ...RuntimePolicy) []GoalSpec

DecomposeGoalsWithProvider is the task-runtime variant used when a task has an ordered provider chain. It preserves the same tools and write behavior while letting the caller own provider selection/failover. maxTokens is the profile's per-reply output cap (0 = send none).

type GoalsVars

type GoalsVars struct{ EngagementDescription, DataDir, Now string }

type MainAgent

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

MainAgent is the thin human-interface orchestrator (docs §4.2 / §7). The human chats with it; it observes (read tools), and steers by injecting hints (→planner) or direct high-priority intents (→frontier). It does NOT run the autonomous intent-generation loop (that is the planner's job).

func NewMainAgent

func NewMainAgent(prov llm.Provider, model, workDir string, tx *transcript.Store, window, maxTurns int) *MainAgent

func (*MainAgent) Chat

func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.AssetStore, ts *db.ExplorationStore, goal, message string, emit func(db.Activity), notify, resume func(), notifyGoal, notifyHint func([]string)) (string, error)

Chat handles one human message and returns the assistant reply. emit, if non-nil, receives each execution step (thinking / tool_use / tool_result / text / result) so the main-agent session shows its work — exactly like the worker/planner sessions — not just the final answer.

func (*MainAgent) SetCompactionWindowResolver

func (m *MainAgent) SetCompactionWindowResolver(fn func() int)

func (*MainAgent) SetFindingRecorder

func (m *MainAgent) SetFindingRecorder(r FindingRecorder)

func (*MainAgent) SetMaxTokens

func (m *MainAgent) SetMaxTokens(fn func() int)

SetMaxTokens wires a resolver for the per-reply output cap. nil/unset or 0 = send no cap and let the endpoint decide. Read per run, like nonStreaming.

func (*MainAgent) SetNativeOllamaResolver

func (m *MainAgent) SetNativeOllamaResolver(fn func() bool)

SetNativeOllamaResolver resolves whether the current run uses native Ollama.

func (*MainAgent) SetNoaEnabled

func (m *MainAgent) SetNoaEnabled(fn func() bool)

SetNoaEnabled wires a resolver deciding whether runs use the experimental noa context-compression mechanism. nil/unset = off (built-in compaction). Read per run so the settings toggle takes effect without rebuilding the agent.

func (*MainAgent) SetNonStreaming

func (m *MainAgent) SetNonStreaming(fn func() bool)

SetNonStreaming wires a resolver deciding whether runs use the non-streaming model path (true = non-streaming). nil/unset = streaming (default).

func (*MainAgent) SetProxy

func (m *MainAgent) SetProxy(addr, caCert string)

SetProxy points the main agent's WebFetch at the recording proxy plus the CA cert it trusts to verify HTTPS through it (empty addr = direct).

func (*MainAgent) SetSteerWork

func (m *MainAgent) SetSteerWork(fn func(intentID int64, msg string) error)

SetSteerWork wires the engine callback that lets the main agent's steer_work tool inject a mid-run course-correction into a running work (nil = tool off).

func (*MainAgent) SetWebSearch

func (m *MainAgent) SetWebSearch(o WebSearchOpts)

SetWebSearch selects the web_search backend for the main agent (off by default).

type MainVars

type MainVars struct{ Goal, AssetSummary, FindingsSummary, DataDir, Now string }

type Planner

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

Planner is the event-driven LLM planner (docs §4.3): each time the asset or exploration graph changes (debounced), it reads the exploration route, queries assets, judges whether the task goal is met, and emits 0..N exploration intents into the frontier. It is the sole intent generator.

func NewPlanner

func NewPlanner(prov llm.Provider, model, workDir string, tx *transcript.Store, window, maxTurns int) *Planner

func (*Planner) Plan

func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts *db.ExplorationStore, goal string, triggers []TriggerEvent, emit func(db.Activity)) (met bool, reason string, err error)

Plan runs one planning round. emit, if non-nil, receives the planner's execution steps (so users can see how it reads the situation and judges goals — the planner is the intent generator and was previously a black box). Returns whether the planner judged the goal met. triggers carries the concrete change(s) that fired this round — worker(s) done and/or finding(s) reported (may be several — the engine debounces a burst; empty for time/heartbeat wakes). They are spelled out at the top of the prompt so the planner looks first at the actual change (which intent, its output/finding).

func (*Planner) SetCompactionWindowResolver

func (p *Planner) SetCompactionWindowResolver(fn func() int)

func (*Planner) SetCompactor

func (p *Planner) SetCompactor(c *Compactor)

SetCompactor wires the cold-node compactor (cold-digest §7). Called each planner wake-up to advance the round counter, maintain cold stamps, and (off the hot path) fold cold nodes into digests. nil = feature disabled.

func (*Planner) SetConstraintInject

func (p *Planner) SetConstraintInject(fn func() bool)

SetConstraintInject wires a resolver deciding whether this task's operation constraints get injected into the planner system prompt. Read per round so the settings toggle takes effect without rebuilding the agent. nil = inject (default).

func (*Planner) SetFindingRecorder

func (p *Planner) SetFindingRecorder(r FindingRecorder)

func (*Planner) SetKillWork

func (p *Planner) SetKillWork(fn func(intentID int64) error)

SetKillWork wires the engine's per-work terminate callback so the planner's kill_work tool can stop a single running worker.

func (*Planner) SetMaxTokens

func (p *Planner) SetMaxTokens(fn func() int)

SetMaxTokens wires a resolver for the per-reply output cap. nil/unset or 0 = send no cap and let the endpoint decide. Read per run, like nonStreaming.

func (*Planner) SetNativeOllamaResolver

func (p *Planner) SetNativeOllamaResolver(fn func() bool)

SetNativeOllamaResolver resolves whether the current run uses native Ollama.

func (*Planner) SetNoaEnabled

func (p *Planner) SetNoaEnabled(fn func() bool)

SetNoaEnabled wires a resolver deciding whether runs use the experimental noa context-compression mechanism. nil/unset = off (built-in compaction). Read per run so the settings toggle takes effect without rebuilding the agent.

func (*Planner) SetNonStreaming

func (p *Planner) SetNonStreaming(fn func() bool)

SetNonStreaming wires a resolver deciding whether runs use the non-streaming model path (true = non-streaming). nil/unset = streaming (default).

func (*Planner) SetProxy

func (p *Planner) SetProxy(addr, caCert string)

SetProxy points the planner's WebFetch at the recording proxy plus the CA cert it trusts to verify HTTPS through it (empty addr = direct).

func (*Planner) SetSteerWork

func (p *Planner) SetSteerWork(fn func(intentID int64, msg string) error)

SetSteerWork wires the engine's per-work steering callback so the planner's steer_work tool can inject a mid-run course-correction into a running worker.

func (*Planner) SetWebSearch

func (p *Planner) SetWebSearch(o WebSearchOpts)

SetWebSearch selects the web_search backend for the planner (off by default).

type PlannerVars

type PlannerVars struct{ Goal, Scope, AssetSummary, DataDir, Now string }

Prompt-variable structs — fields mirror each agent's catalog (docs §5a) so a user template referencing a catalog variable renders; referencing anything else fails template execution and falls back to the built-in default.

type RetryConfig

type RetryConfig struct {
	// ConnectAttempts/ConnectInterval cover pre-stream connection reset/timeout/429/5xx,
	// mapping to llm.Config.MaxRetries/RetryInterval: default 3, exponential 0.5s to 8s.
	ConnectAttempts int
	ConnectInterval time.Duration
	// EmptyAttempts/EmptyInterval cover completed responses without content blocks
	// in openai format, mapping to EmptyResponseRetries/EmptyResponseInterval.
	// Defaults: two retries using the same exponential ladder.
	EmptyAttempts int
	EmptyInterval time.Duration
	// StreamAttempts/StreamInterval add a same-provider safe-window retry layer above
	// the SDK for broken streams/overload/in-stream 429 only before any output is delivered.
	// server/task_llm.go consumes it; defaults are two retries, exponential 0.5s to 4s.
	StreamAttempts int
	StreamInterval time.Duration
}

RetryConfig travels with an LLM profile. Attempts have consistent semantics: zero uses defaults, negative disables retries, positive overrides the count. An interval of zero retains exponential backoff; positive selects a fixed delay.

type RunInfo

type RunInfo struct {
	TaskID        int64  // task registry id; 0 for non-task runs (chat sessions)
	ExplorationID int64  // exploration id; 0 when unknown
	IntentID      int64  // worker's intent node; 0 for planner/mainagent/chat
	SessionID     string // chat conversation id; empty for task runs
}

RunInfo identifies WHICH run a tool call belongs to. Tool assembly only receives (ctx, agentKey) — the task/exploration ids live in the caller's arguments, not the ctx — so anything wired at assembly time (currently the Skill ledger in server/assembly.go) has no way to attribute a call to a task. Each run attaches its own RunInfo before calling AugmentTools; the wiring closure reads it once and captures it, so per-run attribution stays correct without threading parameters through the tool layer. Same pattern as TaskClock (see taskclock.go).

Zero value = attribution unknown; every consumer must treat it as optional.

func RunInfoFrom

func RunInfoFrom(ctx context.Context) RunInfo

RunInfoFrom reads the RunInfo (zero value if none attached).

type RuntimePolicy

type RuntimePolicy struct {
	NativeOllama  bool
	ContextWindow int
}

RuntimePolicy selects the native Ollama context safeguards without changing the historical context management of cloud and compatible providers.

type TaskClock

type TaskClock struct {
	DeadlineUnix int64 // absolute deadline (unix seconds); 0 = no task timeout
	Final        bool  // coordinator-driven FINAL planner round (task ending now)
}

TaskClock carries a task's absolute deadline into a worker/planner run so the run can clamp its own wall-clock budget to the task's remaining time and pick the right wrap-up words (per-run vs task-timeout). Attached to the run ctx by the engine. Zero value = no task-level timeout (behaves exactly as before).

type ToolSeed

type ToolSeed struct {
	Key    string         // Immutable primary key, equal to CoreTool.Name().
	Desc   string         // Top-level description, overridable in UI.
	Schema map[string]any // Parameter JSON Schema: structure is read-only; description/default are editable.
	Agents []string       // Default agent keys: worker/planner/mainagent.
}

ToolSeed snapshots a built-in: Key is CoreTool.Name(), bound to its handler and read-only in UI; Desc/Schema come from code, Agents lists default bindings.

func BuiltinToolSeeds

func BuiltinToolSeeds() []ToolSeed

BuiltinToolSeeds deduplicates each agent's tools by name, merging agent bindings. Tools in defaultUnbound are forced to an empty binding list.

type ToolSet

type ToolSet struct {
	GoalMet bool
	Reason  string
	// contains filtered or unexported fields
}

ToolSet exposes the PG-backed dual graph (asset + exploration) to an LLM agent. One ToolSet is created per planner/worker run; per-run signals live here.

func NewToolSet

func NewToolSet(ts *db.ExplorationStore, worker string, langs ...locale.Lang) *ToolSet

func (*ToolSet) AddHintTool

func (t *ToolSet) AddHintTool() actool.CoreTool

func (*ToolSet) AllDomainTools

func (t *ToolSet) AllDomainTools() []actool.CoreTool

AllDomainTools returns the union of all domain tools across all agent types, deduped by name (mainagent order wins). Used by the server to build a registry for injecting domain tools into agents (Auto, custom) that don't own a per-task ToolSet. The caller provides real stores; tools are callable at taskID=0 scope.

func (*ToolSet) CoverageDisabled

func (t *ToolSet) CoverageDisabled() bool

CoverageDisabled reports whether the coverage feature is off for this task.

func (*ToolSet) DropCoverageTools

func (t *ToolSet) DropCoverageTools(tools []actool.CoreTool) []actool.CoreTool

DropCoverageTools returns tools with the coverage-only ones removed when this task has the feature disabled; otherwise it returns tools unchanged.

func (*ToolSet) GetWorkerTraceTool

func (t *ToolSet) GetWorkerTraceTool() actool.CoreTool

func (*ToolSet) GraphOverviewTool

func (t *ToolSet) GraphOverviewTool() actool.CoreTool

Cross-task reuse: exported accessors returning the per-task tool logic bound to THIS ToolSet's store. Host-side orchestration tools build a ToolSet for an arbitrary task, then Call these — so cross-task reads/hint reuse the exact same logic as the in-task tools. (readTool ignores ToolContext, so Call(…,nil) is safe; add_hint is a writeTool but also doesn't deref the context here.)

func (*ToolSet) ListFindingsTool

func (t *ToolSet) ListFindingsTool() actool.CoreTool

func (*ToolSet) ListWorkerTracesTool

func (t *ToolSet) ListWorkerTracesTool() actool.CoreTool

func (*ToolSet) MainAgentTools

func (t *ToolSet) MainAgentTools() []actool.CoreTool

MainAgentTools returns the human-interface tool set.

func (*ToolSet) NodeDetailTool

func (t *ToolSet) NodeDetailTool() actool.CoreTool

func (*ToolSet) PlannerTools

func (t *ToolSet) PlannerTools() []actool.CoreTool

PlannerTools is the read + intent-generation + goal-judgement tool set.

func (*ToolSet) ReportFindingTool

func (t *ToolSet) ReportFindingTool() actool.CoreTool

func (*ToolSet) SearchWorkerTracesTool

func (t *ToolSet) SearchWorkerTracesTool() actool.CoreTool

func (*ToolSet) SetAssetStore

func (t *ToolSet) SetAssetStore(as *db.AssetStore, cs *db.CompanyStore)

SetAssetStore wires the asset store and company store onto this ToolSet so the insert_assets, add_company_scope, and list_assets tools are active.

func (*ToolSet) SetCoverageEnabled

func (t *ToolSet) SetCoverageEnabled(enabled bool)

SetCoverageEnabled records whether this task has the asset-coverage feature on (default enabled). Passing false makes graphOverviewData omit the coverage block and DropCoverageTools filter the two coverage-only tools out of the agent's tool list. It does NOT stop scope accumulation: insertAssets' auto-scope hook runs either way, because task_scope is the task's range boundary (the filter basis for asset queries), not merely a coverage denominator.

func (*ToolSet) SetEnrich

func (t *ToolSet) SetEnrich(e EnrichTrigger)

SetEnrich wires the async enrichment engine (DNS/HTTP auto-completion).

func (*ToolSet) SetFindingRecorder

func (t *ToolSet) SetFindingRecorder(r FindingRecorder)

func (*ToolSet) SetNotify

func (t *ToolSet) SetNotify(fn func())

SetNotify wires the planner-wake callback (see ToolSet.notify). Set by callers that hold the task handle (main-agent chat, cross-task orchestration).

func (*ToolSet) SetNotifyFinding

func (t *ToolSet) SetNotifyFinding(fn func(int64, string))

SetNotifyFinding wires the finding-wake callback (see ToolSet.notifyFinding).

func (*ToolSet) SetNotifyGoal

func (t *ToolSet) SetNotifyGoal(fn func([]string))

SetNotifyGoal wires the goal-add trigger callback (see ToolSet.notifyGoal). Set only by the main-agent chat, so runtime-added goals are announced to the planner by name.

func (*ToolSet) SetNotifyHint

func (t *ToolSet) SetNotifyHint(fn func([]string))

SetNotifyHint wires the hint-add trigger callback (see ToolSet.notifyHint). Set by the main-agent chat and cross-task orchestration, so a runtime-added hint fires a planner round announced by name instead of a bare wake.

func (*ToolSet) SetOwnerNode

func (t *ToolSet) SetOwnerNode(id int64)

SetOwnerNode sets the exploration node that writes anchor to (worker: its intent node; planner/main: the begin root). Assets created/referenced while ownerNode is set are anchored to it as lineage (not visibility).

func (*ToolSet) SetResumeTask

func (t *ToolSet) SetResumeTask(fn func())

SetResumeTask wires the task-revive callback (see ToolSet.resumeTask). Set only by the main-agent chat, so runtime-added goals can pull a finished task back to running.

func (*ToolSet) SetTaskID

func (t *ToolSet) SetTaskID(id int64)

SetTaskID sets the PG task id on this ToolSet so that report_finding can dual-write to the standalone findings table (which survives task deletion).

func (*ToolSet) WorkerTools

func (t *ToolSet) WorkerTools() []actool.CoreTool

WorkerTools returns the tool set for a work agent.

func (*ToolSet) Writes

func (t *ToolSet) Writes() WriteCounts

Writes reports what this run wrote back, split by node kind (so the engine can tell "explored but persisted nothing" apart from a completed intent, and log an honest breakdown instead of calling assets/findings "facts").

type TriggerEvent

type TriggerEvent struct {
	Kind     string
	IntentID int64
	Detail   string
	Summary  string   // For cancelled: summary captured before deletion, since a hard-deleted node cannot be queried.
	Goals    []string // For goal: one or more new goal texts from this set_goals call.
	OldGoal  string   // For goal_edited: previous goal text.
	NewGoal  string   // For goal_edited: updated goal text.
	Hints    []string // For hint: one or more new hint texts from this add_hint call.
}

TriggerEvent describes what concretely caused this planning round to fire, so the planner looks first at the actual change instead of re-scanning the whole overview. Kind:

"done"    — a worker finished intent IntentID (its output conclusion is fetched).

"finding": a worker reported a finding for IntentID; Detail is its summary. "goal": the human added one or more goals through the main agent's set_goals. Goals contains this call's new goal texts; set_goals supports batching. "goal_deleted": the human removed a goal in overview management; Detail is the removed text. "goal_edited": the human edited a goal in overview management; OldGoal -> NewGoal. "cancelled": the human deleted IntentID; Detail is the deletion reason. The intent is

stopped (not deleted) and the reason is attached to it as a fact.

type WebSearchOpts

type WebSearchOpts struct {
	DeepSeekMeter DeepSeekSearchMeter
	// PolicyResolver reads the live LLM egress policy; it is independent of the selected backend.
	PolicyResolver func() (bool, []string)
	Enabled        bool
	Backend        string
	BraveKey       string
	TavilyKey      string
	Proxy          string
	// DeepSeek credentials come from the active LLM profile's official Anthropic-format
	// endpoint, not a separate setting, and change with the active profile.
	DeepSeekBaseURL string
	DeepSeekAPIKey  string
	DeepSeekModel   string
}

Worker is an LLM work agent (docs §4.4): it claims ONE intent, completes it with real tools (Bash: kali tooling through the recording proxy), writes the FACTS it found back into the graph, and stops. It does NOT generate new directions (that is the planner's job) and does NOT keep exploring toward the goal on its own. Multiple workers run concurrently as goroutines. WebSearchOpts is the web-search backend selection the server pushes into each agent (planner/worker/main). Enabled=false leaves the web_search tool off. Backend is "ddgs" (no key), "brave-free" (BraveKey required), "tavily" (TavilyKey required), or "deepseek" (DeepSeek* required, filled from the active LLM profile). It maps directly onto agentcore.Options. Proxy is a dedicated egress proxy for the search request (http/https/socks5), independent of the traffic-recording MITM proxy — set it when the search endpoint is only reachable via a VPN/SOCKS proxy. Empty = direct.

DeepSeek differs from other backends: it has no standalone search API. Search is available only through its Anthropic-compatible messages endpoint's server web_search_20250305 tool, consuming a model call and making requests on DeepSeek's servers, outside the local proxy and traffic capture.

type Worker

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

func NewWorker

func NewWorker(prov llm.Provider, model, workDir string, tx *transcript.Store, window, maxTurns int, extra ...actool.CoreTool) *Worker

func (*Worker) Execute

func (w *Worker) Execute(ctx context.Context, name string, taskID int64, as *db.AssetStore, ts *db.ExplorationStore, intent *db.Node, hooks harness.HookRunner, emit func(db.Activity), enr EnrichTrigger, notifyFinding func(int64, string)) (harness.TerminalReason, WriteCounts, error)

Execute runs one intent. hooks (the per-task Guard) gates every tool call; may be nil. emit, if non-nil, receives one ActivityRecord per execution step. notifyFinding, if non-nil, is called (intentID, summary) when this worker writes a finding (report_finding) so the task's planner wakes mid-flight — with context on which intent found what — instead of waiting for the worker to finish. Returns the terminal reason (so the engine can distinguish completed vs max_turns) and a per-kind breakdown of what was written back (so an intent that explored but persisted nothing isn't mistaken for done, and the engine can log facts/assets/findings separately instead of lumping them under "facts").

func (*Worker) ExecuteWithMessage

func (w *Worker) ExecuteWithMessage(ctx context.Context, name string, taskID int64, as *db.AssetStore, ts *db.ExplorationStore, intent *db.Node, hooks harness.HookRunner, emit func(db.Activity), enr EnrichTrigger, notifyFinding func(int64, string), requestID, message string) (harness.TerminalReason, WriteCounts, error)

ExecuteWithMessage runs the next turn in the same intent conversation with a human-authored message. The HTTP handler does not edit the transcript; agentcore records the message as a normal user turn when this Worker starts. This keeps Worker continuation identical to the regular agent chat flow.

func (*Worker) SetCompactionWindowResolver

func (w *Worker) SetCompactionWindowResolver(fn func() int)

func (*Worker) SetConstraintInject

func (w *Worker) SetConstraintInject(fn func() bool)

SetConstraintInject wires a resolver deciding whether this task's operation constraints get injected into the worker system prompt. nil = inject (default).

func (*Worker) SetFindingRecorder

func (w *Worker) SetFindingRecorder(r FindingRecorder)

func (*Worker) SetMaxTokens

func (w *Worker) SetMaxTokens(fn func() int)

SetMaxTokens wires a resolver for the per-reply output cap. nil/unset or 0 = send no cap and let the endpoint decide. Read per run, like nonStreaming.

func (*Worker) SetNativeOllamaResolver

func (w *Worker) SetNativeOllamaResolver(fn func() bool)

SetNativeOllamaResolver resolves whether the current run uses native Ollama.

func (*Worker) SetNoaEnabled

func (w *Worker) SetNoaEnabled(fn func() bool)

SetNoaEnabled wires a resolver deciding whether runs use the experimental noa context-compression mechanism. nil/unset = off (built-in compaction). Read per run so the settings toggle takes effect without rebuilding the agent.

func (*Worker) SetNonStreaming

func (w *Worker) SetNonStreaming(fn func() bool)

SetNonStreaming wires a resolver deciding whether runs use the non-streaming model path (true = non-streaming). nil/unset = streaming (default). Read per run so a profile or task-chain toggle takes effect without rebuilding.

func (*Worker) SetProxy

func (w *Worker) SetProxy(addr, caCert string)

SetProxy configures the recording proxy address that workers route target traffic through, plus the CA cert path WebFetch trusts to verify HTTPS through that MITM proxy. Empty addr disables the hint.

func (*Worker) SetRunTimeout

func (w *Worker) SetRunTimeout(run time.Duration)

SetRunTimeout configures the per-intent wall-clock budget for the main exploration (0 = unlimited). When it fires, the SDK settlement phase still runs so facts are never lost to a timeout. Safe to call before Execute.

func (*Worker) SetWebSearch

func (w *Worker) SetWebSearch(o WebSearchOpts)

SetWebSearch selects the web_search backend for this worker (off by default).

type WorkerVars

type WorkerVars struct{ ProxyAddr, WorkerName, DataDir, Now string }

type WriteCounts

type WriteCounts struct {
	Facts    int
	Assets   int
	Findings int
}

WriteCounts breaks down what a worker persisted this run, by node kind, so the engine can log an accurate "wrote back" summary instead of lumping assets and findings under "facts" (record_fact → Facts, insert_assets → Assets, report_finding → Findings; each element of a batch counts once).

func (WriteCounts) String

func (w WriteCounts) String() string

String renders per-kind counts for logs, such as facts 1, assets 25, findings 0.

func (WriteCounts) Total

func (w WriteCounts) Total() int

Total is every node persisted this run, regardless of kind — the "explored but persisted nothing" signal (Total == 0).

Jump to

Keyboard shortcuts

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