agentcore

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Overview

Package agentcore implements the AWS Bedrock AgentCore deploy adapter for PromptKit.

Index

Constants

View Source
const (
	ProtocolHTTP = "http"
	ProtocolA2A  = "a2a"
	ProtocolBoth = "both"
)

Protocol mode constants for the runtime server protocol.

View Source
const (
	StrategyEpisodic       = "episodic"
	StrategySemantic       = "semantic"
	StrategySummary        = "summary"
	StrategyUserPreference = "user_preference"
)

Valid memory strategy names.

View Source
const (
	A2AAuthModeIAM = "iam"
	A2AAuthModeJWT = "jwt"
)

A2A auth mode constants.

View Source
const (
	EnvLogGroup        = "PROMPTPACK_LOG_GROUP"
	EnvTracingEnabled  = "PROMPTPACK_TRACING_ENABLED"
	EnvMemoryStore     = "PROMPTPACK_MEMORY_STORE"
	EnvMemoryID        = "PROMPTPACK_MEMORY_ID"
	EnvA2AAgents       = "PROMPTPACK_AGENTS"
	EnvA2AAuthMode     = "PROMPTPACK_A2A_AUTH_MODE"
	EnvA2AAuthRole     = "PROMPTPACK_A2A_AUTH_ROLE"
	EnvPolicyEngineARN = "PROMPTPACK_POLICY_ENGINE_ARN"
	EnvMetricsConfig   = "PROMPTPACK_METRICS_CONFIG"
	EnvDashboardConfig = "PROMPTPACK_DASHBOARD_CONFIG"
	EnvAgentName       = "PROMPTPACK_AGENT"
	EnvProviderType    = "PROMPTPACK_PROVIDER_TYPE"
	EnvProviderModel   = "PROMPTPACK_PROVIDER_MODEL"
	EnvProtocol        = "PROMPTPACK_PROTOCOL"

	// EnvProviders carries the full set of resolved provider bindings as a
	// JSON array. PROMPTPACK_PROVIDER_TYPE/MODEL cannot express a list with
	// roles, so they remain populated from the primary binding only, for
	// runtimes built before provider bindings existed.
	EnvProviders = "PROMPTPACK_PROVIDERS"
)

Environment variable keys injected into AgentCore runtimes.

View Source
const (
	ErrCategoryPermission    = "permission"
	ErrCategoryConfiguration = "configuration"
	ErrCategoryResource      = "resource"
	ErrCategoryTimeout       = "timeout"
	ErrCategoryNetwork       = "network"
)

Error category constants classify deployment failures for diagnostics.

View Source
const (
	RoleLLM       = "llm"
	RoleEmbedding = "embedding"
	RoleTTS       = "tts"
	RoleSTT       = "stt"
	RoleImage     = "image"
	RoleInference = "inference"
)

Provider binding roles. A binding declares which capability the bound provider serves in the deployed runtime.

View Source
const (
	ResTypeMemory           = "memory"
	ResTypeAgentRuntime     = "agent_runtime"
	ResTypeToolGateway      = "tool_gateway"
	ResTypeA2AEndpoint      = "a2a_endpoint"
	ResTypeEvaluator        = "evaluator"
	ResTypeOnlineEvalConfig = "online_eval_config"
	ResTypeCedarPolicy      = "cedar_policy"
)

Resource type constants used across plan, apply, destroy, and status.

View Source
const (
	ResStatusCreated = "created"
	ResStatusUpdated = "updated"
	ResStatusFailed  = "failed"
	ResStatusPlanned = "planned"
	ResStatusDeleted = "deleted"
)

Resource lifecycle status constants used in ResourceState.Status.

View Source
const (
	StatusHealthy   = "healthy"
	StatusUnhealthy = "unhealthy"
	StatusMissing   = "missing"
)

Health status constants returned by resource checks.

View Source
const (
	TagKeyPackID  = "promptpack:pack-id"
	TagKeyVersion = "promptpack:version"
	TagKeyAgent   = "promptpack:agent"
)

