agent-runtime-definition-builder 0.1.1

Internal immutable Agent definition builder
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
//! Ergonomic, implementation-independent builders for Runtime Agent definitions.
//!
//! This crate owns authoring conveniences only. It may assemble public
//! Extension API values, but it must never load Runtime deployment settings,
//! create Agent Infra clients, or start network listeners.

use std::sync::Arc;

use runtime_extension_api::{
    AgentDefinition, CompletionMode, ContextHook, DefinitionManifest, Guard, Observer, Tool,
};
use runtime_types::DefinitionId;
use sha2::{Digest, Sha256};
use thiserror::Error;

mod skill;
mod workspace;

pub use skill::StaticSkill;
pub use workspace::WorkspaceToolSet;

/// Process environment variable containing the behavior Definition ID.
pub const AGENT_DEFINITION_ID_ENV: &str = "AGENT_DEFINITION_ID";
/// Process environment variable containing the behavior Definition version.
pub const AGENT_DEFINITION_VERSION_ENV: &str = "AGENT_DEFINITION_VERSION";
/// Process environment variable containing the Definition's Runtime type.
pub const AGENT_RUNTIME_TYPE_ENV: &str = "AGENT_RUNTIME_TYPE";

/// Definition identity loaded from the process environment.
///
/// These values identify Agent behavior. They are deliberately separate from
/// `AGENT_INFRA_AGENT_ID` and `AGENT_INFRA_RUNTIME_ID`, which identify Infra
/// resources and are consumed by Runtime Config/Bootstrap instead.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentEnvironment {
    pub definition_id: String,
    pub definition_version: String,
    pub runtime_type: String,
}

impl AgentEnvironment {
    /// Load the three Definition identity variables as one atomic group.
    ///
    /// `Ok(None)` means that none of the variables is present. Supplying only a
    /// subset is rejected so a deployment cannot accidentally combine a new ID
    /// with a source-default version or Runtime type.
    pub fn load() -> Result<Option<Self>, DefinitionBuildError> {
        read_environment(|name| match std::env::var(name) {
            Ok(value) => Ok(Some(value)),
            Err(std::env::VarError::NotPresent) => Ok(None),
            Err(std::env::VarError::NotUnicode(_)) => {
                Err(DefinitionBuildError::InvalidEnvironment { variable: name })
            }
        })
    }

    /// Require a complete Definition identity in the process environment.
    pub fn require() -> Result<Self, DefinitionBuildError> {
        Self::load()?.ok_or(DefinitionBuildError::MissingEnvironment {
            variables: vec![
                AGENT_DEFINITION_ID_ENV,
                AGENT_DEFINITION_VERSION_ENV,
                AGENT_RUNTIME_TYPE_ENV,
            ],
        })
    }
}

