nanocodex-tools 0.1.1

Code Mode and heterogeneous tool runtime for Nanocodex
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
use std::{
    cell::RefCell,
    collections::HashMap,
    rc::Rc,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
        mpsc as std_mpsc,
    },
    thread,
    time::Duration,
};

use rquickjs::{
    CatchResultExt, Context, Ctx, Exception, Function, Persistent, Promise, Runtime,
    function::Func, promise::PromiseState,
};
use serde::Deserialize;
use serde_json::Value;
use tokio::sync::mpsc;

use super::{RuntimeEvent, ToolOutputContent};

const BOOTSTRAP: &str = include_str!("bootstrap.js");

type SavedFunction = Persistent<Function<'static>>;

pub(super) struct EmbeddedHost {
    command_tx: std_mpsc::Sender<HostCommand>,
    events: mpsc::UnboundedReceiver<RuntimeEvent>,
    interrupted: Arc<AtomicBool>,
    worker: Option<thread::JoinHandle<()>>,
}

enum HostCommand {
    Start(StartExecution),
    ToolResult {
        execution_id: u64,
        id: u64,
        value: Value,
        success: bool,
    },
    TimeoutFired {
        execution_id: u64,
        id: u32,
    },
    Shutdown,
}

struct StartExecution {
    execution_id: u64,
    source: String,
    tools: Vec<Value>,
    stored: HashMap<String, Value>,
}

struct ExecutionState {
    execution_id: u64,
    event_tx: mpsc::UnboundedSender<RuntimeEvent>,
    command_tx: std_mpsc::Sender<HostCommand>,
    pending_tools: HashMap<u64, (SavedFunction, SavedFunction)>,
    pending_timeouts: HashMap<u32, SavedFunction>,
    next_tool_id: u64,
    next_timeout_id: u32,
}

#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum ExecutionTerminal {
    Done {
        #[serde(default)]
        content: Vec<ToolOutputContent>,
        #[serde(default)]
        stored: HashMap<String, Value>,
    },
    Error {
        message: String,
        #[serde(default)]
        content: Vec<ToolOutputContent>,
        #[serde(default)]
        stored: HashMap<String, Value>,
    },
}

impl EmbeddedHost {
    pub(super) fn spawn() -> Result<Self, String> {
        let (command_tx, command_rx) = std_mpsc::channel();
        let (event_tx, events) = mpsc::unbounded_channel();
        let (ready_tx, ready_rx) = std_mpsc::sync_channel(1);
        let interrupted = Arc::new(AtomicBool::new(false));
        let worker_interrupted = Arc::clone(&interrupted);
        let worker_command_tx = command_tx.clone();
        let worker = thread::Builder::new()
            .name("nanocodex-code-mode-quickjs".to_owned())
            .spawn(move || {
                run_worker(
                    &command_rx,
                    &worker_command_tx,
                    &event_tx,
                    &ready_tx,
                    &worker_interrupted,
                );
            })
            .map_err(|error| format!("failed to start embedded QuickJS code-mode host: {error}"))?;
        ready_rx
            .recv()
            .map_err(|_| "embedded QuickJS code-mode host ended during startup".to_owned())??;
        Ok(Self {
            command_tx,
            events,
            interrupted,
            worker: Some(worker),
        })
    }

    pub(super) fn start_cell(
        &self,
        execution_id: u64,
        source: &str,
        stored: HashMap<String, Value>,
        tools: Vec<Value>,
    ) -> Result<(), String> {
        self.command_tx
            .send(HostCommand::Start(StartExecution {
                execution_id,
                source: source.to_owned(),
                tools,
                stored,
            }))
            .map_err(|_| "embedded QuickJS code-mode host is unavailable".to_owned())
    }

    pub(super) async fn read_event(&mut self) -> Result<RuntimeEvent, String> {
        self.events
            .recv()
            .await
            .ok_or_else(|| "embedded QuickJS code-mode host ended before a result".to_owned())
    }

    pub(super) fn send_tool_result(
        &self,
        execution_id: u64,
        id: u64,
        value: Value,
        success: bool,
    ) -> Result<(), String> {
        self.command_tx
            .send(HostCommand::ToolResult {
                execution_id,
                id,
                value,
                success,
            })
            .map_err(|_| {
                "embedded QuickJS code-mode host closed before accepting a tool result".into()
            })
    }

