orchestral-runtime 0.4.1

A runtime for reliable, interactive 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
//! Runtime registry for provider-neutral Agent session connectors.
//!
//! The directory owns discovery routing. Each registration also owns a normal
//! [`AgentController`](crate::AgentController), so active external turns use
//! the same durable Agent Protocol path as the built-in Generic Agent.

use std::collections::BTreeMap;
use std::sync::Arc;

use orchestral_core::agent_connector::{
    AgentConnector, AgentConnectorDescriptor, AgentConnectorError, AgentConnectorHealth,
    AgentConnectorId, AgentSessionActionExecution, AgentSessionActionInvocation,
    AgentSessionActionOutcome, AgentSessionActionStatus, AgentSessionChange, AgentSessionDetail,
    AgentSessionListQuery, AgentSessionPage, AgentSessionReadQuery, AgentSessionSummary,
    CreateAgentSessionRequest, InvokeAgentSessionActionRequest, ResolveAgentSessionRequest,
};
use orchestral_core::agent_protocol::spi::{
    AgentJournalStore, AgentProvider, InMemoryAgentJournalStore,
};
use orchestral_core::agent_protocol::wire::{AgentSessionId, Extensions, RunId};
use thiserror::Error;
use tokio::sync::broadcast;
use tokio::sync::RwLock;

use crate::api::AgentApi;
use crate::{AgentController, AgentRunHandle, AgentSdkError};

struct AgentDirectoryEntry {
    descriptor: AgentConnectorDescriptor,
    connector: Arc<dyn AgentConnector>,
    api: AgentApi,
}

/// Process-level registry for installed Agent connectors.
///
/// Connector IDs namespace session IDs. Two different Agents may therefore
/// expose the same opaque session ID without colliding.
#[derive(Default)]
pub struct AgentDirectory {
    entries: RwLock<BTreeMap<AgentConnectorId, Arc<AgentDirectoryEntry>>>,
}

impl AgentDirectory {
    pub fn new() -> Self {
        Self::default()
    }

    pub async fn register(
        &self,
        connector: Arc<dyn AgentConnector>,
        provider: Arc<dyn AgentProvider>,
    ) -> Result<(), AgentDirectoryError> {
        self.register_with_journal(
            connector,
            provider,
            Arc::new(InMemoryAgentJournalStore::default()),
        )
        .await
    }

    pub async fn register_with_journal(
        &self,
        connector: Arc<dyn AgentConnector>,
        provider: Arc<dyn AgentProvider>,
        journal: Arc<dyn AgentJournalStore>,
    ) -> Result<(), AgentDirectoryError> {
        let descriptor = connector.describe();
        descriptor.validate()?;
        let connector_id = descriptor.connector_id.clone();
        let controller = Arc::new(AgentController::with_journal_store(
            provider,
            descriptor.provider_binding.clone(),
            journal,
        )?);
        let entry = Arc::new(AgentDirectoryEntry {
            descriptor,
            connector,
            api: AgentApi::new(controller),
        });

        let mut entries = self.entries.write().await;
        if entries.contains_key(&connector_id) {
            return Err(AgentDirectoryError::RegistrationConflict(connector_id));
        }
        entries.insert(connector_id, entry);
        Ok(())
    }

    pub async fn connectors(&self) -> Vec<AgentConnectorDescriptor> {
        self.entries
            .read()
            .await
            .values()
            .map(|entry| entry.descriptor.clone())
            .collect()
    }

    pub async fn health(
        &self,
        connector_id: &AgentConnectorId,
    ) -> Result<AgentConnectorHealth, AgentDirectoryError> {
        let entry = self.entry(connector_id).await?;
        self.verify_descriptor(&entry)?;
        Ok(entry.connector.health().await?)
    }

    pub async fn list_sessions(
        &self,
        connector_id: &AgentConnectorId,
        query: AgentSessionListQuery,
    ) -> Result<AgentSessionPage, AgentDirectoryError> {
        query.validate()?;
        let entry = self.entry(connector_id).await?;
        self.verify_descriptor(&entry)?;
        let requested_limit = query.limit;
        let page = entry.connector.list_sessions(query).await?;
        page.validate_for(connector_id, requested_limit)?;
        Ok(page)
    }

    pub async fn read_session(
        &self,
        connector_id: &AgentConnectorId,
        session_id: &AgentSessionId,
    ) -> Result<AgentSessionDetail, AgentDirectoryError> {
        if session_id.is_empty() {
            return Err(AgentConnectorError::invalid("session id must not be empty").into());
        }
        let entry = self.entry(connector_id).await?;
        self.verify_descriptor(&entry)?;
        let detail = entry.connector.read_session(session_id).await?;
        detail.validate_for(connector_id)?;
        if detail.summary.session_id != *session_id {
            return Err(AgentConnectorError::protocol(
                "connector returned a different session than requested",
            )
            .into());
        }
        Ok(detail)
    }

