灵隙(synapse) v1.0.0 版本
This commit is contained in:
389
pkg/types/content.go
Normal file
389
pkg/types/content.go
Normal file
@@ -0,0 +1,389 @@
|
||||
package types
|
||||
|
||||
// =============================================================================
|
||||
// Transport Mode Definitions
|
||||
// =============================================================================
|
||||
|
||||
// TransportMode defines the transport mode for task communication
|
||||
type TransportMode string
|
||||
|
||||
const (
|
||||
TransportModeCallback TransportMode = "callback" // Async callback (webhook)
|
||||
TransportModePolling TransportMode = "polling" // Async polling
|
||||
TransportModeSync TransportMode = "sync" // Synchronous
|
||||
TransportModeHybrid TransportMode = "hybrid" // Callback + Polling fallback
|
||||
)
|
||||
|
||||
// TransportPreferences defines transport preferences for a task
|
||||
type TransportPreferences struct {
|
||||
Preferred TransportMode `json:"preferred"`
|
||||
Fallback TransportMode `json:"fallback,omitempty"`
|
||||
CallbackEndpoint string `json:"callback_endpoint,omitempty"`
|
||||
PollingInterval int `json:"polling_interval,omitempty"` // seconds
|
||||
ProgressUpdates bool `json:"progress_updates"`
|
||||
ProgressInterval int `json:"progress_interval,omitempty"` // seconds
|
||||
}
|
||||
|
||||
// DefaultTransportPreferences returns default transport preferences
|
||||
func DefaultTransportPreferences() *TransportPreferences {
|
||||
return &TransportPreferences{
|
||||
Preferred: TransportModeCallback,
|
||||
Fallback: TransportModePolling,
|
||||
PollingInterval: 5,
|
||||
ProgressUpdates: true,
|
||||
ProgressInterval: 10,
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Content Type Definitions
|
||||
// =============================================================================
|
||||
|
||||
// MIME type constants
|
||||
const (
|
||||
MIMEJSON = "application/json"
|
||||
MIMETextPlain = "text/plain"
|
||||
MIMETextMarkdown = "text/markdown"
|
||||
MIMETextHTML = "text/html"
|
||||
MIMETextCSV = "text/csv"
|
||||
MIMEImageJPEG = "image/jpeg"
|
||||
MIMEImagePNG = "image/png"
|
||||
MIMEImageWebP = "image/webp"
|
||||
MIMEImageGIF = "image/gif"
|
||||
MIMEImageSVG = "image/svg+xml"
|
||||
MIMEVideoMP4 = "video/mp4"
|
||||
MIMEVideoWebM = "video/webm"
|
||||
MIMEAudioMP3 = "audio/mpeg"
|
||||
MIMEAudioWAV = "audio/wav"
|
||||
MIMEAudioAAC = "audio/aac"
|
||||
MIMEPDF = "application/pdf"
|
||||
MIMEOctetStream = "application/octet-stream"
|
||||
MIMEMultipartForm = "multipart/form-data"
|
||||
)
|
||||
|
||||
// ContentEncoding defines content encoding methods
|
||||
type ContentEncoding string
|
||||
|
||||
const (
|
||||
EncodingNone ContentEncoding = "none"
|
||||
EncodingBase64 ContentEncoding = "base64"
|
||||
EncodingGzip ContentEncoding = "gzip"
|
||||
EncodingDeflate ContentEncoding = "deflate"
|
||||
)
|
||||
|
||||
// TransferMode defines how content is transferred
|
||||
type TransferMode string
|
||||
|
||||
const (
|
||||
TransferInline TransferMode = "inline" // Embedded in message (base64)
|
||||
TransferURL TransferMode = "url" // Via URL reference
|
||||
TransferStreaming TransferMode = "streaming" // Via streaming protocol
|
||||
TransferMultipart TransferMode = "multipart" // Via multipart form
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Content Objects
|
||||
// =============================================================================
|
||||
|
||||
// ContentBase is the base struct for all content types
|
||||
type ContentBase struct {
|
||||
MIMEType string `json:"mime_type"`
|
||||
Encoding ContentEncoding `json:"encoding,omitempty"`
|
||||
Size int64 `json:"size,omitempty"`
|
||||
Checksum string `json:"checksum,omitempty"` // format: "sha256:xxx"
|
||||
TransferMode TransferMode `json:"transfer_mode"`
|
||||
}
|
||||
|
||||
// TextContent represents textual content
|
||||
type TextContent struct {
|
||||
ContentBase
|
||||
Charset string `json:"charset"`
|
||||
Language string `json:"language,omitempty"`
|
||||
Data string `json:"data"`
|
||||
}
|
||||
|
||||
// JSONContent represents JSON structured content
|
||||
type JSONContent struct {
|
||||
ContentBase
|
||||
Schema string `json:"schema,omitempty"` // Schema identifier
|
||||
SchemaURL string `json:"schema_url,omitempty"` // URL to schema definition
|
||||
Data any `json:"data"`
|
||||
}
|
||||
|
||||
// CodeContent represents source code content
|
||||
type CodeContent struct {
|
||||
ContentBase
|
||||
Language string `json:"language"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Dependencies []string `json:"dependencies,omitempty"`
|
||||
Data string `json:"data"`
|
||||
}
|
||||
|
||||
// FileContent represents a file (image, video, document, etc.)
|
||||
type FileContent struct {
|
||||
ContentBase
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role,omitempty"` // e.g., "reference", "result", "attachment"
|
||||
Description string `json:"description,omitempty"`
|
||||
|
||||
// For inline transfer
|
||||
Data string `json:"data,omitempty"` // base64 encoded if binary
|
||||
|
||||
// For URL transfer
|
||||
URL string `json:"url,omitempty"`
|
||||
URLExpiresAt *Timestamp `json:"url_expires_at,omitempty"`
|
||||
DownloadMethod string `json:"download_method,omitempty"` // GET, POST, signed_url
|
||||
RangeSupported bool `json:"range_supported,omitempty"`
|
||||
|
||||
// Metadata
|
||||
Width int `json:"width,omitempty"` // images/videos
|
||||
Height int `json:"height,omitempty"` // images/videos
|
||||
Duration float64 `json:"duration,omitempty"` // audio/video (seconds)
|
||||
Resolution string `json:"resolution,omitempty"` // videos
|
||||
ThumbnailURL string `json:"thumbnail_url,omitempty"`
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Content Bundles (multiple files)
|
||||
// =============================================================================
|
||||
|
||||
// ContentBundle represents a collection of content items
|
||||
type ContentBundle struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Items []ContentBundleItem `json:"items"`
|
||||
TotalSize int64 `json:"total_size,omitempty"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
|
||||
// ContentBundleItem is an item in a content bundle
|
||||
type ContentBundleItem struct {
|
||||
ID string `json:"id"`
|
||||
Role string `json:"role"` // main, reference, attachment, thumbnail, etc.
|
||||
Content any `json:"content"` // TextContent | FileContent | JSONContent | CodeContent
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// File Transfer Helper Functions
|
||||
// =============================================================================
|
||||
|
||||
// IsSmallFile checks if a file should be transferred inline
|
||||
func IsSmallFile(size int64, threshold int64) bool {
|
||||
if threshold <= 0 {
|
||||
threshold = 1024 * 1024 // 1MB default
|
||||
}
|
||||
return size <= threshold
|
||||
}
|
||||
|
||||
// InferMimeType infers MIME type from filename
|
||||
func InferMimeType(filename string) string {
|
||||
extMap := map[string]string{
|
||||
".json": MIMEJSON,
|
||||
".txt": MIMETextPlain,
|
||||
".md": MIMETextMarkdown,
|
||||
".html": MIMETextHTML,
|
||||
".htm": MIMETextHTML,
|
||||
".csv": MIMETextCSV,
|
||||
".jpg": MIMEImageJPEG,
|
||||
".jpeg": MIMEImageJPEG,
|
||||
".png": MIMEImagePNG,
|
||||
".webp": MIMEImageWebP,
|
||||
".gif": MIMEImageGIF,
|
||||
".svg": MIMEImageSVG,
|
||||
".mp4": MIMEVideoMP4,
|
||||
".webm": MIMEVideoWebM,
|
||||
".mp3": MIMEAudioMP3,
|
||||
".wav": MIMEAudioWAV,
|
||||
".aac": MIMEAudioAAC,
|
||||
".pdf": MIMEPDF,
|
||||
".bin": MIMEOctetStream,
|
||||
}
|
||||
|
||||
// Simple extension matching (lowercase would be better)
|
||||
for ext, mime := range extMap {
|
||||
if len(filename) > len(ext) && filename[len(filename)-len(ext):] == ext {
|
||||
return mime
|
||||
}
|
||||
// Also check uppercase
|
||||
upperExt := toUpper(ext)
|
||||
if len(filename) > len(upperExt) && filename[len(filename)-len(upperExt):] == upperExt {
|
||||
return mime
|
||||
}
|
||||
}
|
||||
|
||||
return MIMEOctetStream
|
||||
}
|
||||
|
||||
func toUpper(s string) string {
|
||||
result := make([]byte, len(s))
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 'a' && c <= 'z' {
|
||||
c = c - 'a' + 'A'
|
||||
}
|
||||
result[i] = c
|
||||
}
|
||||
return string(result)
|
||||
}
|
||||
|
||||
// NewInlineFileContent creates an inline file content (for small files)
|
||||
func NewInlineFileContent(name, mimeType string, data []byte, role string) *FileContent {
|
||||
// base64 encode would happen here in real implementation
|
||||
return &FileContent{
|
||||
ContentBase: ContentBase{
|
||||
MIMEType: mimeType,
|
||||
Encoding: EncodingBase64,
|
||||
Size: int64(len(data)),
|
||||
TransferMode: TransferInline,
|
||||
},
|
||||
Name: name,
|
||||
Role: role,
|
||||
Data: "", // base64.RawStdEncoding.EncodeToString(data)
|
||||
}
|
||||
}
|
||||
|
||||
// NewURLFileContent creates a URL-referenced file content (for large files)
|
||||
func NewURLFileContent(name, mimeType string, size int64, url string, expiresAt *Timestamp, role string) *FileContent {
|
||||
return &FileContent{
|
||||
ContentBase: ContentBase{
|
||||
MIMEType: mimeType,
|
||||
Size: size,
|
||||
TransferMode: TransferURL,
|
||||
},
|
||||
Name: name,
|
||||
Role: role,
|
||||
URL: url,
|
||||
URLExpiresAt: expiresAt,
|
||||
DownloadMethod: "GET",
|
||||
RangeSupported: true,
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Polling API Types
|
||||
// =============================================================================
|
||||
|
||||
// TaskStatusResponse is the response for task status polling
|
||||
type TaskStatusResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Task *TaskInfo `json:"task,omitempty"`
|
||||
Error *SynapseError `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// TaskInfo represents task status information
|
||||
type TaskInfo struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Status string `json:"status"`
|
||||
Progress int `json:"progress"`
|
||||
Message string `json:"message,omitempty"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
UpdatedAt Timestamp `json:"updated_at"`
|
||||
ETA *Timestamp `json:"eta,omitempty"`
|
||||
Result any `json:"result,omitempty"`
|
||||
Error *SynapseError `json:"error,omitempty"`
|
||||
ETag string `json:"etag,omitempty"`
|
||||
}
|
||||
|
||||
// TaskListResponse is the response for listing tasks
|
||||
type TaskListResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Tasks []TaskInfo `json:"tasks"`
|
||||
Total int `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
// TaskEvent represents a task event
|
||||
type TaskEvent struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"` // status_update, progress, log, error, complete
|
||||
Timestamp Timestamp `json:"timestamp"`
|
||||
Data any `json:"data"`
|
||||
}
|
||||
|
||||
// TaskEventsResponse is the response for task events
|
||||
type TaskEventsResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Since string `json:"since"`
|
||||
Events []TaskEvent `json:"events"`
|
||||
HasMore bool `json:"has_more"`
|
||||
Next string `json:"next_cursor,omitempty"`
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Streaming Types
|
||||
// =============================================================================
|
||||
|
||||
// StreamChunk represents a chunk of streaming data
|
||||
type StreamChunk struct {
|
||||
TaskID string `json:"task_id"`
|
||||
Sequence int64 `json:"sequence"`
|
||||
ChunkType string `json:"chunk_type"` // text, binary, audio, video
|
||||
Data string `json:"data"` // base64 for binary
|
||||
Final bool `json:"final"`
|
||||
Timestamp Timestamp `json:"timestamp"`
|
||||
}
|
||||
|
||||
// StreamComplete is sent when streaming is complete
|
||||
type StreamComplete struct {
|
||||
TaskID string `json:"task_id"`
|
||||
TotalChunks int64 `json:"total_chunks"`
|
||||
FullContentChecksum string `json:"full_content_checksum"`
|
||||
Result any `json:"result,omitempty"`
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Capabilities Query (Synchronous)
|
||||
// =============================================================================
|
||||
|
||||
// CapabilitiesResponse is the response for capability query
|
||||
type CapabilitiesResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data *AgentCapabilities `json:"data,omitempty"`
|
||||
Error *SynapseError `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// AgentCapabilities describes an agent's capabilities
|
||||
type AgentCapabilities struct {
|
||||
AgentID string `json:"agent_id"`
|
||||
AgentName string `json:"agent_name"`
|
||||
SystemID string `json:"system_id"`
|
||||
ProtocolVersion string `json:"protocol_version"`
|
||||
|
||||
SupportedTaskTypes []SupportedTaskType `json:"supported_task_types"`
|
||||
SupportedContentTypes []string `json:"supported_content_types"`
|
||||
SupportedTransportModes []TransportMode `json:"supported_transport_modes"`
|
||||
|
||||
// Limits
|
||||
MaxFileSize int64 `json:"max_file_size"`
|
||||
MaxConcurrentTasks int `json:"max_concurrent_tasks"`
|
||||
MaxTaskDuration int `json:"max_task_duration_seconds"`
|
||||
|
||||
// Features
|
||||
SupportProgressUpdates bool `json:"support_progress_updates"`
|
||||
SupportStreaming bool `json:"support_streaming"`
|
||||
SupportHiL bool `json:"support_hil"`
|
||||
SupportGroups bool `json:"support_groups"`
|
||||
}
|
||||
|
||||
// SupportedTaskType describes a supported task type
|
||||
type SupportedTaskType struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
EstimatedTime string `json:"estimated_time"` // e.g., "30s-2min"
|
||||
InputSchema string `json:"input_schema,omitempty"`
|
||||
OutputSchema string `json:"output_schema,omitempty"`
|
||||
Capabilities []string `json:"capabilities,omitempty"`
|
||||
}
|
||||
|
||||
// NewCapabilitiesResponse creates a capabilities response
|
||||
func NewCapabilitiesResponse(caps *AgentCapabilities) *CapabilitiesResponse {
|
||||
return &CapabilitiesResponse{
|
||||
Success: true,
|
||||
Data: caps,
|
||||
}
|
||||
}
|
||||
332
pkg/types/errors.go
Normal file
332
pkg/types/errors.go
Normal file
@@ -0,0 +1,332 @@
|
||||
package types
|
||||
|
||||
// =============================================================================
|
||||
// Synapse Error Codes
|
||||
// =============================================================================
|
||||
|
||||
// SynapseErrorCode defines error code ranges
|
||||
type SynapseErrorCode int
|
||||
|
||||
const (
|
||||
// System errors (1000-1999)
|
||||
ErrSystemError SynapseErrorCode = 1000
|
||||
ErrInternalError SynapseErrorCode = 1001
|
||||
ErrMaintenance SynapseErrorCode = 1002
|
||||
|
||||
// Task errors (2000-2999)
|
||||
ErrTaskNotFound SynapseErrorCode = 2001
|
||||
ErrTaskAlreadyCompleted SynapseErrorCode = 2002
|
||||
ErrTaskCancelled SynapseErrorCode = 2003
|
||||
ErrTaskTimeout SynapseErrorCode = 2004
|
||||
ErrTaskInvalidParams SynapseErrorCode = 2005
|
||||
|
||||
// Information errors (3000-3999)
|
||||
ErrRequiredFieldMissing SynapseErrorCode = 3001
|
||||
ErrInvalidFieldFormat SynapseErrorCode = 3002
|
||||
ErrInfoNotProvided SynapseErrorCode = 3003
|
||||
|
||||
// Capability errors (4000-4999)
|
||||
ErrUnsupportedTaskType SynapseErrorCode = 4001
|
||||
ErrCapabilityLacking SynapseErrorCode = 4002
|
||||
ErrResourceBusy SynapseErrorCode = 4003
|
||||
ErrQuotaExceeded SynapseErrorCode = 4004
|
||||
|
||||
// Security errors (5000-5999)
|
||||
ErrAuthFailed SynapseErrorCode = 5001
|
||||
ErrSignatureInvalid SynapseErrorCode = 5002
|
||||
ErrPermissionDenied SynapseErrorCode = 5003
|
||||
ErrPolicyViolation SynapseErrorCode = 5004
|
||||
|
||||
// Communication errors (6000-6999)
|
||||
ErrEndpointUnreachable SynapseErrorCode = 6001
|
||||
ErrCallbackFailed SynapseErrorCode = 6002
|
||||
ErrMessageFormatInvalid SynapseErrorCode = 6003
|
||||
ErrTTLExpired SynapseErrorCode = 6004
|
||||
|
||||
// Group errors (7000-7999)
|
||||
ErrGroupNotFound SynapseErrorCode = 7001
|
||||
ErrGroupNotActive SynapseErrorCode = 7002
|
||||
ErrMemberNotFound SynapseErrorCode = 7003
|
||||
ErrNotGroupMember SynapseErrorCode = 7004
|
||||
ErrConsensusNotReached SynapseErrorCode = 7005
|
||||
ErrRoleNotFound SynapseErrorCode = 7006
|
||||
ErrAlreadyMember SynapseErrorCode = 7007
|
||||
ErrGroupFull SynapseErrorCode = 7008
|
||||
|
||||
// HiL errors (8000-8999)
|
||||
ErrHumanTimeout SynapseErrorCode = 8001
|
||||
ErrHumanDeclined SynapseErrorCode = 8002
|
||||
ErrEscalationLevel SynapseErrorCode = 8003
|
||||
|
||||
// Validation errors (9000-9999)
|
||||
ErrInvalidParams SynapseErrorCode = 9001
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Error Categories
|
||||
// =============================================================================
|
||||
|
||||
// ErrorCategory maps error codes to categories
|
||||
func (c SynapseErrorCode) Category() string {
|
||||
switch {
|
||||
case c >= 1000 && c < 2000:
|
||||
return "SYSTEM_ERROR"
|
||||
case c >= 2000 && c < 3000:
|
||||
return "TASK_ERROR"
|
||||
case c >= 3000 && c < 4000:
|
||||
return "INFO_ERROR"
|
||||
case c >= 4000 && c < 5000:
|
||||
return "CAPABILITY_ERROR"
|
||||
case c >= 5000 && c < 6000:
|
||||
return "SECURITY_ERROR"
|
||||
case c >= 6000 && c < 7000:
|
||||
return "COMMUNICATION_ERROR"
|
||||
case c >= 7000 && c < 8000:
|
||||
return "GROUP_ERROR"
|
||||
case c >= 8000 && c < 9000:
|
||||
return "HIL_ERROR"
|
||||
case c >= 9000 && c < 10000:
|
||||
return "VALIDATION_ERROR"
|
||||
default:
|
||||
return "UNKNOWN_ERROR"
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Synapse Error
|
||||
// =============================================================================
|
||||
|
||||
// SynapseError represents a structured error response
|
||||
type SynapseError struct {
|
||||
Code SynapseErrorCode `json:"code"`
|
||||
Category string `json:"category"`
|
||||
Message string `json:"message"`
|
||||
Details any `json:"details,omitempty"`
|
||||
RetryAfter *int `json:"retry_after,omitempty"` // seconds
|
||||
Timestamp Timestamp `json:"timestamp"`
|
||||
}
|
||||
|
||||
// NewSynapseError creates a new Synapse error
|
||||
func NewSynapseError(code SynapseErrorCode, message string, details any) *SynapseError {
|
||||
return &SynapseError{
|
||||
Code: code,
|
||||
Category: code.Category(),
|
||||
Message: message,
|
||||
Details: details,
|
||||
Timestamp: NowTimestamp(),
|
||||
}
|
||||
}
|
||||
|
||||
// NewSynapseErrorWithRetry creates a new Synapse error with retry hint
|
||||
func NewSynapseErrorWithRetry(code SynapseErrorCode, message string, details any, retryAfter int) *SynapseError {
|
||||
return &SynapseError{
|
||||
Code: code,
|
||||
Category: code.Category(),
|
||||
Message: message,
|
||||
Details: details,
|
||||
RetryAfter: &retryAfter,
|
||||
Timestamp: NowTimestamp(),
|
||||
}
|
||||
}
|
||||
|
||||
// Error implements the error interface
|
||||
func (e *SynapseError) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
// ToMap converts error to map for JSON serialization
|
||||
func (e *SynapseError) ToMap() map[string]any {
|
||||
m := map[string]any{
|
||||
"code": e.Code,
|
||||
"category": e.Category,
|
||||
"message": e.Message,
|
||||
"timestamp": e.Timestamp,
|
||||
}
|
||||
if e.Details != nil {
|
||||
m["details"] = e.Details
|
||||
}
|
||||
if e.RetryAfter != nil {
|
||||
m["retry_after"] = *e.RetryAfter
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Predefined Errors
|
||||
// =============================================================================
|
||||
|
||||
var (
|
||||
ErrTaskNotFoundError = NewSynapseError(
|
||||
ErrTaskNotFound,
|
||||
"Task not found",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrTaskAlreadyCompletedError = NewSynapseError(
|
||||
ErrTaskAlreadyCompleted,
|
||||
"Task has already been completed",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrTaskCancelledError = NewSynapseError(
|
||||
ErrTaskCancelled,
|
||||
"Task has been cancelled",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrTaskTimeoutError = NewSynapseError(
|
||||
ErrTaskTimeout,
|
||||
"Task execution timed out",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrRequiredFieldMissingError = NewSynapseError(
|
||||
ErrRequiredFieldMissing,
|
||||
"Required field is missing",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrUnsupportedTaskTypeError = NewSynapseError(
|
||||
ErrUnsupportedTaskType,
|
||||
"Task type is not supported by this agent",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrCapabilityLackingError = NewSynapseError(
|
||||
ErrCapabilityLacking,
|
||||
"Agent lacks the required capability",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrResourceBusyError = NewSynapseError(
|
||||
ErrResourceBusy,
|
||||
"Agent is currently busy processing other tasks",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrAuthFailedError = NewSynapseError(
|
||||
ErrAuthFailed,
|
||||
"Authentication failed",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrSignatureInvalidError = NewSynapseError(
|
||||
ErrSignatureInvalid,
|
||||
"Message signature verification failed",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrPermissionDeniedError = NewSynapseError(
|
||||
ErrPermissionDenied,
|
||||
"Permission denied",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrEndpointUnreachableError = NewSynapseError(
|
||||
ErrEndpointUnreachable,
|
||||
"Callback endpoint is unreachable",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrMessageFormatInvalidError = NewSynapseError(
|
||||
ErrMessageFormatInvalid,
|
||||
"Message format is invalid",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrGroupNotFoundError = NewSynapseError(
|
||||
ErrGroupNotFound,
|
||||
"Group not found",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrNotGroupMemberError = NewSynapseError(
|
||||
ErrNotGroupMember,
|
||||
"Agent is not a member of this group",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrGroupNotActiveError = NewSynapseError(
|
||||
ErrGroupNotActive,
|
||||
"Group is not active",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrAlreadyMemberError = NewSynapseError(
|
||||
ErrAlreadyMember,
|
||||
"Agent is already a member of this group",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrGroupFullError = NewSynapseError(
|
||||
ErrGroupFull,
|
||||
"Group has reached maximum capacity",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrMemberNotFoundError = NewSynapseError(
|
||||
ErrMemberNotFound,
|
||||
"Member not found in group",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrInvalidParamsError = NewSynapseError(
|
||||
ErrInvalidParams,
|
||||
"Invalid parameters",
|
||||
nil,
|
||||
)
|
||||
|
||||
ErrHumanTimeoutError = NewSynapseError(
|
||||
ErrHumanTimeout,
|
||||
"Human decision timed out",
|
||||
nil,
|
||||
)
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Error Response Builder
|
||||
// =============================================================================
|
||||
|
||||
// ErrorResponse represents a standard error response
|
||||
type ErrorResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Error *SynapseError `json:"error"`
|
||||
}
|
||||
|
||||
// NewErrorResponse creates an error response
|
||||
func NewErrorResponse(err *SynapseError) *ErrorResponse {
|
||||
return &ErrorResponse{
|
||||
Success: false,
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
|
||||
// SuccessResponse represents a standard success response
|
||||
type SuccessResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Data any `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// NewSuccessResponse creates a success response
|
||||
func NewSuccessResponse() *SuccessResponse {
|
||||
return &SuccessResponse{
|
||||
Success: true,
|
||||
}
|
||||
}
|
||||
|
||||
// NewSuccessResponseWithData creates a success response with data
|
||||
func NewSuccessResponseWithData(data any) *SuccessResponse {
|
||||
return &SuccessResponse{
|
||||
Success: true,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// NewSuccessResponseWithMessage creates a success response with message
|
||||
func NewSuccessResponseWithMessage(message string) *SuccessResponse {
|
||||
return &SuccessResponse{
|
||||
Success: true,
|
||||
Message: message,
|
||||
}
|
||||
}
|
||||
624
pkg/types/types.go
Normal file
624
pkg/types/types.go
Normal file
@@ -0,0 +1,624 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Message ID and Task ID generators
|
||||
// =============================================================================
|
||||
|
||||
// GenerateMessageID generates a unique message ID
|
||||
func GenerateMessageID() string {
|
||||
return fmt.Sprintf("msg-%d-%d", time.Now().UnixNano(), time.Now().UnixMilli()%1000)
|
||||
}
|
||||
|
||||
// GenerateTaskID generates a unique task ID
|
||||
func GenerateTaskID() string {
|
||||
return fmt.Sprintf("task-%d-%d", time.Now().UnixNano(), time.Now().UnixMilli()%1000)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// P2P Message Types
|
||||
// =============================================================================
|
||||
|
||||
// P2PMessageType defines all point-to-point message types
|
||||
type P2PMessageType string
|
||||
|
||||
const (
|
||||
// Task lifecycle
|
||||
P2PTaskRequest P2PMessageType = "p2p:task_request"
|
||||
P2PTaskConfirm P2PMessageType = "p2p:task_confirm"
|
||||
P2PTaskReject P2PMessageType = "p2p:task_reject"
|
||||
P2PTaskNeedInfo P2PMessageType = "p2p:task_need_info"
|
||||
P2PTaskInfoProvided P2PMessageType = "p2p:task_info_provided"
|
||||
P2PTaskStatusUpdate P2PMessageType = "p2p:task_status_update"
|
||||
P2PTaskComplete P2PMessageType = "p2p:task_complete"
|
||||
P2PTaskFailed P2PMessageType = "p2p:task_failed"
|
||||
P2PTaskCancel P2PMessageType = "p2p:task_cancel"
|
||||
P2PTaskAck P2PMessageType = "p2p:task_ack"
|
||||
|
||||
// Communication
|
||||
P2PAck P2PMessageType = "p2p:ack"
|
||||
P2PNack P2PMessageType = "p2p:nack"
|
||||
P2PHeartbeat P2PMessageType = "p2p:heartbeat"
|
||||
P2PCapabilityQuery P2PMessageType = "p2p:capability_query"
|
||||
P2PCapabilityResponse P2PMessageType = "p2p:capability_response"
|
||||
|
||||
// Human-in-the-Loop
|
||||
P2PTaskNeedHuman P2PMessageType = "p2p:task_need_human"
|
||||
P2PHumanDecision P2PMessageType = "p2p:human_decision"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Group Message Types
|
||||
// =============================================================================
|
||||
|
||||
// GroupMessageType defines all group message types
|
||||
type GroupMessageType string
|
||||
|
||||
const (
|
||||
// Group management
|
||||
GroupCreate GroupMessageType = "group:create"
|
||||
GroupDisband GroupMessageType = "group:disband"
|
||||
GroupJoin GroupMessageType = "group:join"
|
||||
GroupLeave GroupMessageType = "group:leave"
|
||||
GroupInvite GroupMessageType = "group:invite"
|
||||
GroupAcceptInvite GroupMessageType = "group:accept_invite"
|
||||
GroupRejectInvite GroupMessageType = "group:reject_invite"
|
||||
GroupMemberUpdate GroupMessageType = "group:member_update"
|
||||
GroupRoleChange GroupMessageType = "group:role_change"
|
||||
|
||||
// Group communication
|
||||
GroupBroadcast GroupMessageType = "group:broadcast"
|
||||
GroupMulticast GroupMessageType = "group:multicast"
|
||||
GroupDirect GroupMessageType = "group:direct"
|
||||
GroupRelay GroupMessageType = "group:relay"
|
||||
|
||||
// Task collaboration
|
||||
GroupTaskSplit GroupMessageType = "group:task_split"
|
||||
GroupTaskAssign GroupMessageType = "group:task_assign"
|
||||
GroupTaskMerge GroupMessageType = "group:task_merge"
|
||||
GroupTaskProgress GroupMessageType = "group:task_progress"
|
||||
|
||||
// Consensus
|
||||
GroupVote GroupMessageType = "group:vote"
|
||||
GroupVoteSubmit GroupMessageType = "group:vote_submit"
|
||||
GroupConsensus GroupMessageType = "group:consensus"
|
||||
|
||||
// Human-in-the-Loop
|
||||
GroupConsensusEscalate GroupMessageType = "group:consensus_escalate"
|
||||
GroupSubtaskEscalate GroupMessageType = "group:subtask_escalate"
|
||||
GroupHumanDecision GroupMessageType = "group:human_decision"
|
||||
InterGroupEscalate GroupMessageType = "inter_group:escalate"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Agent Endpoint
|
||||
// =============================================================================
|
||||
|
||||
// AgentEndpoint represents an agent's network endpoint
|
||||
type AgentEndpoint struct {
|
||||
AgentID string `json:"agent_id"`
|
||||
AgentName string `json:"agent_name,omitempty"`
|
||||
SystemID string `json:"system_id"`
|
||||
SystemName string `json:"system_name,omitempty"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
Version string `json:"version,omitempty"`
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// P2P Task Status
|
||||
// =============================================================================
|
||||
|
||||
// P2PTaskStatus defines task status for P2P operations
|
||||
type P2PTaskStatus string
|
||||
|
||||
const (
|
||||
// Basic states
|
||||
P2PStatusIdle P2PTaskStatus = "idle"
|
||||
P2PStatusPending P2PTaskStatus = "pending"
|
||||
P2PStatusConfirmed P2PTaskStatus = "confirmed"
|
||||
P2PStatusExecuting P2PTaskStatus = "executing"
|
||||
|
||||
// Information exchange
|
||||
P2PStatusInfoNeeded P2PTaskStatus = "info_needed"
|
||||
P2PStatusInfoProvided P2PTaskStatus = "info_provided"
|
||||
|
||||
// Human-in-the-Loop
|
||||
P2PStatusNeedHuman P2PTaskStatus = "need_human"
|
||||
P2PStatusHumanDeciding P2PTaskStatus = "human_deciding"
|
||||
P2PStatusHumanApproved P2PTaskStatus = "human_approved"
|
||||
P2PStatusHumanRejected P2PTaskStatus = "human_rejected"
|
||||
|
||||
// Terminal states
|
||||
P2PStatusCompleted P2PTaskStatus = "completed"
|
||||
P2PStatusFailed P2PTaskStatus = "failed"
|
||||
P2PStatusCancelled P2PTaskStatus = "cancelled"
|
||||
P2PStatusRejected P2PTaskStatus = "rejected"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Group Status
|
||||
// =============================================================================
|
||||
|
||||
// GroupStatus defines group state
|
||||
type GroupStatus string
|
||||
|
||||
const (
|
||||
GroupStatusNone GroupStatus = "none"
|
||||
GroupStatusCreating GroupStatus = "creating"
|
||||
GroupStatusActive GroupStatus = "active"
|
||||
GroupStatusFrozen GroupStatus = "frozen"
|
||||
GroupStatusDisbanded GroupStatus = "disbanded"
|
||||
)
|
||||
|
||||
// GroupMemberStatus defines member state within a group
|
||||
type GroupMemberStatus string
|
||||
|
||||
const (
|
||||
GroupMemberActive GroupMemberStatus = "active"
|
||||
GroupMemberAway GroupMemberStatus = "away"
|
||||
GroupMemberBusy GroupMemberStatus = "busy"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Signature Algorithm
|
||||
// =============================================================================
|
||||
|
||||
// SignatureAlgorithm defines supported signature algorithms
|
||||
type SignatureAlgorithm string
|
||||
|
||||
const (
|
||||
AlgHMACSHA256 SignatureAlgorithm = "HMAC-SHA256" // 默认
|
||||
AlgHMACSHA512 SignatureAlgorithm = "HMAC-SHA512"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Priority
|
||||
// =============================================================================
|
||||
|
||||
// Priority defines message priority
|
||||
type Priority string
|
||||
|
||||
const (
|
||||
PriorityHigh Priority = "high"
|
||||
PriorityNormal Priority = "normal"
|
||||
PriorityLow Priority = "low"
|
||||
PriorityUrgent Priority = "urgent"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Unified Synapse Message
|
||||
// =============================================================================
|
||||
|
||||
// UnifiedSynapseMessage is the base message format for all Synapse communications
|
||||
type UnifiedSynapseMessage struct {
|
||||
// Message identification
|
||||
ID string `json:"id"`
|
||||
Version string `json:"version"`
|
||||
Type string `json:"type"`
|
||||
|
||||
// Sender
|
||||
Sender AgentEndpoint `json:"sender"`
|
||||
|
||||
// Receiver (for P2P)
|
||||
Receiver *AgentEndpoint `json:"receiver,omitempty"`
|
||||
|
||||
// Group context (for Group)
|
||||
GroupID string `json:"group_id,omitempty"`
|
||||
TargetType string `json:"target_type,omitempty"` // "all", "role", "specific"
|
||||
TargetIDs []string `json:"target_ids,omitempty"`
|
||||
|
||||
// Protocol control
|
||||
CorrelationID string `json:"correlation_id,omitempty"`
|
||||
ReplyTo string `json:"reply_to,omitempty"`
|
||||
ConversationID string `json:"conversation_id,omitempty"`
|
||||
|
||||
// Payload
|
||||
Payload json.RawMessage `json:"payload"`
|
||||
|
||||
// Transport control
|
||||
TTL int `json:"ttl,omitempty"`
|
||||
Priority Priority `json:"priority,omitempty"`
|
||||
Broadcast bool `json:"broadcast,omitempty"`
|
||||
|
||||
// Security
|
||||
Signature string `json:"signature,omitempty"`
|
||||
SignatureAlgorithm string `json:"signature_algorithm,omitempty"`
|
||||
Encrypt bool `json:"encrypt,omitempty"`
|
||||
|
||||
// Timestamps
|
||||
Timestamp Timestamp `json:"timestamp"`
|
||||
ExpiresAt Timestamp `json:"expires_at,omitempty"`
|
||||
}
|
||||
|
||||
// Timestamp is an ISO 8601 formatted timestamp
|
||||
type Timestamp string
|
||||
|
||||
func (t Timestamp) Time() (time.Time, error) {
|
||||
return time.Parse(time.RFC3339, string(t))
|
||||
}
|
||||
|
||||
func NowTimestamp() Timestamp {
|
||||
return Timestamp(time.Now().UTC().Format(time.RFC3339))
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// P2P Payloads
|
||||
// =============================================================================
|
||||
|
||||
// TaskRequestPayload is the payload for TASK_REQUEST
|
||||
type TaskRequestPayload struct {
|
||||
Task struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Priority Priority `json:"priority"`
|
||||
Deadline *Timestamp `json:"deadline,omitempty"`
|
||||
Payload map[string]interface{} `json:"payload"`
|
||||
} `json:"task"`
|
||||
Context *struct {
|
||||
SessionID string `json:"session_id,omitempty"`
|
||||
ParentTaskID string `json:"parent_task_id,omitempty"`
|
||||
CorrelationID string `json:"correlation_id,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
} `json:"context,omitempty"`
|
||||
}
|
||||
|
||||
// TaskConfirmPayload is the payload for TASK_CONFIRM
|
||||
type TaskConfirmPayload struct {
|
||||
TaskID string `json:"task_id"`
|
||||
Confirmed bool `json:"confirmed"`
|
||||
EstimatedDuration int `json:"estimated_duration"` // seconds
|
||||
ExpectedCompletion Timestamp `json:"expected_completion"`
|
||||
CapabilitiesUsed []string `json:"capabilities_used"`
|
||||
Constraints *struct {
|
||||
MaxRetries int `json:"max_retries"`
|
||||
FallbackEnabled bool `json:"fallback_enabled"`
|
||||
} `json:"constraints,omitempty"`
|
||||
}
|
||||
|
||||
// TaskRejectPayload is the payload for TASK_REJECT
|
||||
type TaskRejectPayload struct {
|
||||
TaskID string `json:"task_id"`
|
||||
Reason struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Details any `json:"details,omitempty"`
|
||||
} `json:"reason"`
|
||||
Alternatives *struct {
|
||||
SuggestedAgentID string `json:"suggested_agent_id,omitempty"`
|
||||
RetryAfter int `json:"retry_after,omitempty"`
|
||||
PartialSupport bool `json:"partial_support,omitempty"`
|
||||
} `json:"alternatives,omitempty"`
|
||||
}
|
||||
|
||||
// MissingField describes a missing information field
|
||||
type MissingField struct {
|
||||
Field string `json:"field"`
|
||||
Reason string `json:"reason"`
|
||||
SuggestedValue any `json:"suggested_value,omitempty"`
|
||||
Alternatives []any `json:"alternatives,omitempty"`
|
||||
}
|
||||
|
||||
// TaskNeedInfoPayload is the payload for TASK_NEED_INFO
|
||||
type TaskNeedInfoPayload struct {
|
||||
TaskID string `json:"task_id"`
|
||||
MissingFields []MissingField `json:"missing_fields"`
|
||||
Question string `json:"question,omitempty"`
|
||||
RequiredBy *Timestamp `json:"required_by,omitempty"`
|
||||
}
|
||||
|
||||
// TaskInfoProvidedPayload is the payload for TASK_INFO_PROVIDED
|
||||
type TaskInfoProvidedPayload struct {
|
||||
TaskID string `json:"task_id"`
|
||||
ReplyTo string `json:"reply_to"`
|
||||
ProvidedInfo map[string]interface{} `json:"provided_info"`
|
||||
AdditionalContext string `json:"additional_context,omitempty"`
|
||||
}
|
||||
|
||||
// TaskStatusUpdatePayload is the payload for TASK_STATUS_UPDATE
|
||||
type TaskStatusUpdatePayload struct {
|
||||
TaskID string `json:"task_id"`
|
||||
Status string `json:"status"`
|
||||
Progress int `json:"progress"` // 0-100
|
||||
Message string `json:"message,omitempty"`
|
||||
IntermediateResult any `json:"intermediate_result,omitempty"`
|
||||
}
|
||||
|
||||
// TaskCompletePayload is the payload for TASK_COMPLETE
|
||||
type TaskCompletePayload struct {
|
||||
TaskID string `json:"task_id"`
|
||||
Result struct {
|
||||
OutputType string `json:"output_type"`
|
||||
Output any `json:"output"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
} `json:"result"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
}
|
||||
|
||||
// TaskFailedPayload is the payload for TASK_FAILED
|
||||
type TaskFailedPayload struct {
|
||||
TaskID string `json:"task_id"`
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Recoverable bool `json:"recoverable"`
|
||||
Details any `json:"details,omitempty"`
|
||||
} `json:"error"`
|
||||
PartialResult any `json:"partial_result,omitempty"`
|
||||
}
|
||||
|
||||
// TaskCancelPayload is the payload for TASK_CANCEL
|
||||
type TaskCancelPayload struct {
|
||||
TaskID string `json:"task_id"`
|
||||
Reason string `json:"reason"`
|
||||
CancelledBy string `json:"cancelled_by,omitempty"`
|
||||
}
|
||||
|
||||
// TaskNeedHumanPayload is the payload for TASK_NEED_HUMAN
|
||||
type TaskNeedHumanPayload struct {
|
||||
TaskID string `json:"task_id"`
|
||||
Reason struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"reason"`
|
||||
Context struct {
|
||||
TaskSummary string `json:"task_summary"`
|
||||
CurrentProgress int `json:"current_progress"`
|
||||
BlockedReason string `json:"blocked_reason"`
|
||||
RelevantHistory []any `json:"relevant_history,omitempty"`
|
||||
} `json:"context"`
|
||||
Options []struct {
|
||||
Field string `json:"field"`
|
||||
Value any `json:"value"`
|
||||
ProsCons string `json:"pros_cons,omitempty"`
|
||||
Confidence int `json:"confidence,omitempty"`
|
||||
} `json:"options,omitempty"`
|
||||
SuggestedValue any `json:"suggested_value,omitempty"`
|
||||
EscalationLevel int `json:"escalation_level"`
|
||||
Deadline *Timestamp `json:"deadline,omitempty"`
|
||||
}
|
||||
|
||||
// HumanDecisionPayload is the payload for HUMAN_DECISION
|
||||
type HumanDecisionPayload struct {
|
||||
TaskID string `json:"task_id"`
|
||||
DecisionID string `json:"decision_id"`
|
||||
ReplyTo string `json:"reply_to"`
|
||||
DecidedBy struct {
|
||||
UserID string `json:"user_id"`
|
||||
UserName string `json:"user_name"`
|
||||
Role string `json:"role"`
|
||||
} `json:"decided_by"`
|
||||
Decision struct {
|
||||
Action string `json:"action"` // approve, reject, modify, select
|
||||
ApprovedFields map[string]interface{} `json:"approved_fields,omitempty"`
|
||||
ModifiedFields map[string]interface{} `json:"modified_fields,omitempty"`
|
||||
SelectedOption any `json:"selected_option,omitempty"`
|
||||
RejectionReason string `json:"rejection_reason,omitempty"`
|
||||
} `json:"decision"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
Timestamp Timestamp `json:"timestamp"`
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Group Payloads
|
||||
// =============================================================================
|
||||
|
||||
// GroupTopology defines group topology types
|
||||
type GroupTopology string
|
||||
|
||||
const (
|
||||
GroupTopologyStar GroupTopology = "star"
|
||||
GroupTopologyMesh GroupTopology = "mesh"
|
||||
GroupTopologyChain GroupTopology = "chain"
|
||||
GroupTopologyHierarchical GroupTopology = "hierarchical"
|
||||
GroupTopologyFullMesh GroupTopology = "fullmesh"
|
||||
)
|
||||
|
||||
// GroupRole defines a group role
|
||||
type GroupRole struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Permissions []string `json:"permissions"`
|
||||
MaxTasks int `json:"max_tasks"`
|
||||
}
|
||||
|
||||
// GroupMember represents a member in a group
|
||||
type GroupMember struct {
|
||||
AgentID string `json:"agent_id"`
|
||||
AgentName string `json:"agent_name"`
|
||||
Role string `json:"role"`
|
||||
JoinedAt Timestamp `json:"joined_at"`
|
||||
Status GroupMemberStatus `json:"status"`
|
||||
Capabilities []string `json:"capabilities"`
|
||||
LoadFactor float64 `json:"load_factor"` // 0-1, for task assignment
|
||||
}
|
||||
|
||||
// AgentGroup represents a group of agents
|
||||
type AgentGroup struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Topology GroupTopology `json:"topology"`
|
||||
CreatedBy string `json:"created_by"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
Config GroupConfig `json:"config"`
|
||||
Members []GroupMember `json:"members"`
|
||||
Roles []GroupRole `json:"roles"`
|
||||
Status GroupStatus `json:"status"`
|
||||
}
|
||||
|
||||
// GroupConfig defines group configuration
|
||||
type GroupConfig struct {
|
||||
AllowSelfLeave bool `json:"allow_self_leave"`
|
||||
RequiresApproval bool `json:"requires_approval"`
|
||||
ConsensusRequired bool `json:"consensus_required"`
|
||||
ConsensusThreshold float64 `json:"consensus_threshold"` // 0-1
|
||||
BroadcastMode string `json:"broadcast_mode"` // "all" or "smart"
|
||||
}
|
||||
|
||||
// GroupCreatePayload is the payload for GROUP_CREATE
|
||||
type GroupCreatePayload struct {
|
||||
Group struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Topology GroupTopology `json:"topology"`
|
||||
Config GroupConfig `json:"config"`
|
||||
InitialMembers []AgentEndpoint `json:"initial_members,omitempty"`
|
||||
Roles []GroupRole `json:"roles,omitempty"`
|
||||
} `json:"group"`
|
||||
}
|
||||
|
||||
// GroupInvitePayload is the payload for GROUP_INVITE
|
||||
type GroupInvitePayload struct {
|
||||
GroupID string `json:"group_id"`
|
||||
Invitee AgentEndpoint `json:"invitee"`
|
||||
Inviter AgentEndpoint `json:"inviter"`
|
||||
Message string `json:"message,omitempty"`
|
||||
RequiresApproval bool `json:"requires_approval"`
|
||||
}
|
||||
|
||||
// Subtask describes a subtask in task splitting
|
||||
type Subtask struct {
|
||||
ID string `json:"id"`
|
||||
Description string `json:"description"`
|
||||
AssignedTo string `json:"assigned_to"`
|
||||
Dependencies []string `json:"dependencies"`
|
||||
EstimatedDuration int `json:"estimated_duration"` // seconds
|
||||
Priority int `json:"priority"`
|
||||
}
|
||||
|
||||
// MergeStrategy defines how subtask results are merged
|
||||
type MergeStrategy string
|
||||
|
||||
const (
|
||||
MergeAllSuccess MergeStrategy = "all_success"
|
||||
MergeMajority MergeStrategy = "majority"
|
||||
MergeAnyComplete MergeStrategy = "any_complete"
|
||||
MergePriority MergeStrategy = "priority"
|
||||
)
|
||||
|
||||
// GroupTaskSplitPayload is the payload for GROUP_TASK_SPLIT
|
||||
type GroupTaskSplitPayload struct {
|
||||
OriginalTask struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Requirements map[string]interface{} `json:"requirements"`
|
||||
Deadline *Timestamp `json:"deadline,omitempty"`
|
||||
} `json:"original_task"`
|
||||
Subtasks []Subtask `json:"subtasks"`
|
||||
MergeStrategy MergeStrategy `json:"merge_strategy"`
|
||||
}
|
||||
|
||||
// SubtaskResult describes a single subtask result
|
||||
type SubtaskResult struct {
|
||||
SubtaskID string `json:"subtask_id"`
|
||||
AssignedTo string `json:"assigned_to"`
|
||||
Status string `json:"status"` // success, failed, partial
|
||||
Result any `json:"result,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
CompletedAt *Timestamp `json:"completed_at,omitempty"`
|
||||
}
|
||||
|
||||
// GroupTaskMergePayload is the payload for GROUP_TASK_MERGE
|
||||
type GroupTaskMergePayload struct {
|
||||
OriginalTaskID string `json:"original_task_id"`
|
||||
SubtaskResults []SubtaskResult `json:"subtask_results"`
|
||||
MergeStrategyUsed string `json:"merge_strategy_used"`
|
||||
MergedResult any `json:"merged_result"`
|
||||
ConsensusAchieved bool `json:"consensus_achieved"`
|
||||
}
|
||||
|
||||
// GroupVoteOption describes a vote option
|
||||
type GroupVoteOption struct {
|
||||
VoterID string `json:"voter_id"`
|
||||
Option string `json:"option"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Timestamp Timestamp `json:"timestamp"`
|
||||
}
|
||||
|
||||
// GroupVotePayload is the payload for GROUP_VOTE
|
||||
type GroupVotePayload struct {
|
||||
VoteID string `json:"vote_id"`
|
||||
Question string `json:"question"`
|
||||
Options []string `json:"options"`
|
||||
Voters []string `json:"voters"`
|
||||
Deadline Timestamp `json:"deadline"`
|
||||
Threshold float64 `json:"threshold"` // 0-1
|
||||
Status string `json:"status"` // open, closed
|
||||
Votes []GroupVoteOption `json:"votes,omitempty"`
|
||||
}
|
||||
|
||||
// GroupConsensusEscalatePayload is the payload for GROUP_CONSENSUS_ESCALATE
|
||||
type GroupConsensusEscalatePayload struct {
|
||||
VoteID string `json:"vote_id"`
|
||||
EscalationID string `json:"escalation_id"`
|
||||
Question string `json:"question"`
|
||||
Votes []struct {
|
||||
VoterID string `json:"voter_id"`
|
||||
VoterRole string `json:"voter_role"`
|
||||
Option string `json:"option"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
} `json:"votes"`
|
||||
ConsensusStatus struct {
|
||||
RequiredThreshold float64 `json:"required_threshold"`
|
||||
ActualThreshold float64 `json:"actual_threshold"`
|
||||
LeadingOption string `json:"leading_option,omitempty"`
|
||||
OptionsTied bool `json:"options_tied"`
|
||||
} `json:"consensus_status"`
|
||||
EscalateReason struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"escalate_reason"`
|
||||
EscalationLevel int `json:"escalation_level"`
|
||||
DecisionOptions []struct {
|
||||
Option string `json:"option"`
|
||||
SupportCount int `json:"support_count"`
|
||||
SupportAgents []string `json:"support_agents"`
|
||||
} `json:"decision_options"`
|
||||
Deadline Timestamp `json:"deadline"`
|
||||
Context struct {
|
||||
TaskID string `json:"task_id"`
|
||||
OriginalTaskRequirements map[string]interface{} `json:"original_task_requirements"`
|
||||
AgentRecommendations []struct {
|
||||
AgentID string `json:"agent_id"`
|
||||
SuggestedOption string `json:"suggested_option"`
|
||||
} `json:"agent_recommendations"`
|
||||
} `json:"context"`
|
||||
}
|
||||
|
||||
// GroupSubtaskEscalatePayload is the payload for GROUP_SUBTASK_ESCALATE
|
||||
type GroupSubtaskEscalatePayload struct {
|
||||
OriginalTask struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Description string `json:"description"`
|
||||
} `json:"original_task"`
|
||||
Subtask struct {
|
||||
ID string `json:"id"`
|
||||
Description string `json:"description"`
|
||||
AssignedTo string `json:"assigned_to"`
|
||||
BlockedAt string `json:"blocked_at"`
|
||||
BlockedReason struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"blocked_reason"`
|
||||
AttemptedSolutions []string `json:"attempted_solutions"`
|
||||
} `json:"subtask"`
|
||||
RequiredDecision struct {
|
||||
FieldsNeeded []struct {
|
||||
Field string `json:"field"`
|
||||
CurrentValue any `json:"current_value,omitempty"`
|
||||
SuggestedValue any `json:"suggested_value,omitempty"`
|
||||
Alternatives []any `json:"alternatives,omitempty"`
|
||||
ValidationRules string `json:"validation_rules,omitempty"`
|
||||
} `json:"fields_needed"`
|
||||
DecisionType string `json:"decision_type"` // approve, select, provide_info
|
||||
AffectsOtherSubtasks bool `json:"affects_other_subtasks"`
|
||||
RollbackPossible bool `json:"rollback_possible"`
|
||||
} `json:"required_decision"`
|
||||
EscalationLevel int `json:"escalation_level"`
|
||||
Deadline *Timestamp `json:"deadline,omitempty"`
|
||||
}
|
||||
512
pkg/types/types_test.go
Normal file
512
pkg/types/types_test.go
Normal file
@@ -0,0 +1,512 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// 基础类型测试
|
||||
// =============================================================================
|
||||
|
||||
func TestGenerateMessageID(t *testing.T) {
|
||||
id := GenerateMessageID()
|
||||
|
||||
if id == "" {
|
||||
t.Error("Message ID should not be empty")
|
||||
}
|
||||
|
||||
// 验证格式(msg-前缀)
|
||||
if !startsWith(id, "msg-") {
|
||||
t.Errorf("Message ID should have msg- prefix: %s", id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateTaskID(t *testing.T) {
|
||||
id := GenerateTaskID()
|
||||
|
||||
if id == "" {
|
||||
t.Error("Task ID should not be empty")
|
||||
}
|
||||
|
||||
// 验证格式(task-前缀)
|
||||
if !startsWith(id, "task-") {
|
||||
t.Errorf("Task ID should have task- prefix: %s", id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNowTimestamp(t *testing.T) {
|
||||
ts := NowTimestamp()
|
||||
if ts == "" {
|
||||
t.Error("Timestamp should not be empty")
|
||||
}
|
||||
|
||||
// 验证可以解析为时间
|
||||
parsed, err := ts.Time()
|
||||
if err != nil {
|
||||
t.Errorf("Failed to parse timestamp: %v", err)
|
||||
}
|
||||
|
||||
// 验证时间接近当前时间
|
||||
now := time.Now().UTC()
|
||||
diff := now.Sub(parsed)
|
||||
if diff > time.Minute || diff < -time.Minute {
|
||||
t.Errorf("Timestamp difference too large: %v", diff)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimestampTime(t *testing.T) {
|
||||
ts := Timestamp("2026-06-27T10:00:00Z")
|
||||
parsed, err := ts.Time()
|
||||
if err != nil {
|
||||
t.Errorf("Failed to parse timestamp: %v", err)
|
||||
}
|
||||
|
||||
expected := time.Date(2026, 6, 27, 10, 0, 0, 0, time.UTC)
|
||||
if !parsed.Equal(expected) {
|
||||
t.Errorf("Parsed time mismatch: got %v, want %v", parsed, expected)
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// AgentEndpoint 测试
|
||||
// =============================================================================
|
||||
|
||||
func TestAgentEndpointJSON(t *testing.T) {
|
||||
ep := AgentEndpoint{
|
||||
AgentID: "agent-001",
|
||||
AgentName: "TestAgent",
|
||||
SystemID: "system-001",
|
||||
Endpoint: "http://localhost:8080",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
|
||||
// 序列化
|
||||
data, err := json.Marshal(ep)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal AgentEndpoint: %v", err)
|
||||
}
|
||||
|
||||
// 反序列化
|
||||
var parsed AgentEndpoint
|
||||
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||
t.Errorf("Failed to unmarshal AgentEndpoint: %v", err)
|
||||
}
|
||||
|
||||
if parsed.AgentID != ep.AgentID {
|
||||
t.Errorf("AgentID mismatch: got %s, want %s", parsed.AgentID, ep.AgentID)
|
||||
}
|
||||
if parsed.Endpoint != ep.Endpoint {
|
||||
t.Errorf("Endpoint mismatch: got %s, want %s", parsed.Endpoint, ep.Endpoint)
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// UnifiedSynapseMessage 测试
|
||||
// =============================================================================
|
||||
|
||||
func TestUnifiedSynapseMessageJSON(t *testing.T) {
|
||||
receiver := &AgentEndpoint{
|
||||
AgentID: "agent-002",
|
||||
Endpoint: "http://localhost:8081",
|
||||
}
|
||||
|
||||
msg := UnifiedSynapseMessage{
|
||||
ID: GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(P2PTaskRequest),
|
||||
Sender: AgentEndpoint{AgentID: "agent-001", Endpoint: "http://localhost:8080"},
|
||||
Receiver: receiver,
|
||||
Payload: json.RawMessage(`{"task": {"id": "task-001"}}`),
|
||||
Timestamp: NowTimestamp(),
|
||||
Priority: PriorityNormal,
|
||||
}
|
||||
|
||||
// 序列化
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal message: %v", err)
|
||||
}
|
||||
|
||||
// 反序列化
|
||||
var parsed UnifiedSynapseMessage
|
||||
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||
t.Errorf("Failed to unmarshal message: %v", err)
|
||||
}
|
||||
|
||||
if parsed.ID != msg.ID {
|
||||
t.Errorf("Message ID mismatch")
|
||||
}
|
||||
if parsed.Type != msg.Type {
|
||||
t.Errorf("Message type mismatch: got %s, want %s", parsed.Type, msg.Type)
|
||||
}
|
||||
if parsed.Receiver.AgentID != receiver.AgentID {
|
||||
t.Errorf("Receiver AgentID mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnifiedSynapseMessageGroupContext(t *testing.T) {
|
||||
msg := UnifiedSynapseMessage{
|
||||
ID: GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(GroupBroadcast),
|
||||
Sender: AgentEndpoint{AgentID: "agent-001"},
|
||||
GroupID: "group-001",
|
||||
TargetType: "all",
|
||||
Broadcast: true,
|
||||
Payload: json.RawMessage(`{"message": "hello"}`),
|
||||
Timestamp: NowTimestamp(),
|
||||
}
|
||||
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal group message: %v", err)
|
||||
}
|
||||
|
||||
var parsed UnifiedSynapseMessage
|
||||
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||
t.Errorf("Failed to unmarshal group message: %v", err)
|
||||
}
|
||||
|
||||
if parsed.GroupID != "group-001" {
|
||||
t.Errorf("GroupID mismatch: got %s, want group-001", parsed.GroupID)
|
||||
}
|
||||
if !parsed.Broadcast {
|
||||
t.Error("Broadcast should be true")
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// P2P Payload 测试
|
||||
// =============================================================================
|
||||
|
||||
func TestTaskRequestPayloadJSON(t *testing.T) {
|
||||
payload := TaskRequestPayload{}
|
||||
payload.Task.ID = "task-001"
|
||||
payload.Task.Type = "text_generation"
|
||||
payload.Task.Priority = PriorityNormal
|
||||
payload.Task.Payload = map[string]interface{}{
|
||||
"prompt": "写一首诗",
|
||||
}
|
||||
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal TaskRequestPayload: %v", err)
|
||||
}
|
||||
|
||||
var parsed TaskRequestPayload
|
||||
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||
t.Errorf("Failed to unmarshal TaskRequestPayload: %v", err)
|
||||
}
|
||||
|
||||
if parsed.Task.ID != "task-001" {
|
||||
t.Errorf("Task ID mismatch")
|
||||
}
|
||||
if parsed.Task.Type != "text_generation" {
|
||||
t.Errorf("Task type mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskConfirmPayloadJSON(t *testing.T) {
|
||||
payload := TaskConfirmPayload{
|
||||
TaskID: "task-001",
|
||||
Confirmed: true,
|
||||
EstimatedDuration: 60,
|
||||
ExpectedCompletion: NowTimestamp(),
|
||||
CapabilitiesUsed: []string{"text_gen"},
|
||||
}
|
||||
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal TaskConfirmPayload: %v", err)
|
||||
}
|
||||
|
||||
var parsed TaskConfirmPayload
|
||||
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||
t.Errorf("Failed to unmarshal TaskConfirmPayload: %v", err)
|
||||
}
|
||||
|
||||
if parsed.TaskID != "task-001" {
|
||||
t.Errorf("TaskID mismatch")
|
||||
}
|
||||
if !payload.Confirmed {
|
||||
t.Error("Confirmed should be true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskStatusUpdatePayloadJSON(t *testing.T) {
|
||||
payload := TaskStatusUpdatePayload{
|
||||
TaskID: "task-001",
|
||||
Status: "executing",
|
||||
Progress: 50,
|
||||
Message: "Processing...",
|
||||
}
|
||||
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal TaskStatusUpdatePayload: %v", err)
|
||||
}
|
||||
|
||||
var parsed TaskStatusUpdatePayload
|
||||
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||
t.Errorf("Failed to unmarshal TaskStatusUpdatePayload: %v", err)
|
||||
}
|
||||
|
||||
if parsed.Progress != 50 {
|
||||
t.Errorf("Progress mismatch: got %d, want 50", parsed.Progress)
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Group Payload 测试
|
||||
// =============================================================================
|
||||
|
||||
func TestGroupCreatePayloadJSON(t *testing.T) {
|
||||
payload := GroupCreatePayload{}
|
||||
payload.Group.Name = "TestGroup"
|
||||
payload.Group.Topology = GroupTopologyStar
|
||||
payload.Group.Config = GroupConfig{
|
||||
AllowSelfLeave: true,
|
||||
ConsensusRequired: false,
|
||||
ConsensusThreshold: 0.5,
|
||||
}
|
||||
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal GroupCreatePayload: %v", err)
|
||||
}
|
||||
|
||||
var parsed GroupCreatePayload
|
||||
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||
t.Errorf("Failed to unmarshal GroupCreatePayload: %v", err)
|
||||
}
|
||||
|
||||
if parsed.Group.Name != "TestGroup" {
|
||||
t.Errorf("Group name mismatch")
|
||||
}
|
||||
if parsed.Group.Topology != GroupTopologyStar {
|
||||
t.Errorf("Topology mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupTaskSplitPayloadJSON(t *testing.T) {
|
||||
payload := GroupTaskSplitPayload{}
|
||||
payload.OriginalTask.ID = "task-001"
|
||||
payload.OriginalTask.Type = "video_generation"
|
||||
payload.Subtasks = []Subtask{
|
||||
{
|
||||
ID: "sub-001",
|
||||
Description: "Generate scene 1",
|
||||
AssignedTo: "agent-002",
|
||||
Priority: 1,
|
||||
},
|
||||
{
|
||||
ID: "sub-002",
|
||||
Description: "Generate scene 2",
|
||||
AssignedTo: "agent-003",
|
||||
Priority: 2,
|
||||
},
|
||||
}
|
||||
payload.MergeStrategy = MergeMajority
|
||||
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal GroupTaskSplitPayload: %v", err)
|
||||
}
|
||||
|
||||
var parsed GroupTaskSplitPayload
|
||||
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||
t.Errorf("Failed to unmarshal GroupTaskSplitPayload: %v", err)
|
||||
}
|
||||
|
||||
if len(parsed.Subtasks) != 2 {
|
||||
t.Errorf("Subtasks count mismatch: got %d, want 2", len(parsed.Subtasks))
|
||||
}
|
||||
if parsed.MergeStrategy != MergeMajority {
|
||||
t.Errorf("MergeStrategy mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupVotePayloadJSON(t *testing.T) {
|
||||
payload := GroupVotePayload{
|
||||
VoteID: "vote-001",
|
||||
Question: "Which approach is better?",
|
||||
Options: []string{"Option A", "Option B", "Option C"},
|
||||
Voters: []string{"agent-001", "agent-002", "agent-003"},
|
||||
Threshold: 0.5,
|
||||
Status: "open",
|
||||
}
|
||||
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal GroupVotePayload: %v", err)
|
||||
}
|
||||
|
||||
var parsed GroupVotePayload
|
||||
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||
t.Errorf("Failed to unmarshal GroupVotePayload: %v", err)
|
||||
}
|
||||
|
||||
if len(parsed.Options) != 3 {
|
||||
t.Errorf("Options count mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 错误码测试
|
||||
// =============================================================================
|
||||
|
||||
func TestSynapseErrorCategory(t *testing.T) {
|
||||
tests := []struct {
|
||||
code SynapseErrorCode
|
||||
expected string
|
||||
}{
|
||||
{ErrSystemError, "SYSTEM_ERROR"},
|
||||
{ErrTaskNotFound, "TASK_ERROR"},
|
||||
{ErrRequiredFieldMissing, "INFO_ERROR"},
|
||||
{ErrUnsupportedTaskType, "CAPABILITY_ERROR"},
|
||||
{ErrAuthFailed, "SECURITY_ERROR"},
|
||||
{ErrEndpointUnreachable, "COMMUNICATION_ERROR"},
|
||||
{ErrGroupNotFound, "GROUP_ERROR"},
|
||||
{ErrHumanTimeout, "HIL_ERROR"},
|
||||
{ErrInvalidParams, "VALIDATION_ERROR"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
if got := tt.code.Category(); got != tt.expected {
|
||||
t.Errorf("Category for %d: got %s, want %s", tt.code, got, tt.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSynapseError(t *testing.T) {
|
||||
err := NewSynapseError(ErrTaskNotFound, "Task not found", map[string]string{"task_id": "task-001"})
|
||||
|
||||
if err.Code != ErrTaskNotFound {
|
||||
t.Errorf("Error code mismatch")
|
||||
}
|
||||
if err.Message != "Task not found" {
|
||||
t.Errorf("Error message mismatch")
|
||||
}
|
||||
if err.Category != "TASK_ERROR" {
|
||||
t.Errorf("Error category mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSynapseErrorToMap(t *testing.T) {
|
||||
err := NewSynapseError(ErrTaskNotFound, "Task not found", nil)
|
||||
m := err.ToMap()
|
||||
|
||||
if m["code"] != ErrTaskNotFound {
|
||||
t.Errorf("Map code mismatch")
|
||||
}
|
||||
if m["category"] != "TASK_ERROR" {
|
||||
t.Errorf("Map category mismatch")
|
||||
}
|
||||
if m["message"] != "Task not found" {
|
||||
t.Errorf("Map message mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 状态机测试
|
||||
// =============================================================================
|
||||
|
||||
func TestP2PTaskStatusValues(t *testing.T) {
|
||||
statuses := []P2PTaskStatus{
|
||||
P2PStatusIdle,
|
||||
P2PStatusPending,
|
||||
P2PStatusConfirmed,
|
||||
P2PStatusExecuting,
|
||||
P2PStatusCompleted,
|
||||
P2PStatusFailed,
|
||||
P2PStatusCancelled,
|
||||
}
|
||||
|
||||
for _, s := range statuses {
|
||||
if s == "" {
|
||||
t.Error("Status should not be empty")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupStatusValues(t *testing.T) {
|
||||
statuses := []GroupStatus{
|
||||
GroupStatusCreating,
|
||||
GroupStatusActive,
|
||||
GroupStatusFrozen,
|
||||
GroupStatusDisbanded,
|
||||
}
|
||||
|
||||
for _, s := range statuses {
|
||||
if s == "" {
|
||||
t.Error("Status should not be empty")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 消息类型测试
|
||||
// =============================================================================
|
||||
|
||||
func TestP2PMessageTypes(t *testing.T) {
|
||||
types := []P2PMessageType{
|
||||
P2PTaskRequest,
|
||||
P2PTaskConfirm,
|
||||
P2PTaskReject,
|
||||
P2PTaskNeedInfo,
|
||||
P2PTaskInfoProvided,
|
||||
P2PTaskStatusUpdate,
|
||||
P2PTaskComplete,
|
||||
P2PTaskFailed,
|
||||
P2PTaskCancel,
|
||||
P2PTaskAck,
|
||||
P2PAck,
|
||||
P2PNack,
|
||||
P2PHeartbeat,
|
||||
P2PCapabilityQuery,
|
||||
P2PCapabilityResponse,
|
||||
P2PTaskNeedHuman,
|
||||
P2PHumanDecision,
|
||||
}
|
||||
|
||||
for _, mt := range types {
|
||||
if mt == "" {
|
||||
t.Error("Message type should not be empty")
|
||||
}
|
||||
// 验证前缀
|
||||
if !startsWith(string(mt), "p2p:") {
|
||||
t.Errorf("P2P message type should have p2p: prefix: %s", mt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupMessageTypes(t *testing.T) {
|
||||
groupTypes := []GroupMessageType{
|
||||
GroupCreate,
|
||||
GroupDisband,
|
||||
GroupJoin,
|
||||
GroupLeave,
|
||||
GroupBroadcast,
|
||||
GroupTaskSplit,
|
||||
GroupTaskAssign,
|
||||
GroupTaskMerge,
|
||||
GroupVote,
|
||||
GroupVoteSubmit,
|
||||
}
|
||||
|
||||
for _, mt := range groupTypes {
|
||||
if mt == "" {
|
||||
t.Error("Message type should not be empty")
|
||||
}
|
||||
// 验证前缀
|
||||
if !startsWith(string(mt), "group:") {
|
||||
t.Errorf("Group message type should have group: prefix: %s", mt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func startsWith(s, prefix string) bool {
|
||||
return len(s) >= len(prefix) && s[:len(prefix)] == prefix
|
||||
}
|
||||
Reference in New Issue
Block a user