agenttypes

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package agenttypes defines shared data types used across the agent subsystem. It is the leaf of the dependency DAG — subpackages import agenttypes, not root agent.

Index

Constants

View Source
const (
	AutopilotPhaseAudit     = "audit"
	AutopilotPhaseAutopilot = "autopilot"
)

AutopilotPhase constants for the agent autopilot mode console output.

View Source
const (
	SwarmPhaseNormalize       = "native-normalize"
	SwarmPhaseAuth            = "auth"
	SwarmPhaseSourceAnalysis  = "source-analysis"
	SwarmPhaseCodeAudit       = "code-audit"
	SwarmPhaseDiscover        = "native-discover"
	SwarmPhaseRecon           = "native-recon"
	SwarmPhasePlan            = "plan"
	SwarmPhaseExtension       = "native-extension"
	SwarmPhaseScan            = "native-scan"
	SwarmPhaseDiscoverReentry = "native-discover-reentry"
	SwarmPhaseReplanOnEmpty   = "replan-on-empty"
	SwarmPhaseTriage          = "triage"
	SwarmPhaseRescan          = "native-rescan"
)

SwarmPhase constants for the agent swarm mode. Phases prefixed with "native-" are executed by native Go code without AI agent involvement.

View Source
const (
	ScanStrategyLite     = "lite"
	ScanStrategyBalanced = "balanced"
	ScanStrategyDeep     = "deep"
)

Scanning strategy names accepted by runner.LaunchParams.ScanningStrategy and the run_native_scan tool's enum. Centralized here so preset wiring and tests stay in lockstep with the runner's expectations.

View Source
const (
	TriageVerdictConfirmed     = "confirmed"
	TriageVerdictFalsePositive = "false_positive"
)

Triage confirm verdict constants. The parser normalises common aliases ("fp", "true-positive", etc.) to these canonical values.

View Source
const (
	TriageConfirmTemplateID   = "agent-triage-confirm"
	TriageConfirmOutputSchema = "triage_confirm"
)

TriageConfirmTemplateID is the prompt template the triage CLI loads. TriageConfirmOutputSchema is the schema string in that template's frontmatter.

View Source
const (
	EvidenceStatusExploited     = "exploited"
	EvidenceStatusBlocked       = "blocked"
	EvidenceStatusFalsePositive = "false_positive"
)

Evidence status values.

View Source
const (
	RecordSourceDiscoverReentry = "swarm-discover-reentry"
)

Record source labels used in HTTPRecord.Source to attribute where a record came from. Stable values used in DB rows and JSON exports.

Variables

View Source
var AuditDriverPresets = map[Intensity]AuditDriverIntensityPreset{
	IntensityQuick: {
		Mode:        "lite",
		Modes:       []string{"lite"},
		Timeout:     1 * time.Hour,
		CommitDepth: 1,
	},
	IntensityBalanced: {
		Mode:        "balanced",
		Modes:       []string{"balanced"},
		Timeout:     6 * time.Hour,
		CommitDepth: 1,
	},
	IntensityDeep: {
		Mode:        "deep",
		Modes:       []string{"deep", "confirm"},
		Timeout:     12 * time.Hour,
		CommitDepth: 0,
	},
}

AuditDriverPresets maps intensity levels to audit preset values.

deep intensity chains [deep, confirm]: a full audit followed by a confirmation pass that boots the target and executes PoCs against the findings deep surfaced. quick/balanced stay single-mode. Mode is the first element of Modes so single-mode consumers keep working unchanged.

View Source
var AutopilotPresets = map[Intensity]AutopilotIntensityPreset{
	IntensityQuick: {
		MaxCommands:        150,
		Timeout:            1 * time.Hour,
		AuditDriverMode:    "lite",
		Browser:            true,
		NativeScanStrategy: ScanStrategyLite,
	},
	IntensityBalanced: {
		MaxCommands:        750,
		Timeout:            6 * time.Hour,
		AuditDriverMode:    "balanced",
		Browser:            true,
		NativeScanStrategy: ScanStrategyBalanced,
	},
	IntensityDeep: {
		MaxCommands:        3000,
		Timeout:            12 * time.Hour,
		AuditDriverMode:    "deep",
		Browser:            true,
		NativeScanStrategy: ScanStrategyDeep,
	},
}

AutopilotPresets maps intensity levels to autopilot preset values.

View Source
var NativeScanIntensityProfiles = map[Intensity]string{
	IntensityQuick:    "quick",
	IntensityBalanced: "standard",
	IntensityDeep:     "full",
}

NativeScanIntensityProfiles maps intensity levels to scanning profile names for native (non-agent) scan mode.

View Source
var SwarmPhaseAliases = map[string]string{
	"normalize": SwarmPhaseNormalize,
	"discover":  SwarmPhaseDiscover,
	"recon":     SwarmPhaseRecon,
	"extension": SwarmPhaseExtension,
	"scan":      SwarmPhaseScan,
	"rescan":    SwarmPhaseRescan,
}

SwarmPhaseAliases maps legacy phase names to their current constant values. This provides backward compatibility for checkpoints, --start-from, and --skip flags.

View Source
var SwarmPresets = map[Intensity]SwarmIntensityPreset{
	IntensityQuick: {
		Discover:         true,
		CodeAudit:        false,
		Triage:           false,
		MaxIterations:    1,
		Audit:            "lite",
		MaxPlanRecords:   10,
		MasterBatchSize:  5,
		BatchConcurrency: 2,
		ProbeConcurrency: 15,
		Browser:          true,
		Auth:             false,
		SwarmDuration:    2 * time.Hour,
	},
	IntensityBalanced: {
		Discover:         true,
		CodeAudit:        true,
		Triage:           true,
		MaxIterations:    3,
		Audit:            "balanced",
		MaxPlanRecords:   25,
		MasterBatchSize:  5,
		BatchConcurrency: 3,
		ProbeConcurrency: 10,
		Browser:          true,
		Auth:             false,
		SwarmDuration:    12 * time.Hour,
	},
	IntensityDeep: {
		Discover:         true,
		CodeAudit:        true,
		Triage:           true,
		MaxIterations:    5,
		Audit:            "deep",
		MaxPlanRecords:   50,
		MasterBatchSize:  10,
		BatchConcurrency: 5,
		ProbeConcurrency: 5,
		Browser:          true,
		Auth:             true,
		SwarmDuration:    24 * time.Hour,
	},
}

