incurs-codemode 0.1.0

Portable durable Code Mode runtime for incurs 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
use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use incurs::command::RequestContext;
use incurs::tool::{ToolCallControl, ToolEvent, ToolEventSink};
use serde_json::Value;
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;

use crate::{
    ArtifactStore, CapabilitySnapshot, Clock, CodeExecutor, CodeModeRuntime, Connector,
    DispatchRequest, DispatchSession, ExecutionEvent, ExecutionHost, ExecutionState,
    ExecutionStatus, RuntimeStore, SearchOutput, SystemClock, ToolContext,
};

/// Transport context inherited by one Code Mode execution pass.
#[derive(Clone, Default)]
pub struct CodeModeRunOptions {
    /// Cooperative cancellation signal for the active pass.
    pub cancellation: CancellationToken,
    /// Request metadata inherited by connector calls.
    pub request: Option<RequestContext>,
}

struct RuntimeEventSink {
    runtime: Arc<CodeModeRuntime>,
    execution_id: String,
    clock: Arc<dyn Clock>,
}

#[async_trait]
impl ToolEventSink for RuntimeEventSink {
    async fn emit(&self, event: ToolEvent) {
        let at = self.clock.now_ms();
        let event = match event {
            ToolEvent::Progress { message, fraction } => ExecutionEvent::Progress {
                message,
                fraction,
                at,
            },
            ToolEvent::Log { level, message } => ExecutionEvent::Log { level, message, at },
            ToolEvent::Chunk { data } => ExecutionEvent::Chunk { data, at },
        };
        let _ = self.runtime.event(&self.execution_id, event).await;
    }
}

/// Generic Code Mode lifecycle over interchangeable execution and storage adapters.
pub struct CodeMode {
    runtime: Arc<CodeModeRuntime>,
    executor: Box<dyn CodeExecutor>,
    connectors: Vec<Arc<dyn Connector>>,
    clock: Arc<dyn Clock>,
    contexts: Mutex<HashMap<String, ToolContext>>,
}

impl CodeMode {
    /// Creates a native Code Mode runtime using the system clock.
    pub fn new(
        store: Arc<dyn RuntimeStore>,
        executor: impl CodeExecutor + 'static,
        connectors: Vec<Arc<dyn Connector>>,
    ) -> Self {
        Self::with_clock(store, executor, connectors, SystemClock)
    }

    /// Creates Code Mode with an explicit oversized-value artifact store.
    pub fn with_artifact_store(
        store: Arc<dyn RuntimeStore>,
        artifacts: Arc<dyn ArtifactStore>,
        executor: impl CodeExecutor + 'static,
        connectors: Vec<Arc<dyn Connector>>,
    ) -> Self {
        Self {
            runtime: Arc::new(CodeModeRuntime::with_artifacts(store, artifacts)),
            executor: Box::new(executor),
            connectors,
            clock: Arc::new(SystemClock),
            contexts: Mutex::new(HashMap::new()),
        }
    }

    /// Creates Code Mode with an explicit platform clock.
    pub fn with_clock(
        store: Arc<dyn RuntimeStore>,
        executor: impl CodeExecutor + 'static,
        connectors: Vec<Arc<dyn Connector>>,
        clock: impl Clock + 'static,
    ) -> Self {
        Self {
            runtime: Arc::new(CodeModeRuntime::new(store)),
            executor: Box::new(executor),
            connectors,
            clock: Arc::new(clock),
            contexts: Mutex::new(HashMap::new()),
        }
    }

    /// Creates Code Mode with explicit platform clock and artifact storage.
    pub fn with_clock_and_artifact_store(
        store: Arc<dyn RuntimeStore>,
        artifacts: Arc<dyn ArtifactStore>,
        executor: impl CodeExecutor + 'static,
        connectors: Vec<Arc<dyn Connector>>,
        clock: impl Clock + 'static,
    ) -> Self {
        Self {
            runtime: Arc::new(CodeModeRuntime::with_artifacts(store, artifacts)),
            executor: Box::new(executor),
            connectors,
            clock: Arc::new(clock),
            contexts: Mutex::new(HashMap::new()),
        }
    }

    /// Returns the portable runtime for approvals, history, and snippets.
    pub fn runtime(&self) -> Arc<CodeModeRuntime> {
        Arc::clone(&self.runtime)
    }

