-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathagent_os.rs
More file actions
4208 lines (3966 loc) · 164 KB
/
Copy pathagent_os.rs
File metadata and controls
4208 lines (3966 loc) · 164 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
//! The `AgentOs` struct (all fields from ADR-001 §3), the `create` builder, and the `shutdown`
//! (dispose) teardown.
//!
//! `AgentOs` is `Arc`-cloneable; all interior state lives behind concurrent maps / atomics /
//! channels so `&self` methods never need an outer lock. Module files add only `impl AgentOs` blocks
//! and never introduce new struct fields.
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::io::Write;
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Weak};
use std::time::Duration;
use scc::{HashMap as SccHashMap, HashSet as SccHashSet};
use serde::Deserialize;
use serde_json::{Map, Value};
use tokio::sync::{broadcast, oneshot, watch};
use tokio::task::JoinHandle;
use agentos_protocol::generated::v1::{
AcpCallback, AcpCallbackResponse, AcpEvent, AcpHostRequestCallbackResponse,
AcpPermissionCallbackResponse,
};
use agentos_protocol::ACP_EXTENSION_NAMESPACE;
use secure_exec_client::wire;
use secure_exec_vm_config as vm_config;
use crate::config::{
AgentOsConfig, AgentOsLimits, HostTool, MountConfig, PermissionMode, Permissions,
RootFilesystemConfig, RootFilesystemKind, RootFilesystemMode as ConfigRootFilesystemMode,
RootLowerInput, SidecarJsBridgeCall, SidecarJsBridgeCallback,
TimerScheduleDriver, ToolKit,
};
use crate::cron::CronManager;
use crate::error::ClientError;
use crate::json_rpc::JsonRpcNotification;
use crate::process::SYNTHETIC_PID_BASE;
use crate::session::{
record_live_session_event, AgentCapabilities, AgentExitEvent, AgentInfo, PermissionReply,
PermissionRequest, PermissionRouteRequest, PermissionRouteResult, SessionConfigOption,
SessionModeState,
};
use crate::sidecar::{AgentOsSidecar, AgentOsSidecarPlacement, AgentOsSidecarVmLease};
use crate::transport::{SidecarProcess, WireSidecarCallback};
use secure_exec_client::TransportError;
use once_cell::sync::OnceCell;
// ---------------------------------------------------------------------------
// Registry entries
// ---------------------------------------------------------------------------
/// An SDK-spawned process (TS `_processes` value). Keyed by user-facing pid.
pub(crate) struct ProcessEntry {
pub command: String,
pub args: Vec<String>,
pub stdout_tx: broadcast::Sender<Vec<u8>>,
pub stderr_tx: broadcast::Sender<Vec<u8>>,
/// Seeded `None`; the already-exited branch fires immediately once it holds `Some(code)`.
pub exit_tx: watch::Sender<Option<i32>>,
/// The sidecar-side process id used on the wire.
pub process_id: String,
/// The kernel pid returned by the `Execute` response, seeded once the spawn lands. The TS native
/// path builds `displayPidByKernelPid` from this so `all_processes`/`process_tree` report the
/// public spawn pid (the map key) for the spawned root, not the raw kernel pid.
pub kernel_pid: watch::Sender<Option<u32>>,
/// Handles for the per-process output-callback tasks seeded at spawn (`on_stdout`/`on_stderr`).
/// The entry retains its own `stdout_tx`/`stderr_tx` clones for late subscribers, so these tasks
/// never observe the broadcast `Closed`; `shutdown` aborts them when draining the registry.
pub output_tasks: Vec<JoinHandle<()>>,
/// Epoch milliseconds captured when `spawn` registered this process (TS `Date.now()`).
pub started_at: i64,
}
/// A PTY-backed shell (TS `_shells` value). Keyed by synthetic `shell-N` id.
///
/// `data_tx` carries stdout only, matching TS where the kernel handle's `onData` is fed exclusively
/// by `stdoutHandlers`. `stderr_tx` is the dedicated stderr channel that backs the `on_stderr` option
/// and `on_shell_stderr`, matching TS where stderr reaches the host only through `stderrHandlers`.
pub(crate) struct ShellEntry {
pub pid: u32,
pub data_tx: broadcast::Sender<Vec<u8>>,
pub stderr_tx: broadcast::Sender<Vec<u8>>,
/// The sidecar-side process id used on the wire.
pub process_id: String,
/// Spawn-readiness gate. Seeded `false`; flips to `true` once the background `Execute` request is
/// acked. TS `openShell` is fully synchronous so `writeShell` always addresses a live spawn; the
/// Rust wire spawn is async, so `write_shell`/`close_shell` await this gate before issuing their
/// wire request to preserve the deterministic ordering and avoid dropping early input.
pub spawned_tx: watch::Sender<bool>,
/// Exit-code channel backing `wait_shell` (TS `ShellHandle.wait`). Seeded `None`; the background
/// event loop publishes `Some(exit_code)` when the shell process exits.
pub exit_tx: watch::Sender<Option<i32>>,
}
/// A connected ACP terminal process and its output fan-out task.
pub(crate) struct AcpTerminalEntry {
pub exit_task: JoinHandle<()>,
}
/// Mutable output state of a host-request ACP terminal (mirrors the TS `AcpTerminalEntry`
/// `output` / `truncated` accumulation behavior).
pub(crate) struct HostAcpTerminalOutput {
/// Accumulated UTF-8 terminal output (stdout + stderr interleaved, like the TS handle).
pub buffer: String,
pub truncated: bool,
/// Byte limit; `output` is trimmed from the front once it exceeds this. Mirrors the TS
/// `outputByteLimit` (default 1 MiB).
pub output_byte_limit: usize,
}
/// A host-request ACP terminal created via `terminal/create` (mirrors the TS `_acpTerminals`
/// value). Backed by a real PTY shell (`open_shell`); the background fan-out task accumulates
/// output and records the exit code.
pub(crate) struct HostAcpTerminal {
/// The backing shell id (`shell-N`) used for `terminal/write` / `terminal/resize` /
/// `terminal/kill`.
pub shell_id: String,
/// Shared output buffer updated by the fan-out task and read by `terminal/output`.
pub output: Arc<parking_lot::Mutex<HostAcpTerminalOutput>>,
/// Exit code once the process has exited (`None` while running). Mirrors `exitCode`.
pub exit_rx: watch::Receiver<Option<i32>>,
}
/// An ACP session (TS `_sessions` value). Keyed by ACP session id.
pub(crate) struct SessionEntry {
pub agent_type: String,
pub modes: parking_lot::Mutex<Option<SessionModeState>>,
pub config_options: parking_lot::Mutex<Vec<SessionConfigOption>>,
pub capabilities: parking_lot::Mutex<Option<AgentCapabilities>>,
pub agent_info: parking_lot::Mutex<Option<AgentInfo>>,
pub config_overrides: parking_lot::Mutex<std::collections::BTreeMap<String, String>>,
pub event_tx: broadcast::Sender<JsonRpcNotification>,
pub permission_tx: broadcast::Sender<PermissionRequest>,
pub agent_exit_tx: broadcast::Sender<AgentExitEvent>,
pub pending_permission_replies: SccHashMap<String, oneshot::Sender<PermissionReply>>,
pub pending_session_request_lock: parking_lot::Mutex<()>,
/// Pending prompt resolvers, for cancel prompt-fallback + abort-on-close.
///
/// The resolver carries the intended [`JsonRpcResponse`], mirroring the TS resolver shape
/// `{ method, resolve: (response) => void }`. The cause (close vs cancel) decides the payload at
/// the abort/cancel site: abort-on-close resolves with the `-32000` `Session closed: <id>` error,
/// while prompt-cancel resolves with `{ result: { stopReason: "cancelled" } }`. The shape is NOT
/// re-derived from the method downstream.
pub pending_prompt_resolvers:
SccHashMap<i64, oneshot::Sender<crate::json_rpc::JsonRpcResponse>>,
}
// ---------------------------------------------------------------------------
// AgentOs
// ---------------------------------------------------------------------------
/// A self-contained agentOS package to link into a running VM via
/// [`AgentOs::link_software`]. The descriptor is forwarded to the sidecar, which
/// owns the `/opt/agentos` projection (builds the staging tree, derives commands,
/// reads the version from the package's `package.json`).
#[derive(Debug, Clone)]
pub struct PackageDescriptor {
pub name: String,
pub dir: String,
/// `bin/` command that speaks ACP over stdio, if this is an agent package.
pub acp_entrypoint: Option<String>,
}
/// The high-level client. Cheaply cloneable via `Arc`.
#[derive(Clone)]
pub struct AgentOs {
inner: Arc<AgentOsInner>,
}
pub(crate) struct AgentOsInner {
// Transport / connection / VM handle.
pub(crate) transport: Arc<SidecarProcess>,
pub(crate) connection_id: String,
pub(crate) session_id: String,
pub(crate) vm_id: String,
pub(crate) request_counter: AtomicI64,
/// Command names linked at runtime via `link_software` (the sidecar owns the
/// `/opt/agentos` staging dir; this just tracks what we've asked it to link).
pub(crate) linked_commands: parking_lot::Mutex<std::collections::HashSet<String>>,
// Process registries.
pub(crate) process_registry_lock: parking_lot::Mutex<()>,
pub(crate) processes: SccHashMap<u32, ProcessEntry>,
/// Wire `process_id` allocator for `exec` (the kernel-process view). Distinct from the
/// spawn synthetic-pid space so an `exec` call never perturbs the observable `spawn` pid sequence
/// (TS `nextSyntheticPid` is advanced only by `spawn`, never by `exec`).
pub(crate) process_counter: AtomicU64,
/// Synthetic display-pid allocator for `spawn` (TS `nextSyntheticPid`, seeded at
/// [`crate::process::SYNTHETIC_PID_BASE`]). The first spawned process gets `SYNTHETIC_PID_BASE`.
pub(crate) synthetic_pid_counter: AtomicU64,
pub(crate) observed_process_time_lock: parking_lot::Mutex<()>,
/// First-observed start time (epoch ms) per `"<process_id>:<kernel_pid>"`, mirroring TS
/// `observedProcessStartTimes`. A process keeps the timestamp first seen in `all_processes` across
/// later calls instead of advancing on every snapshot.
pub(crate) observed_process_start_times: SccHashMap<String, f64>,
/// First-observed exit time (epoch ms) per SDK-spawned wire `process_id`, mirroring TS
/// `tracked.exitTime` (set once when the process is first seen exited).
pub(crate) observed_process_exit_times: SccHashMap<String, f64>,
// Shell registries.
pub(crate) shells: SccHashMap<String, ShellEntry>,
pub(crate) shell_counter: AtomicU64,
pub(crate) pending_shell_exits: SccHashMap<u64, JoinHandle<()>>,
/// Bounded ordered map (cap [`crate::CLOSED_SHELL_EXIT_CODE_RETENTION_LIMIT`]) of exited shells'
/// exit codes, so `wait_shell` issued after the shell already exited (entry dropped from
/// `shells`) still resolves with the recorded code — mirrors the TS `_closedShellIds` retention.
pub(crate) closed_shell_exit_codes: parking_lot::Mutex<VecDeque<(String, i32)>>,
pub(crate) acp_terminals: SccHashMap<String, AcpTerminalEntry>,
pub(crate) acp_terminal_count: AtomicUsize,
pub(crate) acp_terminal_lifecycle_lock: tokio::sync::Mutex<()>,
/// Host-request ACP terminals created via `terminal/create` (TS `_acpTerminals`). Keyed by the
/// `acp-terminal-N` id the agent uses in subsequent `terminal/*` calls.
pub(crate) host_acp_terminals: SccHashMap<String, HostAcpTerminal>,
/// Monotonic counter for the `acp-terminal-N` ids (TS `_acpTerminalCounter`).
pub(crate) host_acp_terminal_counter: AtomicU64,
// Session registries.
pub(crate) sessions: SccHashMap<String, SessionEntry>,
/// Bounded ordered set (cap [`crate::CLOSED_SESSION_ID_RETENTION_LIMIT`]) for close idempotence.
pub(crate) closed_session_ids: parking_lot::Mutex<VecDeque<String>>,
/// Session ids with an in-flight close in progress. Mirrors TS `_sessionClosePromises`: because
/// `close_session` runs the actual close on a detached task, this set keeps the id "known" during
/// the window between removal from `sessions` and insertion into `closed_session_ids`, so a second
/// `close_session` (or close-after-destroy) does not spuriously throw `SessionNotFound`.
pub(crate) closing_session_ids: SccHashSet<String>,
// Cron.
pub(crate) cron: Arc<CronManager>,
// Config / lifecycle.
pub(crate) config: Arc<AgentOsConfig>,
pub(crate) sidecar: Arc<AgentOsSidecar>,
pub(crate) sidecar_lease: parking_lot::Mutex<Option<AgentOsSidecarVmLease>>,
pub(crate) in_process_mounts: SccHashMap<String, crate::fs::MountedFs>,
pub(crate) disposed: AtomicBool,
/// Handle for the background ACP event-pump task (`spawn_acp_event_pump`). Stored so `shutdown`
/// can abort it; the pump only exits on its own when the shared transport's event channel closes,
/// which does not happen while sibling VMs keep the transport alive. Mirrors `pending_shell_exits`.
pub(crate) acp_event_pump: parking_lot::Mutex<Option<JoinHandle<()>>>,
}
impl AgentOs {
/// The sole public VM entry point. Processes software, spawns/authenticates the sidecar, creates
/// the VM, waits for ready (10s), configures it, takes a lease, and constructs the cron manager
/// (default [`crate::config::TimerScheduleDriver`]).
pub async fn create(options: AgentOsConfig) -> Result<AgentOs, ClientError> {
let config = Arc::new(options);
// 1. Resolve the sidecar handle (shared "default" pool unless configured otherwise) and
// establish/reuse its shared process + authenticated connection. A shared sidecar hosts
// multiple VMs in one process, each opening its own session + VM below.
let sidecar = match &config.sidecar {
Some(crate::config::AgentOsSidecarConfig::Explicit { handle }) => handle.clone(),
Some(crate::config::AgentOsSidecarConfig::Shared { pool }) => {
AgentOs::get_shared_sidecar(pool.clone(), config.sidecar_binary_path.clone())
.await?
}
None => AgentOs::get_shared_sidecar(None, config.sidecar_binary_path.clone()).await?,
};
let (transport, connection_id, _) = sidecar.ensure_connection().await?;
// 2. Open a session for this VM (connection scope) on the shared connection.
let session = match transport
.request_wire(
wire_connection_ownership(&connection_id),
wire::RequestPayload::OpenSessionRequest(wire::OpenSessionRequest {
placement: sidecar_wire_placement(&sidecar),
metadata: HashMap::new(),
}),
)
.await?
{
wire::ResponsePayload::SessionOpenedResponse(opened) => opened,
wire::ResponsePayload::RejectedResponse(rejected) => {
return Err(rejected_to_error(rejected));
}
wire::ResponsePayload::AuthenticatedResponse(_)
| wire::ResponsePayload::VmCreatedResponse(_)
| wire::ResponsePayload::VmDisposedResponse(_)
| wire::ResponsePayload::RootFilesystemBootstrappedResponse(_)
| wire::ResponsePayload::VmConfiguredResponse(_)
| wire::ResponsePayload::HostCallbacksRegisteredResponse(_)
| wire::ResponsePayload::LayerCreatedResponse(_)
| wire::ResponsePayload::LayerSealedResponse(_)
| wire::ResponsePayload::SnapshotImportedResponse(_)
| wire::ResponsePayload::SnapshotExportedResponse(_)
| wire::ResponsePayload::OverlayCreatedResponse(_)
| wire::ResponsePayload::GuestFilesystemResultResponse(_)
| wire::ResponsePayload::RootFilesystemSnapshotResponse(_)
| wire::ResponsePayload::ProcessStartedResponse(_)
| wire::ResponsePayload::StdinWrittenResponse(_)
| wire::ResponsePayload::PtyResizedResponse(_)
| wire::ResponsePayload::StdinClosedResponse(_)
| wire::ResponsePayload::ProcessKilledResponse(_)
| wire::ResponsePayload::ProcessSnapshotResponse(_)
| wire::ResponsePayload::ListenerSnapshotResponse(_)
| wire::ResponsePayload::BoundUdpSnapshotResponse(_)
| wire::ResponsePayload::SignalStateResponse(_)
| wire::ResponsePayload::ZombieTimerCountResponse(_)
| wire::ResponsePayload::FilesystemResultResponse(_)
| wire::ResponsePayload::PermissionDecisionResponse(_)
| wire::ResponsePayload::PersistenceStateResponse(_)
| wire::ResponsePayload::PersistenceFlushedResponse(_)
| wire::ResponsePayload::VmFetchResponse(_)
| wire::ResponsePayload::ExtEnvelope(_)
| wire::ResponsePayload::GuestKernelResultResponse(_)
| wire::ResponsePayload::ResourceSnapshotResponse(_)
| wire::ResponsePayload::PackageLinkedResponse(_) => {
return Err(ClientError::Sidecar(
"unexpected open_session response".to_string(),
));
}
};
let session_id = session.session_id;
// 3. Subscribe to events BEFORE CreateVm so the `ready` lifecycle event cannot be missed.
let mut events = transport.subscribe_wire_events();
let permissions = permissions_policy(&config);
let create_vm_config = serialize_create_vm_config_for_sidecar(&config)?;
if let Some(callback) = config.sidecar_js_bridge_callback.clone() {
let _ = session_js_bridge_callbacks()
.insert(sidecar_session_key(&connection_id, &session_id), callback);
transport.register_wire_callback("js_bridge_call", js_bridge_call_callback());
}
// 4. Create the VM (session scope).
let vm = match transport
.request_wire(
wire_session_ownership(&connection_id, &session_id),
wire::RequestPayload::CreateVmRequest(wire::CreateVmRequest {
runtime: wire::GuestRuntimeKind::JavaScript,
config: serde_json::to_string(&create_vm_config).map_err(|error| {
ClientError::Sidecar(format!(
"failed to serialize create VM config: {error}"
))
})?,
}),
)
.await?
{
wire::ResponsePayload::VmCreatedResponse(created) => created,
wire::ResponsePayload::RejectedResponse(rejected) => {
return Err(rejected_to_error(rejected));
}
wire::ResponsePayload::AuthenticatedResponse(_)
| wire::ResponsePayload::SessionOpenedResponse(_)
| wire::ResponsePayload::VmDisposedResponse(_)
| wire::ResponsePayload::RootFilesystemBootstrappedResponse(_)
| wire::ResponsePayload::VmConfiguredResponse(_)
| wire::ResponsePayload::HostCallbacksRegisteredResponse(_)
| wire::ResponsePayload::LayerCreatedResponse(_)
| wire::ResponsePayload::LayerSealedResponse(_)
| wire::ResponsePayload::SnapshotImportedResponse(_)
| wire::ResponsePayload::SnapshotExportedResponse(_)
| wire::ResponsePayload::OverlayCreatedResponse(_)
| wire::ResponsePayload::GuestFilesystemResultResponse(_)
| wire::ResponsePayload::RootFilesystemSnapshotResponse(_)
| wire::ResponsePayload::ProcessStartedResponse(_)
| wire::ResponsePayload::StdinWrittenResponse(_)
| wire::ResponsePayload::PtyResizedResponse(_)
| wire::ResponsePayload::StdinClosedResponse(_)
| wire::ResponsePayload::ProcessKilledResponse(_)
| wire::ResponsePayload::ProcessSnapshotResponse(_)
| wire::ResponsePayload::ListenerSnapshotResponse(_)
| wire::ResponsePayload::BoundUdpSnapshotResponse(_)
| wire::ResponsePayload::SignalStateResponse(_)
| wire::ResponsePayload::ZombieTimerCountResponse(_)
| wire::ResponsePayload::FilesystemResultResponse(_)
| wire::ResponsePayload::PermissionDecisionResponse(_)
| wire::ResponsePayload::PersistenceStateResponse(_)
| wire::ResponsePayload::PersistenceFlushedResponse(_)
| wire::ResponsePayload::VmFetchResponse(_)
| wire::ResponsePayload::ExtEnvelope(_)
| wire::ResponsePayload::GuestKernelResultResponse(_)
| wire::ResponsePayload::ResourceSnapshotResponse(_)
| wire::ResponsePayload::PackageLinkedResponse(_) => {
return Err(ClientError::Sidecar(
"unexpected create_vm response".to_string(),
));
}
};
let vm_id = vm.vm_id;
// 5. Wait for the VM to reach `ready` (bounded by VM_READY_TIMEOUT_MS).
wait_for_vm_ready(&mut events, &vm_id, crate::VM_READY_TIMEOUT_MS).await?;
// Resolve software packages to host roots (port of TS `processSoftware` for the
// ConfigureVm descriptors). Each `package` is resolved under `module_access_cwd/node_modules`;
// an unresolvable package is an explicit error rather than a silent no-op. Wasm command
// packages additionally become `/__secure_exec/commands/{index}/` mounts so the sidecar can
// discover and resolve guest commands.
// Build the package-projection descriptors from the configured package dirs.
// Each package's name (and optional ACP entrypoint) is read from its
// `agentos-package.json`; the sidecar reads commands/version from the dir and
// builds the `/opt/agentos` projection. Runtime `link_software` appends to it.
let packages = build_package_descriptors(&config)?;
// Native plugin mounts configured on the client.
let mounts = serialize_mounts(&config)?;
// 6. Configure the VM (vm scope). The sidecar owns the `/opt/agentos` package
// projection: it builds the staging dir + registers the read-only host_dir
// mount itself from the forwarded `packages`.
match transport
.request_wire(
wire_vm_ownership(&connection_id, &session_id, &vm_id),
wire::RequestPayload::ConfigureVmRequest(wire::ConfigureVmRequest {
mounts,
// The legacy `software`/SoftwareDescriptor provisioning path is
// retired: all boot software is projected via `packages`.
software: Vec::new(),
permissions: Some(permissions),
module_access_cwd: config.module_access_cwd.clone(),
instructions: config.additional_instructions.clone().into_iter().collect(),
projected_modules: Vec::new(),
command_permissions: HashMap::new(),
loopback_exempt_ports: config.loopback_exempt_ports.clone(),
packages,
packages_mount_at: config.packages_mount_at.clone().unwrap_or_default(),
}),
)
.await?
{
wire::ResponsePayload::VmConfiguredResponse(_) => {}
wire::ResponsePayload::RejectedResponse(rejected) => {
return Err(rejected_to_error(rejected));
}
wire::ResponsePayload::AuthenticatedResponse(_)
| wire::ResponsePayload::SessionOpenedResponse(_)
| wire::ResponsePayload::VmCreatedResponse(_)
| wire::ResponsePayload::VmDisposedResponse(_)
| wire::ResponsePayload::RootFilesystemBootstrappedResponse(_)
| wire::ResponsePayload::HostCallbacksRegisteredResponse(_)
| wire::ResponsePayload::LayerCreatedResponse(_)
| wire::ResponsePayload::LayerSealedResponse(_)
| wire::ResponsePayload::SnapshotImportedResponse(_)
| wire::ResponsePayload::SnapshotExportedResponse(_)
| wire::ResponsePayload::OverlayCreatedResponse(_)
| wire::ResponsePayload::GuestFilesystemResultResponse(_)
| wire::ResponsePayload::RootFilesystemSnapshotResponse(_)
| wire::ResponsePayload::ProcessStartedResponse(_)
| wire::ResponsePayload::StdinWrittenResponse(_)
| wire::ResponsePayload::PtyResizedResponse(_)
| wire::ResponsePayload::StdinClosedResponse(_)
| wire::ResponsePayload::ProcessKilledResponse(_)
| wire::ResponsePayload::ProcessSnapshotResponse(_)
| wire::ResponsePayload::ListenerSnapshotResponse(_)
| wire::ResponsePayload::BoundUdpSnapshotResponse(_)
| wire::ResponsePayload::SignalStateResponse(_)
| wire::ResponsePayload::ZombieTimerCountResponse(_)
| wire::ResponsePayload::FilesystemResultResponse(_)
| wire::ResponsePayload::PermissionDecisionResponse(_)
| wire::ResponsePayload::PersistenceStateResponse(_)
| wire::ResponsePayload::PersistenceFlushedResponse(_)
| wire::ResponsePayload::VmFetchResponse(_)
| wire::ResponsePayload::ExtEnvelope(_)
| wire::ResponsePayload::GuestKernelResultResponse(_)
| wire::ResponsePayload::ResourceSnapshotResponse(_)
| wire::ResponsePayload::PackageLinkedResponse(_) => {
return Err(ClientError::Sidecar(
"unexpected configure_vm response".to_string(),
));
}
}
// 6b. Register host tool kits (if any): forward each tool definition via `register_host_callbacks`,
// record the host execute callbacks in the per-VM registry, and install the shared
// host-callback that routes guest tool calls back to the host by VM.
if !config.tool_kits.is_empty() {
let mut tool_map: HashMap<String, HostTool> = HashMap::new();
for kit in &config.tool_kits {
let mut tools = HashMap::new();
for tool in &kit.tools {
tools.insert(
tool.name.clone(),
wire::RegisteredHostCallbackDefinition {
description: tool.description.clone(),
input_schema: json_utf8(
&tool.input_schema,
"host callback input schema",
)?,
timeout_ms: tool.timeout_ms,
examples: Vec::new(),
},
);
tool_map.insert(format!("{}:{}", kit.name, tool.name), tool.clone());
}
match transport
.request_wire(
wire_vm_ownership(&connection_id, &session_id, &vm_id),
wire::RequestPayload::RegisterHostCallbacksRequest(
wire::RegisterHostCallbacksRequest {
name: kit.name.clone(),
description: kit.description.clone(),
command_aliases: vec![format!("agentos-{}", kit.name)],
registry_command_aliases: vec![String::from("agentos")],
callbacks: tools,
},
),
)
.await?
{
wire::ResponsePayload::HostCallbacksRegisteredResponse(_) => {}
wire::ResponsePayload::RejectedResponse(rejected) => {
return Err(rejected_to_error(rejected));
}
wire::ResponsePayload::AuthenticatedResponse(_)
| wire::ResponsePayload::SessionOpenedResponse(_)
| wire::ResponsePayload::VmCreatedResponse(_)
| wire::ResponsePayload::VmDisposedResponse(_)
| wire::ResponsePayload::RootFilesystemBootstrappedResponse(_)
| wire::ResponsePayload::VmConfiguredResponse(_)
| wire::ResponsePayload::LayerCreatedResponse(_)
| wire::ResponsePayload::LayerSealedResponse(_)
| wire::ResponsePayload::SnapshotImportedResponse(_)
| wire::ResponsePayload::SnapshotExportedResponse(_)
| wire::ResponsePayload::OverlayCreatedResponse(_)
| wire::ResponsePayload::GuestFilesystemResultResponse(_)
| wire::ResponsePayload::RootFilesystemSnapshotResponse(_)
| wire::ResponsePayload::ProcessStartedResponse(_)
| wire::ResponsePayload::StdinWrittenResponse(_)
| wire::ResponsePayload::PtyResizedResponse(_)
| wire::ResponsePayload::StdinClosedResponse(_)
| wire::ResponsePayload::ProcessKilledResponse(_)
| wire::ResponsePayload::ProcessSnapshotResponse(_)
| wire::ResponsePayload::ListenerSnapshotResponse(_)
| wire::ResponsePayload::BoundUdpSnapshotResponse(_)
| wire::ResponsePayload::SignalStateResponse(_)
| wire::ResponsePayload::ZombieTimerCountResponse(_)
| wire::ResponsePayload::FilesystemResultResponse(_)
| wire::ResponsePayload::PermissionDecisionResponse(_)
| wire::ResponsePayload::PersistenceStateResponse(_)
| wire::ResponsePayload::PersistenceFlushedResponse(_)
| wire::ResponsePayload::VmFetchResponse(_)
| wire::ResponsePayload::ExtEnvelope(_)
| wire::ResponsePayload::GuestKernelResultResponse(_)
| wire::ResponsePayload::ResourceSnapshotResponse(_)
| wire::ResponsePayload::PackageLinkedResponse(_) => {
return Err(ClientError::Sidecar(
"unexpected register_host_callbacks response".to_string(),
));
}
}
}
let _ = vm_tools().insert(
vm_id.clone(),
Arc::new(VmHostToolRegistry {
tool_kits: config.tool_kits.clone(),
tool_map,
permissions: config.permissions.clone(),
}),
);
transport.register_wire_callback("host_callback", host_callback_callback());
}
// 7. Lease this VM on the (possibly shared) sidecar, build cron, and assemble the client.
sidecar.active_vm_count.fetch_add(1, Ordering::SeqCst);
let lease = AgentOsSidecarVmLease {
sidecar: sidecar.clone(),
};
let driver = config
.schedule_driver
.clone()
.unwrap_or_else(|| Arc::new(TimerScheduleDriver::new()));
let cron = Arc::new(CronManager::new(driver));
let inner = AgentOsInner {
transport,
connection_id,
session_id,
vm_id,
request_counter: AtomicI64::new(1),
linked_commands: parking_lot::Mutex::new(std::collections::HashSet::new()),
process_registry_lock: parking_lot::Mutex::new(()),
processes: SccHashMap::new(),
process_counter: AtomicU64::new(1),
synthetic_pid_counter: AtomicU64::new(SYNTHETIC_PID_BASE),
observed_process_time_lock: parking_lot::Mutex::new(()),
observed_process_start_times: SccHashMap::new(),
observed_process_exit_times: SccHashMap::new(),
shells: SccHashMap::new(),
shell_counter: AtomicU64::new(0),
pending_shell_exits: SccHashMap::new(),
closed_shell_exit_codes: parking_lot::Mutex::new(VecDeque::new()),
acp_terminals: SccHashMap::new(),
acp_terminal_count: AtomicUsize::new(0),
acp_terminal_lifecycle_lock: tokio::sync::Mutex::new(()),
host_acp_terminals: SccHashMap::new(),
host_acp_terminal_counter: AtomicU64::new(0),
sessions: SccHashMap::new(),
closed_session_ids: parking_lot::Mutex::new(VecDeque::new()),
closing_session_ids: SccHashSet::new(),
cron,
config,
sidecar,
sidecar_lease: parking_lot::Mutex::new(Some(lease)),
in_process_mounts: SccHashMap::new(),
disposed: AtomicBool::new(false),
acp_event_pump: parking_lot::Mutex::new(None),
};
let client = AgentOs {
inner: Arc::new(inner),
};
// Register the permission router and callback unconditionally (unlike `host_callback`,
// which is gated on configured tool kits): any agent session can raise a permission
// request. Re-registering on a shared transport replaces an identical stateless callback,
// same as the `host_callback` pattern.
let _ = vm_permission_routers()
.insert(client.inner.vm_id.clone(), Arc::downgrade(&client.inner));
client
.inner
.transport
.register_wire_callback("ext", permission_request_callback());
spawn_acp_event_pump(&client);
Ok(client)
}
/// Dispose the VM (= TS `dispose`). Teardown order:
/// 1. cron dispose
/// 2. close all sessions (swallow errors)
/// 3. kill all shells + snapshot pending exits
/// 4. kill all ACP terminals
/// 5. drain tracked shell-exit tasks (two-phase, bounded by
/// [`crate::SHELL_DISPOSE_TIMEOUT_MS`])
/// 6. unregister the sidecar event listener
/// 7. release the lease (or tear down the transport)
///
/// Idempotent (guarded by `disposed`).
/// Dynamically link a software package into the RUNNING VM (parity with the
/// TS client's `linkSoftware`). Forwarded to the sidecar, which owns the
/// `/opt/agentos` projection and appends the package to its live staging dir,
/// so the package's commands appear under `/opt/agentos/bin` (on `$PATH`)
/// immediately with no reboot. Errors if a command name is already linked.
pub async fn link_software(&self, descriptor: PackageDescriptor) -> Result<(), ClientError> {
let inner = self.inner();
let response = self
.transport()
.request_wire(
wire_vm_ownership(&inner.connection_id, &inner.session_id, &inner.vm_id),
wire::RequestPayload::LinkPackageRequest(wire::LinkPackageRequest {
// The wire `PackageDescriptor` carries only `{ dir }`; the
// sidecar reads `name`/`acpEntrypoint` from the package's
// `agentos-package.json` at `dir`.
package: wire::PackageDescriptor {
dir: descriptor.dir,
},
}),
)
.await?;
match response {
wire::ResponsePayload::PackageLinkedResponse(linked) => {
let mut guard = inner.linked_commands.lock();
for cmd in linked.commands {
guard.insert(cmd);
}
Ok(())
}
wire::ResponsePayload::RejectedResponse(rejected) => Err(rejected_to_error(rejected)),
other => Err(ClientError::Sidecar(format!(
"unexpected link_package response: {other:?}"
))),
}
}
pub async fn shutdown(&self) -> Result<(), ClientError> {
// Idempotent: only the first caller runs teardown.
if self.inner.disposed.swap(true, Ordering::SeqCst) {
return Ok(());
}
// The `/opt/agentos` projection staging dir is owned + cleaned up by the
// sidecar on VM dispose, so the client no longer removes it here.
// 1. Cron dispose (cancel armed timers + tear down the driver).
self.inner.cron.dispose();
// Abort the background ACP event pump and drain the SDK-spawned process registry. Neither
// ends on its own while a shared transport stays alive: the pump only exits on transport
// close, and the per-process output tasks await a broadcast `Closed` that the entry's own
// retained sender clones prevent. Aborting + clearing here stops both from leaking past
// dispose.
abort_tracked_task(&self.inner.acp_event_pump);
crate::process::drain_process_output_tasks(&self.inner.processes);
// 2-5. Best-effort drain tracked shell and terminal tasks before the VM is disposed, bounded
// by SHELL_DISPOSE_TIMEOUT_MS so late output cannot race a closed transport.
let mut exit_tasks = Vec::new();
self.inner.pending_shell_exits.retain(|_, task| {
exit_tasks.push(std::mem::replace(task, tokio::spawn(async {})));
false
});
{
let _terminal_lifecycle_guard = self.inner.acp_terminal_lifecycle_lock.lock().await;
let mut terminal_entries = Vec::new();
self.inner.acp_terminals.retain(|process_id, entry| {
terminal_entries.push((
process_id.clone(),
std::mem::replace(&mut entry.exit_task, tokio::spawn(async {})),
));
false
});
self.inner.acp_terminal_count.store(0, Ordering::SeqCst);
for (process_id, _) in &terminal_entries {
let transport = self.transport().clone();
let ownership = wire::OwnershipScope::VmOwnership(wire::VmOwnership {
connection_id: self.inner.connection_id.clone(),
session_id: self.inner.session_id.clone(),
vm_id: self.inner.vm_id.clone(),
});
let process_id = process_id.clone();
exit_tasks.push(tokio::spawn(async move {
let _ = transport
.request_wire(
ownership,
wire::RequestPayload::KillProcessRequest(wire::KillProcessRequest {
process_id,
signal: String::from("SIGTERM"),
}),
)
.await;
}));
}
for (_, task) in terminal_entries {
exit_tasks.push(task);
}
}
// Tear down host-request ACP terminals (`terminal/create`). Close the backing shell, which
// sends SIGTERM, removes the shell entry, and ends the fan-out/exit task; the task itself is
// tracked in `pending_shell_exits` above and drained with the other shell exit tasks.
let mut host_terminal_shells = Vec::new();
self.inner.host_acp_terminals.retain(|_, terminal| {
host_terminal_shells.push(terminal.shell_id.clone());
false
});
for shell_id in host_terminal_shells {
let _ = self.close_shell(&shell_id);
}
if !exit_tasks.is_empty() {
let mut drain_tasks = exit_tasks;
if tokio::time::timeout(
Duration::from_millis(crate::SHELL_DISPOSE_TIMEOUT_MS),
futures::future::join_all(drain_tasks.iter_mut()),
)
.await
.is_err()
{
for task in drain_tasks {
task.abort();
}
}
}
// 6-7. Release this VM (DisposeVm best-effort) and its lease. The transport is shared across
// VMs on the same sidecar, so it is only torn down when this was the last VM (matching
// the TS lease/shared-sidecar lifecycle); otherwise sibling VMs keep using it.
let lease = self.inner.sidecar_lease.lock().take();
let _ = self
.transport()
.request_wire(
wire::OwnershipScope::VmOwnership(wire::VmOwnership {
connection_id: self.inner.connection_id.clone(),
session_id: self.inner.session_id.clone(),
vm_id: self.inner.vm_id.clone(),
}),
wire::RequestPayload::DisposeVmRequest(wire::DisposeVmRequest {
reason: wire::DisposeReason::Requested,
}),
)
.await;
let _ = vm_tools().remove(&self.inner.vm_id);
let _ = vm_permission_routers().remove(&self.inner.vm_id);
let _ = session_js_bridge_callbacks().remove(&sidecar_session_key(
&self.inner.connection_id,
&self.inner.session_id,
));
let sidecar = self.inner.sidecar.clone();
if let Some(lease) = lease {
lease.dispose().await?;
}
if sidecar.active_vm_count.load(Ordering::SeqCst) == 0 {
sidecar.kill_connection().await;
let _ = sidecar.dispose().await;
}
Ok(())
}
// --- internal accessors used by sibling impl blocks ---
pub(crate) fn inner(&self) -> &AgentOsInner {
&self.inner
}
pub(crate) fn transport(&self) -> &Arc<SidecarProcess> {
&self.inner.transport
}
pub(crate) fn connection_id(&self) -> &str {
&self.inner.connection_id
}
pub(crate) fn wire_session_id(&self) -> &str {
&self.inner.session_id
}
pub(crate) fn vm_id(&self) -> &str {
&self.inner.vm_id
}
pub(crate) fn config(&self) -> &Arc<AgentOsConfig> {
&self.inner.config
}
pub(crate) fn cron(&self) -> &Arc<CronManager> {
&self.inner.cron
}
/// The (possibly shared) sidecar handle backing this VM. Public for parity with TS
/// `AgentOs.sidecar` (e.g. `describe()` reports `active_vm_count` across VMs sharing a pool).
pub fn sidecar(&self) -> Arc<AgentOsSidecar> {
self.inner.sidecar.clone()
}
/// The commands each configured package *ships*, keyed by the package's
/// manifest name (matching [`SoftwareInfoDto::package`] on the actor-plugin
/// side). Read from each package dir the same way the sidecar's
/// `command_targets` does (`package.json` `bin`, else the `bin/` dir). An agent
/// package (no shipped commands) contributes an empty list.
///
/// WORKAROUND: agent-os owns command *provisioning* (it forwards each package
/// dir), so it can read the host dirs here. The authoritative *resolved* set —
/// deduping when two packages provide the same command, priority order, and
/// executability — is owned by secure-exec's projection. This re-derives a
/// slice of that. TODO: replace with a secure-exec API that reports discovered
/// commands per package instead of us re-reading dirs.
pub fn provided_commands(&self) -> Vec<(String, Vec<String>)> {
self.inner
.config
.packages
.iter()
.filter_map(|package| {
let manifest = read_agentos_package_manifest(&package.dir).ok()?;
Some((manifest.name, package_command_names(&package.dir)))
})
.collect()
}
}
/// Abort and clear a single tracked background-task handle (e.g. the ACP event pump) so it cannot
/// outlive the disposed VM. Mirrors the `pending_shell_exits` drain in `shutdown`.
fn abort_tracked_task(slot: &parking_lot::Mutex<Option<JoinHandle<()>>>) {
if let Some(handle) = slot.lock().take() {
handle.abort();
}
}
fn spawn_acp_event_pump(client: &AgentOs) {
let mut events = client.transport().subscribe_wire_events();
let inner = Arc::downgrade(&client.inner);
let handle = tokio::spawn(async move {
loop {
match events.recv().await {
Ok((ownership, wire::EventPayload::ExtEnvelope(envelope))) => {
let Some(inner) = inner.upgrade() else {
break;
};
if inner.disposed.load(Ordering::SeqCst) {
break;
}
if wire_ownership_vm_id(&ownership) != Some(inner.vm_id.as_str()) {
continue;
}
if let Err(error) = deliver_acp_ext_event(&inner, envelope) {
tracing::warn!(?error, "failed to deliver acp extension event");
}
}
Ok((
_,
wire::EventPayload::VmLifecycleEvent(_)
| wire::EventPayload::ProcessOutputEvent(_)
| wire::EventPayload::ProcessExitedEvent(_)
| wire::EventPayload::StructuredEvent(_),
)) => {}
Err(broadcast::error::RecvError::Lagged(_)) => {}
Err(broadcast::error::RecvError::Closed) => break,
}
}
});
*client.inner.acp_event_pump.lock() = Some(handle);
}
fn deliver_acp_ext_event(
inner: &AgentOsInner,
envelope: wire::ExtEnvelope,
) -> Result<(), ClientError> {
if envelope.namespace != ACP_EXTENSION_NAMESPACE {
return Ok(());
}
let event: AcpEvent = serde_bare::from_slice(&envelope.payload)
.map_err(|error| ClientError::Sidecar(format!("invalid ACP event: {error}")))?;
match event {
AcpEvent::AcpSessionEvent(event) => {
let notification: JsonRpcNotification = serde_json::from_str(&event.notification)
.map_err(|error| {
ClientError::Sidecar(format!("invalid ACP session notification: {error}"))
})?;
let delivered = inner
.sessions
.read(&event.session_id, |_, entry| {
record_live_session_event(entry, notification.clone());
})
.is_some();
if !delivered {
tracing::warn!(
session_id = event.session_id,
"received acp event for unknown session"
);
}
Ok(())
}
AcpEvent::AcpAgentStderrEvent(event) => {
if !event.session_id.is_empty()
&& inner.sessions.read(&event.session_id, |_, _| ()).is_none()
{
tracing::warn!(
session_id = event.session_id,
agent_type = event.agent_type,
process_id = event.process_id,
"received acp stderr event for unknown session"
);
}
let mut stderr = std::io::stderr().lock();
if let Err(error) = stderr.write_all(&event.chunk).and_then(|_| stderr.flush()) {
tracing::warn!(?error, "failed to write acp stderr event");
}
Ok(())
}
AcpEvent::AcpAgentExitedEvent(event) => {
tracing::warn!(
session_id = event.session_id,
agent_type = event.agent_type,
process_id = event.process_id,
exit_code = ?event.exit_code,
restart = event.restart,
restart_count = event.restart_count,
max_restarts = event.max_restarts,
"acp agent adapter exited unexpectedly"
);
let delivered = inner
.sessions
.read(&event.session_id, |_, entry| {
let _ = entry.agent_exit_tx.send(AgentExitEvent {
session_id: event.session_id.clone(),
agent_type: event.agent_type.clone(),
process_id: event.process_id.clone(),
exit_code: event.exit_code,
restart: event.restart.clone(),
restart_count: event.restart_count,
max_restarts: event.max_restarts,
});
})
.is_some();
if !delivered {
tracing::warn!(
session_id = event.session_id,
"received acp agent exit event for unknown session"
);
}
Ok(())
}
}
}
/// Convert a sidecar's client-side placement into the wire `SidecarPlacement` for OpenSession.
fn sidecar_wire_placement(sidecar: &AgentOsSidecar) -> wire::SidecarPlacement {
match &sidecar.placement {
AgentOsSidecarPlacement::Shared { pool } => {
wire::SidecarPlacement::SidecarPlacementShared(wire::SidecarPlacementShared {
pool: pool.clone(),
})
}
AgentOsSidecarPlacement::Explicit { sidecar_id } => {
wire::SidecarPlacement::SidecarPlacementExplicit(wire::SidecarPlacementExplicit {
sidecar_id: sidecar_id.clone(),
})
}
}
}
fn wire_connection_ownership(connection_id: &str) -> wire::OwnershipScope {
wire::OwnershipScope::ConnectionOwnership(wire::ConnectionOwnership {
connection_id: connection_id.to_string(),
})