    pub async fn read_session_page(
        &self,
        connector_id: &AgentConnectorId,
        session_id: &AgentSessionId,
        query: AgentSessionReadQuery,
    ) -> Result<AgentSessionDetail, AgentDirectoryError> {
        if session_id.is_empty() {
            return Err(AgentConnectorError::invalid("session id must not be empty").into());
        }
        query.validate()?;
        let entry = self.entry(connector_id).await?;
        self.verify_descriptor(&entry)?;
        let detail = entry.connector.read_session_page(session_id, query).await?;
        detail.validate_for(connector_id)?;
        if detail.summary.session_id != *session_id {
            return Err(AgentConnectorError::protocol(
                "connector returned a different session than requested",
            )
            .into());
        }
        Ok(detail)
    }

    pub async fn subscribe_session_changes(
        &self,
        connector_id: &AgentConnectorId,
        session_id: &AgentSessionId,
    ) -> Result<broadcast::Receiver<AgentSessionChange>, AgentDirectoryError> {
        if session_id.is_empty() {
            return Err(AgentConnectorError::invalid("session id must not be empty").into());
        }
        let entry = self.entry(connector_id).await?;
        self.verify_descriptor(&entry)?;
        Ok(entry
            .connector
            .subscribe_session_changes(session_id)
            .await?)
    }

    pub async fn resolve_request(
        &self,
        connector_id: &AgentConnectorId,
        request: ResolveAgentSessionRequest,
    ) -> Result<(), AgentDirectoryError> {
        if request.session_id.is_empty() || request.request_id.is_empty() {
            return Err(AgentConnectorError::invalid(
                "session request resolution requires session and request identities",
            )
            .into());
        }
        request.response.validate()?;
        let entry = self.entry(connector_id).await?;
        self.verify_descriptor(&entry)?;
        if !entry.descriptor.capabilities.resolve_requests {
            return Err(AgentConnectorError::unsupported(
                "connector does not declare provider-native request resolution",
            )
            .into());
        }
        entry.connector.resolve_request(request).await?;
        Ok(())
    }

    pub async fn create_session(
        &self,
        connector_id: &AgentConnectorId,
        request: CreateAgentSessionRequest,
    ) -> Result<AgentSessionSummary, AgentDirectoryError> {
        let entry = self.entry(connector_id).await?;
        self.verify_descriptor(&entry)?;
        if !entry.descriptor.capabilities.create {
            return Err(AgentConnectorError::unsupported(
                "connector does not declare session creation",
            )
            .into());
        }
        let summary = entry.connector.create_session(request).await?;
        summary.validate_for(connector_id)?;
        entry
            .api
            .create_session(Some(summary.session_id.clone()))
            .await?;
        Ok(summary)
    }

    pub async fn invoke_action(
        &self,
        connector_id: &AgentConnectorId,
        request: InvokeAgentSessionActionRequest,
    ) -> Result<AgentSessionActionOutcome, AgentDirectoryError> {
        if request.session_id.is_empty() || request.action_id.is_empty() {
            return Err(AgentConnectorError::invalid(
                "session action requires session and action identities",
            )
            .into());
        }
        let entry = self.entry(connector_id).await?;
        self.verify_descriptor(&entry)?;
        let action = entry.descriptor.action(&request.action_id).ok_or_else(|| {
            AgentConnectorError::unsupported(format!(
                "connector does not declare action {}",
                request.action_id
            ))
        })?;
        if action.input_schema.is_none() && !request.arguments.is_null() {
            return Err(AgentConnectorError::invalid(format!(
                "action {} takes no arguments",
                request.action_id
            ))
            .into());
        }
        if action.execution == AgentSessionActionExecution::Run {
            // Resolve the session before starting so a forged connector/session
            // pair cannot allocate a Host-only Run.
            self.read_session_page(
                connector_id,
                &request.session_id,
                AgentSessionReadQuery {
                    cursor: None,
                    limit: 1,
                },
            )
            .await?;
            entry
                .api
                .create_session(Some(request.session_id.clone()))
                .await?;
            let run_id = request
                .run_id
                .unwrap_or_else(|| RunId::new(format!("session-action-{}", uuid::Uuid::new_v4())));
            entry
                .api
                .start_session_action(
                    &request.session_id,
                    run_id.clone(),
                    action.title.clone(),
                    AgentSessionActionInvocation {
                        action_id: request.action_id,
                        arguments: request.arguments,
                    },
                )
                .await?;
            return Ok(AgentSessionActionOutcome {
                status: AgentSessionActionStatus::Running { run_id },
                session: None,
                content: Vec::new(),
                details: serde_json::Value::Null,
            });
        }
        if request.run_id.is_some() {
            return Err(AgentConnectorError::invalid(
                "run_id is only valid for Run session actions",
            )
            .into());
        }
        let outcome = entry.connector.invoke_action(request).await?;
        if !matches!(outcome.status, AgentSessionActionStatus::Completed) {
            return Err(AgentConnectorError::protocol(
                "an immediate session action returned a running outcome",
            )
            .into());
        }
        if let Some(summary) = &outcome.session {
            summary.validate_for(connector_id)?;
        }
        for content in &outcome.content {
            content
                .validate_integrity()
                .map_err(|error| AgentConnectorError::protocol(error.to_string()))?;
        }
        Ok(outcome)
    }

