1use std::collections::BTreeMap;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicU64, Ordering};
4
5use multicast::telemetry::opentelemetry::trace::FutureExt;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8
9use crate::{
10 CallAttempt, CallRecovery, CodeModeRuntime, Connector, ConnectorDescription, ReplayPolicy,
11 RuntimeError, ToolContext, ToolDecision, describe, search,
12};
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct DispatchResponse {
17 pub result: Option<Value>,
19 #[serde(rename = "__codemode_control__")]
21 pub control: Option<String>,
22 pub message: Option<String>,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct StepResponse {
29 pub kind: String,
31 pub seq: u64,
33 pub result: Option<Value>,
35}
36
37pub struct DispatchSession {
39 runtime: Arc<CodeModeRuntime>,
40 execution_id: String,
41 context: ToolContext,
42 connectors: BTreeMap<String, Arc<dyn Connector>>,
43 descriptions: BTreeMap<String, ConnectorDescription>,
44 described: tokio::sync::Mutex<BTreeMap<String, ConnectorDescription>>,
46 sequence: AtomicU64,
47}
48
49impl DispatchSession {
50 pub(crate) async fn checkpoint(&self) -> Result<Option<crate::ExecutionCheckpoint>, String> {
51 self.runtime
52 .checkpoint(&self.execution_id)
53 .await
54 .map_err(|e| e.to_string())
55 }
56
57 pub(crate) async fn save_checkpoint(
58 &self,
59 checkpoint: &crate::ExecutionCheckpoint,
60 ) -> Result<(), String> {
61 self.runtime
62 .save_checkpoint(&self.execution_id, checkpoint)
63 .await
64 .map_err(|e| e.to_string())
65 }
66 pub async fn new(
68 runtime: Arc<CodeModeRuntime>,
69 execution_id: impl Into<String>,
70 connectors: Vec<Arc<dyn Connector>>,
71 ) -> Result<Self, String> {
72 let execution_id = execution_id.into();
73 let mut descriptions = Vec::new();
74 for connector in &connectors {
75 descriptions.push(connector.describe().await?);
76 }
77 Self::new_with_descriptions(runtime, execution_id, connectors, descriptions).await
78 }
79
80 pub async fn new_with_descriptions(
82 runtime: Arc<CodeModeRuntime>,
83 execution_id: impl Into<String>,
84 connectors: Vec<Arc<dyn Connector>>,
85 snapshot: Vec<ConnectorDescription>,
86 ) -> Result<Self, String> {
87 let execution_id = execution_id.into();
88 Self::new_with_descriptions_and_context(
89 runtime,
90 ToolContext {
91 call: None,
92 execution_id,
93 control: Default::default(),
94 request: None,
95 telemetry_context: multicast::telemetry::opentelemetry::Context::current(),
96 },
97 connectors,
98 snapshot,
99 )
100 .await
101 }
102
103 pub async fn new_with_descriptions_and_context(
105 runtime: Arc<CodeModeRuntime>,
106 context: ToolContext,
107 connectors: Vec<Arc<dyn Connector>>,
108 snapshot: Vec<ConnectorDescription>,
109 ) -> Result<Self, String> {
110 let mut resolved = BTreeMap::new();
114 for connector in connectors {
115 let name = connector.name().to_string();
116 if resolved.insert(name.clone(), connector).is_some() {
117 return Err(format!("Duplicate connector name \"{name}\""));
118 }
119 }
120 let descriptions = snapshot
121 .into_iter()
122 .map(|description| (description.name.clone(), description))
123 .collect();
124 Ok(Self {
125 runtime,
126 execution_id: context.execution_id.clone(),
127 context,
128 connectors: resolved,
129 descriptions,
130 described: tokio::sync::Mutex::new(BTreeMap::new()),
131 sequence: AtomicU64::new(0),
132 })
133 }
134
135 pub fn descriptions(&self) -> Vec<ConnectorDescription> {
137 self.descriptions.values().cloned().collect()
138 }
139
140 async fn describe_once(&self, name: &str) -> Result<ConnectorDescription, String> {
147 {
152 let cache = self.described.lock().await;
153 if let Some(description) = cache.get(name) {
154 return Ok(description.clone());
155 }
156 }
157 let connector = self
158 .connectors
159 .get(name)
160 .ok_or_else(|| capability_unavailable(name, ""))?;
161 let description = connector.describe().await?;
162 self.described
163 .lock()
164 .await
165 .insert(name.to_string(), description.clone());
166 Ok(description)
167 }
168
169 async fn described_all(&self) -> Result<Vec<ConnectorDescription>, String> {
175 let names: Vec<String> = self.connectors.keys().cloned().collect();
176 let mut descriptions = Vec::with_capacity(names.len());
177 for name in names {
178 descriptions.push(self.describe_once(&name).await?);
179 }
180 Ok(descriptions)
181 }
182
183 pub async fn call(
185 &self,
186 connector: &str,
187 method: &str,
188 arguments: Value,
189 now: u64,
190 ) -> DispatchResponse {
191 let seq = self.sequence.fetch_add(1, Ordering::Relaxed);
192 self.call_at(seq, connector, method, arguments, now).await
193 }
194
195 pub async fn call_at(
197 &self,
198 seq: u64,
199 connector: &str,
200 method: &str,
201 arguments: Value,
202 now: u64,
203 ) -> DispatchResponse {
204 async {
205 let mut observation =
206 crate::telemetry::Observation::call(&self.execution_id, seq, connector, method);
207 let result = self
208 .call_inner(seq, connector, method, arguments, now)
209 .with_context(observation.context())
210 .await;
211 observation.finish(match &result {
212 _ if self.context.control.cancellation.is_cancelled() => "cancelled",
213 Err(_) => "error",
214 Ok(response) if response.control.as_deref() == Some("pause") => "paused",
215 _ => "completed",
216 });
217 match result {
218 Ok(response) => response,
219 Err(error) => DispatchResponse {
220 result: None,
221 control: Some("error".to_string()),
222 message: Some(error),
223 },
224 }
225 }
226 .with_context(self.context.telemetry_context.clone())
227 .await
228 }
229
230 pub async fn begin_step(&self, name: &str, now: u64) -> Result<StepResponse, RuntimeError> {
232 let seq = self.sequence.fetch_add(1, Ordering::Relaxed);
233 self.begin_step_at(seq, name, now).await
234 }
235
236 pub async fn begin_step_at(
238 &self,
239 seq: u64,
240 name: &str,
241 now: u64,
242 ) -> Result<StepResponse, RuntimeError> {
243 Ok(
244 match self
245 .runtime
246 .decide(
247 &self.execution_id,
248 seq,
249 "__step",
250 name,
251 Value::Null,
252 false,
253 false,
254 now,
255 )
256 .await?
257 {
258 ToolDecision::Replay(result) => StepResponse {
259 kind: "replay".to_string(),
260 seq,
261 result: Some(result),
262 },
263 ToolDecision::Execute(seq) | ToolDecision::Recover(seq) => StepResponse {
264 kind: "execute".to_string(),
265 seq,
266 result: None,
267 },
268 ToolDecision::Pause(seq) => StepResponse {
269 kind: "pause".to_string(),
270 seq,
271 result: None,
272 },
273 },
274 )
275 }
276
277 pub async fn record_step(&self, seq: u64, result: Value, now: u64) -> Result<(), RuntimeError> {
279 self.runtime
280 .record_result(&self.execution_id, seq, result, now)
281 .await
282 }
283
284 pub async fn pass_ended(&self, status: &str) {
286 for connector in self.connectors.values() {
287 connector.pass_ended(&self.execution_id, status).await;
288 }
289 }
290
291 pub async fn execution_ended(&self, status: &str) {
293 for connector in self.connectors.values() {
294 connector.execution_ended(&self.execution_id, status).await;
295 }
296 }
297
298 async fn call_inner(
299 &self,
300 seq: u64,
301 connector_name: &str,
302 method: &str,
303 arguments: Value,
304 now: u64,
305 ) -> Result<DispatchResponse, String> {
306 if connector_name == "codemode" {
307 return self.call_builtin(seq, method, arguments, now).await;
308 }
309 let connector = self
310 .connectors
311 .get(connector_name)
312 .ok_or_else(|| capability_unavailable(connector_name, method))?;
313 let description = self.describe_once(connector_name).await?;
314 let tool = description
315 .tools
316 .iter()
317 .find(|tool| tool.name == method)
318 .ok_or_else(|| format!("Tool \"{method}\" not found on {connector_name}"))?;
319 let arguments = connector
320 .prepare_arguments(seq, tool, arguments, &self.context)
321 .await?;
322 match self
323 .runtime
324 .decide(
325 &self.execution_id,
326 seq,
327 connector_name,
328 method,
329 arguments.clone(),
330 tool.policy.requires_approval,
331 tool.policy.replay == ReplayPolicy::Reexecute,
332 now,
333 )
334 .await
335 .map_err(|error| error.to_string())?
336 {
337 ToolDecision::Replay(result) => Ok(DispatchResponse {
338 result: Some(result),
339 control: None,
340 message: None,
341 }),
342 ToolDecision::Pause(_) => Ok(DispatchResponse {
343 result: None,
344 control: Some("pause".to_string()),
345 message: None,
346 }),
347 decision @ (ToolDecision::Execute(_) | ToolDecision::Recover(_)) => {
348 self.invoke_connector(
349 connector.as_ref(),
350 seq,
351 method,
352 arguments,
353 now,
354 matches!(decision, ToolDecision::Recover(_)),
355 )
356 .await
357 }
358 }
359 }
360
361 #[allow(clippy::too_many_arguments)]
362 async fn invoke_connector(
363 &self,
364 connector: &dyn Connector,
365 seq: u64,
366 method: &str,
367 arguments: Value,
368 now: u64,
369 mut recovering: bool,
370 ) -> Result<DispatchResponse, String> {
371 let state = self
372 .runtime
373 .execution(&self.execution_id)
374 .await
375 .map_err(|error| error.to_string())?
376 .ok_or("Execution missing")?;
377 let previous = state
378 .log
379 .iter()
380 .find(|entry| entry.seq == seq)
381 .ok_or("Call missing")?;
382 let mut context = self.context.clone();
383 context.call = Some(CallAttempt {
384 sequence: seq,
385 idempotency_key: format!("multicast:{}:{seq}", self.execution_id),
386 attempt: previous.attempts,
387 });
388 let limit = connector
389 .retry_policy(method)
390 .max_attempts
391 .clamp(1, crate::MAX_CALL_ATTEMPTS);
392 let result = loop {
393 if context.control.cancellation.is_cancelled() {
394 return Err("Connector call cancelled".into());
395 }
396 if recovering {
397 let recovery = connector.recover(method, &arguments, &context).await?;
398 if context.control.cancellation.is_cancelled() {
399 return Err("Connector call cancelled".into());
400 }
401 match recovery {
402 CallRecovery::Applied(result) => break result,
403 CallRecovery::Retry => {}
404 CallRecovery::Uncertain => {
405 let reason = serde_json::json!({
406 "code": "CALL_OUTCOME_UNCERTAIN", "retryable": false,
407 "message": "Reconcile the interrupted call before resuming execution",
408 "sequence": seq,
409 "idempotencyKey": context.call.as_ref().map(|call| &call.idempotency_key),
410 }).to_string();
411 self.runtime
412 .suspend_call(&self.execution_id, reason.clone(), now)
413 .await
414 .map_err(|error| error.to_string())?;
415 return Ok(DispatchResponse {
416 result: None,
417 control: Some("pause".into()),
418 message: Some(reason),
419 });
420 }
421 }
422 }
423 let attempt = self
424 .runtime
425 .charge_attempt(&self.execution_id, seq, limit, now)
426 .await
427 .map_err(|error| error.to_string())?;
428 context
429 .call
430 .as_mut()
431 .expect("call identity installed")
432 .attempt = attempt;
433 self.runtime
434 .workflow_charge(&self.execution_id, now)
435 .await?;
436 match connector.execute(method, arguments.clone(), &context).await {
437 Ok(result) => break result,
438 Err(error) if suspends(&error) => {
439 self.runtime
440 .defer_call(&self.execution_id, seq, error.clone(), now)
441 .await
442 .map_err(|error| error.to_string())?;
443 return Ok(DispatchResponse {
444 result: None,
445 control: Some("pause".into()),
446 message: Some(error),
447 });
448 }
449 Err(error) if limit > 1 && retryable(&error) => recovering = true,
450 Err(error) => return Err(error),
451 }
452 };
453 self.runtime
454 .record_result(&self.execution_id, seq, result.clone(), now)
455 .await
456 .map_err(|error| error.to_string())?;
457 Ok(DispatchResponse {
458 result: Some(result),
459 control: None,
460 message: None,
461 })
462 }
463
464 async fn call_builtin(
465 &self,
466 seq: u64,
467 method: &str,
468 arguments: Value,
469 now: u64,
470 ) -> Result<DispatchResponse, String> {
471 if let Some(operation) = method.strip_prefix("workflows.") {
472 let decision = self
473 .runtime
474 .decide(
475 &self.execution_id,
476 seq,
477 "codemode",
478 method,
479 arguments.clone(),
480 false,
481 false,
482 now,
483 )
484 .await
485 .map_err(|e| e.to_string())?;
486 return match decision {
487 ToolDecision::Replay(value) => Ok(DispatchResponse {
488 result: Some(value),
489 control: None,
490 message: None,
491 }),
492 ToolDecision::Pause(_) => Ok(DispatchResponse {
493 result: None,
494 control: Some("pause".into()),
495 message: None,
496 }),
497 ToolDecision::Execute(_) | ToolDecision::Recover(_) => {
498 let response = match self
499 .runtime
500 .workflow_call(&self.execution_id, seq, operation, arguments, now)
501 .await
502 {
503 Ok(response) => response,
504 Err(error) => DispatchResponse {
505 result: Some(serde_json::json!({"__workflow_error":error})),
506 control: None,
507 message: None,
508 },
509 };
510 if response.control.is_none() {
511 self.runtime
512 .record_result(
513 &self.execution_id,
514 seq,
515 response.result.clone().unwrap_or(Value::Null),
516 now,
517 )
518 .await
519 .map_err(|e| e.to_string())?;
520 }
521 Ok(response)
522 }
523 };
524 }
525 match self
526 .runtime
527 .decide(
528 &self.execution_id,
529 seq,
530 "codemode",
531 method,
532 arguments.clone(),
533 false,
534 true,
535 now,
536 )
537 .await
538 .map_err(|error| error.to_string())?
539 {
540 ToolDecision::Pause(_) => Ok(DispatchResponse {
541 result: None,
542 control: Some("pause".to_string()),
543 message: None,
544 }),
545 ToolDecision::Replay(result) => Ok(DispatchResponse {
546 result: Some(result),
547 control: None,
548 message: None,
549 }),
550 ToolDecision::Execute(seq) | ToolDecision::Recover(seq) => {
551 let connectors = self.described_all().await?;
552 let snippets = self
553 .runtime
554 .snippets()
555 .await
556 .map_err(|error| error.to_string())?;
557 let value = match method {
558 "search" => serde_json::to_value(search(
559 arguments
560 .get("query")
561 .and_then(Value::as_str)
562 .unwrap_or_default(),
563 &connectors,
564 &snippets,
565 )),
566 "describe" => serde_json::to_value(describe(
567 arguments
568 .get("target")
569 .and_then(Value::as_str)
570 .unwrap_or_default(),
571 &connectors,
572 &snippets,
573 )),
574 _ => return Err(format!("Tool \"{method}\" not found on codemode")),
575 }
576 .map_err(|error| error.to_string())?;
577 self.runtime
578 .record_result(&self.execution_id, seq, value.clone(), now)
579 .await
580 .map_err(|error| error.to_string())?;
581 Ok(DispatchResponse {
582 result: Some(value),
583 control: None,
584 message: None,
585 })
586 }
587 }
588 }
589}
590
591fn capability_unavailable(connector: &str, method: &str) -> String {
592 serde_json::json!({
593 "code": "CAPABILITY_UNAVAILABLE",
594 "message": format!(
595 "Capability {connector}.{method} existed when the execution began but is unavailable"
596 ),
597 "connector": connector,
598 "method": method,
599 })
600 .to_string()
601}
602
603fn suspends(error: &str) -> bool {
606 serde_json::from_str::<Value>(error)
607 .ok()
608 .and_then(|value| value.get("suspend").and_then(Value::as_bool))
609 == Some(true)
610}
611
612fn retryable(error: &str) -> bool {
613 serde_json::from_str::<Value>(error)
614 .ok()
615 .and_then(|value| value.get("retryable").and_then(Value::as_bool))
616 == Some(true)
617}