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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
//! AcpProcess — manages a single ACP agent child process with JSON-RPC over stdio.
//!
//! The lifecycle mirrors the Next.js `AcpProcess` class:
//! 1. `spawn(command, args)` — start the child, launch a background stdout reader
//! 2. `initialize()` — send "initialize" request, wait for response
//! 3. `new_session(cwd)` — send "session/new", get back sessionId
//! 4. `prompt(sid, text)` — send "session/prompt" (5-min timeout), stream via SSE
//! 5. `kill()` — terminate the process
//!
//! Agent→client requests (permissions, fs, terminal) are handled in the background reader.
//! Agent message notifications are traced to JSONL files for attribution tracking.
use std::collections::HashMap;
use std::io::ErrorKind;
#[cfg(windows)]
use std::os::windows::process::CommandExt;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin};
use tokio::sync::{broadcast, oneshot, Mutex};
use super::terminal_manager::TerminalManager;
#[cfg(windows)]
use super::CREATE_NO_WINDOW;
use crate::trace::{
Contributor, TraceConversation, TraceEventType, TraceRecord, TraceTool, TraceWriter,
};
/// Callback type for session/update notifications from the agent.
pub type NotificationSender = broadcast::Sender<serde_json::Value>;
/// Type alias for the pending request map to avoid complex type repetition.
type PendingMap = Arc<Mutex<HashMap<u64, oneshot::Sender<Result<serde_json::Value, String>>>>>;
/// A managed ACP agent child process.
pub struct AcpProcess {
stdin: Arc<Mutex<ChildStdin>>,
child: Arc<Mutex<Option<Child>>>,
pending: PendingMap,
next_id: Arc<AtomicU64>,
alive: Arc<AtomicBool>,
notification_tx: NotificationSender,
display_name: String,
/// The command used to spawn this process (e.g., "npx", "uvx", "opencode")
command: String,
_reader_handle: tokio::task::JoinHandle<()>,
}
impl AcpProcess {
/// Spawn the agent process and start the background reader.
///
/// `our_session_id` is used to rewrite the agent's session ID in notifications
/// so the frontend SSE stream matches on the correct session.
pub async fn spawn(
command: &str,
args: &[&str],
cwd: &str,
notification_tx: NotificationSender,
display_name: &str,
our_session_id: &str,
) -> Result<Self, String> {
tracing::info!(
"[AcpProcess:{}] Spawning: {} {} (cwd: {})",
display_name,
command,
args.join(" "),
cwd,
);
let cwd_path = Path::new(cwd);
if !cwd_path.exists() {
return Err(format!(
"Invalid session cwd '{}': directory does not exist",
cwd
));
}
if !cwd_path.is_dir() {
return Err(format!(
"Invalid session cwd '{}': path is not a directory",
cwd
));
}
// Resolve the actual binary path using the full shell PATH
// (macOS GUI apps have a minimal PATH that won't find user CLI tools)
let resolved_command =
crate::shell_env::which(command).unwrap_or_else(|| command.to_string());
let mut command_builder = tokio::process::Command::new(&resolved_command);
command_builder
.args(args)
.current_dir(cwd)
.env("PATH", crate::shell_env::full_path())
.env("NODE_NO_READLINE", "1")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
#[cfg(windows)]
command_builder
.as_std_mut()
.creation_flags(CREATE_NO_WINDOW);
// codex-acp often returns only stopReason in session/prompt result.
// Enabling lightweight codex logs gives us process_output lines that
// include assistant deltas, which the CLI can aggregate as final output.
if resolved_command.ends_with("codex-acp") && std::env::var_os("RUST_LOG").is_none() {
command_builder.env(
"RUST_LOG",
"info,codex_acp::thread=info,codex_acp::codex_agent=info",
);
}
let mut child = command_builder.spawn().map_err(|e| match e.kind() {
ErrorKind::NotFound => {
let resolved_exists = Path::new(&resolved_command).exists();
if resolved_exists {
format!(
"Failed to execute '{}' (resolved: '{}'): {}. The binary exists, but a required interpreter or wrapper target may be missing.",
command, resolved_command, e
)
} else {
format!(
"Failed to spawn '{}' (resolved: '{}'): {}. Is it installed and in PATH?",
command, resolved_command, e
)
}
}
_ => format!(
"Failed to spawn '{}' (resolved: '{}') from cwd '{}': {}",
command, resolved_command, cwd, e
),
})?;
let stdin = child
.stdin
.take()
.ok_or_else(|| "No stdin on child process".to_string())?;
let stdout = child
.stdout
.take()
.ok_or_else(|| "No stdout on child process".to_string())?;
let stderr = child.stderr.take();
let alive = Arc::new(AtomicBool::new(true));
let pending: PendingMap = Arc::new(Mutex::new(HashMap::new()));
let stdin = Arc::new(Mutex::new(stdin));
let name = display_name.to_string();
// Log stderr in background and forward to frontend as process_output
if let Some(stderr) = stderr {
let name_clone = name.clone();
let ntx_stderr = notification_tx.clone();
let our_sid_stderr = our_session_id.to_string();
let resolved_command_stderr = resolved_command.clone();
tokio::spawn(async move {
let reader = BufReader::new(stderr);
let mut lines = reader.lines();
while let Ok(Some(line)) = lines.next_line().await {
if !line.trim().is_empty() {
if should_ignore_process_stderr(
&resolved_command_stderr,
&name_clone,
&line,
) {
continue;
}
tracing::debug!("[AcpProcess:{} stderr] {}", name_clone, line);
// Forward stderr to frontend as process_output notification
let notification = serde_json::json!({
"jsonrpc": "2.0",
"method": "session/update",
"params": {
"sessionId": our_sid_stderr,
"update": {
"sessionUpdate": "process_output",
"source": "stderr",
"data": format!("{}\n", line),
"displayName": name_clone,
}
}
});
let _ = ntx_stderr.send(notification);
}
}
});
}
// Background stdout reader — dispatches responses, notifications, agent requests
let alive_clone = alive.clone();
let pending_clone = pending.clone();
let ntx = notification_tx.clone();
let stdin_clone = stdin.clone();
let name_clone = name.clone();
let our_sid = our_session_id.to_string();
let cwd_clone = cwd.to_string();
let provider_clone = display_name.to_string();
let reader_handle = tokio::spawn(async move {
let reader = BufReader::new(stdout);
let mut lines = reader.lines();
// Buffer for accumulating agent message chunks
let mut agent_msg_buffer = String::new();
// Buffer for accumulating agent thought chunks
let mut agent_thought_buffer = String::new();
// Buffer for pending tool calls awaiting rawInput (OpenCode sends empty rawInput initially)
let mut pending_tool_calls: std::collections::HashMap<String, (String, bool)> =
std::collections::HashMap::new();
while let Ok(Some(line)) = lines.next_line().await {
let line = line.trim().to_string();
if line.is_empty() {
continue;
}
let msg: serde_json::Value = match serde_json::from_str(&line) {
Ok(v) => v,
Err(_) => {
// Try to find embedded JSON objects
if let Some(v) = try_parse_embedded_json(&line) {
v
} else {
tracing::debug!(
"[AcpProcess:{}] Non-JSON stdout: {}",
name_clone,
truncate_content(&line, 200)
);
continue;
}
}
};
let has_id = msg.get("id").is_some() && !msg.get("id").unwrap().is_null();
let has_result = msg.get("result").is_some();
let has_error = msg.get("error").is_some();
let has_method = msg.get("method").and_then(|m| m.as_str()).is_some();
if has_id && (has_result || has_error) {
// Response to a pending request
let id = msg["id"].as_u64().unwrap_or(0);
let mut map = pending_clone.lock().await;
if let Some(tx) = map.remove(&id) {
if has_error {
let err_msg =
msg["error"]["message"].as_str().unwrap_or("unknown error");
let err_code = msg["error"]["code"].as_i64().unwrap_or(0);
let _ = tx.send(Err(format!("ACP Error [{}]: {}", err_code, err_msg)));
} else {
let _ = tx.send(Ok(msg["result"].clone()));
}
}
} else if has_id && has_method {
// Agent→Client request — handle it
let method = msg["method"].as_str().unwrap_or("");
let id_val = msg["id"].clone();
tracing::info!(
"[AcpProcess:{}] Agent request: {} (id={})",
name_clone,
method,
id_val
);
let response =
handle_agent_request(method, &msg["params"], &our_sid, &ntx).await;
let reply = serde_json::json!({
"jsonrpc": "2.0",
"id": id_val,
"result": response,
});
let data = format!("{}\n", serde_json::to_string(&reply).unwrap());
let mut stdin = stdin_clone.lock().await;
let _ = stdin.write_all(data.as_bytes()).await;
let _ = stdin.flush().await;
} else if has_method {
// Notification (no id) — forward to SSE
// Rewrite the agent's sessionId to our session ID so the
// frontend SSE stream can match on the correct session.
let mut rewritten = msg.clone();
if let Some(params) = rewritten.get_mut("params") {
if params.get("sessionId").is_some() {
params["sessionId"] = serde_json::Value::String(our_sid.clone());
}
}
// ── Trace: various event types ─────────────────────────────
if let Some(params) = msg.get("params") {
if let Some(update) = params.get("update") {
let session_update = update
.get("sessionUpdate")
.and_then(|v| v.as_str())
.unwrap_or("");
match session_update {
"agent_thought_chunk" => {
// Accumulate thought chunks
let text = update
.get("content")
.and_then(|c| c.get("text"))
.and_then(|t| t.as_str())
.unwrap_or("");
agent_thought_buffer.push_str(text);
// Trace when buffer reaches 100+ chars
if agent_thought_buffer.len() >= 100 {
let record = TraceRecord::new(
&our_sid,
TraceEventType::AgentThought,
Contributor::new(&provider_clone, None),
)
.with_conversation(TraceConversation {
turn: None,
role: Some("assistant".to_string()),
content_preview: Some(truncate_content(
&agent_thought_buffer,
200,
)),
full_content: Some(agent_thought_buffer.clone()),
});
let writer = TraceWriter::new(&cwd_clone);
let _ = writer.append_safe(&record).await;
agent_thought_buffer.clear();
}
}
"agent_message_chunk" => {
// Accumulate message chunks
let text = update
.get("content")
.and_then(|c| c.get("text"))
.and_then(|t| t.as_str())
.unwrap_or("");
agent_msg_buffer.push_str(text);
// Trace when buffer reaches 100+ chars
if agent_msg_buffer.len() >= 100 {
let record = TraceRecord::new(
&our_sid,
TraceEventType::AgentMessage,
Contributor::new(&provider_clone, None),
)
.with_conversation(TraceConversation {
turn: None,
role: Some("assistant".to_string()),
content_preview: Some(truncate_content(
&agent_msg_buffer,
200,
)),
full_content: Some(agent_msg_buffer.clone()),
});
let writer = TraceWriter::new(&cwd_clone);
let _ = writer.append_safe(&record).await;
agent_msg_buffer.clear();
}
}
"agent_message" => {
// Full message - trace immediately
let text = update
.get("content")
.and_then(|c| c.get("text"))
.and_then(|t| t.as_str())
.unwrap_or("");
let record = TraceRecord::new(
&our_sid,
TraceEventType::AgentMessage,
Contributor::new(&provider_clone, None),
)
.with_conversation(TraceConversation {
turn: None,
role: Some("assistant".to_string()),
content_preview: Some(truncate_content(text, 200)),
full_content: Some(text.to_string()),
});
let writer = TraceWriter::new(&cwd_clone);
let _ = writer.append_safe(&record).await;
}
"tool_call" => {
// Tool call - OpenCode may send rawInput as empty initially
let tool_call_id =
update.get("toolCallId").and_then(|v| v.as_str());
let kind = update
.get("kind")
.and_then(|v| v.as_str())
.or_else(|| update.get("title").and_then(|v| v.as_str()))
.unwrap_or("unknown");
let raw_input = update.get("rawInput").cloned();
// Check if rawInput is empty or null
let has_input = raw_input.as_ref().is_some_and(|v| {
if let Some(obj) = v.as_object() {
!obj.is_empty()
} else {
!v.is_null()
}
});
if has_input {
// Trace immediately with full input (Claude Code behavior)
let record = TraceRecord::new(
&our_sid,
TraceEventType::ToolCall,
Contributor::new(&provider_clone, None),
)
.with_tool(TraceTool {
name: kind.to_string(),
tool_call_id: tool_call_id.map(|s| s.to_string()),
status: Some("running".to_string()),
input: raw_input,
output: None,
});
let writer = TraceWriter::new(&cwd_clone);
let _ = writer.append_safe(&record).await;
} else if let Some(id) = tool_call_id {
// OpenCode behavior: rawInput is empty, wait for tool_call_update
pending_tool_calls
.insert(id.to_string(), (kind.to_string(), false));
}
}
"tool_call_update" => {
// Tool update - may contain rawInput (OpenCode) or just rawOutput (completion)
let tool_call_id =
update.get("toolCallId").and_then(|v| v.as_str());
let kind = update
.get("kind")
.and_then(|v| v.as_str())
.or_else(|| update.get("title").and_then(|v| v.as_str()))
.unwrap_or("unknown");
let raw_input = update.get("rawInput").cloned();
let raw_output = update
.get("rawOutput")
.and_then(|v| v.as_str())
.map(|s| serde_json::Value::String(s.to_string()))
.or_else(|| update.get("rawOutput").cloned());
let status = update
.get("status")
.and_then(|v| v.as_str())
.unwrap_or("completed");
// Check if this update has rawInput and the tool_call wasn't traced yet
let has_input = raw_input.as_ref().is_some_and(|v| {
if let Some(obj) = v.as_object() {
!obj.is_empty()
} else {
!v.is_null()
}
});
if let Some(id) = tool_call_id {
if let Some((stored_kind, traced)) =
pending_tool_calls.get_mut(id)
{
if has_input && !*traced {
// Record the tool_call trace now with actual input
let record = TraceRecord::new(
&our_sid,
TraceEventType::ToolCall,
Contributor::new(&provider_clone, None),
)
.with_tool(TraceTool {
name: stored_kind.clone(),
tool_call_id: Some(id.to_string()),
status: Some("running".to_string()),
input: raw_input.clone(),
output: None,
});
let writer = TraceWriter::new(&cwd_clone);
let _ = writer.append_safe(&record).await;
*traced = true;
}
}
}
// Record tool_result trace when status indicates completion or we have output
let is_complete = status == "completed"
|| status == "failed"
|| raw_output.is_some();
if is_complete {
let record = TraceRecord::new(
&our_sid,
TraceEventType::ToolResult,
Contributor::new(&provider_clone, None),
)
.with_tool(TraceTool {
name: kind.to_string(),
tool_call_id: tool_call_id.map(|s| s.to_string()),
status: Some(status.to_string()),
input: None,
output: raw_output,
});
let writer = TraceWriter::new(&cwd_clone);
let _ = writer.append_safe(&record).await;
// Clean up pending entry
if let Some(id) = tool_call_id {
pending_tool_calls.remove(id);
}
}
}
_ => {}
}
}
}
let _ = ntx.send(rewritten);
} else {
tracing::debug!(
"[AcpProcess:{}] Unhandled message: {}",
name_clone,
truncate_content(&line, 200)
);
}
}
// Flush any remaining buffered agent message content
if !agent_msg_buffer.is_empty() {
let record = TraceRecord::new(
&our_sid,
TraceEventType::AgentMessage,
Contributor::new(&provider_clone, None),
)
.with_conversation(TraceConversation {
turn: None,
role: Some("assistant".to_string()),
content_preview: Some(truncate_content(&agent_msg_buffer, 200)),
full_content: Some(agent_msg_buffer.clone()),
});
let writer = TraceWriter::new(&cwd_clone);
let _ = writer.append_safe(&record).await;
}
// Flush any remaining buffered agent thought content
if !agent_thought_buffer.is_empty() {
let record = TraceRecord::new(
&our_sid,
TraceEventType::AgentThought,
Contributor::new(&provider_clone, None),
)
.with_conversation(TraceConversation {
turn: None,
role: Some("assistant".to_string()),
content_preview: Some(truncate_content(&agent_thought_buffer, 200)),
full_content: Some(agent_thought_buffer.clone()),
});
let writer = TraceWriter::new(&cwd_clone);
let _ = writer.append_safe(&record).await;
}
alive_clone.store(false, Ordering::SeqCst);
tracing::info!("[AcpProcess:{}] stdout reader finished", name_clone);
});
// Wait briefly for process to stabilize
tokio::time::sleep(Duration::from_millis(300)).await;
if !alive.load(Ordering::SeqCst) {
return Err(format!("{} process died during startup", display_name));
}
tracing::info!("[AcpProcess:{}] Process started", display_name);
Ok(Self {
stdin,
child: Arc::new(Mutex::new(Some(child))),
pending,
next_id: Arc::new(AtomicU64::new(1)),
alive,
notification_tx,
display_name: display_name.to_string(),
command: command.to_string(),
_reader_handle: reader_handle,
})
}
/// Whether the process is still alive.
pub fn is_alive(&self) -> bool {
self.alive.load(Ordering::SeqCst)
}
/// Send a JSON-RPC request and wait for the response.
pub async fn send_request(
&self,
method: &str,
params: serde_json::Value,
timeout_ms: Option<u64>,
) -> Result<serde_json::Value, String> {
if !self.is_alive() {
return Err(format!("{} process is not alive", self.display_name));
}
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
let (tx, rx) = oneshot::channel();
self.pending.lock().await.insert(id, tx);
let msg = serde_json::json!({
"jsonrpc": "2.0",
"id": id,
"method": method,
"params": params,
});
let data = format!("{}\n", serde_json::to_string(&msg).unwrap());
{
let mut stdin = self.stdin.lock().await;
stdin
.write_all(data.as_bytes())
.await
.map_err(|e| format!("Write {}: {}", method, e))?;
stdin
.flush()
.await
.map_err(|e| format!("Flush {}: {}", method, e))?;
}
// Determine timeout based on method and command type
// npx/uvx agents may need longer timeout for first-time package download
let is_npx_or_uvx = self.command == "npx" || self.command == "uvx";
let default_timeout = match method {
"initialize" | "session/new" | "session/load" => {
if is_npx_or_uvx {
120_000 // 2 min for npx/uvx (may need to download packages)
} else {
15_000 // 15s for others
}
}
"session/prompt" => 300_000, // 5 min
_ => 30_000,
};
let timeout_dur = Duration::from_millis(timeout_ms.unwrap_or(default_timeout));
match tokio::time::timeout(timeout_dur, rx).await {
Ok(Ok(result)) => result,
Ok(Err(_)) => Err(format!("Channel closed for {} (id={})", method, id)),
Err(_) => {
self.pending.lock().await.remove(&id);
Err(format!(
"Timeout waiting for {} (id={}, {}ms)",
method,
id,
timeout_dur.as_millis()
))
}
}
}
/// Initialize the ACP protocol.
pub async fn initialize(&self) -> Result<serde_json::Value, String> {
self.initialize_with_timeout(None).await
}
/// Initialize the ACP protocol with an optional timeout override.
pub async fn initialize_with_timeout(
&self,
timeout_ms: Option<u64>,
) -> Result<serde_json::Value, String> {
let result = self
.send_request(
"initialize",
serde_json::json!({
"protocolVersion": 1,
"clientInfo": {
"name": "routa-desktop",
"version": "0.1.0"
}
}),
timeout_ms,
)
.await?;
tracing::info!(
"[AcpProcess:{}] Initialized: {}",
self.display_name,
serde_json::to_string(&result).unwrap_or_default()
);
Ok(result)
}
/// Create a new ACP session. Returns the agent's session ID.
pub async fn new_session(
&self,
cwd: &str,
mcp_servers: &[serde_json::Value],
) -> Result<String, String> {
let result = self
.send_request(
"session/new",
serde_json::json!({
"cwd": cwd,
"mcpServers": mcp_servers
}),
None,
)
.await?;
let session_id = result["sessionId"]
.as_str()
.ok_or_else(|| "No sessionId in session/new response".to_string())?
.to_string();
tracing::info!(
"[AcpProcess:{}] Session created: {}",
self.display_name,
session_id
);
Ok(session_id)
}
/// Load a persisted ACP session. Returns the agent's resumed session ID.
pub async fn load_session(
&self,
session_id: &str,
cwd: &str,
mcp_servers: &[serde_json::Value],
) -> Result<String, String> {
let result = self
.send_request(
"session/load",
serde_json::json!({
"sessionId": session_id,
"cwd": cwd,
"mcpServers": mcp_servers,
}),
None,
)
.await?;
let resumed_session_id = result["sessionId"]
.as_str()
.unwrap_or(session_id)
.to_string();
tracing::info!(
"[AcpProcess:{}] Session loaded: {}",
self.display_name,
resumed_session_id
);
Ok(resumed_session_id)
}
/// Send a prompt to an existing session. 5-minute timeout.
pub async fn prompt(&self, session_id: &str, text: &str) -> Result<serde_json::Value, String> {
self.send_request(
"session/prompt",
serde_json::json!({
"sessionId": session_id,
"prompt": [{ "type": "text", "text": text }]
}),
Some(300_000),
)
.await
}
/// Send session/cancel notification (no response expected).
pub async fn cancel(&self, session_id: &str) {
let msg = serde_json::json!({
"jsonrpc": "2.0",
"method": "session/cancel",
"params": { "sessionId": session_id }
});
let data = format!("{}\n", serde_json::to_string(&msg).unwrap());
let mut stdin = self.stdin.lock().await;
let _ = stdin.write_all(data.as_bytes()).await;
let _ = stdin.flush().await;
}
/// Get the notification broadcast sender (for subscribing to SSE).
pub fn notification_sender(&self) -> &NotificationSender {
&self.notification_tx
}
/// Kill the agent process.
pub async fn kill(&self) {
self.alive.store(false, Ordering::SeqCst);
if let Some(mut child) = self.child.lock().await.take() {
tracing::info!("[AcpProcess:{}] Killing process", self.display_name);
let _ = child.kill().await;
}
// Reject all pending requests
let mut map = self.pending.lock().await;
for (_, tx) in map.drain() {
let _ = tx.send(Err("Process killed".to_string()));
}
}
}
/// Handle agent→client requests. Auto-approves permissions, handles fs ops.
async fn handle_agent_request(
method: &str,
params: &serde_json::Value,
session_id: &str,
notification_tx: &NotificationSender,
) -> serde_json::Value {
match method {
"session/request_permission" => {
tracing::info!("[AcpProcess] session/request_permission params={}", params);
build_permission_approval_result(params)
}
"fs/read_text_file" => {
let path = params["path"].as_str().unwrap_or("");
match tokio::fs::read_to_string(path).await {
Ok(content) => serde_json::json!({ "content": content }),
Err(e) => serde_json::json!({
"error": format!("Failed to read file: {}", e)
}),
}
}
"fs/write_text_file" => {
let path = params["path"].as_str().unwrap_or("");
let content = params["content"].as_str().unwrap_or("");
if let Some(parent) = std::path::Path::new(path).parent() {
let _ = tokio::fs::create_dir_all(parent).await;
}
match tokio::fs::write(path, content).await {
Ok(_) => serde_json::json!({}),
Err(e) => serde_json::json!({
"error": format!("Failed to write file: {}", e)
}),
}
}
"terminal/create" => {
match TerminalManager::global()
.create(params, session_id, notification_tx)
.await
{
Ok(result) => result,
Err(error) => serde_json::json!({ "error": error }),
}
}
"terminal/output" => {
let terminal_id = params["terminalId"].as_str().unwrap_or("");
match TerminalManager::global().get_output(terminal_id).await {
Ok(result) => result,
Err(error) => serde_json::json!({ "error": error }),
}
}
"terminal/wait_for_exit" => {
let terminal_id = params["terminalId"].as_str().unwrap_or("");
match TerminalManager::global().wait_for_exit(terminal_id).await {
Ok(result) => result,
Err(error) => serde_json::json!({ "error": error }),
}
}
"terminal/kill" => {
let terminal_id = params["terminalId"].as_str().unwrap_or("");
match TerminalManager::global().kill(terminal_id).await {
Ok(_) => serde_json::json!({}),
Err(error) => serde_json::json!({ "error": error }),
}
}
"terminal/release" => {
let terminal_id = params["terminalId"].as_str().unwrap_or("");
TerminalManager::global().release(terminal_id).await;
serde_json::json!({})
}
_ => {
tracing::warn!("[AcpProcess] Unknown agent request: {}", method);
serde_json::json!({})
}
}
}
/// Try to find and parse embedded JSON objects in a line.
fn try_parse_embedded_json(line: &str) -> Option<serde_json::Value> {
let mut depth = 0i32;
let mut start = None;
for (i, ch) in line.char_indices() {
match ch {
'{' => {
if depth == 0 {
start = Some(i);
}
depth += 1;
}
'}' => {
depth -= 1;
if depth == 0 {
if let Some(s) = start {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&line[s..=i]) {
return Some(v);
}
}
start = None;
}
}
_ => {}
}
}
None
}
/// Build permission approval response following ACP spec and codex-acp expectations.
/// This mirrors the Next.js implementation in acp-process.ts.
fn build_permission_approval_result(params: &serde_json::Value) -> serde_json::Value {
// Default scope is "turn"
let scope = "turn";
// Try to resolve optionId from params.options array
if let Some(option_id) = resolve_permission_option_id(params, scope) {
return serde_json::json!({
"outcome": {
"outcome": "selected",
"optionId": option_id
}
});
}
// Fallback: return cancelled outcome
serde_json::json!({
"outcome": {
"outcome": "cancelled"
}
})
}
/// Resolve the appropriate permission optionId from the options array.
/// Prefers "approved" or "approved-for-session" for turn/session scope.
fn resolve_permission_option_id(params: &serde_json::Value, scope: &str) -> Option<String> {
let options = params.get("options")?.as_array()?;
// Define preferred option IDs based on scope
let preferred_ids = if scope == "session" {
vec![
"approved-for-session",
"approved-always",
"approved-execpolicy-amendment",
"approved",
]
} else {
vec![
"approved",
"approved-once",
"approved-for-session",
"approved-always",
"approved-execpolicy-amendment",
]
};
// Define preferred option kinds
let preferred_kinds = if scope == "session" {
vec!["allow_always", "allow_once"]
} else {
vec!["allow_once", "allow_always"]
};
// First, try to find by preferred optionId
for pref_id in &preferred_ids {
for option in options {
if let Some(option_id) = option.get("optionId").and_then(|v| v.as_str()) {
if option_id == *pref_id {
return Some(option_id.to_string());
}
}
}
}
// Second, try to find by preferred kind
for pref_kind in &preferred_kinds {
for option in options {
if let Some(kind) = option.get("kind").and_then(|v| v.as_str()) {
if kind == *pref_kind {
if let Some(option_id) = option.get("optionId").and_then(|v| v.as_str()) {
return Some(option_id.to_string());
}
}
}
}
}
// Fallback: use first available option or default
if let Some(first_option) = options.first() {
if let Some(option_id) = first_option.get("optionId").and_then(|v| v.as_str()) {
return Some(option_id.to_string());
}
}
// Last resort: return default based on scope
Some(if scope == "session" {
"approved-for-session".to_string()
} else {
"approved".to_string()
})
}
/// Safely truncate a string at a UTF-8 character boundary.
/// Returns a substring of at most `max_bytes` bytes, but ensures it doesn't
/// cut in the middle of a multi-byte UTF-8 character.
fn truncate_content(s: &str, max_bytes: usize) -> String {
if s.len() <= max_bytes {
return s.to_string();
}
// Find the last valid UTF-8 character boundary before max_bytes
let mut end = max_bytes;
while end > 0 && !s.is_char_boundary(end) {
end -= 1;
}
s[..end].to_string()
}
fn should_ignore_process_stderr(command: &str, display_name: &str, line: &str) -> bool {
is_codex_process(command, display_name) && is_codex_otel_stderr(line)
}
fn is_codex_process(command: &str, display_name: &str) -> bool {
let trimmed_command = command.trim();
display_name.trim().eq_ignore_ascii_case("codex")
|| trimmed_command.eq_ignore_ascii_case("codex-acp")
|| trimmed_command.ends_with("/codex-acp")
}
fn is_codex_otel_stderr(line: &str) -> bool {
let trimmed = line.trim();
trimmed.contains("codex_otel.log_only:") || trimmed.contains("codex_otel.trace_safe:")
}
#[cfg(test)]
mod tests {
use super::{is_codex_otel_stderr, resolve_permission_option_id, should_ignore_process_stderr};
use serde_json::json;
#[test]
fn ignores_codex_otel_stderr_noise() {
let line = "INFO ... codex_otel.log_only: event.kind=response.output_text.delta";
assert!(should_ignore_process_stderr(
"/opt/homebrew/bin/codex-acp",
"Codex",
line
));
assert!(is_codex_otel_stderr(line));
}
#[test]
fn preserves_non_otel_codex_stderr() {
let line = "ERROR codex_api::endpoint::responses_websocket: failed to connect";
assert!(!should_ignore_process_stderr(
"/opt/homebrew/bin/codex-acp",
"Codex",
line
));
}
#[test]
fn preserves_other_provider_stderr() {
let line = "INFO ... codex_otel.log_only: event.kind=response.output_text.delta";
assert!(!should_ignore_process_stderr(
"/usr/bin/opencode",
"OpenCode",
line
));
}
#[test]
fn resolve_permission_option_id_prefers_turn_approval() {
let params = json!({
"options": [
{ "optionId": "denied", "kind": "deny_once" },
{ "optionId": "approved", "kind": "allow_once" }
]
});
assert_eq!(
resolve_permission_option_id(¶ms, "turn").as_deref(),
Some("approved")
);
}
}