a2a

package
v1.3.19 Latest Latest
Warning

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

Go to latest
Published: May 23, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SkillCodeEdit    = "code-edit"
	SkillFileSearch  = "file-search"
	SkillCommandExec = "command-exec"
	SkillGitOps      = "git-ops"
	SkillCodeReview  = "code-review"
	SkillFullTask    = "full-task"
)

SkillID constants — generic across all ggcode instances.

View Source
const A2AProtocolVersion = "1.0"

A2AProtocolVersion is the implemented A2A protocol version.

Variables

View Source
var (
	ErrParseError     = &JSONRPCError{Code: -32700, Message: "Parse error"}
	ErrInvalidRequest = &JSONRPCError{Code: -32600, Message: "Invalid request"}
	ErrMethodNotFound = &JSONRPCError{Code: -32601, Message: "Method not found"}
	ErrInvalidParams  = &JSONRPCError{Code: -32602, Message: "Invalid params"}
	ErrInternal       = &JSONRPCError{Code: -32603, Message: "Internal error"}

	// A2A-specific error codes (per spec, -32000 to -32099).
	ErrTaskNotFound              = &JSONRPCError{Code: -32001, Message: "Task not found"}
	ErrTaskNotCancelable         = &JSONRPCError{Code: -32002, Message: "Task not cancelable"}
	ErrPushNotSupported          = &JSONRPCError{Code: -32003, Message: "Push notification not supported"}
	ErrUnsupportedOp             = &JSONRPCError{Code: -32004, Message: "Unsupported operation"}
	ErrContentType               = &JSONRPCError{Code: -32005, Message: "Incompatible content types"}
	ErrAuthRequired              = &JSONRPCError{Code: -32006, Message: "Authentication required"}
	ErrUnsupportedMode           = &JSONRPCError{Code: -32007, Message: "Unsupported output mode"}
	ErrExtendedCardNotConfigured = &JSONRPCError{Code: -32008, Message: "Extended agent card not configured"}
)

Standard JSON-RPC error codes.

Functions

func GenerateInstanceID

func GenerateInstanceID() string

GenerateInstanceID creates a unique ID for this ggcode process.

func MCPBridgeTools

func MCPBridgeTools(client *Client) []tool.Tool

MCPBridgeTools returns MCP-compatible tool definitions that wrap A2A client operations. These tools are for external MCP clients (Claude, Cursor, Copilot, etc.) that don't speak A2A natively. They let the MCP client discover and interact with this ggcode instance as if it were a set of MCP tools.

ggcode instances talking to each other should use A2A protocol directly, NOT through MCP.

func PreferredIP added in v1.1.47

func PreferredIP() string

PreferredIP returns the preferred outbound IP address on the default route. This is the IP that other machines on the same LAN can reach. Falls back to 127.0.0.1 if no suitable address is found.

func PreferredInterface added in v1.1.47

func PreferredInterface() *net.Interface

PreferredInterface returns the net.Interface that carries the default-route IP. Returns nil if not found (caller should fall back to default behavior).

func TestHandler added in v1.1.88

func TestHandler() string

TestHandler is a placeholder handler.

func TestHandlerV2 added in v1.1.88

func TestHandlerV2() string

TestHandlerV2 is the v2 handler.

Types

type AgentCapabilities

type AgentCapabilities struct {
	Streaming         bool `json:"streaming"`
	PushNotifications bool `json:"pushNotifications"`
	ExtendedAgentCard bool `json:"extendedAgentCard,omitempty"`
}

AgentCapabilities declares optional protocol features.

type AgentCard

