bzzz-core 0.1.0

Bzzz core library - Declarative orchestration engine for AI Agents
Documentation
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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
//! State Model v1
//!
//! Core state objects for Bzzz orchestration:
//! - Run: A single execution of an Agent or Swarm
//! - Step: A single step within a Run
//! - Session: A logical grouping of related Runs
//! - Artifact: Output produced by a Run or Step

use std::path::PathBuf;
use std::time::{Duration, Instant, SystemTime};

// ============================================================================
// ID Types
// ============================================================================

/// Unique identifier for a Run
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct RunId(pub String);

impl RunId {
    /// Generate a new unique RunId using UUID v4
    pub fn new() -> Self {
        RunId(uuid::Uuid::new_v4().to_string())
    }

    /// Create a RunId from a string
    pub fn from_string(s: String) -> Self {
        RunId(s)
    }

    /// Get the inner string
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Default for RunId {
    fn default() -> Self {
        Self::new()
    }
}

/// Unique identifier for a Step within a Run
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct StepId(pub String);

impl StepId {
    /// Generate a new unique StepId
    pub fn new() -> Self {
        StepId(uuid::Uuid::new_v4().to_string())
    }

    /// Get the inner string
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Default for StepId {
    fn default() -> Self {
        Self::new()
    }
}

/// Unique identifier for a Session
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct SessionId(pub String);

impl SessionId {
    /// Generate a new unique SessionId
    pub fn new() -> Self {
        SessionId(uuid::Uuid::new_v4().to_string())
    }

    /// Get the inner string
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Default for SessionId {
    fn default() -> Self {
        Self::new()
    }
}

/// Unique identifier for an Artifact
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct ArtifactId(pub String);

impl ArtifactId {
    /// Generate a new unique ArtifactId
    pub fn new() -> Self {
        ArtifactId(uuid::Uuid::new_v4().to_string())
    }

    /// Get the inner string
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Default for ArtifactId {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Run Types
// ============================================================================

/// Status of a Run
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum RunStatus {
    /// Execution has not started
    Pending,
    /// Execution is in progress
    Running,
    /// Execution completed successfully
    Completed,
    /// Execution failed with error
    Failed,
    /// Execution was cancelled by user
    Cancelled,
    /// Execution exceeded time limit
    Timeout,
}

/// Target of a Run - what is being executed
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum RunTarget {
    /// Execute a single Agent
    Agent {
        /// Path to AgentSpec file
        spec_path: PathBuf,
    },
    /// Execute a Swarm
    Swarm {
        /// Path to SwarmFile
        swarmfile_path: PathBuf,
    },
    /// Execute via A2A protocol (remote HTTP agent)
    A2AAgent {
        /// A2A agent endpoint URL
        url: String,
    },
}

/// Kind of runtime environment
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum RuntimeKind {
    /// Local subprocess execution
    Local,
    /// Docker container execution
    Docker,
    /// HTTP remote execution
    Http,
    /// Cloud managed execution
    Cloud,
}

/// Error from a Run execution
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, serde::Serialize, serde::Deserialize)]
pub enum RunError {
    /// Failed to start execution
    #[error("Startup failed: {message}")]
    StartupFailed {
        /// Error message
        message: String,
    },
    /// Execution failed with error
    #[error("Execution failed: {message}")]
    ExecutionFailed {
        /// Error message
        message: String,
    },
    /// Execution was cancelled
    #[error("Cancelled: {reason}")]
    Cancelled {
        /// Cancellation reason
        reason: String,
    },
    /// Execution exceeded time limit
    #[error("Timeout after {after:?}")]
    Timeout {
        /// Time limit that was exceeded
        after: Duration,
    },
    /// Individual worker exceeded its per-worker time limit
    #[error("Worker '{worker}' timed out after {after:?}")]
    WorkerTimeout {
        /// Worker name that timed out
        worker: String,
        /// Time limit that was exceeded
        after: Duration,
    },
    /// Invalid configuration
    #[error("Invalid config: {message}")]
    InvalidConfig {
        /// Error message
        message: String,
    },
    /// Runtime error
    #[error("Runtime error: {message}")]
    RuntimeError {
        /// Error message
        message: String,
    },
    /// Artifact error
    #[error("Artifact error: {message}")]
    ArtifactError {
        /// Error message
        message: String,
    },
    /// Resource not found (e.g., run, container, agent)
    #[error("Not found: {resource_type} '{id}'")]
    NotFound {
        /// Type of resource
        resource_type: String,
        /// Resource identifier
        id: String,
    },
    /// Pattern execution error
    #[error("Pattern '{pattern}' error in step '{step}': {message}")]
    PatternError {
        /// Pattern type
        pattern: String,
        /// Step identifier
        step: String,
        /// Error message
        message: String,
    },
    /// Agent spec validation error
    #[error("Agent spec validation failed: {message}")]
    ValidationError {
        /// Error message
        message: String,
    },
}

impl RunError {
    /// Create a StartupFailed error
    pub fn startup_failed(message: impl Into<String>) -> Self {
        RunError::StartupFailed {
            message: message.into(),
        }
    }

