echo_agent 0.1.0

AI Agent framework with ReAct loop, multi-provider LLM, tool execution, and A2A HTTP server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
//! A2A 协议类型定义
//!
//! 遵循 Google A2A 协议规范定义 Agent Card、Task 等类型。

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// ── JSON-RPC / A2A 常量 ──────────────────────────────────────────────────────

/// JSON-RPC 协议版本
pub const JSONRPC_VERSION: &str = "2.0";

/// A2A 方法名
pub const METHOD_SEND: &str = "tasks/send";
/// Subscribe to task updates.
pub const METHOD_SEND_SUBSCRIBE: &str = "tasks/sendSubscribe";
/// Get task status.
pub const METHOD_GET: &str = "tasks/get";
/// Cancel a running task.
pub const METHOD_CANCEL: &str = "tasks/cancel";

/// A2A 错误码
pub const ERROR_CODE_PARSE: i64 = -32700;
/// Method not found.
pub const ERROR_CODE_METHOD_NOT_FOUND: i64 = -32601;
/// Invalid parameters.
pub const ERROR_CODE_INVALID_PARAMS: i64 = -32602;
/// Task execution failed.
pub const ERROR_CODE_TASK_FAILED: i64 = -32000;
/// Task not found.
pub const ERROR_CODE_TASK_NOT_FOUND: i64 = -32001;
/// Task is already in terminal state.
pub const ERROR_CODE_TERMINAL_STATE: i64 = -32002;
/// Invalid state transition.
pub const ERROR_CODE_INVALID_TRANSITION: i64 = -32003;

// ── Agent Card ───────────────────────────────────────────────────────────────

/// Agent Card — 描述 Agent 的能力和接口(A2A 规范核心类型)
///
/// 通过 `/.well-known/agent.json` 端点发布,供其他 Agent 发现和调用。
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentCard {
    /// Agent 名称
    pub name: String,
    /// Agent 描述
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Agent 服务的 URL 端点
    pub url: String,
    /// Agent 版本
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// Agent 提供者信息
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<AgentProvider>,
    /// Agent 技能列表
    #[serde(default)]
    pub skills: Vec<AgentSkill>,
    /// 支持的输入内容类型
    #[serde(default = "default_content_types")]
    pub default_input_modes: Vec<String>,
    /// 支持的输出内容类型
    #[serde(default = "default_content_types")]
    pub default_output_modes: Vec<String>,
    /// 认证方式
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authentication: Option<AgentAuthentication>,
    /// 额外能力标记
    #[serde(default)]
    pub capabilities: AgentCapabilities,
}

fn default_content_types() -> Vec<String> {
    vec!["text/plain".to_string()]
}

impl AgentCard {
    /// 创建 AgentCard 构建器
    pub fn builder(name: impl Into<String>, url: impl Into<String>) -> AgentCardBuilder {
        AgentCardBuilder {
            name: name.into(),
            url: url.into(),
            description: None,
            version: None,
            provider: None,
            skills: Vec::new(),
            default_input_modes: default_content_types(),
            default_output_modes: default_content_types(),
            authentication: None,
            capabilities: AgentCapabilities::default(),
        }
    }

    /// 从已有的 Agent trait 对象自动生成 Agent Card
    pub fn from_agent(agent: &dyn crate::agent::Agent, url: impl Into<String>) -> Self {
        let skills: Vec<AgentSkill> = agent
            .tool_definitions()
            .into_iter()
            .map(|td| AgentSkill::new(&td.function.name, &td.function.description))
            .collect();

        AgentCard {
            name: agent.name().to_string(),
            description: Some(agent.system_prompt().to_string()),
            url: url.into(),
            version: Some("1.0.0".to_string()),
            provider: None,
            skills,
            default_input_modes: default_content_types(),
            default_output_modes: default_content_types(),
            authentication: None,
            capabilities: AgentCapabilities::default(),
        }
    }
}

/// Agent Card 构建器
pub struct AgentCardBuilder {
    name: String,
    url: String,
    description: Option<String>,
    version: Option<String>,
    provider: Option<AgentProvider>,
    skills: Vec<AgentSkill>,
    default_input_modes: Vec<String>,
    default_output_modes: Vec<String>,
    authentication: Option<AgentAuthentication>,
    capabilities: AgentCapabilities,
}