#[derive(Debug, Error)]
pub enum DefinitionBuildError {
    #[error("invalid definition id: {0}")]
    InvalidId(String),
    #[error("definition version must not be empty")]
    EmptyVersion,
    #[error("runtime type must not be empty")]
    EmptyRuntimeType,
    #[error("system prompt must not be empty")]
    EmptySystemPrompt,
    #[error("duplicate tool: {0}")]
    DuplicateTool(String),
    #[error("duplicate context hook: {0}")]
    DuplicateContextHook(String),
    #[error("required completion tool is not registered: {0}")]
    MissingCompletionTool(String),
    #[error("Agent Definition environment is incomplete; set all of {variables:?}")]
    MissingEnvironment { variables: Vec<&'static str> },
    #[error("Agent Definition environment variable {variable} is not valid UTF-8")]
    InvalidEnvironment { variable: &'static str },
    #[error("invalid static skill: {0}")]
    InvalidSkill(String),
}

/// Fluent builder for one immutable [`AgentDefinition`].
///
/// The builder is intentionally additive: a developer may register only a
/// custom Tool, only a Skill, a Skill plus standard Workspace Tools, or any
/// combination of Tool/Hook/Guard/Observer. No hidden default Tool or network
/// capability is added.
pub struct AgentDefinitionBuilder {
    id: String,
    version: String,
    runtime_type: String,
    system_prompt: String,
    tools: Vec<Arc<dyn Tool>>,
    context_hooks: Vec<Arc<dyn ContextHook>>,
    guards: Vec<Arc<dyn Guard>>,
    observers: Vec<Arc<dyn Observer>>,
    completion_mode: CompletionMode,
}

impl AgentDefinitionBuilder {
    /// Start from source-controlled Definition identity.
    pub fn new(id: impl Into<String>, version: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            version: version.into(),
            runtime_type: "generic".into(),
            system_prompt: String::new(),
            tools: Vec::new(),
            context_hooks: Vec::new(),
            guards: Vec::new(),
            observers: Vec::new(),
            completion_mode: CompletionMode::ModelOrTool,
        }
    }

    /// Start from the complete `AGENT_DEFINITION_*` environment identity.
    ///
    /// Prefer this constructor in a generic Runtime distribution whose exact
    /// Definition identity is deployment-owned. A checked-in Agent may instead
    /// use [`Self::new`] followed by [`Self::load_env`] to make environment
    /// override support explicit while retaining source defaults.
    pub fn from_env() -> Result<Self, DefinitionBuildError> {
        let environment = AgentEnvironment::require()?;
        Ok(
            Self::new(environment.definition_id, environment.definition_version)
                .runtime_type(environment.runtime_type),
        )
    }

    /// Explicitly apply a complete Definition identity from the environment.
    ///
    /// If none of the three variables is set, the source identity is retained.
    /// A partial environment is always an error. This method never reads Infra
    /// IDs, model selection, workspace binding, URLs, or credentials.
    pub fn load_env(mut self) -> Result<Self, DefinitionBuildError> {
        if let Some(environment) = AgentEnvironment::load()? {
            self.id = environment.definition_id;
            self.version = environment.definition_version;
            self.runtime_type = environment.runtime_type;
        }
        Ok(self)
    }

    /// Set the behavior family used by Bootstrap binding validation.
    pub fn runtime_type(mut self, value: impl Into<String>) -> Self {
        self.runtime_type = value.into();
        self
    }
    pub fn system_prompt(mut self, value: impl Into<String>) -> Self {
        self.system_prompt = value.into();
        self
    }
    pub fn tool(mut self, value: Arc<dyn Tool>) -> Self {
        self.tools.push(value);
        self
    }

    /// Register one always-available static Skill as a Context Hook.
    pub fn skill(mut self, value: StaticSkill) -> Self {
        self.context_hooks.push(Arc::new(value));
        self
    }

    /// Register a standard set of capability-scoped Workspace Tools.
    ///
    /// The tools operate exclusively through `ToolContext.workspace`; no local
    /// path, endpoint, credential, or concrete Infra SDK client is exposed.
    pub fn workspace_tools(mut self, value: WorkspaceToolSet) -> Self {
        self.tools.extend(value.into_tools());
        self
    }

    /// Register a dynamic Context Hook for stateful Skills, Memory, or Plan.
    pub fn context_hook(mut self, value: Arc<dyn ContextHook>) -> Self {
        self.context_hooks.push(value);
        self
    }
    pub fn guard(mut self, value: Arc<dyn Guard>) -> Self {
        self.guards.push(value);
        self
    }
    pub fn observer(mut self, value: Arc<dyn Observer>) -> Self {
        self.observers.push(value);
        self
    }
    pub fn completion_mode(mut self, value: CompletionMode) -> Self {
        self.completion_mode = value;
        self
    }

    pub fn build(self) -> Result<Arc<AgentDefinition>, DefinitionBuildError> {
        let id = DefinitionId::new(self.id)
            .map_err(|error| DefinitionBuildError::InvalidId(error.to_string()))?;
        if self.version.trim().is_empty() {
            return Err(DefinitionBuildError::EmptyVersion);
        }
        if self.runtime_type.trim().is_empty() {
            return Err(DefinitionBuildError::EmptyRuntimeType);
        }
        if self.system_prompt.trim().is_empty() {
            return Err(DefinitionBuildError::EmptySystemPrompt);
        }
        let mut tools = std::collections::BTreeMap::new();
        for tool in &self.tools {
            let descriptor = tool.descriptor();
            let name = descriptor.name.clone();
            if tools
                .insert(
                    name.clone(),
                    serde_json::to_string(&descriptor)
                        .expect("ToolDescriptor serialization is infallible"),
                )
                .is_some()
            {
                return Err(DefinitionBuildError::DuplicateTool(name));
            }
        }
        let mut hooks = std::collections::BTreeMap::new();
        for hook in &self.context_hooks {
            let name = hook.name().to_owned();
            if hooks
                .insert(name.clone(), hook.definition_fingerprint())
                .is_some()
            {
                return Err(DefinitionBuildError::DuplicateContextHook(name));
            }
        }
        if let CompletionMode::RequiredTool(name) = &self.completion_mode
            && !tools.contains_key(name)
        {
            return Err(DefinitionBuildError::MissingCompletionTool(name.clone()));
        }
        let digest = definition_digest(
            id.as_str(),
            &self.version,
            &self.runtime_type,
            &self.system_prompt,
            tools
                .iter()
                .map(|(name, fingerprint)| format!("tool:{name}:{fingerprint}"))
                .chain(
                    hooks
                        .iter()
                        .map(|(name, fingerprint)| format!("hook:{name}:{fingerprint}")),
                ),
        );
        Ok(Arc::new(AgentDefinition {
            manifest: DefinitionManifest {
                id,
                version: self.version,
                runtime_type: self.runtime_type,
                schema_version: 1,
                digest,
            },
            system_prompt: self.system_prompt,
            tools: self.tools,
            context_hooks: self.context_hooks,
            guards: self.guards,
            observers: self.observers,
            completion_mode: self.completion_mode,
        }))
    }
}

fn read_environment(
    read: impl Fn(&'static str) -> Result<Option<String>, DefinitionBuildError>,
) -> Result<Option<AgentEnvironment>, DefinitionBuildError> {
    let id = read(AGENT_DEFINITION_ID_ENV)?;
    let version = read(AGENT_DEFINITION_VERSION_ENV)?;
    let runtime_type = read(AGENT_RUNTIME_TYPE_ENV)?;
    let present = [id.is_some(), version.is_some(), runtime_type.is_some()];
    if present.iter().all(|value| !value) {
        return Ok(None);
    }
    if !present.iter().all(|value| *value) {
        let variables = [
            (AGENT_DEFINITION_ID_ENV, id.is_none()),
            (AGENT_DEFINITION_VERSION_ENV, version.is_none()),
            (AGENT_RUNTIME_TYPE_ENV, runtime_type.is_none()),
        ]
        .into_iter()
        .filter_map(|(name, missing)| missing.then_some(name))
        .collect();
        return Err(DefinitionBuildError::MissingEnvironment { variables });
    }
    Ok(Some(AgentEnvironment {
        definition_id: id.expect("presence checked"),
        definition_version: version.expect("presence checked"),
        runtime_type: runtime_type.expect("presence checked"),
    }))
}

fn definition_digest(
    id: &str,
    version: &str,
    runtime_type: &str,
    prompt: &str,
    components: impl Iterator<Item = String>,
) -> String {
    let mut digest = Sha256::new();
    for value in [id, version, runtime_type, prompt] {
        digest.update(value.len().to_be_bytes());
        digest.update(value.as_bytes());
    }
    for component in components {
        digest.update(component.len().to_be_bytes());
        digest.update(component.as_bytes());
    }
    format!("sha256:{:x}", digest.finalize())
}

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

    #[test]
    fn definition_digest_is_reproducible() {
        let one = definition_digest(
            "a",
            "1",
            "generic",
            "prompt",
            ["x".to_owned(), "y".to_owned()].into_iter(),
        );
        let two = definition_digest(
            "a",
            "1",
            "generic",
            "prompt",
            ["x".to_owned(), "y".to_owned()].into_iter(),
        );
        assert_eq!(one, two);
    }

    #[test]
    fn environment_identity_is_atomic() {
        let complete = read_environment(|name| match name {
            AGENT_DEFINITION_ID_ENV => Ok(Some("review-agent".into())),
            AGENT_DEFINITION_VERSION_ENV => Ok(Some("1.2.3".into())),
            AGENT_RUNTIME_TYPE_ENV => Ok(Some("review".into())),
            _ => Ok(None),
        })
        .unwrap()
        .unwrap();
        assert_eq!(complete.definition_id, "review-agent");

        let error = read_environment(|name| {
            Ok((name == AGENT_DEFINITION_ID_ENV).then(|| "review-agent".into()))
        })
        .unwrap_err();
        assert!(matches!(
            error,
            DefinitionBuildError::MissingEnvironment { .. }
        ));
    }

    #[test]
    fn skill_and_workspace_tools_are_independently_composable() {
        let skill_only = AgentDefinitionBuilder::new("skill-only", "1")
            .system_prompt("Use the skill.")
            .skill(StaticSkill::new("review", "Review carefully.").unwrap())
            .build()
            .unwrap();
        assert!(skill_only.tools.is_empty());
        assert_eq!(skill_only.context_hooks.len(), 1);

        let skill_and_workspace = AgentDefinitionBuilder::new("skill-workspace", "1")
            .system_prompt("Inspect the workspace.")
            .skill(StaticSkill::new("inspect", "Read evidence first.").unwrap())
            .workspace_tools(WorkspaceToolSet::read_only())
            .build()
            .unwrap();
        let names = skill_and_workspace
            .tools
            .iter()
            .map(|tool| tool.descriptor().name)
            .collect::<Vec<_>>();
        assert_eq!(
            names,
            ["workspace.read", "workspace.list", "workspace.search"]
        );

        let changed_skill = AgentDefinitionBuilder::new("skill-workspace", "1")
            .system_prompt("Inspect the workspace.")
            .skill(StaticSkill::new("inspect", "Use different evidence.").unwrap())
            .workspace_tools(WorkspaceToolSet::read_only())
            .build()
            .unwrap();
        assert_ne!(
            skill_and_workspace.manifest.digest,
            changed_skill.manifest.digest
        );
    }
}