atlasic

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2025 License: MIT Imports: 21 Imported by: 1 module, 0 packages

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

README

ATLASIC

Go Reference Go Report Card

ATLASIC (A2A Toolkit Library to build Agent Service for Infrastructure on Cloud) is a Go library implementing the Agent-to-Agent (A2A) communication protocol. It provides a complete toolkit for building HTTP-based agent services with standardized messaging, task management, and event streaming capabilities.

Features

  • A2A Protocol Implementation: Full compliance with Agent-to-Agent communication specification
  • HTTP Server: Ready-to-use server with JSON-RPC and Server-Sent Events
  • Authentication: Built-in API Key and JWT authenticators with custom authentication support
  • Storage Backends: Local filesystem and AWS S3 adapters
  • Job Queue: In-memory and AWS SQS adapters for distributed processing
  • Event Sourcing: Complete task history with optimistic concurrency control
  • Streaming Support: Real-time agent communication with SSE
  • Content Negotiation: Flexible output format handling

Quick Start

package main

import (
    "context"
    "log"
    
    "github.com/mashiike/atlasic"
    "github.com/mashiike/atlasic/a2a"
)

func main() {
    // Define your agent
    agent := atlasic.NewAgent(
        a2a.AgentMetadata{
            Provider: "example-org",
            Version:  "1.0.0",
        },
        func(ctx context.Context, handle atlasic.TaskHandle) error {
            // Add your agent logic here
            return handle.AddMessage(ctx, []a2a.Part{
                a2a.NewTextPart("Hello from my agent!"),
            })
        },
    )

    // Start server
    server := &atlasic.Server{
        Addr:  ":8080",
        Agent: agent,
    }
    
    log.Fatal(server.RunWithContext(context.Background()))
}

Storage Options

Local Development
// Uses local filesystem storage (default)
server := &atlasic.Server{
    Addr:  ":8080",
    Agent: agent,
}
AWS S3 Storage
import "github.com/mashiike/atlasic/awsadp"

storage := awsadp.NewS3Storage(awsadp.S3StorageConfig{
    Client: s3Client,
    Bucket: "my-atlasic-bucket",
})

server := &atlasic.Server{
    Addr:    ":8080",
    Agent:   agent,
    Storage: storage,
}
AWS SQS JobQueue
import "github.com/mashiike/atlasic/awsadp"

jobQueue, _ := awsadp.NewSQSJobQueue(awsadp.SQSJobQueueConfig{
    Client:   sqsClient,
    QueueURL: "https://sqs.us-east-1.amazonaws.com/123456789012/my-queue",
})

server := &atlasic.Server{
    Addr:     ":8080",
    Agent:    agent,
    Storage:  storage,
    JobQueue: jobQueue,
}

Authentication

ATLASIC supports flexible authentication through the transport.Authenticator interface. Two built-in authenticators are provided:

API Key Authentication

Simple API key authentication for basic security:

server := &atlasic.Server{
    Addr:  ":8080",
    Agent: agent,
    Authenticator: atlasic.StaticAPIKeyAuthenticator{
        APIKey:     "your-secret-api-key",
        HeaderName: "X-API-Key", // Optional, defaults to "X-API-Key"
    },
}

Usage:

curl -X POST http://localhost:8080/ \
  -H "X-API-Key: your-secret-api-key" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc": "2.0", "method": "message.send", "params": {...}}'
JWT Authentication

Production-ready JWT authentication with audience and expiration validation:

import "github.com/golang-jwt/jwt/v5"

auth := atlasic.NewJWTAuthenticator([]byte("your-secret-key")).
    WithAudience("your-service-name").
    WithValidateFunc(func(claims jwt.MapClaims) error {
        // Custom validation logic
        if role, ok := claims["role"].(string); !ok || role != "admin" {
            return errors.New("admin role required")
        }
        return nil
    })

server := &atlasic.Server{
    Addr:          ":8080",
    Agent:         agent,
    Authenticator: auth,
}

Usage:

curl -X POST http://localhost:8080/ \
  -H "Authorization: Bearer your-jwt-token" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc": "2.0", "method": "message.send", "params": {...}}'
Custom Authentication

Implement your own authenticator by satisfying the transport.Authenticator interface:

type CustomAuthenticator struct {
    // your fields
}

func (c *CustomAuthenticator) Authenticate(ctx context.Context, r *http.Request) (*http.Request, error) {
    // Your authentication logic
    // Return modified request with authentication context
}

func (c *CustomAuthenticator) GetSecuritySchemes() map[string]a2a.SecurityScheme {
    // Return security scheme definition for AgentCard
}

func (c *CustomAuthenticator) GetSecurityRequirements() []map[string][]string {
    // Return security requirements for AgentCard
}
Accessing Authentication Context