    /// Create an ExecutionFailed error
    pub fn execution_failed(message: impl Into<String>) -> Self {
        RunError::ExecutionFailed {
            message: message.into(),
        }
    }

    /// Create a Cancelled error
    pub fn cancelled(reason: impl Into<String>) -> Self {
        RunError::Cancelled {
            reason: reason.into(),
        }
    }

    /// Create a Timeout error
    pub fn timeout(after: Duration) -> Self {
        RunError::Timeout { after }
    }

    /// Create a WorkerTimeout error
    pub fn worker_timeout(worker: impl Into<String>, after: Duration) -> Self {
        RunError::WorkerTimeout {
            worker: worker.into(),
            after,
        }
    }

    /// Create an InvalidConfig error
    pub fn invalid_config(message: impl Into<String>) -> Self {
        RunError::InvalidConfig {
            message: message.into(),
        }
    }

    /// Create a RuntimeError
    pub fn runtime_error(message: impl Into<String>) -> Self {
        RunError::RuntimeError {
            message: message.into(),
        }
    }

    /// Create a NotFound error
    pub fn not_found(resource_type: impl Into<String>, id: impl Into<String>) -> Self {
        RunError::NotFound {
            resource_type: resource_type.into(),
            id: id.into(),
        }
    }

    /// Create a PatternError
    pub fn pattern_error(
        pattern: impl Into<String>,
        step: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        RunError::PatternError {
            pattern: pattern.into(),
            step: step.into(),
            message: message.into(),
        }
    }

    /// Create a ValidationError
    pub fn validation_error(message: impl Into<String>) -> Self {
        RunError::ValidationError {
            message: message.into(),
        }
    }

    /// Check if this error is retryable
    ///
    /// Retryable errors: Timeout, RuntimeError, PatternError
    /// Non-retryable: StartupFailed, InvalidConfig, ValidationError, NotFound, Cancelled
    pub fn is_retryable(&self) -> bool {
        matches!(
            self,
            RunError::Timeout { .. }
                | RunError::WorkerTimeout { .. }
                | RunError::RuntimeError { .. }
                | RunError::PatternError { .. }
        )
    }

    /// Check if this is a user-initiated cancellation
    pub fn is_cancellation(&self) -> bool {
        matches!(self, RunError::Cancelled { .. })
    }

    /// Check if this is a configuration/validation error
    pub fn is_config_error(&self) -> bool {
        matches!(
            self,
            RunError::InvalidConfig { .. } | RunError::ValidationError { .. }
        )
    }
}

/// A single execution of an Agent or Swarm
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Run {
    /// Unique identifier for this run
    pub id: RunId,
    /// Current status
    pub status: RunStatus,
    /// What is being executed
    pub target: RunTarget,
    /// Runtime environment
    pub runtime_kind: RuntimeKind,
    /// Optional session this run belongs to
    pub session_id: Option<SessionId>,
    /// When the run was created
    pub created_at: SystemTime,
    /// When execution started
    pub started_at: Option<SystemTime>,
    /// When execution finished
    pub finished_at: Option<SystemTime>,
    /// Optional timeout duration
    pub timeout: Option<Duration>,
    /// Error if failed
    pub error: Option<RunError>,
    /// Steps in this run
    pub steps: Vec<Step>,
    /// Output artifacts
    pub artifacts: Vec<ArtifactId>,
    /// Input data for the worker (resolved template expressions, JSON-serialized)
    #[serde(default)]
    pub input: Option<serde_json::Value>,
}

impl Run {
    /// Create a new run
    pub fn new(target: RunTarget, runtime_kind: RuntimeKind) -> Self {
        Run {
            id: RunId::new(),
            status: RunStatus::Pending,
            target,
            runtime_kind,
            session_id: None,
            created_at: SystemTime::now(),
            started_at: None,
            finished_at: None,
            timeout: None,
            error: None,
            steps: Vec::new(),
            artifacts: Vec::new(),
            input: None,
        }
    }

    /// Set input data for the worker
    pub fn with_input(mut self, input: serde_json::Value) -> Self {
        self.input = Some(input);
        self
    }