impl AgentCardBuilder {
    /// Set the description of the agent.
    pub fn description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    /// Set the version of the agent.
    pub fn version(mut self, version: impl Into<String>) -> Self {
        self.version = Some(version.into());
        self
    }

    /// Set the provider information of the agent.
    pub fn provider(mut self, provider: AgentProvider) -> Self {
        self.provider = Some(provider);
        self
    }

    /// Add a single skill to the agent.
    pub fn skill(mut self, skill: AgentSkill) -> Self {
        self.skills.push(skill);
        self
    }

    /// Add multiple skills to the agent.
    pub fn skills(mut self, skills: Vec<AgentSkill>) -> Self {
        self.skills.extend(skills);
        self
    }

    /// Set the default input modes (content types) supported by the agent.
    pub fn input_modes(mut self, modes: Vec<impl Into<String>>) -> Self {
        self.default_input_modes = modes.into_iter().map(|m| m.into()).collect();
        self
    }

    /// Set the default output modes (content types) supported by the agent.
    pub fn output_modes(mut self, modes: Vec<impl Into<String>>) -> Self {
        self.default_output_modes = modes.into_iter().map(|m| m.into()).collect();
        self
    }

    /// Set authentication configuration for the agent.
    pub fn authentication(mut self, auth: AgentAuthentication) -> Self {
        self.authentication = Some(auth);
        self
    }

    /// Enable streaming capability for the agent.
    pub fn streaming(mut self) -> Self {
        self.capabilities.streaming = true;
        self
    }

    /// Enable push notifications capability for the agent.
    pub fn push_notifications(mut self) -> Self {
        self.capabilities.push_notifications = true;
        self
    }

    /// Build the AgentCard with the configured fields.
    pub fn build(self) -> AgentCard {
        AgentCard {
            name: self.name,
            description: self.description,
            url: self.url,
            version: self.version,
            provider: self.provider,
            skills: self.skills,
            default_input_modes: self.default_input_modes,
            default_output_modes: self.default_output_modes,
            authentication: self.authentication,
            capabilities: self.capabilities,
        }
    }
}

/// Agent 提供者信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentProvider {
    /// 组织/公司名称
    pub organization: String,
    /// 联系方式 URL
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

impl AgentProvider {
    /// Create a new AgentProvider with the given organization name.
    pub fn new(organization: impl Into<String>) -> Self {
        Self {
            organization: organization.into(),
            url: None,
        }
    }

    /// Set the URL for the agent provider.
    pub fn with_url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }
}

/// Agent 技能描述
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentSkill {
    /// 技能 ID
    pub id: String,
    /// 技能名称
    pub name: String,
    /// 技能描述
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// 示例输入
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub examples: Vec<String>,
    /// 支持的输入类型
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub input_modes: Vec<String>,
    /// 支持的输出类型
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub output_modes: Vec<String>,
    /// 自定义标签
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
}

impl AgentSkill {
    /// Create a new AgentSkill with the given name and description.
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        let name_str: String = name.into();
        Self {
            id: name_str.clone(),
            name: name_str,
            description: Some(description.into()),
            examples: Vec::new(),
            input_modes: Vec::new(),
            output_modes: Vec::new(),
            tags: Vec::new(),
        }
    }

    /// Add examples to the skill.
    pub fn with_examples(mut self, examples: Vec<impl Into<String>>) -> Self {
        self.examples = examples.into_iter().map(|e| e.into()).collect();
        self
    }

    /// Add tags to the skill.
    pub fn with_tags(mut self, tags: Vec<impl Into<String>>) -> Self {
        self.tags = tags.into_iter().map(|t| t.into()).collect();
        self
    }
}

/// Agent 认证配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentAuthentication {
    /// 认证方案列表
    pub schemes: Vec<AuthenticationScheme>,
}

/// 认证方案
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticationScheme {
    /// 方案类型: "apiKey", "bearer", "oauth2" 等
    pub scheme: String,
    /// 附加配置
    #[serde(flatten)]
    pub config: HashMap<String, serde_json::Value>,
}

/// Agent 能力标记
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentCapabilities {
    /// 是否支持流式输出
    #[serde(default)]
    pub streaming: bool,
    /// 是否支持推送通知
    #[serde(default)]
    pub push_notifications: bool,
    /// 是否支持会话状态
    #[serde(default)]
    pub state_transition_history: bool,
}