    /// Returns model-facing JavaScript declarations and connector guidance.
    pub async fn instructions(&self) -> Result<String, String> {
        let mut descriptions = Vec::new();
        for connector in &self.connectors {
            descriptions.push(connector.describe().await?);
        }
        let mut sections = descriptions
            .iter()
            .filter_map(|connector| {
                connector
                    .instructions
                    .as_ref()
                    .map(|instructions| format!("## {}\n\n{instructions}", connector.name))
            })
            .collect::<Vec<_>>();
        sections.extend(descriptions.iter().map(crate::generate_types));
        Ok(sections.join("\n\n"))
    }

    /// Searches current connector methods and saved snippets.
    pub async fn search(&self, query: &str) -> Result<SearchOutput, String> {
        let mut descriptions = Vec::new();
        for connector in &self.connectors {
            descriptions.push(connector.describe().await?);
        }
        let snippets = self
            .runtime
            .snippets()
            .await
            .map_err(|error| error.to_string())?;
        Ok(crate::search(query, &descriptions, &snippets))
    }

    /// Returns one execution by identifier.
    pub async fn execution(&self, execution_id: &str) -> Result<ExecutionState, String> {
        self.require(execution_id).await
    }

    /// Returns one bounded execution snapshot with artifact references intact.
    pub async fn execution_snapshot(&self, execution_id: &str) -> Result<ExecutionState, String> {
        self.runtime
            .execution_snapshot(execution_id)
            .await
            .map_err(|error| error.to_string())?
            .ok_or_else(|| format!("Execution \"{execution_id}\" not found"))
    }

    /// Returns one oversized value owned by an execution.
    pub async fn artifact(&self, execution_id: &str, artifact_id: &str) -> Result<Value, String> {
        self.runtime
            .artifact(execution_id, artifact_id)
            .await
            .map_err(|error| error.to_string())?
            .ok_or_else(|| {
                format!("Artifact \"{artifact_id}\" not found for execution \"{execution_id}\"")
            })
    }

    /// Returns ordered retained events for one execution.
    pub async fn events(&self, execution_id: &str) -> Result<Vec<ExecutionEvent>, String> {
        Ok(self.require(execution_id).await?.events)
    }

    /// Cancels a running or paused execution.
    pub async fn cancel(&self, execution_id: &str) -> Result<ExecutionState, String> {
        if let Some(context) = self.contexts.lock().await.get(execution_id) {
            context.control.cancellation.cancel();
        }
        self.runtime
            .cancel(execution_id, self.clock.now_ms())
            .await
            .map_err(|error| error.to_string())?;
        self.require(execution_id).await
    }

    /// Creates a durable running execution without driving its first pass.
    pub async fn start(&self, code: &str) -> Result<ExecutionState, String> {
        let mut descriptions = Vec::new();
        for connector in &self.connectors {
            descriptions.push(connector.describe().await?);
        }
        let capabilities = CapabilitySnapshot::new(descriptions)?;
        let id = self
            .runtime
            .begin_with_capabilities(code, capabilities, self.clock.now_ms())
            .await
            .map_err(|error| error.to_string())?;
        self.require(&id).await
    }

    /// Starts and drives a new execution until it completes, fails, or pauses.
    pub async fn execute(&self, code: &str) -> Result<ExecutionState, String> {
        self.execute_with(code, CodeModeRunOptions::default()).await
    }

    /// Starts and drives a new execution with transport request context.
    pub async fn execute_with(
        &self,
        code: &str,
        options: CodeModeRunOptions,
    ) -> Result<ExecutionState, String> {
        let state = self.start(code).await?;
        self.drive_with(&state.id, options).await
    }

    /// Resumes a paused execution and drives the next replay pass.
    pub async fn resume(&self, execution_id: &str) -> Result<ExecutionState, String> {
        self.resume_with(execution_id, CodeModeRunOptions::default())
            .await
    }

    /// Resumes a paused execution with transport request context.
    pub async fn resume_with(
        &self,
        execution_id: &str,
        options: CodeModeRunOptions,
    ) -> Result<ExecutionState, String> {
        self.runtime
            .resume(execution_id, self.clock.now_ms())
            .await
            .map_err(|error| error.to_string())?;
        self.drive_with(execution_id, options).await
    }

    /// Approves a pending action and resumes only if this call won the race.
    pub async fn approve(&self, execution_id: &str, seq: u64) -> Result<ExecutionState, String> {
        self.approve_with(execution_id, seq, CodeModeRunOptions::default())
            .await
    }