Tag key constants for pack metadata applied to all created AWS resources.

Variables

View Source
var (
	// Version is the semantic version of this build.
	Version = "dev"
	// Commit is the git commit hash of this build.
	Commit = "none"
	// Date is the build timestamp.
	Date = "unknown"
)

Build-time variables injected via ldflags.

Functions

func DiagnosticSummary

func DiagnosticSummary(errs []error) string

DiagnosticSummary returns a multi-line diagnostic string for a slice of errors, suitable for display to the user after a failed deployment.

func FormatWarnings

func FormatWarnings(warnings []DiagnosticWarning) string

FormatWarnings returns a multi-line string from a list of warnings, suitable for display to the user.

Types

type A2AAuthConfig

type A2AAuthConfig struct {
	Mode         string   `json:"mode"`                       // "iam" or "jwt"
	DiscoveryURL string   `json:"discovery_url,omitempty"`    // required for jwt
	AllowedAud   []string `json:"allowed_audience,omitempty"` // JWT audiences
	AllowedClts  []string `json:"allowed_clients,omitempty"`  // JWT client IDs
}

A2AAuthConfig holds A2A authentication settings.

type AdapterState

type AdapterState struct {
	Resources  []ResourceState `json:"resources"`
	PackID     string          `json:"pack_id,omitempty"`
	Version    string          `json:"version,omitempty"`
	DeployedAt string          `json:"deployed_at,omitempty"`
}

AdapterState holds resource info from previous deploys. It is serialized as the opaque "prior_state" string exchanged between Plan, Apply, and Status.

type AlarmEntry

type AlarmEntry struct {
	MetricName string   `json:"metric_name"`
	Min        *float64 `json:"min,omitempty"`
	Max        *float64 `json:"max,omitempty"`
}

AlarmEntry describes a CloudWatch alarm threshold for a metric.

type ArenaAPIGatewayConfig

type ArenaAPIGatewayConfig struct {
	RestAPIID string                    `json:"rest_api_id"`
	Stage     string                    `json:"stage"`
	Filters   []ArenaAPIGatewayFilter   `json:"filters,omitempty"`
	Overrides []ArenaAPIGatewayOverride `json:"overrides,omitempty"`
}

ArenaAPIGatewayConfig holds API Gateway target configuration.

type ArenaAPIGatewayFilter

type ArenaAPIGatewayFilter struct {
	Path    string   `json:"path"`
	Methods []string `json:"methods"`
}

ArenaAPIGatewayFilter specifies which operations from the REST API to expose.

type ArenaAPIGatewayOverride

type ArenaAPIGatewayOverride struct {
	Name        string `json:"name"`
	Path        string `json:"path"`
	Method      string `json:"method"`
	Description string `json:"description,omitempty"`
}

ArenaAPIGatewayOverride defines an explicit tool with custom name and description.

type ArenaConfig

type ArenaConfig struct {
	ToolSpecs       map[string]*ArenaToolSpec `json:"tool_specs,omitempty"`
	MCPServers      []ArenaMCPServer          `json:"mcp_servers,omitempty"`
	LoadedProviders map[string]*ArenaProvider `json:"loaded_providers,omitempty"`
	ProviderSpecs   map[string]*ArenaProvider `json:"provider_specs,omitempty"`
}

ArenaConfig holds the subset of the PromptKit arena config that the adapter needs for infrastructure decisions.

type ArenaCredentialConfig

type ArenaCredentialConfig struct {
	Type string `json:"type"` // "GATEWAY_IAM_ROLE" | "OAUTH" | "API_KEY"
}

ArenaCredentialConfig specifies the credential provider for a gateway target. API Gateway targets use "GATEWAY_IAM_ROLE"; OpenAPI and Smithy targets require "OAUTH" or "API_KEY".

type ArenaHTTPConfig