    /// Start one Agent Protocol Run against a connector-owned session.
    pub async fn start_text(
        &self,
        connector_id: &AgentConnectorId,
        session_id: &AgentSessionId,
        run_id: Option<RunId>,
        input: impl Into<String>,
    ) -> Result<AgentRunHandle, AgentDirectoryError> {
        // Read first so a stale or forged connector/session pair cannot create
        // a Host-only session that the external Provider cannot resolve.
        self.read_session_page(
            connector_id,
            session_id,
            AgentSessionReadQuery {
                cursor: None,
                limit: 1,
            },
        )
        .await?;
        let entry = self.entry(connector_id).await?;
        entry.api.create_session(Some(session_id.clone())).await?;
        Ok(entry.api.start_text(session_id, run_id, input).await?)
    }

    /// Start one Agent Protocol Run with provider-neutral Content blocks.
    pub async fn start_content(
        &self,
        connector_id: &AgentConnectorId,
        session_id: &AgentSessionId,
        run_id: Option<RunId>,
        input: Vec<orchestral_core::agent_protocol::wire::Content>,
    ) -> Result<AgentRunHandle, AgentDirectoryError> {
        self.start_content_with_extensions(
            connector_id,
            session_id,
            run_id,
            input,
            Extensions::new(),
        )
        .await
    }

    /// Starts a Run with digest-bound, namespaced Host metadata. The directory
    /// keeps this provider-neutral and forwards the immutable extensions
    /// through the shared Agent Protocol controller.
    pub async fn start_content_with_extensions(
        &self,
        connector_id: &AgentConnectorId,
        session_id: &AgentSessionId,
        run_id: Option<RunId>,
        input: Vec<orchestral_core::agent_protocol::wire::Content>,
        extensions: Extensions,
    ) -> Result<AgentRunHandle, AgentDirectoryError> {
        self.read_session_page(
            connector_id,
            session_id,
            AgentSessionReadQuery {
                cursor: None,
                limit: 1,
            },
        )
        .await?;
        let entry = self.entry(connector_id).await?;
        entry.api.create_session(Some(session_id.clone())).await?;
        Ok(entry
            .api
            .start_content_with_extensions(session_id, run_id, input, extensions)
            .await?)
    }

    pub async fn agent_api(
        &self,
        connector_id: &AgentConnectorId,
    ) -> Result<AgentApi, AgentDirectoryError> {
        Ok(self.entry(connector_id).await?.api.clone())
    }

    async fn entry(
        &self,
        connector_id: &AgentConnectorId,
    ) -> Result<Arc<AgentDirectoryEntry>, AgentDirectoryError> {
        self.entries
            .read()
            .await
            .get(connector_id)
            .cloned()
            .ok_or_else(|| AgentDirectoryError::ConnectorNotFound(connector_id.clone()))
    }

    fn verify_descriptor(&self, entry: &AgentDirectoryEntry) -> Result<(), AgentDirectoryError> {
        let observed = entry.connector.describe();
        observed.validate()?;
        if observed != entry.descriptor {
            return Err(AgentDirectoryError::DescriptorChanged(
                entry.descriptor.connector_id.clone(),
            ));
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum AgentDirectoryError {
    #[error("Agent connector is not registered: {0}")]
    ConnectorNotFound(AgentConnectorId),
    #[error("Agent connector is already registered: {0}")]
    RegistrationConflict(AgentConnectorId),
    #[error("Agent connector descriptor changed after registration: {0}")]
    DescriptorChanged(AgentConnectorId),
    #[error(transparent)]
    Connector(#[from] AgentConnectorError),
    #[error(transparent)]
    Protocol(#[from] orchestral_core::agent_protocol::wire::AgentProtocolError),
    #[error(transparent)]
    Agent(#[from] AgentSdkError),
}