SwarmPresets maps intensity levels to swarm preset values.

Functions

func ExpandHome

func ExpandHome(path string) string

ExpandHome expands ~ prefix to the user's home directory.

func NormalizeSwarmPhase

func NormalizeSwarmPhase(phase string) string

NormalizeSwarmPhase resolves a phase name, accepting both current and legacy names.

func PhaseSkipped

func PhaseSkipped(skipPhases []string, phase string) bool

PhaseSkipped returns true if the given phase is in the skip list.

Types

type AgentExpectResponse

type AgentExpectResponse struct {
	Status       []int  `json:"status,omitempty"`
	BodyContains string `json:"body_contains,omitempty"`
}

AgentExpectResponse defines expected response constraints for validation.

func (*AgentExpectResponse) UnmarshalJSON

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

UnmarshalJSON implements lenient parsing for AgentExpectResponse. Handles: status as ["200","201"], status as single int/string, body_contains as any type.

type AgentExtensionsOutput

type AgentExtensionsOutput struct {
	Extensions []GeneratedExtension `json:"extensions"`
	// These fields may appear in the same JSON block (from swarm plan output)
	QuickChecks []QuickCheck `json:"quick_checks,omitempty"`
	Snippets    []Snippet    `json:"snippets,omitempty"`
}

AgentExtensionsOutput wraps a list of extensions for JSON parsing.

type AgentExtractRule

type AgentExtractRule struct {
	Source  string `json:"source"`             // "cookie", "json", "header", "regex"
	Name    string `json:"name,omitempty"`     // cookie name or header name
	Path    string `json:"path,omitempty"`     // JSONPath for json source
	ApplyAs string `json:"apply_as,omitempty"` // e.g. "Authorization: Bearer {value}"
	Pattern string `json:"pattern,omitempty"`  // regex pattern (source: "regex")
	Group   int    `json:"group,omitempty"`    // capture group index (source: "regex")
}

AgentExtractRule defines how to extract an auth token from a login response.

func (*AgentExtractRule) UnmarshalJSON

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

UnmarshalJSON implements lenient parsing for AgentExtractRule. Handles: group as string "1", all string fields as any type.

type AgentFinding

type AgentFinding struct {
	Title       string   `json:"title"`
	Description string   `json:"description"`
	Severity    string   `json:"severity"`
	Confidence  string   `json:"confidence,omitempty"`
	File        string   `json:"file,omitempty"`
	Line        int      `json:"line,omitempty"`
	Snippet     string   `json:"snippet,omitempty"`
	CWE         string   `json:"cwe,omitempty"`
	Tags        []string `json:"tags,omitempty"`
}

AgentFinding represents a single finding reported by an AI agent.

func (*AgentFinding) UnmarshalJSON

func (f *AgentFinding) UnmarshalJSON(data []byte) error

UnmarshalJSON implements lenient parsing for AgentFinding. Handles: line as string ("42"), tags as single string, severity as int.

type AgentFindingsOutput

type AgentFindingsOutput struct {
	Findings []AgentFinding `json:"findings"`
}

AgentFindingsOutput is the expected JSON output for findings-type templates.

type AgentHTTPRecord

type AgentHTTPRecord struct {
	Method  string            `json:"method"`
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"`
	Body    string            `json:"body,omitempty"`
	Notes   string            `json:"notes,omitempty"`
}

AgentHTTPRecord represents an HTTP request/response pair reported by an AI agent.

func (*AgentHTTPRecord) UnmarshalJSON

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

UnmarshalJSON implements custom unmarshaling that tolerates the body field being a JSON object/array instead of a string. LLMs frequently output "body": {"key":"value"} instead of "body": "{\"key\":\"value\"}". This detects non-string body values and re-serializes them to a JSON string.

type AgentHTTPRecordsOutput

type AgentHTTPRecordsOutput struct {
	HTTPRecords []AgentHTTPRecord `json:"http_records"`
}

AgentHTTPRecordsOutput is the expected JSON output for http_records-type templates.

type AgentLoginFlow

type AgentLoginFlow struct {
	URL         string             `json:"url"`
	Method      string             `json:"method"`
	ContentType string             `json:"content_type,omitempty"`
	Body        string             `json:"body,omitempty"`
	Extract     []AgentExtractRule `json:"extract,omitempty"`
	// Shorthand: type + token_path expand into extract rules.
	Type      string `json:"type,omitempty"`       // "bearer" or "cookie"
	TokenPath string `json:"token_path,omitempty"` // JSONPath for bearer type
	// Response validation.
	Expect *AgentExpectResponse `json:"expect,omitempty"`
}

AgentLoginFlow defines a login flow discovered from source code analysis.

type AgentSessionConfig

type AgentSessionConfig struct {
	Sessions []AgentSessionEntry `json:"sessions"`
}

AgentSessionConfig holds session definitions generated by the source analysis agent.

type AgentSessionEntry

type AgentSessionEntry struct {
	Name    string            `json:"name"`
	Role    string            `json:"role"`              // "primary" or "compare"
	Headers map[string]string `json:"headers,omitempty"` // static auth headers
	Login   *AgentLoginFlow   `json:"login,omitempty"`   // login-based auth
}

AgentSessionEntry represents a single session identity for authenticated scanning.

type AppIntent