type ArenaHTTPConfig struct {
	URL    string `json:"url,omitempty"`
	Method string `json:"method,omitempty"`
}

ArenaHTTPConfig holds HTTP-specific tool configuration.

type ArenaMCPServer

type ArenaMCPServer struct {
	Name    string   `json:"name,omitempty"`
	Command string   `json:"command,omitempty"`
	Args    []string `json:"args,omitempty"`
}

ArenaMCPServer describes an MCP server from the arena config.

type ArenaProvider

type ArenaProvider struct {
	ID    string `json:"id,omitempty"`
	Type  string `json:"type"`
	Model string `json:"model"`
}

ArenaProvider describes a provider from the arena config.

type ArenaSchemaConfig

type ArenaSchemaConfig struct {
	Inline string `json:"inline,omitempty"`
	S3URI  string `json:"s3_uri,omitempty"`
}

ArenaSchemaConfig is shared by OpenAPI and Smithy targets. Exactly one of Inline or S3URI should be set.

type ArenaToolSpec

type ArenaToolSpec struct {
	Name        string                 `json:"name,omitempty"`
	Description string                 `json:"description,omitempty"`
	Mode        string                 `json:"mode,omitempty"` // "mock" | "live" | "mcp" | "a2a"
	InputSchema any                    `json:"input_schema,omitempty"`
	HTTPConfig  *ArenaHTTPConfig       `json:"http,omitempty"`
	LambdaARN   string                 `json:"lambda_arn,omitempty"`
	APIGateway  *ArenaAPIGatewayConfig `json:"api_gateway,omitempty"`
	OpenAPI     *ArenaSchemaConfig     `json:"openapi,omitempty"`
	Smithy      *ArenaSchemaConfig     `json:"smithy,omitempty"`
	Credential  *ArenaCredentialConfig `json:"credential,omitempty"`
}

ArenaToolSpec describes a single tool from the arena config.

type Config

type Config struct {
	Region            string               `json:"region"`
	RuntimeRoleARN    string               `json:"runtime_role_arn"`
	Memory            MemoryConfig         `json:"memory_store,omitempty"`
	RuntimeBinaryPath string               `json:"runtime_binary_path,omitempty"`
	Protocol          string               `json:"protocol,omitempty"`
	Tags              map[string]string    `json:"tags,omitempty"`
	DryRun            bool                 `json:"dry_run,omitempty"`
	Tools             *ToolsConfig         `json:"tools,omitempty"`
	Observability     *ObservabilityConfig `json:"observability,omitempty"`
	A2AAuth           *A2AAuthConfig       `json:"a2a_auth,omitempty"`

	// Providers declares which providers the deployed runtime uses and in
	// what role. When empty the adapter falls back to deriving a single LLM
	// provider from the arena config, which is deprecated.
	Providers []ProviderBinding `json:"providers,omitempty"`

	// ToolTargets maps tool names to provider-specific target config
	// (e.g. lambda_arn). These are merged into ArenaConfig.ToolSpecs
	// so that buildTargetConfig can find Lambda ARNs and other
	// target configuration supplied via the deploy section.
	ToolTargets map[string]*ArenaToolSpec `json:"tool_targets,omitempty"`

	// PackJSON holds the raw pack JSON content to inject as an env var
	// on the runtime container. Populated at apply-time from PlanRequest.
	// NOT serialized — it is a transient, computed field.
	PackJSON string `json:"-"`

	// RuntimeEnvVars is populated at apply-time from config fields.
	// It is NOT serialized — it is a transient, computed field.
	RuntimeEnvVars map[string]string `json:"-"`

	// ResourceTags is populated at apply-time by merging default pack
	// metadata tags with user-defined tags. It is NOT serialized.
	ResourceTags map[string]string `json:"-"`

	// EvalDefs is populated at apply-time from pack evals. It maps
	// evaluator resource names to their definitions. NOT serialized.
	EvalDefs map[string]evals.EvalDef `json:"-"`

	// EvalARNs maps evaluator resource names to their ARNs, populated
	// at apply-time after the evaluator phase. NOT serialized.
	EvalARNs map[string]string `json:"-"`

	// BuiltinEvalIDs lists built-in evaluator IDs (e.g. "Builtin.Helpfulness")
	// from the pack. These are passed directly to the online eval config
	// without creating evaluator resources. NOT serialized.
	BuiltinEvalIDs []string `json:"-"`

	// GatewayARN is populated at apply-time after the tool gateway phase.
	// Used by Cedar tool policies that need a specific gateway resource. NOT serialized.
	GatewayARN string `json:"-"`

	// ArenaConfig is the parsed arena configuration, populated from
	// PlanRequest.ArenaConfig. NOT part of the deploy config JSON.
	ArenaConfig *ArenaConfig `json:"-"`

	// PackTools holds pack tool definitions, populated at apply-time.
	// Used to build inline tool schemas for Lambda gateway targets.
	PackTools map[string]*prompt.PackTool `json:"-"`

	// PromptNames is a set of prompt names from the pack. Used to
	// determine if a runtime name matches an actual prompt (multi-agent)
	// vs the pack ID (single-agent). NOT serialized.
	PromptNames map[string]bool `json:"-"`
}

