multicast-codemode 1.0.0

Portable durable Code Mode runtime for multicast tools
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use multicast::telemetry::opentelemetry::trace::FutureExt;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{
    CallAttempt, CallRecovery, CodeModeRuntime, Connector, ConnectorDescription, ReplayPolicy,
    RuntimeError, ToolContext, ToolDecision, describe, search,
};

/// Wire-safe result of one connector dispatch.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DispatchResponse {
    /// Successful connector or replay result.
    pub result: Option<Value>,
    /// Control signal consumed by the sandbox proxy.
    #[serde(rename = "__codemode_control__")]
    pub control: Option<String>,
    /// Host-side connector or runtime error.
    pub message: Option<String>,
}

/// Wire-safe decision for a local `codemode.step` callback.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StepResponse {
    /// Replay, execute, or pause.
    pub kind: String,
    /// Host-assigned sequence.
    pub seq: u64,
    /// Previously recorded step result.
    pub result: Option<Value>,
}

/// One replay pass's sequenced bridge between a sandbox and Rust connectors.
pub struct DispatchSession {
    runtime: Arc<CodeModeRuntime>,
    execution_id: String,
    context: ToolContext,
    connectors: BTreeMap<String, Arc<dyn Connector>>,
    descriptions: BTreeMap<String, ConnectorDescription>,
    /// Descriptions resolved so far, filled in as namespaces are first used.
    described: tokio::sync::Mutex<BTreeMap<String, ConnectorDescription>>,
    sequence: AtomicU64,
}

impl DispatchSession {
    pub(crate) async fn checkpoint(&self) -> Result<Option<crate::ExecutionCheckpoint>, String> {
        self.runtime
            .checkpoint(&self.execution_id)
            .await
            .map_err(|e| e.to_string())
    }

    pub(crate) async fn save_checkpoint(
        &self,
        checkpoint: &crate::ExecutionCheckpoint,
    ) -> Result<(), String> {
        self.runtime
            .save_checkpoint(&self.execution_id, checkpoint)
            .await
            .map_err(|e| e.to_string())
    }
    /// Resolves connector descriptions and creates a fresh replay cursor.
    pub async fn new(
        runtime: Arc<CodeModeRuntime>,
        execution_id: impl Into<String>,
        connectors: Vec<Arc<dyn Connector>>,
    ) -> Result<Self, String> {
        let execution_id = execution_id.into();
        let mut descriptions = Vec::new();
        for connector in &connectors {
            descriptions.push(connector.describe().await?);
        }
        Self::new_with_descriptions(runtime, execution_id, connectors, descriptions).await
    }

    /// Creates a replay cursor using a previously captured capability snapshot.
    pub async fn new_with_descriptions(
        runtime: Arc<CodeModeRuntime>,
        execution_id: impl Into<String>,
        connectors: Vec<Arc<dyn Connector>>,
        snapshot: Vec<ConnectorDescription>,
    ) -> Result<Self, String> {
        let execution_id = execution_id.into();
        Self::new_with_descriptions_and_context(
            runtime,
            ToolContext {
                call: None,
                execution_id,
                control: Default::default(),
                request: None,
                telemetry_context: multicast::telemetry::opentelemetry::Context::current(),
            },
            connectors,
            snapshot,
        )
        .await
    }

    /// Creates a replay cursor with an execution-scoped connector context.
    pub async fn new_with_descriptions_and_context(
        runtime: Arc<CodeModeRuntime>,
        context: ToolContext,
        connectors: Vec<Arc<dyn Connector>>,
        snapshot: Vec<ConnectorDescription>,
    ) -> Result<Self, String> {
        // Namespaces are registered by name alone. Describing every connector here
        // meant contacting every configured server before any program ran, so one
        // slow or dead server delayed or failed executions that never mentioned it.
        let mut resolved = BTreeMap::new();
        for connector in connectors {
            let name = connector.name().to_string();
            if resolved.insert(name.clone(), connector).is_some() {
                return Err(format!("Duplicate connector name \"{name}\""));
            }
        }
        let descriptions = snapshot
            .into_iter()
            .map(|description| (description.name.clone(), description))
            .collect();
        Ok(Self {
            runtime,
            execution_id: context.execution_id.clone(),
            context,
            connectors: resolved,
            descriptions,
            described: tokio::sync::Mutex::new(BTreeMap::new()),
            sequence: AtomicU64::new(0),
        })
    }

    /// Returns descriptions used to generate the child Worker bindings.
    pub fn descriptions(&self) -> Vec<ConnectorDescription> {
        self.descriptions.values().cloned().collect()
    }