type AppIntent struct {
	Target          string                `json:"target,omitempty"`            // URL if mentioned
	SourcePath      string                `json:"source_path,omitempty"`       // filesystem path if mentioned
	Focus           string                `json:"focus,omitempty"`             // vulnerability focus if mentioned
	Instruction     string                `json:"instruction,omitempty"`       // leftover context
	Discover        bool                  `json:"discover,omitempty"`          // implied by target + source combo
	CodeAudit       bool                  `json:"code_audit,omitempty"`        // implied by source-only
	Audit           string                `json:"audit,omitempty"`             // "lite", "balanced", "deep", or "" (background vigolium-audit)
	Piolium         string                `json:"piolium,omitempty"`           // piolium mode: "lite", "balanced", "deep", "longshot", etc., or "" (auto-pick / unset)
	Diff            string                `json:"diff,omitempty"`              // PR URL, git ref range (main...branch), or HEAD~N
	Files           []string              `json:"files,omitempty"`             // specific files to focus on (relative to source)
	Browser         bool                  `json:"browser,omitempty"`           // enable browser-based interaction
	MaxCommands     int                   `json:"max_commands,omitempty"`      // command limit override
	Timeout         string                `json:"timeout,omitempty"`           // duration string (e.g. "2h", "30m")
	Intensity       string                `json:"intensity,omitempty"`         // "quick", "balanced", "deep"
	Credentials     string                `json:"credentials,omitempty"`       // compact credential hint, e.g. "admin/admin123"
	CredentialSets  []IntentCredentialSet `json:"credential_sets,omitempty"`   // structured roles/accounts
	AuthRequired    bool                  `json:"auth_required,omitempty"`     // explicit auth intent from prompt
	RequiresBrowser bool                  `json:"requires_browser,omitempty"`  // explicit browser requirement from prompt
	BrowserStartURL string                `json:"browser_start_url,omitempty"` // explicit login/start URL
	FocusRoutes     []string              `json:"focus_routes,omitempty"`      // explicit auth/browser focus routes
}

AppIntent holds parameters for a single application to scan.

type AttackPlan

type AttackPlan struct {
	ModuleTags []string          `json:"module_tags,omitempty"`
	ModuleIDs  []string          `json:"module_ids,omitempty"`
	FocusAreas []string          `json:"focus_areas,omitempty"`
	SkipPaths  []string          `json:"skip_paths,omitempty"`
	Endpoints  []PlannedEndpoint `json:"endpoints,omitempty"`
	Notes      string            `json:"notes,omitempty"`
}

AttackPlan is the structured output from the plan agent checkpoint (phase 2). The agent analyzes discovery results and produces a scanning strategy.

type AuditAgentConfig

type AuditAgentConfig struct {
	// Harness selects the audit harness flavor. Zero-valued (empty Name)
	// is treated as the audit harness for backward compatibility.
	Harness HarnessSpec

	Mode        string // "deep", "balanced", "lite", "merge", "revisit", etc.
	Platform    string // "audit" (embedded vigolium-audit binary) or "pi" (piolium)
	SourcePath  string
	SessionDir  string
	ProjectUUID string
	ScanUUID    string

	// Modes is the mode chain for this run. Empty (or single-element)
	// behaves exactly like the legacy single-Mode path. With >1 element:
	//   - audit: rendered as `--modes a,b,c` (audit owns the sequential
	//     execution, stop-on-non-complete, and aggregate cost cap).
	//   - piolium: the chain is driven by PioliumChainScanner, which runs
	//     one `pi` subprocess per supported mode in the same source dir and
	//     collapses them into a single aggregated AgenticScan row.
	// EffectiveModes() normalizes this to always return at least one mode.
	Modes []string

	// ForceAgenticScanUUID, when non-empty, overrides the UUID the runner
	// would otherwise derive. Set by PioliumChainScanner so every per-mode
	// inner runner imports its findings under the one aggregated child row.
	ForceAgenticScanUUID string

	// SuppressAgenticScanRow makes the runner skip AgenticScan row
	// create/progress/finalize bookkeeping while STILL importing findings
	// (under the shared UUID) and computing the cost summary. Used for the
	// per-mode inner runners of a piolium chain — the chain scanner owns
	// the single aggregated row instead.
	SuppressAgenticScanRow bool

	// KeepSourceOutputDir suppresses the per-run cleanup of
	// <source>/<harness>/ after the subprocess exits. The piolium chain
	// sets it on every mode except the last so a later confirm/revisit
	// mode can read the prior mode's on-disk audit-state.json.
	KeepSourceOutputDir bool

	// KeepRaw maps to vigolium-audit's `--keep-raw` flag: opt out of the
	// deep/confirm auto-prune of raw scanner output, draft findings, and
	// intermediate workspaces so the operator can review them under
	// <source>/vigolium-results/ (and the synced session copy). Audit-only;
	// ignored for the piolium harness.
	KeepRaw bool

	// AuditDriverInvocation carries the `--agent` + auth-override args the
	// vigolium-audit binary needs. Resolved by callers from OliumConfig (or a
	// CLI override) and passed through to buildAuditAgentCommand.
	// Empty Agent falls back to claude (vigolium-audit's own default).
	// Ignored for the piolium harness.
	AuditDriverInvocation AuditDriverInvocation

	// ParentAgenticScanUUID is the autopilot/swarm AgenticScan UUID that spawned this audit.
	ParentAgenticScanUUID string

	SyncInterval time.Duration // how often to sync audit-state.json (default: 30s)
	StreamWriter io.Writer     // optional: stream audit output in real-time

	// Stream enables Claude's stream-json output format and live rendering via
	// the claudestream package. Only meaningful for the "claude" platform and
	// when StreamWriter is non-nil. Other platforms ignore this flag.
	Stream bool

	// ShowThinking opts into rendering the agent's internal thinking blocks
	// (audit NDJSON `thinking` events) to the live stream. Off by default
	// because thinking is very noisy and chains often hundreds of blocks
	// per phase. The CLI flag `--show-thinking` (and the equivalent REST
	// field) sets this.
	ShowThinking bool

	// CommitScanLimit caps deep-mode commit archaeology to at most N commits.
	// 0 keeps the upstream default (500).
	CommitScanLimit int
	// CommitScanSince caps deep-mode commit archaeology to commits since this
	// git date expression. Empty keeps the upstream default ("60 days ago").
	CommitScanSince string

	// AdditionalArgs are appended verbatim to the agent process argv after
	// the harness-specific args. Used by piolium for --plm-* passthroughs
	// (e.g. --plm-phase-retries, --plm-longshot-limit). Ignored for audit.
	AdditionalArgs []string

	// PiProvider and PiModel, when set, are passed to `pi` as
	// `--provider <name> --model <id>` so a single audit run can override
	// the user's defaultProvider/defaultModel from ~/.pi/agent/settings.json.
	// Only consumed by the pi platform; ignored for audit.
	PiProvider string
	PiModel    string

	// StreamDecoder, when non-nil, decodes the agent process's stdout as
	// line-oriented JSON and renders it to render. Raw lines are mirrored
	// to raw (typically <sessionDir>/audit-stream.jsonl) for replay.
	// Claude has a built-in default; piolium passes pistream.Stream.
	StreamDecoder func(stream io.Reader, render io.Writer, raw io.Writer) error

	// AuthOverride carries per-run BYOK creds (api key, oauth token, or
	// codex cred file) supplied via the audit CLI flags or REST body. It
	// has already been folded into AuditDriverInvocation by the resolver, so
	// the audit launch path does NOT consult this field directly. The
	// piolium launcher reads it to (a) inject ANTHROPIC_API_KEY /
	// CLAUDE_CODE_OAUTH_TOKEN / OPENAI_API_KEY env on the pi subprocess
	// and (b) stage a codex cred file at <pi-agent-dir>/auth.json for
	// the duration of the run. Empty = no override (inherit ambient
	// auth from agent.olium.* / pi settings).
	AuthOverride AuthOverride
}