type AgentCard struct {
	Name               string                `json:"name"`
	Description        string                `json:"description"`
	URL                string                `json:"url"`
	Version            string                `json:"version,omitempty"`
	Provider           *AgentProvider        `json:"provider,omitempty"`
	Capabilities       AgentCapabilities     `json:"capabilities"`
	SecuritySchemes    map[string]Security   `json:"securitySchemes,omitempty"` // deprecated, kept for compat
	Security           []map[string][]string `json:"security,omitempty"`        // security requirements
	DefaultInputModes  []string              `json:"defaultInputModes"`
	DefaultOutputModes []string              `json:"defaultOutputModes"`
	Skills             []Skill               `json:"skills"`
	Interfaces         []AgentInterface      `json:"interfaces,omitempty"`
	Extensions         []AgentExtension      `json:"extensions,omitempty"`
	Metadata           interface{}           `json:"metadata,omitempty"`
}

AgentCard describes an agent's identity, capabilities, and skills. Served at GET /.well-known/agent.json

type AgentExtension added in v1.1.46

type AgentExtension struct {
	URI         string                 `json:"uri"`
	Description string                 `json:"description,omitempty"`
	Required    bool                   `json:"required,omitempty"`
	Params      map[string]interface{} `json:"params,omitempty"`
}

AgentExtension declares an optional extension the agent supports.

type AgentInterface added in v1.1.46

