agent-runtime-extension-api 0.1.1

Internal extension contract backing the Agent Runtime SDK
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
//! Public extension contract used by first-party and third-party Agent definitions.

use std::{collections::BTreeMap, sync::Arc, time::Instant};

use async_trait::async_trait;
use runtime_types::{DefinitionId, ExecutionId, ToolCallId};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
use tokio_util::sync::CancellationToken;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ToolDescriptor {
    pub name: String,
    pub description: String,
    pub input_schema: Value,
    #[serde(default)]
    pub required_capabilities: Vec<String>,
    #[serde(default)]
    pub side_effect: SideEffect,
}

#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SideEffect {
    #[default]
    ReadOnly,
    WorkspaceWrite,
    Process,
    External,
}

#[derive(Debug, Error, Clone)]
pub enum ExtensionError {
    #[error("invalid extension input: {0}")]
    Invalid(String),
    #[error("extension permission denied: {0}")]
    Denied(String),
    #[error("extension operation failed: {0}")]
    Failed(String),
    #[error("extension operation canceled")]
    Canceled,
    #[error("extension operation timed out")]
    Timeout,
}

#[derive(Debug, Clone)]
pub struct ExtensionContext {
    pub execution_id: ExecutionId,
    pub deadline: Instant,
    pub cancellation: CancellationToken,
}

#[derive(Clone)]
pub struct ToolContext {
    pub extension: ExtensionContext,
    pub call_id: ToolCallId,
    pub workspace: Arc<dyn WorkspaceFacade>,
    pub interaction: Arc<dyn InteractionFacade>,
    pub subagent: Arc<dyn SubagentFacade>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ToolOutcome {
    pub content: String,
    pub failed: bool,
    pub completion: Option<String>,
    pub metadata: BTreeMap<String, Value>,
    pub context_invalidation: ContextInvalidation,
}

impl ToolOutcome {
    pub fn success(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            failed: false,
            completion: None,
            metadata: BTreeMap::new(),
            context_invalidation: ContextInvalidation::NONE,
        }
    }
    pub fn failure(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            failed: true,
            completion: None,
            metadata: BTreeMap::new(),
            context_invalidation: ContextInvalidation::NONE,
        }
    }

    pub fn complete(answer: impl Into<String>) -> Self {
        let answer = answer.into();
        Self {
            content: answer.clone(),
            failed: false,
            completion: Some(answer),
            metadata: BTreeMap::new(),
            context_invalidation: ContextInvalidation::NONE,
        }
    }

    pub fn with_context_invalidation(mut self, invalidation: ContextInvalidation) -> Self {
        self.context_invalidation = invalidation;
        self
    }
}