In your agent implementation, you can access authentication information:

// For JWT authentication
if claims, ok := atlasic.GetJWTClaims(ctx); ok {
    userID, _ := atlasic.GetJWTSubject(ctx)
    // Use claims and userID
}

// For custom authentication
// Access your custom context values using context.Value()

API Usage

Send Message
curl -X POST http://localhost:8080/message/send \
  -H "Content-Type: application/json" \
  -d '{
    "message": {
      "messageId": "msg-1",
      "role": "user",
      "parts": [{"kind": "text", "text": "Hello"}]
    }
  }'
Stream Messages
curl -N http://localhost:8080/message/stream \
  -H "Accept: text/event-stream" \
  -H "Content-Type: application/json" \
  -d '{
    "message": {
      "messageId": "msg-2", 
      "role": "user",
      "parts": [{"kind": "text", "text": "Hello"}]
    }
  }'

Development

Prerequisites
Quick Development Setup
# Install dependencies
task deps

# Run unit tests
task test

# Run integration tests (includes S3Storage + SQSJobQueue)
task test:integration

# Run all quality checks
task check

# Generate coverage report
task test:coverage
Available Commands
# Core development
task build          # Build the project
task test            # Run unit tests
task test:integration # Run integration tests (starts Docker services)
task test:coverage   # Run tests with coverage report

# Code quality
task fmt             # Format code
task lint            # Run linter
task check           # Run all quality checks

# Docker services (for integration tests)
task docker:up       # Start minio + ElasticMQ
task docker:down     # Stop services
task docker:restart  # Restart services

# Cleanup
task clean           # Clean build artifacts
Manual Testing (without Task)
# Unit tests only
go test -short ./...

# Integration tests (requires Docker services)
docker-compose up -d
go test ./awsadp -v
docker-compose down

License

MIT License. See LICENSE for details.

Documentation

Overview

Package atlasic provides A2A (Agent-to-Agent) Toolkit Library for building supervisor-style multi-agent collaborative systems.

Package atlasic provides A2A (Agent-to-Agent) Toolkit Library for building supervisor-style multi-agent collaborative systems.

Index

Constants

View Source
const (
	// HistoryLengthAll specifies that GetTask should return all history
	// When this value is passed as historyLength, the Storage implementation
	// should return the complete task history without limitation
	HistoryLengthAll = -1
)

Storage constants

Variables

View Source
var (
	// ErrTaskNotFound is returned when a requested task does not exist
	ErrTaskNotFound = errors.New("task not found")
	// ErrContextNotFound is returned when a requested context does not exist
	ErrContextNotFound = errors.New("context not found")
	// ErrPushNotificationConfigNotFound is returned when push notification config does not exist
	ErrPushNotificationConfigNotFound = errors.New("push notification config not found")
	// ErrFileNotFound is returned when a requested file does not exist
	ErrFileNotFound = errors.New("file not found")
)

Storage error variables that implementations should return

View Source
var (
	// ErrTaskLockAlreadyAcquired is returned when a task lock is already held
	ErrTaskLockAlreadyAcquired = errors.New("task lock already acquired")
	// ErrTaskLockerClosed is returned when attempting to use a closed task locker
	ErrTaskLockerClosed = errors.New("task locker is closed")
)

TaskLocker error variables

View Source
var (
	// ErrJobQueueClosed is returned when attempting to use a closed job queue
	ErrJobQueueClosed = errors.New("job queue is closed")
)

JobQueue error variables

View Source
var (
	ErrSkipEvent = errors.New("skip event") // Special error to skip processing an event
)

Functions

func GetAgentServiceFromContext added in v0.2.0

func GetAgentServiceFromContext(ctx context.Context, extensionURIs ...string) (transport.AgentService, error)

GetAgentServiceFromContext retrieves the AgentService from the given context. If extensionURIs are provided, returns an AgentService with those extensions applied. Returns error if no AgentService is found in the context or extension processing fails.

func GetJWTClaims

func GetJWTClaims(ctx context.Context) (jwt.MapClaims, bool)

GetJWTClaims retrieves JWT claims from the request context

func GetJWTSubject

func GetJWTSubject(ctx context.Context) (string, bool)

GetJWTSubject retrieves the subject (sub) claim from JWT

func GetJWTToken

func GetJWTToken(ctx context.Context) (string, bool)

GetJWTToken retrieves the raw JWT token string from the request context

Types

type Agent

type Agent interface {
	GetMetadata(ctx context.Context) (*AgentMetadata, error)
	Execute(ctx context.Context, handle TaskHandle) (*a2a.Message, error)
}

func NewAgent

func NewAgent(metadata *AgentMetadata, f func(ctx context.Context, handle TaskHandle) (*a2a.Message, error)) Agent

type AgentMetadata