Config holds AWS Bedrock AgentCore-specific configuration.

func (*Config) HasMemory

func (c *Config) HasMemory() bool

HasMemory returns true if any memory strategies are configured.

func (*Config) MemoryStrategiesCSV

func (c *Config) MemoryStrategiesCSV() string

MemoryStrategiesCSV returns the configured strategies as a comma-separated string, suitable for environment variable injection.

func (*Config) UnmarshalJSON

func (c *Config) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshalling for Config to handle the polymorphic memory_store field (string, array, or object).

type DashboardAnnotations

type DashboardAnnotations struct {
	Horizontal []DashboardThreshold `json:"horizontal,omitempty"`
}

DashboardAnnotations holds horizontal threshold lines.

type DashboardConfig

type DashboardConfig struct {
	Widgets []DashboardWidget `json:"widgets"`
}

DashboardConfig is the top-level CloudWatch dashboard body injected into runtimes via PROMPTPACK_DASHBOARD_CONFIG.

type DashboardThreshold

type DashboardThreshold struct {
	Label string  `json:"label"`
	Value float64 `json:"value"`
	Color string  `json:"color"`
}

DashboardThreshold represents a threshold line on a widget.

type DashboardWidget

type DashboardWidget struct {
	Type       string               `json:"type"`
	X          int                  `json:"x"`
	Y          int                  `json:"y"`
	Width      int                  `json:"width"`
	Height     int                  `json:"height"`
	Properties DashboardWidgetProps `json:"properties"`
}

DashboardWidget represents a single widget in the dashboard.

type DashboardWidgetProps

type DashboardWidgetProps struct {
	Title       string                `json:"title"`
	View        string                `json:"view,omitempty"`
	Stacked     bool                  `json:"stacked,omitempty"`
	Region      string                `json:"region,omitempty"`
	Metrics     [][]string            `json:"metrics,omitempty"`
	Annotations *DashboardAnnotations `json:"annotations,omitempty"`
	Period      int                   `json:"period,omitempty"`
}

DashboardWidgetProps holds widget display properties.

type DataPlaneClient

type DataPlaneClient interface {
	CreateEvent(
		ctx context.Context,
		input *bedrockagentcore.CreateEventInput,
		opts ...func(*bedrockagentcore.Options),
	) (*bedrockagentcore.CreateEventOutput, error)

	ListEvents(
		ctx context.Context,
		input *bedrockagentcore.ListEventsInput,
		opts ...func(*bedrockagentcore.Options),
	) (*bedrockagentcore.ListEventsOutput, error)
}

DataPlaneClient abstracts the AWS Bedrock AgentCore data-plane API for testing.

func NewDataPlaneClient