type AgentInterface struct {
	Type     string                 `json:"type"` // "json-rpc-2.0", "grpc", "rest"
	URL      string                 `json:"url"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

AgentInterface describes a protocol binding (JSON-RPC, gRPC, REST).

type AgentProvider

type AgentProvider struct {
	URL          string `json:"url"`
	Organization string `json:"organization"`
}

AgentProvider identifies the organization behind the agent.

type Artifact

type Artifact struct {
	ArtifactID string          `json:"artifactId"`
	Parts      []Part          `json:"parts"`
	Append     bool            `json:"append,omitempty"`
	LastChunk  bool            `json:"lastChunk,omitempty"`
	Metadata   json.RawMessage `json:"metadata,omitempty"`
}

Artifact holds task output.

type AuthenticationInfo added in v1.1.46

type AuthenticationInfo struct {
	Schemes    []string `json:"schemes"`
	Credential string   `json:"credential,omitempty"`
}

AuthenticationInfo carries credentials for push notification callbacks.

type CancelTaskParams

type CancelTaskParams struct {
	ID string `json:"id"`
}

CancelTaskParams is the params for "tasks/cancel".

type Client

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

Client is an A2A protocol client that sends tasks to remote agents.

func NewClient

func NewClient(baseURL, apiKey string, opts ...ClientOption) *Client

NewClient creates a new A2A client targeting the given server URL.

func (*Client) AuthMethod added in v1.1.46

func (c *Client) AuthMethod() string

AuthMethod returns the negotiated authentication method.

func (*Client) CancelTask

func (c *Client) CancelTask(ctx context.Context, taskID string) (*Task, error)

CancelTask requests cancellation of a running task.

func (*Client) Card

func (c *Client) Card() *AgentCard

Card returns the cached agent card (nil if Discover hasn't been called).

func (*Client) DeletePushConfig added in v1.1.46

func (c *Client) DeletePushConfig(ctx context.Context, id string) error

DeletePushConfig removes a push notification config by ID.

func (*Client) Discover

func (c *Client) Discover(ctx context.Context) (*AgentCard, error)

Discover fetches and caches the remote agent's Agent Card.

func (*Client) GetExtendedAgentCard added in v1.1.46

func (c *Client) GetExtendedAgentCard(ctx context.Context) (json.RawMessage, error)

GetExtendedAgentCard retrieves the authenticated extended agent card.

func (*Client) GetPushConfig added in v1.1.46

func (c *Client) GetPushConfig(ctx context.Context, id string) (*PushNotificationConfig, error)

GetPushConfig retrieves a push notification config by ID.

func (*Client) GetTask

func (c *Client) GetTask(ctx context.Context, taskID string) (*Task, error)

GetTask retrieves the current state of a task.

func (*Client) ListPushConfigs added in v1.1.46

func (c *Client) ListPushConfigs(ctx context.Context) ([]PushNotificationConfig, error)

ListPushConfigs returns all push notification configs.

func (*Client) ListTasks added in v1.1.46

func (c *Client) ListTasks(ctx context.Context, pageToken string, pageSize int) (*ListTasksResult, error)

ListTasks retrieves a paginated list of tasks from the remote agent.

func (*Client) NegotiateAuth added in v1.1.46

func (c *Client) NegotiateAuth() error

NegotiateAuth reads the Agent Card's securitySchemes and prepares the appropriate authentication mechanism.

This must be called after Discover(). It checks what the server requires and configures the client accordingly:

  • If server declares no security → no auth needed
  • If server has apiKey scheme and client has apiKey → use API Key
  • If server has oauth2/openIdConnect scheme → use Bearer token (must be set via WithBearerToken or SetBearerToken before calling)
  • If server has mutualTLS scheme → use mTLS (must be configured via WithMTLS option)

Returns an error if the server requires an auth mechanism the client hasn't been configured for.

func (*Client) Resubscribe

func (c *Client) Resubscribe(ctx context.Context, taskID string) (<-chan JSONRPCResponse, error)

Resubscribe reconnects to a task's SSE stream. Use this when a previous SendMessageStream connection was interrupted.

func (*Client) SendMessage

func (c *Client) SendMessage(ctx context.Context, skill, text string, existingTaskID ...string) (*Task, error)

SendMessage sends a synchronous message and waits for task completion. If existingTaskID is non-empty, continues an existing task (multi-turn).

func (*Client) SendMessageStream

func (c *Client) SendMessageStream(ctx context.Context, skill, text string) (<-chan JSONRPCResponse, error)

SendMessageStream sends a message and returns a channel of SSE events.

func (*Client) SendMessageWithConfig added in v1.1.46

func (c *Client) SendMessageWithConfig(ctx context.Context, params SendMessageParams) (*Task, error)

SendMessageWithConfig sends a message with full configuration options.

func (*Client) SetAPIKey added in v1.1.46

func (c *Client) SetAPIKey(key string)

SetAPIKey updates the API key.

func (*Client) SetBearerToken added in v1.1.46

func (c *Client) SetBearerToken(token string)

SetBearerToken updates the bearer token (e.g., after OAuth2 token refresh).

func (*Client) SetPushConfig added in v1.1.46

SetPushConfig creates or updates a push notification config.

type ClientOption added in v1.1.46

type ClientOption func(*Client)

ClientOption configures a Client.

func WithBearerToken added in v1.1.46

func WithBearerToken(token string) ClientOption

WithBearerToken sets a pre-obtained OAuth2/OIDC bearer token.

func WithMTLS added in v1.1.46

func WithMTLS(tlsConfig *tls.Config) ClientOption

WithMTLS configures the client to use mutual TLS.

func WithTokenProvider added in v1.1.46

func WithTokenProvider(p TokenProvider) ClientOption

WithTokenProvider sets a token provider for automatic OAuth2 token acquisition. When NegotiateAuth encounters a server requiring bearer auth and no token is available, it calls the provider to obtain one (e.g., via PKCE or Device flow).

type FilePart

type FilePart struct {
	Name  string `json:"name,omitempty"`
	MIME  string `json:"mimeType,omitempty"`
	Bytes string `json:"bytes,omitempty"` // base64
	URI   string `json:"uri,omitempty"`   // alternative to bytes
}

FilePart carries a file attachment (inline or by reference).

type GetTaskParams

type GetTaskParams struct {
	ID            string `json:"id"`
	HistoryLength *int   `json:"historyLength,omitempty"`
}

GetTaskParams is the params for "tasks/get".

type HandlerOption

type HandlerOption func(*TaskHandler)

HandlerOption configures a TaskHandler.

func WithMaxTasks

func WithMaxTasks(n int) HandlerOption

WithMaxTasks sets the concurrent task limit.

func WithOnTaskEvent added in v1.1.46

func WithOnTaskEvent(fn func(TaskEventMessage)) HandlerOption

WithOnTaskEvent sets the callback for task lifecycle events.

func WithTimeout

func WithTimeout(d time.Duration) HandlerOption

WithTimeout sets the per-task timeout.

type InstanceInfo

type InstanceInfo struct {
	ID           string `json:"id"`
	PID          int    `json:"pid"`
	Workspace    string `json:"workspace"`
	StartedAt    string `json:"started_at"`
	Endpoint     string `json:"endpoint"`
	AgentCardURL string `json:"agent_card_url"`
	Status       string `json:"status"` // "ready", "busy", "stopping"
}

InstanceInfo describes a running ggcode instance for discovery.

func (InstanceInfo) DisplayName added in v1.1.47

func (i InstanceInfo) DisplayName() string

DisplayName returns a human-readable identifier: "workspace-name:port". Two instances in the same directory are distinguished by port.

type JSONRPCError

type JSONRPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    string `json:"data,omitempty"`
}

JSONRPCError follows the JSON-RPC 2.0 error spec.

func (*JSONRPCError) Error

func (e *JSONRPCError) Error() string

type JSONRPCRequest

type JSONRPCRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id,omitempty"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

JSONRPCRequest is a generic JSON-RPC 2.0 request.

type JSONRPCResponse

type JSONRPCResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id,omitempty"`
	Result  interface{}     `json:"result,omitempty"`
	Error   *JSONRPCError   `json:"error,omitempty"`
}