    pub(super) async fn terminate(&mut self) {
        self.interrupted.store(true, Ordering::Release);
        let _ = self.command_tx.send(HostCommand::Shutdown);
        if let Some(worker) = self.worker.take() {
            let _ = tokio::task::spawn_blocking(move || worker.join()).await;
        }
    }
}

impl Drop for EmbeddedHost {
    fn drop(&mut self) {
        self.interrupted.store(true, Ordering::Release);
        let _ = self.command_tx.send(HostCommand::Shutdown);
    }
}

fn run_worker(
    command_rx: &std_mpsc::Receiver<HostCommand>,
    command_tx: &std_mpsc::Sender<HostCommand>,
    event_tx: &mpsc::UnboundedSender<RuntimeEvent>,
    ready_tx: &std_mpsc::SyncSender<Result<(), String>>,
    interrupted: &Arc<AtomicBool>,
) {
    let runtime = match Runtime::new() {
        Ok(runtime) => runtime,
        Err(error) => {
            let _ = ready_tx.send(Err(format!(
                "failed to initialize embedded QuickJS runtime: {error}"
            )));
            return;
        }
    };
    let interrupt_signal = Arc::clone(interrupted);
    runtime.set_interrupt_handler(Some(Box::new(move || {
        interrupt_signal.load(Ordering::Acquire)
    })));
    let prewarmed_context = match Context::full(&runtime) {
        Ok(context) => context,
        Err(error) => {
            let _ = ready_tx.send(Err(format!(
                "failed to create embedded QuickJS context: {error}"
            )));
            return;
        }
    };
    drop(prewarmed_context);
    runtime.run_gc();
    if ready_tx.send(Ok(())).is_err() {
        return;
    }

    loop {
        match command_rx.recv() {
            Ok(HostCommand::Start(start)) => {
                interrupted.store(false, Ordering::Release);
                let context = match Context::full(&runtime) {
                    Ok(context) => context,
                    Err(error) => {
                        tracing::error!(
                            target: "nanocodex_tools",
                            %error,
                            "failed to create a fresh embedded QuickJS context"
                        );
                        return;
                    }
                };
                let result = run_execution(
                    &context,
                    start,
                    command_rx,
                    command_tx.clone(),
                    event_tx.clone(),
                );
                drop(context);
                runtime.run_gc();
                if result.is_err() {
                    return;
                }
            }
            Ok(HostCommand::TimeoutFired { .. } | HostCommand::ToolResult { .. }) => {}
            Ok(HostCommand::Shutdown) | Err(_) => return,
        }
    }
}

fn run_execution(
    context: &Context,
    start: StartExecution,
    command_rx: &std_mpsc::Receiver<HostCommand>,
    command_tx: std_mpsc::Sender<HostCommand>,
    event_tx: mpsc::UnboundedSender<RuntimeEvent>,
) -> Result<(), String> {
    context.with(|ctx| run_execution_in_context(&ctx, start, command_rx, command_tx, event_tx))
}

fn run_execution_in_context<'js>(
    ctx: &Ctx<'js>,
    start: StartExecution,
    command_rx: &std_mpsc::Receiver<HostCommand>,
    command_tx: std_mpsc::Sender<HostCommand>,
    event_tx: mpsc::UnboundedSender<RuntimeEvent>,
) -> Result<(), String> {
    let execution_id = start.execution_id;
    let state = Rc::new(RefCell::new(ExecutionState {
        execution_id,
        event_tx,
        command_tx,
        pending_tools: HashMap::new(),
        pending_timeouts: HashMap::new(),
        next_tool_id: 1,
        next_timeout_id: 1,
    }));
    install_native_functions(ctx, &state)?;
    let run_cell = ctx
        .eval::<Function<'js>, _>(BOOTSTRAP)
        .catch(ctx)
        .map_err(|error| format!("failed to evaluate embedded QuickJS bootstrap: {error}"))?;
    remove_native_globals(ctx)?;

    let tools = serde_json::to_string(&start.tools)
        .map_err(|error| format!("failed to encode QuickJS tool metadata: {error}"))?;
    let stored = serde_json::to_string(&start.stored)
        .map_err(|error| format!("failed to encode QuickJS stored values: {error}"))?;
    let promise = run_cell
        .call::<_, Promise<'js>>((start.source, tools, stored))
        .catch(ctx)
        .map_err(|error| format!("embedded QuickJS execution failed to start: {error}"))?;
    drain_jobs(ctx);

    let result = (|| {
        loop {
            if let Some(terminal) = completed_terminal(ctx, &promise)? {
                return send_terminal(&state, terminal);
            }
            match command_rx.recv() {
                Ok(HostCommand::ToolResult {
                    execution_id: result_execution_id,
                    id,
                    value,
                    success,
                }) if result_execution_id == execution_id => {
                    resolve_tool(ctx, &state, id, &value, success)?;
                    drain_jobs(ctx);
                }
                Ok(HostCommand::TimeoutFired {
                    execution_id: timeout_execution_id,
                    id,
                }) if timeout_execution_id == execution_id => {
                    invoke_timeout(ctx, &state, id)?;
                    drain_jobs(ctx);
                }
                Ok(HostCommand::Shutdown) | Err(_) => {
                    return Err("embedded QuickJS host stopped".into());
                }
                Ok(
                    HostCommand::Start(_)
                    | HostCommand::ToolResult { .. }
                    | HostCommand::TimeoutFired { .. },
                ) => {}
            }
        }
    })();
    let mut state = state.borrow_mut();
    state.pending_tools.clear();
    state.pending_timeouts.clear();
    result
}