type AgentMetadata struct {
	Name               string             `json:"name"`
	Description        string             `json:"description"`
	Skills             []a2a.AgentSkill   `json:"skills"`
	DefaultInputModes  []string           `json:"default_input_modes,omitempty"`
	DefaultOutputModes []string           `json:"default_output_modes,omitempty"`
	Version            string             `json:"version"`
	Provider           *a2a.AgentProvider `json:"provider,omitempty"` // Optional provider information
}

AgentMetadata represents Agent-specific metadata AgentService is responsible for server-side settings like URLs, version, etc.

type AgentService

type AgentService struct {
	Storage Storage
	Agent   Agent

	// Streaming configuration
	StreamingPollInterval time.Duration // Public field for polling interval in streaming operations

	// Job processing configuration
	HeartbeatInterval        time.Duration // Public field for heartbeat interval during job execution
	CancelMonitoringInterval time.Duration // Public field for task cancellation monitoring interval

	// Logging
	Logger *slog.Logger // Public field for logging configuration

	// JobQueue for asynchronous agent execution
	JobQueue JobQueue // Public field for background job processing

	// TaskLocker for preventing concurrent task execution (optional)
	TaskLocker TaskLocker // Public field for task locking

	// DisableStreaming disables streaming capabilities when set to true
	DisableStreaming bool // Public field for disabling streaming features

	// DisablePushNotifications disables push notification capabilities when set to true
	DisablePushNotifications bool // Public field for disabling push notification features

	// PushNotifier for sending push notifications
	PushNotifier PushNotifier // Public field for push notification delivery

	// BaseEndpoint of the agent service
	BaseEndpoint string // Public field for agent base endpoint (defaults to transport.PlaceholderURL)
	// contains filtered or unexported fields
}

AgentService combines Agent execution with Storage capabilities It dynamically determines AgentCard capabilities based on Storage interface implementations

func NewAgentService

func NewAgentService(storage Storage, agent Agent) *AgentService

NewAgentService creates a new AgentService with default IDGenerator

func (*AgentService) CancelTask

func (s *AgentService) CancelTask(ctx context.Context, params a2a.TaskIDParams) (*a2a.Task, error)

func (*AgentService) Close

func (s *AgentService) Close() error

Close gracefully shuts down the AgentService and its workers

func (*AgentService) DeleteTaskPushNotificationConfig

func (s *AgentService) DeleteTaskPushNotificationConfig(ctx context.Context, params a2a.DeleteTaskPushNotificationConfigParams) error

func (*AgentService) GetAgentCard

func (s *AgentService) GetAgentCard(ctx context.Context) (*a2a.AgentCard, error)

func (*AgentService) GetTask

func (s *AgentService) GetTask(ctx context.Context, params a2a.TaskQueryParams) (*a2a.Task, error)

GetTask retrieves the current state of a task from the agent

func (*AgentService) GetTaskPushNotificationConfig

func (s *AgentService) GetTaskPushNotificationConfig(ctx context.Context, params a2a.GetTaskPushNotificationConfigParams) (*a2a.TaskPushNotificationConfig, error)

func (*AgentService) ListTaskPushNotificationConfig

func (s *AgentService) ListTaskPushNotificationConfig(ctx context.Context, params a2a.TaskIDParams) ([]a2a.TaskPushNotificationConfig, error)

func (*AgentService) NewTaskHandle

func (s *AgentService) NewTaskHandle(ctx context.Context, params TaskHandleParams) TaskHandle

func (*AgentService) ProcessJob

func (s *AgentService) ProcessJob(ctx context.Context, job *Job) error

ProcessJob processes a single job - used for FaaS environments This method can be called directly from Lambda handlers

func (*AgentService) SendMessage

func (s *AgentService) SendMessage(ctx context.Context, params a2a.MessageSendParams) (*a2a.SendMessageResult, error)

SendMessage implements the core A2A message sending workflow

func (*AgentService) SendStreamingMessage

func (s *AgentService) SendStreamingMessage(ctx context.Context, params a2a.MessageSendParams) (<-chan a2a.StreamResponse, error)

func (*AgentService) SetIDGenerator

func (s *AgentService) SetIDGenerator(idGen IDGenerator)

SetIDGenerator sets a custom IDGenerator for the AgentService This replaces the default DefaultIDGenerator set in NewAgentService

func (*AgentService) SetTaskPushNotificationConfig

func (s *AgentService) SetTaskPushNotificationConfig(ctx context.Context, config a2a.TaskPushNotificationConfig) (*a2a.TaskPushNotificationConfig, error)

func (*AgentService) Start

func (s *AgentService) Start(ctx context.Context) error

Start initiates background workers for processing jobs from the JobQueue This method should be called for long-running processes (ECS/Server)

func (*AgentService) SupportedOutputModes