// ── A2A Task 状态机 ──────────────────────────────────────────────────────────
//
//  submitted → working → [input-required] → completed / failed
//                       ↑___________________↓
//
//  终态: completed, failed, canceled

/// 任务生命周期状态(A2A 规范状态机)
///
/// ```text
/// submitted → working → completed
///                     → failed
///                     → input-required ⇄ working
///
/// 任何非终态 → canceled
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum TaskState {
    /// 任务已提交,等待处理
    Submitted,
    /// Agent 正在执行
    Working,
    /// Agent 需要更多输入才能继续
    InputRequired,
    /// 任务成功完成
    Completed,
    /// 任务执行失败
    Failed,
    /// 任务已被取消
    Canceled,
}

impl TaskState {
    /// 是否为终态(completed / failed / canceled)
    pub fn is_terminal(self) -> bool {
        matches!(self, Self::Completed | Self::Failed | Self::Canceled)
    }

    /// 校验状态转换是否合法
    pub fn can_transition_to(self, next: Self) -> bool {
        if self.is_terminal() {
            return false;
        }
        matches!(
            (self, next),
            (Self::Submitted, Self::Working)
                | (Self::Submitted, Self::Canceled)
                | (Self::Working, Self::Completed)
                | (Self::Working, Self::Failed)
                | (Self::Working, Self::InputRequired)
                | (Self::Working, Self::Canceled)
                | (Self::InputRequired, Self::Working)
                | (Self::InputRequired, Self::Canceled)
        )
    }
}

impl std::fmt::Display for TaskState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Submitted => write!(f, "submitted"),
            Self::Working => write!(f, "working"),
            Self::InputRequired => write!(f, "input-required"),
            Self::Completed => write!(f, "completed"),
            Self::Failed => write!(f, "failed"),
            Self::Canceled => write!(f, "canceled"),
        }
    }
}

// ── A2A Task 类型 ────────────────────────────────────────────────────────────

/// A2A 任务请求
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct A2ATaskRequest {
    /// JSON-RPC 版本
    pub jsonrpc: String,
    /// 请求 ID
    pub id: String,
    /// 方法名
    pub method: String,
    /// 参数
    pub params: A2ATaskParams,
}

/// A2A 任务参数
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct A2ATaskParams {
    /// 任务 ID(可选,新任务可省略)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// 会话 ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    /// 消息内容
    pub message: A2AMessage,
}

/// A2A 消息
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct A2AMessage {
    /// 角色: "user" 或 "agent"
    pub role: String,
    /// 消息部分列表
    pub parts: Vec<A2APart>,
}

/// 消息内容部分
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum A2APart {
    /// 文本内容
    #[serde(rename = "text")]
    Text {
        /// 文本内容
        text: String,
    },
    /// 文件内容
    #[serde(rename = "file")]
    File {
        /// MIME type of the file.
        #[serde(rename = "mimeType")]
        mime_type: String,
        /// Base64-encoded file data.
        data: String,
    },
}

impl A2AMessage {
    /// 创建用户文本消息
    pub fn user_text(text: impl Into<String>) -> Self {
        Self {
            role: "user".to_string(),
            parts: vec![A2APart::Text { text: text.into() }],
        }
    }

    /// 创建 Agent 文本消息
    pub fn agent_text(text: impl Into<String>) -> Self {
        Self {
            role: "agent".to_string(),
            parts: vec![A2APart::Text { text: text.into() }],
        }
    }

    /// 获取所有文本内容
    pub fn text_content(&self) -> String {
        self.parts
            .iter()
            .filter_map(|p| match p {
                A2APart::Text { text } => Some(text.as_str()),
                _ => None,
            })
            .collect::<Vec<_>>()
            .join("\n")
    }
}

/// A2A 任务响应
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct A2ATaskResponse {
    /// JSON-RPC 版本
    pub jsonrpc: String,
    /// 请求 ID(解析失败时为 None)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// 任务结果
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<A2ATask>,
    /// 错误信息
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<A2AError>,
}