AuditAgentConfig configures a background audit- or piolium-flavored audit run.

func (AuditAgentConfig) EffectiveModes

func (c AuditAgentConfig) EffectiveModes() []string

EffectiveModes normalizes the run's mode chain. It always returns at least one mode: cfg.Modes when set, otherwise the single cfg.Mode (and "lite" as the last-resort default, matching the legacy behavior).

type AuditAgentStatus

type AuditAgentStatus struct {
	Running         bool   `json:"running"`
	Status          string `json:"status"`
	Mode            string `json:"mode"`
	Phase           string `json:"current_phase"`
	CompletedPhases int    `json:"completed_phases"`
	TotalPhases     int    `json:"total_phases"`
}

AuditAgentStatus summarizes the current state of the background audit.

type AuditDriverAgent

type AuditDriverAgent string

AuditDriverAgent identifies the underlying CLI/SDK adapter the embedded vigolium-audit binary will drive on this run. Maps to vigolium-audit's `--agent` (claude|codex). Empty falls back to claude (vigolium-audit default).

const (
	AuditDriverAgentClaude AuditDriverAgent = "claude"
	AuditDriverAgentCodex  AuditDriverAgent = "codex"
)

type AuditDriverAuthFlags

type AuditDriverAuthFlags struct {
	APIKey        string // --api-key
	OAuthToken    string // --oauth-token
	OAuthCredFile string // --oauth-cred-file
}

AuditDriverAuthFlags are the one-shot auth overrides vigolium-audit accepts. Empty fields mean "inherit ambient auth" — audit falls back to the agent CLI's standard credential store.

type AuditDriverIntensityPreset

type AuditDriverIntensityPreset struct {
	Mode        string
	Modes       []string
	Timeout     time.Duration
	CommitDepth int // git clone --depth (0 = full history, used for deep commit archaeology)
}

AuditDriverIntensityPreset holds the preset values for the foreground audit audit (vigolium agent audit / POST /api/agent/run/audit) at a given intensity. Mode maps onto the audit harness mode string (lite/balanced/deep). Modes carries the full mode chain — a single-element slice for the simple presets, multi-element for chained presets (deep = [deep, confirm]). Mode stays populated with Modes[0] for the many single-mode consumers (settings.yaml audit config, piolium ResolvePioliumAuditConfig) that do not chain. Timeout is only consumed by the API path; the CLI audit command runs as a foreground process and takes no overall timeout flag.

type AuditDriverInvocation

type AuditDriverInvocation struct {
	Agent AuditDriverAgent
	Auth  AuditDriverAuthFlags
}

AuditDriverInvocation collects the agent + auth tuple the audit launcher needs to compose vigolium-audit invocation args. Returned by ResolveAuditDriverInvocation so each entry point shares one resolution path.

func (AuditDriverInvocation) Args

func (i AuditDriverInvocation) Args() []string

Args renders the invocation as the slice of CLI flags appended to `audit run`. The agent flag is always emitted (defaulting to claude); auth flags are emitted only when non-empty.

type AuthOverride

type AuthOverride struct {
	APIKey        string
	OAuthToken    string
	OAuthCredFile string
	Agent         string
}

AuthOverride is a per-run BYOK bundle the operator passes via the `vigolium agent audit` CLI flags or the /api/agent/run/audit body. At most one of APIKey / OAuthToken / OAuthCredFile should be set (validated centrally; see agent.ValidateAuthOverride). Empty struct = inherit agent.olium.* config, which is the existing pre-BYOK behavior.

Same struct flows to both audit drivers:

  • audit: the resolver folds it into AuditDriverAuthFlags so vigolium-audit gets --api-key / --oauth-token / --oauth-cred-file directly.
  • piolium: vigolium maps it to env vars on the pi subprocess (pi has no equivalent CLI flags), and stages oauth_cred_file at <pi-agent-dir>/auth.json with backup-and-restore for codex.

Agent is the resolved audit-style identity ("claude" or "codex") this auth applies to. The CLI/REST entry point fills it in from --provider / `agent` (or, when those are empty, from agent.olium.provider). It exists on AuthOverride rather than being re-derived inside each driver so both audit and piolium see the same answer to "is this a claude key or a codex key?".

func (AuthOverride) IsZero

func (o AuthOverride) IsZero() bool

IsZero reports whether no override fields are set. Used by callers to short-circuit the resolver and keep the existing inherit-config path. Agent alone is not significant — it carries no secret on its own and a bare Agent string with no key fields means "no override".

type AutopilotIntensityPreset

type AutopilotIntensityPreset struct {
	MaxCommands     int
	Timeout         time.Duration
	AuditDriverMode string
	Browser         bool
	// NativeScanStrategy is the scanning_strategy passed to the pre-scan
	// kicked off in target-only autopilot runs (no --source). Maps onto the
	// runner.LaunchParams.ScanningStrategy enum: "lite"|"balanced"|"deep".
	// The pre-scan seeds http_records and findings into the DB before the
	// operator agent loop starts, so the agent has real traffic to reason
	// about and richer raw material for custom JS extensions.
	NativeScanStrategy string
	// NoPrescan disables the autopilot pre-scan entirely. Default false;
	// flipped true via the --no-prescan flag for operators who already ran
	// a scan or want a cold-start blackbox session.
	NoPrescan bool
}

AutopilotIntensityPreset holds the preset values for autopilot at a given intensity.