func (s *AgentService) SupportedOutputModes(ctx context.Context) ([]string, error)

func (*AgentService) TaskResubscription

func (s *AgentService) TaskResubscription(ctx context.Context, params a2a.TaskIDParams) (<-chan a2a.StreamResponse, error)

type DefaultIDGenerator

type DefaultIDGenerator struct{}

DefaultIDGenerator implements IDGenerator using UUID v7

func (*DefaultIDGenerator) GenerateContextID

func (g *DefaultIDGenerator) GenerateContextID() string

GenerateContextID generates a context ID using UUID v7

func (*DefaultIDGenerator) GenerateMessageID

func (g *DefaultIDGenerator) GenerateMessageID() string

GenerateMessageID generates a message ID using UUID v7

func (*DefaultIDGenerator) GeneratePushNotificationConfigID

func (g *DefaultIDGenerator) GeneratePushNotificationConfigID() string

GeneratePushNotificationConfigID generates a push notification config ID using UUID v7

func (*DefaultIDGenerator) GenerateTaskID

func (g *DefaultIDGenerator) GenerateTaskID() string

GenerateTaskID generates a task ID using UUID v7

type DefaultPushNotifier

type DefaultPushNotifier struct {
	Client *http.Client
}

DefaultPushNotifier implements PushNotifier using standard HTTP client

func NewDefaultPushNotifier

func NewDefaultPushNotifier() *DefaultPushNotifier

NewDefaultPushNotifier creates a new DefaultPushNotifier with default HTTP client

func (*DefaultPushNotifier) Close

func (n *DefaultPushNotifier) Close() error

Close gracefully shuts down the notifier

func (*DefaultPushNotifier) Notify

Notify sends HTTP POST request to the configured URL with the event data

func (*DefaultPushNotifier) ValidateEndpoint

func (n *DefaultPushNotifier) ValidateEndpoint(ctx context.Context, config a2a.PushNotificationConfig) error

ValidateEndpoint performs no validation - always returns nil (no-check implementation)

type EventParser added in v0.1.0

type EventParser interface {
	// ParseEvent parses an event and returns a JobConfig for it
	ParseEvent(ctx context.Context, event json.RawMessage) (*Job, error)
}

type FileSystemStorage

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

FileSystemStorage implements Storage interface using filesystem with JSON files

func NewFileSystemStorage

func NewFileSystemStorage(basePath string) (*FileSystemStorage, error)

NewFileSystemStorage creates a new FileSystemStorage instance

func (*FileSystemStorage) Append

func (fs *FileSystemStorage) Append(ctx context.Context, contextID string, taskID string, expected uint64, events []a2a.StreamResponse) (next uint64, err error)

func (*FileSystemStorage) DeleteContextFile

func (fs *FileSystemStorage) DeleteContextFile(ctx context.Context, contextID, path string) error

func (*FileSystemStorage) DeleteTaskFile

func (fs *FileSystemStorage) DeleteTaskFile(ctx context.Context, taskID, path string) error

func (*FileSystemStorage) DeleteTaskPushNotificationConfig

func (fs *FileSystemStorage) DeleteTaskPushNotificationConfig(ctx context.Context, taskID, configID string) error

func (*FileSystemStorage) GetTask

func (fs *FileSystemStorage) GetTask(ctx context.Context, taskID string, historyLength int) (*a2a.Task, uint64, error)

func (*FileSystemStorage) GetTaskPushNotificationConfig

func (fs *FileSystemStorage) GetTaskPushNotificationConfig(ctx context.Context, taskID, configID string) (a2a.TaskPushNotificationConfig, error)

func (*FileSystemStorage) ListContextFiles

func (fs *FileSystemStorage) ListContextFiles(ctx context.Context, contextID, pathPrefix string) ([]string, error)

func (*FileSystemStorage) ListTaskFiles

func (fs *FileSystemStorage) ListTaskFiles(ctx context.Context, taskID, pathPrefix string) ([]string, error)

func (*FileSystemStorage) ListTaskPushNotificationConfig

func (fs *FileSystemStorage) ListTaskPushNotificationConfig(ctx context.Context, taskID string) ([]a2a.TaskPushNotificationConfig, error)

func (*FileSystemStorage) ListTasksByContext

func (fs *FileSystemStorage) ListTasksByContext(ctx context.Context, contextID string, historyLength int) ([]*a2a.Task, []uint64, error)

func (*FileSystemStorage) Load

func (fs *FileSystemStorage) Load(ctx context.Context, contextID string, taskID string, from uint64, limit int) ([]a2a.StreamResponse, uint64, error)

func (*FileSystemStorage) OpenContextFile

func (fs *FileSystemStorage) OpenContextFile(ctx context.Context, contextID, path string, flag int, perm os.FileMode) (fs.File, error)