JSONRPCResponse is a generic JSON-RPC 2.0 response.

type ListTasksResult added in v1.1.46

type ListTasksResult struct {
	Tasks     []Task `json:"tasks"`
	NextToken string `json:"nextToken,omitempty"`
}

ListTasksResult holds the paginated response from tasks/list.

type Message

type Message struct {
	Role      string          `json:"role"` // "user" or "agent"
	Parts     []Part          `json:"parts"`
	MessageID string          `json:"messageId,omitempty"`
	Metadata  json.RawMessage `json:"metadata,omitempty"`
}

Message carries conversation content within a task.

type OAuthFlowAuthorizationCode added in v1.1.46

type OAuthFlowAuthorizationCode struct {
	AuthorizationURL string            `json:"authorizationUrl"`
	TokenURL         string            `json:"tokenUrl"`
	RefreshURL       string            `json:"refreshUrl,omitempty"`
	Scopes           map[string]string `json:"scopes"`
}

OAuthFlowAuthorizationCode is the Authorization Code + PKCE flow. No client_secret required for public clients.

type OAuthFlowClientCredentials added in v1.1.46

type OAuthFlowClientCredentials struct {
	TokenURL string            `json:"tokenUrl"`
	Scopes   map[string]string `json:"scopes"`
}

OAuthFlowClientCredentials is the machine-to-machine flow. Requires client_id + client_secret (user-configured, not hardcoded).

type OAuthFlowDeviceCode added in v1.1.46

type OAuthFlowDeviceCode struct {
	DeviceAuthorizationURL string            `json:"deviceAuthorizationUrl"`
	TokenURL               string            `json:"tokenUrl"`
	RefreshURL             string            `json:"refreshUrl,omitempty"`
	Scopes                 map[string]string `json:"scopes"`
}

OAuthFlowDeviceCode is the device authorization flow. No client_secret required. Ideal for headless/CLI environments.

type OAuthFlows added in v1.1.46

type OAuthFlows struct {
	AuthorizationCode *OAuthFlowAuthorizationCode `json:"authorizationCode,omitempty"`
	ClientCredentials *OAuthFlowClientCredentials `json:"clientCredentials,omitempty"`
	DeviceCode        *OAuthFlowDeviceCode        `json:"deviceCode,omitempty"`
}

OAuthFlows contains the supported OAuth2 grant types.

type Part