func NewDataPlaneClient(
	region string,
) (DataPlaneClient, error)

NewDataPlaneClient creates a DataPlaneClient backed by the real AWS Bedrock AgentCore data-plane SDK.

type DeployError

type DeployError struct {
	// Category classifies the failure (e.g. "permission", "configuration").
	Category string
	// ResourceType is the type of resource that failed (e.g. "agent_runtime").
	ResourceType string
	// ResourceName is the name of the resource that failed.
	ResourceName string
	// Operation is the action that failed (e.g. "create", "update", "delete").
	Operation string
	// Message is the primary error description.
	Message string
	// Remediation is a human-readable hint on how to fix the issue.
	Remediation string
	// Cause is the underlying error, if any.
	Cause error
}

DeployError is a structured error type that provides actionable diagnostics for deployment failures. It includes the failed resource, error category, and a human-readable remediation hint.

func IsDeployError

func IsDeployError(err error) *DeployError

IsDeployError returns the DeployError if err is (or wraps) one.

func (*DeployError) Error

func (e *DeployError) Error() string

Error implements the error interface with a diagnostic-rich message.

func (*DeployError) Unwrap

func (e *DeployError) Unwrap() error

Unwrap returns the underlying cause for errors.Is/As compatibility.

type DiagnosticWarning

type DiagnosticWarning struct {
	Category string
	Message  string
	Hint     string
}

DiagnosticWarning represents a non-fatal issue detected during pre-deploy diagnostics.

func DiagnoseConfig

func DiagnoseConfig(cfg *Config) []DiagnosticWarning

DiagnoseConfig checks the configuration for common misconfigurations and returns warnings. Unlike validate(), these are non-fatal — they highlight issues that are likely to cause deploy failures.

func (DiagnosticWarning) String

func (w DiagnosticWarning) String() string

String formats the warning for display.

type MemoryConfig

type MemoryConfig struct {
	Strategies       []string `json:"strategies"`
	EventExpiryDays  int32    `json:"event_expiry_days,omitempty"`
	EncryptionKeyARN string   `json:"encryption_key_arn,omitempty"`
}

MemoryConfig holds memory configuration for the deployment.

type MetricEntry

type MetricEntry struct {
	EvalID     string `json:"eval_id"`
	MetricName string `json:"metric_name"`
	MetricType string `json:"metric_type"`
	Unit       string `json:"unit"`
}

MetricEntry describes a single eval metric for CloudWatch.

type MetricsConfig

type MetricsConfig struct {
	Namespace  string            `json:"namespace"`
	Dimensions map[string]string `json:"dimensions"`
	Metrics    []MetricEntry     `json:"metrics"`
	Alarms     []AlarmEntry      `json:"alarms,omitempty"`
}

MetricsConfig is the top-level CloudWatch metrics configuration injected into runtimes via PROMPTPACK_METRICS_CONFIG.

type ObservabilityConfig

type ObservabilityConfig struct {
	CloudWatchLogGroup string `json:"cloudwatch_log_group,omitempty"`
	TracingEnabled     bool   `json:"tracing_enabled,omitempty"`
}

ObservabilityConfig holds observability settings.

type Provider

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

Provider implements deploy.Provider for AWS Bedrock AgentCore.

func NewProvider

func NewProvider() *Provider

NewProvider creates a new Provider with the real AWS client factories. Credentials are resolved via the standard aws-sdk-go-v2/config chain.

func (*Provider) Apply

func (p *Provider) Apply(
	ctx context.Context, req *deploy.PlanRequest, callback deploy.ApplyCallback,
) (string, error)

Apply executes a deployment plan, streaming progress events via the callback. Resources are created in dependency order:

  1. Tool Gateway entries (from pack tools)
  2. Agent runtimes (one per agent member, or single for non-multi-agent)
  3. A2A wiring between agents
  4. Evaluators

When DryRun is enabled in config, Apply emits planned resource events without calling any AWS APIs and returns a preview of the deployment.