func (*FileSystemStorage) OpenTaskFile

func (fs *FileSystemStorage) OpenTaskFile(ctx context.Context, taskID, path string, flag int, perm os.FileMode) (fs.File, error)

func (*FileSystemStorage) SaveTask

func (fs *FileSystemStorage) SaveTask(ctx context.Context, task *a2a.Task, expectedVersion, newVersion uint64) error

func (*FileSystemStorage) SaveTaskPushNotificationConfig

func (fs *FileSystemStorage) SaveTaskPushNotificationConfig(ctx context.Context, config a2a.TaskPushNotificationConfig) error

type IDGenerator

type IDGenerator interface {
	// GenerateTaskID generates a unique task identifier
	GenerateTaskID() string
	// GenerateContextID generates a unique context identifier
	GenerateContextID() string
	// GenerateMessageID generates a unique message identifier
	GenerateMessageID() string
	// GeneratePushNotificationConfigID generates a unique push notification config identifier
	GeneratePushNotificationConfigID() string
}

IDGenerator provides unique ID generation for A2A entities

type InMemoryJobQueue

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

InMemoryJobQueue is a simple in-memory implementation of JobQueue using channels

func NewInMemoryJobQueue

func NewInMemoryJobQueue(size int) *InMemoryJobQueue

NewInMemoryJobQueue creates a new in-memory job queue with the specified buffer size

func (*InMemoryJobQueue) Close

func (q *InMemoryJobQueue) Close() error

Close gracefully shuts down the queue

func (*InMemoryJobQueue) Dequeue

func (q *InMemoryJobQueue) Dequeue(ctx context.Context) (*Job, error)

Dequeue retrieves a job from the queue, blocking until one is available

func (*InMemoryJobQueue) Enqueue

func (q *InMemoryJobQueue) Enqueue(ctx context.Context, config JobConfig) error

Enqueue adds a new job to the queue

type InMemoryTaskLocker

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

InMemoryTaskLocker is a simple in-memory implementation of TaskLocker

func NewInMemoryTaskLocker

func NewInMemoryTaskLocker() *InMemoryTaskLocker

NewInMemoryTaskLocker creates a new in-memory task locker

func (*InMemoryTaskLocker) Close

func (l *InMemoryTaskLocker) Close() error

Close gracefully shuts down the task locker

func (*InMemoryTaskLocker) Lock

func (l *InMemoryTaskLocker) Lock(ctx context.Context, taskID string) (func(), error)

Lock attempts to acquire a lock for the specified task

type JWTAuthenticator

type JWTAuthenticator struct {
	// SecretKey is used for HMAC signing methods (HS256, HS384, HS512)
	SecretKey []byte

	// SigningMethod specifies the JWT signing method (default: HS256)
	SigningMethod jwt.SigningMethod

	// Audience specifies the expected audience (aud) claim
	// If empty, audience validation is skipped
	Audience string

	// ValidateFunc allows custom validation of JWT claims
	// If nil, only signature, expiration, and audience are validated
	ValidateFunc func(claims jwt.MapClaims) error
}

JWTAuthenticator implements JWT (JSON Web Token) based authentication

func NewJWTAuthenticator

func NewJWTAuthenticator(secretKey []byte) *JWTAuthenticator

NewJWTAuthenticator creates a new JWT authenticator with HMAC-SHA256

func (*JWTAuthenticator) Authenticate

func (j *JWTAuthenticator) Authenticate(ctx context.Context, r *http.Request) (*http.Request, error)

Authenticate implements the transport.Authenticator interface

func (*JWTAuthenticator) GetSecurityRequirements

func (j *JWTAuthenticator) GetSecurityRequirements(r *http.Request) []map[string][]string

GetSecurityRequirements implements the transport.Authenticator interface

func (*JWTAuthenticator) GetSecuritySchemes

func (j *JWTAuthenticator) GetSecuritySchemes(r *http.Request) map[string]a2a.SecurityScheme

GetSecuritySchemes implements the transport.Authenticator interface

func (*JWTAuthenticator) WithAudience

func (j *JWTAuthenticator) WithAudience(audience string) *JWTAuthenticator

WithAudience sets the expected audience for JWT validation

func (*JWTAuthenticator) WithSigningMethod

func (j *JWTAuthenticator) WithSigningMethod(method jwt.SigningMethod) *JWTAuthenticator

WithSigningMethod sets the JWT signing method

func (*JWTAuthenticator) WithValidateFunc

func (j *JWTAuthenticator) WithValidateFunc(fn func(claims jwt.MapClaims) error) *JWTAuthenticator

WithValidateFunc sets a custom validation function for JWT claims

type Job