type Part struct {
	Kind string          `json:"kind"` // "text", "file", "data"
	Text string          `json:"text,omitempty"`
	File *FilePart       `json:"file,omitempty"`
	Data json.RawMessage `json:"data,omitempty"`
}

Part is a discriminated content block (text, file, or data).

type PushNotificationConfig added in v1.1.46

type PushNotificationConfig struct {
	TaskID         string              `json:"taskId,omitempty"`
	ID             string              `json:"id"`
	URL            string              `json:"url"`
	Token          string              `json:"token,omitempty"`
	Authentication *AuthenticationInfo `json:"authentication,omitempty"`
	Metadata       json.RawMessage     `json:"metadata,omitempty"`
}

PushNotificationConfig describes a callback endpoint for task notifications.

type Registry

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

Registry manages local A2A instance discovery via a shared JSON file.

func NewRegistry

func NewRegistry() (*Registry, error)

NewRegistry creates or opens the local instance registry.

func (*Registry) Discover

func (r *Registry) Discover() ([]InstanceInfo, error)

Discover returns all running instances (excluding self). Merges local file discovery with mDNS LAN discovery, deduplicating by ID.

func (*Registry) DiscoverByCapability

func (r *Registry) DiscoverByCapability(tag string) ([]InstanceInfo, error)

DiscoverByCapability returns instances whose metadata matches the given tag. Tag can be a language name ("go", "typescript"), framework ("npm"), or partial workspace path.

func (*Registry) EnableLANDiscovery added in v1.1.47

func (r *Registry) EnableLANDiscovery()

EnableLANDiscovery enables mDNS broadcasting for this registry. Must be called before Register.

func (*Registry) Register

func (r *Registry) Register(info InstanceInfo) error

Register adds this instance to the registry. Writes a per-PID file — no cross-process read-modify-write contention. Register adds this instance to the registry. Cleans up stale files from the same PID, writes a new file, and optionally starts mDNS broadcasting.

func (*Registry) Unregister

func (r *Registry) Unregister() error

Unregister removes this instance from the registry and stops mDNS.

func (*Registry) UpdateStatus

func (r *Registry) UpdateStatus(status string) error

UpdateStatus refreshes the status field for this instance.

type RemoteTool

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

RemoteTool lets a ggcode agent discover and call other ggcode instances via A2A protocol. This is for agent-to-agent communication within ggcode itself — NOT for external MCP clients.

The agent says "call the order-service and ask it to list orders" and this tool figures out which instance matches "order-service", connects to it, and returns the result.

func NewRemoteTool

func NewRemoteTool(reg *Registry, apiKey string) *RemoteTool

NewRemoteTool creates an A2A remote tool for agent-to-agent calls.

func (*RemoteTool) Description

func (t *RemoteTool) Description() string

func (*RemoteTool) Execute

func (t *RemoteTool) Execute(ctx context.Context, input json.RawMessage) (tool.Result, error)

func (*RemoteTool) Name

func (t *RemoteTool) Name() string

func (*RemoteTool) Parameters

func (t *RemoteTool) Parameters() json.RawMessage

func (*RemoteTool) RefreshCache

func (t *RemoteTool) RefreshCache()

RefreshCache forces a cache refresh. Called periodically by background goroutine.

type Security

type Security struct {
	Type        string `json:"type"`               // "apiKey"
	Location    string `json:"location,omitempty"` // "header"
	Name        string `json:"name,omitempty"`     // "X-API-Key"
	Description string `json:"description,omitempty"`
}

Security describes a security scheme (API Key only for now). Deprecated: Use SecurityScheme instead. Kept for backward compat.

type SecurityScheme added in v1.1.46

