⚠️ Experimental — This resource is part of the Guild platform and may change in future releases.
Manages a StackGen AI agent. Agents are registered with the Guild platform and can be governed by policies attached via sg_agent_policy_attachment.
409 conflict adoption is controlled by the provider attribute adopt_on_conflict (default true).
Import using the agent name.
# When to use: Start with a bare agent when you only need a named target for
# webhooks, schedules, or workflow stage_bindings. Add persona/models/integrations
# later (see resource_extended.tf) once the agent should talk to tools/LLMs.
#
# Prefer data.sg_agent when the agent is owned by an installed app (e.g. SRE
# investigator) and this stack should not recreate it.
#
# Related: sg_guild_model (+ provider), sg_guild_integration, sg_agent_policy_attachment,
# sg_agent_budget, sg_workflow, sg_webhook, sg_agent_schedule, sg_remote_runner.
resource "sg_agent" "example" {
name = "my-first-agent"
}
# HITL bypass rules (Guild AutoApproveToolRule). Use tool wildcards for integration prefixes.
resource "sg_agent" "example_auto_approve" {
name = "mcp-consumer"
auto_approve_tools = [
{ tool = "terraform_plan" },
{ tool = "stackgen-mcp_*" },
{
tool = "browser_navigate"
when_args_contain = jsonencode({ url = "https://internal.example.com" })
},
]
}
# When to use: Mid-complexity agent with tools, tags, models, integrations, and
# middleware context budgets. Prefer resource_production.tf when you also need
# diary / PII / remote runners.
#
# Agent with tools, tags, models, and integrations (Guild — experimental).
resource "sg_agent" "example_full" {
name = "infra-bot"
description = "Answers infra questions and runs approved tools."
persona = "You are an SRE assistant with read-only production access."
tools = ["kubectl_get", "terraform_plan"]
auto_approve_tools = [
{ tool = "kubectl_get" },
]
auto_deny_tools = ["terraform_apply"]
tags = ["sre", "production"]
model_names = ["gpt-4o"]
integrations = ["slack"]
knowledge = {
memory_enabled = true
}
middleware = {
# Compress oversized tool output locally, but give observability queries a
# larger evidence budget than the global defaults.
context_mode = {
threshold = 10000
max_chunks = 10
per_tool = {
"*_observability_query" = {
threshold = 50000
max_chunks = 40
chunk_size = 1200
}
}
}
}
}
# When to use: Production-shaped agent with persona, models, integrations,
# remote runners, diary summarization, and PII overlays. Create models and
# integrations first (Layer 0–1), then attach this agent (Layer 2).
#
# Prerequisites: sg_guild_model names in model_names; integration names that
# already exist; optional remote runner names/IDs.
resource "sg_agent" "example_production" {
name = "sre-copilot"
description = "On-call assistant with read-only cloud and observability tools."
persona = "You are an SRE assistant. Prefer evidence over speculation. Never mutate production without HITL."
model_names = ["gpt-4o-default"]
integrations = ["example-grafana", "example-aws", "example-slack"]
remote_runners = ["onprem-runner"]
tags = ["sre", "production"]
auto_approve_tools = [
{ tool = "grafana_*" },
{ tool = "kubectl_get" },
]
auto_deny_tools = ["terraform_apply", "kubectl_delete"]
knowledge = {
memory_enabled = true
}
diary = {
enabled = true
compression = "relaxed"
max_sample_events = 50
max_error_warn_events = 25
max_payload_bytes = 262144
max_episodic_entries = 20
max_feedback_entries = 10
}
pii_redaction = {
enabled = true
deny = [
{
name = "password-assignment"
pattern = "(?i)password\\s*[:=]\\s*\\S+"
},
]
}
}
Import an existing sg_agent using its name:
terraform import sg_agent.example 'my-first-agent'
Attach only integration names already registered in the same organization. model_names must likewise refer to existing Guild models; provision those first. Imported agents should be refreshed before changing nested configuration.
name (String) Agent name. Must be unique. Changing this forces a new resource.auto_approve_tools (Attributes List) Rules for tools that bypass HITL. Each block names a tool (or prefix wildcard ending in *) and optionally restricts auto-approval to calls whose arguments contain when_args_contain. (see below for nested schema)auto_deny_tools (Set of String) Tool names that are always denied.autonomy_budget (Attributes) Per-agent autonomy budget thresholds (LLM calls and tokens per execution). Send an empty block to clear stored config on update. (see below for nested schema)description (String) Human-readable description of the agent. Sent on register/update; preserved in state if Guild omits it on read.diary (Attributes) Nightly diary LLM summarization budget for this agent. (see below for nested schema)eval (Attributes) Automated agent quality evaluation configuration. (see below for nested schema)hitl (Attributes) Human-in-the-loop approval configuration. (see below for nested schema)integrations (Set of String) Names of guild-level integrations to attach.is_router (Boolean) When true, the agent acts as a logical router distributing traffic to variants via MAB.knowledge (Attributes) Vector memory namespace configuration for this agent. (see below for nested schema)middleware (Attributes) Per-agent tool middleware configuration. (see below for nested schema)model_config (Attributes) Per-agent model provider configuration. (see below for nested schema)model_names (Set of String) Names of registered models assigned to this agent.parent_agent_id (String) When set, this agent is a variant of the parent logical agent (server-assigned UUID).persona (String) System prompt / persona that defines the agent’s behavior. Hard-capped at 15000 bytes to match the Guild server limit.pii_redaction (Attributes) Per-agent PII redaction policy (enable flag plus deny/allow RE2 rules) layered on the platform baseline. (see below for nested schema)rca (Attributes) Per-agent root cause analysis settings. (see below for nested schema)remote_runners (Set of String) Remote runner names or IDs (see sg_remote_runner) this agent may dispatch tools to. When set, the agent is constrained to those runners only.runbook (Attributes) Per-agent runbook generation settings. (see below for nested schema)semantic_router_policy_id (String) OPA policy ID for semantic routing.skills (Set of String) Skill locations for dynamic tools.tags (Set of String) Labels for discovery and cost allocation.tools (Set of String) Tool names this agent can invoke. Changing this forces a new resource (Guild API does not support updating tools in place).autonomy_tier (String) Burn-derived autonomy privilege tier (healthy, elevated, or exhausted). Set by enrichment, not configurable in HCL.autonomy_tier_snapshot (Attributes) Metrics and reason from the latest enrichment evaluation that set autonomy_tier. Null when never evaluated or after Start resets tier to healthy. (see below for nested schema)contact_id (String) Identity for escalations.environment (String) Deployment environment (e.g. prod or staging).id (String) Agent identifier (server-assigned).started (Boolean) Whether the agent is currently running.status (String) Agent lifecycle status (active or halted).auto_approve_toolsRequired:
tool (String) Tool name (exact, case-insensitive) or prefix wildcard ending in * (e.g. stackgen-mcp_*).Optional:
when_args_contain (String) JSON object that call arguments must contain (subset match). Omit or use {} for any arguments. Use jsonencode() in HCL for nested keys.autonomy_budgetOptional:
elevated_llm_calls (Number) LLM call count per execution that triggers the elevated (HITL) tier. Default 48.elevated_tokens (Number) Total token count per execution that triggers the elevated tier. Default 50000.enabled (Boolean) Enable budget enforcement for this agent. When false (default), the agent runs without tier constraints.exhausted_llm_calls (Number) LLM call count per execution that triggers the exhausted (suspend) tier. Default 96.exhausted_tokens (Number) Total token count per execution that triggers the exhausted tier. Default 100000.suspend_on_exhausted (Boolean) When true and the tier is exhausted, the agent is automatically halted via the Halt API. When false, exhaustion is only reported in metrics/logs.diaryOptional:
compression (String) Diary summarization compression preset: aggressive, relaxed, or full.enabled (Boolean) When false, skip LLM diary generation for this agent. Omit to inherit default (true).max_episodic_entries (Number) Maximum episodic memory entries passed to the diary summarizer.max_error_warn_events (Number) Sub-cap for ERROR and WARN audit events always included in the sample.max_feedback_entries (Number) Maximum user message feedback rows passed to the diary summarizer.max_payload_bytes (Number) Maximum JSON bytes per audit event payload after truncation.max_sample_events (Number) Maximum audit events in the LLM prompt after stratified sampling.evalOptional:
auto_record_reward (Boolean) Automatically record the composite eval score as a MAB reward.enabled (Boolean) Enable eval-driven MAB rewards.error_weight (Number) Weight of the error evaluator (0.0-1.0).escalation_threshold (Number) If composite score drops below this an escalation event is emitted.ideal_response_max (Number) Upper bound of the ideal response length range.ideal_response_min (Number) Lower bound of the ideal response length range.latency_weight (Number) Weight of the latency evaluator.max_latency_ms (Number) Maximum acceptable response time in milliseconds.min_response_length (Number) Minimum acceptable response length in characters.response_length_weight (Number) Weight of the response length evaluator.target_latency_ms (Number) Target response time in milliseconds.hitlOptional:
always_allowed (Set of String) Tool names or patterns that bypass HITL approval.denied_tools (Set of String) Tool names or patterns that are always denied.knowledgeOptional:
memory_enabled (Boolean) Enable vector memory tools (memory_store and memory_search) for this agent. Defaults to the platform vector store setting when omitted.middlewareOptional:
circuit_breaker (Attributes) Circuit breaker to stop calling repeatedly-failing tools. (see below for nested schema)concurrency (Attributes) Concurrent tool call limiting. (see below for nested schema)context_mode (Attributes) BM25-based local compression of oversized tool outputs. (see below for nested schema)metrics (Attributes) Prometheus metrics emission for tool calls. (see below for nested schema)retry (Attributes) Automatic retry configuration for failed tool calls. (see below for nested schema)sanitize (Attributes) Output sanitization (PII scrubbing). (see below for nested schema)timeout (Attributes) Per-tool-call timeout configuration. (see below for nested schema)tracing (Attributes) OpenTelemetry tracing spans for tool calls. (see below for nested schema)validation (Attributes) Input/output validation for tool calls. (see below for nested schema)middleware.circuit_breakerOptional:
enabled (Boolean) Whether circuit breaker is enabled.failure_threshold (Number) Open after N consecutive failures.half_open_max_calls (Number) Max calls in half-open state.open_duration (Number) Duration in nanoseconds to stay open.middleware.concurrencyOptional:
enabled (Boolean) Whether concurrency limiting is enabled.max_concurrent (Number) Maximum concurrent tool calls.middleware.context_modeOptional:
chunk_size (Number) Target character count per chunk. Default 800.disabled (Boolean) Set true to disable context-mode compression.max_chunks (Number) Maximum number of chunks or JSON array items to keep. Default 10.min_term_len (Number) Minimum query-term length when preferring JSON rows that match tool args. Default 3.per_tool (Attributes Map) Per-tool overrides keyed by exact tool name or a single trailing wildcard (e.g. *_observability_query). Set fields replace the global context_mode defaults for matching tools. (see below for nested schema)threshold (Number) Character count above which compression activates. Default 10000.middleware.context_mode.per_toolOptional:
chunk_size (Number) Target character count per chunk for this tool.disabled (Boolean) Skip context-mode compression for this tool.max_chunks (Number) Maximum number of chunks or JSON array items to keep for this tool.min_term_len (Number) Minimum query-term length when preferring JSON rows that match tool args for this tool.threshold (Number) Character count above which compression activates for this tool.middleware.metricsOptional:
enabled (Boolean) Whether this middleware is enabled.middleware.retryOptional:
enabled (Boolean) Whether retry is enabled.max_retries (Number) Maximum number of retries.middleware.sanitizeOptional:
enabled (Boolean) Whether this middleware is enabled.middleware.timeoutOptional:
default_ms (Number) Default timeout in milliseconds.enabled (Boolean) Whether timeout is enabled.middleware.tracingOptional:
enabled (Boolean) Whether this middleware is enabled.middleware.validationOptional:
enabled (Boolean) Whether this middleware is enabled.model_configOptional:
providers (Attributes List) Ordered list of model providers for this agent. (see below for nested schema)model_config.providersRequired:
model_name (String) Model identifier (e.g. gpt-4o or claude-sonnet-4-6).provider (String) LLM provider type (openai or anthropic or google etc).Optional:
good_for_task (String) Deprecated task affinity. Remove it and choose thinking explicitly; task values cannot be mapped automatically.host (String) Custom API endpoint URL.thinking (Boolean) Mark this provider row as a thinking model when true. Omit for Guild non-thinking default.variant (String) Provider-specific variant.pii_redactionOptional:
allow (Attributes List) Regex rules whose matches are kept visible (never redacted). Allow takes precedence over deny and the global scanner. (see below for nested schema)deny (Attributes List) Extra regex rules whose matches are always redacted. (see below for nested schema)enabled (Boolean) Whether PII redaction runs for this agent. Omit to inherit the platform default (enabled); set false to disable.pii_redaction.allowRequired:
name (String) Human-readable label for this rule (diagnostics).pattern (String) Go RE2 regular expression matched against text.pii_redaction.denyRequired:
name (String) Human-readable label for this rule (diagnostics).pattern (String) Go RE2 regular expression matched against text.rcaOptional:
auto_trigger (Boolean) Auto-trigger RCA when error thresholds are exceeded.enabled (Boolean) Whether RCA analysis is available.error_threshold (Number) Number of errors within the window that triggers RCA.error_window_mins (Number) Time window in minutes for counting errors.git (Attributes) Git push settings for RCA reports. (see below for nested schema)rca.gitOptional:
git_path (String) Directory prefix inside the repository.git_ref (String) Branch to push to (default main).git_repo (String) Git remote URL (HTTPS or SSH).secret_id (String) Key for SecretProvider to retrieve Git auth token.runbookOptional:
enabled (Boolean) Whether runbook generation runs for this agent.git (Attributes) Git push settings for runbook outputs. (see below for nested schema)min_tokens (Number) Skip generation for chats shorter than this.runbook.gitOptional:
git_path (String) Directory prefix inside the repository.git_ref (String) Branch to push to (default main).git_repo (String) Git remote URL (HTTPS or SSH).secret_id (String) Key for SecretProvider to retrieve Git auth token.autonomy_tier_snapshotRead-Only:
elevated_llm_calls_threshold (Number) Effective elevated LLM-call threshold used for classification.elevated_tokens_threshold (Number) Effective elevated token threshold used for classification.evaluated_at (String) When enrichment classified this sample (RFC3339).exhausted_llm_calls_threshold (Number) Effective exhausted LLM-call threshold used for classification.exhausted_tokens_threshold (Number) Effective exhausted token threshold used for classification.llm_calls (Number) LLM call count from the evaluated execution.reason (String) Why the current autonomy_tier was assigned for the latest evaluated execution.tool_calls (Number) Tool call count from the evaluated execution.total_tokens (Number) Total tokens (input + output) from the evaluated execution.trace_id (String) Langfuse or execution trace ID for the sample, when known.