-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasync_session.rs
More file actions
2214 lines (1974 loc) · 82 KB
/
async_session.rs
File metadata and controls
2214 lines (1974 loc) · 82 KB
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Async session for code execution.
//!
//! Provides an async interface for executing code via the daemon's kernel.
//! All methods return Python coroutines that can be awaited.
use pyo3::prelude::*;
use pyo3_async_runtimes::tokio::future_into_py;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::Mutex;
use runtimed::notebook_sync_client::{
NotebookBroadcastReceiver, NotebookSyncClient, NotebookSyncHandle, NotebookSyncReceiver,
};
use runtimed::protocol::{NotebookBroadcast, NotebookRequest, NotebookResponse};
use crate::daemon_paths::{get_blob_paths_async, get_socket_path};
use crate::error::to_py_err;
use crate::event_stream::ExecutionEventStream;
use crate::output::{Cell, ExecutionResult, NotebookConnectionInfo, Output, SyncEnvironmentResult};
use crate::output_resolver;
use crate::subscription::EventSubscription;
use notebook_doc::metadata::NotebookMetadataSnapshot;
/// An async session for executing code via the runtimed daemon.
///
/// Each session connects to a unique "virtual notebook" room in the daemon
/// and can launch a kernel and execute code. Sessions are isolated from
/// each other but multiple sessions can share the same kernel if they
/// use the same notebook_id.
///
/// Example:
/// async with AsyncSession() as session:
/// await session.start_kernel()
/// cell_id = await session.create_cell("print('hello')")
/// result = await session.execute_cell(cell_id)
/// print(result.stdout) # "hello\n"
#[pyclass]
pub struct AsyncSession {
state: Arc<Mutex<AsyncSessionState>>,
notebook_id: String,
}
struct AsyncSessionState {
handle: Option<NotebookSyncHandle>,
/// Keep the sync receiver alive so the sync task doesn't exit
#[allow(dead_code)]
sync_rx: Option<NotebookSyncReceiver>,
broadcast_rx: Option<NotebookBroadcastReceiver>,
kernel_started: bool,
env_source: Option<String>,
/// Base URL for blob server (for resolving blob hashes)
blob_base_url: Option<String>,
/// Path to blob store directory (fallback for direct disk access)
blob_store_path: Option<PathBuf>,
/// Connection info from daemon (for open_notebook/create_notebook)
connection_info: Option<NotebookConnectionInfo>,
/// Notebook path (for project file detection during kernel launch)
notebook_path: Option<String>,
}
impl AsyncSessionState {
fn new() -> Self {
Self {
handle: None,
sync_rx: None,
broadcast_rx: None,
kernel_started: false,
env_source: None,
blob_base_url: None,
blob_store_path: None,
connection_info: None,
notebook_path: None,
}
}
}
#[pymethods]
impl AsyncSession {
/// Create a new async session.
///
/// Args:
/// notebook_id: Optional unique identifier for this session.
/// If not provided, a random UUID is generated.
/// Multiple AsyncSession objects with the same notebook_id
/// will share the same kernel.
#[new]
#[pyo3(signature = (notebook_id=None))]
fn new(notebook_id: Option<String>) -> PyResult<Self> {
let notebook_id =
notebook_id.unwrap_or_else(|| format!("agent-session-{}", uuid::Uuid::new_v4()));
Ok(Self {
state: Arc::new(Mutex::new(AsyncSessionState::new())),
notebook_id,
})
}
/// Get the notebook ID for this session.
#[getter]
fn notebook_id(&self) -> &str {
&self.notebook_id
}
/// Check if the session is connected to the daemon.
///
/// Returns a coroutine that resolves to bool.
fn is_connected<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
future_into_py(py, async move {
let state = state.lock().await;
Ok(state.handle.is_some())
})
}
/// Check if a kernel has been started.
///
/// Returns a coroutine that resolves to bool.
fn kernel_started<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
future_into_py(py, async move {
let state = state.lock().await;
Ok(state.kernel_started)
})
}
/// Get the environment source (e.g., "uv:prewarmed") if kernel is running.
///
/// Returns a coroutine that resolves to Optional[str].
fn env_source<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
future_into_py(py, async move {
let state = state.lock().await;
Ok(state.env_source.clone())
})
}
/// Get the connection info from daemon (for open_notebook/create_notebook).
///
/// Returns None if not connected via open_notebook() or create_notebook().
/// Returns a coroutine that resolves to Optional[NotebookConnectionInfo].
fn connection_info<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
future_into_py(py, async move {
let state = state.lock().await;
Ok(state.connection_info.clone())
})
}
/// Open an existing notebook file via the daemon.
///
/// The daemon loads the file, derives the notebook_id from the canonical path,
/// and returns connection info including trust status.
///
/// Args:
/// path: Path to the .ipynb file.
///
/// Returns:
/// A coroutine that resolves to a new AsyncSession connected to the opened notebook.
///
/// Raises:
/// RuntimedError: If the file cannot be opened or parsed.
#[staticmethod]
fn open_notebook(py: Python<'_>, path: String) -> PyResult<Bound<'_, PyAny>> {
future_into_py(py, async move {
let path_buf = PathBuf::from(&path);
let socket_path = get_socket_path();
let (handle, sync_rx, broadcast_rx, _cells, _metadata, info) =
NotebookSyncClient::connect_open_split(socket_path.clone(), path_buf, None)
.await
.map_err(to_py_err)?;
// Check for error in response
if let Some(error) = info.error {
return Err(to_py_err(error));
}
let notebook_id = info.notebook_id.clone();
let connection_info = NotebookConnectionInfo::from_protocol(info);
let (blob_base_url, blob_store_path) = get_blob_paths_async(&socket_path).await;
let state = AsyncSessionState {
handle: Some(handle),
sync_rx: Some(sync_rx),
broadcast_rx: Some(broadcast_rx),
kernel_started: false,
env_source: None,
blob_base_url,
blob_store_path,
connection_info: Some(connection_info),
notebook_path: Some(path),
};
Ok(AsyncSession {
state: Arc::new(Mutex::new(state)),
notebook_id,
})
})
}
/// Create a new notebook via the daemon.
///
/// The daemon creates an empty notebook with one code cell and returns
/// connection info with a generated UUID as the notebook_id.
///
/// Args:
/// runtime: The kernel runtime type ("python" or "deno"). Defaults to "python".
/// working_dir: Optional working directory for project file detection.
///
/// Returns:
/// A coroutine that resolves to a new AsyncSession connected to the created notebook.
#[staticmethod]
#[pyo3(signature = (runtime="python", working_dir=None))]
fn create_notebook<'py>(
py: Python<'py>,
runtime: &str,
working_dir: Option<String>,
) -> PyResult<Bound<'py, PyAny>> {
// Validate working_dir if provided
if let Some(ref wd) = working_dir {
let path = std::path::Path::new(wd);
if !path.exists() {
return Err(pyo3::exceptions::PyFileNotFoundError::new_err(format!(
"working_dir does not exist: {}",
wd
)));
}
if !path.is_dir() {
return Err(pyo3::exceptions::PyNotADirectoryError::new_err(format!(
"working_dir is not a directory: {}",
wd
)));
}
}
let runtime = runtime.to_string();
future_into_py(py, async move {
let working_dir_str = working_dir.clone();
let working_dir_buf = working_dir.map(PathBuf::from);
let socket_path = get_socket_path();
let (handle, sync_rx, broadcast_rx, _cells, _metadata, info) =
NotebookSyncClient::connect_create_split(
socket_path.clone(),
runtime,
working_dir_buf,
None,
None,
)
.await
.map_err(to_py_err)?;
// Check for error in response
if let Some(error) = info.error {
return Err(to_py_err(error));
}
let notebook_id = info.notebook_id.clone();
let connection_info = NotebookConnectionInfo::from_protocol(info);
let (blob_base_url, blob_store_path) = get_blob_paths_async(&socket_path).await;
let state = AsyncSessionState {
handle: Some(handle),
sync_rx: Some(sync_rx),
broadcast_rx: Some(broadcast_rx),
kernel_started: false,
env_source: None,
blob_base_url,
blob_store_path,
connection_info: Some(connection_info),
notebook_path: working_dir_str,
};
Ok(AsyncSession {
state: Arc::new(Mutex::new(state)),
notebook_id,
})
})
}
/// Connect to the daemon.
///
/// This is called automatically by start_kernel() if not already connected.
/// Respects the RUNTIMED_SOCKET_PATH environment variable if set.
///
/// Returns a coroutine.
fn connect<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let notebook_id = self.notebook_id.clone();
future_into_py(py, async move {
let mut state = state.lock().await;
if state.handle.is_some() {
return Ok(()); // Already connected
}
let socket_path = get_socket_path();
let (handle, sync_rx, broadcast_rx, _cells, _notebook_path) =
NotebookSyncClient::connect_split(socket_path.clone(), notebook_id)
.await
.map_err(to_py_err)?;
let (blob_base_url, blob_store_path) = get_blob_paths_async(&socket_path).await;
state.handle = Some(handle);
state.sync_rx = Some(sync_rx);
state.broadcast_rx = Some(broadcast_rx);
state.blob_base_url = blob_base_url;
state.blob_store_path = blob_store_path;
Ok(())
})
}
/// Start a kernel for this session.
///
/// Args:
/// kernel_type: Type of kernel ("python" or "deno"). Defaults to "python".
/// env_source: Environment source. Defaults to "auto" (auto-detect from
/// notebook metadata or project files). For Deno kernels, this is
/// ignored and always uses "deno".
/// notebook_path: Optional path to the notebook file on disk.
/// Used for project file detection (pyproject.toml, pixi.toml,
/// environment.yml) when env_source is "auto". If not provided,
/// uses the path from open_notebook() if available.
///
/// If a kernel is already running for this session's notebook_id,
/// this returns immediately without starting a new one.
///
/// Returns a coroutine.
#[pyo3(signature = (kernel_type="python", env_source="auto", notebook_path=None))]
fn start_kernel<'py>(
&self,
py: Python<'py>,
kernel_type: &str,
env_source: &str,
notebook_path: Option<&str>,
) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let notebook_id = self.notebook_id.clone();
let kernel_type = kernel_type.to_string();
let env_source = env_source.to_string();
let notebook_path = notebook_path.map(|s| s.to_string());
future_into_py(py, async move {
// Ensure connected first
{
let state_guard = state.lock().await;
if state_guard.handle.is_none() {
drop(state_guard);
// Connect
let socket_path = if let Ok(path) = std::env::var("RUNTIMED_SOCKET_PATH") {
std::path::PathBuf::from(path)
} else {
runtimed::default_socket_path()
};
let (handle, sync_rx, broadcast_rx, _cells, _notebook_path) =
NotebookSyncClient::connect_split(socket_path.clone(), notebook_id)
.await
.map_err(to_py_err)?;
let (blob_base_url, blob_store_path) =
if let Some(parent) = socket_path.parent() {
let daemon_json = parent.join("daemon.json");
let base_url = if daemon_json.exists() {
tokio::fs::read_to_string(&daemon_json)
.await
.ok()
.and_then(|contents| {
serde_json::from_str::<serde_json::Value>(&contents).ok()
})
.and_then(|info| info.get("blob_port").and_then(|p| p.as_u64()))
.map(|port| format!("http://127.0.0.1:{}", port))
} else {
None
};
let store_path = parent.join("blobs");
let store_path = if store_path.exists() {
Some(store_path)
} else {
None
};
(base_url, store_path)
} else {
(None, None)
};
let mut state_guard2 = state.lock().await;
state_guard2.handle = Some(handle);
state_guard2.sync_rx = Some(sync_rx);
state_guard2.broadcast_rx = Some(broadcast_rx);
state_guard2.blob_base_url = blob_base_url;
state_guard2.blob_store_path = blob_store_path;
}
}
let mut state_guard = state.lock().await;
let handle = state_guard
.handle
.as_ref()
.ok_or_else(|| to_py_err("Not connected"))?;
// Use provided notebook_path or fall back to stored path from open_notebook()
let resolved_path = notebook_path.or_else(|| state_guard.notebook_path.clone());
let response = handle
.send_request(NotebookRequest::LaunchKernel {
kernel_type,
env_source,
notebook_path: resolved_path,
})
.await
.map_err(to_py_err)?;
match response {
NotebookResponse::KernelLaunched {
env_source: actual_env,
..
} => {
state_guard.kernel_started = true;
state_guard.env_source = Some(actual_env);
Ok(())
}
NotebookResponse::KernelAlreadyRunning {
env_source: actual_env,
..
} => {
state_guard.kernel_started = true;
state_guard.env_source = Some(actual_env);
Ok(())
}
NotebookResponse::Error { error } => Err(to_py_err(error)),
other => Err(to_py_err(format!("Unexpected response: {:?}", other))),
}
})
}
// =========================================================================
// Document Operations (write to automerge doc, synced to all clients)
// =========================================================================
/// Create a new cell in the automerge document.
///
/// The cell is written to the shared document and synced to all connected
/// clients. Use execute_cell() to execute it.
///
/// Args:
/// source: The cell source code (default: empty string).
/// cell_type: Cell type - "code", "markdown", or "raw" (default: "code").
/// index: Position to insert the cell (default: append at end).
///
/// Returns a coroutine that resolves to the cell ID (str).
#[pyo3(signature = (source="", cell_type="code", index=None))]
fn create_cell<'py>(
&self,
py: Python<'py>,
source: &str,
cell_type: &str,
index: Option<usize>,
) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let source = source.to_string();
let cell_type = cell_type.to_string();
future_into_py(py, async move {
// Ensure connected
{
let state_guard = state.lock().await;
if state_guard.handle.is_none() {
drop(state_guard);
return Err(to_py_err("Not connected. Call connect() first."));
}
}
let cell_id = format!("cell-{}", uuid::Uuid::new_v4());
let state_guard = state.lock().await;
let handle = state_guard
.handle
.as_ref()
.ok_or_else(|| to_py_err("Not connected"))?;
let cells = handle.get_cells();
let insert_index = index.unwrap_or(cells.len());
handle
.add_cell(insert_index, &cell_id, &cell_type)
.await
.map_err(to_py_err)?;
if !source.is_empty() {
handle
.update_source(&cell_id, &source)
.await
.map_err(to_py_err)?;
}
Ok(cell_id)
})
}
/// Update a cell's source in the automerge document.
///
/// The change is synced to all connected clients.
///
/// Args:
/// cell_id: The cell ID.
/// source: The new source code.
///
/// Returns a coroutine.
fn set_source<'py>(
&self,
py: Python<'py>,
cell_id: &str,
source: &str,
) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let cell_id = cell_id.to_string();
let source = source.to_string();
future_into_py(py, async move {
let state_guard = state.lock().await;
let handle = state_guard
.handle
.as_ref()
.ok_or_else(|| to_py_err("Not connected"))?;
handle
.update_source(&cell_id, &source)
.await
.map_err(to_py_err)
})
}
/// Append text to a cell's source in the automerge document.
///
/// Unlike set_source() which replaces the entire text (using Myers diff
/// internally), this directly inserts characters at the end of the source
/// Text CRDT. This is ideal for streaming/agentic use cases where an
/// external process is appending tokens incrementally — each append is
/// a minimal CRDT operation that syncs efficiently to all connected clients.
///
/// Args:
/// cell_id: The cell ID.
/// text: The text to append to the cell's source.
///
/// Returns a coroutine.
fn append_source<'py>(
&self,
py: Python<'py>,
cell_id: &str,
text: &str,
) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let cell_id = cell_id.to_string();
let text = text.to_string();
future_into_py(py, async move {
let state_guard = state.lock().await;
let handle = state_guard
.handle
.as_ref()
.ok_or_else(|| to_py_err("Not connected"))?;
handle
.append_source(&cell_id, &text)
.await
.map_err(to_py_err)
})
}
/// Get a cell from the automerge document.
///
/// Args:
/// cell_id: The cell ID.
///
/// Returns a coroutine that resolves to Cell object.
///
/// Raises:
/// RuntimedError: If cell not found.
fn get_cell<'py>(&self, py: Python<'py>, cell_id: &str) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let cell_id = cell_id.to_string();
future_into_py(py, async move {
// Get snapshot and blob config while holding lock
let (snapshot, blob_base_url, blob_store_path) = {
let state_guard = state.lock().await;
let handle = state_guard
.handle
.as_ref()
.ok_or_else(|| to_py_err("Not connected"))?;
let blob_base_url = state_guard.blob_base_url.clone();
let blob_store_path = state_guard.blob_store_path.clone();
let cells = handle.get_cells();
let snapshot = cells
.into_iter()
.find(|c| c.id == cell_id)
.ok_or_else(|| to_py_err(format!("Cell not found: {}", cell_id)))?;
(snapshot, blob_base_url, blob_store_path)
}; // Lock released here
// Resolve outputs outside the lock
let outputs = output_resolver::resolve_cell_outputs(
&snapshot.outputs,
&blob_base_url,
&blob_store_path,
)
.await;
Ok(Cell::from_snapshot_with_outputs(snapshot, outputs))
})
}
/// Get all cells from the automerge document.
///
/// Returns a coroutine that resolves to List[Cell].
fn get_cells<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
future_into_py(py, async move {
// Get snapshots and blob config while holding lock
let (snapshots, blob_base_url, blob_store_path) = {
let state_guard = state.lock().await;
let handle = state_guard
.handle
.as_ref()
.ok_or_else(|| to_py_err("Not connected"))?;
let blob_base_url = state_guard.blob_base_url.clone();
let blob_store_path = state_guard.blob_store_path.clone();
let snapshots = handle.get_cells();
(snapshots, blob_base_url, blob_store_path)
}; // Lock released here
// Resolve outputs for all cells outside the lock
let mut cells = Vec::with_capacity(snapshots.len());
for snapshot in snapshots {
let outputs = output_resolver::resolve_cell_outputs(
&snapshot.outputs,
&blob_base_url,
&blob_store_path,
)
.await;
cells.push(Cell::from_snapshot_with_outputs(snapshot, outputs));
}
Ok(cells)
})
}
/// Delete a cell from the automerge document.
///
/// Args:
/// cell_id: The cell ID to delete.
///
/// Returns a coroutine.
fn delete_cell<'py>(&self, py: Python<'py>, cell_id: &str) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let cell_id = cell_id.to_string();
future_into_py(py, async move {
let state_guard = state.lock().await;
let handle = state_guard
.handle
.as_ref()
.ok_or_else(|| to_py_err("Not connected"))?;
handle.delete_cell(&cell_id).await.map_err(to_py_err)
})
}
/// Move a cell to a new position in the notebook.
///
/// Updates the cell's fractional index position field. No delete/re-insert —
/// the cell object is preserved in the Automerge document.
///
/// Args:
/// cell_id: The cell ID to move.
/// after_cell_id: Place the cell after this cell ID. None means move to the start.
///
/// Returns:
/// A coroutine that resolves to the new fractional position string.
#[pyo3(signature = (cell_id, after_cell_id=None))]
fn move_cell<'py>(
&self,
py: Python<'py>,
cell_id: &str,
after_cell_id: Option<&str>,
) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let cell_id = cell_id.to_string();
let after_cell_id = after_cell_id.map(|s| s.to_string());
future_into_py(py, async move {
let state_guard = state.lock().await;
let handle = state_guard
.handle
.as_ref()
.ok_or_else(|| to_py_err("Not connected"))?;
handle
.move_cell(&cell_id, after_cell_id.as_deref())
.await
.map_err(to_py_err)
})
}
/// Save the notebook to a .ipynb file.
///
/// Reads cells and metadata from the synced Automerge document, resolves
/// output manifests from the blob store, and writes standard nbformat v4 JSON.
///
/// Args:
/// path: Optional target path for the notebook file. If it doesn't end
/// with .ipynb, the extension will be appended. If None, saves to
/// the notebook's original file path (the notebook_id).
///
/// Returns:
/// A coroutine that resolves to the absolute path where the file was written.
///
/// Raises:
/// RuntimedError: If not connected or write fails.
#[pyo3(signature = (path=None))]
fn save<'py>(&self, py: Python<'py>, path: Option<&str>) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let path = path.map(|s| s.to_string());
future_into_py(py, async move {
let state_guard = state.lock().await;
let handle = state_guard
.handle
.as_ref()
.ok_or_else(|| to_py_err("Not connected"))?;
let response = handle
.send_request(NotebookRequest::SaveNotebook {
format_cells: false,
path,
})
.await
.map_err(to_py_err)?;
match response {
NotebookResponse::NotebookSaved { path } => Ok(path),
NotebookResponse::Error { error } => Err(to_py_err(error)),
other => Err(to_py_err(format!("Unexpected response: {:?}", other))),
}
})
}
// =========================================================================
// Metadata Operations (synced via automerge doc)
// =========================================================================
/// Set a metadata value in the automerge document.
///
/// The value is synced to the daemon and all connected clients.
/// Use the key "notebook_metadata" to set the NotebookMetadataSnapshot
/// (JSON-encoded kernelspec, language_info, and runt config).
///
/// Args:
/// key: The metadata key.
/// value: The metadata value (typically JSON).
///
/// Returns a coroutine.
fn set_metadata<'py>(
&self,
py: Python<'py>,
key: &str,
value: &str,
) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let key = key.to_string();
let value = value.to_string();
future_into_py(py, async move {
let state_guard = state.lock().await;
let handle = state_guard
.handle
.as_ref()
.ok_or_else(|| to_py_err("Not connected"))?;
handle.set_metadata(&key, &value).await.map_err(to_py_err)
})
}
/// Get a metadata value from the automerge document.
///
/// Reads from the local replica of the automerge doc.
///
/// Args:
/// key: The metadata key.
///
/// Returns a coroutine that resolves to the metadata value (str) or None.
fn get_metadata<'py>(&self, py: Python<'py>, key: &str) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let key = key.to_string();
future_into_py(py, async move {
let state_guard = state.lock().await;
let handle = state_guard
.handle
.as_ref()
.ok_or_else(|| to_py_err("Not connected"))?;
handle.get_metadata(&key).await.map_err(to_py_err)
})
}
// =========================================================================
// Dependency Management (convenience methods for notebook_metadata)
// =========================================================================
/// Get current UV dependencies.
///
/// Returns a coroutine that resolves to list of UV dependency specifiers.
fn get_uv_dependencies<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
future_into_py(py, async move {
let snapshot = get_notebook_metadata_async(&state).await?;
Ok(snapshot
.runt
.uv
.map(|uv| uv.dependencies)
.unwrap_or_default())
})
}
/// Add a UV dependency to the notebook.
///
/// Deduplicates by package name (case-insensitive): if a dependency with the
/// same package name already exists, it is replaced with the new specifier.
///
/// Args:
/// package: PEP 508 dependency specifier (e.g., "pandas>=2.0", "requests").
///
/// Returns a coroutine that resolves to None. Callers should use
/// `get_uv_dependencies()` to read current state.
fn add_uv_dependency<'py>(
&self,
py: Python<'py>,
package: &str,
) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let package = package.to_string();
future_into_py(py, async move {
let mut snapshot = get_notebook_metadata_async(&state).await?;
snapshot.add_uv_dependency(&package);
set_notebook_metadata_async(&state, &snapshot).await?;
Ok(())
})
}
/// Remove a UV dependency by package name (case-insensitive, version-agnostic).
///
/// Args:
/// package: Package name to remove (e.g., "pandas"). Version specifiers are ignored.
///
/// Returns a coroutine that resolves to bool indicating if a dependency was removed.
fn remove_uv_dependency<'py>(
&self,
py: Python<'py>,
package: &str,
) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let package = package.to_string();
future_into_py(py, async move {
let mut snapshot = get_notebook_metadata_async(&state).await?;
let removed = snapshot.remove_uv_dependency(&package);
if removed {
set_notebook_metadata_async(&state, &snapshot).await?;
}
Ok(removed)
})
}
/// Get current Conda dependencies.
///
/// Returns a coroutine that resolves to list of Conda package names.
fn get_conda_dependencies<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
future_into_py(py, async move {
let snapshot = get_notebook_metadata_async(&state).await?;
Ok(snapshot
.runt
.conda
.map(|c| c.dependencies)
.unwrap_or_default())
})
}
/// Add a Conda dependency to the notebook.
///
/// Deduplicates by package name (case-insensitive): if a dependency with the
/// same package name already exists, it is replaced with the new specifier.
///
/// Args:
/// package: Conda package specifier (e.g., "numpy", "scipy>=1.0").
///
/// Returns a coroutine that resolves to None. Callers should use
/// `get_conda_dependencies()` to read current state.
fn add_conda_dependency<'py>(
&self,
py: Python<'py>,
package: &str,
) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let package = package.to_string();
future_into_py(py, async move {
let mut snapshot = get_notebook_metadata_async(&state).await?;
snapshot.add_conda_dependency(&package);
set_notebook_metadata_async(&state, &snapshot).await?;
Ok(())
})
}
/// Remove a Conda dependency by package name (case-insensitive, version-agnostic).
///
/// Args:
/// package: Package name to remove (e.g., "numpy"). Version specifiers are ignored.
///
/// Returns a coroutine that resolves to bool indicating if a dependency was removed.
fn remove_conda_dependency<'py>(
&self,
py: Python<'py>,
package: &str,
) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let package = package.to_string();
future_into_py(py, async move {
let mut snapshot = get_notebook_metadata_async(&state).await?;
let removed = snapshot.remove_conda_dependency(&package);
if removed {
set_notebook_metadata_async(&state, &snapshot).await?;
}
Ok(removed)
})
}
// =========================================================================
// Execution (document-first: reads source from automerge doc)
// =========================================================================
/// Execute a cell by ID.
///
/// The daemon reads the cell's source from the automerge document and
/// executes it. This ensures all clients see the same code being executed.
///
/// If a kernel isn't running yet, this will start one automatically.
/// If a kernel is already running in the daemon (e.g., started by another
/// client), it will reuse that kernel.
///
/// Args:
/// cell_id: The cell ID to execute.
/// timeout_secs: Maximum time to wait for execution (default: 60).
///
/// Returns a coroutine that resolves to ExecutionResult.
///
/// Raises:
/// RuntimedError: If not connected, cell not found, or timeout.
#[pyo3(signature = (cell_id, timeout_secs=60.0))]
fn execute_cell<'py>(
&self,
py: Python<'py>,
cell_id: &str,
timeout_secs: f64,
) -> PyResult<Bound<'py, PyAny>> {
let state = Arc::clone(&self.state);
let notebook_id = self.notebook_id.clone();
let cell_id = cell_id.to_string();
future_into_py(py, async move {
// Auto-start kernel if not running
{
let state_guard = state.lock().await;
if !state_guard.kernel_started {
drop(state_guard);
// Need to connect and start kernel
let state_guard = state.lock().await;
if state_guard.handle.is_none() {
drop(state_guard);