type SecurityScheme struct {
	// Common fields
	Type        string `json:"type"` // "apiKey", "http", "oauth2", "openIdConnect", "mutualTLS"
	Description string `json:"description,omitempty"`

	// APIKey scheme fields
	In   string `json:"in,omitempty"`   // "header" or "query"
	Name string `json:"name,omitempty"` // header/query parameter name

	// HTTP Auth scheme fields (Bearer, Basic)
	Scheme string `json:"scheme,omitempty"` // "bearer" or "basic"

	// OAuth2 scheme fields
	Flows *OAuthFlows `json:"flows,omitempty"`

	// OpenID Connect scheme fields
	OpenIDConnectURL string `json:"openIdConnectUrl,omitempty"`
}

SecurityScheme is the OneOf type for all supported authentication schemes. Exactly one of the embedded scheme fields should be set.

type SendMessageConfig added in v1.1.46

type SendMessageConfig struct {
	AcceptedOutputModes []string `json:"acceptedOutputModes,omitempty"`
	HistoryLength       *int     `json:"historyLength,omitempty"`
	PushNotification    string   `json:"pushNotification,omitempty"`
	ReturnImmediately   bool     `json:"returnImmediately,omitempty"`
}

SendMessageConfig controls how the remote agent should handle the message.

type SendMessageParams

type SendMessageParams struct {
	Message       Message            `json:"message"`
	Skill         string             `json:"skill,omitempty"`
	TaskID        string             `json:"id,omitempty"`        // for continuing an existing task
	ContextID     string             `json:"contextId,omitempty"` // for continuing an existing context
	Configuration *SendMessageConfig `json:"configuration,omitempty"`
}

SendMessageParams is the params for "message/send" and "message/stream".

type Server

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

Server is an A2A protocol server that handles JSON-RPC requests over HTTP.

func NewServer

func NewServer(cfg ServerConfig, handler *TaskHandler) *Server

NewServer creates a new A2A server.

func (*Server) AgentCard

func (s *Server) AgentCard() AgentCard

AgentCard returns a copy of the current agent card.

func (*Server) Endpoint

func (s *Server) Endpoint() string

Endpoint returns the base URL of the server.

func (*Server) Port

func (s *Server) Port() int

Port returns the actual port (only valid after Start).

func (*Server) SetAllowUnauthenticated added in v1.1.98

func (s *Server) SetAllowUnauthenticated(v bool)

SetAllowUnauthenticated allows remote unauthenticated access. By default, only localhost requests are allowed without auth.

func (*Server) SetExtendedCard added in v1.1.46

func (s *Server) SetExtendedCard(card json.RawMessage)

SetExtendedCard sets the optional extended agent card content.

func (*Server) SetHandler added in v1.1.46

func (s *Server) SetHandler(h *TaskHandler)

SetHandler connects the TaskHandler and wires push notifications.

func (*Server) SetMTLSEnabled added in v1.1.46

func (s *Server) SetMTLSEnabled(enabled bool)

SetMTLSEnabled marks the server as using mutual TLS. Use SetTLSConfig to provide the actual TLS configuration.

func (*Server) SetTLSConfig added in v1.1.46

func (s *Server) SetTLSConfig(tlsCfg *tls.Config)

SetTLSConfig configures the server to use TLS with client certificate verification. This enables mutual TLS (mTLS) authentication.

func (*Server) SetTokenValidator added in v1.1.46

func (s *Server) SetTokenValidator(v *auth.TokenValidator)

SetTokenValidator installs an OAuth2/OIDC token validator.

func (*Server) Start

func (s *Server) Start() error

Start starts the HTTP server. If port is 0, a random port is assigned.

func (*Server) Stop

func (s *Server) Stop()

Stop gracefully shuts down the server.

type ServerConfig

type ServerConfig struct {
	Host     string   // bind address (default "127.0.0.1")
	Port     int      // 0 = auto-assign
	APIKey   string   // single key (legacy, merged into APIKeys)
	APIKeys  []string // multiple keys (any match authenticates)
	Instance string   // instance identifier
}

ServerConfig holds A2A server configuration.

type Skill