/// A2A 任务
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct A2ATask {
    /// 任务 ID
    pub id: String,
    /// 会话 ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    /// 任务状态
    pub status: A2ATaskStatus,
    /// 消息历史
    #[serde(default)]
    pub history: Vec<A2AMessage>,
    /// Agent 产出的成果
    #[serde(default)]
    pub artifacts: Vec<A2AArtifact>,
}

/// 任务状态
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct A2ATaskStatus {
    /// 状态枚举
    pub state: TaskState,
    /// 状态消息(可含 Agent 回复或错误说明)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<A2AMessage>,
    /// 状态变更时间戳(ISO 8601)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,
}

impl A2ATaskStatus {
    /// Create a new task status with the given state and current timestamp.
    pub fn new(state: TaskState) -> Self {
        Self {
            state,
            message: None,
            timestamp: Some(chrono::Utc::now().to_rfc3339()),
        }
    }

    /// Create a new task status with the given state and message.
    pub fn with_message(state: TaskState, message: A2AMessage) -> Self {
        Self {
            state,
            message: Some(message),
            timestamp: Some(chrono::Utc::now().to_rfc3339()),
        }
    }
}

/// Agent 产出
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct A2AArtifact {
    /// 产出名称
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Artifact 在列表中的索引(流式追加时标识同一 artifact)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub index: Option<usize>,
    /// 产出内容部分
    pub parts: Vec<A2APart>,
    /// 是否追加到已有同 index 的 artifact(流式场景)
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub append: bool,
}

/// A2A 错误
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct A2AError {
    /// 错误码
    pub code: i32,
    /// 错误消息
    pub message: String,
}

// ── A2A 流式事件类型 ─────────────────────────────────────────────────────────
//
// 用于 tasks/sendSubscribe 的 SSE 流式响应。
// 每个事件是一行 JSON,格式:`data: <json>\n\n`

/// 流式响应中的事件类型
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum A2AStreamEvent {
    /// 任务状态变更事件
    #[serde(rename = "status")]
    StatusUpdate(TaskStatusUpdateEvent),
    /// Artifact 更新事件(流式产出)
    #[serde(rename = "artifact")]
    ArtifactUpdate(TaskArtifactUpdateEvent),
}

/// 任务状态变更事件
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TaskStatusUpdateEvent {
    /// 任务 ID
    pub task_id: String,
    /// 新状态
    pub status: A2ATaskStatus,
    /// 是否为该任务的最终事件
    #[serde(rename = "final", default)]
    pub is_final: bool,
}

/// Artifact 更新事件(增量产出)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TaskArtifactUpdateEvent {
    /// 任务 ID
    pub task_id: String,
    /// 更新的 Artifact
    pub artifact: A2AArtifact,
    /// 是否为该任务的最终事件
    #[serde(rename = "final", default)]
    pub is_final: bool,
}

