pipelin3r 0.1.0

Pipeline orchestration for LLM-powered workflows
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
//! Typed LLM model and provider selection with TOML-based configuration.

use std::collections::BTreeMap;
use std::path::Path;

/// Embedded default model configuration, compiled from `models.toml`.
const DEFAULT_MODELS_TOML: &str = include_str!("../models.toml");

/// Tool available to an agent during invocation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Tool {
    /// File reading tool.
    Read,
    /// File writing tool.
    Write,
    /// Content search (grep) tool.
    Grep,
    /// File pattern matching (glob) tool.
    Glob,
    /// Web search tool.
    WebSearch,
    /// Web page fetch tool.
    WebFetch,
    /// Custom tool name (passed through as-is).
    Custom(String),
}

impl Tool {
    /// Get the tool name string used in the CLI `--allowedTools` flag.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Read => "Read",
            Self::Write => "Write",
            Self::Grep => "Grep",
            Self::Glob => "Glob",
            Self::WebSearch => "WebSearch",
            Self::WebFetch => "WebFetch",
            Self::Custom(s) => s.as_str(),
        }
    }
}

impl std::fmt::Display for Tool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// LLM model selection.
#[derive(Debug, Clone)]
pub enum Model {
    /// Claude Opus 4.6
    Opus4_6,
    /// Claude Sonnet 4.6
    Sonnet4_6,
    /// Claude Haiku 4.5
    Haiku4_5,
    /// Custom model identifier (passed through as-is).
    Custom(String),
}

/// LLM provider.
#[derive(Debug, Clone, Default)]
pub enum Provider {
    /// Anthropic direct API.
    #[default]
    Anthropic,
    /// `OpenRouter` proxy.
    OpenRouter,
    /// AWS Bedrock.
    Bedrock,
    /// Google Vertex AI.
    Vertex,
    /// Custom provider (model IDs passed through as-is).
    Custom(String),
}

impl Model {
    /// Get the model ID string for the given provider using hardcoded defaults.
    ///
    /// Known models are mapped to provider-specific identifiers.
    /// `Custom` variants are passed through unchanged regardless of provider.
    pub fn id(&self, provider: &Provider) -> String {
        let base = match self {
            Self::Opus4_6 => "claude-opus-4-6",
            Self::Sonnet4_6 => "claude-sonnet-4-6",
            Self::Haiku4_5 => "claude-haiku-4-5",
            Self::Custom(id) => return id.clone(),
        };
        match provider {
            Provider::OpenRouter => format!("anthropic/{base}"),
            Provider::Bedrock => format!("anthropic.{base}-v1"),
            Provider::Anthropic | Provider::Custom(_) | Provider::Vertex => String::from(base),
        }
    }

    /// Get the TOML configuration key for this model variant.
    ///
    /// Returns `None` for `Custom` models (they bypass configuration).
    const fn config_key(&self) -> Option<&str> {
        match self {
            Self::Opus4_6 => Some("opus_4_6"),
            Self::Sonnet4_6 => Some("sonnet_4_6"),
            Self::Haiku4_5 => Some("haiku_4_5"),
            Self::Custom(_) => None,
        }
    }
}

impl Provider {
    /// Get the TOML configuration key for this provider variant.
    ///
    /// Returns `None` for `Custom` providers (they bypass configuration).
    const fn config_key(&self) -> Option<&str> {
        match self {
            Self::Anthropic => Some("anthropic"),
            Self::OpenRouter => Some("openrouter"),
            Self::Bedrock => Some("bedrock"),
            Self::Vertex => Some("vertex"),
            Self::Custom(_) => None,
        }
    }
}

/// Loaded model ID configuration, grouped by provider.
///
/// Holds a mapping of `provider_key -> model_key -> model_id_string`.
/// Use [`ModelConfig::resolve`] to look up the model ID for a given
/// model/provider pair, falling back to hardcoded defaults when the
/// config does not contain the entry.
#[derive(Debug, Clone, Default)]
pub struct ModelConfig {
    providers: BTreeMap<String, BTreeMap<String, String>>,
}

impl ModelConfig {
    /// Load model configuration from a TOML string.
    ///
    /// # Errors
    /// Returns an error if the TOML string cannot be parsed.
    pub fn from_toml(toml_str: &str) -> Result<Self, crate::error::PipelineError> {
        let providers: BTreeMap<String, BTreeMap<String, String>> = toml::from_str(toml_str)
            .map_err(|e| crate::error::PipelineError::Config(format!("failed to parse model TOML: {e}")))?;
        Ok(Self { providers })
    }