    /// Add session association
    pub fn with_session(mut self, session_id: SessionId) -> Self {
        self.session_id = Some(session_id);
        self
    }

    /// Set timeout duration
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Mark execution as started
    pub fn start(&mut self) {
        self.status = RunStatus::Running;
        self.started_at = Some(SystemTime::now());
    }

    /// Mark execution as completed
    pub fn complete(&mut self) {
        self.status = RunStatus::Completed;
        self.finished_at = Some(SystemTime::now());
    }

    /// Mark execution as failed
    pub fn fail(&mut self, error: RunError) {
        self.status = RunStatus::Failed;
        self.error = Some(error);
        self.finished_at = Some(SystemTime::now());
    }

    /// Mark execution as cancelled
    pub fn cancel(&mut self, reason: String) {
        self.status = RunStatus::Cancelled;
        self.error = Some(RunError::Cancelled { reason });
        self.finished_at = Some(SystemTime::now());
    }

    /// Mark execution as timed out
    pub fn timeout(&mut self) {
        self.status = RunStatus::Timeout;
        if let Some(timeout) = self.timeout {
            self.error = Some(RunError::Timeout { after: timeout });
        }
        self.finished_at = Some(SystemTime::now());
    }

    /// Get execution duration if completed
    pub fn duration(&self) -> Option<Duration> {
        match (self.started_at, self.finished_at) {
            (Some(start), Some(end)) => end.duration_since(start).ok(),
            _ => None,
        }
    }
}

// ============================================================================
// Step Types
// ============================================================================

/// Status of a Step
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum StepStatus {
    /// Step has not started
    Pending,
    /// Step is in progress
    Running,
    /// Step completed successfully
    Completed,
    /// Step failed with error
    Failed,
    /// Step was skipped
    Skipped,
    /// Step was cancelled
    Cancelled,
}

/// Error from a Step execution
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, serde::Serialize, serde::Deserialize)]
pub enum StepError {
    /// Agent execution failed
    #[error("Agent failed: {message}")]
    AgentFailed {
        /// Error message
        message: String,
    },
    /// Invalid input provided
    #[error("Invalid input: {message}")]
    InvalidInput {
        /// Error message
        message: String,
    },
    /// Output generation failed
    #[error("Output failed: {message}")]
    OutputFailed {
        /// Error message
        message: String,
    },
    /// Step exceeded time limit
    #[error("Timeout after {after:?}")]
    Timeout {
        /// Time limit that was exceeded
        after: Duration,
    },
    /// Step was cancelled
    #[error("Cancelled: {reason}")]
    Cancelled {
        /// Cancellation reason
        reason: String,
    },
    /// Pattern execution error
    #[error("Pattern '{pattern}' error: {message}")]
    PatternError {
        /// Pattern name
        pattern: String,
        /// Error message
        message: String,
    },
}

impl StepError {
    /// Create an AgentFailed error
    pub fn agent_failed(message: impl Into<String>) -> Self {
        StepError::AgentFailed {
            message: message.into(),
        }
    }

    /// Create an InvalidInput error
    pub fn invalid_input(message: impl Into<String>) -> Self {
        StepError::InvalidInput {
            message: message.into(),
        }
    }

    /// Create an OutputFailed error
    pub fn output_failed(message: impl Into<String>) -> Self {
        StepError::OutputFailed {
            message: message.into(),
        }
    }

    /// Create a Timeout error
    pub fn timeout(after: Duration) -> Self {
        StepError::Timeout { after }
    }

    /// Create a Cancelled error
    pub fn cancelled(reason: impl Into<String>) -> Self {
        StepError::Cancelled {
            reason: reason.into(),
        }
    }

    /// Create a PatternError
    pub fn pattern_error(pattern: impl Into<String>, message: impl Into<String>) -> Self {
        StepError::PatternError {
            pattern: pattern.into(),
            message: message.into(),
        }
    }

    /// Check if this error is retryable
    pub fn is_retryable(&self) -> bool {
        matches!(
            self,
            StepError::Timeout { .. } | StepError::PatternError { .. }
        )
    }