    /// Approves a pending action and resumes with transport request context.
    pub async fn approve_with(
        &self,
        execution_id: &str,
        seq: u64,
        options: CodeModeRunOptions,
    ) -> Result<ExecutionState, String> {
        if !self
            .runtime
            .approve(execution_id, seq, self.clock.now_ms())
            .await
            .map_err(|error| error.to_string())?
        {
            return self.require(execution_id).await;
        }
        self.drive_with(execution_id, options).await
    }

    /// Rejects a pending action and notifies connector lifecycle hooks.
    pub async fn reject(&self, execution_id: &str, seq: u64) -> Result<ExecutionState, String> {
        if self
            .runtime
            .reject(execution_id, seq, self.clock.now_ms())
            .await
            .map_err(|error| error.to_string())?
        {
            self.notify_execution_end(execution_id, "rejected").await;
        }
        self.require(execution_id).await
    }

    /// Compensates applied connector actions in reverse order.
    pub async fn rollback(&self, execution_id: &str) -> Result<ExecutionState, String> {
        for action in self
            .runtime
            .actions_to_revert(execution_id)
            .await
            .map_err(|error| error.to_string())?
        {
            let connector = self
                .connector(&action.connector)
                .await?
                .ok_or_else(|| format!("Connector \"{}\" not found", action.connector))?;
            if !connector
                .revert(
                    &action.method,
                    action.arguments,
                    action.result.unwrap_or(Value::Null),
                    &ToolContext {
                        execution_id: execution_id.to_string(),
                        control: Default::default(),
                        request: None,
                    },
                )
                .await?
            {
                return Err(format!(
                    "{}.{} did not compensate step {}",
                    action.connector, action.method, action.seq
                ));
            }
            self.runtime
                .mark_reverted(execution_id, action.seq, self.clock.now_ms())
                .await
                .map_err(|error| error.to_string())?;
        }
        self.runtime
            .finish_rollback(execution_id, self.clock.now_ms())
            .await
            .map_err(|error| error.to_string())?;
        self.notify_execution_end(execution_id, "rolled_back").await;
        self.require(execution_id).await
    }

    /// Expires stale live executions and releases connector resources.
    pub async fn expire(&self, max_age_ms: u64) -> Result<Vec<String>, String> {
        let ids = self
            .runtime
            .expire(self.clock.now_ms(), max_age_ms)
            .await
            .map_err(|error| error.to_string())?;
        for id in &ids {
            let status = self.require(id).await?.status;
            self.notify_execution_end(
                id,
                if status == ExecutionStatus::Rejected {
                    "rejected"
                } else {
                    "error"
                },
            )
            .await;
        }
        Ok(ids)
    }

    /// Handles one program-to-host dispatch request.
    pub async fn dispatch(&self, request: DispatchRequest) -> Result<Value, String> {
        match request {
            DispatchRequest::Call {
                execution_id,
                seq,
                connector,
                method,
                arguments,
            } => {
                let session = self.session(&execution_id).await?;
                serde_json::to_value(
                    session
                        .call_at(seq, &connector, &method, arguments, self.clock.now_ms())
                        .await,
                )
                .map_err(|error| error.to_string())
            }
            DispatchRequest::BeginStep {
                execution_id,
                seq,
                name,
            } => {
                let session = self.session(&execution_id).await?;
                serde_json::to_value(
                    session
                        .begin_step_at(seq, &name, self.clock.now_ms())
                        .await
                        .map_err(|error| error.to_string())?,
                )
                .map_err(|error| error.to_string())
            }
            DispatchRequest::RecordStep {
                execution_id,
                seq,
                result,
            } => {
                self.runtime
                    .record_result(&execution_id, seq, result, self.clock.now_ms())
                    .await
                    .map_err(|error| error.to_string())?;
                Ok(serde_json::json!({ "ok": true }))
            }
        }
    }