    /// Load model configuration from a TOML file path.
    ///
    /// # Errors
    /// Returns an error if the file cannot be read or parsed.
    pub fn from_file(path: &Path) -> Result<Self, crate::error::PipelineError> {
        let content = std::fs::read_to_string(path).map_err(|e| {
            crate::error::PipelineError::Config(format!("failed to read model config {}: {e}", path.display()))
        })?;
        Self::from_toml(&content)
    }

    /// Load the built-in default configuration (embedded at compile time).
    ///
    /// # Panics
    /// This function does not panic. The embedded TOML is validated at
    /// development time, so parsing is expected to succeed. If parsing
    /// fails, an empty config is returned and all lookups fall through
    /// to hardcoded defaults.
    pub fn default_config() -> Self {
        Self::from_toml(DEFAULT_MODELS_TOML).unwrap_or_default()
    }

    /// Resolve a model ID for the given model and provider.
    ///
    /// Looks up the model ID in the loaded configuration first.
    /// Falls back to the hardcoded [`Model::id`] method if:
    /// - The model is `Custom` (always passed through as-is)
    /// - The provider is `Custom` (always uses hardcoded logic)
    /// - The configuration does not contain the provider or model key
    pub fn resolve(&self, model: &Model, provider: &Provider) -> String {
        let Some(provider_key) = provider.config_key() else {
            return model.id(provider);
        };
        let Some(model_key) = model.config_key() else {
            return model.id(provider);
        };

        self.providers
            .get(provider_key)
            .and_then(|models| models.get(model_key))
            .cloned()
            .unwrap_or_else(|| model.id(provider))
    }
}

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

    // --- Tool enum tests ---

    #[test]
    fn tool_as_str_known_variants() {
        assert_eq!(Tool::Read.as_str(), "Read", "Read tool name");
        assert_eq!(Tool::Write.as_str(), "Write", "Write tool name");
        assert_eq!(Tool::Grep.as_str(), "Grep", "Grep tool name");
        assert_eq!(Tool::Glob.as_str(), "Glob", "Glob tool name");
        assert_eq!(Tool::WebSearch.as_str(), "WebSearch", "WebSearch tool name");
        assert_eq!(Tool::WebFetch.as_str(), "WebFetch", "WebFetch tool name");
    }

    #[test]
    fn tool_as_str_custom() {
        let tool = Tool::Custom(String::from("MyCustomTool"));
        assert_eq!(
            tool.as_str(),
            "MyCustomTool",
            "Custom tool should pass through"
        );
    }

    #[test]
    fn regression_tool_enum_returns_strings_not_indices() {
        // Regression: Tool variants returned numeric indices or debug strings
        // instead of the expected CLI tool name strings.
        assert_eq!(
            Tool::Read.as_str(),
            "Read",
            "Tool::Read must return \"Read\", not a number or debug repr"
        );
        assert_eq!(
            Tool::Custom(String::from("Mcp")).as_str(),
            "Mcp",
            "Tool::Custom must return the inner string as-is"
        );
        // Verify all known variants produce non-empty proper strings.
        let known = [
            Tool::Read, Tool::Write, Tool::Grep,
            Tool::Glob, Tool::WebSearch, Tool::WebFetch,
        ];
        for tool in &known {
            let s = tool.as_str();
            assert!(!s.is_empty(), "tool string must not be empty");
            assert!(
                s.chars().next().is_some_and(char::is_uppercase),
                "tool string must start with uppercase: {s}"
            );
        }
    }

    #[test]
    fn tool_display() {
        assert_eq!(format!("{}", Tool::Read), "Read", "Display for Read");
        assert_eq!(
            format!("{}", Tool::Custom(String::from("X"))),
            "X",
            "Display for Custom"
        );
    }

    // --- Model tests ---

    #[test]
    fn anthropic_opus() {
        assert_eq!(
            Model::Opus4_6.id(&Provider::Anthropic),
            "claude-opus-4-6",
            "Anthropic Opus model ID"
        );
    }

    #[test]
    fn anthropic_sonnet() {
        assert_eq!(
            Model::Sonnet4_6.id(&Provider::Anthropic),
            "claude-sonnet-4-6",
            "Anthropic Sonnet model ID"
        );
    }

    #[test]
    fn anthropic_haiku() {
        assert_eq!(
            Model::Haiku4_5.id(&Provider::Anthropic),
            "claude-haiku-4-5",
            "Anthropic Haiku model ID"
        );
    }

    #[test]
    fn openrouter_opus() {
        assert_eq!(
            Model::Opus4_6.id(&Provider::OpenRouter),
            "anthropic/claude-opus-4-6",
            "OpenRouter Opus model ID"
        );
    }

    #[test]
    fn openrouter_sonnet() {
        assert_eq!(
            Model::Sonnet4_6.id(&Provider::OpenRouter),
            "anthropic/claude-sonnet-4-6",
            "OpenRouter Sonnet model ID"
        );
    }

    #[test]
    fn bedrock_opus() {
        assert_eq!(
            Model::Opus4_6.id(&Provider::Bedrock),
            "anthropic.claude-opus-4-6-v1",
            "Bedrock Opus model ID"
        );
    }

    #[test]
    fn bedrock_haiku() {
        assert_eq!(
            Model::Haiku4_5.id(&Provider::Bedrock),
            "anthropic.claude-haiku-4-5-v1",
            "Bedrock Haiku model ID"
        );
    }

    #[test]
    fn vertex_sonnet() {
        assert_eq!(
            Model::Sonnet4_6.id(&Provider::Vertex),
            "claude-sonnet-4-6",
            "Vertex Sonnet model ID (hardcoded fallback)"
        );
    }

    #[test]
    fn custom_model_passthrough() {
        let model = Model::Custom(String::from("my-fine-tuned-model"));
        assert_eq!(
            model.id(&Provider::Anthropic),
            "my-fine-tuned-model",
            "Custom model should pass through for Anthropic"
        );
        assert_eq!(
            model.id(&Provider::OpenRouter),
            "my-fine-tuned-model",
            "Custom model should pass through for OpenRouter"
        );
        assert_eq!(
            model.id(&Provider::Bedrock),
            "my-fine-tuned-model",
            "Custom model should pass through for Bedrock"
        );
    }

    #[test]
    fn custom_provider_uses_base_ids() {
        let provider = Provider::Custom(String::from("my-provider"));
        assert_eq!(
            Model::Opus4_6.id(&provider),
            "claude-opus-4-6",
            "Custom provider should use base model IDs"
        );
    }

    #[test]
    fn default_provider_is_anthropic() {
        let provider = Provider::default();
        assert_eq!(
            Model::Opus4_6.id(&provider),
            "claude-opus-4-6",
            "Default provider should behave like Anthropic"
        );
    }

    // --- ModelConfig tests ---

    #[test]
    fn config_from_toml_roundtrip() {
        let toml_str = r#"
[anthropic]
opus_4_6 = "claude-opus-4-6"
sonnet_4_6 = "claude-sonnet-4-6"

[openrouter]
opus_4_6 = "anthropic/claude-opus-4-6"
"#;
        let config = ModelConfig::from_toml(toml_str);
        assert!(config.is_ok(), "should parse valid TOML");
        let config = config.unwrap_or_default();
        assert_eq!(
            config
                .providers
                .get("anthropic")
                .and_then(|m| m.get("opus_4_6")),
            Some(&String::from("claude-opus-4-6")),
            "should contain anthropic opus entry"
        );
    }

    #[test]
    fn config_resolve_with_loaded_config() {
        let toml_str = r#"
[vertex]
opus_4_6 = "claude-opus-4-6@20250514"
sonnet_4_6 = "claude-sonnet-4-6@20250514"
haiku_4_5 = "claude-haiku-4-5@20251001"
"#;
        let config = ModelConfig::from_toml(toml_str).unwrap_or_default();
        assert_eq!(
            config.resolve(&Model::Opus4_6, &Provider::Vertex),
            "claude-opus-4-6@20250514",
            "should resolve vertex opus from config"
        );
        assert_eq!(
            config.resolve(&Model::Haiku4_5, &Provider::Vertex),
            "claude-haiku-4-5@20251001",
            "should resolve vertex haiku from config"
        );
    }

    #[test]
    fn config_resolve_fallback_for_missing_entry() {
        let toml_str = r#"
[anthropic]
opus_4_6 = "claude-opus-4-6"
"#;
        let config = ModelConfig::from_toml(toml_str).unwrap_or_default();
        // haiku_4_5 is not in config — should fall back to hardcoded.
        assert_eq!(
            config.resolve(&Model::Haiku4_5, &Provider::Anthropic),
            "claude-haiku-4-5",
            "should fall back to hardcoded for missing model key"
        );
        // openrouter is not in config at all — should fall back to hardcoded.
        assert_eq!(
            config.resolve(&Model::Opus4_6, &Provider::OpenRouter),
            "anthropic/claude-opus-4-6",
            "should fall back to hardcoded for missing provider"
        );
    }

    #[test]
    fn config_default_loads_embedded_toml() {
        let config = ModelConfig::default_config();
        assert_eq!(
            config.resolve(&Model::Opus4_6, &Provider::Anthropic),
            "claude-opus-4-6",
            "default config should resolve anthropic opus"
        );
        assert_eq!(
            config.resolve(&Model::Sonnet4_6, &Provider::OpenRouter),
            "anthropic/claude-sonnet-4-6",
            "default config should resolve openrouter sonnet"
        );
        assert_eq!(
            config.resolve(&Model::Haiku4_5, &Provider::Bedrock),
            "anthropic.claude-haiku-4-5-v1",
            "default config should resolve bedrock haiku"
        );
        assert_eq!(
            config.resolve(&Model::Opus4_6, &Provider::Vertex),
            "claude-opus-4-6@20250514",
            "default config should resolve vertex opus with date suffix"
        );
    }

    #[test]
    fn config_custom_model_bypasses_config() {
        let config = ModelConfig::default_config();
        let model = Model::Custom(String::from("my-custom-model"));
        assert_eq!(
            config.resolve(&model, &Provider::Anthropic),
            "my-custom-model",
            "custom model should bypass config lookup"
        );
        assert_eq!(
            config.resolve(&model, &Provider::OpenRouter),
            "my-custom-model",
            "custom model should bypass config for all providers"
        );
    }

    #[test]
    fn config_custom_provider_bypasses_config() {
        let config = ModelConfig::default_config();
        let provider = Provider::Custom(String::from("my-provider"));
        assert_eq!(
            config.resolve(&Model::Opus4_6, &provider),
            "claude-opus-4-6",
            "custom provider should bypass config and use hardcoded base ID"
        );
    }

    #[test]
    fn config_from_toml_invalid() {
        let result = ModelConfig::from_toml("this is not [valid toml");
        assert!(result.is_err(), "should fail on invalid TOML");
    }

    #[test]
    fn config_from_file_nonexistent() {
        let result = ModelConfig::from_file(Path::new("/nonexistent/models.toml"));
        assert!(result.is_err(), "should fail on nonexistent file");
    }

    #[test]
    fn config_empty_toml_falls_back() {
        let config = ModelConfig::from_toml("").unwrap_or_default();
        assert_eq!(
            config.resolve(&Model::Opus4_6, &Provider::Anthropic),
            "claude-opus-4-6",
            "empty config should fall back to hardcoded"
        );
    }

    #[test]
    fn config_key_model_variants() {
        assert_eq!(
            Model::Opus4_6.config_key(),
            Some("opus_4_6"),
            "Opus4_6 config key"
        );
        assert_eq!(
            Model::Sonnet4_6.config_key(),
            Some("sonnet_4_6"),
            "Sonnet4_6 config key"
        );
        assert_eq!(
            Model::Haiku4_5.config_key(),
            Some("haiku_4_5"),
            "Haiku4_5 config key"
        );
        assert_eq!(
            Model::Custom(String::from("x")).config_key(),
            None,
            "Custom model has no config key"
        );
    }

    #[test]
    fn config_key_provider_variants() {
        assert_eq!(
            Provider::Anthropic.config_key(),
            Some("anthropic"),
            "Anthropic config key"
        );
        assert_eq!(
            Provider::OpenRouter.config_key(),
            Some("openrouter"),
            "OpenRouter config key"
        );
        assert_eq!(
            Provider::Bedrock.config_key(),
            Some("bedrock"),
            "Bedrock config key"
        );
        assert_eq!(
            Provider::Vertex.config_key(),
            Some("vertex"),
            "Vertex config key"
        );
        assert_eq!(
            Provider::Custom(String::from("x")).config_key(),
            None,
            "Custom provider has no config key"
        );
    }
}