agents-kit 0.0.1

Rust agent control Kit for Codex, OpenCode, and provider-backed Custom runtimes
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
//! Backend-advertised model, personality, and reasoning selectors.
//!
//! Selectors preserve their exact strings. Construction validates shape, not
//! availability; use [`crate::AgentBackend::list_models`] for the selected
//! backend's inventory. [`ModelInfo`] reports optional backend metadata without
//! turning it into a cross-provider capability promise.

//!
//! # Supplied selector restrictions
//!
//! | Backend | Reasoning | Personality |
//! | --- | --- | --- |
//! | Codex | Exact effort advertised for the selected model | Rejected: the selected native protocol retired personality selection |
//! | OpenCode | Portable override is Unsupported | Portable override is Unsupported |
//! | Custom | `minimal`, `low`, `medium`, `high`, `maximum`, mapped to Provider's portable reasoning enum | Unsupported |
//!
//! Custom's selected Provider Model still validates whether it can honor the
//! mapped effort. Arbitrary native efforts such as `xhigh` are not a Custom
//! escape hatch. An omitted override stays omitted at the Agent request boundary;
//! effective values also depend on conversation/workspace defaults. Availability
//! of a model name or a syntactically valid selector is not execution evidence.
//! Caller implementations may support their own advertised selectors.
//!
//! # Exact Codex selection
//!
//! This example requires the supported Codex executable on `PATH`, native
//! authentication and access to the exact model. Building starts a subprocess;
//! listing and prompting use the real native service, so this compiles without
//! running as a doctest. No caller Provider is constructed for a native Agent.
//!
//! ```no_run
//! use std::{num::NonZeroUsize, time::Duration};
//! use agents_kit::{AgentBackend, AgentBuilder, AgentStorage, ConversationBackend, WorkspaceBackend};
//! use agents_kit::config::{AgentConfig, CodexConfig};
//! use agents_kit::conversation::NewConversation;
//! use agents_kit::model::{ModelSelector, ReasoningEffort};
//! use agents_kit::prompt::PromptRequest;
//! use agents_kit::workspace::{NewWorkspace, WorkspaceContext, WorkspaceDefaults,
//!     WorkspaceExecutionPolicy, WorkspaceNetworkAccess, WorkspaceRoot,
//!     WorkspaceRootAccess, WorkspaceSandboxMode};
//! use storage_kit::{StateStore,
//!     state::config::{LanceStateStoreConfig, StateStoreConfig}};
//! # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
//! # runtime.block_on(async {
//! let store = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory())).await?;
//! let config = AgentConfig::new(CodexConfig::spawn(Duration::from_secs(15),
//!     Duration::from_secs(90))?.into(), Duration::from_secs(60), NonZeroUsize::MIN)?;
//! let agent = AgentBuilder::create(config, AgentStorage::new(store)).build().await?;
//! let outcome = async {
//!     let selected = ModelSelector::new("gpt-6-luna")?;
//!     let effort = ReasoningEffort::medium();
//!     let inventory = agent.list_models().await?;
//!     let model = inventory.iter().find(|item| item.selector() == &selected)
//!         .ok_or_else(|| agents_kit::KitError::unsupported("required exact model is unavailable"))?;
//!     if !model.reasoning_efforts().contains(&effort) {
//!         return Err(agents_kit::KitError::unsupported("required effort is unavailable").into());
//!     }
//!     let cwd = std::env::current_dir()?;
//!     let context = WorkspaceContext::new(cwd.clone(),
//!         vec![WorkspaceRoot::new(cwd, WorkspaceRootAccess::ReadOnly)?],
//!         WorkspaceExecutionPolicy::new(WorkspaceSandboxMode::ReadOnly, WorkspaceNetworkAccess::Disabled))?;
//!     let workspace = agent.new_workspace(NewWorkspace::new("review", context, WorkspaceDefaults::empty())?).await?;
//!     let conversation = workspace.new_conversation(NewConversation::new(None, None, vec![])?).await?;
//!     let response = conversation.prompt(PromptRequest::new("Describe the current task without changing files.")?
//!         .with_model(selected).with_reasoning_effort(effort)
//!         .with_timeout(Duration::from_secs(90))?).await;
//!     let close = conversation.close().await;
//!     let workspace_close = workspace.close().await;
//!     let response = response?;
//!     close?;
//!     workspace_close?;
//!     assert!(!response.output().trim().is_empty()); // progress, not a prescribed wording grade
//!     Ok::<(), Box<dyn std::error::Error>>(())
//! }.await;
//! let shutdown = agent.shutdown().await;
//! outcome?;
//! shutdown?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! # })?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::KitError;

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// Selects one backend model by its canonical opaque value.
///
/// ```
/// use agents_kit::model::ModelSelector;
///
/// let selector = ModelSelector::new("model-slug")?;
/// assert_eq!(selector.as_str(), "model-slug");
/// # Ok::<(), agents_kit::KitError>(())
/// ```
pub struct ModelSelector {
    value: String,
}