type Job struct {
	TaskID              string
	ContextID           string
	IncomingMessageID   string      // ID of the incoming message that triggered this job
	AcceptedOutputModes []string    // Accepted output modes from MessageSendConfiguration
	HTTPHeaders         http.Header // HTTP headers to preserve for Agent execution (filtered for security)

	// Function fields for queue operations
	ExtendTimeoutFunc func(context.Context, time.Duration) error
	CompleteFunc      func() error
	FailFunc          func() error
}

Job represents a background job for agent execution

type JobConfig

type JobConfig struct {
	TaskID              string
	ContextID           string
	IncomingMessageID   string      // ID of the incoming message that triggered this job
	AcceptedOutputModes []string    // Accepted output modes from MessageSendConfiguration
	HTTPHeaders         http.Header // HTTP headers to preserve for Agent execution (filtered for security)
}

JobConfig represents the configuration for creating a job

type JobQueue

type JobQueue interface {
	// Enqueue adds a new job to the queue
	Enqueue(ctx context.Context, config JobConfig) error

	// Dequeue retrieves a job from the queue, blocking until one is available
	Dequeue(ctx context.Context) (*Job, error)

	// Close gracefully shuts down the queue
	Close() error
}

JobQueue provides an interface for background job management

type PushNotificationError

type PushNotificationError struct {
	StatusCode int
	URL        string
}

PushNotificationError represents an error during push notification delivery

func (*PushNotificationError) Error

func (e *PushNotificationError) Error() string

type PushNotifier

type PushNotifier interface {
	// Notify sends a push notification for the given event (at-least-once delivery)
	Notify(ctx context.Context, config a2a.PushNotificationConfig, event a2a.StreamResponse) error

	// ValidateEndpoint checks if the notification endpoint is valid and reachable
	ValidateEndpoint(ctx context.Context, config a2a.PushNotificationConfig) error

	// Close gracefully shuts down the notifier
	Close() error
}

PushNotifier handles push notification delivery for task events

type RemoteAgent

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

RemoteAgent implements Agent interface using transport.Client to communicate with remote agents

func NewRemoteAgent

func NewRemoteAgent(baseURL string, opts ...transport.ClientOption) *RemoteAgent

NewRemoteAgent creates a new RemoteAgent that communicates with a remote agent via HTTP

func (*RemoteAgent) Execute

func (r *RemoteAgent) Execute(ctx context.Context, handle TaskHandle) (*a2a.Message, error)

Execute executes a task on the remote agent

func (*RemoteAgent) GetMetadata

func (r *RemoteAgent) GetMetadata(ctx context.Context) (*AgentMetadata, error)

GetMetadata retrieves and caches agent metadata from the remote agent

type Server

type Server struct {
	// Addr specifies the TCP address for the server to listen on,
	// in the form "host:port". If empty, ":80" is used.
	Addr string

	// RPCPath specifies the base path for the JSON-RPC API.
	RPCPath string

	// AgentCardPath specifies the path for the agent card endpoint.
	AgentCardPath string

	// Storage specifies the storage backend for tasks and events.
	// If nil, a FileSystemStorage with default location is used.
	Storage Storage

	// JobQueue specifies the job queue for asynchronous agent execution.
	// If nil, an InMemoryJobQueue with default size is used.
	JobQueue JobQueue

	// Agent specifies the agent implementation.
	// This field is required and cannot be nil.
	Agent Agent

	// Authenticator specifies the authentication provider for the server.
	// If nil, no authentication is required.
	Authenticator transport.Authenticator

	// Extensions specifies the extensions to be used by the server.
	// Extensions are applied to the transport layer.
	Extensions []transport.Extension

	LambdaOptions []lambda.Option // Options for AWS Lambda integration
	// contains filtered or unexported fields
}

Server provides a high-level interface for running an A2A agent service with sensible defaults and easy configuration, similar to http.Server

func (*Server) AddExtension added in v0.1.0

func (s *Server) AddExtension(extensions ...transport.Extension)

AddExtension adds A2A protocol extensions to the server. Extensions are applied to the transport layer for request/response processing.

func (*Server) Handle added in v0.1.0

func (s *Server) Handle(pattern string, handler http.Handler)

Handle registers a handler for the given pattern. It panics if the pattern is already registered or conflicts with A2A endpoints.

func (*Server) HandleFunc added in v0.1.0

func (s *Server) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))

HandleFunc registers a handler function for the given pattern. It panics if the pattern is already registered or conflicts with A2A endpoints.

func (*Server) Handler added in v0.2.0

func (s *Server) Handler(r *http.Request) (http.Handler, string)

Handler returns the HTTP handler for the server.

func (*Server) Run

func (s *Server) Run() error

Run starts the server and blocks until the server shuts down.

func (*Server) RunWithContext

func (s *Server) RunWithContext(ctx context.Context) error