#[allow(clippy::too_many_lines)]
fn install_native_functions<'js>(
    ctx: &Ctx<'js>,
    state: &Rc<RefCell<ExecutionState>>,
) -> Result<(), String> {
    let globals = ctx.globals();

    let tool_state = Rc::clone(state);
    globals
        .set(
            "__nanocodexTool",
            Func::from(
                move |ctx: Ctx<'js>,
                      name: String,
                      input_json: String|
                      -> rquickjs::Result<Promise<'js>> {
                    let input = serde_json::from_str(&input_json).map_err(|error| {
                        Exception::throw_type(&ctx, &format!("invalid tool input: {error}"))
                    })?;
                    let (promise, resolve, reject) = Promise::new(&ctx)?;
                    let mut state = tool_state.borrow_mut();
                    let id = state.next_tool_id;
                    state.next_tool_id = state.next_tool_id.saturating_add(1);
                    state.pending_tools.insert(
                        id,
                        (
                            Persistent::save(&ctx, resolve),
                            Persistent::save(&ctx, reject),
                        ),
                    );
                    let _ = state.event_tx.send(RuntimeEvent::ToolCall {
                        cell_id: state.execution_id,
                        id,
                        name,
                        input,
                    });
                    Ok(promise)
                },
            ),
        )
        .catch(ctx)
        .map_err(|error| format!("failed to install QuickJS tool callback: {error}"))?;

    let notify_state = Rc::clone(state);
    globals
        .set(
            "__nanocodexNotify",
            Func::from(move |text: String| {
                let state = notify_state.borrow();
                let _ = state.event_tx.send(RuntimeEvent::Notify {
                    cell_id: state.execution_id,
                    text,
                });
            }),
        )
        .catch(ctx)
        .map_err(|error| format!("failed to install QuickJS notify callback: {error}"))?;

    let yield_state = Rc::clone(state);
    globals
        .set(
            "__nanocodexYield",
            Func::from(
                move |ctx: Ctx<'js>, content_json: String| -> rquickjs::Result<()> {
                    let content = serde_json::from_str(&content_json).map_err(|error| {
                        Exception::throw_type(&ctx, &format!("invalid yielded content: {error}"))
                    })?;
                    let state = yield_state.borrow();
                    let _ = state.event_tx.send(RuntimeEvent::Yielded {
                        cell_id: state.execution_id,
                        content,
                    });
                    Ok(())
                },
            ),
        )
        .catch(ctx)
        .map_err(|error| format!("failed to install QuickJS yield callback: {error}"))?;

    let timeout_state = Rc::clone(state);
    globals
        .set(
            "__nanocodexSetTimeout",
            Func::from(
                move |ctx: Ctx<'js>,
                      callback: Function<'js>,
                      delay_ms: i64|
                      -> rquickjs::Result<u32> {
                    let delay_ms = u64::try_from(delay_ms).unwrap_or_default();
                    let mut state = timeout_state.borrow_mut();
                    let id = state.next_timeout_id;
                    state.next_timeout_id = state.next_timeout_id.saturating_add(1);
                    let execution_id = state.execution_id;
                    let command_tx = state.command_tx.clone();
                    state
                        .pending_timeouts
                        .insert(id, Persistent::save(&ctx, callback));
                    thread::spawn(move || {
                        thread::sleep(Duration::from_millis(delay_ms));
                        let _ = command_tx.send(HostCommand::TimeoutFired { execution_id, id });
                    });
                    Ok(id)
                },
            ),
        )
        .catch(ctx)
        .map_err(|error| format!("failed to install QuickJS timer callback: {error}"))?;

    let clear_timeout_state = Rc::clone(state);
    globals
        .set(
            "__nanocodexClearTimeout",
            Func::from(move |id: u32| {
                clear_timeout_state
                    .borrow_mut()
                    .pending_timeouts
                    .remove(&id);
            }),
        )
        .catch(ctx)
        .map_err(|error| format!("failed to install QuickJS timer cleanup: {error}"))?;
    Ok(())
}