    /// Check if this is a cancellation
    pub fn is_cancellation(&self) -> bool {
        matches!(self, StepError::Cancelled { .. })
    }
}

/// A single step within a Run
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Step {
    /// Unique identifier for this step
    pub id: StepId,
    /// Run this step belongs to
    pub run_id: RunId,
    /// Current status
    pub status: StepStatus,
    /// Step name
    pub name: String,
    /// Path to agent spec
    pub agent_spec_path: PathBuf,
    /// When step was created
    pub created_at: SystemTime,
    /// When step started
    pub started_at: Option<SystemTime>,
    /// When step finished
    pub finished_at: Option<SystemTime>,
    /// Error if failed
    pub error: Option<StepError>,
    /// Output artifacts
    pub output_artifacts: Vec<ArtifactId>,
}

impl Step {
    /// Create a new step
    pub fn new(run_id: RunId, name: String, agent_spec_path: PathBuf) -> Self {
        Step {
            id: StepId::new(),
            run_id,
            status: StepStatus::Pending,
            name,
            agent_spec_path,
            created_at: SystemTime::now(),
            started_at: None,
            finished_at: None,
            error: None,
            output_artifacts: Vec::new(),
        }
    }

    /// Mark step as started
    pub fn start(&mut self) {
        self.status = StepStatus::Running;
        self.started_at = Some(SystemTime::now());
    }

    /// Mark step as completed with artifacts
    pub fn complete(&mut self, artifacts: Vec<ArtifactId>) {
        self.status = StepStatus::Completed;
        self.output_artifacts = artifacts;
        self.finished_at = Some(SystemTime::now());
    }

    /// Mark step as failed
    pub fn fail(&mut self, error: StepError) {
        self.status = StepStatus::Failed;
        self.error = Some(error);
        self.finished_at = Some(SystemTime::now());
    }

    /// Mark step as skipped
    pub fn skip(&mut self) {
        self.status = StepStatus::Skipped;
        self.finished_at = Some(SystemTime::now());
    }

    /// Mark step as cancelled
    pub fn cancel(&mut self, reason: String) {
        self.status = StepStatus::Cancelled;
        self.error = Some(StepError::Cancelled { reason });
        self.finished_at = Some(SystemTime::now());
    }
}

// ============================================================================
// Session Types
// ============================================================================

/// Status of a Session
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum SessionStatus {
    /// Session is active
    Active,
    /// Session has ended
    Ended,
    /// Session was cancelled
    Cancelled,
}

/// A logical grouping of related Runs
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Session {
    /// Unique identifier
    pub id: SessionId,
    /// Current status
    pub status: SessionStatus,
    /// Session name
    pub name: String,
    /// When session was created
    pub created_at: SystemTime,
    /// When session ended
    pub ended_at: Option<SystemTime>,
    /// Runs in this session
    pub run_ids: Vec<RunId>,
}

impl Session {
    /// Create a new session
    pub fn new(name: String) -> Self {
        Session {
            id: SessionId::new(),
            status: SessionStatus::Active,
            name,
            created_at: SystemTime::now(),
            ended_at: None,
            run_ids: Vec::new(),
        }
    }

    /// Add a run to this session
    pub fn add_run(&mut self, run_id: RunId) {
        self.run_ids.push(run_id);
    }

    /// End the session
    pub fn end(&mut self) {
        self.status = SessionStatus::Ended;
        self.ended_at = Some(SystemTime::now());
    }

    /// Cancel the session
    pub fn cancel(&mut self) {
        self.status = SessionStatus::Cancelled;
        self.ended_at = Some(SystemTime::now());
    }
}

// ============================================================================
// Artifact Types
// ============================================================================

/// Location where an artifact is stored
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ArtifactLocation {
    /// Local filesystem path
    Local {
        /// File path
        path: PathBuf,
    },
    /// HTTP URL
    Http {
        /// URL to fetch artifact
        url: String,
    },
    /// Cloud storage URI
    CloudStorage {
        /// Cloud storage URI
        uri: String,
    },
    /// Inline content
    Inline {
        /// Raw content bytes
        content: Vec<u8>,
    },
}

/// Checksum for artifact integrity
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Checksum {
    /// Algorithm used (e.g., "sha256")
    pub algorithm: String,
    /// Checksum value
    pub value: String,
}

impl Checksum {
    /// Create a new checksum
    pub fn new(algorithm: impl Into<String>, value: impl Into<String>) -> Self {
        Checksum {
            algorithm: algorithm.into(),
            value: value.into(),
        }
    }

    /// Create a SHA-256 checksum
    pub fn sha256(value: impl Into<String>) -> Self {
        Checksum::new("sha256", value)
    }
}

/// Output produced by a Run or Step
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Artifact {
    /// Unique identifier
    pub id: ArtifactId,
    /// Artifact name
    pub name: String,
    /// MIME content type
    pub content_type: String,
    /// Size in bytes
    pub size: u64,
    /// Where the artifact is stored
    pub location: ArtifactLocation,
    /// Optional integrity checksum
    pub checksum: Option<Checksum>,
    /// When artifact was created
    pub created_at: SystemTime,
    /// Run that produced this artifact
    pub source_run: Option<RunId>,
    /// Step that produced this artifact
    pub source_step: Option<StepId>,
}

impl Artifact {
    /// Create a new artifact
    pub fn new(name: String, content_type: String, location: ArtifactLocation) -> Self {
        Artifact {
            id: ArtifactId::new(),
            name,
            content_type,
            size: 0,
            location,
            checksum: None,
            created_at: SystemTime::now(),
            source_run: None,
            source_step: None,
        }
    }