type AutopilotPipelineResult

type AutopilotPipelineResult struct {
	FindingsCount         int
	FindingsSaved         int
	FindingsBySeverity    map[string]int
	OperatorFindingsCount int // findings reported by the autonomous operator via report_finding
	VerifiedFindingCount  int
	Degraded              bool
	Warnings              []string
	BrowserDecision       string
	ArtifactsDir          string
	Duration              time.Duration
	SessionDir            string
	// Reentries counts how many post-halt coverage-verify re-prompts fired.
	Reentries int
}

AutopilotPipelineResult holds the outcome of an autopilot pipeline run.

type BatchProvenance

type BatchProvenance struct {
	ModuleTags map[string]int `json:"module_tags,omitempty"` // tag -> batch number
	ModuleIDs  map[string]int `json:"module_ids,omitempty"`  // id -> batch number
	Extensions map[string]int `json:"extensions,omitempty"`  // filename -> batch number
	FocusAreas map[string]int `json:"focus_areas,omitempty"` // focus area -> batch number
}

BatchProvenance tracks which batch contributed each item to a merged plan.

type DiffContext

type DiffContext struct {
	ChangedFiles []string `json:"changed_files"`           // changed file paths relative to source root
	PatchContent string   `json:"patch_content,omitempty"` // unified diff patch content
	DiffRef      string   `json:"diff_ref"`                // original ref/URL for display (e.g. "origin/main...feature")
}

DiffContext holds parsed diff information for focused scanning. When present, the agent and vigolium-audit prioritize the changed files.

type ExploitationEvidence

type ExploitationEvidence struct {
	FindingRef  string   `json:"finding_ref"`
	Status      string   `json:"status"` // "exploited", "blocked", "false_positive"
	VulnClass   string   `json:"vuln_class"`
	Payload     string   `json:"payload"`
	Request     string   `json:"request"`
	Response    string   `json:"response"`
	Impact      string   `json:"impact"`
	Screenshots []string `json:"screenshots,omitempty"`
	Confidence  string   `json:"confidence"` // "proven", "likely", "unconfirmed"
	Notes       string   `json:"notes,omitempty"`
}

ExploitationEvidence records proof that a finding is exploitable.

type FollowUpScan

type FollowUpScan struct {
	URL        string   `json:"url"`
	Method     string   `json:"method,omitempty"`
	ModuleTags []string `json:"module_tags,omitempty"`
	ModuleIDs  []string `json:"module_ids,omitempty"`
	Rationale  string   `json:"rationale,omitempty"`
	TargetURLs []string `json:"target_urls,omitempty"` // specific URLs to rescan (preserves URL-to-module mapping)
}

FollowUpScan describes a targeted rescan recommended by the triage agent.

type GeneratedExtension

type GeneratedExtension struct {
	Filename string `json:"filename"`
	Code     string `json:"code"`
	Reason   string `json:"reason"`
}

GeneratedExtension represents a JavaScript extension generated by the agent.

type HarnessSpec

type HarnessSpec struct {
	// Name is the harness identifier. "audit" and "piolium" are recognized.
	// An empty Name defaults to audit for backward compatibility.
	Name string
	// SourceFolder is the directory the harness writes under <source>/ during
	// the run (e.g. "audit", "piolium").
	SourceFolder string
	// SessionSubdir is where vigolium syncs the harness output under the
	// session dir (e.g. "vigolium-results", "piolium").
	SessionSubdir string
	// EnvPrefix is the prefix for env vars exported to the agent process
	// (e.g. "ARCHON_", "PIOLIUM_").
	EnvPrefix string
	// DBMode populates database.AgenticScan.Mode (e.g. "audit", "piolium").
	DBMode string
	// DBAgentName populates database.AgenticScan.AgentName (e.g. "vigolium-audit",
	// "piolium").
	DBAgentName string
	// DBInputType populates database.AgenticScan.InputType.
	DBInputType string
	// FindingIDPrefix is the module_id prefix on imported findings (e.g.
	// "audit" → "audit:c1-...", "piolium" → "piolium:c1-...").
	FindingIDPrefix string
	// FindingTag is added to every imported finding's tag list.
	FindingTag string
}

HarnessSpec describes the on-disk layout, slash-command shape, and DB metadata for an audit-flavored audit harness. Audit (claude/codex) and piolium (pi) share the same parser and audit-state.json schema but differ in folder names, slash command, env-var prefix, and DB import metadata.

type InputType

type InputType string

InputType identifies the format of a raw input string.

const (
	InputTypeURL        InputType = "url"
	InputTypeCurl       InputType = "curl"
	InputTypeBurp       InputType = "burp"
	InputTypeRaw        InputType = "raw"
	InputTypeBase64     InputType = "base64"
	InputTypeRecordUUID InputType = "record_uuid"
	InputTypeUnknown    InputType = "unknown"
)

type Intensity

type Intensity string

Intensity represents the scan intensity level.

const (
	IntensityQuick    Intensity = "quick"
	IntensityBalanced Intensity = "balanced"
	IntensityDeep     Intensity = "deep"
)

func ValidateIntensity

func ValidateIntensity(s string) (Intensity, error)

ValidateIntensity normalizes and validates an intensity string. Returns IntensityBalanced for empty input.

type IntentCredentialSet

type IntentCredentialSet struct {
	Name     string `json:"name,omitempty"`
	Role     string `json:"role,omitempty"` // "primary" or "compare"
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
}

IntentCredentialSet represents a role/credential pair extracted from a prompt.

type IntentParseConfig

type IntentParseConfig struct {
	SessionsDir string
}

IntentParseConfig holds optional configuration for intent parsing.

type IntentParseOption

type IntentParseOption func(*IntentParseConfig)

IntentParseOption is a functional option for ParseScanIntent.

func WithSessionsDir

func WithSessionsDir(dir string) IntentParseOption

WithSessionsDir sets the sessions directory used by intent-setup runs (clone targets, docker workdirs, etc.) when the agent must take real side effects before returning an intent.

type InvalidExtension

type InvalidExtension struct {
	Extension GeneratedExtension
	Err       error
}

InvalidExtension holds an extension that failed syntax validation along with the compile error, so it can be passed to the LLM for repair.

type Options

