-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmod.rs
More file actions
2191 lines (2018 loc) · 88.5 KB
/
mod.rs
File metadata and controls
2191 lines (2018 loc) · 88.5 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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0
use std::cell::RefCell;
use std::path::{Component, PathBuf};
use std::pin::Pin;
use std::rc::Rc;
use std::sync::Arc;
use agent_client_protocol as acp;
use futures::StreamExt as _;
use tokio::sync::{mpsc, oneshot};
use zeph_core::channel::{ChannelMessage, LoopbackChannel, LoopbackHandle};
use zeph_core::text::truncate_to_chars;
use zeph_core::{LoopbackEvent, StopHint};
use zeph_llm::any::AnyProvider;
use zeph_llm::provider::LlmProvider as _;
use zeph_mcp::McpManager;
use zeph_mcp::manager::ServerEntry;
use zeph_memory::ConversationId;
use zeph_memory::store::SqliteStore;
use zeph_tools::is_private_ip;
use crate::fs::AcpFileExecutor;
use crate::lsp::DiagnosticsCache;
use crate::permission::AcpPermissionGate;
use crate::terminal::AcpShellExecutor;
use crate::transport::{ConnSlot, SharedAvailableModels};
/// Factory that creates a provider by `{provider}:{model}` key.
pub type ProviderFactory = Arc<dyn Fn(&str) -> Option<AnyProvider> + Send + Sync>;
/// Per-session context passed to the agent spawner.
///
/// `conversation_id` is `Some` when a `SQLite`-backed [`ConversationId`] was
/// successfully created or retrieved for this session. `None` means the store
/// was unavailable at session creation time; the agent operates without
/// persistent history in that case.
pub struct SessionContext {
pub session_id: acp::SessionId,
pub conversation_id: Option<ConversationId>,
pub working_dir: PathBuf,
}
const MAX_PROMPT_BYTES: usize = 1_048_576; // 1 MiB
const MAX_IMAGE_BASE64_BYTES: usize = 20 * 1_048_576; // 20 MiB base64-encoded
const SUPPORTED_IMAGE_MIMES: &[&str] = &[
"image/jpeg",
"image/jpg",
"image/png",
"image/gif",
"image/webp",
];
const LOOPBACK_CHANNEL_CAPACITY: usize = 64;
/// Maximum bytes fetched from an HTTP resource link.
const MAX_RESOURCE_BYTES: usize = 1_048_576; // 1 MiB
/// Timeout for HTTP resource link fetch.
const RESOURCE_FETCH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
/// Pseudo-filesystem path components that expose secrets or kernel internals.
const BLOCKED_PATH_COMPONENTS: &[&str] = &["proc", "sys", "dev", ".ssh", ".gnupg", ".aws"];
/// Resolve a `ResourceLink` URI to its text content.
///
/// Supports `file://` and `http(s)://` URIs. Returns an error for unsupported
/// schemes or security violations (SSRF, path traversal, binary content).
///
/// `session_cwd` is used as the allowed root for `file://` URIs. Only paths
/// that are descendants of `session_cwd` are permitted.
async fn resolve_resource_link(
link: &acp::ResourceLink,
session_cwd: &std::path::Path,
) -> Result<String, crate::error::AcpError> {
let uri = &link.uri;
if let Some(path_str) = uri.strip_prefix("file://") {
// Canonicalize to resolve symlinks and `..` — single syscall, no TOCTOU.
let path = std::path::Path::new(path_str);
// Pre-check size to avoid loading large files into memory before rejection.
let meta = tokio::time::timeout(RESOURCE_FETCH_TIMEOUT, tokio::fs::metadata(path))
.await
.map_err(|_| {
crate::error::AcpError::ResourceLink(format!("file:// metadata timed out: {uri}"))
})?
.map_err(|e| {
crate::error::AcpError::ResourceLink(format!("file:// stat failed: {e}"))
})?;
if meta.len() > MAX_RESOURCE_BYTES as u64 {
return Err(crate::error::AcpError::ResourceLink(format!(
"file:// content exceeds size limit ({MAX_RESOURCE_BYTES} bytes): {uri}"
)));
}
let canonical = tokio::fs::canonicalize(path).await.map_err(|e| {
crate::error::AcpError::ResourceLink(format!("file:// resolution failed: {e}"))
})?;
// Enforce cwd boundary: only files inside the session working directory are allowed.
if !canonical.starts_with(session_cwd) {
return Err(crate::error::AcpError::ResourceLink(format!(
"file:// path outside session working directory: {uri}"
)));
}
// Reject pseudo-filesystems and sensitive directories.
for component in canonical.components() {
if let Component::Normal(name) = component {
let name_str = name.to_string_lossy();
if BLOCKED_PATH_COMPONENTS
.iter()
.any(|blocked| name_str == *blocked)
{
return Err(crate::error::AcpError::ResourceLink(format!(
"file:// path blocked: {uri}"
)));
}
}
}
let bytes = tokio::time::timeout(RESOURCE_FETCH_TIMEOUT, tokio::fs::read(&canonical))
.await
.map_err(|_| {
crate::error::AcpError::ResourceLink(format!("file:// read timed out: {uri}"))
})?
.map_err(|e| {
crate::error::AcpError::ResourceLink(format!("file:// read failed: {e}"))
})?;
// Reject binary files (null byte check — S-1).
if bytes.contains(&0u8) {
return Err(crate::error::AcpError::ResourceLink(format!(
"binary file not supported as ResourceLink content: {uri}"
)));
}
String::from_utf8(bytes).map_err(|_| {
crate::error::AcpError::ResourceLink(format!(
"file:// content is not valid UTF-8: {uri}"
))
})
} else if uri.starts_with("http://") || uri.starts_with("https://") {
// No-redirect policy prevents redirect-based SSRF bypass.
let client = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.timeout(RESOURCE_FETCH_TIMEOUT)
.build()
.map_err(|e| crate::error::AcpError::ResourceLink(format!("HTTP client error: {e}")))?;
let resp = client
.get(uri.as_str())
.header(reqwest::header::ACCEPT, "text/*")
.send()
.await
.map_err(|e| crate::error::AcpError::ResourceLink(format!("HTTP fetch failed: {e}")))?;
// Post-fetch IP check: eliminates DNS rebinding TOCTOU window (RC-1).
// Fail-closed: if remote_addr() is unavailable (e.g. rustls), reject the response.
match resp.remote_addr() {
None => {
return Err(crate::error::AcpError::ResourceLink(format!(
"SSRF check failed: remote address unavailable for {uri}"
)));
}
Some(remote_addr) if is_private_ip(remote_addr.ip()) => {
return Err(crate::error::AcpError::ResourceLink(format!(
"SSRF blocked: {uri} resolved to private address {remote_addr}"
)));
}
Some(_) => {}
}
if !resp.status().is_success() {
return Err(crate::error::AcpError::ResourceLink(format!(
"HTTP fetch returned {}: {uri}",
resp.status()
)));
}
// Reject non-text content types.
let content_type = resp
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
if !content_type.is_empty() && !content_type.starts_with("text/") {
return Err(crate::error::AcpError::ResourceLink(format!(
"non-text MIME type rejected for ResourceLink: {content_type}"
)));
}
// Stream up to MAX_RESOURCE_BYTES to avoid unbounded memory use.
let mut body = resp.bytes_stream();
let mut buf = Vec::with_capacity(4096);
while let Some(chunk) = body.next().await {
let chunk = chunk.map_err(|e| {
crate::error::AcpError::ResourceLink(format!("HTTP read error: {e}"))
})?;
if buf.len() + chunk.len() > MAX_RESOURCE_BYTES {
buf.extend_from_slice(&chunk[..MAX_RESOURCE_BYTES.saturating_sub(buf.len())]);
break;
}
buf.extend_from_slice(&chunk);
}
String::from_utf8(buf).map_err(|_| {
crate::error::AcpError::ResourceLink(format!(
"HTTP response body is not valid UTF-8: {uri}"
))
})
} else {
Err(crate::error::AcpError::ResourceLink(format!(
"unsupported URI scheme in ResourceLink: {uri}"
)))
}
}
/// IDE-proxied capabilities passed to the agent loop per session.
///
/// Each field is `None` when the IDE did not advertise the corresponding capability.
pub struct AcpContext {
pub file_executor: Option<AcpFileExecutor>,
pub shell_executor: Option<AcpShellExecutor>,
pub permission_gate: Option<AcpPermissionGate>,
/// Shared cancellation signal: notify to interrupt the running agent operation.
pub cancel_signal: std::sync::Arc<tokio::sync::Notify>,
/// Shared slot for runtime model switching via `set_session_config_option`.
/// When `Some`, the agent should swap its provider before the next turn.
pub provider_override: Arc<std::sync::RwLock<Option<AnyProvider>>>,
/// Tool call ID of the parent agent's tool call that spawned this subagent session.
/// `None` for top-level (non-subagent) sessions.
pub parent_tool_use_id: Option<String>,
/// LSP provider when the IDE advertised `meta["lsp"]` capability.
pub lsp_provider: Option<crate::lsp::AcpLspProvider>,
/// Shared diagnostics cache — written by the LSP notification handler in `ZephAcpAgent`
/// and read by the agent loop context builder to inject diagnostics into the system prompt.
pub diagnostics_cache: Arc<std::sync::RwLock<DiagnosticsCache>>,
}
/// Factory: receives a [`LoopbackChannel`], optional [`AcpContext`], and [`SessionContext`],
/// then runs the agent loop.
///
/// Each call creates an independent agent with its own conversation history,
/// enabling true multi-session isolation.
pub type AgentSpawner = Arc<
dyn Fn(
LoopbackChannel,
Option<AcpContext>,
SessionContext,
) -> Pin<Box<dyn std::future::Future<Output = ()> + 'static>>
+ Send
+ Sync
+ 'static,
>;
/// Thread-safe variant of `AgentSpawner` required by the HTTP transport.
///
/// Used with `AcpHttpState` to satisfy `axum::State` requirements (`Send + Sync`).
#[cfg(feature = "acp-http")]
pub type SendAgentSpawner = AgentSpawner;
/// Sender half for delivering session notifications to the background writer.
pub(crate) type NotifySender =
mpsc::UnboundedSender<(acp::SessionNotification, oneshot::Sender<()>)>;
pub(crate) struct SessionEntry {
pub(crate) input_tx: mpsc::Sender<ChannelMessage>,
// Receiver is owned solely by the prompt() handler; RefCell avoids Arc<Mutex> overhead.
// prompt() is not called concurrently for the same session.
pub(crate) output_rx: RefCell<Option<mpsc::Receiver<LoopbackEvent>>>,
pub(crate) cancel_signal: std::sync::Arc<tokio::sync::Notify>,
pub(crate) last_active: std::cell::Cell<std::time::Instant>,
pub(crate) created_at: chrono::DateTime<chrono::Utc>,
pub(crate) working_dir: RefCell<Option<std::path::PathBuf>>,
/// Shared provider override slot; written by `set_session_config_option`, read by agent loop.
provider_override: Arc<std::sync::RwLock<Option<AnyProvider>>>,
/// Currently selected model identifier (display / tracking only).
current_model: RefCell<String>,
/// Current session mode (ask / architect / code).
current_mode: RefCell<acp::SessionModeId>,
/// Set after the first successful prompt so title generation fires only once.
first_prompt_done: std::cell::Cell<bool>,
/// Auto-generated session title; populated after first prompt via `SessionTitle` event.
title: RefCell<Option<String>>,
/// Whether extended thinking is enabled for this session.
thinking_enabled: std::cell::Cell<bool>,
/// Auto-approve level for this session ("suggest" | "auto-edit" | "full-auto").
auto_approve_level: RefCell<String>,
/// Shell executor for this session, retained so the event loop can release terminals
/// after `tool_call_update` notifications are sent (ACP requires the terminal to
/// remain alive until after the notification that embeds it).
pub(crate) shell_executor: Option<AcpShellExecutor>,
}
type SessionMap = Rc<RefCell<std::collections::HashMap<acp::SessionId, SessionEntry>>>;
pub struct ZephAcpAgent {
notify_tx: NotifySender,
spawner: AgentSpawner,
pub(crate) sessions: SessionMap,
conn_slot: ConnSlot,
agent_name: String,
agent_version: String,
max_sessions: usize,
idle_timeout: std::time::Duration,
pub(crate) store: Option<SqliteStore>,
permission_file: Option<std::path::PathBuf>,
// IDE capabilities received during initialize(); used by build_acp_context.
client_caps: RefCell<acp::ClientCapabilities>,
/// Factory for creating a new provider by `{provider}:{model}` key.
provider_factory: Option<ProviderFactory>,
/// Available model identifiers advertised in `new_session` `config_options`.
available_models: SharedAvailableModels,
/// Shared MCP manager for `ext_method` add/remove/list.
mcp_manager: Option<Arc<McpManager>>,
/// Project rule file paths advertised in `new_session` `_meta`.
project_rules: Vec<std::path::PathBuf>,
/// Maximum characters for auto-generated session titles.
title_max_chars: usize,
/// Maximum number of sessions returned by `list_sessions` (0 = unlimited).
max_history: usize,
/// LSP extension configuration (from `[acp.lsp]`).
lsp_config: zeph_core::config::AcpLspConfig,
/// Per-agent diagnostics cache, shared between the agent (writer) and `AcpContext` (reader).
diagnostics_cache: Arc<std::sync::RwLock<DiagnosticsCache>>,
}
impl ZephAcpAgent {
pub fn new(
spawner: AgentSpawner,
notify_tx: NotifySender,
conn_slot: ConnSlot,
max_sessions: usize,
session_idle_timeout_secs: u64,
permission_file: Option<std::path::PathBuf>,
) -> Self {
let lsp_config = zeph_core::config::AcpLspConfig::default();
let max_diag_files = lsp_config.max_diagnostic_files;
Self {
notify_tx,
spawner,
sessions: Rc::new(RefCell::new(std::collections::HashMap::new())),
conn_slot,
agent_name: "zeph".to_owned(),
agent_version: env!("CARGO_PKG_VERSION").to_owned(),
max_sessions,
idle_timeout: std::time::Duration::from_secs(session_idle_timeout_secs),
store: None,
permission_file,
client_caps: RefCell::new(acp::ClientCapabilities::default()),
provider_factory: None,
available_models: Arc::new(std::sync::RwLock::new(Vec::new())),
mcp_manager: None,
project_rules: Vec::new(),
title_max_chars: 60,
max_history: 100,
lsp_config,
diagnostics_cache: Arc::new(std::sync::RwLock::new(DiagnosticsCache::new(
max_diag_files,
))),
}
}
/// Configure LSP extension settings.
#[must_use]
pub fn with_lsp_config(mut self, config: zeph_core::config::AcpLspConfig) -> Self {
let max_files = config.max_diagnostic_files;
self.lsp_config = config;
self.diagnostics_cache = Arc::new(std::sync::RwLock::new(DiagnosticsCache::new(max_files)));
self
}
#[must_use]
pub fn with_store(mut self, store: SqliteStore) -> Self {
self.store = Some(store);
self
}
#[must_use]
pub fn with_agent_info(mut self, name: impl Into<String>, version: impl Into<String>) -> Self {
self.agent_name = name.into();
self.agent_version = version.into();
self
}
#[must_use]
pub fn with_provider_factory(
mut self,
factory: ProviderFactory,
available_models: SharedAvailableModels,
) -> Self {
self.provider_factory = Some(factory);
self.available_models = available_models;
self
}
fn available_models_snapshot(&self) -> Vec<String> {
self.available_models
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
fn initial_model(&self) -> String {
self.available_models_snapshot()
.into_iter()
.next()
.unwrap_or_default()
}
#[must_use]
pub fn with_mcp_manager(mut self, manager: Arc<McpManager>) -> Self {
self.mcp_manager = Some(manager);
self
}
#[must_use]
pub fn with_project_rules(mut self, rules: Vec<std::path::PathBuf>) -> Self {
self.project_rules = rules;
self
}
#[must_use]
pub fn with_title_max_chars(mut self, max_chars: usize) -> Self {
self.title_max_chars = max_chars;
self
}
#[must_use]
pub fn with_max_history(mut self, max_history: usize) -> Self {
self.max_history = max_history;
self
}
/// Spawn a background task that periodically evicts idle sessions.
///
/// Must be called from within a `LocalSet` context.
pub fn start_idle_reaper(&self) {
let sessions = Rc::clone(&self.sessions);
let idle_timeout = self.idle_timeout;
tokio::task::spawn_local(async move {
let mut interval = tokio::time::interval(std::time::Duration::from_secs(60));
interval.tick().await; // skip first tick
loop {
interval.tick().await;
let now = std::time::Instant::now();
let expired: Vec<acp::SessionId> = sessions
.borrow()
.iter()
.filter(|(_, e)| {
// Only evict idle sessions (output_rx is Some = not busy).
e.output_rx.borrow().is_some()
&& now.duration_since(e.last_active.get()) > idle_timeout
})
.map(|(id, _)| id.clone())
.collect();
for id in expired {
if let Some(entry) = sessions.borrow_mut().remove(&id) {
entry.cancel_signal.notify_one();
tracing::debug!(session_id = %id, "evicted idle ACP session (timeout)");
}
}
}
});
}
fn build_acp_context(
&self,
session_id: &acp::SessionId,
cancel_signal: std::sync::Arc<tokio::sync::Notify>,
provider_override: Arc<std::sync::RwLock<Option<AnyProvider>>>,
cwd: PathBuf,
) -> Option<AcpContext> {
let conn_guard = self.conn_slot.borrow();
let conn = conn_guard.as_ref()?;
let (perm_gate, perm_handler) =
AcpPermissionGate::new(Rc::clone(conn), self.permission_file.clone());
tokio::task::spawn_local(perm_handler);
// Use actual IDE capabilities from initialize(); default to false (deny by default).
let caps = self.client_caps.borrow();
let can_read = caps.fs.read_text_file;
let can_write = caps.fs.write_text_file;
let ide_supports_lsp =
self.lsp_config.enabled && caps.meta.as_ref().is_some_and(|m| m.contains_key("lsp"));
drop(caps);
let (fs_exec, fs_handler) = AcpFileExecutor::new(
Rc::clone(conn),
session_id.clone(),
can_read,
can_write,
cwd,
Some(perm_gate.clone()),
);
tokio::task::spawn_local(fs_handler);
let (shell_exec, shell_handler) = AcpShellExecutor::new(
Rc::clone(conn),
session_id.clone(),
Some(perm_gate.clone()),
120,
);
tokio::task::spawn_local(shell_handler);
let lsp_provider = if ide_supports_lsp {
let (provider, handler) = crate::lsp::AcpLspProvider::new(
Rc::clone(conn),
true,
self.lsp_config.request_timeout_secs,
self.lsp_config.max_references,
self.lsp_config.max_workspace_symbols,
);
tokio::task::spawn_local(handler);
Some(provider)
} else {
None
};
Some(AcpContext {
file_executor: Some(fs_exec),
shell_executor: Some(shell_exec),
permission_gate: Some(perm_gate),
cancel_signal,
provider_override,
parent_tool_use_id: None,
lsp_provider,
diagnostics_cache: Arc::clone(&self.diagnostics_cache),
})
}
async fn send_notification(&self, notification: acp::SessionNotification) -> acp::Result<()> {
let (tx, rx) = oneshot::channel();
self.notify_tx
.send((notification, tx))
.map_err(|_| acp::Error::internal_error().data("notification channel closed"))?;
rx.await
.map_err(|_| acp::Error::internal_error().data("notification ack lost"))
}
fn handle_lsp_publish_diagnostics(&self, params: &str) {
#[derive(serde::Deserialize)]
struct PublishDiagnosticsParams {
uri: String,
#[serde(default)]
diagnostics: Vec<crate::lsp::LspDiagnostic>,
}
match serde_json::from_str::<PublishDiagnosticsParams>(params) {
Ok(p) => {
let max = self.lsp_config.max_diagnostics_per_file;
let mut diags = p.diagnostics;
diags.truncate(max);
tracing::debug!(
uri = %p.uri,
count = diags.len(),
"lsp/publishDiagnostics: cached"
);
self.diagnostics_cache
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.update(p.uri, diags);
}
Err(e) => {
tracing::warn!(error = %e, "lsp/publishDiagnostics: failed to parse params");
}
}
}
async fn handle_lsp_did_save(&self, params: &str) {
#[derive(serde::Deserialize)]
struct DidSaveParams {
uri: String,
}
use acp::Client as _;
if !self.lsp_config.auto_diagnostics_on_save {
return;
}
let uri = match serde_json::from_str::<DidSaveParams>(params) {
Ok(p) => p.uri,
Err(e) => {
tracing::warn!(error = %e, "lsp/didSave: failed to parse params");
return;
}
};
let conn = {
let guard = self.conn_slot.borrow();
guard.as_ref().cloned()
};
let Some(conn) = conn else {
return;
};
let params_json = serde_json::json!({ "uri": &uri });
let raw = match serde_json::value::to_raw_value(¶ms_json) {
Ok(r) => r,
Err(e) => {
tracing::warn!(error = %e, "lsp/didSave: failed to serialize params");
return;
}
};
let req = acp::ExtRequest::new("lsp/diagnostics", std::sync::Arc::from(raw));
let timeout = std::time::Duration::from_secs(self.lsp_config.request_timeout_secs);
match tokio::time::timeout(timeout, conn.ext_method(req)).await {
Ok(Ok(resp)) => {
match serde_json::from_str::<Vec<crate::lsp::LspDiagnostic>>(resp.0.get()) {
Ok(mut diags) => {
let max = self.lsp_config.max_diagnostics_per_file;
diags.truncate(max);
tracing::debug!(
uri = %uri,
count = diags.len(),
"lsp/didSave: fetched diagnostics"
);
self.diagnostics_cache
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.update(uri, diags);
}
Err(e) => {
tracing::warn!(error = %e, "lsp/didSave: failed to parse diagnostics response");
}
}
}
Ok(Err(e)) => {
tracing::warn!(error = %e, "lsp/didSave: diagnostics request failed");
}
Err(_) => {
tracing::warn!(uri = %uri, "lsp/didSave: diagnostics request timed out");
}
}
}
}
#[derive(serde::Deserialize)]
struct McpRemoveParams {
id: String,
}
/// Look up the `ConversationId` for an existing ACP session, creating one for legacy
/// sessions that predate migration 026 (where `conversation_id` is `NULL`).
///
/// Returns `None` when the store is unavailable or all creation attempts fail, allowing
/// the caller to proceed in ephemeral (no-history) mode rather than failing the session.
async fn resolve_conversation_id(
store: &zeph_memory::store::SqliteStore,
session_id: &acp::SessionId,
) -> Option<ConversationId> {
match store
.get_acp_session_conversation_id(&session_id.to_string())
.await
{
Ok(Some(cid)) => Some(cid),
Ok(None) => {
// Legacy session (conversation_id IS NULL): create and persist.
match store.create_conversation().await {
Ok(cid) => {
if let Err(e) = store
.set_acp_session_conversation_id(&session_id.to_string(), cid)
.await
{
tracing::warn!(error = %e, "failed to set conversation_id for legacy session");
}
Some(cid)
}
Err(e) => {
tracing::warn!(error = %e, "failed to create conversation for legacy session; session will have no persistent history");
None
}
}
}
Err(e) => {
tracing::warn!(error = %e, "failed to look up conversation_id; session will have no persistent history");
None
}
}
}
#[async_trait::async_trait(?Send)]
impl acp::Agent for ZephAcpAgent {
async fn initialize(
&self,
args: acp::InitializeRequest,
) -> acp::Result<acp::InitializeResponse> {
tracing::debug!("ACP initialize");
*self.client_caps.borrow_mut() = args.client_capabilities;
let title = format!("{} AI Agent", self.agent_name);
// stdio transport implies a trusted local client; do not expose internal
// configuration details. Provide only a generic authentication hint.
let mut meta = serde_json::Map::new();
meta.insert(
"auth_hint".to_owned(),
serde_json::json!("authentication required"),
);
let mut caps = acp::AgentCapabilities::new()
.load_session(true)
.prompt_capabilities(
acp::PromptCapabilities::new()
.image(true)
.embedded_context(true),
)
.meta({
let mut cap_meta = serde_json::Map::new();
cap_meta.insert("config_options".to_owned(), serde_json::json!(true));
cap_meta.insert("ext_methods".to_owned(), serde_json::json!(true));
if self.lsp_config.enabled {
cap_meta.insert(
"lsp".to_owned(),
serde_json::json!({
"methods": crate::lsp::LSP_METHODS,
"notifications": crate::lsp::LSP_NOTIFICATIONS,
}),
);
}
cap_meta
});
// Advertise MCP transport capabilities when McpManager is present.
// Only StreamableHTTP (http=true) is supported; SSE is deprecated in MCP spec 2025-11-25.
if self.mcp_manager.is_some() {
caps = caps.mcp_capabilities(acp::McpCapabilities::new().http(true).sse(false));
}
#[cfg(any(feature = "unstable-session-fork", feature = "unstable-session-resume",))]
let caps = {
let mut session_caps = acp::SessionCapabilities::new();
session_caps = session_caps.list(acp::SessionListCapabilities::default());
#[cfg(feature = "unstable-session-fork")]
{
session_caps = session_caps.fork(acp::SessionForkCapabilities::default());
}
#[cfg(feature = "unstable-session-resume")]
{
session_caps = session_caps.resume(acp::SessionResumeCapabilities::default());
}
caps.session_capabilities(session_caps)
};
#[cfg(feature = "unstable-logout")]
let caps = caps
.auth(acp::AgentAuthCapabilities::default().logout(acp::LogoutCapabilities::default()));
Ok(acp::InitializeResponse::new(acp::ProtocolVersion::LATEST)
.agent_info(
acp::Implementation::new(&self.agent_name, &self.agent_version).title(title),
)
.agent_capabilities(caps)
.meta(meta))
}
async fn ext_method(&self, args: acp::ExtRequest) -> acp::Result<acp::ExtResponse> {
if let Some(fut) = crate::custom::dispatch(self, &args) {
return fut.await;
}
// Fall through to inline MCP management methods from main.
// Defined below in the second ext_method block merged from origin/main.
self.ext_method_mcp(&args).await
}
async fn ext_notification(&self, args: acp::ExtNotification) -> acp::Result<()> {
tracing::debug!(method = %args.method, "received ext_notification");
match args.method.as_ref() {
"lsp/publishDiagnostics" => {
self.handle_lsp_publish_diagnostics(args.params.get());
}
"lsp/didSave" => {
self.handle_lsp_did_save(args.params.get()).await;
}
_ => {}
}
Ok(())
}
async fn authenticate(
&self,
_args: acp::AuthenticateRequest,
) -> acp::Result<acp::AuthenticateResponse> {
// stdio transport: authentication is a no-op, IDE client is trusted.
Ok(acp::AuthenticateResponse::default())
}
#[cfg(feature = "unstable-logout")]
async fn logout(&self, _args: acp::LogoutRequest) -> acp::Result<acp::LogoutResponse> {
// Zeph uses vault-based authentication, not session-based auth.
// Logout is a no-op but we advertise the capability for protocol compliance.
tracing::debug!("ACP logout (no-op: vault-based auth)");
Ok(acp::LogoutResponse::default())
}
async fn new_session(
&self,
args: acp::NewSessionRequest,
) -> acp::Result<acp::NewSessionResponse> {
// LRU eviction: find and remove the oldest idle (non-busy) session when at limit.
if self.sessions.borrow().len() >= self.max_sessions {
let evict_id = {
let sessions = self.sessions.borrow();
sessions
.iter()
.filter(|(_, e)| e.output_rx.borrow().is_some())
.min_by_key(|(_, e)| e.last_active.get())
.map(|(id, _)| id.clone())
};
match evict_id {
Some(id) => {
if let Some(entry) = self.sessions.borrow_mut().remove(&id) {
entry.cancel_signal.notify_one();
tracing::debug!(session_id = %id, "evicted idle ACP session (LRU)");
}
}
None => {
return Err(acp::Error::internal_error().data("session limit reached"));
}
}
}
let session_id = acp::SessionId::new(uuid::Uuid::new_v4().to_string());
tracing::debug!(%session_id, "new ACP session");
let (channel, handle) = LoopbackChannel::pair(LOOPBACK_CHANNEL_CAPACITY);
// Clone once for build_acp_context; ownership of the original moves into SessionEntry.
let cancel_signal = std::sync::Arc::clone(&handle.cancel_signal);
let provider_override: Arc<std::sync::RwLock<Option<AnyProvider>>> =
Arc::new(std::sync::RwLock::new(None));
let provider_override_for_ctx = Arc::clone(&provider_override);
let session_cwd = args.cwd.clone();
let acp_ctx = self.build_acp_context(
&session_id,
cancel_signal,
provider_override_for_ctx,
session_cwd.clone(),
);
let shell_executor = acp_ctx.as_ref().and_then(|c| c.shell_executor.clone());
let initial_model = self.initial_model();
let entry = Self::make_session_entry(
handle,
initial_model.clone(),
session_cwd.clone(),
shell_executor,
provider_override,
);
self.sessions.borrow_mut().insert(session_id.clone(), entry);
// Create a fresh conversation for this session and persist the session<->conversation
// mapping synchronously so that load_session can always find it. Both operations are
// fast SQLite writes; keeping them inline avoids a race where the agent starts
// load_history() before the mapping is committed.
let conversation_id = self.create_session_conversation(&session_id).await;
let session_ctx = SessionContext {
session_id: session_id.clone(),
conversation_id,
working_dir: session_cwd.clone(),
};
let spawner = Arc::clone(&self.spawner);
tokio::task::spawn_local(async move {
(spawner)(channel, acp_ctx, session_ctx).await;
});
let available_models = self.available_models_snapshot();
let config_options =
build_config_options(&available_models, &initial_model, false, "suggest");
let default_mode_id = acp::SessionModeId::new(DEFAULT_MODE_ID);
let mut resp = acp::NewSessionResponse::new(session_id.clone())
.modes(build_mode_state(&default_mode_id));
if !config_options.is_empty() {
resp = resp.config_options(config_options);
}
if !self.project_rules.is_empty() {
let rules: Vec<serde_json::Value> = self
.project_rules
.iter()
.filter_map(|p| p.file_name())
.map(|n| serde_json::json!({"name": n.to_string_lossy()}))
.collect();
let mut meta = serde_json::Map::new();
meta.insert("projectRules".to_owned(), serde_json::Value::Array(rules));
resp = resp.meta(meta);
}
self.send_commands_update_nowait(session_id);
Ok(resp)
}
async fn prompt(&self, args: acp::PromptRequest) -> acp::Result<acp::PromptResponse> {
tracing::debug!(session_id = %args.session_id, "ACP prompt");
// Capture session cwd for file:// boundary enforcement.
let session_cwd = self
.sessions
.borrow()
.get(&args.session_id)
.and_then(|e| e.working_dir.borrow().clone())
.unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
let (text, attachments) = self
.collect_prompt_content(&args.prompt, &session_cwd)
.await?;
let trimmed_text = text.trim_start();
if trimmed_text.starts_with('/') {
let is_acp_native = trimmed_text == "/help"
|| trimmed_text.starts_with("/help ")
|| trimmed_text == "/mode"
|| trimmed_text.starts_with("/mode ")
|| trimmed_text == "/clear"
|| trimmed_text.starts_with("/review")
|| trimmed_text == "/model"
|| trimmed_text.starts_with("/model ");
if is_acp_native {
return self
.handle_slash_command(&args.session_id, trimmed_text)
.await;
}
}
let (input_tx, output_rx) = {
let sessions = self.sessions.borrow();
let entry = sessions
.get(&args.session_id)
.ok_or_else(|| acp::Error::internal_error().data("session not found"))?;
let rx =
entry.output_rx.borrow_mut().take().ok_or_else(|| {
acp::Error::internal_error().data("prompt already in progress")
})?;
entry.last_active.set(std::time::Instant::now());
(entry.input_tx.clone(), rx)
};
// Persist user message before sending to agent.
if let Some(ref store) = self.store {
let sid = args.session_id.to_string();
let payload = text.clone();
let store = store.clone();
tokio::task::spawn_local(async move {
if let Err(e) = store.save_acp_event(&sid, "user_message", &payload).await {
tracing::warn!(error = %e, "failed to persist user message");
}
});
}
input_tx
.send(ChannelMessage {
text: text.clone(),
attachments,
})
.await
.map_err(|_| acp::Error::internal_error().data("agent channel closed"))?;
// Grab the cancel_signal so we can detect cancellation during the drain loop.
let cancel_signal = self
.sessions
.borrow()
.get(&args.session_id)
.map(|e| std::sync::Arc::clone(&e.cancel_signal));
// Block until the agent finishes this turn (signals via Flush or channel close).
let (cancelled, stop_hint, rx) = self
.drain_agent_events(&args.session_id, output_rx, cancel_signal)
.await;
// Return the receiver so future prompt() calls on this session can proceed.
if let Some(entry) = self.sessions.borrow().get(&args.session_id) {
*entry.output_rx.borrow_mut() = Some(rx);
}
let stop_reason = if cancelled {
acp::StopReason::Cancelled
} else {
match stop_hint {
Some(StopHint::MaxTokens) => acp::StopReason::MaxTokens,
Some(StopHint::MaxTurnRequests) => acp::StopReason::MaxTurnRequests,
None => acp::StopReason::EndTurn,
}
};
// Generate session title after first successful agent response (fire-and-forget).
if !cancelled {
self.maybe_generate_session_title(&args.session_id, &text);
}
Ok(acp::PromptResponse::new(stop_reason))
}
async fn cancel(&self, args: acp::CancelNotification) -> acp::Result<()> {
tracing::debug!(session_id = %args.session_id, "ACP cancel");
// Signal the agent loop to stop, but keep the session alive — the IDE may
// send another prompt on the same session_id after cancellation.
if let Some(entry) = self.sessions.borrow().get(&args.session_id) {
entry.cancel_signal.notify_one();