func (*Provider) Destroy

func (p *Provider) Destroy(
	ctx context.Context, req *deploy.DestroyRequest, callback deploy.DestroyCallback,
) error

Destroy tears down deployed resources in reverse dependency order, streaming progress events via the callback.

func (*Provider) GetProviderInfo

func (p *Provider) GetProviderInfo(_ context.Context) (*deploy.ProviderInfo, error)

GetProviderInfo returns metadata about the agentcore adapter.

func (*Provider) Import

Import imports an existing AWS resource into the adapter state.

func (*Provider) Plan

Plan generates a deployment plan for the given pack and config.

func (*Provider) Status

func (p *Provider) Status(
	ctx context.Context, req *deploy.StatusRequest,
) (*deploy.StatusResponse, error)

Status returns the current deployment status by checking each resource.

func (*Provider) ValidateConfig

func (p *Provider) ValidateConfig(
	_ context.Context, req *deploy.ValidateRequest,
) (*deploy.ValidateResponse, error)

ValidateConfig parses and validates the provider configuration. In addition to hard errors, it runs diagnostic checks and appends non-fatal warnings so the user can fix common misconfigurations.

type ProviderBinding

type ProviderBinding struct {
	// Name is the logical binding name, unique within the deploy config.
	// The binding named "default" is the runtime's primary provider.
	Name string `json:"name"`

	// Role is the capability this provider serves. Defaults to "llm".
	Role string `json:"role,omitempty"`

	// ArenaProvider names a provider from the arena config to inherit
	// type and model from.
	ArenaProvider string `json:"arena_provider,omitempty"`

	// Type and Model declare the provider inline, overriding anything
	// inherited via ArenaProvider.
	Type  string `json:"type,omitempty"`
	Model string `json:"model,omitempty"`
}

ProviderBinding declares one provider the deployed runtime should use.

A binding resolves its type and model either by naming a provider from the arena config (ArenaProvider, preserving "deploy what you tested") or by declaring them inline (keeping the deploy config self-contained). When both are given, the inline fields win field-by-field.

type ResolvedProvider

type ResolvedProvider struct {
	Name    string `json:"name"`
	Role    string `json:"role"`
	Type    string `json:"type"`
	Model   string `json:"model,omitempty"`
	Primary bool   `json:"primary,omitempty"`
}

ResolvedProvider is a fully-resolved binding, ready to be serialized into the PROMPTPACK_PROVIDERS env var the runtime reads.

type ResourceState

type ResourceState struct {
	Type     string            `json:"type"`
	Name     string            `json:"name"`
	ARN      string            `json:"arn,omitempty"`
	Status   string            `json:"status,omitempty"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

ResourceState describes a single deployed resource.

type StateStore

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

StateStore implements statestore.Store and statestore.MessageAppender by persisting conversation messages as events in an AWS Bedrock AgentCore Memory resource.

func NewStateStore

func NewStateStore(
	memoryID string, client DataPlaneClient,
) *StateStore

NewStateStore creates a new StateStore.

func (*StateStore) AppendMessages

func (s *StateStore) AppendMessages(
	ctx context.Context,
	id string,
	messages []types.Message,
) error

AppendMessages writes messages directly without requiring a prior Load.

func (*StateStore) Fork

func (s *StateStore) Fork(
	ctx context.Context, sourceID, newID string,
) error

Fork copies all events from sourceID into a new session newID.

func (*StateStore) Load

Load retrieves a conversation by listing all events for the given session ID.

func (*StateStore) Save

func (s *StateStore) Save(
	ctx context.Context,
	state *statestore.ConversationState,
) error

Save persists only new (delta) messages since the last Load or Save for this conversation.

type ToolsConfig

type ToolsConfig struct {
	CodeInterpreter bool `json:"code_interpreter,omitempty"`
}

ToolsConfig holds tool-related settings for the AgentCore runtime.

Jump to

Keyboard shortcuts

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