type Options struct {
	// AgentName is a label retained for DB bookkeeping; dispatch goes
	// through olium regardless of value.
	AgentName string

	// Prompt mode: template-based or inline
	PromptTemplate string // template ID (e.g. "security-code-review")
	PromptFile     string // path to a prompt file
	PromptInline   string // inline prompt string
	Stdin          bool   // read prompt from stdin

	// Context
	SourcePath  string   // path to source code repository (--source flag)
	Files       []string // specific files to include (relative to SourcePath)
	Source      string   // source identifier for findings
	Append      string   // extra text appended to the rendered prompt
	Instruction string   // user-provided custom instruction appended to the prompt
	TargetURL   string   // target URL for scanning context
	Hostname    string   // target hostname (derived from TargetURL if empty)

	// Output
	OutputPath  string // write agent output to this file
	DryRun      bool   // render prompt and print it, don't execute agent
	ShowPrompt  bool   // print rendered prompt to stderr before executing
	ScanUUID    string // scan UUID to attach findings to
	ProjectUUID string // project UUID for data scoping
	// EnableBurpBridgeTools exposes only the live read-only Burp search and
	// inspect tools on a fresh agent session. It does not enable replay tools.
	EnableBurpBridgeTools bool      `json:"-"`
	StreamWriter          io.Writer `json:"-"` // when non-nil, agent output is streamed here in real-time
	SessionDir            string    `json:"-"` // session directory for artifacts (transcripts, generated extensions, etc.)
	Verbose               bool      `json:"-"` // when true, the toollog renders a per-tool result preview alongside the standard one-liner

	// Extra template data (injected into {{.Extra}} in prompt templates)
	Extra map[string]string `json:"-"`

	// Retry: when non-nil, retries transient agent failures with exponential backoff.
	Retry *RetryConfig `json:"-"`
}

Options holds parameters for a single agent run.

type PlannedEndpoint

type PlannedEndpoint struct {
	URL       string   `json:"url"`
	Method    string   `json:"method,omitempty"`
	Priority  string   `json:"priority"` // high, medium, low
	Rationale string   `json:"rationale,omitempty"`
	Tags      []string `json:"tags,omitempty"`
}

PlannedEndpoint represents a prioritized endpoint in the attack plan.

type ProgressEvent

type ProgressEvent struct {
	Phase        string `json:"phase"`
	SubPhase     string `json:"sub_phase,omitempty"`
	Current      int    `json:"current,omitempty"`
	Total        int    `json:"total,omitempty"`
	FindingCount int    `json:"finding_count,omitempty"`
	Message      string `json:"message,omitempty"`
}

ProgressEvent reports granular progress during agent scans.

type PromptTemplate

type PromptTemplate struct {
	ID           string   `yaml:"id"`
	Name         string   `yaml:"name"`
	Description  string   `yaml:"description"`
	OutputSchema string   `yaml:"output_schema"` // "findings" or "http_records"
	Variables    []string `yaml:"variables"`
	Body         string   `yaml:"-"`
	Source       string   `yaml:"-"` // "embedded", "user", "config"
}

PromptTemplate represents a parsed prompt template with frontmatter metadata.

type QuickCheck

type QuickCheck struct {
	ID       string              `json:"id"`
	Severity string              `json:"severity,omitempty"` // default: "medium"
	Scan     string              `json:"scan"`               // "per_insertion_point", "per_request", "per_host"
	Payloads []string            `json:"payloads,omitempty"` // for per_insertion_point: payloads to inject
	Requests []QuickCheckRequest `json:"requests,omitempty"` // for per_request/per_host: requests to send
	Match    QuickCheckMatch     `json:"match"`
}

QuickCheck is a declarative shorthand for simple payload-and-match scan checks. The swarm runner auto-generates a full JS extension from each QuickCheck.

type QuickCheckLintIssue

type QuickCheckLintIssue struct {
	Severity string // "error" or "warning"
	Message  string
}

QuickCheckLintIssue represents a single lint finding for a quick check or snippet.

type QuickCheckMatch

type QuickCheckMatch struct {
	BodyContains   string `json:"body_contains,omitempty"`
	BodyRegex      string `json:"body_regex,omitempty"`
	Status         int    `json:"status,omitempty"`
	HeaderContains string `json:"header_contains,omitempty"`
}

QuickCheckMatch defines match conditions for a quick check (OR logic).

func (*QuickCheckMatch) UnmarshalJSON

func (m *QuickCheckMatch) UnmarshalJSON(data []byte) error

UnmarshalJSON implements lenient parsing for QuickCheckMatch. Handles: status as string "200".

type QuickCheckRequest

type QuickCheckRequest struct {
	Method  string            `json:"method"`
	Path    string            `json:"path"`
	Headers map[string]string `json:"headers,omitempty"`
	Body    string            `json:"body,omitempty"`
}

QuickCheckRequest defines a request to send in per_request/per_host quick checks.

type RepairConfig

type RepairConfig struct {
	AgentName    string
	ShowPrompt   bool
	TargetURL    string   // target URL for regeneration context
	FocusAreas   []string // focus areas from the swarm plan
	ModuleTags   []string // module tags from the swarm plan
	ExploreNotes string   // session explore notes for context-aware session repair (optional)
}

RepairConfig holds agent settings for the repair LLM call.

type ResolvedSource

type ResolvedSource struct {
	LocalPath string // absolute local filesystem path to source
}

ResolvedSource holds the result of source path resolution. The --source flag may be a local path, git URL, or archive file; ResolveSource() normalizes all of these into a local directory path.

type Result

type Result struct {
	AgentName      string                 `json:"agent_name"`
	TemplateID     string                 `json:"template_id,omitempty"`
	RawOutput      string                 `json:"raw_output"`
	RenderedPrompt string                 `json:"-"` // rendered prompt sent to agent (not serialized)
	Findings       []AgentFinding         `json:"findings,omitempty"`
	HTTPRecords    []AgentHTTPRecord      `json:"http_records,omitempty"`
	Evidence       []ExploitationEvidence `json:"evidence,omitempty"`
	OutputSchema   string                 `json:"output_schema,omitempty"` // "findings" or "http_records"
	SavedCount     int                    `json:"saved_count"`
	SkippedCount   int                    `json:"skipped_count"`
	DryRun         bool                   `json:"dry_run,omitempty"`

	// TokenUsage carries the cumulative input/output token counts reported by
	// the provider for this single agent call (sum across all turns of the
	// multi-turn loop). Aggregated upward by SwarmRunner / autopilot.
	TokenUsage TokenUsage `json:"token_usage,omitempty"`

	// ParseError, when non-nil, signals that the LLM produced output but
	// the parser couldn't extract structured findings/records from it.
	// Distinguishes "model returned nothing" (RawOutput empty) from
	// "model returned garbage / template regression" (RawOutput populated,
	// ParseError set). Callers should retry, surface a warning, or fail
	// loudly rather than silently dropping the parse failure.
	ParseError string `json:"parse_error,omitempty"`
}

