-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathengine.rs
More file actions
1918 lines (1793 loc) · 76.4 KB
/
Copy pathengine.rs
File metadata and controls
1918 lines (1793 loc) · 76.4 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 host-free ACP engine: owns session state and dispatches ACP requests,
//! driving host-coupled work through the synchronous [`AcpHost`] seam.
//!
//! Ported from `agentos-sidecar::acp_extension` (async) to synchronous, host-free
//! form. All five ACP requests are ported onto the [`AcpHost`] seam: the
//! pure-state ones (`get_session_state`, `close_session`), the bootstrap one
//! (`create_session`), the in-session RPC one (`session_request`, i.e.
//! `session/prompt` + other in-session methods), and `resume_session` (native
//! `session/load` tier with the universal `session/new` fallback). Notification
//! streaming as ACP events and the `session/cancel` not-found fallback remain a
//! documented follow-up that layers on the same loop (see `session_request`).
use std::collections::BTreeMap;
use agentos_protocol::generated::v1::{
AcpCloseSessionRequest, AcpCreateSessionRequest, AcpDeliverAgentOutputRequest,
AcpGetSessionStateRequest, AcpPendingResponse, AcpResumeSessionRequest, AcpRequest, AcpResponse,
AcpRuntimeKind, AcpSessionClosedResponse, AcpSessionRequest, AcpSessionResumedResponse,
AcpSessionRpcResponse,
};
use serde_json::{json, Map, Value};
use crate::host::{AcpHost, SpawnAgentRequest};
use crate::json_rpc::send_json_rpc;
use crate::session::AcpSessionRecord;
use crate::AcpCoreError;
/// Matches the native sidecar's `SESSION_CLOSE_TIMEOUT` (5s).
const SESSION_CLOSE_TIMEOUT_MS: u64 = 5_000;
/// Matches the native `INITIALIZE_TIMEOUT` (10s) and `SESSION_NEW_TIMEOUT` (30s).
const INITIALIZE_TIMEOUT_MS: u64 = 10_000;
const SESSION_NEW_TIMEOUT_MS: u64 = 30_000;
/// Matches the native `ACP_RESUME_PROTOCOL_VERSION`.
const ACP_RESUME_PROTOCOL_VERSION: i32 = 1;
/// Matches the native `DEFAULT_RESUME_CLIENT_CAPABILITIES`.
const DEFAULT_RESUME_CLIENT_CAPABILITIES: &str = "{}";
/// Transcript-continuation preamble armed by the resume fallback tier; matches the
/// native `CONTINUATION_PREAMBLE`.
const CONTINUATION_PREAMBLE: &str = "You are continuing an earlier session. The full prior transcript is at `{path}`. Read it with your file tools if you need context before answering.";
/// Agent launch parameters resolved from a projected `/opt/agentos` package
/// manifest. The npm-agnostic client sends only the agent name; the sidecar owns
/// the name -> package -> entrypoint/env/launchArgs resolution. Mirrors the native
/// sidecar's `ResolvedAgent`.
struct ResolvedAgent {
entrypoint: String,
env: BTreeMap<String, String>,
launch_args: Vec<String>,
}
/// The subset of `agentos-package.json` the sidecar needs to launch an agent.
#[derive(serde::Deserialize)]
struct AgentPackageManifest {
#[serde(default)]
agent: Option<AgentPackageAgentBlock>,
}
#[derive(serde::Deserialize)]
struct AgentPackageAgentBlock {
#[serde(rename = "acpEntrypoint", default)]
acp_entrypoint: String,
#[serde(default)]
env: BTreeMap<String, String>,
#[serde(rename = "launchArgs", default)]
launch_args: Vec<String>,
}
/// Resolve an agent name to its launch parameters by reading the projected
/// manifest at `/opt/agentos/<name>/current/agentos-package.json` over the host
/// filesystem seam. A missing file, a missing `agent` block, or an empty
/// `agent.acpEntrypoint` all map to a single typed "unknown agent" error. Mirrors
/// the native sidecar `resolve_agent`.
fn resolve_agent<H: AcpHost>(
host: &mut H,
agent_type: &str,
) -> Result<ResolvedAgent, AcpCoreError> {
let unknown = || {
AcpCoreError::InvalidState(format!(
"unknown agent type \"{agent_type}\": no projected /opt/agentos/{agent_type} package \
with an agent.acpEntrypoint — pass its package to AgentOs software"
))
};
let path = format!("/opt/agentos/{agent_type}/current/agentos-package.json");
let bytes = host.read_file(&path).map_err(|_| unknown())?;
let manifest: AgentPackageManifest = serde_json::from_slice(&bytes).map_err(|_| unknown())?;
let agent = manifest.agent.ok_or_else(|| unknown())?;
if agent.acp_entrypoint.is_empty() {
return Err(unknown());
}
Ok(ResolvedAgent {
entrypoint: format!("/opt/agentos/bin/{}", agent.acp_entrypoint),
env: agent.env,
launch_args: agent.launch_args,
})
}
/// Host-free ACP session engine. The native and browser sidecars each hold one of
/// these and feed it decoded requests plus the caller's connection id (for the
/// per-connection ownership checks) and an [`AcpHost`] for the host-coupled steps.
#[derive(Debug, Default)]
pub struct AcpCore {
sessions: BTreeMap<String, AcpSessionRecord>,
next_process_id: u64,
/// In-flight RESUMABLE create_session handshakes (browser path). The synchronous
/// `create_session` blocks; the resumable path (begin_create_session +
/// feed_agent_output) never does, so the single-threaded kernel worker can
/// release the wasm borrow between steps and service the agent's own syscalls on
/// fresh, non-nested calls (see AGENTOS-WEB-ASYNC-AGENTS.md §3.2 + the
/// pushFrame-re-entrancy constraint). Native keeps using the blocking path.
pending_creates: BTreeMap<String, PendingCreate>,
/// In-flight RESUMABLE session/prompt (and other in-session RPC) requests,
/// keyed by the agent's process id.
pending_prompts: BTreeMap<String, PendingPrompt>,
}
/// State of one in-flight resumable `session/prompt` (or other in-session RPC).
#[derive(Debug)]
struct PendingPrompt {
session_id: String,
rpc_id: i64,
stdout_buffer: String,
}
/// State of one in-flight resumable `create_session` handshake.
#[derive(Debug)]
struct PendingCreate {
owner_connection_id: String,
agent_type: String,
pid: Option<u32>,
protocol_version: i32,
cwd: String,
mcp_servers: Value,
step: CreateStep,
stdout_buffer: String,
init_result: Option<Map<String, Value>>,
}
#[derive(Debug, PartialEq, Eq)]
enum CreateStep {
AwaitingInitialize,
AwaitingSessionNew,
}
/// Outcome of feeding agent output into a resumable handshake.
#[derive(Debug)]
pub enum ResumeStep {
/// More agent output is needed; the interaction is still in flight.
Pending,
/// The interaction completed; deliver this response as the (deferred) result.
Done(AcpResponse),
}
/// Result of the ACP bootstrap handshake (initialize + session/new).
struct SessionBootstrap {
session_id: String,
modes: Option<String>,
config_options: Vec<String>,
agent_capabilities: Option<String>,
agent_info: Option<String>,
stdout_buffer: String,
}
impl AcpCore {
pub fn new() -> Self {
Self::default()
}
pub fn session_count(&self) -> usize {
self.sessions.len()
}
fn allocate_process_id(&mut self, prefix: &str) -> String {
let id = self.next_process_id;
self.next_process_id += 1;
format!("{prefix}-{id}")
}
/// Insert/replace a session record (used by the create/resume handlers once a
/// process is live).
pub fn insert_session(&mut self, record: AcpSessionRecord) {
self.sessions.insert(record.session_id.clone(), record);
}
/// `session/state`: pure state lookup with per-connection ownership. A non-owner
/// (or missing session) fails closed with the SAME error so another connection's
/// session is not revealed across the tenant boundary.
pub fn get_session_state(
&self,
caller_connection_id: &str,
request: &AcpGetSessionStateRequest,
) -> Result<AcpResponse, AcpCoreError> {
let unknown =
|| AcpCoreError::InvalidState(format!("unknown ACP session {}", request.session_id));
let session = self.sessions.get(&request.session_id).ok_or_else(unknown)?;
if session.owner_connection_id != caller_connection_id {
return Err(unknown());
}
Ok(AcpResponse::AcpSessionStateResponse(session.state_response()))
}
/// `session/close`: owner-only teardown. Removes the record, then SIGTERM →
/// (timeout) → SIGKILL the agent process through the host seam. Mirrors the
/// native `close_session` flow.
pub fn close_session<H: AcpHost>(
&mut self,
host: &mut H,
caller_connection_id: &str,
request: &AcpCloseSessionRequest,
) -> Result<AcpResponse, AcpCoreError> {
let owned_by_caller = self
.sessions
.get(&request.session_id)
.is_some_and(|session| session.owner_connection_id == caller_connection_id);
let session = if owned_by_caller {
self.sessions.remove(&request.session_id)
} else {
None
};
let Some(session) = session else {
return Err(AcpCoreError::InvalidState(format!(
"unknown ACP session {}",
request.session_id
)));
};
let _ = host.close_stdin(&session.process_id);
let _ = host.kill_agent(&session.process_id, "SIGTERM");
if host
.wait_for_exit(&session.process_id, SESSION_CLOSE_TIMEOUT_MS)?
.is_none()
{
let _ = host.kill_agent(&session.process_id, "SIGKILL");
let _ = host.wait_for_exit(&session.process_id, SESSION_CLOSE_TIMEOUT_MS)?;
}
Ok(AcpResponse::AcpSessionClosedResponse(
AcpSessionClosedResponse {
session_id: request.session_id.clone(),
},
))
}
/// `session/create`: launch the agent adapter, run the ACP bootstrap handshake
/// (`initialize` then `session/new`) over the sync seam, and record the session.
/// NOTE: opencode-specific prompt injection / config-option derivation from the
/// native `create_session` are deferred follow-ups; the minimal core launches the
/// adapter as configured and records what the handshake returns.
pub fn create_session<H: AcpHost>(
&mut self,
host: &mut H,
caller_connection_id: &str,
request: &AcpCreateSessionRequest,
) -> Result<AcpResponse, AcpCoreError> {
let resolved = resolve_agent(host, &request.agent_type)?;
let process_id = self.allocate_process_id("acp-agent");
let mut env: BTreeMap<String, String> = request.env.clone().into_iter().collect();
env.insert(String::from("SECURE_EXEC_KEEP_STDIN_OPEN"), String::from("1"));
// Manifest env applies as DEFAULTS; caller/base env wins on conflicts.
for (key, value) in &resolved.env {
env.entry(key.clone()).or_insert_with(|| value.clone());
}
// Manifest launch args first, then any caller-supplied args.
let mut args = resolved.launch_args.clone();
args.extend(request.args.iter().cloned());
let spawned = host.spawn_agent(SpawnAgentRequest {
process_id: process_id.clone(),
runtime: request.runtime.clone(),
entrypoint: Some(resolved.entrypoint.clone()),
command: None,
args,
env,
cwd: Some(request.cwd.clone()),
})?;
let bootstrap = match self.bootstrap_session(host, request, &process_id) {
Ok(bootstrap) => bootstrap,
Err(error) => {
let _ = host.kill_agent(&process_id, "SIGKILL");
return Err(error);
}
};
let session = AcpSessionRecord {
session_id: bootstrap.session_id.clone(),
owner_connection_id: caller_connection_id.to_string(),
agent_type: request.agent_type.clone(),
process_id: process_id.clone(),
pid: spawned.pid,
modes: bootstrap.modes,
config_options: bootstrap.config_options,
agent_capabilities: bootstrap.agent_capabilities,
agent_info: bootstrap.agent_info,
stdout_buffer: bootstrap.stdout_buffer,
next_request_id: 3,
closed: false,
exit_code: None,
pending_preamble: None,
};
host.bind_session(&session.session_id, &process_id)?;
let response = AcpResponse::AcpSessionCreatedResponse(session.created_response());
self.sessions.insert(session.session_id.clone(), session);
Ok(response)
}
/// RESUMABLE `create_session` — start (browser path). Spawns the agent and writes
/// the `initialize` request, then RETURNS without waiting (no `poll_output`). The
/// caller feeds the agent's stdout back via [`feed_agent_output`]; between calls
/// the kernel worker is free (the wasm borrow is released), so it can service the
/// agent's own syscalls on fresh, non-nested calls. Returns the process id used
/// as the handshake handle.
pub fn begin_create_session<H: AcpHost>(
&mut self,
host: &mut H,
caller_connection_id: &str,
request: &AcpCreateSessionRequest,
) -> Result<String, AcpCoreError> {
let resolved = resolve_agent(host, &request.agent_type)?;
let process_id = self.allocate_process_id("acp-agent");
let mut env: BTreeMap<String, String> = request.env.clone().into_iter().collect();
env.insert(String::from("SECURE_EXEC_KEEP_STDIN_OPEN"), String::from("1"));
// Manifest env applies as DEFAULTS; caller/base env wins on conflicts.
for (key, value) in &resolved.env {
env.entry(key.clone()).or_insert_with(|| value.clone());
}
// Manifest launch args first, then any caller-supplied args.
let mut args = resolved.launch_args.clone();
args.extend(request.args.iter().cloned());
let spawned = host.spawn_agent(SpawnAgentRequest {
process_id: process_id.clone(),
runtime: request.runtime.clone(),
entrypoint: Some(resolved.entrypoint.clone()),
command: None,
args,
env,
cwd: Some(request.cwd.clone()),
})?;
let client_capabilities =
parse_json_text(&request.client_capabilities, "clientCapabilities")?;
let mcp_servers = parse_json_text(&request.mcp_servers, "mcpServers")?;
let initialize = json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": request.protocol_version,
"clientCapabilities": client_capabilities,
},
});
if let Err(error) = write_json_line(host, &process_id, &initialize) {
let _ = host.kill_agent(&process_id, "SIGKILL");
return Err(error);
}
self.pending_creates.insert(
process_id.clone(),
PendingCreate {
owner_connection_id: caller_connection_id.to_string(),
agent_type: request.agent_type.clone(),
pid: spawned.pid,
protocol_version: request.protocol_version,
cwd: request.cwd.clone(),
mcp_servers,
step: CreateStep::AwaitingInitialize,
stdout_buffer: String::new(),
init_result: None,
},
);
Ok(process_id)
}
/// RESUMABLE — feed agent stdout into whatever interaction is in flight for this
/// process (a `create_session` handshake or a `session/prompt`), advancing it
/// without ever blocking. Returns [`ResumeStep::Done`] with the response when the
/// interaction completes, else [`ResumeStep::Pending`]. The kernel worker calls
/// this across separate `pushFrame`s and services the agent's syscalls in between
/// (legal — not nested).
pub fn feed_agent_output<H: AcpHost>(
&mut self,
host: &mut H,
process_id: &str,
chunk: &[u8],
) -> Result<ResumeStep, AcpCoreError> {
if self.pending_creates.contains_key(process_id) {
self.feed_create(host, process_id, chunk)
} else if self.pending_prompts.contains_key(process_id) {
self.feed_prompt(process_id, chunk)
} else {
Err(AcpCoreError::InvalidState(format!(
"no pending ACP interaction for {process_id}"
)))
}
}
fn feed_create<H: AcpHost>(
&mut self,
host: &mut H,
process_id: &str,
chunk: &[u8],
) -> Result<ResumeStep, AcpCoreError> {
let mut session_result: Option<Map<String, Value>> = None;
{
let pending = self.pending_creates.get_mut(process_id).ok_or_else(|| {
AcpCoreError::InvalidState(format!("no pending create_session for {process_id}"))
})?;
pending
.stdout_buffer
.push_str(&String::from_utf8_lossy(chunk));
while let Some(idx) = pending.stdout_buffer.find('\n') {
let line: String = pending.stdout_buffer.drain(..=idx).collect();
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let Ok(message) = serde_json::from_str::<Value>(trimmed) else {
continue;
};
match pending.step {
CreateStep::AwaitingInitialize => {
if message.get("id").and_then(Value::as_i64) != Some(1) {
continue;
}
let init = response_result(message, "ACP initialize")?;
validate_initialize_result(&init, pending.protocol_version)?;
pending.init_result = Some(init);
let session_new = json!({
"jsonrpc": "2.0",
"id": 2,
"method": "session/new",
"params": { "cwd": pending.cwd.clone(), "mcpServers": pending.mcp_servers.clone() },
});
write_json_line(host, process_id, &session_new)?;
pending.step = CreateStep::AwaitingSessionNew;
}
CreateStep::AwaitingSessionNew => {
if message.get("id").and_then(Value::as_i64) != Some(2) {
continue;
}
session_result = Some(response_result(message, "ACP session/new")?);
break;
}
}
}
}
let Some(session_result) = session_result else {
return Ok(ResumeStep::Pending);
};
// Handshake complete: build + record the session outside the pending borrow.
let pending = self
.pending_creates
.remove(process_id)
.expect("pending entry exists");
let init_result = pending.init_result.clone().unwrap_or_default();
let session_id = session_id_from_session_result(&session_result, process_id);
host.bind_session(&session_id, process_id)?;
let record = AcpSessionRecord {
session_id: session_id.clone(),
owner_connection_id: pending.owner_connection_id.clone(),
agent_type: pending.agent_type.clone(),
process_id: process_id.to_string(),
pid: pending.pid,
modes: optional_field_json(&session_result, &init_result, "modes"),
config_options: config_options(&init_result, &session_result),
agent_capabilities: optional_value_json(init_result.get("agentCapabilities")),
agent_info: optional_value_json(init_result.get("agentInfo")),
stdout_buffer: String::new(),
next_request_id: 3,
closed: false,
exit_code: None,
pending_preamble: None,
};
let response = AcpResponse::AcpSessionCreatedResponse(record.created_response());
self.sessions.insert(session_id, record);
Ok(ResumeStep::Done(response))
}
/// RESUMABLE `session/prompt` (and other in-session RPC) — start. Owner-only;
/// allocates the rpc id, injects `sessionId`, consumes any armed preamble, writes
/// the request, and RETURNS without waiting. The agent's reply (and its mid-turn
/// syscalls — pi's inference is a `net` call here) are handled via
/// `feed_agent_output` across separate, non-nested `pushFrame`s.
pub fn begin_session_request<H: AcpHost>(
&mut self,
host: &mut H,
caller_connection_id: &str,
request: &AcpSessionRequest,
) -> Result<String, AcpCoreError> {
let mut outbound_params = match request.params.as_deref() {
Some(params) => to_record(parse_json_text(params, "session request params")?),
None => Map::new(),
};
outbound_params.insert(
String::from("sessionId"),
Value::String(request.session_id.clone()),
);
let unknown =
|| AcpCoreError::InvalidState(format!("unknown ACP session {}", request.session_id));
let session = self.sessions.get_mut(&request.session_id).ok_or_else(unknown)?;
if session.owner_connection_id != caller_connection_id {
return Err(unknown());
}
let rpc_id = session.allocate_request_id();
let pending_preamble = if request.method == "session/prompt" {
session.pending_preamble.take()
} else {
None
};
let process_id = session.process_id.clone();
if let Some(preamble) = pending_preamble.as_deref() {
prepend_prompt_preamble(&mut outbound_params, preamble);
}
let outbound = json!({
"jsonrpc": "2.0",
"id": rpc_id,
"method": request.method,
"params": Value::Object(outbound_params),
});
write_json_line(host, &process_id, &outbound)?;
self.pending_prompts.insert(
process_id.clone(),
PendingPrompt {
session_id: request.session_id.clone(),
rpc_id,
stdout_buffer: String::new(),
},
);
Ok(process_id)
}
fn feed_prompt(&mut self, process_id: &str, chunk: &[u8]) -> Result<ResumeStep, AcpCoreError> {
let mut completed: Option<(String, String)> = None; // (session_id, response_text)
{
let pending = self
.pending_prompts
.get_mut(process_id)
.expect("pending prompt exists");
pending
.stdout_buffer
.push_str(&String::from_utf8_lossy(chunk));
while let Some(idx) = pending.stdout_buffer.find('\n') {
let line: String = pending.stdout_buffer.drain(..=idx).collect();
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let Ok(message) = serde_json::from_str::<Value>(trimmed) else {
continue;
};
// Ignore notifications / other ids; only the matching response completes.
if message.get("id").and_then(Value::as_i64) != Some(pending.rpc_id) {
continue;
}
let text = serde_json::to_string(&message).map_err(|error| {
AcpCoreError::InvalidState(format!(
"failed to serialize ACP session response: {error}"
))
})?;
completed = Some((pending.session_id.clone(), text));
break;
}
}
let Some((session_id, response)) = completed else {
return Ok(ResumeStep::Pending);
};
self.pending_prompts.remove(process_id);
Ok(ResumeStep::Done(AcpResponse::AcpSessionRpcResponse(
AcpSessionRpcResponse {
session_id,
response,
},
)))
}
/// In-flight resumable interactions (create + prompt), for diagnostics/tests.
pub fn pending_create_count(&self) -> usize {
self.pending_creates.len()
}
pub fn pending_prompt_count(&self) -> usize {
self.pending_prompts.len()
}
fn bootstrap_session<H: AcpHost>(
&self,
host: &mut H,
request: &AcpCreateSessionRequest,
process_id: &str,
) -> Result<SessionBootstrap, AcpCoreError> {
let mut stdout = String::new();
let client_capabilities = parse_json_text(&request.client_capabilities, "clientCapabilities")?;
let mcp_servers = parse_json_text(&request.mcp_servers, "mcpServers")?;
let initialize = json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": request.protocol_version,
"clientCapabilities": client_capabilities,
},
});
let init_response =
send_json_rpc(host, process_id, &initialize, 1, INITIALIZE_TIMEOUT_MS, &mut stdout)?;
let init_result = response_result(init_response, "ACP initialize")?;
validate_initialize_result(&init_result, request.protocol_version)?;
let session_new = json!({
"jsonrpc": "2.0",
"id": 2,
"method": "session/new",
"params": { "cwd": request.cwd, "mcpServers": mcp_servers },
});
let session_response =
send_json_rpc(host, process_id, &session_new, 2, SESSION_NEW_TIMEOUT_MS, &mut stdout)?;
let session_result = response_result(session_response, "ACP session/new")?;
let session_id = session_id_from_session_result(&session_result, process_id);
Ok(SessionBootstrap {
session_id,
modes: optional_field_json(&session_result, &init_result, "modes"),
config_options: config_options(&init_result, &session_result),
agent_capabilities: optional_value_json(init_result.get("agentCapabilities")),
agent_info: optional_value_json(init_result.get("agentInfo")),
stdout_buffer: stdout,
})
}
/// In-session JSON-RPC (`session/prompt`, `session/set_mode`, `session/cancel`,
/// etc.): owner-only, forwards the method+params to the live adapter over the
/// seam and returns the agent's JSON-RPC response. Mirrors the native
/// `session_request`.
///
/// FOLLOW-UP (documented, parity-tracked): the native handler also (a) forwards
/// adapter notifications emitted during the exchange as `AcpSessionEvent`s and
/// synthesizes mode/plan notifications via `apply_request_success`, and (b)
/// converts a `session/cancel` "method not found" into a `session/cancel`
/// notification fallback. Those layer on the same loop once the host seam
/// surfaces notifications; the core request/response path is faithful now.
pub fn session_request<H: AcpHost>(
&mut self,
host: &mut H,
caller_connection_id: &str,
request: &AcpSessionRequest,
) -> Result<AcpResponse, AcpCoreError> {
let mut outbound_params = match request.params.as_deref() {
Some(params) => to_record(parse_json_text(params, "session request params")?),
None => Map::new(),
};
outbound_params.insert(
String::from("sessionId"),
Value::String(request.session_id.clone()),
);
// Enforce per-connection ownership and allocate the rpc id BEFORE any
// outbound write. A non-owner (or missing session) fails closed with the
// SAME error as `get_session_state` so the victim session is not revealed
// and no state is mutated on a rejected attempt.
let unknown =
|| AcpCoreError::InvalidState(format!("unknown ACP session {}", request.session_id));
let session = self.sessions.get_mut(&request.session_id).ok_or_else(unknown)?;
if session.owner_connection_id != caller_connection_id {
return Err(unknown());
}
let rpc_id = session.allocate_request_id();
// The transcript-continuation preamble is consumed once, on the first
// `session/prompt` after a fallback resume; other methods leave it armed.
let pending_preamble = if request.method == "session/prompt" {
session.pending_preamble.take()
} else {
None
};
let process_id = session.process_id.clone();
let mut stdout_buffer = std::mem::take(&mut session.stdout_buffer);
if let Some(preamble) = pending_preamble.as_deref() {
prepend_prompt_preamble(&mut outbound_params, preamble);
}
let outbound = json!({
"jsonrpc": "2.0",
"id": rpc_id,
"method": request.method,
"params": Value::Object(outbound_params),
});
let timeout = request_timeout_ms(&request.method);
let response = match send_json_rpc(
host,
&process_id,
&outbound,
rpc_id,
timeout,
&mut stdout_buffer,
) {
Ok(response) => response,
Err(error) => {
// Persist any drained stdout and re-arm the consumed preamble so a
// transient failure does not silently drop transcript context.
if let Some(session) = self.sessions.get_mut(&request.session_id) {
session.stdout_buffer = stdout_buffer;
if pending_preamble.is_some() && session.pending_preamble.is_none() {
session.pending_preamble = pending_preamble;
}
}
return Err(error);
}
};
if let Some(session) = self.sessions.get_mut(&request.session_id) {
session.stdout_buffer = stdout_buffer;
}
let response_text = serde_json::to_string(&response).map_err(|error| {
AcpCoreError::InvalidState(format!("failed to serialize ACP session response: {error}"))
})?;
Ok(AcpResponse::AcpSessionRpcResponse(AcpSessionRpcResponse {
session_id: request.session_id.clone(),
response: response_text,
}))
}
/// `session/resume`: re-attach a session that exists in durable storage but is
/// not live in this VM. Launches a fresh adapter, re-probes its capabilities via
/// `initialize`, then tries the native `session/load`/`session/resume` tier and
/// falls back to a fresh `session/new` (arming the transcript-continuation
/// preamble) on the `unknown_session` sentinel. Mirrors the native
/// `resume_session` state machine (spec §6/§8).
pub fn resume_session<H: AcpHost>(
&mut self,
host: &mut H,
caller_connection_id: &str,
request: &AcpResumeSessionRequest,
) -> Result<AcpResponse, AcpCoreError> {
let resolved = resolve_agent(host, &request.agent_type)?;
let process_id = self.allocate_process_id("acp-agent");
let mut env: BTreeMap<String, String> = request.env.clone().into_iter().collect();
env.insert(String::from("SECURE_EXEC_KEEP_STDIN_OPEN"), String::from("1"));
// Manifest env applies as DEFAULTS; caller/base env wins on conflicts.
for (key, value) in &resolved.env {
env.entry(key.clone()).or_insert_with(|| value.clone());
}
let spawned = host.spawn_agent(SpawnAgentRequest {
process_id: process_id.clone(),
runtime: AcpRuntimeKind::JavaScript,
entrypoint: Some(resolved.entrypoint.clone()),
command: None,
args: resolved.launch_args.clone(),
env,
cwd: Some(request.cwd.clone()),
})?;
let outcome = match self.resume_bootstrap(host, request, &process_id) {
Ok(outcome) => outcome,
Err(error) => {
let _ = host.kill_agent(&process_id, "SIGKILL");
return Err(error);
}
};
let session = AcpSessionRecord {
session_id: outcome.bootstrap.session_id.clone(),
owner_connection_id: caller_connection_id.to_string(),
agent_type: request.agent_type.clone(),
process_id: process_id.clone(),
pid: spawned.pid,
modes: outcome.bootstrap.modes,
config_options: outcome.bootstrap.config_options,
agent_capabilities: outcome.bootstrap.agent_capabilities,
agent_info: outcome.bootstrap.agent_info,
stdout_buffer: outcome.bootstrap.stdout_buffer,
next_request_id: 3,
closed: false,
exit_code: None,
pending_preamble: outcome.pending_preamble,
};
host.bind_session(&session.session_id, &process_id)?;
let response = AcpResponse::AcpSessionResumedResponse(AcpSessionResumedResponse {
session_id: session.session_id.clone(),
mode: outcome.mode,
});
self.sessions.insert(session.session_id.clone(), session);
Ok(response)
}
fn resume_bootstrap<H: AcpHost>(
&self,
host: &mut H,
request: &AcpResumeSessionRequest,
process_id: &str,
) -> Result<ResumeOutcome, AcpCoreError> {
let mut stdout = String::new();
let client_capabilities =
parse_json_text(DEFAULT_RESUME_CLIENT_CAPABILITIES, "clientCapabilities")?;
let initialize = json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": ACP_RESUME_PROTOCOL_VERSION,
"clientCapabilities": client_capabilities,
},
});
let init_response =
send_json_rpc(host, process_id, &initialize, 1, INITIALIZE_TIMEOUT_MS, &mut stdout)?;
let init_result = response_result(init_response, "ACP initialize")?;
validate_initialize_result(&init_result, ACP_RESUME_PROTOCOL_VERSION)?;
let agent_capabilities = init_result.get("agentCapabilities").cloned();
// Tier 1 — native (capability-gated). Re-probed caps decide eligibility.
if let Some(native_method) = native_resume_method(agent_capabilities.as_ref()) {
let load = json!({
"jsonrpc": "2.0",
"id": 2,
"method": native_method,
"params": { "sessionId": request.session_id, "cwd": request.cwd, "mcpServers": [] },
});
let mut load_response = send_json_rpc(
host,
process_id,
&load,
2,
SESSION_NEW_TIMEOUT_MS,
&mut stdout,
)?;
normalize_unknown_session_error(&mut load_response);
if load_response.get("error").is_none() {
let load_result = response_result(load_response, &format!("ACP {native_method}"))?;
return Ok(ResumeOutcome {
bootstrap: self.build_bootstrap(
request.session_id.clone(),
&init_result,
&load_result,
agent_capabilities.as_ref(),
stdout,
),
mode: String::from("native"),
pending_preamble: None,
});
}
// Only the `unknown_session` sentinel falls through; every other error
// propagates verbatim (the durable store survived; this is a real error).
if !is_unknown_session_error(&load_response) {
return Err(response_result(load_response, &format!("ACP {native_method}"))
.expect_err("native resume error object must map to an AcpCoreError"));
}
// fall through to Tier 2
}
// Tier 2 — universal fallback: a fresh session plus the transcript pointer.
let session_new = json!({
"jsonrpc": "2.0",
"id": 2,
"method": "session/new",
"params": { "cwd": request.cwd, "mcpServers": [] },
});
let session_response = send_json_rpc(
host,
process_id,
&session_new,
2,
SESSION_NEW_TIMEOUT_MS,
&mut stdout,
)?;
let session_result = response_result(session_response, "ACP session/new")?;
let live_session_id = session_id_from_session_result(&session_result, process_id);
let pending_preamble = request
.transcript_path
.as_deref()
.filter(|path| !path.is_empty())
.map(|path| CONTINUATION_PREAMBLE.replace("{path}", path));
Ok(ResumeOutcome {
bootstrap: self.build_bootstrap(
live_session_id,
&init_result,
&session_result,
agent_capabilities.as_ref(),
stdout,
),
mode: String::from("fallback"),
pending_preamble,
})
}
fn build_bootstrap(
&self,
session_id: String,
init_result: &Map<String, Value>,
session_result: &Map<String, Value>,
agent_capabilities: Option<&Value>,
stdout_buffer: String,
) -> SessionBootstrap {
SessionBootstrap {
session_id,
modes: optional_field_json(session_result, init_result, "modes"),
config_options: config_options(init_result, session_result),
agent_capabilities: optional_value_json(agent_capabilities),
agent_info: optional_value_json(init_result.get("agentInfo")),
stdout_buffer,
}
}
/// Dispatch a decoded ACP request to the right handler.
pub fn dispatch<H: AcpHost>(
&mut self,
host: &mut H,
caller_connection_id: &str,
request: AcpRequest,
) -> Result<AcpResponse, AcpCoreError> {
match request {
AcpRequest::AcpCreateSessionRequest(request) => {
self.create_session(host, caller_connection_id, &request)
}
AcpRequest::AcpGetSessionStateRequest(request) => {
self.get_session_state(caller_connection_id, &request)
}
AcpRequest::AcpCloseSessionRequest(request) => {
self.close_session(host, caller_connection_id, &request)
}
AcpRequest::AcpSessionRequest(request) => {
self.session_request(host, caller_connection_id, &request)
}
AcpRequest::AcpResumeSessionRequest(request) => {
self.resume_session(host, caller_connection_id, &request)
}
AcpRequest::AcpDeliverAgentOutputRequest(request) => {
self.deliver_agent_output(host, &request)
}
// Agent enumeration needs a directory listing of `/opt/agentos`, which
// the host-free `AcpHost` seam does not expose (it has `read_file`, not
// `read_dir`). The native sidecar answers `list_agents` directly from the
// projected packages; the browser resumable path does not support it yet.
AcpRequest::AcpListAgentsRequest(_) => Err(AcpCoreError::InvalidState(
"list_agents is not handled by the host-free ACP core; the native sidecar answers \
it from the projected /opt/agentos packages"
.to_string(),
)),
}
}
/// RESUMABLE dispatch (browser path): `create_session` / `session/prompt` start a
/// non-blocking handshake and return [`AcpPendingResponse`] with the process
/// handle; `deliver_agent_output` feeds the agent's stdout and returns the real
/// result once the handshake completes (else another `AcpPendingResponse`).
/// Everything else (get_state / close / resume) is delegated to the synchronous
/// handlers. This is what the in-worker kernel calls so it never block-waits
/// inside `pushFrame` while an agent makes a mid-turn syscall (§3.2.1).
pub fn dispatch_resumable<H: AcpHost>(
&mut self,
host: &mut H,
caller_connection_id: &str,
request: AcpRequest,
) -> Result<AcpResponse, AcpCoreError> {
match request {
AcpRequest::AcpCreateSessionRequest(request) => {
let process_id =
self.begin_create_session(host, caller_connection_id, &request)?;
Ok(AcpResponse::AcpPendingResponse(AcpPendingResponse {
process_id,
}))
}
AcpRequest::AcpSessionRequest(request) => {
let process_id =
self.begin_session_request(host, caller_connection_id, &request)?;
Ok(AcpResponse::AcpPendingResponse(AcpPendingResponse {
process_id,
}))
}
AcpRequest::AcpDeliverAgentOutputRequest(request) => {
self.deliver_agent_output(host, &request)
}
other => self.dispatch(host, caller_connection_id, other),
}
}
fn deliver_agent_output<H: AcpHost>(
&mut self,
host: &mut H,
request: &AcpDeliverAgentOutputRequest,
) -> Result<AcpResponse, AcpCoreError> {
match self.feed_agent_output(host, &request.process_id, &request.chunk)? {
ResumeStep::Pending => Ok(AcpResponse::AcpPendingResponse(AcpPendingResponse {
process_id: request.process_id.clone(),
})),
ResumeStep::Done(response) => Ok(response),
}
}
}