    /// Drives one running execution pass with transport request context.
    pub async fn drive_with(
        &self,
        execution_id: &str,
        options: CodeModeRunOptions,
    ) -> Result<ExecutionState, String> {
        let state = self.require(execution_id).await?;
        if matches!(
            state.status,
            ExecutionStatus::Completed
                | ExecutionStatus::Error
                | ExecutionStatus::Rejected
                | ExecutionStatus::RolledBack
                | ExecutionStatus::Cancelled
        ) {
            return Ok(state);
        }
        let context = self.context(execution_id, options);
        let cancellation = context.control.cancellation.clone();
        self.contexts
            .lock()
            .await
            .insert(execution_id.to_string(), context.clone());
        let session = match self.session_with_context(execution_id, context).await {
            Ok(session) => session,
            Err(error) => {
                self.contexts.lock().await.remove(execution_id);
                return Err(error);
            }
        };
        let descriptions = session.descriptions();
        let execution = self.executor.execute(
            &state.code,
            &descriptions,
            execution_id,
            Arc::new(ExecutionHost::new(
                Arc::clone(&session),
                Arc::clone(&self.clock),
            )),
        );
        tokio::pin!(execution);
        let response = tokio::select! {
            _ = cancellation.cancelled() => None,
            response = &mut execution => Some(response),
        };
        self.contexts.lock().await.remove(execution_id);
        let Some(response) = response else {
            self.runtime
                .cancel(execution_id, self.clock.now_ms())
                .await
                .map_err(|error| error.to_string())?;
            session.pass_ended("cancelled").await;
            session.execution_ended("cancelled").await;
            return self.require(execution_id).await;
        };
        let response = match response {
            Ok(response) => response,
            Err(error) => {
                self.runtime
                    .fail(execution_id, error, Vec::new(), self.clock.now_ms())
                    .await
                    .map_err(|error| error.to_string())?;
                session.pass_ended("error").await;
                session.execution_ended("error").await;
                return self.require(execution_id).await;
            }
        };
        let current = self.require(execution_id).await?;
        if current.status == ExecutionStatus::Paused {
            session.pass_ended("paused").await;
            return Ok(current);
        }
        if current.status == ExecutionStatus::Error {
            session.pass_ended("error").await;
            session.execution_ended("error").await;
            return Ok(current);
        }
        if let Some(error) = response.error {
            self.runtime
                .fail(execution_id, error, response.logs, self.clock.now_ms())
                .await
                .map_err(|error| error.to_string())?;
            session.pass_ended("error").await;
            session.execution_ended("error").await;
        } else {
            self.runtime
                .complete(
                    execution_id,
                    response.result.unwrap_or(Value::Null),
                    response.logs,
                    self.clock.now_ms(),
                )
                .await
                .map_err(|error| error.to_string())?;
            session.pass_ended("completed").await;
            session.execution_ended("completed").await;
        }
        self.require(execution_id).await
    }

    async fn session(&self, execution_id: &str) -> Result<Arc<DispatchSession>, String> {
        let context = self
            .contexts
            .lock()
            .await
            .get(execution_id)
            .cloned()
            .unwrap_or_else(|| self.context(execution_id, CodeModeRunOptions::default()));
        self.session_with_context(execution_id, context).await
    }

    async fn session_with_context(
        &self,
        execution_id: &str,
        context: ToolContext,
    ) -> Result<Arc<DispatchSession>, String> {
        let state = self.require(execution_id).await?;
        let descriptions = if let Some(capabilities) = state.capabilities {
            capabilities.connectors
        } else {
            let mut descriptions = Vec::new();
            for connector in &self.connectors {
                descriptions.push(connector.describe().await?);
            }
            descriptions
        };
        Ok(Arc::new(
            DispatchSession::new_with_descriptions_and_context(
                Arc::clone(&self.runtime),
                context,
                self.connectors.clone(),
                descriptions,
            )
            .await?,
        ))
    }

    fn context(&self, execution_id: &str, options: CodeModeRunOptions) -> ToolContext {
        ToolContext {
            execution_id: execution_id.to_string(),
            control: ToolCallControl {
                cancellation: options.cancellation,
                events: Some(Arc::new(RuntimeEventSink {
                    runtime: Arc::clone(&self.runtime),
                    execution_id: execution_id.to_string(),
                    clock: Arc::clone(&self.clock),
                })),
            },
            request: options.request,
        }
    }

    async fn require(&self, execution_id: &str) -> Result<ExecutionState, String> {
        self.runtime
            .execution(execution_id)
            .await
            .map_err(|error| error.to_string())?
            .ok_or_else(|| format!("Execution \"{execution_id}\" not found"))
    }

    async fn connector(&self, name: &str) -> Result<Option<&Arc<dyn Connector>>, String> {
        for connector in &self.connectors {
            if connector.describe().await?.name == name {
                return Ok(Some(connector));
            }
        }
        Ok(None)
    }

    async fn notify_execution_end(&self, execution_id: &str, status: &str) {
        for connector in &self.connectors {
            connector.execution_ended(execution_id, status).await;
        }
    }
}