fn remove_native_globals(ctx: &Ctx<'_>) -> Result<(), String> {
    let globals = ctx.globals();
    for name in [
        "__nanocodexTool",
        "__nanocodexNotify",
        "__nanocodexYield",
        "__nanocodexSetTimeout",
        "__nanocodexClearTimeout",
    ] {
        globals
            .remove(name)
            .catch(ctx)
            .map_err(|error| format!("failed to remove QuickJS global `{name}`: {error}"))?;
    }
    Ok(())
}

fn completed_terminal(
    ctx: &Ctx<'_>,
    promise: &Promise<'_>,
) -> Result<Option<ExecutionTerminal>, String> {
    match promise.state() {
        PromiseState::Pending => Ok(None),
        PromiseState::Resolved => {
            let encoded = promise
                .result::<String>()
                .ok_or_else(|| "embedded QuickJS promise lost its result".to_owned())?
                .catch(ctx)
                .map_err(|error| format!("failed to read embedded QuickJS result: {error}"))?;
            serde_json::from_str(&encoded)
                .map(Some)
                .map_err(|error| format!("embedded QuickJS returned an invalid result: {error}"))
        }
        PromiseState::Rejected => {
            let result = promise
                .result::<String>()
                .ok_or_else(|| "embedded QuickJS promise lost its rejection".to_owned())?
                .catch(ctx);
            match result {
                Err(error) => Err(format!("embedded QuickJS execution rejected: {error}")),
                Ok(_) => {
                    Err("rejected embedded QuickJS promise returned a successful value".to_owned())
                }
            }
        }
    }
}

fn send_terminal(
    state: &Rc<RefCell<ExecutionState>>,
    terminal: ExecutionTerminal,
) -> Result<(), String> {
    let state = state.borrow();
    let event = match terminal {
        ExecutionTerminal::Done { content, stored } => RuntimeEvent::Done {
            cell_id: state.execution_id,
            content,
            stored,
        },
        ExecutionTerminal::Error {
            message,
            content,
            stored,
        } => RuntimeEvent::Error {
            cell_id: state.execution_id,
            message,
            content,
            stored,
        },
    };
    state
        .event_tx
        .send(event)
        .map_err(|_| "embedded QuickJS execution observer closed".to_owned())
}

fn resolve_tool(
    ctx: &Ctx<'_>,
    state: &Rc<RefCell<ExecutionState>>,
    id: u64,
    value: &Value,
    success: bool,
) -> Result<(), String> {
    let (resolve, reject) = state
        .borrow_mut()
        .pending_tools
        .remove(&id)
        .ok_or_else(|| format!("embedded QuickJS received a result for unknown tool call {id}"))?;
    let function = if success { resolve } else { reject };
    let function = function
        .restore(ctx)
        .map_err(|error| format!("failed to restore QuickJS tool promise: {error}"))?;
    let encoded = serde_json::to_string(value)
        .map_err(|error| format!("failed to encode QuickJS tool result: {error}"))?;
    function
        .call::<_, ()>((encoded,))
        .catch(ctx)
        .map_err(|error| format!("failed to settle QuickJS tool promise: {error}"))
}

fn invoke_timeout(
    ctx: &Ctx<'_>,
    state: &Rc<RefCell<ExecutionState>>,
    id: u32,
) -> Result<(), String> {
    let callback = state.borrow_mut().pending_timeouts.remove(&id);
    let Some(callback) = callback else {
        return Ok(());
    };
    let callback = callback
        .restore(ctx)
        .map_err(|error| format!("failed to restore QuickJS timeout callback: {error}"))?;
    callback
        .call::<_, ()>(())
        .catch(ctx)
        .map_err(|error| format!("embedded QuickJS timeout callback failed: {error}"))
}

fn drain_jobs(ctx: &Ctx<'_>) {
    while ctx.execute_pending_job() {}
}