    /// Set artifact size
    pub fn with_size(mut self, size: u64) -> Self {
        self.size = size;
        self
    }

    /// Set artifact checksum
    pub fn with_checksum(mut self, checksum: Checksum) -> Self {
        self.checksum = Some(checksum);
        self
    }

    /// Set source run
    pub fn from_run(mut self, run_id: RunId) -> Self {
        self.source_run = Some(run_id);
        self
    }

    /// Set source step
    pub fn from_step(mut self, step_id: StepId) -> Self {
        self.source_step = Some(step_id);
        self
    }
}

// ============================================================================
// Execution Handle
// ============================================================================

/// A handle to an active execution
#[derive(Debug, Clone)]
pub struct ExecutionHandle {
    /// Run ID for this execution
    pub run_id: RunId,
    /// Runtime environment
    pub runtime_kind: RuntimeKind,
    /// When handle was created
    pub created_at: Instant,
    /// Runtime-specific handle string
    pub runtime_handle: String,
}

impl ExecutionHandle {
    /// Create a new execution handle
    pub fn new(run_id: RunId, runtime_kind: RuntimeKind, runtime_handle: String) -> Self {
        ExecutionHandle {
            run_id,
            runtime_kind,
            created_at: Instant::now(),
            runtime_handle,
        }
    }

    /// Get elapsed time since handle creation
    pub fn elapsed(&self) -> Duration {
        self.created_at.elapsed()
    }
}

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

    #[test]
    fn test_run_input_default_none() {
        let run = Run::new(
            RunTarget::Agent {
                spec_path: PathBuf::from("agent.yaml"),
            },
            RuntimeKind::Local,
        );
        assert!(run.input.is_none());
    }

    #[test]
    fn test_run_with_input() {
        use serde_json::json;
        let value = json!({"key": "value"});
        let run = Run::new(
            RunTarget::Agent {
                spec_path: PathBuf::from("agent.yaml"),
            },
            RuntimeKind::Local,
        )
        .with_input(value.clone());
        assert_eq!(run.input, Some(value));
    }

    #[test]
    fn test_run_id_generation() {
        let id1 = RunId::new();
        let id2 = RunId::new();
        assert_ne!(id1, id2);
    }

    #[test]
    fn test_run_lifecycle() {
        let mut run = Run::new(
            RunTarget::Agent {
                spec_path: PathBuf::from("agent.yaml"),
            },
            RuntimeKind::Local,
        );
        assert_eq!(run.status, RunStatus::Pending);
        assert!(run.started_at.is_none());

        run.start();
        assert_eq!(run.status, RunStatus::Running);

        run.complete();
        assert_eq!(run.status, RunStatus::Completed);
        assert!(run.duration().is_some());
    }

    #[test]
    fn test_run_failure() {
        let mut run = Run::new(
            RunTarget::Agent {
                spec_path: PathBuf::from("agent.yaml"),
            },
            RuntimeKind::Local,
        );
        run.start();
        run.fail(RunError::ExecutionFailed {
            message: "test".into(),
        });
        assert_eq!(run.status, RunStatus::Failed);
    }

    #[test]
    fn test_step_lifecycle() {
        let run_id = RunId::new();
        let mut step = Step::new(run_id, "test-step".into(), PathBuf::from("agent.yaml"));
        assert_eq!(step.status, StepStatus::Pending);

        step.start();
        assert_eq!(step.status, StepStatus::Running);

        step.complete(vec![ArtifactId::new()]);
        assert_eq!(step.status, StepStatus::Completed);
        assert!(!step.output_artifacts.is_empty());
    }

    #[test]
    fn test_session() {
        let mut session = Session::new("test".into());
        session.add_run(RunId::new());
        assert_eq!(session.run_ids.len(), 1);
        session.end();
        assert_eq!(session.status, SessionStatus::Ended);
    }

    #[test]
    fn test_artifact() {
        let artifact = Artifact::new(
            "output.json".into(),
            "application/json".into(),
            ArtifactLocation::Local {
                path: PathBuf::from("/tmp/out.json"),
            },
        )
        .with_size(1024);
        assert_eq!(artifact.name, "output.json");
        assert_eq!(artifact.size, 1024);
    }
}