impl ModelSelector {
    /// Validates and constructs a nonempty, unpadded selector.
    ///
    /// # Errors
    /// Returns [`crate::error::ErrorKind::InvalidInput`] for an empty or padded value.
    ///
    /// ```
    /// use agents_kit::model::ModelSelector;
    /// let model = ModelSelector::new("exact-model-id")?;
    /// assert_eq!(model.as_str(), "exact-model-id");
    /// assert!(ModelSelector::new(" model ").is_err());
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn new(value: impl Into<String>) -> Result<Self, KitError> {
        let value = value.into();
        if value.is_empty() || value.trim() != value {
            return Err(KitError::invalid_input(
                "model selector must be nonempty and unpadded",
            ));
        }
        Ok(Self { value })
    }

    /// Returns the canonical selector value.
    ///
    /// ```
    /// use agents_kit::model::ModelSelector;
    /// assert_eq!(ModelSelector::new("model-id")?.as_str(), "model-id");
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn as_str(&self) -> &str {
        &self.value
    }
}

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

impl Serialize for ModelSelector {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.value)
    }
}

impl<'de> Deserialize<'de> for ModelSelector {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// Selects one backend-advertised personality by its canonical opaque value.
///
/// ```
/// use agents_kit::model::PersonalitySelector;
/// let personality = PersonalitySelector::new("concise")?;
/// assert_eq!(personality.as_str(), "concise");
/// # Ok::<(), agents_kit::KitError>(())
/// ```
pub struct PersonalitySelector {
    value: String,
}

impl PersonalitySelector {
    /// Validates and constructs a nonempty, unpadded personality selector.
    ///
    /// # Errors
    /// Returns [`crate::error::ErrorKind::InvalidInput`] for an empty or padded value.
    /// This does not check whether a backend advertises the personality.
    ///
    /// ```
    /// use agents_kit::model::PersonalitySelector;
    /// assert!(PersonalitySelector::new("").is_err());
    /// assert_eq!(PersonalitySelector::new("concise")?.as_str(), "concise");
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn new(value: impl Into<String>) -> Result<Self, KitError> {
        let value = value.into();
        if value.is_empty() || value.trim() != value {
            return Err(KitError::invalid_input(
                "personality selector must be nonempty and unpadded",
            ));
        }
        Ok(Self { value })
    }

    /// Returns the canonical selector value.
    ///
    /// ```
    /// use agents_kit::model::PersonalitySelector;
    /// assert_eq!(PersonalitySelector::new("concise")?.as_str(), "concise");
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn as_str(&self) -> &str {
        &self.value
    }
}

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

impl Serialize for PersonalitySelector {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.value)
    }
}

impl<'de> Deserialize<'de> for PersonalitySelector {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// Describes an open-ended backend reasoning-effort value.
///
/// The conventional constructors do not establish support on a selected model.
/// See the [supplied selector restrictions](self#supplied-selector-restrictions).
///
/// ```
/// use agents_kit::model::ReasoningEffort;
/// assert_eq!(ReasoningEffort::high().as_str(), "high");
/// ```
pub struct ReasoningEffort {
    value: String,
}

impl ReasoningEffort {
    /// Validates and constructs a nonempty, unpadded effort value.
    ///
    /// # Errors
    /// Returns [`crate::error::ErrorKind::InvalidInput`] for an empty or padded value.
    ///
    /// ```
    /// use agents_kit::model::ReasoningEffort;
    /// assert_eq!(ReasoningEffort::new("custom-effort")?.as_str(), "custom-effort");
    /// assert!(ReasoningEffort::new(" high").is_err());
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn new(value: impl Into<String>) -> Result<Self, KitError> {
        let value = value.into();
        if value.is_empty() || value.trim() != value {
            return Err(KitError::invalid_input(
                "reasoning effort must be nonempty and unpadded",
            ));
        }
        Ok(Self { value })
    }

    /// Constructs the conventional low effort value.
    ///
    /// ```
    /// assert_eq!(agents_kit::model::ReasoningEffort::low().as_str(), "low");
    /// ```
    pub fn low() -> Self {
        Self {
            value: "low".to_owned(),
        }
    }

    /// Constructs the conventional medium effort value.
    ///
    /// ```
    /// assert_eq!(agents_kit::model::ReasoningEffort::medium().as_str(), "medium");
    /// ```
    pub fn medium() -> Self {
        Self {
            value: "medium".to_owned(),
        }
    }

    /// Constructs the conventional high effort value.
    ///
    /// ```
    /// assert_eq!(agents_kit::model::ReasoningEffort::high().as_str(), "high");
    /// ```
    pub fn high() -> Self {
        Self {
            value: "high".to_owned(),
        }
    }