RunWithContext starts the server with the given context and blocks until the server shuts down or the context is cancelled.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections.

func (*Server) Use

func (s *Server) Use(middlewares ...func(http.Handler) http.Handler)

Use adds HTTP middlewares to the server. Middlewares are applied to all HTTP requests in the order they are added.

type StaticAPIKeyAuthenticator

type StaticAPIKeyAuthenticator struct {
	APIKey     string // The expected API key value
	HeaderName string // The header name to check (default: X-API-Key)
}

StaticAPIKeyAuthenticator implements a simple static API key authenticator This is a sample implementation for demonstration purposes that only checks API key matching

func (StaticAPIKeyAuthenticator) Authenticate

func (s StaticAPIKeyAuthenticator) Authenticate(ctx context.Context, r *http.Request) (*http.Request, error)

Authenticate implements the transport.Authenticator interface

func (StaticAPIKeyAuthenticator) GetSecurityRequirements

func (s StaticAPIKeyAuthenticator) GetSecurityRequirements(r *http.Request) []map[string][]string

GetSecurityRequirements implements the transport.Authenticator interface

func (StaticAPIKeyAuthenticator) GetSecuritySchemes

func (s StaticAPIKeyAuthenticator) GetSecuritySchemes(r *http.Request) map[string]a2a.SecurityScheme

GetSecuritySchemes implements the transport.Authenticator interface

type Storage

type Storage interface {
	// Task operations (Query side)
	GetTask(ctx context.Context, taskID string, historyLength int) (*a2a.Task, uint64, error)
	SaveTask(ctx context.Context, task *a2a.Task, expectedVersion, newVersion uint64) error
	ListTasksByContext(ctx context.Context, contextID string, historyLength int) ([]*a2a.Task, []uint64, error)

	// Event stream operations (Command side) - enables streaming capabilities
	Append(ctx context.Context, contextID string, taskID string, expected uint64, events []a2a.StreamResponse) (next uint64, err error)
	Load(ctx context.Context, contextID string, taskID string, from uint64, limit int) ([]a2a.StreamResponse, uint64, error)

	// Push notification configuration operations (supports multiple configs per task)
	SaveTaskPushNotificationConfig(ctx context.Context, config a2a.TaskPushNotificationConfig) error
	GetTaskPushNotificationConfig(ctx context.Context, taskID, configID string) (a2a.TaskPushNotificationConfig, error)
	ListTaskPushNotificationConfig(ctx context.Context, taskID string) ([]a2a.TaskPushNotificationConfig, error)
	DeleteTaskPushNotificationConfig(ctx context.Context, taskID, configID string) error

	// Context virtual filesystem operations - enables context-scoped file sharing
	OpenContextFile(ctx context.Context, contextID, path string, flag int, perm os.FileMode) (fs.File, error)
	ListContextFiles(ctx context.Context, contextID, pathPrefix string) ([]string, error)
	DeleteContextFile(ctx context.Context, contextID, path string) error

	// Task virtual filesystem operations - enables task-scoped file operations
	OpenTaskFile(ctx context.Context, taskID, path string, flag int, perm os.FileMode) (fs.File, error)
	ListTaskFiles(ctx context.Context, taskID, pathPrefix string) ([]string, error)
	DeleteTaskFile(ctx context.Context, taskID, path string) error
}

Storage provides task persistence and event stream operations (CQRS-based) Implementations should return well-defined errors for consistent handling:

  • ErrTaskNotFound: when a requested task does not exist
  • ErrContextNotFound: when a requested context does not exist
  • ErrPushNotificationConfigNotFound: when push notification config does not exist
  • ErrFileNotFound: when a requested file does not exist

type TaskHandle

type TaskHandle interface {
	// Task information access
	GetContextID() string
	GetTaskID() string
	GetTask(ctx context.Context, historyLength int) (*a2a.Task, error)
	GetInitialStatus() a2a.TaskStatus // Get task status at the time of dequeue/creation
	GetAcceptedOutputModes() []string // Get accepted output modes for this task
	GetIncomingMessage() a2a.Message  // Get the incoming message that triggered this task
	GetHTTPHeaders() http.Header      // Get HTTP headers from the original request

	// Task state mutations - implementation handles streaming notifications automatically
	// Role is fixed to RoleAgent for all TaskHandle operations
	AddMessage(ctx context.Context, parts []a2a.Part, optFns ...func(*a2a.MessageOptions)) (string, error)
	UpdateStatus(ctx context.Context, state a2a.TaskState, parts []a2a.Part, optFns ...func(*a2a.MessageOptions)) (a2a.TaskStatus, error)
	UpsertArtifact(ctx context.Context, artifact a2a.Artifact) error

	// History-specific operations - enables differential message retrieval
	GetLastMessageID(ctx context.Context) (string, error)
	GetHistorySince(ctx context.Context, sinceMessageID string) ([]a2a.Message, error)

	// Context virtual filesystem operations - enables context-scoped file sharing
	OpenContextFile(ctx context.Context, path string, flag int, perm os.FileMode) (fs.File, error)
	ListContextFiles(ctx context.Context, pathPrefix string) ([]string, error)
	DeleteContextFile(ctx context.Context, path string) error

	// Task virtual filesystem operations - enables task-scoped file operations
	OpenTaskFile(ctx context.Context, path string, flag int, perm os.FileMode) (fs.File, error)
	ListTaskFiles(ctx context.Context, pathPrefix string) ([]string, error)
	DeleteTaskFile(ctx context.Context, path string) error
}