/// 流式 JSON-RPC 响应包装(SSE `data:` 行的载体)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct A2AStreamResponse {
    /// JSON-RPC 版本
    pub jsonrpc: String,
    /// 请求 ID
    pub id: String,
    /// 事件结果
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<A2AStreamEvent>,
    /// 错误信息
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<A2AError>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_agent_card_builder() {
        let card = AgentCard::builder("test-agent", "http://localhost:8080")
            .description("测试 Agent")
            .version("1.0.0")
            .skill(AgentSkill::new("calc", "数学计算"))
            .streaming()
            .build();

        assert_eq!(card.name, "test-agent");
        assert_eq!(card.description.as_deref(), Some("测试 Agent"));
        assert_eq!(card.skills.len(), 1);
        assert!(card.capabilities.streaming);
    }

    #[test]
    fn test_agent_card_serialization() {
        let card = AgentCard::builder("test", "http://localhost")
            .skill(AgentSkill::new("echo", "回声"))
            .build();

        let json = serde_json::to_string_pretty(&card).unwrap();
        assert!(json.contains("\"name\":"));
        assert!(json.contains("\"skills\":"));

        let parsed: AgentCard = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.name, "test");
    }

    #[test]
    fn test_a2a_message() {
        let msg = A2AMessage::user_text("你好");
        assert_eq!(msg.role, "user");
        assert_eq!(msg.text_content(), "你好");
    }

    #[test]
    fn test_agent_skill() {
        let skill = AgentSkill::new("translate", "翻译")
            .with_tags(vec!["nlp", "translation"])
            .with_examples(vec!["翻译'你好'为英文"]);

        assert_eq!(skill.id, "translate");
        assert_eq!(skill.tags.len(), 2);
        assert_eq!(skill.examples.len(), 1);
    }

    // ── TaskState 状态机测试 ──────────────────────────────────

    #[test]
    fn test_task_state_terminal() {
        assert!(!TaskState::Submitted.is_terminal());
        assert!(!TaskState::Working.is_terminal());
        assert!(!TaskState::InputRequired.is_terminal());
        assert!(TaskState::Completed.is_terminal());
        assert!(TaskState::Failed.is_terminal());
        assert!(TaskState::Canceled.is_terminal());
    }

    #[test]
    fn test_task_state_transitions() {
        assert!(TaskState::Submitted.can_transition_to(TaskState::Working));
        assert!(TaskState::Submitted.can_transition_to(TaskState::Canceled));
        assert!(!TaskState::Submitted.can_transition_to(TaskState::Completed));

        assert!(TaskState::Working.can_transition_to(TaskState::Completed));
        assert!(TaskState::Working.can_transition_to(TaskState::Failed));
        assert!(TaskState::Working.can_transition_to(TaskState::InputRequired));
        assert!(TaskState::Working.can_transition_to(TaskState::Canceled));
        assert!(!TaskState::Working.can_transition_to(TaskState::Submitted));

        // input-required ⇄ working cycle
        assert!(TaskState::InputRequired.can_transition_to(TaskState::Working));
        assert!(TaskState::InputRequired.can_transition_to(TaskState::Canceled));
        assert!(!TaskState::InputRequired.can_transition_to(TaskState::Completed));

        // terminal states cannot transition
        assert!(!TaskState::Completed.can_transition_to(TaskState::Working));
        assert!(!TaskState::Failed.can_transition_to(TaskState::Working));
        assert!(!TaskState::Canceled.can_transition_to(TaskState::Working));
    }

    #[test]
    fn test_task_state_serde_kebab_case() {
        let json = serde_json::to_string(&TaskState::InputRequired).unwrap();
        assert_eq!(json, "\"input-required\"");

        let parsed: TaskState = serde_json::from_str("\"input-required\"").unwrap();
        assert_eq!(parsed, TaskState::InputRequired);

        let parsed: TaskState = serde_json::from_str("\"working\"").unwrap();
        assert_eq!(parsed, TaskState::Working);
    }

    #[test]
    fn test_task_status_with_timestamp() {
        let status = A2ATaskStatus::new(TaskState::Working);
        assert_eq!(status.state, TaskState::Working);
        assert!(status.timestamp.is_some());
        assert!(status.message.is_none());

        let status =
            A2ATaskStatus::with_message(TaskState::Completed, A2AMessage::agent_text("done"));
        assert_eq!(status.state, TaskState::Completed);
        assert!(status.message.is_some());
    }

    #[test]
    fn test_artifact_with_streaming_fields() {
        let artifact = A2AArtifact {
            name: Some("output".to_string()),
            index: Some(0),
            parts: vec![A2APart::Text {
                text: "chunk".into(),
            }],
            append: true,
        };
        let json = serde_json::to_string(&artifact).unwrap();
        assert!(json.contains("\"index\":0"));
        assert!(json.contains("\"append\":true"));

        let non_append = A2AArtifact {
            name: None,
            index: None,
            parts: vec![A2APart::Text {
                text: "full".into(),
            }],
            append: false,
        };
        let json = serde_json::to_string(&non_append).unwrap();
        assert!(!json.contains("index"));
        assert!(!json.contains("append"));
    }

    #[test]
    fn test_stream_event_serialization() {
        let event = A2AStreamEvent::StatusUpdate(TaskStatusUpdateEvent {
            task_id: "t1".into(),
            status: A2ATaskStatus::new(TaskState::Working),
            is_final: false,
        });
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains("\"type\":\"status\""));
        assert!(json.contains("\"working\""));

        let event = A2AStreamEvent::ArtifactUpdate(TaskArtifactUpdateEvent {
            task_id: "t1".into(),
            artifact: A2AArtifact {
                name: None,
                index: Some(0),
                parts: vec![A2APart::Text { text: "hi".into() }],
                append: true,
            },
            is_final: false,
        });
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains("\"type\":\"artifact\""));
    }
}