type Skill struct {
	ID          string   `json:"id"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Tags        []string `json:"tags,omitempty"`
	Examples    []string `json:"examples,omitempty"`
}

Skill describes one focused capability of the agent.

func DefaultSkills

func DefaultSkills() []Skill

DefaultSkills returns the fixed set of skills every ggcode instance advertises.

type SkillPermission

type SkillPermission struct {
	AllowedTools  []string // nil = all tools allowed
	ReadOnly      bool
	MaxIterations int // 0 = unlimited
}

SkillPermission defines what a skill can do.

type StreamResponse added in v1.1.46

type StreamResponse struct {
	Task           *Task                    `json:"task,omitempty"`
	Message        *Message                 `json:"message,omitempty"`
	StatusUpdate   *TaskStatusUpdateEvent   `json:"statusUpdate,omitempty"`
	ArtifactUpdate *TaskArtifactUpdateEvent `json:"artifactUpdate,omitempty"`
}

StreamResponse is the spec OneOf wrapper for streaming and push events. Exactly one of Task, Message, StatusUpdate, ArtifactUpdate must be set.

type Task

type Task struct {
	ID        string          `json:"id"`
	ContextID string          `json:"contextId"`
	Status    TaskStatus      `json:"status"`
	Skill     string          `json:"skill,omitempty"`
	History   []Message       `json:"history,omitempty"`
	Artifacts []Artifact      `json:"artifacts,omitempty"`
	Metadata  json.RawMessage `json:"metadata,omitempty"`
	CreatedAt time.Time       `json:"createdAt"`
	UpdatedAt time.Time       `json:"updatedAt"`
	// contains filtered or unexported fields
}

Task represents an A2A task with its full lifecycle.

func (*Task) Kind

func (t *Task) Kind() string

Kind returns the A2A object type.

func (*Task) Snapshot added in v1.1.45

func (t *Task) Snapshot() Task

Snapshot returns a deep copy of the task safe for external consumption. The done channel is not copied.

type TaskArtifactUpdateEvent added in v1.1.46

type TaskArtifactUpdateEvent struct {
	TaskID    string   `json:"id"`
	Artifact  Artifact `json:"artifact"`
	Append    bool     `json:"append,omitempty"`
	LastChunk bool     `json:"lastChunk,omitempty"`
}

TaskArtifactUpdateEvent is sent via SSE when an artifact is produced.

type TaskEvent

type TaskEvent struct {
	ID    string      `json:"id"`
	Event string      `json:"event"` // "status", "artifact", "completed", "failed"
	Data  interface{} `json:"data"`
}

TaskEvent represents an SSE event for task updates (legacy, kept for compat).

type TaskEventMessage added in v1.1.46

type TaskEventMessage struct {
	Type    string // "start", "complete", "fail", "cancel"
	TaskID  string
	Skill   string
	Message string // human-readable summary
	Error   string // only for "fail"
}

TaskEventMessage describes an A2A task lifecycle event.

type TaskHandler

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

TaskHandler processes incoming A2A tasks.

func NewTaskHandler

func NewTaskHandler(workspace string, a *agent.Agent, reg *tool.Registry, opts ...HandlerOption) *TaskHandler

NewTaskHandler creates a handler bound to a specific workspace.

func (*TaskHandler) ActiveTaskCount

func (h *TaskHandler) ActiveTaskCount() int

ActiveTaskCount returns the number of non-terminal tasks.

func (*TaskHandler) ActiveTasks added in v1.1.46

func (h *TaskHandler) ActiveTasks() []Task

ActiveTasks returns snapshots of currently running A2A tasks.

func (*TaskHandler) CancelTask

func (h *TaskHandler) CancelTask(id string) error

CancelTask cancels a running task by canceling its context.

func (*TaskHandler) GetTask

func (h *TaskHandler) GetTask(id string) (*Task, bool)

GetTask returns a snapshot of the current state of a task.

func (*TaskHandler) GetTaskDone added in v1.1.45

func (h *TaskHandler) GetTaskDone(id string) <-chan struct{}

GetTaskDone returns the notification channel for a task. The channel is closed when the task reaches a terminal state. Returns nil if the task doesn't exist.

func (*TaskHandler) Handle

func (h *TaskHandler) Handle(ctx context.Context, skill string, input Message, existingTaskID string) (*Task, error)

Handle processes an incoming message as an A2A task. If params.TaskID is set, it continues an existing task (multi-turn). Otherwise it creates a new task.

func (*TaskHandler) ListTasks added in v1.1.46

func (h *TaskHandler) ListTasks(pageToken string, pageSize int) ([]Task, string)

ListTasks returns a page of tasks and a next-page token (cursor pagination).

func (*TaskHandler) RequestInput

func (h *TaskHandler) RequestInput(id string, prompt string) error

RequestInput puts a task into input-required state and returns. The caller should then wait for the client to send a follow-up message.

func (*TaskHandler) SetOnTaskEvent added in v1.1.46

func (h *TaskHandler) SetOnTaskEvent(fn func(TaskEventMessage))

SetOnTaskEvent sets the callback at runtime.

func (*TaskHandler) SetPushNotifier added in v1.1.46

func (h *TaskHandler) SetPushNotifier(fn func(taskID string, payload StreamResponse))

func (*TaskHandler) Timeout

func (h *TaskHandler) Timeout() time.Duration

Timeout returns the configured task timeout.

func (*TaskHandler) WorkspaceMetadata

func (h *TaskHandler) WorkspaceMetadata() WorkspaceMeta

WorkspaceMetadata returns the detected workspace metadata.

type TaskState

type TaskState string

TaskState represents the lifecycle state of a task.

const (
	TaskStateSubmitted     TaskState = "submitted"
	TaskStateWorking       TaskState = "working"
	TaskStateInputRequired TaskState = "input-required"
	TaskStateCompleted     TaskState = "completed"
	TaskStateCanceled      TaskState = "canceled"
	TaskStateFailed        TaskState = "failed"
	TaskStateRejected      TaskState = "rejected"
	TaskStateAuthRequired  TaskState = "auth-required"
)

func (TaskState) IsTerminal

func (s TaskState) IsTerminal() bool

IsTerminal returns true for states that cannot transition further.

type TaskStatus

type TaskStatus struct {
	State     TaskState `json:"state"`
	Timestamp time.Time `json:"timestamp"`
}

TaskStatus wraps a TaskState to satisfy the A2A spec requirement that task.status is serialized as { "state": "..." } rather than a bare string.

func (TaskStatus) IsTerminal

func (s TaskStatus) IsTerminal() bool

IsTerminal returns true for states that cannot transition further.

type TaskStatusUpdateEvent added in v1.1.46

type TaskStatusUpdateEvent struct {
	TaskID string     `json:"id"`
	Status TaskStatus `json:"status"`
	Final  bool       `json:"final"`
}

TaskStatusUpdateEvent is sent via SSE when a task's status changes.

type TaskSubscriptionParams

type TaskSubscriptionParams struct {
	ID string `json:"id"`
}

TaskSubscriptionParams is the params for "tasks/stream" (SSE subscription).

type TokenProvider added in v1.1.46

type TokenProvider interface {
	GetToken(ctx context.Context) (accessToken, refreshToken string, expiry time.Time, err error)
}

TokenProvider obtains an OAuth2/OIDC access token interactively. Implementations include PKCE flow, Device flow, or any custom mechanism.

type WorkspaceMeta

type WorkspaceMeta struct {
	Workspace  string   `json:"workspace"`
	Languages  []string `json:"languages,omitempty"`
	Frameworks []string `json:"frameworks,omitempty"`
	HasGit     bool     `json:"has_git"`
	HasTests   bool     `json:"has_tests"`
	ProjName   string   `json:"project_name"`
}

WorkspaceMeta holds dynamically detected workspace properties.

Jump to

Keyboard shortcuts

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