返回 CodeWhale
acp.rs
1 //! The Engine's one Agent Client Protocol client, over a fleet worker's duplex
2 //! stdio.
3 //!
4 //! The fleet host owns the process: groups, parent-death, stop, restart and
5 //! logs. This module owns only the wire, and the wire is the official
6 //! `agent-client-protocol` SDK: one connection thread per client drives the
7 //! SDK over the worker's pipes, and the caller's thread sends one request at a
8 //! time and answers the agent's requests. What we send is built from the
9 //! official v1 types; what an agent sends is read leniently as JSON. A caller
10 //! supplies an [`AcpHandler`] that sees every `session/update` and answers
11 //! every `session/request_permission`; [`PermissionPolicy`] is the
12 //! fixed-answer handler for callers with no person in the loop.
13 //!
14 //! Deliberately absent: filesystem and terminal client methods (advertised
15 //! false and answered method-not-found), elicitation (declined), `authenticate`
16 //! and any credential handling. The agent runs in its own process with its
17 //! own login and tools, and its stderr stays in the worker log. Messages from
18 //! another session id are ignored, and a permission request for one is
19 //! answered `cancelled`. A line longer than [`MAX_MESSAGE_BYTES`] ends the
20 //! connection rather than being parsed.
21 //!
22 //! Known limits: each message is bounded but the number of queued messages is
23 //! not, so an agent that floods small frames grows memory until the caller
24 //! drains them. A permission request the agent withdraws with
25 //! `$/cancel_request` is answered `cancelled`, but only once the handler
26 //! returns; the handler is not interrupted.
27
28 use std::path::{Path, PathBuf};
29 use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
30 use std::sync::{Arc, Mutex};
31 use std::time::{Duration, Instant};
32
33 use agent_client_protocol::schema::ProtocolVersion;
34 use agent_client_protocol::v1::schema::{
35 CancelNotification, ClientCapabilities, ContentBlock, CreateElicitationResponse,
36 ElicitationAction, Implementation, InitializeRequest, LoadSessionRequest, NewSessionRequest,
37 PromptRequest, RequestPermissionOutcome, RequestPermissionResponse, ResumeSessionRequest,
38 SelectedPermissionOutcome, SetSessionConfigOptionRequest, SetSessionModeRequest,
39 };
40 use agent_client_protocol::{Client, ErrorCode, Lines, UntypedMessage};
41 use codewhale_util::bounded_lines::{BoundedLines, MAX_FRAME_BYTES, is_frame_refusal};
42 use futures_util::{Sink, Stream};
43 use serde::Serialize;
44 use serde_json::{Value, json};
45 use tokio::io::AsyncWriteExt as _;
46 use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
47 use tokio_util::sync::CancellationToken;
48
49 use super::AgentIo;
50
51 const CLIENT_NAME: &str = "codewhale";
52 pub const MAX_MESSAGE_BYTES: usize = MAX_FRAME_BYTES;
53 pub const AUTH_REQUIRED: i64 = -32000;
54 const ABORT_POLL: Duration = Duration::from_millis(25);
55 pub const MAX_CONTROLS: usize = 32;
56 pub const MAX_CHOICES: usize = 256;
57 pub const MAX_VALUE_BYTES: usize = 128;
58 const MAX_NAME_CHARS: usize = 200;
59 const MAX_DESCRIPTION_CHARS: usize = 400;
60
61 pub mod refusal {
62 pub const CONTROL_NOT_OFFERED: &str = "control_not_offered";
63 pub const CONTROL_UNAVAILABLE: &str = "control_unavailable";
64 pub const CHOICE_NOT_OFFERED: &str = "choice_not_offered";
65 pub const CHOICE_REJECTED: &str = "choice_rejected";
66 pub const UNSUPPORTED_CONTROL: &str = "unsupported_control";
67 pub const CONTROL_TYPE_UNSUPPORTED: &str = "control_type_unsupported";
68 pub const CONTROL_HAS_NO_CHOICES: &str = "control_has_no_choices";
69 }
70
71 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
72 pub enum PermissionPolicy {
73 /// Choose the first option the agent labels `allow_once`.
74 AllowOnce,
75 /// Choose the first option the agent labels `reject_once`.
76 RejectOnce,
77 /// Answer `cancelled`, the protocol's "no decision" outcome.
78 Cancel,
79 }
80
81 impl PermissionPolicy {
82 fn option_kind(self) -> &'static str {
83 match self {
84 PermissionPolicy::AllowOnce => "allow_once",
85 PermissionPolicy::RejectOnce => "reject_once",
86 PermissionPolicy::Cancel => "",
87 }
88 }
89 }
90
91 #[derive(Debug, Clone, PartialEq, Eq)]
92 pub enum PermissionAnswer {
93 Selected(String),
94 Cancelled,
95 }
96
97 impl PermissionAnswer {
98 fn outcome(&self) -> RequestPermissionOutcome {
99 match self {
100 PermissionAnswer::Selected(option_id) => RequestPermissionOutcome::Selected(
101 SelectedPermissionOutcome::new(option_id.clone()),
102 ),
103 PermissionAnswer::Cancelled => RequestPermissionOutcome::Cancelled,
104 }
105 }
106 }
107
108 pub trait AcpHandler {
109 fn update(&mut self, update: &Value);
110 fn permission(&mut self, params: &Value) -> PermissionAnswer;
111 }
112
113 #[derive(Debug)]
114 pub struct AcpError {
115 message: String,
116 code: Option<i64>,
117 }
118
119 impl AcpError {
120 fn new(message: impl Into<String>) -> Self {
121 Self {
122 message: message.into(),
123 code: None,
124 }
125 }
126
127 fn timeout(method: &str) -> Self {
128 Self::new(format!("{method} did not answer before the deadline"))
129 }
130
131 pub fn code(&self) -> Option<i64> {
132 self.code
133 }
134
135 fn from_agent(method: &str, error: &SdkError) -> Self {
136 Self {
137 message: format!("{method} failed: {}", describe(error)),
138 code: Some(i64::from(i32::from(error.code))),
139 }
140 }
141
142 pub fn is_auth_required(&self) -> bool {
143 self.code == Some(AUTH_REQUIRED)
144 }
145 }
146
147 impl std::fmt::Display for AcpError {
148 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149 f.write_str(&self.message)
150 }
151 }
152
153 impl std::error::Error for AcpError {}
154
155 #[derive(Debug, Clone, PartialEq, Eq)]
156 pub struct AgentIdentity {
157 pub name: String,
158 pub version: String,
159 pub protocol_version: u64,
160 pub load_session: bool,
161 pub resume_session: bool,
162 pub capabilities: AgentCapabilities,
163 }
164
165 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
166 pub struct AgentCapabilities {
167 pub load_session: bool,
168 pub resume_session: bool,
169 pub fork_session: bool,
170 pub list_sessions: bool,
171 pub additional_directories: bool,
172 pub prompt_image: bool,
173 pub prompt_audio: bool,
174 pub prompt_embedded_context: bool,
175 }
176
177 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
178 pub struct Choice {
179 pub value: String,
180 pub name: String,
181 #[serde(skip_serializing_if = "Option::is_none")]
182 pub description: Option<String>,
183 }
184
185 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
186 #[serde(rename_all = "snake_case")]
187 pub enum ControlKind {
188 Model,
189 Mode,
190 Config,
191 }
192
193 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
194 #[serde(tag = "method")]
195 pub enum ControlWrite {
196 #[serde(rename = "session/set_config_option")]
197 SetConfigOption { config_id: String },
198 #[serde(rename = "session/set_model")]
199 SetModel,
200 #[serde(rename = "session/set_mode")]
201 SetMode,
202 }
203
204 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
205 pub struct ControlRefusal {
206 pub code: &'static str,
207 pub reason: String,
208 }
209
210 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
211 pub struct Control {
212 pub id: String,
213 pub kind: ControlKind,
214 pub name: String,
215 #[serde(skip_serializing_if = "Option::is_none")]
216 pub description: Option<String>,
217 #[serde(skip_serializing_if = "Option::is_none")]
218 pub category: Option<String>,
219 #[serde(skip_serializing_if = "Option::is_none")]
220 pub current: Option<String>,
221 pub choices: Vec<Choice>,
222 pub truncated: bool,
223 #[serde(skip_serializing_if = "Option::is_none")]
224 pub write: Option<ControlWrite>,
225 #[serde(skip_serializing_if = "Option::is_none")]
226 pub unavailable: Option<ControlRefusal>,
227 }
228
229 impl Control {
230 pub fn offers(&self, value: &str) -> bool {
231 self.unavailable.is_none() && self.choices.iter().any(|choice| choice.value == value)
232 }
233 }
234
235 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
236 pub struct SessionOffer {
237 pub controls: Vec<Control>,
238 pub malformed_controls: usize,
239 }
240
241 impl SessionOffer {
242 pub fn control(&self, id: &str) -> Option<&Control> {
243 self.controls.iter().find(|control| control.id == id)
244 }
245
246 pub fn thought_level_control(&self) -> Option<&Control> {
247 self.controls.iter().find(|control| {
248 control.kind == ControlKind::Config
249 && (control.category.as_deref() == Some("thought_level")
250 || matches!(
251 control.id.as_str(),
252 "config:thought_level" | "config:reasoning_effort"
253 ))
254 })
255 }
256
257 pub fn thought_level_control_mut(&mut self) -> Option<&mut Control> {
258 self.controls.iter_mut().find(|control| {
259 control.kind == ControlKind::Config
260 && (control.category.as_deref() == Some("thought_level")
261 || matches!(
262 control.id.as_str(),
263 "config:thought_level" | "config:reasoning_effort"
264 ))
265 })
266 }
267 }
268
269 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
270 pub struct ActionSupport {
271 pub action: &'static str,
272 pub supported: bool,
273 #[serde(skip_serializing_if = "Option::is_none")]
274 pub code: Option<&'static str>,
275 #[serde(skip_serializing_if = "Option::is_none")]
276 pub reason: Option<&'static str>,
277 #[serde(skip_serializing_if = "Option::is_none")]
278 pub agent_reports: Option<bool>,
279 }
280
281 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
282 pub struct OptionsAgent {
283 pub id: String,
284 pub name: String,
285 pub version: String,
286 pub protocol_version: u64,
287 }
288
289 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
290 pub struct AgentOptions {
291 pub agent: OptionsAgent,
292 pub cwd: String,
293 pub capabilities: AgentCapabilities,
294 pub controls: Vec<Control>,
295 pub malformed_controls: usize,
296 pub actions: Vec<ActionSupport>,
297 }
298
299 impl AgentOptions {
300 pub fn new(identity: &AgentIdentity, id: &str, cwd: &Path, offer: SessionOffer) -> Self {
301 let actions = action_support(&identity.capabilities, &offer);
302 Self {
303 agent: OptionsAgent {
304 id: id.to_string(),
305 name: identity.name.clone(),
306 version: identity.version.clone(),
307 protocol_version: identity.protocol_version,
308 },
309 cwd: cwd.display().to_string(),
310 capabilities: identity.capabilities.clone(),
311 controls: offer.controls,
312 malformed_controls: offer.malformed_controls,
313 actions,
314 }
315 }
316 }
317
318 fn action_support(capabilities: &AgentCapabilities, offer: &SessionOffer) -> Vec<ActionSupport> {
319 let offered = |kind: ControlKind| {
320 offer
321 .controls
322 .iter()
323 .any(|control| control.kind == kind && control.unavailable.is_none())
324 };
325 let choice = |action, kind| {
326 let supported = offered(kind);
327 ActionSupport {
328 action,
329 supported,
330 code: (!supported).then_some(refusal::CONTROL_NOT_OFFERED),
331 reason: (!supported).then_some("The agent did not offer this control."),
332 agent_reports: None,
333 }
334 };
335 let refused = |action, reason, agent_reports| ActionSupport {
336 action,
337 supported: false,
338 code: Some(refusal::UNSUPPORTED_CONTROL),
339 reason: Some(reason),
340 agent_reports,
341 };
342 let thought_supported = offer
343 .thought_level_control()
344 .is_some_and(|control| control.unavailable.is_none());
345 vec![
346 choice("model_choice", ControlKind::Model),
347 ActionSupport {
348 action: "thought_level_choice",
349 supported: thought_supported,
350 code: (!thought_supported).then_some(refusal::CONTROL_NOT_OFFERED),
351 reason: (!thought_supported).then_some("The agent did not offer this control."),
352 agent_reports: None,
353 },
354 choice("mode_choice", ControlKind::Mode),
355 choice("config_choice", ControlKind::Config),
356 refused(
357 "steering",
358 "Agent Client Protocol has no way to steer a running turn; interrupt it and send a new message.",
359 None,
360 ),
361 refused(
362 "compaction",
363 "Codewhale cannot compact another agent's context.",
364 None,
365 ),
366 refused(
367 "fork",
368 "Codewhale does not fork another agent's session.",
369 Some(capabilities.fork_session),
370 ),
371 refused(
372 "images",
373 "Codewhale sends text prompts to another agent only.",
374 Some(capabilities.prompt_image),
375 ),
376 refused(
377 "dynamic_tools",
378 "The agent uses its own tools; Codewhale tools cannot be added.",
379 None,
380 ),
381 refused(
382 "output_limit",
383 "Codewhale cannot cap another agent's output tokens.",
384 None,
385 ),
386 refused(
387 "provider_override",
388 "Codewhale providers do not apply; choose the agent's own model.",
389 None,
390 ),
391 refused(
392 "remote_placement",
393 "The agent runs on this computer only.",
394 None,
395 ),
396 ]
397 }
398
399 pub struct NewSession {
400 pub session_id: String,
401 pub offer: SessionOffer,
402 }
403
404 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
405 pub struct AgentTokenUsage {
406 pub input_tokens: Option<u64>,
407 pub output_tokens: Option<u64>,
408 pub total_tokens: Option<u64>,
409 pub thought_tokens: Option<u64>,
410 pub cached_read_tokens: Option<u64>,
411 pub cached_write_tokens: Option<u64>,
412 }
413
414 impl AgentTokenUsage {
415 pub fn is_empty(&self) -> bool {
416 *self == Self::default()
417 }
418
419 fn from_result(result: &Value) -> Option<Self> {
420 let usage = result.get("usage")?.as_object()?;
421 let field = |name: &str| usage.get(name).and_then(Value::as_u64);
422 let parsed = Self {
423 input_tokens: field("inputTokens"),
424 output_tokens: field("outputTokens"),
425 total_tokens: field("totalTokens"),
426 thought_tokens: field("thoughtTokens"),
427 cached_read_tokens: field("cachedReadTokens"),
428 cached_write_tokens: field("cachedWriteTokens"),
429 };
430 (!parsed.is_empty()).then_some(parsed)
431 }
432 }
433
434 #[derive(Debug, Clone, PartialEq, Eq)]
435 pub struct PromptReply {
436 pub stop_reason: String,
437 pub usage: Option<AgentTokenUsage>,
438 }
439
440 fn bounded_text(value: Option<&Value>, max_chars: usize) -> Option<String> {
441 let text: String = value?
442 .as_str()?
443 .chars()
444 .filter(|ch| !ch.is_control())
445 .take(max_chars)
446 .collect();
447 let text = text.trim();
448 (!text.is_empty()).then(|| text.to_string())
449 }
450
451 fn offered_value(value: Option<&Value>) -> Option<String> {
452 let value = value?.as_str()?;
453 (!value.is_empty() && value.len() <= MAX_VALUE_BYTES && !value.chars().any(char::is_control))
454 .then(|| value.to_string())
455 }
456
457 fn push_choice(
458 choices: &mut Vec<Choice>,
459 truncated: &mut bool,
460 value: Option<String>,
461 name: Option<&Value>,
462 description: Option<&Value>,
463 ) {
464 let Some(value) = value else {
465 *truncated = true;
466 return;
467 };
468 if choices.iter().any(|choice| choice.value == value) {
469 return;
470 }
471 if choices.len() >= MAX_CHOICES {
472 *truncated = true;
473 return;
474 }
475 choices.push(Choice {
476 name: bounded_text(name, MAX_NAME_CHARS).unwrap_or_else(|| value.clone()),
477 description: bounded_text(description, MAX_DESCRIPTION_CHARS),
478 value,
479 });
480 }
481
482 fn config_choices(options: &[Value]) -> (Vec<Choice>, bool) {
483 let mut choices = Vec::new();
484 let mut truncated = false;
485 for option in options {
486 if let Some(group) = option.get("options").and_then(Value::as_array) {
487 for grouped in group {
488 push_choice(
489 &mut choices,
490 &mut truncated,
491 offered_value(grouped.get("value")),
492 grouped.get("name"),
493 grouped.get("description"),
494 );
495 }
496 } else {
497 push_choice(
498 &mut choices,
499 &mut truncated,
500 offered_value(option.get("value")),
501 option.get("name"),
502 option.get("description"),
503 );
504 }
505 }
506 (choices, truncated)
507 }
508
509 impl SessionOffer {
510 pub fn from_session_result(result: &Value) -> Self {
511 let mut offer = Self::default();
512 let mut model_claimed = false;
513 let mut mode_claimed = false;
514 let options = result
515 .get("configOptions")
516 .and_then(Value::as_array)
517 .map(Vec::as_slice)
518 .unwrap_or_default();
519 for option in options {
520 if offer.controls.len() >= MAX_CONTROLS {
521 offer.malformed_controls += 1;
522 continue;
523 }
524 let Some(config_id) = offered_value(option.get("id")) else {
525 offer.malformed_controls += 1;
526 continue;
527 };
528 let category = bounded_text(option.get("category"), 64);
529 let kind = if !model_claimed
530 && (config_id == "model" || category.as_deref() == Some("model"))
531 {
532 model_claimed = true;
533 ControlKind::Model
534 } else if !mode_claimed && (config_id == "mode" || category.as_deref() == Some("mode"))
535 {
536 mode_claimed = true;
537 ControlKind::Mode
538 } else {
539 ControlKind::Config
540 };
541 let id = match kind {
542 ControlKind::Model => "model".to_string(),
543 ControlKind::Mode => "mode".to_string(),
544 ControlKind::Config => format!("config:{config_id}"),
545 };
546 if offer.control(&id).is_some() {
547 offer.malformed_controls += 1;
548 continue;
549 }
550 let is_select = option.get("type").and_then(Value::as_str) == Some("select");
551 let (choices, truncated) = if is_select {
552 config_choices(
553 option
554 .get("options")
555 .and_then(Value::as_array)
556 .map(Vec::as_slice)
557 .unwrap_or_default(),
558 )
559 } else {
560 (Vec::new(), false)
561 };
562 let unavailable = if !is_select {
563 Some(ControlRefusal {
564 code: refusal::CONTROL_TYPE_UNSUPPORTED,
565 reason: "Codewhale can only write select-type agent options.".to_string(),
566 })
567 } else if choices.is_empty() {
568 Some(ControlRefusal {
569 code: refusal::CONTROL_HAS_NO_CHOICES,
570 reason: "The agent offered this option with no choices.".to_string(),
571 })
572 } else {
573 None
574 };
575 offer.controls.push(Control {
576 name: bounded_text(option.get("name"), MAX_NAME_CHARS)
577 .unwrap_or_else(|| config_id.clone()),
578 description: bounded_text(option.get("description"), MAX_DESCRIPTION_CHARS),
579 category,
580 current: offered_value(option.get("currentValue")),
581 write: unavailable
582 .is_none()
583 .then_some(ControlWrite::SetConfigOption { config_id }),
584 id,
585 kind,
586 choices,
587 truncated,
588 unavailable,
589 });
590 }
591 if !model_claimed
592 && let Some(models) = result.get("models").filter(|value| value.is_object())
593 {
594 offer.push_legacy(
595 ControlKind::Model,
596 models.get("currentModelId"),
597 models.get("availableModels"),
598 "modelId",
599 ControlWrite::SetModel,
600 );
601 }
602 if !mode_claimed && let Some(modes) = result.get("modes").filter(|value| value.is_object())
603 {
604 offer.push_legacy(
605 ControlKind::Mode,
606 modes.get("currentModeId"),
607 modes.get("availableModes"),
608 "id",
609 ControlWrite::SetMode,
610 );
611 }
612 offer
613 }
614
615 pub fn refresh_config_options(&mut self, result: &Value) {
616 if result
617 .get("configOptions")
618 .and_then(Value::as_array)
619 .is_none()
620 {
621 return;
622 }
623 let mut next = Self::from_session_result(result);
624 if next.control("model").is_none()
625 && let Some(legacy_model) = self.control("model").cloned()
626 {
627 next.controls.push(legacy_model);
628 }
629 if next.control("mode").is_none()
630 && let Some(legacy_mode) = self.control("mode").cloned()
631 {
632 next.controls.push(legacy_mode);
633 }
634 *self = next;
635 }
636
637 fn push_legacy(
638 &mut self,
639 kind: ControlKind,
640 current: Option<&Value>,
641 available: Option<&Value>,
642 value_key: &str,
643 write: ControlWrite,
644 ) {
645 let mut choices = Vec::new();
646 let mut truncated = false;
647 for entry in available
648 .and_then(Value::as_array)
649 .map(Vec::as_slice)
650 .unwrap_or_default()
651 {
652 push_choice(
653 &mut choices,
654 &mut truncated,
655 offered_value(entry.get(value_key)),
656 entry.get("name"),
657 entry.get("description"),
658 );
659 }
660 if choices.is_empty() {
661 self.malformed_controls += 1;
662 return;
663 }
664 let (id, name) = match kind {
665 ControlKind::Model => ("model", "Model"),
666 _ => ("mode", "Mode"),
667 };
668 self.controls.push(Control {
669 id: id.to_string(),
670 kind,
671 name: name.to_string(),
672 description: None,
673 category: None,
674 current: offered_value(current),
675 choices,
676 truncated,
677 write: Some(write),
678 unavailable: None,
679 });
680 }
681 }
682
683 #[derive(Debug, Clone, Default, PartialEq, Eq)]
684 pub struct PromptOutcome {
685 pub stop_reason: String,
686 pub text: String,
687 pub tool_calls: Vec<String>,
688 pub decisions: Vec<String>,
689 }
690
691 struct PolicyHandler<'a> {
692 policy: PermissionPolicy,
693 outcome: &'a mut PromptOutcome,
694 }
695
696 impl AcpHandler for PolicyHandler<'_> {
697 fn update(&mut self, update: &Value) {
698 match update
699 .get("sessionUpdate")
700 .and_then(Value::as_str)
701 .unwrap_or("")
702 {
703 "agent_message_chunk" => {
704 if let Some(chunk) = update
705 .get("content")
706 .and_then(|content| content.get("text"))
707 .and_then(Value::as_str)
708 {
709 self.outcome.text.push_str(chunk);
710 }
711 }
712 "tool_call" => {
713 let title = update
714 .get("title")
715 .and_then(Value::as_str)
716 .unwrap_or("tool");
717 let kind = update
718 .get("kind")
719 .and_then(Value::as_str)
720 .unwrap_or("other");
721 self.outcome.tool_calls.push(format!("{kind}:{title}"));
722 }
723 _ => {}
724 }
725 }
726
727 fn permission(&mut self, params: &Value) -> PermissionAnswer {
728 let answer = if self.policy == PermissionPolicy::Cancel {
729 PermissionAnswer::Cancelled
730 } else {
731 AcpClient::permission_option(params, self.policy)
732 .map_or(PermissionAnswer::Cancelled, PermissionAnswer::Selected)
733 };
734 if let PermissionAnswer::Selected(option) = &answer {
735 self.outcome.decisions.push(option.clone());
736 }
737 answer
738 }
739 }
740
741 struct DiscardHandler;
742
743 impl AcpHandler for DiscardHandler {
744 fn update(&mut self, _update: &Value) {}
745
746 fn permission(&mut self, _params: &Value) -> PermissionAnswer {
747 PermissionAnswer::Cancelled
748 }
749 }
750
751 type SdkError = agent_client_protocol::Error;
752
753 enum Command {
754 Request {
755 method: &'static str,
756 params: Value,
757 token: u64,
758 cancel: Option<CancellationToken>,
759 },
760 Notify(Value),
761 }
762
763 enum Event {
764 Update(Value),
765 Request {
766 method: String,
767 params: Value,
768 responder: Box<agent_client_protocol::v1::Responder<Value>>,
769 },
770 Response {
771 token: u64,
772 result: Result<Value, AcpError>,
773 },
774 Closed(Option<String>),
775 }
776
777 /// One live ACP conversation over a worker's pipes.
778 pub struct AcpClient {
779 commands: UnboundedSender<Command>,
780 events: Receiver<Event>,
781 closed: Arc<Mutex<Option<String>>>,
782 next_token: u64,
783 abort: Option<CancellationToken>,
784 }
785
786 /// A write-only handle that can send `session/cancel` while a prompt blocks
787 /// the client that owns the event queue.
788 #[derive(Clone)]
789 pub struct AcpCanceller {
790 commands: UnboundedSender<Command>,
791 session: String,
792 }
793
794 impl AcpCanceller {
795 pub fn cancel(&self) -> Result<(), AcpError> {
796 send_cancel(&self.commands, &self.session)
797 }
798 }
799
800 impl std::fmt::Debug for AcpClient {
801 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
802 f.debug_struct("AcpClient")
803 .field("next_token", &self.next_token)
804 .finish_non_exhaustive()
805 }
806 }
807
808 fn encode(message: impl Serialize) -> Result<Value, AcpError> {
809 serde_json::to_value(message)
810 .map_err(|err| AcpError::new(format!("encoding a message failed: {err}")))
811 }
812
813 fn describe(error: &SdkError) -> String {
814 let message = if error.message.is_empty() {
815 "the agent refused"
816 } else {
817 error.message.as_str()
818 };
819 let data = error.data.as_ref().map(|data| match data {
820 Value::Object(fields) => ["message", "details", "error"]
821 .iter()
822 .find_map(|key| fields.get(*key).filter(|value| value.is_string()).cloned())
823 .unwrap_or_else(|| Value::String(data.to_string())),
824 Value::String(_) => data.clone(),
825 other => Value::String(other.to_string()),
826 });
827 match bounded_text(data.as_ref(), MAX_DESCRIPTION_CHARS) {
828 Some(detail) => format!("{message}: {detail}"),
829 None => message.to_string(),
830 }
831 }
832
833 fn send_cancel(commands: &UnboundedSender<Command>, session: &str) -> Result<(), AcpError> {
834 let params = encode(CancelNotification::new(session.to_string()))?;
835 commands
836 .send(Command::Notify(params))
837 .map_err(|_| AcpError::new("the agent's connection has ended"))
838 }
839
840 fn wire_path(path: &Path) -> PathBuf {
841 PathBuf::from(path.display().to_string())
842 }
843
844 fn advertised_dirs(identity: &AgentIdentity, add_dirs: &[PathBuf]) -> Vec<PathBuf> {
845 if identity.capabilities.additional_directories {
846 add_dirs.iter().map(|dir| wire_path(dir)).collect()
847 } else {
848 Vec::new()
849 }
850 }
851
852 fn bounded_lines<R>(
853 reader: R,
854 closed: Arc<Mutex<Option<String>>>,
855 ) -> impl Stream<Item = std::io::Result<String>> + Send + 'static
856 where
857 R: tokio::io::AsyncBufRead + Unpin + Send + 'static,
858 {
859 futures_util::stream::unfold(
860 (BoundedLines::new(reader), closed),
861 |(mut lines, closed)| async move {
862 loop {
863 match lines.next_line().await {
864 Ok(Some(line)) if line.trim().is_empty() => continue,
865 Ok(Some(line)) => return Some((Ok(line), (lines, closed))),
866 Ok(None) => return None,
867 Err(error) => {
868 if is_frame_refusal(&error)
869 && let Ok(mut slot) = closed.lock()
870 {
871 slot.get_or_insert_with(|| {
872 format!("the agent's message was refused: {error}")
873 });
874 }
875 return Some((Err(error), (lines, closed)));
876 }
877 }
878 }
879 },
880 )
881 }
882
883 fn line_sink<W>(writer: W) -> impl Sink<String, Error = std::io::Error> + Send + 'static
884 where
885 W: tokio::io::AsyncWrite + Unpin + Send + 'static,
886 {
887 futures_util::sink::unfold(writer, |mut writer, line: String| async move {
888 writer.write_all(line.as_bytes()).await?;
889 writer.write_all(b"\n").await?;
890 writer.flush().await?;
891 Ok::<_, std::io::Error>(writer)
892 })
893 }
894
895 async fn drive(
896 io: AgentIo,
897 mut commands: UnboundedReceiver<Command>,
898 events: Sender<Event>,
899 closed: Arc<Mutex<Option<String>>>,
900 ) -> Result<(), SdkError> {
901 let stdin =
902 tokio::process::ChildStdin::from_std(io.stdin).map_err(SdkError::into_internal_error)?;
903 let stdout = tokio::process::ChildStdout::from_std(io.stdout.into_inner())
904 .map_err(SdkError::into_internal_error)?;
905 let transport = Lines::new(
906 line_sink(stdin),
907 bounded_lines(tokio::io::BufReader::new(stdout), closed),
908 );
909 let requests = events.clone();
910 let updates = events.clone();
911 Client
912 .v1()
913 .on_receive_request(
914 async move |request: UntypedMessage, responder, _cx| {
915 let (method, params) = request.into_parts();
916 let _ = requests.send(Event::Request {
917 method,
918 params,
919 responder: Box::new(responder),
920 });
921 Ok(())
922 },
923 agent_client_protocol::on_receive_request!(),
924 )
925 .on_receive_notification(
926 async move |notification: UntypedMessage, _cx| {
927 let (method, params) = notification.into_parts();
928 if method == "session/update" {
929 let _ = updates.send(Event::Update(params));
930 }
931 Ok(())
932 },
933 agent_client_protocol::on_receive_notification!(),
934 )
935 .connect_with(transport, async move |cx| {
936 loop {
937 let command = tokio::select! {
938 command = commands.recv() => command,
939 () = cx.incoming_closed() => None,
940 };
941 match command {
942 Some(Command::Request {
943 method,
944 params,
945 token,
946 cancel,
947 }) => {
948 let answered = events.clone();
949 let sent = if cancel.as_ref().is_some_and(CancellationToken::is_cancelled) {
950 Err(AcpError::new(format!(
951 "{method} was cancelled before dispatch"
952 )))
953 } else {
954 UntypedMessage::new(method, params)
955 .and_then(|message| {
956 cx.send_request(message).on_receiving_result(
957 async move |result| {
958 let _ = answered.send(Event::Response {
959 token,
960 result: result.map_err(|error| {
961 AcpError::from_agent(method, &error)
962 }),
963 });
964 Ok(())
965 },
966 )
967 })
968 .map_err(|error| AcpError::from_agent(method, &error))
969 };
970 if let Err(error) = sent {
971 let _ = events.send(Event::Response {
972 token,
973 result: Err(error),
974 });
975 }
976 }
977 Some(Command::Notify(params)) => {
978 if let Err(error) = UntypedMessage::new("session/cancel", params)
979 .and_then(|message| cx.send_notification(message))
980 {
981 tracing::warn!(error = %describe(&error), "sending session/cancel failed");
982 }
983 }
984 None => return Ok(()),
985 }
986 }
987 })
988 .await
989 }
990
991 impl AcpClient {
992 pub fn new(io: AgentIo) -> Self {
993 let (commands, command_rx) = unbounded_channel();
994 let (event_tx, events) = channel();
995 let closed = Arc::new(Mutex::new(None));
996 let stream_closed = Arc::clone(&closed);
997 let spawned = std::thread::Builder::new()
998 .name("acp-conn".to_string())
999 .spawn(move || {
1000 let ended = match tokio::runtime::Builder::new_current_thread()
1001 .enable_all()
1002 .build()
1003 {
1004 Ok(runtime) => {
1005 let ended = runtime.block_on(drive(
1006 io,
1007 command_rx,
1008 event_tx.clone(),
1009 stream_closed,
1010 ));
1011 runtime.shutdown_background();
1012 ended
1013 }
1014 Err(error) => Err(SdkError::into_internal_error(error)),
1015 };
1016 let reason = match ended {
1017 Ok(()) => None,
1018 Err(error) if agent_client_protocol::is_incoming_transport_closed(&error) => {
1019 None
1020 }
1021 Err(error) => {
1022 Some(format!("the agent connection failed: {}", describe(&error)))
1023 }
1024 };
1025 let _ = event_tx.send(Event::Closed(reason));
1026 });
1027 if let Err(error) = spawned
1028 && let Ok(mut slot) = closed.lock()
1029 {
1030 *slot = Some(format!("the agent connection could not start: {error}"));
1031 }
1032 Self {
1033 commands,
1034 events,
1035 closed,
1036 next_token: 1,
1037 abort: None,
1038 }
1039 }
1040
1041 pub fn abort_requests_on(&mut self, abort: Option<CancellationToken>) {
1042 self.abort = abort;
1043 }
1044
1045 /// A handle that can settle a blocked prompt from another thread.
1046 pub fn canceller(&self, session: &str) -> AcpCanceller {
1047 AcpCanceller {
1048 commands: self.commands.clone(),
1049 session: session.to_string(),
1050 }
1051 }
1052
1053 fn ended(&self, method: &str, reason: Option<String>) -> AcpError {
1054 let refused = self.closed.lock().ok().and_then(|slot| slot.clone());
1055 AcpError::new(
1056 refused
1057 .or(reason)
1058 .unwrap_or_else(|| format!("the agent exited before answering {method}")),
1059 )
1060 }
1061
1062 fn read(&mut self, deadline: Instant, method: &str) -> Result<Event, AcpError> {
1063 loop {
1064 if self
1065 .abort
1066 .as_ref()
1067 .is_some_and(CancellationToken::is_cancelled)
1068 {
1069 return Err(AcpError::new(format!(
1070 "{method} was cancelled before the agent answered"
1071 )));
1072 }
1073 let left = deadline.saturating_duration_since(Instant::now());
1074 if left.is_zero() {
1075 return Err(AcpError::timeout(method));
1076 }
1077 let wait = if self.abort.is_some() {
1078 left.min(ABORT_POLL)
1079 } else {
1080 left
1081 };
1082 match self.events.recv_timeout(wait) {
1083 Ok(event) => return Ok(event),
1084 Err(RecvTimeoutError::Timeout) => {}
1085 Err(RecvTimeoutError::Disconnected) => return Err(self.ended(method, None)),
1086 }
1087 }
1088 }
1089
1090 fn request(
1091 &mut self,
1092 method: &'static str,
1093 params: Value,
1094 session: Option<&str>,
1095 deadline: Instant,
1096 handler: &mut dyn AcpHandler,
1097 cancel: Option<&CancellationToken>,
1098 ) -> Result<Value, AcpError> {
1099 let token = self.next_token;
1100 self.next_token += 1;
1101 self.commands
1102 .send(Command::Request {
1103 method,
1104 params,
1105 token,
1106 cancel: cancel.cloned(),
1107 })
1108 .map_err(|_| self.ended(method, None))?;
1109 let ours = |params: &Value| {
1110 session.is_some_and(|session| {
1111 params.get("sessionId").and_then(Value::as_str) == Some(session)
1112 })
1113 };
1114 loop {
1115 match self.read(deadline, method)? {
1116 Event::Response {
1117 token: answered,
1118 result,
1119 } => {
1120 if answered == token {
1121 return result;
1122 }
1123 }
1124 Event::Update(params) => {
1125 if ours(&params)
1126 && let Some(update) = params.get("update")
1127 {
1128 handler.update(update);
1129 }
1130 }
1131 Event::Request {
1132 method: incoming,
1133 params,
1134 responder,
1135 } => {
1136 let answered = match incoming.as_str() {
1137 "session/request_permission" => {
1138 let answer = if ours(&params) {
1139 handler.permission(&params)
1140 } else {
1141 PermissionAnswer::Cancelled
1142 };
1143 let answer = if cancel.is_some_and(CancellationToken::is_cancelled)
1144 || responder.cancellation().is_cancelled()
1145 {
1146 PermissionAnswer::Cancelled
1147 } else {
1148 answer
1149 };
1150 responder
1151 .respond(encode(RequestPermissionResponse::new(answer.outcome()))?)
1152 }
1153 "elicitation/create" => responder.respond(encode(
1154 CreateElicitationResponse::new(ElicitationAction::Decline),
1155 )?),
1156 other => responder.respond_with_error(SdkError::new(
1157 ErrorCode::METHOD_NOT_FOUND,
1158 format!("{other} is not supported by this client"),
1159 )),
1160 };
1161 answered.map_err(|error| {
1162 AcpError::new(format!("answering the agent failed: {}", describe(&error)))
1163 })?;
1164 }
1165 Event::Closed(reason) => return Err(self.ended(method, reason)),
1166 }
1167 }
1168 }
1169
1170 pub fn initialize(&mut self, timeout: Duration) -> Result<AgentIdentity, AcpError> {
1171 let deadline = Instant::now() + timeout;
1172 let result = self.request(
1173 "initialize",
1174 encode(
1175 InitializeRequest::new(ProtocolVersion::V1)
1176 .client_capabilities(ClientCapabilities::new())
1177 .client_info(Implementation::new(CLIENT_NAME, env!("CARGO_PKG_VERSION"))),
1178 )?,
1179 None,
1180 deadline,
1181 &mut DiscardHandler,
1182 None,
1183 )?;
1184 let info = result.get("agentInfo").cloned().unwrap_or(Value::Null);
1185 let capabilities = result
1186 .get("agentCapabilities")
1187 .cloned()
1188 .unwrap_or(Value::Null);
1189 let protocol_version = result
1190 .get("protocolVersion")
1191 .and_then(Value::as_u64)
1192 .filter(|version| *version == 1)
1193 .ok_or_else(|| AcpError::new("the agent did not negotiate ACP protocol version 1"))?;
1194 let flag = |pointer: &str| {
1195 capabilities
1196 .pointer(pointer)
1197 .is_some_and(|value| !value.is_null() && value != &Value::Bool(false))
1198 };
1199 let capability_report = AgentCapabilities {
1200 load_session: capabilities
1201 .get("loadSession")
1202 .and_then(Value::as_bool)
1203 .unwrap_or(false),
1204 resume_session: flag("/sessionCapabilities/resume"),
1205 fork_session: flag("/sessionCapabilities/fork"),
1206 list_sessions: flag("/sessionCapabilities/list"),
1207 additional_directories: flag("/sessionCapabilities/additionalDirectories"),
1208 prompt_image: flag("/promptCapabilities/image"),
1209 prompt_audio: flag("/promptCapabilities/audio"),
1210 prompt_embedded_context: flag("/promptCapabilities/embeddedContext"),
1211 };
1212 Ok(AgentIdentity {
1213 capabilities: capability_report,
1214 name: info
1215 .get("name")
1216 .and_then(Value::as_str)
1217 .unwrap_or("agent")
1218 .to_string(),
1219 version: info
1220 .get("version")
1221 .and_then(Value::as_str)
1222 .unwrap_or("0")
1223 .to_string(),
1224 protocol_version,
1225 load_session: capabilities
1226 .get("loadSession")
1227 .and_then(Value::as_bool)
1228 .unwrap_or(false),
1229 resume_session: capabilities
1230 .pointer("/sessionCapabilities/resume")
1231 .is_some_and(|value| !value.is_null() && value != &Value::Bool(false)),
1232 })
1233 }
1234
1235 pub fn new_session(
1236 &mut self,
1237 identity: &AgentIdentity,
1238 cwd: &Path,
1239 add_dirs: &[PathBuf],
1240 timeout: Duration,
1241 ) -> Result<NewSession, AcpError> {
1242 let deadline = Instant::now() + timeout;
1243 let result = self.request(
1244 "session/new",
1245 encode(
1246 NewSessionRequest::new(wire_path(cwd))
1247 .additional_directories(advertised_dirs(identity, add_dirs)),
1248 )?,
1249 None,
1250 deadline,
1251 &mut DiscardHandler,
1252 None,
1253 )?;
1254 let session_id = result
1255 .get("sessionId")
1256 .and_then(Value::as_str)
1257 .map(str::to_string)
1258 .ok_or_else(|| AcpError::new("session/new did not name a session"))?;
1259 Ok(NewSession {
1260 session_id,
1261 offer: SessionOffer::from_session_result(&result),
1262 })
1263 }
1264
1265 pub fn reopen_session(
1266 &mut self,
1267 identity: &AgentIdentity,
1268 session: &str,
1269 cwd: &Path,
1270 add_dirs: &[PathBuf],
1271 timeout: Duration,
1272 ) -> Result<SessionOffer, AcpError> {
1273 let dirs = advertised_dirs(identity, add_dirs);
1274 let (method, params) = if identity.resume_session {
1275 (
1276 "session/resume",
1277 encode(
1278 ResumeSessionRequest::new(session.to_string(), wire_path(cwd))
1279 .additional_directories(dirs),
1280 )?,
1281 )
1282 } else if identity.load_session {
1283 (
1284 "session/load",
1285 encode(
1286 LoadSessionRequest::new(session.to_string(), wire_path(cwd))
1287 .additional_directories(dirs),
1288 )?,
1289 )
1290 } else {
1291 return Err(AcpError::new(
1292 "the agent cannot reopen its stored session; start a new session",
1293 ));
1294 };
1295 let deadline = Instant::now() + timeout;
1296 self.request(
1297 method,
1298 params,
1299 Some(session),
1300 deadline,
1301 &mut DiscardHandler,
1302 None,
1303 )
1304 .map(|result| SessionOffer::from_session_result(&result))
1305 }
1306
1307 pub fn apply_control(
1308 &mut self,
1309 session: &str,
1310 control: &Control,
1311 value: &str,
1312 timeout: Duration,
1313 ) -> Result<(), AcpError> {
1314 self.apply_control_with_result(session, control, value, timeout)
1315 .map(|_| ())
1316 }
1317
1318 pub fn apply_control_with_result(
1319 &mut self,
1320 session: &str,
1321 control: &Control,
1322 value: &str,
1323 timeout: Duration,
1324 ) -> Result<Value, AcpError> {
1325 let deadline = Instant::now() + timeout;
1326 let (method, params) = match control.write.as_ref() {
1327 Some(ControlWrite::SetConfigOption { config_id }) => (
1328 "session/set_config_option",
1329 encode(SetSessionConfigOptionRequest::new(
1330 session.to_string(),
1331 config_id.clone(),
1332 value,
1333 ))?,
1334 ),
1335 Some(ControlWrite::SetModel) => (
1336 "session/set_model",
1337 json!({"sessionId": session, "modelId": value}),
1338 ),
1339 Some(ControlWrite::SetMode) => (
1340 "session/set_mode",
1341 encode(SetSessionModeRequest::new(
1342 session.to_string(),
1343 value.to_string(),
1344 ))?,
1345 ),
1346 None => {
1347 return Err(AcpError::new(
1348 "the agent did not offer this control for writing",
1349 ));
1350 }
1351 };
1352 self.request(
1353 method,
1354 params,
1355 Some(session),
1356 deadline,
1357 &mut DiscardHandler,
1358 None,
1359 )
1360 }
1361
1362 pub fn set_config_option(
1363 &mut self,
1364 session: &str,
1365 config_id: &str,
1366 value: &str,
1367 timeout: Duration,
1368 ) -> Result<(), AcpError> {
1369 let deadline = Instant::now() + timeout;
1370 self.request(
1371 "session/set_config_option",
1372 encode(SetSessionConfigOptionRequest::new(
1373 session.to_string(),
1374 config_id.to_string(),
1375 value,
1376 ))?,
1377 Some(session),
1378 deadline,
1379 &mut DiscardHandler,
1380 None,
1381 )
1382 .map(|_| ())
1383 }
1384
1385 pub fn prompt_with(
1386 &mut self,
1387 session: &str,
1388 text: &str,
1389 timeout: Duration,
1390 handler: &mut dyn AcpHandler,
1391 cancel: Option<&CancellationToken>,
1392 ) -> Result<PromptReply, AcpError> {
1393 let deadline = Instant::now() + timeout;
1394 let result = self.request(
1395 "session/prompt",
1396 encode(PromptRequest::new(
1397 session.to_string(),
1398 vec![ContentBlock::from(text)],
1399 ))?,
1400 Some(session),
1401 deadline,
1402 handler,
1403 cancel,
1404 )?;
1405 let stop_reason = result
1406 .get("stopReason")
1407 .and_then(Value::as_str)
1408 .filter(|reason| !reason.is_empty())
1409 .map(str::to_string)
1410 .ok_or_else(|| AcpError::new("session/prompt did not report a stop reason"))?;
1411 Ok(PromptReply {
1412 stop_reason,
1413 usage: AgentTokenUsage::from_result(&result),
1414 })
1415 }
1416
1417 pub fn prompt(
1418 &mut self,
1419 session: &str,
1420 text: &str,
1421 policy: PermissionPolicy,
1422 timeout: Duration,
1423 ) -> Result<PromptOutcome, AcpError> {
1424 let mut outcome = PromptOutcome::default();
1425 let reply = self.prompt_with(
1426 session,
1427 text,
1428 timeout,
1429 &mut PolicyHandler {
1430 policy,
1431 outcome: &mut outcome,
1432 },
1433 None,
1434 )?;
1435 outcome.stop_reason = reply.stop_reason;
1436 Ok(outcome)
1437 }
1438
1439 pub fn cancel(&self, session: &str) -> Result<(), AcpError> {
1440 send_cancel(&self.commands, session)
1441 }
1442
1443 pub fn permission_option(params: &Value, policy: PermissionPolicy) -> Option<String> {
1444 let wanted = policy.option_kind();
1445 params
1446 .get("options")
1447 .and_then(Value::as_array)
1448 .and_then(|options| {
1449 options
1450 .iter()
1451 .find(|option| option.get("kind").and_then(Value::as_str) == Some(wanted))
1452 })
1453 .and_then(|option| option.get("optionId").and_then(Value::as_str))
1454 .map(str::to_string)
1455 }
1456 }
1457
1458 #[cfg(test)]
1459 mod tests {
1460 use super::*;
1461
1462 #[test]
1463 fn agent_error_detail_survives_structured_data() {
1464 let error = SdkError::internal_error()
1465 .data(json!({"message": "402 Payment Required: usage balance exhausted"}));
1466 assert_eq!(
1467 describe(&error),
1468 "Internal error: 402 Payment Required: usage balance exhausted"
1469 );
1470 let error = SdkError::internal_error().data(json!({"status": 402}));
1471 assert_eq!(describe(&error), "Internal error: {\"status\":402}");
1472 }
1473 use crate::fleet::host::{
1474 FleetHostAdapter, FleetHostWorkerState, FleetWorkerCommand, FleetWorkerStartRequest,
1475 FleetWorkerTransport, LocalProcessFleetHostAdapter,
1476 };
1477 use std::collections::{BTreeMap, BTreeSet};
1478 use std::path::PathBuf;
1479
1480 fn fixture() -> PathBuf {
1481 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/acp-agent.mjs")
1482 }
1483
1484 fn node() -> Option<String> {
1485 let output = std::process::Command::new("node")
1486 .arg("--version")
1487 .output()
1488 .ok()?;
1489 output.status.success().then(|| "node".to_string())
1490 }
1491
1492 fn json_rpc_request(
1493 env: BTreeMap<String, String>,
1494 allow: BTreeSet<String>,
1495 ) -> FleetWorkerStartRequest {
1496 let mut request = FleetWorkerStartRequest::new(
1497 "w-acp",
1498 FleetWorkerCommand::new("node", [fixture().display().to_string()]),
1499 );
1500 request.transport = FleetWorkerTransport::JsonRpc;
1501 request.env = env;
1502 request.env_allowlist = allow;
1503 request
1504 }
1505
1506 #[test]
1507 fn a_session_offer_is_parsed_bounded_and_never_widened() {
1508 let many: Vec<Value> = (0..(MAX_CHOICES + 40))
1509 .map(|index| json!({"value": format!("v{index}"), "name": "x".repeat(900)}))
1510 .collect();
1511 let offer = SessionOffer::from_session_result(&json!({
1512 "configOptions": [
1513 {"id": "model", "name": "Model", "category": "model", "type": "select",
1514 "currentValue": "a",
1515 "options": [{"group": "g", "name": "G", "options": [
1516 {"value": "a", "name": "A"}, {"value": "a", "name": "dup"}, {"value": "b", "name": "B", "description": "d"}]},
1517 {"value": "c", "name": "C"}]},
1518 {"id": "flag", "name": "Flag", "type": "boolean", "currentValue": true},
1519 {"id": "none", "name": "None", "type": "select", "options": []},
1520 {"id": "", "name": "No id", "type": "select", "options": []},
1521 {"id": "big", "name": "Big", "type": "select", "currentValue": "v0", "options": many},
1522 {"id": "bad\nid", "name": "Control char", "type": "select", "options": [{"value": "x"}]}
1523 ],
1524 "modes": {"currentModeId": "m1", "availableModes": [{"id": "m1", "name": "M1"}, {"id": "", "name": "bad"}]},
1525 "models": {"currentModelId": "legacy", "availableModels": [{"modelId": "legacy", "name": "Legacy"}]}
1526 }));
1527 let ids: Vec<&str> = offer.controls.iter().map(|c| c.id.as_str()).collect();
1528 assert_eq!(
1529 ids,
1530 ["model", "config:flag", "config:none", "config:big", "mode"]
1531 );
1532 assert_eq!(offer.malformed_controls, 2);
1533 let model = offer.control("model").unwrap();
1534 let values: Vec<&str> = model.choices.iter().map(|c| c.value.as_str()).collect();
1535 assert_eq!(
1536 values,
1537 ["a", "b", "c"],
1538 "groups flatten and duplicates collapse"
1539 );
1540 assert_eq!(model.choices[1].description.as_deref(), Some("d"));
1541 assert!(model.offers("c") && !model.offers("legacy") && !model.offers(""));
1542 assert_eq!(
1543 offer
1544 .control("config:flag")
1545 .unwrap()
1546 .unavailable
1547 .as_ref()
1548 .unwrap()
1549 .code,
1550 refusal::CONTROL_TYPE_UNSUPPORTED
1551 );
1552 assert!(!offer.control("config:flag").unwrap().offers("true"));
1553 assert_eq!(
1554 offer
1555 .control("config:none")
1556 .unwrap()
1557 .unavailable
1558 .as_ref()
1559 .unwrap()
1560 .code,
1561 refusal::CONTROL_HAS_NO_CHOICES
1562 );
1563 let big = offer.control("config:big").unwrap();
1564 assert_eq!(big.choices.len(), MAX_CHOICES);
1565 assert!(big.truncated);
1566 assert!(big.choices[0].name.chars().count() <= MAX_NAME_CHARS);
1567 assert!(!big.offers(&format!("v{}", MAX_CHOICES + 1)));
1568 let mode = offer.control("mode").unwrap();
1569 assert_eq!(mode.write, Some(ControlWrite::SetMode));
1570 assert_eq!(mode.choices.len(), 1);
1571 assert!(
1572 mode.truncated,
1573 "a dropped malformed choice marks the list incomplete"
1574 );
1575
1576 let legacy = SessionOffer::from_session_result(&json!({
1577 "models": {"currentModelId": "legacy", "availableModels": [{"modelId": "legacy", "name": "Legacy"}]}
1578 }));
1579 assert_eq!(
1580 legacy.control("model").unwrap().write,
1581 Some(ControlWrite::SetModel)
1582 );
1583 assert!(
1584 SessionOffer::from_session_result(&json!({}))
1585 .controls
1586 .is_empty()
1587 );
1588 }
1589
1590 #[test]
1591 fn prompt_usage_keeps_only_what_the_agent_reported() {
1592 let usage = AgentTokenUsage::from_result(&json!({
1593 "stopReason": "end_turn",
1594 "usage": {"inputTokens": 5, "outputTokens": "many", "totalTokens": 9}
1595 }))
1596 .unwrap();
1597 assert_eq!(usage.input_tokens, Some(5));
1598 assert_eq!(usage.output_tokens, None);
1599 assert_eq!(usage.total_tokens, Some(9));
1600 assert!(AgentTokenUsage::from_result(&json!({"stopReason": "end_turn"})).is_none());
1601 assert!(AgentTokenUsage::from_result(&json!({"usage": {}})).is_none());
1602 }
1603
1604 #[test]
1605 fn a_json_rpc_worker_speaks_acp_end_to_end() {
1606 let Some(_node) = node() else {
1607 return;
1608 };
1609 let workspace = tempfile::tempdir().unwrap();
1610 let mut host = LocalProcessFleetHostAdapter::new(workspace.path());
1611 let mut request = json_rpc_request(
1612 BTreeMap::from([(
1613 "CODEWHALE_TEST_SECRET".to_string(),
1614 "must-not-travel".to_string(),
1615 )]),
1616 BTreeSet::from(["PATH".to_string()]),
1617 );
1618 request.cwd = Some(workspace.path().to_path_buf());
1619 host.start_worker(request).unwrap();
1620
1621 let io = host
1622 .take_worker_io("w-acp")
1623 .expect("a JsonRpc worker yields its pipes");
1624 assert!(
1625 host.take_worker_io("w-acp").is_none(),
1626 "the stream is taken exactly once"
1627 );
1628 let mut client = AcpClient::new(io);
1629
1630 let identity = client.initialize(Duration::from_secs(20)).unwrap();
1631 assert_eq!(identity.name, "fixture-agent");
1632 assert_eq!(identity.protocol_version, 1);
1633 assert!(identity.load_session);
1634
1635 let session = client
1636 .new_session(&identity, workspace.path(), &[], Duration::from_secs(20))
1637 .unwrap()
1638 .session_id;
1639 let allowed = client
1640 .prompt(
1641 &session,
1642 "hello fleet",
1643 PermissionPolicy::AllowOnce,
1644 Duration::from_secs(20),
1645 )
1646 .unwrap();
1647 assert_eq!(allowed.stop_reason, "end_turn");
1648 assert!(
1649 allowed.text.contains("hello fleet"),
1650 "streamed text: {:?}",
1651 allowed.text
1652 );
1653 assert!(
1654 allowed
1655 .tool_calls
1656 .iter()
1657 .any(|call| call == "edit:Write fixture.txt"),
1658 "tool calls: {:?}",
1659 allowed.tool_calls
1660 );
1661 assert!(
1662 workspace.path().join("fixture.txt").exists(),
1663 "an allowed edit wrote its file"
1664 );
1665
1666 std::fs::remove_file(workspace.path().join("fixture.txt")).unwrap();
1667 let rejected = client
1668 .prompt(
1669 &session,
1670 "hello again",
1671 PermissionPolicy::RejectOnce,
1672 Duration::from_secs(20),
1673 )
1674 .unwrap();
1675 assert_eq!(rejected.stop_reason, "end_turn");
1676 assert!(
1677 !workspace.path().join("fixture.txt").exists(),
1678 "a rejected edit wrote nothing"
1679 );
1680
1681 client
1682 .reopen_session(
1683 &identity,
1684 &session,
1685 workspace.path(),
1686 &[],
1687 Duration::from_secs(20),
1688 )
1689 .unwrap();
1690
1691 let dumped = std::fs::read_to_string(workspace.path().join("fixture-env.json")).unwrap();
1692 assert!(
1693 !dumped.contains("CODEWHALE_TEST_SECRET"),
1694 "an unlisted variable never reached the agent"
1695 );
1696
1697 let status = host.stop_worker("w-acp").unwrap();
1698 assert_ne!(status.state, FleetHostWorkerState::Running);
1699 }
1700
1701 #[test]
1702 fn invalid_acp_envelopes_and_protocol_versions_are_refused() {
1703 if node().is_none() {
1704 return;
1705 }
1706 for (response, timeout, expected) in [
1707 (
1708 "({ id: request.id, result: { protocolVersion: 1 } })",
1709 Duration::from_secs(3),
1710 "deadline",
1711 ),
1712 (
1713 "({ jsonrpc: '2.0', id: request.id, result: { protocolVersion: 2 } })",
1714 Duration::from_secs(20),
1715 "protocol version",
1716 ),
1717 (
1718 "({ jsonrpc: '2.0', id: request.id })",
1719 Duration::from_secs(3),
1720 "deadline",
1721 ),
1722 ] {
1723 let workspace = tempfile::tempdir().unwrap();
1724 let program = format!(
1725 "require('node:readline').createInterface({{input:process.stdin}}).once('line', line => {{ const request=JSON.parse(line); console.log(JSON.stringify({response})); }});"
1726 );
1727 let mut host = LocalProcessFleetHostAdapter::new(workspace.path());
1728 let mut request = FleetWorkerStartRequest::new(
1729 "invalid-acp",
1730 FleetWorkerCommand::new("node", ["-e".to_string(), program]),
1731 );
1732 request.transport = FleetWorkerTransport::JsonRpc;
1733 request.cwd = Some(workspace.path().to_path_buf());
1734 host.start_worker(request).unwrap();
1735 let io = host.take_worker_io("invalid-acp").unwrap();
1736 let mut client = AcpClient::new(io);
1737 let error = client.initialize(timeout).unwrap_err();
1738 assert!(error.to_string().contains(expected), "{response}: {error}");
1739 host.stop_worker("invalid-acp").unwrap();
1740 }
1741 }
1742
1743 #[test]
1744 fn a_logs_worker_keeps_its_log_and_has_no_duplex_io() {
1745 let workspace = tempfile::tempdir().unwrap();
1746 let mut host = LocalProcessFleetHostAdapter::new(workspace.path());
1747 let mut request = FleetWorkerStartRequest::new(
1748 "w-logs",
1749 FleetWorkerCommand::new("sh", ["-c", "echo logged-line"]),
1750 );
1751 request.cwd = Some(workspace.path().to_path_buf());
1752 let handle = host.start_worker(request).unwrap();
1753 assert!(
1754 host.take_worker_io("w-logs").is_none(),
1755 "a Logs worker has no duplex io"
1756 );
1757
1758 let deadline = std::time::Instant::now() + Duration::from_secs(10);
1759 let mut log = String::new();
1760 while std::time::Instant::now() < deadline {
1761 log = host.read_logs("w-logs", 4096).unwrap();
1762 if log.contains("logged-line") {
1763 break;
1764 }
1765 std::thread::sleep(Duration::from_millis(50));
1766 }
1767 assert!(log.contains("logged-line"), "log was {log:?}");
1768 assert!(handle.log_path.exists());
1769 }
1770
1771 #[test]
1772 fn a_cancel_settles_a_prompt_that_never_answers() {
1773 let Some(_node) = node() else {
1774 return;
1775 };
1776 let workspace = tempfile::tempdir().unwrap();
1777 let mut host = LocalProcessFleetHostAdapter::new(workspace.path());
1778 let mut request = json_rpc_request(
1779 BTreeMap::from([("HANG".to_string(), "1".to_string())]),
1780 BTreeSet::from(["HANG".to_string()]),
1781 );
1782 request.cwd = Some(workspace.path().to_path_buf());
1783 host.start_worker(request).unwrap();
1784
1785 let io = host.take_worker_io("w-acp").expect("duplex io");
1786 let mut client = AcpClient::new(io);
1787 let identity = client.initialize(Duration::from_secs(20)).unwrap();
1788 let session = client
1789 .new_session(&identity, workspace.path(), &[], Duration::from_secs(20))
1790 .unwrap()
1791 .session_id;
1792 let canceller = client.canceller(&session);
1793 let prompt_session = session.clone();
1794 let blocked = std::thread::spawn(move || {
1795 client.prompt(
1796 &prompt_session,
1797 "hang",
1798 PermissionPolicy::AllowOnce,
1799 Duration::from_secs(30),
1800 )
1801 });
1802 std::thread::sleep(Duration::from_millis(400));
1803 canceller.cancel().unwrap();
1804 let outcome = blocked.join().unwrap().unwrap();
1805 assert_eq!(outcome.stop_reason, "cancelled");
1806 host.stop_worker("w-acp").unwrap();
1807 }
1808
1809 const WIRE_AGENT: &str = r#"
1810 const fs = require('fs');
1811 const send = (message) => process.stdout.write(JSON.stringify(message) + '\n');
1812 let pending = null;
1813 require('readline').createInterface({ input: process.stdin }).on('line', (line) => {
1814 fs.appendFileSync('received.jsonl', line + '\n');
1815 const message = JSON.parse(line);
1816 if (message.method === 'initialize') {
1817 send({ jsonrpc: '2.0', id: message.id, result: { protocolVersion: 1, agentCapabilities: {}, agentInfo: { name: 'wire-agent', version: '0' } } });
1818 } else if (message.method === 'session/new') {
1819 send({ jsonrpc: '2.0', id: message.id, result: { sessionId: 's1' } });
1820 } else if (message.method === 'session/set_config_option') {
1821 send({ jsonrpc: '2.0', id: message.id, result: { configOptions: [] } });
1822 } else if (message.method === 'session/prompt') {
1823 const text = message.params.prompt[0].text;
1824 const options = [{ optionId: 'allow', name: 'Allow', kind: 'allow_once' }];
1825 if (text === 'hang') {
1826 pending = message.id;
1827 send({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: 's1', update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'mine' } } } });
1828 send({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: 'other', update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'theirs' } } } });
1829 send({ jsonrpc: '2.0', id: 'p-other', method: 'session/request_permission', params: { sessionId: 'other', toolCall: { toolCallId: 't1' }, options } });
1830 } else if (text === 'withdraw') {
1831 pending = message.id;
1832 send({ jsonrpc: '2.0', id: 'p-withdrawn', method: 'session/request_permission', params: { sessionId: 's1', toolCall: { toolCallId: 't2' }, options } });
1833 send({ jsonrpc: '2.0', method: '$/cancel_request', params: { requestId: 'p-withdrawn' } });
1834 } else if (text === 'flood') {
1835 process.stdout.write('"' + 'x'.repeat(8 * 1024 * 1024 + 16) + '"\n');
1836 }
1837 } else if (message.method === 'session/cancel' && pending !== null) {
1838 send({ jsonrpc: '2.0', id: pending, result: { stopReason: 'cancelled' } });
1839 pending = null;
1840 } else if (message.id === 'p-withdrawn' && pending !== null) {
1841 send({ jsonrpc: '2.0', id: pending, result: { stopReason: 'end_turn' } });
1842 pending = null;
1843 }
1844 });
1845 "#;
1846
1847 fn wire_client(workspace: &Path) -> (LocalProcessFleetHostAdapter, AcpClient, String) {
1848 let mut host = LocalProcessFleetHostAdapter::new(workspace);
1849 let mut request = FleetWorkerStartRequest::new(
1850 "w-wire",
1851 FleetWorkerCommand::new("node", ["-e".to_string(), WIRE_AGENT.to_string()]),
1852 );
1853 request.transport = FleetWorkerTransport::JsonRpc;
1854 request.cwd = Some(workspace.to_path_buf());
1855 host.start_worker(request).unwrap();
1856 let mut client = AcpClient::new(host.take_worker_io("w-wire").unwrap());
1857 let identity = client.initialize(Duration::from_secs(20)).unwrap();
1858 assert_eq!(identity.name, "wire-agent");
1859 let session = client
1860 .new_session(&identity, workspace, &[], Duration::from_secs(20))
1861 .unwrap()
1862 .session_id;
1863 (host, client, session)
1864 }
1865
1866 struct SlowAllow {
1867 texts: Vec<String>,
1868 }
1869
1870 impl AcpHandler for SlowAllow {
1871 fn update(&mut self, update: &Value) {
1872 if let Some(text) = update.pointer("/content/text").and_then(Value::as_str) {
1873 self.texts.push(text.to_string());
1874 }
1875 }
1876
1877 fn permission(&mut self, _params: &Value) -> PermissionAnswer {
1878 std::thread::sleep(Duration::from_millis(750));
1879 PermissionAnswer::Selected("allow".to_string())
1880 }
1881 }
1882
1883 #[test]
1884 fn foreign_sessions_withdrawn_requests_and_missed_deadlines_keep_their_rules() {
1885 if node().is_none() {
1886 return;
1887 }
1888 let workspace = tempfile::tempdir().unwrap();
1889 let (mut host, mut client, session) = wire_client(workspace.path());
1890
1891 let canceller = client.canceller(&session);
1892 let prompt_session = session.clone();
1893 let blocked = std::thread::spawn(move || {
1894 let mut handler = SlowAllow { texts: Vec::new() };
1895 let reply = client.prompt_with(
1896 &prompt_session,
1897 "hang",
1898 Duration::from_secs(30),
1899 &mut handler,
1900 None,
1901 );
1902 (client, reply, handler.texts)
1903 });
1904 std::thread::sleep(Duration::from_millis(400));
1905 canceller.cancel().unwrap();
1906 let (mut client, reply, texts) = blocked.join().unwrap();
1907 assert_eq!(reply.unwrap().stop_reason, "cancelled");
1908 assert_eq!(texts, ["mine"], "another session's update was ignored");
1909
1910 let mut handler = SlowAllow { texts: Vec::new() };
1911 let withdrawn = client
1912 .prompt_with(
1913 &session,
1914 "withdraw",
1915 Duration::from_secs(20),
1916 &mut handler,
1917 None,
1918 )
1919 .unwrap();
1920 assert_eq!(withdrawn.stop_reason, "end_turn");
1921
1922 let silent = client
1923 .prompt(
1924 &session,
1925 "silent",
1926 PermissionPolicy::AllowOnce,
1927 Duration::from_millis(500),
1928 )
1929 .unwrap_err();
1930 assert!(silent.to_string().contains("deadline"), "{silent}");
1931 client
1932 .set_config_option(&session, "model", "any", Duration::from_secs(20))
1933 .unwrap();
1934
1935 let received: Vec<Value> = std::fs::read_to_string(workspace.path().join("received.jsonl"))
1936 .unwrap()
1937 .lines()
1938 .map(|line| serde_json::from_str(line).unwrap())
1939 .collect();
1940 let answer = |id: &str| {
1941 received
1942 .iter()
1943 .find(|message| message["id"] == id)
1944 .map(|message| message["result"]["outcome"].clone())
1945 };
1946 assert!(
1947 received
1948 .iter()
1949 .any(|message| message["method"] == "session/cancel"
1950 && message["params"]["sessionId"] == session.as_str()),
1951 "{received:?}"
1952 );
1953 assert_eq!(
1954 answer("p-other"),
1955 Some(json!({"outcome": "cancelled"})),
1956 "a foreign permission request is answered cancelled: {received:?}"
1957 );
1958 assert_eq!(
1959 answer("p-withdrawn"),
1960 Some(json!({"outcome": "cancelled"})),
1961 "a withdrawn permission request is never answered with a selection: {received:?}"
1962 );
1963 assert!(
1964 !received
1965 .iter()
1966 .any(|message| message["method"] == "$/cancel_request"),
1967 "a missed deadline sends nothing to the agent: {received:?}"
1968 );
1969 let requests: Vec<&Value> = received
1970 .iter()
1971 .filter(|message| message.get("method").is_some() && message.get("id").is_some())
1972 .collect();
1973 assert_eq!(requests.len(), 6, "{received:?}");
1974 assert!(
1975 requests.iter().all(|message| message["id"].is_string()),
1976 "request ids are strings: {received:?}"
1977 );
1978 host.stop_worker("w-wire").unwrap();
1979 }
1980
1981 #[test]
1982 fn a_line_over_the_limit_ends_the_connection_unparsed() {
1983 if node().is_none() {
1984 return;
1985 }
1986 let workspace = tempfile::tempdir().unwrap();
1987 let (mut host, mut client, session) = wire_client(workspace.path());
1988 let flooded = client
1989 .prompt(
1990 &session,
1991 "flood",
1992 PermissionPolicy::AllowOnce,
1993 Duration::from_secs(20),
1994 )
1995 .unwrap_err();
1996 assert!(flooded.to_string().contains("8 MiB"), "{flooded}");
1997 let after = client
1998 .set_config_option(&session, "model", "any", Duration::from_secs(5))
1999 .unwrap_err();
2000 assert!(
2001 after.to_string().contains("8 MiB"),
2002 "the connection stays ended: {after}"
2003 );
2004 host.stop_worker("w-wire").unwrap();
2005 }
2006 }
2007
2007 lines RUST