    /// Returns one connector's description, contacting it at most once per pass.
    ///
    /// This is the whole of the laziness. A namespace the program never calls is
    /// never described, so a server that is slow, unreachable or removed costs
    /// nothing until something actually uses it, and cannot fail an execution that
    /// does not touch it.
    async fn describe_once(&self, name: &str) -> Result<ConnectorDescription, String> {
        // The cache lock is scoped so it is never held across `describe`. A
        // connector may reach back into this session -- a nested apoc invocation
        // does exactly that -- and holding the lock across that await would
        // deadlock the outer program against its own child.
        {
            let cache = self.described.lock().await;
            if let Some(description) = cache.get(name) {
                return Ok(description.clone());
            }
        }
        let connector = self
            .connectors
            .get(name)
            .ok_or_else(|| capability_unavailable(name, ""))?;
        let description = connector.describe().await?;
        self.described
            .lock()
            .await
            .insert(name.to_string(), description.clone());
        Ok(description)
    }

    /// Describes every connector, for the callers that genuinely need all of them.
    ///
    /// Only the in-sandbox `codemode.search` and `codemode.describe` use this: a
    /// program asking what exists is asking to enumerate, so it pays for the
    /// enumeration. Nothing on the ordinary dispatch path calls it.
    async fn described_all(&self) -> Result<Vec<ConnectorDescription>, String> {
        let names: Vec<String> = self.connectors.keys().cloned().collect();
        let mut descriptions = Vec::with_capacity(names.len());
        for name in names {
            descriptions.push(self.describe_once(&name).await?);
        }
        Ok(descriptions)
    }

    /// Executes or replays one connector call under the runtime policy.
    pub async fn call(
        &self,
        connector: &str,
        method: &str,
        arguments: Value,
        now: u64,
    ) -> DispatchResponse {
        let seq = self.sequence.fetch_add(1, Ordering::Relaxed);
        self.call_at(seq, connector, method, arguments, now).await
    }

    /// Executes or replays one connector call at an explicit sandbox sequence.
    pub async fn call_at(
        &self,
        seq: u64,
        connector: &str,
        method: &str,
        arguments: Value,
        now: u64,
    ) -> DispatchResponse {
        async {
            let mut observation =
                crate::telemetry::Observation::call(&self.execution_id, seq, connector, method);
            let result = self
                .call_inner(seq, connector, method, arguments, now)
                .with_context(observation.context())
                .await;
            observation.finish(match &result {
                _ if self.context.control.cancellation.is_cancelled() => "cancelled",
                Err(_) => "error",
                Ok(response) if response.control.as_deref() == Some("pause") => "paused",
                _ => "completed",
            });
            match result {
                Ok(response) => response,
                Err(error) => DispatchResponse {
                    result: None,
                    control: Some("error".to_string()),
                    message: Some(error),
                },
            }
        }
        .with_context(self.context.telemetry_context.clone())
        .await
    }

    /// Begins a deterministic local step.
    pub async fn begin_step(&self, name: &str, now: u64) -> Result<StepResponse, RuntimeError> {
        let seq = self.sequence.fetch_add(1, Ordering::Relaxed);
        self.begin_step_at(seq, name, now).await
    }

    /// Begins a deterministic local step at an explicit sandbox sequence.
    pub async fn begin_step_at(
        &self,
        seq: u64,
        name: &str,
        now: u64,
    ) -> Result<StepResponse, RuntimeError> {
        Ok(
            match self
                .runtime
                .decide(
                    &self.execution_id,
                    seq,
                    "__step",
                    name,
                    Value::Null,
                    false,
                    false,
                    now,
                )
                .await?
            {
                ToolDecision::Replay(result) => StepResponse {
                    kind: "replay".to_string(),
                    seq,
                    result: Some(result),
                },
                ToolDecision::Execute(seq) | ToolDecision::Recover(seq) => StepResponse {
                    kind: "execute".to_string(),
                    seq,
                    result: None,
                },
                ToolDecision::Pause(seq) => StepResponse {
                    kind: "pause".to_string(),
                    seq,
                    result: None,
                },
            },
        )
    }

    /// Records a local step result for replay.
    pub async fn record_step(&self, seq: u64, result: Value, now: u64) -> Result<(), RuntimeError> {
        self.runtime
            .record_result(&self.execution_id, seq, result, now)
            .await
    }