#[async_trait]
pub trait Tool: Send + Sync {
    fn descriptor(&self) -> ToolDescriptor;
    async fn invoke(
        &self,
        context: ToolContext,
        arguments: Value,
    ) -> Result<ToolOutcome, ExtensionError>;
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorkspaceEntry {
    pub path: String,
    pub is_dir: bool,
    pub size: Option<u64>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandOutcome {
    pub exit_code: i32,
    pub stdout: String,
    pub stderr: String,
    pub truncated: bool,
}

#[async_trait]
pub trait WorkspaceFacade: Send + Sync {
    async fn describe(&self) -> Result<String, ExtensionError>;
    async fn read_text(&self, path: &str) -> Result<String, ExtensionError>;
    async fn write_text(&self, path: &str, content: &str) -> Result<(), ExtensionError>;
    async fn list(&self, path: &str) -> Result<Vec<WorkspaceEntry>, ExtensionError>;
    async fn search(
        &self,
        path: &str,
        query: &str,
        limit: usize,
    ) -> Result<Vec<String>, ExtensionError>;
    async fn execute(
        &self,
        command: &str,
        cwd: Option<&str>,
    ) -> Result<CommandOutcome, ExtensionError>;
}

#[async_trait]
pub trait InteractionFacade: Send + Sync {
    async fn request_text(&self, prompt: &str) -> Result<String, ExtensionError>;
}

#[async_trait]
pub trait SubagentFacade: Send + Sync {
    async fn execute(&self, prompt: &str, max_model_turns: usize)
    -> Result<String, ExtensionError>;
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContextItem {
    pub source: String,
    pub content: String,
    pub priority: i32,
    pub required: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ContextSlot {
    System,
    Instructions,
    ToolCatalog,
    Skills,
    Memory,
    Plan,
    RuntimeState,
    History,
    Observations,
    Checkpoint,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContextSensitivity {
    Public,
    Internal,
    Sensitive,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ContextInvalidation(u16);

impl ContextInvalidation {
    pub const NONE: Self = Self(0);
    pub const SYSTEM: Self = Self(1 << 0);
    pub const TOOL_CATALOG: Self = Self(1 << 1);
    pub const SKILLS: Self = Self(1 << 2);
    pub const MEMORY: Self = Self(1 << 3);
    pub const PLAN: Self = Self(1 << 4);
    pub const RUNTIME_STATE: Self = Self(1 << 5);

    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    pub const fn contains(self, other: Self) -> bool {
        self.0 & other.0 == other.0
    }

    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }
}

impl std::ops::BitOr for ContextInvalidation {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self::Output {
        self.union(rhs)
    }
}

impl std::ops::BitOrAssign for ContextInvalidation {
    fn bitor_assign(&mut self, rhs: Self) {
        *self = self.union(rhs);
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContextResource {
    pub id: String,
    pub slot: ContextSlot,
    pub source: String,
    pub content: String,
    pub required: bool,
    pub sensitivity: ContextSensitivity,
    pub version: String,
    /// Stable content identity used by the Kernel to avoid treating an
    /// unchanged resource as a refresh.
    pub digest: String,
    /// Agent-side estimate for diagnostics. The Kernel always measures the
    /// final serialized request independently and remains authoritative.
    pub estimated_tokens: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContextResourceKey {
    pub slot: ContextSlot,
    pub id: String,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ContextPatch {
    pub resources: Vec<ContextResource>,
    pub removals: Vec<ContextResourceKey>,
    pub invalidations: ContextInvalidation,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ContextEvent {
    ExecutionStart,
    BeforeModel {
        turn: usize,
    },
    AfterTool {
        turn: usize,
        tool_name: String,
        failed: bool,
        invalidation: ContextInvalidation,
    },
    BeforeCompaction {
        turn: usize,
    },
    AfterCompaction {
        turn: usize,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContextFrame {
    pub execution_id: ExecutionId,
    pub turn: usize,
    pub user_prompt: String,
    pub visible_tools: Vec<String>,
    pub pending_invalidations: ContextInvalidation,
    pub resources: Vec<ContextResource>,
    pub budget: Option<ContextBudgetFrame>,
    pub latest_tool: Option<ContextToolFrame>,
    pub transcript_summary: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContextBudgetFrame {
    pub max_input_tokens: u64,
    pub message_tokens: u64,
    pub tool_schema_tokens: u64,
    pub protocol_overhead_tokens: u64,
    pub reserved_output_tokens: u64,
    pub total_tokens: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContextToolFrame {
    pub name: String,
    pub failed: bool,
}

#[async_trait]
pub trait ContextHook: Send + Sync {
    fn name(&self) -> &str;

    /// Stable authoring fingerprint for the Hook implementation/configuration.
    ///
    /// The Definition builder incorporates this value into its immutable
    /// digest. Change it whenever Hook behavior or embedded static resources
    /// change. Per-execution dynamic resource content still carries its own
    /// `ContextResource.digest` at runtime.
    fn definition_fingerprint(&self) -> String;

    async fn apply(
        &self,
        context: &ExtensionContext,
        event: &ContextEvent,
        frame: &ContextFrame,
    ) -> Result<ContextPatch, ExtensionError>;
}

#[derive(Debug, Clone)]
pub struct ToolInvocation {
    pub execution_id: ExecutionId,
    pub call_id: ToolCallId,
    pub descriptor: ToolDescriptor,
    pub arguments: Value,
}

#[async_trait]
pub trait Guard: Send + Sync {
    async fn authorize(&self, invocation: &ToolInvocation) -> Result<(), ExtensionError>;
}

#[derive(Debug, Clone)]
pub enum ObserverEvent {
    ExecutionStarted {
        execution_id: ExecutionId,
    },
    ModelCompleted {
        execution_id: ExecutionId,
        turn: usize,
    },
    ToolCompleted {
        execution_id: ExecutionId,
        call_id: ToolCallId,
        name: String,
        failed: bool,
    },
    ExecutionFinished {
        execution_id: ExecutionId,
        succeeded: bool,
    },
}

#[async_trait]
pub trait Observer: Send + Sync {
    async fn observe(&self, event: ObserverEvent) -> Result<(), ExtensionError>;
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DefinitionManifest {
    pub id: DefinitionId,
    pub version: String,
    pub runtime_type: String,
    pub schema_version: u32,
    pub digest: String,
}

pub struct AgentDefinition {
    pub manifest: DefinitionManifest,
    pub system_prompt: String,
    pub tools: Vec<Arc<dyn Tool>>,
    pub context_hooks: Vec<Arc<dyn ContextHook>>,
    pub guards: Vec<Arc<dyn Guard>>,
    pub observers: Vec<Arc<dyn Observer>>,
    pub completion_mode: CompletionMode,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CompletionMode {
    ModelOrTool,
    RequiredTool(String),
}

impl AgentDefinition {
    pub fn tool(&self, name: &str) -> Option<Arc<dyn Tool>> {
        self.tools
            .iter()
            .find(|tool| tool.descriptor().name == name)
            .cloned()
    }
}