type TaskHandleParams

type TaskHandleParams struct {
	ContextID           string
	TaskID              string
	InitialStatus       a2a.TaskStatus // Status at the time of task handle creation
	AcceptedOutputModes []string       // Accepted output modes for this task
	IncomingMessage     a2a.Message    // The incoming message that triggered this task
	HTTPHeaders         http.Header    // HTTP headers from the original request
}

type TaskLocker

type TaskLocker interface {
	// Lock attempts to acquire a lock for the specified task
	// Returns a function to unlock when successful, or an error if lock cannot be acquired
	Lock(ctx context.Context, taskID string) (unlock func(), err error)
	// Close gracefully shuts down the task locker
	Close() error
}

TaskLocker provides task-level locking to prevent concurrent execution

type TaskStatusError

type TaskStatusError interface {
	error
	ToTaskStatus() a2a.TaskStatus
}

TaskStatusError allows errors to define custom task status for more precise error handling

type TaskUpdater

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

TaskUpdater handles task state updates using Event Sourcing pattern It maintains the current task state and applies StreamResponse events to update it

func NewTaskUpdater

func NewTaskUpdater(snapshotTask *a2a.Task, snapshotVersion uint64) *TaskUpdater

NewTaskUpdater creates a new TaskUpdater with initial snapshot and version

func (*TaskUpdater) AddMessage

func (tu *TaskUpdater) AddMessage(message a2a.Message)

AddMessage adds a message to the task and creates corresponding event

func (*TaskUpdater) GetExpectedVersion

func (tu *TaskUpdater) GetExpectedVersion() uint64

GetExpectedVersion returns the initial version for optimistic concurrency control

func (*TaskUpdater) GetPendingEvents

func (tu *TaskUpdater) GetPendingEvents() []a2a.StreamResponse

GetPendingEvents returns all pending events that need to be appended to the stream

func (*TaskUpdater) GetTask

func (tu *TaskUpdater) GetTask() *a2a.Task

GetTask returns the current task state

func (*TaskUpdater) GetVersion

func (tu *TaskUpdater) GetVersion() uint64

GetVersion returns the current version

func (*TaskUpdater) UpdateStatus

func (tu *TaskUpdater) UpdateStatus(status a2a.TaskStatus)

UpdateStatus updates the task status and creates corresponding event

func (*TaskUpdater) UpsertArtifact

func (tu *TaskUpdater) UpsertArtifact(artifact a2a.Artifact)

UpsertArtifact upserts an artifact and creates corresponding event

Directories

Path Synopsis
_examples
client command
extensions command
lambda command
server command
Package a2a provides Agent-to-Agent (A2A) Protocol implementation for ATLASIC.
Package a2a provides Agent-to-Agent (A2A) Protocol implementation for ATLASIC.
Package atlasictest provides testing utilities for ATLASIC A2A agents.
Package atlasictest provides testing utilities for ATLASIC A2A agents.
Package awsadp provides AWS adapters for ATLASIC interfaces.
Package awsadp provides AWS adapters for ATLASIC interfaces.
Package model provides core types and utilities for language model integration, tool use, reasoning, and model provider management in the atlasic project.
Package model provides core types and utilities for language model integration, tool use, reasoning, and model provider management in the atlasic project.
bedrock
Package bedrock provides integration with AWS Bedrock for model inference and conversation APIs.
Package bedrock provides integration with AWS Bedrock for model inference and conversation APIs.
ollama
Package ollama provides a model provider implementation for interacting with the Ollama API.
Package ollama provides a model provider implementation for interacting with the Ollama API.
openai
Package openai provides integration with OpenAI for image generation using GPT Image 1.
Package openai provides integration with OpenAI for image generation using GPT Image 1.
Package prompt provides utilities for building prompts and messages for LLM interactions.
Package prompt provides utilities for building prompts and messages for LLM interactions.
Package transport provides functionality for handling network transport mechanisms.
Package transport provides functionality for handling network transport mechanisms.

Jump to

Keyboard shortcuts

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