Result holds the outcome of an agent run.

type RetryConfig

type RetryConfig struct {
	MaxRetries    int           // maximum number of retries (default: 2)
	InitialDelay  time.Duration // initial backoff delay (default: 2s)
	MaxDelay      time.Duration // maximum backoff delay (default: 30s)
	BackoffFactor float64       // exponential backoff multiplier (default: 2.0)
}

RetryConfig controls retry behavior for agent calls.

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns sensible defaults for agent call retries.

func (RetryConfig) BackoffDelay

func (rc RetryConfig) BackoffDelay(current time.Duration) time.Duration

BackoffDelay computes the next backoff delay given the current delay.

func (RetryConfig) EffectiveBackoffFactor

func (rc RetryConfig) EffectiveBackoffFactor() float64

EffectiveBackoffFactor returns BackoffFactor or the default if unset.

func (RetryConfig) EffectiveInitialDelay

func (rc RetryConfig) EffectiveInitialDelay() time.Duration

EffectiveInitialDelay returns InitialDelay or the default if unset.

func (RetryConfig) EffectiveMaxDelay

func (rc RetryConfig) EffectiveMaxDelay() time.Duration

EffectiveMaxDelay returns MaxDelay or the default if unset.

func (RetryConfig) EffectiveMaxRetries

func (rc RetryConfig) EffectiveMaxRetries() int

EffectiveMaxRetries returns MaxRetries or the default if unset. Use MaxRetries=-1 to explicitly disable retries (returns 0).

type ScanFunc

type ScanFunc func(ctx context.Context, req ScanRequest) error

ScanFunc is the unified callback signature for running scans.

type ScanIntent

type ScanIntent struct {
	Apps    []AppIntent   `json:"apps"`
	Raw     string        `json:"raw"`
	Cleanup *SetupCleanup `json:"cleanup,omitempty"` // resources created during SDK-based setup
}

ScanIntent holds structured parameters extracted from a natural language scan prompt.

type ScanRequest

type ScanRequest struct {
	ModuleTags   []string // module tags from the agent's plan
	ModuleIDs    []string // explicit module IDs from the agent's plan
	ExtensionDir string   // path to generated JS extensions (empty if none)
	IsRescan     bool     // true for triage-driven targeted rescans
	TargetURLs   []string // optional: restrict rescan to these URLs only
	// ScanUUID is the run-unique native scan_uuid the pipeline owns. Scan
	// callbacks tag the native scan's findings with it so the pipeline can
	// attribute them to this run (agentic_scan_uuid) and scope finding counts
	// to the run instead of the whole project. Empty falls back to the
	// callback's own configured scan_uuid.
	ScanUUID string
}

ScanRequest is the configuration for a native scan callback.

type SetupCleanup

type SetupCleanup struct {
	DockerProjects []string `json:"docker_projects,omitempty"`
	Containers     []string `json:"containers,omitempty"`
	CloneDirs      []string `json:"-"` // populated locally, not from JSON
}

SetupCleanup tracks resources created during SDK-based intent setup that need to be cleaned up when the scan completes.

func (*SetupCleanup) Cleanup

func (sc *SetupCleanup) Cleanup()

Cleanup stops docker containers/projects created during setup. Safe to call on nil receiver.

type Snippet

type Snippet struct {
	ID       string `json:"id"`
	Severity string `json:"severity,omitempty"` // default: "medium"
	Scan     string `json:"scan"`               // "per_insertion_point", "per_request", "per_host"
	Body     string `json:"body"`               // JS function body
}

Snippet is a shorthand extension where only the scan function body is provided. The swarm runner wraps it in a full module scaffold with access to ctx, insertion, and vigolium.* APIs.

type SourceAnalysisConfig

type SourceAnalysisConfig struct {
	AgentName      string
	TargetURL      string
	SourcePath     string
	Files          []string
	Instruction    string // user-provided custom instruction appended to the prompt
	DryRun         bool
	ShowPrompt     bool // print rendered prompt to stderr before executing
	ScanUUID       string
	ProjectUUID    string
	StreamWriter   io.Writer
	SessionDir     string // when set, per-phase prompt/output files are written here
	MaxConcurrency int    // max parallel sub-agents in RunSourceAnalysisParallel (0 = default 3)
}

SourceAnalysisConfig holds parameters for a source code analysis run.

type SourceAnalysisResult

type SourceAnalysisResult struct {
	HTTPRecords   []AgentHTTPRecord    `json:"http_records"`
	SessionConfig *AgentSessionConfig  `json:"session_config,omitempty"`
	Extensions    []GeneratedExtension `json:"extensions,omitempty"`
	// SessionExploreNotes carries the raw explore-phase notes about auth/credentials/sessions.
	// Not serialized — used internally to provide context for session config repair.
	SessionExploreNotes string `json:"-"`
}

SourceAnalysisResult is the structured output from the source analysis phase (phase 0). The agent explores source code and extracts routes, session config, and custom extensions.

type SwarmCheckpoint

type SwarmCheckpoint struct {
	CompletedPhases  []string          `json:"completed_phases"`
	TargetURL        string            `json:"target_url"`
	RecordCount      int               `json:"record_count"`
	Plan             *SwarmPlan        `json:"plan,omitempty"`
	ExtensionDir     string            `json:"extension_dir,omitempty"`
	Timestamp        time.Time         `json:"timestamp"`
	TriageRound      int               `json:"triage_round,omitempty"`      // last completed triage round (0-indexed)
	ExtensionRenames map[string]string `json:"extension_renames,omitempty"` // original filename -> renamed filename
	LastFindingID    int64             `json:"last_finding_id,omitempty"`
	Warnings         []string          `json:"warnings,omitempty"`
	InitialRecords   int               `json:"initial_records,omitempty"`
	SourceRecords    int               `json:"source_records,omitempty"`
	DiscoveryRecords int               `json:"discovery_records,omitempty"`
}