    /// Returns the canonical effort value.
    ///
    /// ```
    /// use agents_kit::model::ReasoningEffort;
    /// let effort = ReasoningEffort::low();
    /// assert_eq!(effort.as_str(), "low");
    /// ```
    pub fn as_str(&self) -> &str {
        &self.value
    }
}

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

impl Serialize for ReasoningEffort {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.value)
    }
}

impl<'de> Deserialize<'de> for ReasoningEffort {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
/// Describes one selectable model returned by agent inventory.
///
/// ```
/// use agents_kit::model::{ModelInfo, ModelSelector};
/// let info = ModelInfo::new(ModelSelector::new("model-id")?, None, vec![], true)?;
/// assert!(info.is_default());
/// assert_eq!(info.selector().as_str(), "model-id");
/// # Ok::<(), agents_kit::KitError>(())
/// ```
pub struct ModelInfo {
    selector: ModelSelector,
    display_name: Option<String>,
    reasoning_efforts: Vec<ReasoningEffort>,
    personalities: Vec<PersonalitySelector>,
    is_default: bool,
}

impl ModelInfo {
    /// Constructs validated model inventory information.
    ///
    /// # Errors
    /// Returns [`crate::error::ErrorKind::InvalidInput`] for a present empty or
    /// padded display name. It performs no model discovery or network request.
    ///
    /// ```
    /// use agents_kit::model::{ModelInfo, ModelSelector, ReasoningEffort};
    /// let info = ModelInfo::new(ModelSelector::new("model-id")?,
    ///     Some("Example model".into()), vec![ReasoningEffort::low()], false)?;
    /// assert_eq!(info.display_name(), Some("Example model"));
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn new(
        selector: ModelSelector,
        display_name: Option<String>,
        reasoning_efforts: Vec<ReasoningEffort>,
        is_default: bool,
    ) -> Result<Self, KitError> {
        if display_name
            .as_deref()
            .is_some_and(|name| name.is_empty() || name.trim() != name)
        {
            return Err(KitError::invalid_input(
                "model display name must be nonempty and unpadded when present",
            ));
        }
        Ok(Self {
            selector,
            display_name,
            reasoning_efforts,
            personalities: Vec::new(),
            is_default,
        })
    }

    /// Replaces the ordered backend-advertised personality values.
    ///
    /// ```
    /// use agents_kit::model::{ModelInfo, ModelSelector, PersonalitySelector};
    /// let info = ModelInfo::new(ModelSelector::new("model-id")?, None, vec![], false)?
    ///     .with_personalities(vec![PersonalitySelector::new("concise")?]);
    /// assert_eq!(info.personalities()[0].as_str(), "concise");
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    #[must_use]
    pub fn with_personalities(mut self, personalities: Vec<PersonalitySelector>) -> Self {
        self.personalities = personalities;
        self
    }

    /// Returns the selector callers can round-trip into prompts and defaults.
    ///
    /// ```
    /// use agents_kit::model::{ModelInfo, ModelSelector};
    /// let info = ModelInfo::new(ModelSelector::new("model-id")?, None, vec![], false)?;
    /// let request = agents_kit::prompt::PromptRequest::new("Hello")?.with_model(info.selector().clone());
    /// assert_eq!(request.model(), Some(info.selector()));
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn selector(&self) -> &ModelSelector {
        &self.selector
    }

    /// Returns the optional caller-facing model name.
    ///
    /// ```
    /// use agents_kit::model::{ModelInfo, ModelSelector};
    /// let info = ModelInfo::new(ModelSelector::new("model-id")?, None, vec![], false)?;
    /// assert_eq!(info.display_name(), None);
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn display_name(&self) -> Option<&str> {
        self.display_name.as_deref()
    }

    /// Returns the advertised open-ended reasoning-effort values.
    ///
    /// ```
    /// use agents_kit::model::{ModelInfo, ModelSelector, ReasoningEffort};
    /// let info = ModelInfo::new(ModelSelector::new("model-id")?, None,
    ///     vec![ReasoningEffort::low()], false)?;
    /// assert_eq!(info.reasoning_efforts(), &[ReasoningEffort::low()]);
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn reasoning_efforts(&self) -> &[ReasoningEffort] {
        &self.reasoning_efforts
    }

    /// Returns the ordered backend-advertised personality values.
    ///
    /// ```
    /// use agents_kit::model::{ModelInfo, ModelSelector};
    /// let info = ModelInfo::new(ModelSelector::new("model-id")?, None, vec![], false)?;
    /// assert!(info.personalities().is_empty());
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn personalities(&self) -> &[PersonalitySelector] {
        &self.personalities
    }

    /// Reports whether this is the sourced agent-wide default model.
    ///
    /// ```
    /// use agents_kit::model::{ModelInfo, ModelSelector};
    /// let info = ModelInfo::new(ModelSelector::new("model-id")?, None, vec![], true)?;
    /// assert!(info.is_default());
    /// # Ok::<(), agents_kit::KitError>(())
    /// ```
    pub fn is_default(&self) -> bool {
        self.is_default
    }
}