    /// Notifies connectors that the current sandbox pass ended.
    pub async fn pass_ended(&self, status: &str) {
        for connector in self.connectors.values() {
            connector.pass_ended(&self.execution_id, status).await;
        }
    }

    /// Notifies connectors that the execution reached a terminal state.
    pub async fn execution_ended(&self, status: &str) {
        for connector in self.connectors.values() {
            connector.execution_ended(&self.execution_id, status).await;
        }
    }

    async fn call_inner(
        &self,
        seq: u64,
        connector_name: &str,
        method: &str,
        arguments: Value,
        now: u64,
    ) -> Result<DispatchResponse, String> {
        if connector_name == "codemode" {
            return self.call_builtin(seq, method, arguments, now).await;
        }
        let connector = self
            .connectors
            .get(connector_name)
            .ok_or_else(|| capability_unavailable(connector_name, method))?;
        let description = self.describe_once(connector_name).await?;
        let tool = description
            .tools
            .iter()
            .find(|tool| tool.name == method)
            .ok_or_else(|| format!("Tool \"{method}\" not found on {connector_name}"))?;
        let arguments = connector
            .prepare_arguments(seq, tool, arguments, &self.context)
            .await?;
        match self
            .runtime
            .decide(
                &self.execution_id,
                seq,
                connector_name,
                method,
                arguments.clone(),
                tool.policy.requires_approval,
                tool.policy.replay == ReplayPolicy::Reexecute,
                now,
            )
            .await
            .map_err(|error| error.to_string())?
        {
            ToolDecision::Replay(result) => Ok(DispatchResponse {
                result: Some(result),
                control: None,
                message: None,
            }),
            ToolDecision::Pause(_) => Ok(DispatchResponse {
                result: None,
                control: Some("pause".to_string()),
                message: None,
            }),
            decision @ (ToolDecision::Execute(_) | ToolDecision::Recover(_)) => {
                self.invoke_connector(
                    connector.as_ref(),
                    seq,
                    method,
                    arguments,
                    now,
                    matches!(decision, ToolDecision::Recover(_)),
                )
                .await
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    async fn invoke_connector(
        &self,
        connector: &dyn Connector,
        seq: u64,
        method: &str,
        arguments: Value,
        now: u64,
        mut recovering: bool,
    ) -> Result<DispatchResponse, String> {
        let state = self
            .runtime
            .execution(&self.execution_id)
            .await
            .map_err(|error| error.to_string())?
            .ok_or("Execution missing")?;
        let previous = state
            .log
            .iter()
            .find(|entry| entry.seq == seq)
            .ok_or("Call missing")?;
        let mut context = self.context.clone();
        context.call = Some(CallAttempt {
            sequence: seq,
            idempotency_key: format!("multicast:{}:{seq}", self.execution_id),
            attempt: previous.attempts,
        });
        let limit = connector
            .retry_policy(method)
            .max_attempts
            .clamp(1, crate::MAX_CALL_ATTEMPTS);
        let result = loop {
            if context.control.cancellation.is_cancelled() {
                return Err("Connector call cancelled".into());
            }
            if recovering {
                let recovery = connector.recover(method, &arguments, &context).await?;
                if context.control.cancellation.is_cancelled() {
                    return Err("Connector call cancelled".into());
                }
                match recovery {
                    CallRecovery::Applied(result) => break result,
                    CallRecovery::Retry => {}
                    CallRecovery::Uncertain => {
                        let reason = serde_json::json!({
                            "code": "CALL_OUTCOME_UNCERTAIN", "retryable": false,
                            "message": "Reconcile the interrupted call before resuming execution",
                            "sequence": seq,
                            "idempotencyKey": context.call.as_ref().map(|call| &call.idempotency_key),
                        }).to_string();
                        self.runtime
                            .suspend_call(&self.execution_id, reason.clone(), now)
                            .await
                            .map_err(|error| error.to_string())?;
                        return Ok(DispatchResponse {
                            result: None,
                            control: Some("pause".into()),
                            message: Some(reason),
                        });
                    }
                }
            }
            let attempt = self
                .runtime
                .charge_attempt(&self.execution_id, seq, limit, now)
                .await
                .map_err(|error| error.to_string())?;
            context
                .call
                .as_mut()
                .expect("call identity installed")
                .attempt = attempt;
            self.runtime
                .workflow_charge(&self.execution_id, now)
                .await?;
            match connector.execute(method, arguments.clone(), &context).await {
                Ok(result) => break result,
                Err(error) if suspends(&error) => {
                    self.runtime
                        .defer_call(&self.execution_id, seq, error.clone(), now)
                        .await
                        .map_err(|error| error.to_string())?;
                    return Ok(DispatchResponse {
                        result: None,
                        control: Some("pause".into()),
                        message: Some(error),
                    });
                }
                Err(error) if limit > 1 && retryable(&error) => recovering = true,
                Err(error) => return Err(error),
            }
        };
        self.runtime
            .record_result(&self.execution_id, seq, result.clone(), now)
            .await
            .map_err(|error| error.to_string())?;
        Ok(DispatchResponse {
            result: Some(result),
            control: None,
            message: None,
        })
    }

    async fn call_builtin(
        &self,
        seq: u64,
        method: &str,
        arguments: Value,
        now: u64,
    ) -> Result<DispatchResponse, String> {
        if let Some(operation) = method.strip_prefix("workflows.") {
            let decision = self
                .runtime
                .decide(
                    &self.execution_id,
                    seq,
                    "codemode",
                    method,
                    arguments.clone(),
                    false,
                    false,
                    now,
                )
                .await
                .map_err(|e| e.to_string())?;
            return match decision {
                ToolDecision::Replay(value) => Ok(DispatchResponse {
                    result: Some(value),
                    control: None,
                    message: None,
                }),
                ToolDecision::Pause(_) => Ok(DispatchResponse {
                    result: None,
                    control: Some("pause".into()),
                    message: None,
                }),
                ToolDecision::Execute(_) | ToolDecision::Recover(_) => {
                    let response = match self
                        .runtime
                        .workflow_call(&self.execution_id, seq, operation, arguments, now)
                        .await
                    {
                        Ok(response) => response,
                        Err(error) => DispatchResponse {
                            result: Some(serde_json::json!({"__workflow_error":error})),
                            control: None,
                            message: None,
                        },
                    };
                    if response.control.is_none() {
                        self.runtime
                            .record_result(
                                &self.execution_id,
                                seq,
                                response.result.clone().unwrap_or(Value::Null),
                                now,
                            )
                            .await
                            .map_err(|e| e.to_string())?;
                    }
                    Ok(response)
                }
            };
        }
        match self
            .runtime
            .decide(
                &self.execution_id,
                seq,
                "codemode",
                method,
                arguments.clone(),
                false,
                true,
                now,
            )
            .await
            .map_err(|error| error.to_string())?
        {
            ToolDecision::Pause(_) => Ok(DispatchResponse {
                result: None,
                control: Some("pause".to_string()),
                message: None,
            }),
            ToolDecision::Replay(result) => Ok(DispatchResponse {
                result: Some(result),
                control: None,
                message: None,
            }),
            ToolDecision::Execute(seq) | ToolDecision::Recover(seq) => {
                let connectors = self.described_all().await?;
                let snippets = self
                    .runtime
                    .snippets()
                    .await
                    .map_err(|error| error.to_string())?;
                let value = match method {
                    "search" => serde_json::to_value(search(
                        arguments
                            .get("query")
                            .and_then(Value::as_str)
                            .unwrap_or_default(),
                        &connectors,
                        &snippets,
                    )),
                    "describe" => serde_json::to_value(describe(
                        arguments
                            .get("target")
                            .and_then(Value::as_str)
                            .unwrap_or_default(),
                        &connectors,
                        &snippets,
                    )),
                    _ => return Err(format!("Tool \"{method}\" not found on codemode")),
                }
                .map_err(|error| error.to_string())?;
                self.runtime
                    .record_result(&self.execution_id, seq, value.clone(), now)
                    .await
                    .map_err(|error| error.to_string())?;
                Ok(DispatchResponse {
                    result: Some(value),
                    control: None,
                    message: None,
                })
            }
        }
    }
}

fn capability_unavailable(connector: &str, method: &str) -> String {
    serde_json::json!({
        "code": "CAPABILITY_UNAVAILABLE",
        "message": format!(
            "Capability {connector}.{method} existed when the execution began but is unavailable"
        ),
        "connector": connector,
        "method": method,
    })
    .to_string()
}

/// A connector reports `"suspend": true` only when the call provably never reached the remote
/// system, such as a missing credential; the run pauses and the call re-executes on resume.
fn suspends(error: &str) -> bool {
    serde_json::from_str::<Value>(error)
        .ok()
        .and_then(|value| value.get("suspend").and_then(Value::as_bool))
        == Some(true)
}

fn retryable(error: &str) -> bool {
    serde_json::from_str::<Value>(error)
        .ok()
        .and_then(|value| value.get("retryable").and_then(Value::as_bool))
        == Some(true)
}