SwarmCheckpoint captures swarm pipeline state for checkpoint/resume.

func (*SwarmCheckpoint) LastPhase

func (cp *SwarmCheckpoint) LastPhase() string

LastPhase returns the last completed phase, or "" if none.

type SwarmIntensityPreset

type SwarmIntensityPreset struct {
	Discover         bool
	CodeAudit        bool // applied only when source is provided
	Triage           bool
	MaxIterations    int
	Audit            string // audit mode when source is provided; empty = disabled
	MaxPlanRecords   int
	MasterBatchSize  int
	BatchConcurrency int
	ProbeConcurrency int
	Browser          bool
	Auth             bool // applied only when browser is enabled
	SwarmDuration    time.Duration
}

SwarmIntensityPreset holds the preset values for swarm at a given intensity.

type SwarmPlan

type SwarmPlan struct {
	ModuleTags  []string             `json:"module_tags,omitempty"`
	ModuleIDs   []string             `json:"module_ids,omitempty"`
	Extensions  []GeneratedExtension `json:"extensions,omitempty"`
	QuickChecks []QuickCheck         `json:"quick_checks,omitempty"`
	Snippets    []Snippet            `json:"snippets,omitempty"`
	FocusAreas  []string             `json:"focus_areas,omitempty"`
	// RecommendedSkills is the planner's context-driven selection of skill
	// names (from the <available_skills> menu) that the triage phase should
	// load for confirmation/escalation. Unioned with the always-on set and any
	// operator override before the triage engine is built.
	RecommendedSkills     []string `json:"recommended_skills,omitempty"`
	Notes                 string   `json:"notes,omitempty"`
	NeedsExtensions       bool     `json:"needs_extensions,omitempty"`
	NeedsExtensionsReason string   `json:"needs_extensions_reason,omitempty"`
	ExtensionAgentError   string   `json:"extension_agent_error,omitempty"`
}

SwarmPlan is the structured output from the master agent in agent swarm mode. The agent analyzes the target request, selects modules, and generates custom extensions.

type SwarmResult

type SwarmResult struct {
	SwarmPlan       *SwarmPlan               `json:"swarm_plan,omitempty"`
	TriageResults   []*TriageResult          `json:"triage_results,omitempty"`
	TotalFindings   int                      `json:"total_findings"`
	TotalRecords    int                      `json:"total_records"`
	SeverityCounts  map[string]int           `json:"severity_counts,omitempty"` // critical, high, medium, low, info
	Confirmed       int                      `json:"confirmed"`
	FalsePositives  int                      `json:"false_positives"`
	Iterations      int                      `json:"iterations"`
	Duration        time.Duration            `json:"duration"`
	AgenticScanUUID string                   `json:"agentic_scan_uuid"`
	SessionDir      string                   `json:"session_dir,omitempty"`
	PhaseTimings    map[string]time.Duration `json:"phase_timings,omitempty"`
	TokenUsage      TokenUsage               `json:"token_usage,omitempty"`
	BatchProvenance *BatchProvenance         `json:"batch_provenance,omitempty"` // only set when plan was merged from multiple batches
	Degraded        bool                     `json:"degraded,omitempty"`
	Warnings        []string                 `json:"warnings,omitempty"`
}

SwarmResult holds the outcome of an agent swarm run.

type TemplateData

type TemplateData struct {
	SourceCode          string
	Language            string
	Framework           string
	FilePath            string
	SourcePath          string
	DirectoryTree       string
	SkipGuidance        string
	SourceHint          string
	TargetURL           string
	Hostname            string
	Endpoints           string
	Extra               map[string]string
	PreviousFindings    string // JSON array of findings from DB
	DiscoveredEndpoints string // JSON array of HTTP records from DB
	HighRiskEndpoints   string // JSON array of top risk-scored HTTP records from DB
	ModuleList          string // JSON array of available scanner modules
	ModuleTags          string // JSON array of unique module tags
	ModuleCatalog       string // human-readable, categorized list of module tags + total count
	ScanStats           string // JSON object of scan statistics
	AvailableCommands   string // hardcoded CLI command reference
}

TemplateData holds the variables passed to a prompt template.

type TokenUsage

type TokenUsage struct {
	InputTokens  int `json:"input_tokens"`
	OutputTokens int `json:"output_tokens"`
}

TokenUsage tracks cumulative token consumption across agent calls in a run.

type TriageConfirmResult

type TriageConfirmResult struct {
	Verdict   string `json:"verdict"`   // one of TriageVerdictConfirmed, TriageVerdictFalsePositive
	Reasoning string `json:"reasoning"` // free-form explanation of how the verdict was reached
	Notes     string `json:"notes,omitempty"`
}

TriageConfirmResult is the structured output from the single-finding confirmation triage agent (the `vigolium agent triage` CLI subcommand). The agent reasons about one finding's evidence, optionally re-probes the target, and returns a verdict plus reasoning.

type TriageResult

type TriageResult struct {
	Confirmed      []TriagedFinding `json:"confirmed"`
	FalsePositives []TriagedFinding `json:"false_positives"`
	FollowUps      []FollowUpScan   `json:"follow_up_scans,omitempty"`
	Verdict        string           `json:"verdict"` // "done" or "rescan"
	Notes          string           `json:"notes,omitempty"`
}

TriageResult is the structured output from the triage agent checkpoint (phase 4). The agent reviews findings and decides whether additional scanning is needed.

type TriagedFinding

type TriagedFinding struct {
	Title       string `json:"title"`
	ModuleID    string `json:"module_id,omitempty"`
	URL         string `json:"url,omitempty"`
	FindingHash string `json:"finding_hash,omitempty"`
	Reason      string `json:"reason,omitempty"`
}

TriagedFinding is a finding that has been reviewed by the triage agent. FindingHash is the database finding_hash echoed back by the agent so the triage verdict can be written back to Finding.Status.

Jump to

Keyboard shortcuts

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