返回 CodeWhale
external_agent.rs
根目录 / crates / engine / src / runtime_threads / manager / external_agent.rs
1 use std::sync::mpsc as std_mpsc;
2
3 use super::*;
4 use crate::external_agents::acp::{
5 AcpCanceller, AcpClient, AcpError, AcpHandler, AgentIdentity, AgentOptions, AgentTokenUsage,
6 Control, PermissionAnswer, PromptReply, SessionOffer, refusal,
7 };
8 use crate::external_agents::cli_agent::{CliTurnEvent, CliTurnRequest, run_cli_turn_blocking};
9 use crate::fleet::agents::{DirectCliKind, ExternalAgentLaunch, ExternalAgentTransport};
10 use crate::fleet::host::{
11 FleetHostAdapter, FleetWorkerCommand, FleetWorkerStartRequest, FleetWorkerTransport,
12 LocalProcessFleetHostAdapter,
13 };
14
15 const SETUP_TIMEOUT: Duration = Duration::from_secs(60);
16 const PROMPT_TIMEOUT: Duration = Duration::from_secs(6 * 60 * 60);
17 const CANCEL_GRACE: Duration = Duration::from_secs(10);
18 const APPROVAL_SETTLE_TIMEOUT: Duration = Duration::from_secs(30);
19 const MAX_DETAIL_BYTES: usize = 256 * 1024;
20 const MAX_INPUT_BYTES: usize = 16 * 1024;
21 const MAX_LABEL_CHARS: usize = 200;
22 const MAX_ID_BYTES: usize = 128;
23 const MAX_TOOL_ITEMS_PER_TURN: usize = 512;
24 const MAX_LOCATIONS: usize = 32;
25 const MAX_OPTIONS: usize = 16;
26 const MAX_CONCURRENT_OPTION_PROBES: usize = 4;
27 static OPTIONS_PROBES: std::sync::LazyLock<Arc<tokio::sync::Semaphore>> =
28 std::sync::LazyLock::new(|| {
29 Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_OPTION_PROBES))
30 });
31 const KILLED_REASON: &str = "The agent did not stop; Codewhale ended its process.";
32 const PLAN_MODES: &[&str] = &[
33 "plan",
34 "https://agentclientprotocol.com/protocol/session-modes#plan",
35 "read-only",
36 "readonly",
37 "denyUnmatched",
38 ];
39 const PLAN_FALLBACK_MODES: &[&str] = &["ask"];
40 const ASK_MODES: &[&str] = &[
41 "default",
42 "manual",
43 "suggest",
44 "ask",
45 "onRequest",
46 "promptUnmatched",
47 "https://agentclientprotocol.com/protocol/session-modes#agent",
48 ];
49 const NO_EDIT_MODES: &[&str] = &[
50 "read-only",
51 "readonly",
52 "denyUnmatched",
53 "plan",
54 "https://agentclientprotocol.com/protocol/session-modes#plan",
55 "ask",
56 ];
57 const POSTURE_NOT_ENFORCED: &str = "posture_not_enforced";
58
59 pub(crate) struct ExternalThreadState {
60 pub(super) session: Arc<ExternalSession>,
61 pub(super) active_turn: Option<ExternalActiveTurn>,
62 pub(super) updating_model: bool,
63 }
64
65 pub(crate) struct ExternalActiveTurn {
66 pub(super) turn_id: String,
67 pub(super) interrupt_requested: bool,
68 pub(super) killed: bool,
69 pub(super) cancel: CancellationToken,
70 pub(super) persisted: watch::Receiver<bool>,
71 }
72
73 enum SessionCommand {
74 Prompt {
75 text: String,
76 permission: ApprovalMode,
77 plan: bool,
78 signals: mpsc::Sender<AgentSignal>,
79 cancel: CancellationToken,
80 },
81 SetChoices {
82 choices: Vec<(&'static str, String)>,
83 reply: std_mpsc::Sender<Result<Option<Option<String>>, anyhow::Error>>,
84 },
85 }
86
87 enum AgentSignal {
88 Update(Value),
89 SessionId(String),
90 Permission {
91 params: Value,
92 reply: std_mpsc::Sender<PermissionAnswer>,
93 },
94 Posture(Value),
95 Finished(Result<PromptReply, String>),
96 }
97
98 trait ExternalHostStop: Send + Sync {
99 fn stop(&self, worker_id: &str) -> Result<()>;
100 }
101
102 struct AcpHostStop(parking_lot::Mutex<LocalProcessFleetHostAdapter>);
103
104 impl ExternalHostStop for AcpHostStop {
105 fn stop(&self, worker_id: &str) -> Result<()> {
106 self.0
107 .lock()
108 .stop_worker(worker_id)
109 .map(|_| ())
110 .map_err(|error| anyhow!("stopping external agent {worker_id} failed: {error}"))
111 }
112 }
113
114 pub(crate) struct ExternalSession {
115 commands: parking_lot::Mutex<Option<std_mpsc::Sender<SessionCommand>>>,
116 canceller: Option<AcpCanceller>,
117 host: Option<Arc<dyn ExternalHostStop>>,
118 worker_id: String,
119 }
120
121 impl ExternalSession {
122 fn send(&self, command: SessionCommand) -> Result<()> {
123 self.commands
124 .lock()
125 .as_ref()
126 .ok_or_else(|| anyhow!("the agent session has ended"))?
127 .send(command)
128 .map_err(|_| anyhow!("the agent session has ended"))
129 }
130
131 pub(super) fn set_choices_blocking(
132 &self,
133 choices: Vec<(&'static str, String)>,
134 ) -> Result<Option<Option<String>>> {
135 let (reply, receiver) = std_mpsc::channel();
136 self.send(SessionCommand::SetChoices { choices, reply })?;
137 receiver
138 .recv()
139 .map_err(|_| anyhow!("the agent session has ended"))?
140 }
141
142 pub(super) fn stop_blocking(&self) -> Result<()> {
143 self.commands.lock().take();
144 if let Some(host) = &self.host {
145 host.stop(&self.worker_id)?;
146 }
147 Ok(())
148 }
149 }
150
151 impl Drop for ExternalSession {
152 fn drop(&mut self) {
153 if let Err(error) = self.stop_blocking() {
154 tracing::warn!(worker = %self.worker_id, %error, "stopping a dropped external agent failed");
155 }
156 }
157 }
158
159 struct ForwardingHandler {
160 signals: mpsc::Sender<AgentSignal>,
161 }
162
163 impl AcpHandler for ForwardingHandler {
164 fn update(&mut self, update: &Value) {
165 let _ = self
166 .signals
167 .blocking_send(AgentSignal::Update(update.clone()));
168 }
169
170 fn permission(&mut self, params: &Value) -> PermissionAnswer {
171 let (reply, answer) = std_mpsc::channel();
172 if self
173 .signals
174 .blocking_send(AgentSignal::Permission {
175 params: params.clone(),
176 reply,
177 })
178 .is_err()
179 {
180 return PermissionAnswer::Cancelled;
181 }
182 answer.recv().unwrap_or(PermissionAnswer::Cancelled)
183 }
184 }
185
186 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
187 pub(in crate::runtime_threads) struct PostureTiers {
188 pub primary: &'static [&'static str],
189 pub fallback: &'static [&'static str],
190 }
191
192 pub(in crate::runtime_threads) fn posture_modes(
193 permission: ApprovalMode,
194 plan: bool,
195 ) -> Option<PostureTiers> {
196 if plan {
197 return Some(PostureTiers {
198 primary: PLAN_MODES,
199 fallback: PLAN_FALLBACK_MODES,
200 });
201 }
202 match permission {
203 ApprovalMode::Never => Some(PostureTiers {
204 primary: NO_EDIT_MODES,
205 fallback: &[],
206 }),
207 ApprovalMode::Suggest | ApprovalMode::Auto => Some(PostureTiers {
208 primary: ASK_MODES,
209 fallback: NO_EDIT_MODES,
210 }),
211 ApprovalMode::AcceptEdits | ApprovalMode::Bypass => None,
212 }
213 }
214
215 pub(in crate::runtime_threads) fn posture_choice(
216 control: Option<&Control>,
217 tiers: &PostureTiers,
218 ) -> Option<String> {
219 let control = control.filter(|control| control.unavailable.is_none())?;
220 let pick_in = |wanted: &[&str]| {
221 control
222 .current
223 .as_deref()
224 .filter(|current| wanted.contains(current) && control.offers(current))
225 .or_else(|| wanted.iter().copied().find(|id| control.offers(id)))
226 .map(str::to_string)
227 };
228 pick_in(tiers.primary).or_else(|| pick_in(tiers.fallback))
229 }
230
231 fn apply_posture(
232 client: &mut AcpClient,
233 session_id: &str,
234 mode: &mut Option<Control>,
235 permission: ApprovalMode,
236 plan: bool,
237 ) -> Result<Option<Value>, String> {
238 let Some(tiers) = posture_modes(permission, plan) else {
239 return Ok(None);
240 };
241 let chosen = posture_choice(mode.as_ref(), &tiers);
242 if let (Some(control), Some(value)) = (mode.as_mut(), chosen.as_ref())
243 && control.current.as_deref() != Some(value.as_str())
244 {
245 client
246 .apply_control(session_id, control, value, SETUP_TIMEOUT)
247 .map_err(|error| {
248 label(
249 Some(&Value::String(format!(
250 "The agent refused mode `{value}`, which Codewhale needs to keep this session's approval posture: {error}"
251 ))),
252 "the agent refused its mode",
253 )
254 })?;
255 control.current = Some(value.clone());
256 }
257 let enforced = chosen.is_some();
258 Ok(Some(json!({
259 "posture": codewhale_runtime::runtime_policy::approval_wire(permission),
260 "plan": plan,
261 "agent_mode": chosen.or_else(|| mode.as_ref().and_then(|control| control.current.clone())),
262 "enforced": enforced,
263 "code": (!enforced).then_some(POSTURE_NOT_ENFORCED),
264 "reason": (!enforced).then_some(
265 "This agent offers no mode that asks before edits; Codewhale's approvals apply only when the agent asks."
266 ),
267 })))
268 }
269
270 fn run_session(
271 mut client: AcpClient,
272 session_id: String,
273 mut offer: SessionOffer,
274 launch: ExternalAgentLaunch,
275 login: Option<&'static str>,
276 commands: std_mpsc::Receiver<SessionCommand>,
277 ) {
278 while let Ok(command) = commands.recv() {
279 match command {
280 SessionCommand::Prompt {
281 text,
282 permission,
283 plan,
284 signals,
285 cancel,
286 } => {
287 let mut mode = offer.control("mode").cloned();
288 match apply_posture(&mut client, &session_id, &mut mode, permission, plan) {
289 Ok(Some(posture)) => {
290 if let (Some(slot), Some(updated)) = (
291 offer
292 .controls
293 .iter_mut()
294 .find(|control| control.id == "mode"),
295 mode,
296 ) {
297 *slot = updated;
298 }
299 let _ = signals.blocking_send(AgentSignal::Posture(posture));
300 }
301 Ok(None) => {}
302 Err(error) => {
303 let _ = signals.blocking_send(AgentSignal::Finished(Err(error)));
304 continue;
305 }
306 }
307 let mut handler = ForwardingHandler {
308 signals: signals.clone(),
309 };
310 let result = client
311 .prompt_with(
312 &session_id,
313 &text,
314 PROMPT_TIMEOUT,
315 &mut handler,
316 Some(&cancel),
317 )
318 .map_err(|error| {
319 label(Some(&Value::String(error.to_string())), "the agent failed")
320 });
321 let _ = signals.blocking_send(AgentSignal::Finished(result));
322 }
323 SessionCommand::SetChoices { choices, reply } => {
324 let prev_offer = offer.clone();
325 let prev_model = offer
326 .controls
327 .iter()
328 .find(|control| control.id == "model")
329 .and_then(|control| control.current.clone());
330 let prev_thought_level = offer
331 .thought_level_control()
332 .and_then(|control| control.current.clone());
333 let mut model_applied = false;
334 let result = match apply_choices_tracked(
335 &mut client,
336 &session_id,
337 &mut offer,
338 &choices,
339 &mut model_applied,
340 ) {
341 Ok(()) => Ok((!offer.controls.is_empty()).then(|| {
342 offer.thought_level_control().and_then(|control| {
343 control
344 .current
345 .as_deref()
346 .filter(|value| control.offers(value))
347 .map(str::to_owned)
348 })
349 })),
350 Err(error) => {
351 if !model_applied {
352 offer = prev_offer;
353 } else if let Some(prev_model_id) = prev_model.as_deref() {
354 if prev_offer.controls.is_empty() {
355 if client
356 .set_config_option(
357 &session_id,
358 "model",
359 prev_model_id,
360 SETUP_TIMEOUT,
361 )
362 .is_ok()
363 {
364 offer = prev_offer;
365 }
366 } else if let Some(prev_control) = prev_offer.control("model").cloned()
367 && prev_control.unavailable.is_none()
368 && prev_control.write.is_some()
369 && let Ok(rollback) = client.apply_control_with_result(
370 &session_id,
371 &prev_control,
372 prev_model_id,
373 SETUP_TIMEOUT,
374 )
375 {
376 offer = prev_offer;
377 offer.refresh_config_options(&rollback);
378 set_choice_current(&mut offer, "model", prev_model_id.to_string());
379 if let Some(prev_thought) = prev_thought_level.as_deref()
380 && let Some(thought_control) =
381 offer.thought_level_control().cloned()
382 && thought_control.unavailable.is_none()
383 && thought_control.write.is_some()
384 && thought_control.offers(prev_thought)
385 && thought_control.current.as_deref() != Some(prev_thought)
386 && let Ok(thought_rollback) = client.apply_control_with_result(
387 &session_id,
388 &thought_control,
389 prev_thought,
390 SETUP_TIMEOUT,
391 )
392 {
393 offer.refresh_config_options(&thought_rollback);
394 set_choice_current(
395 &mut offer,
396 "thought_level",
397 prev_thought.to_string(),
398 );
399 }
400 }
401 }
402 Err(sign_in_or(error, &launch, login))
403 }
404 };
405 let _ = reply.send(result);
406 }
407 }
408 }
409 }
410
411 struct SessionStart {
412 session: ExternalSession,
413 identity: AgentIdentity,
414 session_id: String,
415 initial_model: Option<String>,
416 initial_thought_level: Option<String>,
417 }
418
419 struct AgentProcess {
420 host: Option<LocalProcessFleetHostAdapter>,
421 worker_id: String,
422 }
423
424 impl AgentProcess {
425 fn spawn(
426 log_root: &Path,
427 worker_id: String,
428 workspace: &Path,
429 launch: &ExternalAgentLaunch,
430 ) -> Result<(Self, AcpClient)> {
431 let mut host = LocalProcessFleetHostAdapter::new(log_root);
432 let mut request = FleetWorkerStartRequest::new(
433 worker_id.clone(),
434 FleetWorkerCommand::new(launch.program.display().to_string(), launch.args.clone()),
435 );
436 request.transport = FleetWorkerTransport::JsonRpc;
437 request.cwd = Some(workspace.to_path_buf());
438 request.env_allowlist = launch.env.keys().cloned().collect();
439 request.env = launch.env.clone();
440 host.start_worker(request)
441 .map_err(|error| anyhow!("{} could not start: {error}", launch.agent_name))?;
442 let io = host.take_worker_io(&worker_id);
443 let process = Self {
444 host: Some(host),
445 worker_id,
446 };
447 let Some(io) = io else {
448 bail!("{} started without a protocol channel", launch.agent_name);
449 };
450 Ok((process, AcpClient::new(io)))
451 }
452
453 fn release(mut self) -> LocalProcessFleetHostAdapter {
454 self.host.take().expect("an agent process is released once")
455 }
456
457 fn stop(&mut self) {
458 if let Some(mut host) = self.host.take()
459 && let Err(error) = host.stop_worker(&self.worker_id)
460 {
461 tracing::warn!(worker = %self.worker_id, %error, "stopping an external agent failed");
462 }
463 }
464 }
465
466 impl Drop for AgentProcess {
467 fn drop(&mut self) {
468 self.stop();
469 }
470 }
471
472 fn sign_in_or(
473 error: anyhow::Error,
474 launch: &ExternalAgentLaunch,
475 login: Option<&'static str>,
476 ) -> anyhow::Error {
477 let agent_name = launch.agent_name.as_str();
478 if error
479 .downcast_ref::<AcpError>()
480 .is_some_and(AcpError::is_auth_required)
481 {
482 crate::fleet::agents::record_sign_in(&launch.agent_id, false);
483 let hint = login
484 .map(|command| format!(" Run `{command}` in a terminal, then try again."))
485 .unwrap_or_default();
486 return crate::fleet::agents::ExecutorUnavailable::new(
487 crate::fleet::agents::ExecutorUnavailable::NEEDS_SIGN_IN,
488 format!("{agent_name} needs you to sign in to it first.{hint}"),
489 )
490 .into();
491 }
492 if error
493 .downcast_ref::<crate::fleet::agents::ExecutorUnavailable>()
494 .is_some()
495 {
496 return error;
497 }
498 anyhow!("{agent_name}: {error}")
499 }
500
501 fn executor_choices(executor: &ExecutorRecord) -> Vec<(&'static str, String)> {
502 let mut choices = Vec::new();
503 if let Some(model) = executor.model.as_ref() {
504 choices.push(("model", model.clone()));
505 }
506 if let Some(thought_level) = executor.thought_level.as_ref() {
507 choices.push(("thought_level", thought_level.clone()));
508 }
509 choices
510 }
511
512 pub(super) fn refuse(code: &'static str, message: impl Into<String>) -> anyhow::Error {
513 crate::fleet::agents::ExecutorUnavailable::new(code, message).into()
514 }
515
516 fn resolve_choice_control<'a>(offer: &'a SessionOffer, id: &str) -> Option<&'a Control> {
517 if id == "thought_level" {
518 offer.thought_level_control()
519 } else {
520 offer.control(id)
521 }
522 }
523
524 fn set_choice_current(offer: &mut SessionOffer, id: &str, value: String) {
525 let slot = if id == "thought_level" {
526 offer.thought_level_control_mut()
527 } else {
528 offer.controls.iter_mut().find(|control| control.id == id)
529 };
530 if let Some(slot) = slot {
531 slot.current = Some(value);
532 }
533 }
534
535 fn apply_choices(
536 client: &mut AcpClient,
537 session_id: &str,
538 offer: &mut SessionOffer,
539 choices: &[(&'static str, String)],
540 ) -> Result<()> {
541 let mut model_applied = false;
542 apply_choices_tracked(client, session_id, offer, choices, &mut model_applied)
543 }
544
545 fn apply_choices_tracked(
546 client: &mut AcpClient,
547 session_id: &str,
548 offer: &mut SessionOffer,
549 choices: &[(&'static str, String)],
550 model_applied: &mut bool,
551 ) -> Result<()> {
552 for (id, value) in choices {
553 let shown = label(Some(&Value::String(value.clone())), "");
554 if offer.controls.is_empty() && *id == "model" {
555 client
556 .set_config_option(session_id, "model", value, SETUP_TIMEOUT)
557 .map_err(|error| rejected_choice(id, &shown, error))?;
558 *model_applied = true;
559 continue;
560 }
561 let Some(control) = resolve_choice_control(offer, id).cloned() else {
562 return Err(refuse(
563 refusal::CONTROL_NOT_OFFERED,
564 format!("The agent does not offer a {id} choice, so `{shown}` was not applied."),
565 ));
566 };
567 if let Some(why) = control.unavailable.as_ref() {
568 return Err(refuse(refusal::CONTROL_UNAVAILABLE, why.reason.clone()));
569 }
570 if !control.offers(value) {
571 return Err(refuse(
572 refusal::CHOICE_NOT_OFFERED,
573 format!(
574 "The agent no longer offers `{shown}` for {id}; choose one of its current options."
575 ),
576 ));
577 }
578 if control.current.as_deref() == Some(value.as_str()) {
579 continue;
580 }
581 let response = client
582 .apply_control_with_result(session_id, &control, value, SETUP_TIMEOUT)
583 .map_err(|error| rejected_choice(id, &shown, error))?;
584 if *id == "model" {
585 *model_applied = true;
586 }
587 offer.refresh_config_options(&response);
588 set_choice_current(offer, id, value.clone());
589 }
590 Ok(())
591 }
592
593 fn rejected_choice(id: &str, shown: &str, error: AcpError) -> anyhow::Error {
594 if error.is_auth_required() {
595 return error.into();
596 }
597 refuse(
598 refusal::CHOICE_REJECTED,
599 format!("The agent refused {id} `{shown}`: {error}"),
600 )
601 }
602
603 fn run_cli_session(
604 kind: DirectCliKind,
605 launch: ExternalAgentLaunch,
606 workspace: PathBuf,
607 add_dirs: Vec<PathBuf>,
608 mut model: Option<String>,
609 mut effort: Option<String>,
610 mut foreign_session_id: Option<String>,
611 commands: std_mpsc::Receiver<SessionCommand>,
612 ) {
613 while let Ok(command) = commands.recv() {
614 match command {
615 SessionCommand::Prompt {
616 text,
617 permission,
618 plan,
619 signals,
620 cancel,
621 } => {
622 let req = CliTurnRequest {
623 kind,
624 program: launch.program.clone(),
625 base_args: launch.args.clone(),
626 env: launch.env.clone(),
627 workspace: workspace.clone(),
628 add_dirs: add_dirs.clone(),
629 prompt: text,
630 model: model.clone(),
631 effort: effort.clone(),
632 session_id: foreign_session_id.clone(),
633 permission,
634 plan,
635 };
636 let result =
637 run_cli_turn_blocking(&req, PROMPT_TIMEOUT, &cancel, |event| match event {
638 CliTurnEvent::SessionId(sid) => {
639 if valid_id(&sid) && foreign_session_id.as_deref() != Some(sid.as_str())
640 {
641 foreign_session_id = Some(sid.clone());
642 let _ = signals.blocking_send(AgentSignal::SessionId(sid));
643 }
644 }
645 CliTurnEvent::TextDelta(text) => {
646 let _ = signals.blocking_send(AgentSignal::Update(json!({
647 "sessionUpdate": "agent_message_chunk",
648 "content": { "type": "text", "text": text },
649 })));
650 }
651 CliTurnEvent::ToolStart { id, name, input } => {
652 let _ = signals.blocking_send(AgentSignal::Update(json!({
653 "sessionUpdate": "tool_call",
654 "toolCallId": id,
655 "title": name,
656 "kind": "other",
657 "status": "in_progress",
658 "rawInput": input,
659 })));
660 }
661 CliTurnEvent::ToolEnd { id, output, failed } => {
662 let _ = signals.blocking_send(AgentSignal::Update(json!({
663 "sessionUpdate": "tool_call_update",
664 "toolCallId": id,
665 "status": if failed { "failed" } else { "completed" },
666 "rawOutput": output,
667 })));
668 }
669 CliTurnEvent::Usage(_) | CliTurnEvent::Error(_) => {}
670 })
671 .map(|outcome| PromptReply {
672 stop_reason: outcome.stop_reason,
673 usage: outcome.usage,
674 });
675 let _ = signals.blocking_send(AgentSignal::Finished(result));
676 }
677 SessionCommand::SetChoices { choices, reply } => {
678 for (id, value) in choices {
679 match id {
680 "model" => model = Some(value),
681 "thought_level" => effort = Some(value),
682 _ => {}
683 }
684 }
685 let _ = reply.send(Ok(None));
686 }
687 }
688 }
689 }
690
691 fn start_session_blocking(
692 log_root: PathBuf,
693 thread_id: String,
694 workspace: PathBuf,
695 add_dirs: Vec<PathBuf>,
696 launch: ExternalAgentLaunch,
697 executor: ExecutorRecord,
698 login: Option<&'static str>,
699 abandoned: CancellationToken,
700 ) -> Result<SessionStart> {
701 if let ExternalAgentTransport::DirectCli(kind) = launch.transport {
702 let worker_id = format!("cli-{thread_id}");
703 let initial_model = executor.model.clone();
704 let initial_thought_level = executor.thought_level.clone();
705 let persisted_session_id = executor
706 .foreign_session_id
707 .clone()
708 .filter(|id| id != &worker_id && valid_id(id));
709 let session_id = persisted_session_id
710 .clone()
711 .unwrap_or_else(|| worker_id.clone());
712 let identity = AgentIdentity {
713 name: launch.agent_name.clone(),
714 version: "0".to_string(),
715 protocol_version: 0,
716 load_session: true,
717 resume_session: true,
718 capabilities: Default::default(),
719 };
720 let (commands, receiver) = std_mpsc::channel();
721 let agent_id = launch.agent_id.clone();
722 let model = initial_model.clone();
723 let effort = initial_thought_level.clone();
724 std::thread::Builder::new()
725 .name(format!("cli-{agent_id}"))
726 .spawn(move || {
727 run_cli_session(
728 kind,
729 launch,
730 workspace,
731 add_dirs,
732 model,
733 effort,
734 persisted_session_id,
735 receiver,
736 );
737 })
738 .map_err(|error| anyhow!("starting the CLI agent session thread failed: {error}"))?;
739 return Ok(SessionStart {
740 session: ExternalSession {
741 commands: parking_lot::Mutex::new(Some(commands)),
742 canceller: None,
743 host: None,
744 worker_id,
745 },
746 identity,
747 session_id,
748 initial_model,
749 initial_thought_level,
750 });
751 }
752 let worker_id = format!("acp-{thread_id}");
753 let (process, mut client) =
754 AgentProcess::spawn(&log_root, worker_id.clone(), &workspace, &launch)?;
755 client.abort_requests_on(Some(abandoned));
756 let choices = executor_choices(&executor);
757 let setup = (|| -> Result<(AgentIdentity, String, SessionOffer)> {
758 let identity = client.initialize(SETUP_TIMEOUT)?;
759 let (session_id, mut offer) = match executor.foreign_session_id.as_deref() {
760 Some(session_id) => {
761 let offer = client.reopen_session(
762 &identity,
763 session_id,
764 &workspace,
765 &add_dirs,
766 SETUP_TIMEOUT,
767 )?;
768 (session_id.to_string(), offer)
769 }
770 None => {
771 let started =
772 client.new_session(&identity, &workspace, &add_dirs, SETUP_TIMEOUT)?;
773 (started.session_id, started.offer)
774 }
775 };
776 apply_choices(&mut client, &session_id, &mut offer, &choices)?;
777 Ok((identity, session_id, offer))
778 })();
779 let (identity, session_id, offer) = setup.map_err(|error| sign_in_or(error, &launch, login))?;
780 let initial_model = executor.model.clone().or_else(|| {
781 offer.control("model").and_then(|control| {
782 control
783 .current
784 .as_deref()
785 .filter(|value| control.offers(value))
786 .map(str::to_owned)
787 })
788 });
789 let initial_thought_level = executor.thought_level.clone().or_else(|| {
790 offer.thought_level_control().and_then(|control| {
791 control
792 .current
793 .as_deref()
794 .filter(|value| control.offers(value))
795 .map(str::to_owned)
796 })
797 });
798 crate::fleet::agents::record_sign_in(&launch.agent_id, true);
799 if !valid_id(&session_id) {
800 bail!("{} named an invalid session id", launch.agent_name);
801 }
802 client.abort_requests_on(None);
803 let canceller = client.canceller(&session_id);
804 let (commands, receiver) = std_mpsc::channel();
805 let session_for_thread = session_id.clone();
806 let agent_id = launch.agent_id.clone();
807 std::thread::Builder::new()
808 .name(format!("acp-{agent_id}"))
809 .spawn(move || run_session(client, session_for_thread, offer, launch, login, receiver))
810 .map_err(|error| anyhow!("starting the agent session thread failed: {error}"))?;
811 Ok(SessionStart {
812 session: ExternalSession {
813 commands: parking_lot::Mutex::new(Some(commands)),
814 canceller: Some(canceller),
815 host: Some(Arc::new(AcpHostStop(parking_lot::Mutex::new(
816 process.release(),
817 )))),
818 worker_id,
819 },
820 identity,
821 session_id,
822 initial_model,
823 initial_thought_level,
824 })
825 }
826
827 fn probe_options_blocking(
828 log_root: PathBuf,
829 workspace: PathBuf,
830 launch: ExternalAgentLaunch,
831 login: Option<&'static str>,
832 requested_model: Option<String>,
833 abandoned: CancellationToken,
834 ) -> Result<AgentOptions> {
835 if matches!(launch.transport, ExternalAgentTransport::DirectCli(_)) {
836 let identity = AgentIdentity {
837 name: launch.agent_name.clone(),
838 version: "0".to_string(),
839 protocol_version: 0,
840 load_session: true,
841 resume_session: true,
842 capabilities: Default::default(),
843 };
844 return Ok(AgentOptions::new(
845 &identity,
846 &launch.agent_id,
847 &workspace,
848 SessionOffer::default(),
849 ));
850 }
851 let worker_id = format!("acp-options-{}", runtime_record_id("probe"));
852 let (mut process, mut client) = AgentProcess::spawn(&log_root, worker_id, &workspace, &launch)?;
853 client.abort_requests_on(Some(abandoned));
854 let probed = (|| -> Result<AgentOptions> {
855 let identity = client.initialize(SETUP_TIMEOUT)?;
856 let mut started = client.new_session(&identity, &workspace, &[], SETUP_TIMEOUT)?;
857 let base_current_model = started
858 .offer
859 .control("model")
860 .and_then(|control| control.current.clone());
861 if let Some(model) = requested_model.as_deref()
862 && let Some(control) = started.offer.control("model").cloned()
863 && control.unavailable.is_none()
864 && control.write.is_some()
865 && control.offers(model)
866 && control.current.as_deref() != Some(model)
867 && let Ok(response) = client.apply_control_with_result(
868 &started.session_id,
869 &control,
870 model,
871 SETUP_TIMEOUT,
872 )
873 {
874 started.offer.refresh_config_options(&response);
875 if let Some(base) = base_current_model {
876 set_choice_current(&mut started.offer, "model", base);
877 }
878 }
879 Ok(AgentOptions::new(
880 &identity,
881 &launch.agent_id,
882 &workspace,
883 started.offer,
884 ))
885 })();
886 drop(client);
887 process.stop();
888 let options = probed.map_err(|error| sign_in_or(error, &launch, login))?;
889 crate::fleet::agents::record_sign_in(&launch.agent_id, true);
890 Ok(options)
891 }
892
893 fn valid_id(value: &str) -> bool {
894 !value.is_empty()
895 && value.len() <= MAX_ID_BYTES
896 && value
897 .chars()
898 .all(|ch| !ch.is_control() && !ch.is_whitespace())
899 }
900
901 fn bounded_id(value: Option<&Value>) -> Option<String> {
902 value
903 .and_then(Value::as_str)
904 .filter(|value| valid_id(value))
905 .map(str::to_string)
906 }
907
908 fn label(value: Option<&Value>, fallback: &str) -> String {
909 let text: String = value
910 .and_then(Value::as_str)
911 .unwrap_or(fallback)
912 .chars()
913 .filter(|ch| !ch.is_control() && !crate::session_manager::is_title_format_char(*ch))
914 .take(MAX_LABEL_CHARS)
915 .collect();
916 let text = text.trim();
917 if text.is_empty() {
918 fallback.to_string()
919 } else {
920 text.to_string()
921 }
922 }
923
924 fn clean_text(text: &str) -> String {
925 text.chars()
926 .filter(|ch| {
927 (!ch.is_control() || matches!(ch, '\n' | '\t'))
928 && !crate::session_manager::is_title_format_char(*ch)
929 })
930 .collect()
931 }
932
933 const TRUNCATED_MARKER: &str = "\n[truncated]";
934
935 fn push_bounded(detail: &mut String, text: &str) {
936 let _ = push_bounded_delta(detail, text);
937 }
938
939 fn push_bounded_delta(detail: &mut String, text: &str) -> Option<String> {
940 if detail.len() >= MAX_DETAIL_BYTES || detail.ends_with(TRUNCATED_MARKER) {
941 return None;
942 }
943 let room = MAX_DETAIL_BYTES - detail.len();
944 if text.len() <= room {
945 if text.is_empty() {
946 return None;
947 }
948 detail.push_str(text);
949 return Some(text.to_string());
950 }
951 let max_body = MAX_DETAIL_BYTES.saturating_sub(TRUNCATED_MARKER.len());
952 if detail.len() > max_body {
953 let mut keep = max_body;
954 while !detail.is_char_boundary(keep) {
955 keep -= 1;
956 }
957 detail.truncate(keep);
958 detail.push_str(TRUNCATED_MARKER);
959 Some(TRUNCATED_MARKER.to_string())
960 } else {
961 let before = detail.len();
962 let mut cut = max_body - detail.len();
963 while !text.is_char_boundary(cut) {
964 cut -= 1;
965 }
966 detail.push_str(&text[..cut]);
967 detail.push_str(TRUNCATED_MARKER);
968 Some(detail[before..].to_string())
969 }
970 }
971
972 struct CappedByteCount {
973 bytes: usize,
974 }
975
976 impl std::io::Write for CappedByteCount {
977 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
978 self.bytes = self.bytes.saturating_add(buf.len());
979 if self.bytes > MAX_INPUT_BYTES {
980 return Err(std::io::Error::other("over cap"));
981 }
982 Ok(buf.len())
983 }
984
985 fn flush(&mut self) -> std::io::Result<()> {
986 Ok(())
987 }
988 }
989
990 fn bounded_json(value: Option<&Value>) -> Option<Value> {
991 let value = value.filter(|value| !value.is_null())?;
992 let mut counter = CappedByteCount { bytes: 0 };
993 if serde_json::to_writer(&mut counter, value).is_ok() {
994 let mut value = value.clone();
995 crate::tools::web::consent::strip_consent_marker(&mut value);
996 Some(value)
997 } else {
998 Some(Value::String(format!(
999 "[more than {MAX_INPUT_BYTES} bytes of tool input omitted]"
1000 )))
1001 }
1002 }
1003
1004 fn tool_kind(update: &Value) -> &'static str {
1005 match update
1006 .get("kind")
1007 .and_then(Value::as_str)
1008 .unwrap_or("other")
1009 {
1010 "read" => "read",
1011 "edit" => "edit",
1012 "delete" => "delete",
1013 "move" => "move",
1014 "search" => "search",
1015 "execute" => "execute",
1016 "think" => "think",
1017 "fetch" => "fetch",
1018 "switch_mode" => "switch_mode",
1019 _ => "other",
1020 }
1021 }
1022
1023 fn item_kind_for_tool(kind: &str) -> TurnItemKind {
1024 match kind {
1025 "execute" => TurnItemKind::CommandExecution,
1026 "edit" | "delete" | "move" => TurnItemKind::FileChange,
1027 "switch_mode" => TurnItemKind::Status,
1028 _ => TurnItemKind::ToolCall,
1029 }
1030 }
1031
1032 fn tool_status(update: &Value) -> Option<TurnItemLifecycleStatus> {
1033 match update.get("status").and_then(Value::as_str)? {
1034 "pending" => Some(TurnItemLifecycleStatus::Queued),
1035 "in_progress" => Some(TurnItemLifecycleStatus::InProgress),
1036 "completed" => Some(TurnItemLifecycleStatus::Completed),
1037 "failed" => Some(TurnItemLifecycleStatus::Failed),
1038 _ => None,
1039 }
1040 }
1041
1042 fn location_entries(update: &Value) -> Vec<Value> {
1043 update
1044 .get("locations")
1045 .and_then(Value::as_array)
1046 .map(|locations| {
1047 locations
1048 .iter()
1049 .take(MAX_LOCATIONS)
1050 .filter_map(|location| {
1051 let path = location.get("path").and_then(Value::as_str)?;
1052 if path.len() > 4096 || path.chars().any(char::is_control) {
1053 return None;
1054 }
1055 let mut entry = json!({ "path": path });
1056 if let Some(line) = location
1057 .get("line")
1058 .and_then(Value::as_u64)
1059 .filter(|line| (1..=u64::from(u32::MAX)).contains(line))
1060 {
1061 entry["line"] = json!(line);
1062 }
1063 Some(entry)
1064 })
1065 .collect()
1066 })
1067 .unwrap_or_default()
1068 }
1069
1070 fn locations(update: &Value) -> Vec<String> {
1071 location_entries(update)
1072 .iter()
1073 .filter_map(|entry| {
1074 entry
1075 .get("path")
1076 .and_then(Value::as_str)
1077 .map(str::to_string)
1078 })
1079 .collect()
1080 }
1081
1082 fn content_text(content: Option<&Value>) -> String {
1083 let mut out = String::new();
1084 let Some(blocks) = content.and_then(Value::as_array) else {
1085 return out;
1086 };
1087 for block in blocks.iter().take(64) {
1088 match block.get("type").and_then(Value::as_str) {
1089 Some("content") => {
1090 if let Some(text) = block.pointer("/content/text").and_then(Value::as_str) {
1091 push_bounded(&mut out, &clean_text(text));
1092 out.push('\n');
1093 }
1094 }
1095 Some("diff") => {
1096 let path = label(block.get("path"), "file");
1097 push_bounded(&mut out, &format!("Changed {path}\n"));
1098 }
1099 Some("terminal") => push_bounded(&mut out, "Terminal output\n"),
1100 _ => {}
1101 }
1102 }
1103 out
1104 }
1105
1106 fn chunk_text(update: &Value) -> Option<String> {
1107 update
1108 .pointer("/content/text")
1109 .and_then(Value::as_str)
1110 .map(clean_text)
1111 .filter(|text| !text.is_empty())
1112 }
1113
1114 #[derive(Default)]
1115 pub(in crate::runtime_threads) struct ExternalProjection {
1116 message: Option<TurnItemRecord>,
1117 reasoning: Option<TurnItemRecord>,
1118 tools: HashMap<String, TurnItemRecord>,
1119 tool_items: usize,
1120 plan: Option<TurnItemRecord>,
1121 title: Option<String>,
1122 failure: Option<String>,
1123 context: Option<(Option<u64>, Option<u64>)>,
1124 tokens: Option<AgentTokenUsage>,
1125 }
1126
1127 #[derive(Debug, Clone, PartialEq, Eq)]
1128 struct PermissionOption {
1129 id: String,
1130 name: String,
1131 kind: String,
1132 }
1133
1134 fn permission_options(params: &Value) -> Vec<PermissionOption> {
1135 params
1136 .get("options")
1137 .and_then(Value::as_array)
1138 .map(|options| {
1139 options
1140 .iter()
1141 .take(MAX_OPTIONS)
1142 .filter_map(|option| {
1143 let id = bounded_id(option.get("optionId"))?;
1144 let kind =
1145 match option.get("kind").and_then(Value::as_str)? {
1146 kind @ ("allow_once" | "allow_always" | "reject_once"
1147 | "reject_always") => kind.to_string(),
1148 _ => return None,
1149 };
1150 Some(PermissionOption {
1151 id,
1152 name: label(option.get("name"), &kind),
1153 kind,
1154 })
1155 })
1156 .collect()
1157 })
1158 .unwrap_or_default()
1159 }
1160
1161 fn pick(options: &[PermissionOption], preferred: &[&str]) -> PermissionAnswer {
1162 preferred
1163 .iter()
1164 .find_map(|kind| options.iter().find(|option| option.kind == *kind))
1165 .map_or(PermissionAnswer::Cancelled, |option| {
1166 PermissionAnswer::Selected(option.id.clone())
1167 })
1168 }
1169
1170 fn answer_for(
1171 decision: ExternalApprovalDecision,
1172 options: &[PermissionOption],
1173 ) -> PermissionAnswer {
1174 match decision {
1175 ExternalApprovalDecision::Allow { remember: true } => {
1176 pick(options, &["allow_always", "allow_once"])
1177 }
1178 ExternalApprovalDecision::Allow { remember: false } => pick(options, &["allow_once"]),
1179 ExternalApprovalDecision::Deny { remember: true } => {
1180 pick(options, &["reject_always", "reject_once"])
1181 }
1182 ExternalApprovalDecision::Deny { remember: false } => pick(options, &["reject_once"]),
1183 }
1184 }
1185
1186 async fn posture_answer(
1187 thread: &ThreadRecord,
1188 permission: ApprovalMode,
1189 plan_mode: bool,
1190 kind: &str,
1191 paths: &[String],
1192 options: &[PermissionOption],
1193 ) -> Option<(bool, PermissionAnswer)> {
1194 if plan_mode || permission == ApprovalMode::Never {
1195 return Some((false, pick(options, &["reject_once", "reject_always"])));
1196 }
1197 if permission == ApprovalMode::Bypass {
1198 return Some((true, pick(options, &["allow_once", "allow_always"])));
1199 }
1200 if permission == ApprovalMode::AcceptEdits
1201 && matches!(kind, "edit" | "delete" | "move")
1202 && !paths.is_empty()
1203 && inside_roots(thread, paths).await
1204 {
1205 return Some((true, pick(options, &["allow_once"])));
1206 }
1207 None
1208 }
1209
1210 async fn canonical_or_parent(path: &Path) -> Option<PathBuf> {
1211 if let Ok(resolved) = tokio::fs::canonicalize(path).await {
1212 return Some(resolved);
1213 }
1214 let parent = path.parent()?;
1215 let name = path.file_name()?;
1216 tokio::fs::canonicalize(parent)
1217 .await
1218 .ok()
1219 .map(|parent| parent.join(name))
1220 }
1221
1222 async fn inside_roots(thread: &ThreadRecord, paths: &[String]) -> bool {
1223 let mut roots = Vec::new();
1224 for root in std::iter::once(&thread.workspace).chain(thread.add_dirs.iter()) {
1225 if let Ok(root) = tokio::fs::canonicalize(root).await {
1226 roots.push(root);
1227 }
1228 }
1229 if roots.is_empty() {
1230 return false;
1231 }
1232 for path in paths {
1233 let path = Path::new(path);
1234 if !path.is_absolute()
1235 || path
1236 .components()
1237 .any(|component| matches!(component, Component::ParentDir))
1238 {
1239 return false;
1240 }
1241 let Some(resolved) = canonical_or_parent(path).await else {
1242 return false;
1243 };
1244 if !roots.iter().any(|root| resolved.starts_with(root)) {
1245 return false;
1246 }
1247 }
1248 true
1249 }
1250
1251 fn new_item(
1252 turn_id: &str,
1253 kind: TurnItemKind,
1254 summary: String,
1255 detail: String,
1256 metadata: Option<Value>,
1257 ) -> TurnItemRecord {
1258 TurnItemRecord {
1259 schema_version: CURRENT_RUNTIME_SCHEMA_VERSION,
1260 id: runtime_record_id("item"),
1261 turn_id: turn_id.to_string(),
1262 kind,
1263 status: TurnItemLifecycleStatus::InProgress,
1264 summary,
1265 detail: Some(detail),
1266 metadata,
1267 artifact_refs: Vec::new(),
1268 artifacts: Vec::new(),
1269 started_at: Some(Utc::now()),
1270 ended_at: None,
1271 }
1272 }
1273
1274 impl RuntimeThreadManager {
1275 pub(super) async fn external_session(
1276 &self,
1277 thread: &ThreadRecord,
1278 ) -> Result<Arc<ExternalSession>> {
1279 if let Some(state) = self.active.lock().await.external.get(&thread.id) {
1280 return Ok(Arc::clone(&state.session));
1281 }
1282 let loading = Arc::clone(&self.engine_load).lock_owned().await;
1283 if let Some(state) = self.active.lock().await.external.get(&thread.id) {
1284 return Ok(Arc::clone(&state.session));
1285 }
1286 self.ensure_accepting_execution()?;
1287 let current_thread = self.store.load_thread(&thread.id)?;
1288 let executor = current_thread
1289 .executor
1290 .clone()
1291 .ok_or_else(|| anyhow!("thread {} has no external executor", thread.id))?;
1292 executor.validate()?;
1293 let (default_name, login) = crate::fleet::agents::agent_meta(&executor.agent_id)
1294 .ok_or_else(|| anyhow!("No external agent is named `{}`.", executor.agent_id))?;
1295 let preferred_transport = executor
1296 .transport
1297 .as_deref()
1298 .or_else(|| (executor.kind == EXECUTOR_KIND_CLI).then_some(EXECUTOR_TRANSPORT_CLI));
1299 let launch = match preferred_transport {
1300 Some(transport) => {
1301 crate::fleet::agents::launch_with_transport(&executor.agent_id, Some(transport))
1302 .await?
1303 }
1304 None => crate::fleet::agents::launch(&executor.agent_id).await?,
1305 };
1306 let resolved_transport = launch.transport.as_str().to_string();
1307 let log_root = self
1308 .session_store_binding()
1309 .data_dir
1310 .join("external-agents");
1311 tokio::fs::create_dir_all(&log_root)
1312 .await
1313 .context("creating the external agent log directory failed")?;
1314 let thread_id = current_thread.id.clone();
1315 let workspace = current_thread.workspace.clone();
1316 let add_dirs = current_thread.add_dirs.clone();
1317 let starting = executor.clone();
1318 let abandoned = self.cancel_token.child_token();
1319 let _abandon = abandoned.clone().drop_guard();
1320 let (started, _loading) = tokio::task::spawn_blocking(move || {
1321 let started = start_session_blocking(
1322 log_root, thread_id, workspace, add_dirs, launch, starting, login, abandoned,
1323 );
1324 (started, loading)
1325 })
1326 .await
1327 .context("external agent start worker failed")?;
1328 let SessionStart {
1329 session,
1330 identity,
1331 session_id,
1332 initial_model,
1333 initial_thought_level,
1334 } = started?;
1335 self.ensure_accepting_execution()?;
1336 let session = Arc::new(session);
1337 let store = self.store.clone();
1338 let persisted_thread = thread.id.clone();
1339 let agent_name = label(Some(&Value::String(identity.name.clone())), &default_name);
1340 let agent_version = label(Some(&Value::String(identity.version.clone())), "0");
1341 let effective_model = executor.model.clone().or_else(|| initial_model.clone());
1342 let effective_thought_level = executor
1343 .thought_level
1344 .clone()
1345 .or_else(|| initial_thought_level.clone());
1346 let started_payload = json!({
1347 "agent_id": executor.agent_id,
1348 "agent_name": agent_name,
1349 "agent_version": agent_version,
1350 "transport": resolved_transport,
1351 "protocol_version": identity.protocol_version,
1352 "foreign_session_id": session_id,
1353 "model": effective_model,
1354 "thought_level": effective_thought_level,
1355 "reopened": executor.foreign_session_id.is_some(),
1356 });
1357 let persisted = tokio::task::spawn_blocking(move || {
1358 let _thread_mutation = store.thread_mutation.lock();
1359 let mut current = store.load_thread(&persisted_thread)?;
1360 let record = current
1361 .executor
1362 .as_mut()
1363 .ok_or_else(|| anyhow!("thread executor changed while its agent started"))?;
1364 record.transport = Some(resolved_transport);
1365 record.agent_name = Some(agent_name);
1366 record.agent_version = Some(agent_version);
1367 record.protocol_version = Some(identity.protocol_version);
1368 record.foreign_session_id = Some(session_id);
1369 if record.model.is_none()
1370 && let Some(model) = initial_model
1371 {
1372 current.model = model.clone();
1373 record.model = Some(model);
1374 }
1375 if record.thought_level.is_none()
1376 && let Some(thought_level) = initial_thought_level
1377 {
1378 record.thought_level = Some(thought_level);
1379 }
1380 current.updated_at = Utc::now();
1381 store.save_thread(&current)
1382 })
1383 .await
1384 .context("external agent record worker failed")?;
1385 if let Err(error) = persisted {
1386 let stopping = Arc::clone(&session);
1387 let _ = tokio::task::spawn_blocking(move || stopping.stop_blocking()).await;
1388 return Err(error);
1389 }
1390 self.active.lock().await.external.insert(
1391 thread.id.clone(),
1392 ExternalThreadState {
1393 session: Arc::clone(&session),
1394 active_turn: None,
1395 updating_model: false,
1396 },
1397 );
1398 self.emit_event(&thread.id, None, None, "executor.started", started_payload)
1399 .await?;
1400 Ok(session)
1401 }
1402
1403 pub async fn external_agent_options(&self, agent_id: &str, cwd: &Path) -> Result<AgentOptions> {
1404 self.external_agent_options_for_model(agent_id, cwd, None)
1405 .await
1406 }
1407
1408 pub async fn external_agent_options_for_model(
1409 &self,
1410 agent_id: &str,
1411 cwd: &Path,
1412 model: Option<&str>,
1413 ) -> Result<AgentOptions> {
1414 self.ensure_accepting_execution()?;
1415 let (_, login) = crate::fleet::agents::agent_meta(agent_id).ok_or_else(|| {
1416 crate::fleet::agents::ExecutorUnavailable::new(
1417 crate::fleet::agents::ExecutorUnavailable::UNKNOWN_AGENT,
1418 format!("No external agent is named `{agent_id}`."),
1419 )
1420 })?;
1421 let requested_model = model
1422 .map(str::trim)
1423 .filter(|value| !value.is_empty())
1424 .map(str::to_owned);
1425 let workspace = tokio::fs::canonicalize(cwd)
1426 .await
1427 .map_err(|error| anyhow!("cwd {} is unavailable: {error}", cwd.display()))?;
1428 anyhow::ensure!(
1429 tokio::fs::metadata(&workspace)
1430 .await
1431 .is_ok_and(|metadata| metadata.is_dir()),
1432 "cwd {} is not a directory",
1433 workspace.display()
1434 );
1435 let launch = crate::fleet::agents::launch(agent_id).await?;
1436 let log_root = self
1437 .session_store_binding()
1438 .data_dir
1439 .join("external-agents");
1440 tokio::fs::create_dir_all(&log_root)
1441 .await
1442 .context("creating the external agent log directory failed")?;
1443 let abandoned = self.cancel_token.child_token();
1444 let _abandon = abandoned.clone().drop_guard();
1445 let permit = tokio::select! {
1446 permit = Arc::clone(&OPTIONS_PROBES).acquire_owned() => permit?,
1447 () = abandoned.cancelled() => bail!("Runtime is shutting down; execution admission is closed"),
1448 };
1449 self.ensure_accepting_execution()?;
1450 tokio::task::spawn_blocking(move || {
1451 let _permit = permit;
1452 probe_options_blocking(
1453 log_root,
1454 workspace,
1455 launch,
1456 login,
1457 requested_model,
1458 abandoned,
1459 )
1460 })
1461 .await
1462 .context("external agent options worker failed")?
1463 }
1464
1465 pub(super) async fn external_thread_loaded(&self, thread_id: &str) -> bool {
1466 self.active.lock().await.external.contains_key(thread_id)
1467 }
1468
1469 #[cfg(test)]
1470 pub(crate) async fn external_turn_is_active(&self, thread_id: &str) -> bool {
1471 self.active
1472 .lock()
1473 .await
1474 .external
1475 .get(thread_id)
1476 .is_some_and(|state| state.active_turn.is_some())
1477 }
1478
1479 pub async fn stop_external_agent(&self, thread_id: &str) -> Result<bool> {
1480 let removed = {
1481 let mut active = self.active.lock().await;
1482 if active
1483 .external
1484 .get(thread_id)
1485 .is_some_and(|state| state.active_turn.is_some() || state.updating_model)
1486 {
1487 bail!("thread {thread_id} has an active turn; stop the turn first");
1488 }
1489 active.external.remove(thread_id)
1490 };
1491 let Some(state) = removed else {
1492 return Ok(false);
1493 };
1494 tokio::task::spawn_blocking(move || state.session.stop_blocking())
1495 .await
1496 .context("external agent stop worker failed")??;
1497 self.emit_event(
1498 thread_id,
1499 None,
1500 None,
1501 "executor.stopped",
1502 json!({ "reason": "stopped" }),
1503 )
1504 .await?;
1505 Ok(true)
1506 }
1507
1508 pub(super) async fn stop_all_external_sessions(&self) -> Result<()> {
1509 let sessions = {
1510 let mut active = self.active.lock().await;
1511 active
1512 .external
1513 .iter_mut()
1514 .map(|(id, state)| {
1515 if let Some(turn) = state.active_turn.as_mut() {
1516 turn.interrupt_requested = true;
1517 turn.cancel.cancel();
1518 turn.killed = true;
1519 }
1520 (id.clone(), Arc::clone(&state.session))
1521 })
1522 .collect::<Vec<_>>()
1523 };
1524 self.pending_approvals
1525 .lock()
1526 .retain(|_, entry| !sessions.iter().any(|(id, _)| id == &entry.thread_id));
1527 let mut failure = None;
1528 for (_, session) in sessions {
1529 if let Err(error) = tokio::task::spawn_blocking(move || session.stop_blocking())
1530 .await
1531 .context("external agent stop worker failed")
1532 .and_then(|result| result)
1533 {
1534 failure = Some(error);
1535 }
1536 }
1537 failure.map_or(Ok(()), Err)
1538 }
1539
1540 pub(super) async fn start_external_turn(
1541 &self,
1542 thread: ThreadRecord,
1543 mut req: StartTurnRequest,
1544 input_source: &RuntimeTurnInputSource,
1545 reserved_turn_id: Option<&str>,
1546 mut prompt: String,
1547 ) -> Result<(TurnRecord, bool)> {
1548 anyhow::ensure!(
1549 matches!(input_source, RuntimeTurnInputSource::ExternalUser),
1550 "this kind of turn is not available in a session with another agent"
1551 );
1552 if !req.images.is_empty() {
1553 return Err(refuse(
1554 refusal::UNSUPPORTED_CONTROL,
1555 "Image inputs are not available in a session with another agent.",
1556 ));
1557 }
1558 if !req.dynamic_tools.is_empty() {
1559 return Err(refuse(
1560 refusal::UNSUPPORTED_CONTROL,
1561 "Dynamic tools are not available in a session with another agent.",
1562 ));
1563 }
1564 if req.model.is_some()
1565 || req.reasoning_effort.is_some()
1566 || req.max_output_tokens.is_some()
1567 || req.model_provider.is_some()
1568 || req.model_provider_id.is_some()
1569 || req.account_model_owner.is_some()
1570 {
1571 return Err(refuse(
1572 refusal::UNSUPPORTED_CONTROL,
1573 "A session with another agent keeps its saved agent model; per-turn model, reasoning, output and provider controls are unavailable.",
1574 ));
1575 }
1576 if req.allowed_tools.is_some() {
1577 return Err(refuse(
1578 refusal::UNSUPPORTED_CONTROL,
1579 "A session with another agent uses that agent's own tools; tool allowlists are unavailable.",
1580 ));
1581 }
1582 if req.environment_id.is_some() {
1583 return Err(crate::fleet::agents::ExecutorUnavailable::new(
1584 crate::fleet::agents::ExecutorUnavailable::ENVIRONMENT_NOT_SUPPORTED,
1585 "This build cannot move an external agent turn to another environment.",
1586 )
1587 .into());
1588 }
1589 let executor = thread
1590 .executor
1591 .clone()
1592 .ok_or_else(|| anyhow!("thread {} has no external executor", thread.id))?;
1593 executor.validate()?;
1594 let policy =
1595 if req.mode.is_some() || req.permission_posture.is_some() || req.auto_approve.is_some()
1596 {
1597 runtime_policy_with_overrides(
1598 &thread,
1599 req.mode.as_deref(),
1600 req.permission_posture.as_deref(),
1601 req.auto_approve,
1602 )?
1603 } else {
1604 RuntimePolicyProjection::from_persisted(
1605 &thread.mode,
1606 thread.permission_posture.as_deref(),
1607 thread.auto_approve,
1608 )
1609 };
1610 let operation = match req.operation_key.as_deref() {
1611 Some(operation_key) => {
1612 validate_runtime_turn_operation_key(operation_key)?;
1613 let fingerprint = codewhale_runtime::hashing::sha256_hex(
1614 codewhale_runtime::hashing::canonical_json(&json!({
1615 "domain": "codewhale:external-agent-turn:v1",
1616 "agent_id": executor.agent_id,
1617 "prompt": prompt,
1618 "input_summary": req.input_summary,
1619 "permission": policy.permission_wire(),
1620 "mode": policy.mode.as_setting(),
1621 }))
1622 .as_bytes(),
1623 );
1624 let prepared = self.prepare_runtime_turn_operation(
1625 &thread.id,
1626 Some(operation_key),
1627 fingerprint,
1628 reserved_turn_id,
1629 )?;
1630 if let Some(prepared) = prepared.as_ref() {
1631 let manager = self.clone();
1632 let prepared = prepared.clone();
1633 if let Some(original) = tokio::task::spawn_blocking(move || {
1634 manager.replay_turn_for_operation(&prepared)
1635 })
1636 .await
1637 .context("external operation replay worker failed")??
1638 {
1639 return Ok((original, true));
1640 }
1641 }
1642 prepared
1643 }
1644 None => None,
1645 };
1646 if take_user_command(&mut req, &mut prompt)?.is_some() {
1647 return Err(refuse(
1648 refusal::UNSUPPORTED_CONTROL,
1649 "A session with another agent uses that agent's own tools; a command that limits tools is unavailable.",
1650 ));
1651 }
1652
1653 let now = Utc::now();
1654 let turn_id = operation
1655 .as_ref()
1656 .map(|operation| operation.binding.turn_id.clone())
1657 .unwrap_or_else(|| runtime_record_id("turn"));
1658 let input_summary = req
1659 .input_summary
1660 .clone()
1661 .unwrap_or_else(|| summarize_text(&prompt, SUMMARY_LIMIT));
1662 let user_item = TurnItemRecord {
1663 schema_version: CURRENT_RUNTIME_SCHEMA_VERSION,
1664 id: runtime_record_id("item"),
1665 turn_id: turn_id.clone(),
1666 kind: TurnItemKind::UserMessage,
1667 status: TurnItemLifecycleStatus::Completed,
1668 summary: input_summary.clone(),
1669 detail: input_source.item_detail(&prompt),
1670 metadata: None,
1671 artifact_refs: Vec::new(),
1672 artifacts: Vec::new(),
1673 started_at: Some(now),
1674 ended_at: Some(now),
1675 };
1676 let mut turn = TurnRecord {
1677 imported_history: false,
1678 source_usage_origin_turn_id: None,
1679 source_accounting: false,
1680 source_usage_records: Default::default(),
1681 prefix_checkpoint: None,
1682 decision_receipts: Vec::new(),
1683 max_output_tokens: None,
1684 schema_version: CURRENT_RUNTIME_SCHEMA_VERSION,
1685 id: turn_id.clone(),
1686 thread_id: thread.id.clone(),
1687 status: RuntimeTurnStatus::InProgress,
1688 input_summary,
1689 created_at: now,
1690 started_at: Some(now),
1691 ended_at: None,
1692 duration_ms: None,
1693 usage: None,
1694 routing_settlement: false,
1695 effective_route_usage: None,
1696 permission_posture: Some(policy.permission_wire().to_string()),
1697 mode: Some(policy.mode.as_setting().to_string()),
1698 effective_provider: None,
1699 effective_provider_id: None,
1700 effective_openrouter_vendor: None,
1701 effective_billing_surface: None,
1702 effective_endpoint_fingerprint: None,
1703 effective_provider_live_pricing: None,
1704 effective_billing_mode: None,
1705 effective_dispatched_at: None,
1706 effective_model: executor.model.clone(),
1707 routed_usage: Vec::new(),
1708 routed_usage_drop_records: Vec::new(),
1709 routed_usage_source_ids: Vec::new(),
1710 routed_usage_dropped_records: 0,
1711 model_request_diagnostics: None,
1712 prepared_mcp_tools: None,
1713 operation_activity: None,
1714 error: None,
1715 item_ids: vec![user_item.id.clone()],
1716 steer_count: 0,
1717 agent_mail_message_id: None,
1718 input_source: Some(input_source.turn_source_label().to_string()),
1719 artifacts: Vec::new(),
1720 workspace: None,
1721 workspace_snapshots: Vec::new(),
1722 delegated_writes: Vec::new(),
1723 };
1724 self.wait_for_stopping_turn_to_settle(&thread.id).await;
1725 let mut projection = self.reconciled_projection(&thread.id).await?;
1726 let mut active = self.active.lock().await;
1727 if !active.external.contains_key(&thread.id) {
1728 drop(active);
1729 drop(projection);
1730 self.external_session(&thread).await?;
1731 if turn.effective_model.is_none()
1732 && let Ok(refreshed) = self.store.load_thread(&thread.id)
1733 {
1734 turn.effective_model = refreshed.executor.and_then(|record| record.model);
1735 }
1736 self.wait_for_stopping_turn_to_settle(&thread.id).await;
1737 projection = self.reconciled_projection(&thread.id).await?;
1738 active = self.active.lock().await;
1739 }
1740 let Some(state) = active.external.get_mut(&thread.id) else {
1741 bail!("the agent session ended before the turn could start");
1742 };
1743 let session = Arc::clone(&state.session);
1744 if state.active_turn.is_some() || state.updating_model {
1745 let mut active_persisted = state
1746 .active_turn
1747 .as_ref()
1748 .map(|active_turn| active_turn.persisted.clone());
1749 drop(active);
1750 drop(projection);
1751 if let Some(operation) = operation.as_ref() {
1752 if let Some(persisted) = active_persisted.as_mut() {
1753 let _ = persisted.wait_for(|done| *done).await;
1754 }
1755 let manager = self.clone();
1756 let operation = operation.clone();
1757 if let Some(original) = tokio::task::spawn_blocking(move || {
1758 manager.replay_turn_for_operation(&operation)
1759 })
1760 .await
1761 .context("external operation replay worker failed")??
1762 {
1763 return Ok((original, true));
1764 }
1765 }
1766 bail!("Thread already has an active turn");
1767 }
1768 let cancel = self.cancel_token.child_token();
1769 let (persisted_tx, persisted_rx) = watch::channel(false);
1770 state.active_turn = Some(ExternalActiveTurn {
1771 turn_id: turn_id.clone(),
1772 interrupt_requested: false,
1773 killed: false,
1774 cancel: cancel.clone(),
1775 persisted: persisted_rx,
1776 });
1777 let manager = self.clone();
1778 let plan_mode = policy.mode == codewhale_config::AppMode::Plan;
1779 let permission = policy.permission;
1780 let (accepted, acceptance) = oneshot::channel();
1781 let worker = tokio::spawn(async move {
1782 let persisting = manager.clone();
1783 let persisted_thread = thread.clone();
1784 let persisted_turn = turn.clone();
1785 let persisted_item = user_item.clone();
1786 let persisted = tokio::task::spawn_blocking(move || {
1787 let store = &persisting.store;
1788 let persisted = (|| -> Result<()> {
1789 if let Some(operation) = operation.as_ref() {
1790 store.save_turn_operation_binding(&operation.binding)?;
1791 }
1792 store.save_item(&persisted_item)?;
1793 store.save_turn(&persisted_turn)?;
1794 let _thread_mutation = store.thread_mutation.lock();
1795 let mut current = store.load_thread(&persisted_thread.id)?;
1796 anyhow::ensure!(
1797 current.executor.as_ref().map(|record| &record.agent_id)
1798 == persisted_thread
1799 .executor
1800 .as_ref()
1801 .map(|record| &record.agent_id),
1802 "Thread executor changed while preparing the turn; retry"
1803 );
1804 current.latest_turn_id = Some(persisted_turn.id.clone());
1805 current.updated_at = now;
1806 store.save_thread(&current)
1807 })();
1808 if let Err(error) = persisted {
1809 let cleanup = persisting.cleanup_unaccepted_turn_records(
1810 &persisted_turn.id,
1811 Some(&persisted_item.id),
1812 operation
1813 .as_ref()
1814 .map(|operation| operation.binding.operation_key_fingerprint.as_str()),
1815 );
1816 return match cleanup {
1817 Ok(()) => Err(anyhow!("Failed to persist turn: {error}")),
1818 Err(cleanup) => Err(anyhow!(
1819 "Failed to persist turn: {error}; cleanup also failed: {cleanup}"
1820 )),
1821 };
1822 }
1823 Ok(())
1824 })
1825 .await
1826 .context("external turn persistence worker failed")
1827 .and_then(|result| result);
1828 let _ = persisted_tx.send(true);
1829 if let Err(error) = persisted {
1830 if let Some(state) = manager.active.lock().await.external.get_mut(&thread.id) {
1831 state.active_turn = None;
1832 }
1833 let _ = accepted.send(Err(error.to_string()));
1834 return;
1835 }
1836 manager
1837 .emit_claimed_turn_started(
1838 &turn,
1839 Some(&user_item),
1840 ClaimedTurnKind::Message {
1841 structured_review: false,
1842 narrowing: crate::core::engine::TurnNarrowing::Inherit,
1843 },
1844 )
1845 .await;
1846 let (signals, receiver) = mpsc::channel(16);
1847 let sent = session.send(SessionCommand::Prompt {
1848 text: prompt,
1849 permission,
1850 plan: plan_mode,
1851 signals: signals.clone(),
1852 cancel,
1853 });
1854 if let Err(error) = sent {
1855 let _ = signals
1856 .send(AgentSignal::Finished(Err(error.to_string())))
1857 .await;
1858 }
1859 drop(signals);
1860 let _ = accepted.send(Ok(turn));
1861 manager
1862 .drive_external_turn(thread, turn_id, permission, plan_mode, receiver)
1863 .await;
1864 });
1865 self.track_receipt_worker(worker);
1866 drop(active);
1867 drop(projection);
1868 let turn = acceptance
1869 .await
1870 .context("external turn worker ended before acceptance")?
1871 .map_err(anyhow::Error::msg)?;
1872 Ok((turn, false))
1873 }
1874
1875 async fn drive_external_turn(
1876 self,
1877 thread: ThreadRecord,
1878 turn_id: String,
1879 permission: ApprovalMode,
1880 plan_mode: bool,
1881 mut receiver: mpsc::Receiver<AgentSignal>,
1882 ) {
1883 let mut projection = ExternalProjection::default();
1884 let outcome = loop {
1885 match receiver.recv().await {
1886 Some(AgentSignal::Update(update)) => {
1887 if projection.failure.is_none()
1888 && let Err(error) = self
1889 .apply_external_update(&thread, &turn_id, &mut projection, &update)
1890 .await
1891 {
1892 projection.failure =
1893 Some(format!("Recording the agent's update failed: {error}"));
1894 let session = self
1895 .active
1896 .lock()
1897 .await
1898 .external
1899 .get(&thread.id)
1900 .map(|state| Arc::clone(&state.session));
1901 if let Some(session) = session {
1902 let _ =
1903 tokio::task::spawn_blocking(move || session.stop_blocking()).await;
1904 }
1905 }
1906 }
1907 Some(AgentSignal::SessionId(session_id)) => {
1908 let store = self.store.clone();
1909 let persisted_thread = thread.id.clone();
1910 let _ = tokio::task::spawn_blocking(move || -> Result<()> {
1911 let _thread_mutation = store.thread_mutation.lock();
1912 let mut current = store.load_thread(&persisted_thread)?;
1913 if let Some(record) = current.executor.as_mut() {
1914 record.foreign_session_id = Some(session_id);
1915 current.updated_at = Utc::now();
1916 store.save_thread(&current)?;
1917 }
1918 Ok(())
1919 })
1920 .await;
1921 }
1922 Some(AgentSignal::Permission { params, reply }) => {
1923 let answer = if projection.failure.is_some() {
1924 PermissionAnswer::Cancelled
1925 } else {
1926 self.bridge_external_permission(
1927 &thread, &turn_id, permission, plan_mode, &params,
1928 )
1929 .await
1930 };
1931 let _ = reply.send(answer);
1932 }
1933 Some(AgentSignal::Posture(posture)) => {
1934 if let Err(error) = self
1935 .emit_event(
1936 &thread.id,
1937 Some(&turn_id),
1938 None,
1939 "turn.agent_posture",
1940 posture,
1941 )
1942 .await
1943 {
1944 tracing::warn!(thread_id = %thread.id, turn_id = %turn_id, %error, "recording an external agent's posture failed");
1945 }
1946 }
1947 Some(AgentSignal::Finished(result)) => {
1948 break result.map(|reply| {
1949 projection.tokens = reply.usage;
1950 reply.stop_reason
1951 });
1952 }
1953 None => break Err("the agent session ended".to_string()),
1954 }
1955 };
1956 if let Err(error) = self
1957 .emit_agent_usage(&thread.id, &turn_id, &projection)
1958 .await
1959 {
1960 tracing::warn!(thread_id = %thread.id, turn_id = %turn_id, %error, "recording an external agent's usage failed");
1961 }
1962 if let Err(error) = self
1963 .settle_external_turn(&thread, &turn_id, projection, outcome)
1964 .await
1965 {
1966 tracing::warn!(thread_id = %thread.id, turn_id = %turn_id, %error, "settling an external agent turn failed");
1967 }
1968 }
1969
1970 async fn emit_agent_usage(
1971 &self,
1972 thread_id: &str,
1973 turn_id: &str,
1974 projection: &ExternalProjection,
1975 ) -> Result<()> {
1976 let tokens = projection
1977 .tokens
1978 .as_ref()
1979 .filter(|tokens| !tokens.is_empty());
1980 let reported = tokens.is_some() || projection.context.is_some();
1981 let payload = json!({
1982 "kind": "turn_total",
1983 "source": if reported { "agent reported" } else { "none" },
1984 "tokens": tokens.map_or_else(|| json!("unknown"), |tokens| json!(tokens)),
1985 "context": projection.context.map_or_else(
1986 || json!("unknown"),
1987 |(used, size)| json!({ "used": used, "size": size }),
1988 ),
1989 "cost": "unknown",
1990 });
1991 self.emit_event(thread_id, Some(turn_id), None, "turn.agent_usage", payload)
1992 .await?;
1993 Ok(())
1994 }
1995
1996 async fn open_external_item(
1997 &self,
1998 thread_id: &str,
1999 turn_id: &str,
2000 item: &TurnItemRecord,
2001 tool: Option<Value>,
2002 ) -> Result<()> {
2003 self.save_streaming_item(item).await?;
2004 let manager = self.clone();
2005 let attached_turn = turn_id.to_string();
2006 let attached_item = item.id.clone();
2007 tokio::task::spawn_blocking(move || {
2008 manager.attach_item_to_turn(&attached_turn, &attached_item)
2009 })
2010 .await
2011 .context("external item attachment worker failed")??;
2012 let mut payload = json!({ "item": item });
2013 if let Some(tool) = tool {
2014 payload["tool"] = tool;
2015 }
2016 self.emit_event(
2017 thread_id,
2018 Some(turn_id),
2019 Some(&item.id),
2020 "item.started",
2021 payload,
2022 )
2023 .await?;
2024 Ok(())
2025 }
2026
2027 async fn stream_external_chunk(
2028 &self,
2029 thread_id: &str,
2030 turn_id: &str,
2031 projection: &mut ExternalProjection,
2032 reasoning: bool,
2033 text: &str,
2034 ) -> Result<()> {
2035 let (kind, delta_kind) = if reasoning {
2036 (TurnItemKind::AgentReasoning, "agent_reasoning")
2037 } else {
2038 (TurnItemKind::AgentMessage, "agent_message")
2039 };
2040 let (slot, other) = if reasoning {
2041 (&mut projection.reasoning, &mut projection.message)
2042 } else {
2043 (&mut projection.message, &mut projection.reasoning)
2044 };
2045 self.close_streaming_item(
2046 thread_id,
2047 turn_id,
2048 other,
2049 TurnItemLifecycleStatus::Completed,
2050 )
2051 .await?;
2052 if slot.is_none() {
2053 let item = new_item(turn_id, kind, String::new(), String::new(), None);
2054 self.open_external_item(thread_id, turn_id, &item, None)
2055 .await?;
2056 *slot = Some(item);
2057 }
2058 let Some(item) = slot.as_mut() else {
2059 return Ok(());
2060 };
2061 let detail = item.detail.get_or_insert_default();
2062 let Some(delta) = push_bounded_delta(detail, text) else {
2063 return Ok(());
2064 };
2065 item.summary = summarize_text(detail, SUMMARY_LIMIT);
2066 let projection_lock = self.projection_lock(thread_id);
2067 let _projection = projection_lock.lock().await;
2068 self.save_streaming_item(item).await?;
2069 self.emit_event(
2070 thread_id,
2071 Some(turn_id),
2072 Some(&item.id),
2073 "item.delta",
2074 json!({ "delta": delta, "kind": delta_kind }),
2075 )
2076 .await?;
2077 Ok(())
2078 }
2079
2080 async fn apply_external_update(
2081 &self,
2082 thread: &ThreadRecord,
2083 turn_id: &str,
2084 projection: &mut ExternalProjection,
2085 update: &Value,
2086 ) -> Result<()> {
2087 let thread_id = thread.id.as_str();
2088 match update.get("sessionUpdate").and_then(Value::as_str) {
2089 Some("agent_message_chunk") => {
2090 if let Some(text) = chunk_text(update) {
2091 self.stream_external_chunk(thread_id, turn_id, projection, false, &text)
2092 .await?;
2093 }
2094 }
2095 Some("agent_thought_chunk") => {
2096 if let Some(text) = chunk_text(update) {
2097 self.stream_external_chunk(thread_id, turn_id, projection, true, &text)
2098 .await?;
2099 }
2100 }
2101 Some("tool_call") => {
2102 let Some(call_id) = bounded_id(update.get("toolCallId")) else {
2103 return Ok(());
2104 };
2105 self.close_streaming_item(
2106 thread_id,
2107 turn_id,
2108 &mut projection.message,
2109 TurnItemLifecycleStatus::Completed,
2110 )
2111 .await?;
2112 self.close_streaming_item(
2113 thread_id,
2114 turn_id,
2115 &mut projection.reasoning,
2116 TurnItemLifecycleStatus::Completed,
2117 )
2118 .await?;
2119 if projection.tools.contains_key(&call_id)
2120 || projection.tool_items >= MAX_TOOL_ITEMS_PER_TURN
2121 {
2122 return self
2123 .update_external_tool(thread_id, turn_id, projection, &call_id, update)
2124 .await;
2125 }
2126 let kind = tool_kind(update);
2127 let title = label(update.get("title"), "Tool call");
2128 let paths = location_entries(update);
2129 let input = bounded_json(update.get("rawInput"));
2130 let mut detail = String::new();
2131 if let Some(input) = input.as_ref() {
2132 push_bounded(&mut detail, &input.to_string());
2133 detail.push('\n');
2134 }
2135 push_bounded(&mut detail, &content_text(update.get("content")));
2136 let mut item = new_item(
2137 turn_id,
2138 item_kind_for_tool(kind),
2139 title.clone(),
2140 detail,
2141 Some(json!({
2142 "external_agent": { "tool_call_id": call_id, "kind": kind, "locations": paths }
2143 })),
2144 );
2145 if tool_status(update) == Some(TurnItemLifecycleStatus::Queued) {
2146 item.status = TurnItemLifecycleStatus::Queued;
2147 }
2148 self.open_external_item(
2149 thread_id,
2150 turn_id,
2151 &item,
2152 Some(json!({ "id": call_id, "name": kind, "input": input })),
2153 )
2154 .await?;
2155 projection.tool_items += 1;
2156 projection.tools.insert(call_id.clone(), item);
2157 if matches!(
2158 tool_status(update),
2159 Some(TurnItemLifecycleStatus::Completed | TurnItemLifecycleStatus::Failed)
2160 ) {
2161 self.update_external_tool(thread_id, turn_id, projection, &call_id, update)
2162 .await?;
2163 }
2164 }
2165 Some("tool_call_update") => {
2166 if let Some(call_id) = bounded_id(update.get("toolCallId")) {
2167 self.update_external_tool(thread_id, turn_id, projection, &call_id, update)
2168 .await?;
2169 }
2170 }
2171 Some("plan" | "plan_update") => {
2172 let mut detail = String::new();
2173 for entry in update
2174 .get("entries")
2175 .and_then(Value::as_array)
2176 .map(Vec::as_slice)
2177 .unwrap_or_default()
2178 .iter()
2179 .take(64)
2180 {
2181 let status = label(entry.get("status"), "pending");
2182 let content = label(entry.get("content"), "");
2183 push_bounded(&mut detail, &format!("[{status}] {content}\n"));
2184 }
2185 match projection.plan.as_mut() {
2186 Some(item) => {
2187 item.detail = Some(detail);
2188 self.save_streaming_item(item).await?;
2189 }
2190 None => {
2191 let item = new_item(
2192 turn_id,
2193 TurnItemKind::Status,
2194 "Plan".to_string(),
2195 detail,
2196 Some(json!({ "external_agent": { "plan": true } })),
2197 );
2198 self.open_external_item(thread_id, turn_id, &item, None)
2199 .await?;
2200 projection.plan = Some(item);
2201 }
2202 }
2203 }
2204 Some("usage_update") => {
2205 let used = update.get("used").and_then(Value::as_u64);
2206 let size = update.get("size").and_then(Value::as_u64);
2207 if used.is_some() || size.is_some() {
2208 projection.context = Some((used, size));
2209 self.emit_event(
2210 thread_id,
2211 Some(turn_id),
2212 None,
2213 "turn.agent_usage",
2214 json!({ "kind": "context_window", "used": used, "size": size, "source": "agent reported", "cost": "unknown" }),
2215 )
2216 .await?;
2217 }
2218 }
2219 Some("current_mode_update") => {
2220 let mode = bounded_id(update.get("currentModeId").or_else(|| update.get("modeId")));
2221 if let Some(mode) = mode {
2222 self.emit_event(
2223 thread_id,
2224 Some(turn_id),
2225 None,
2226 "turn.agent_mode",
2227 json!({ "mode": mode, "source": "agent reported" }),
2228 )
2229 .await?;
2230 }
2231 }
2232 Some("available_commands_update") => {
2233 let commands: Vec<Value> = update
2234 .get("availableCommands")
2235 .and_then(Value::as_array)
2236 .map(Vec::as_slice)
2237 .unwrap_or_default()
2238 .iter()
2239 .take(64)
2240 .filter_map(|command| {
2241 let name = bounded_id(command.get("name"))?;
2242 let description = label(command.get("description"), "");
2243 Some(json!({ "name": name, "description": description }))
2244 })
2245 .collect();
2246 self.emit_event(
2247 thread_id,
2248 Some(turn_id),
2249 None,
2250 "turn.agent_commands",
2251 json!({ "commands": commands, "source": "agent reported" }),
2252 )
2253 .await?;
2254 }
2255 Some("session_info_update") => {
2256 if let Some(title) = update.get("title").and_then(Value::as_str) {
2257 let title = label(Some(&Value::String(title.to_string())), "");
2258 if !title.is_empty() {
2259 projection.title = Some(title);
2260 }
2261 }
2262 }
2263 _ => {}
2264 }
2265 Ok(())
2266 }
2267
2268 async fn update_external_tool(
2269 &self,
2270 thread_id: &str,
2271 turn_id: &str,
2272 projection: &mut ExternalProjection,
2273 call_id: &str,
2274 update: &Value,
2275 ) -> Result<()> {
2276 let Some(item) = projection.tools.get_mut(call_id) else {
2277 return Ok(());
2278 };
2279 if item.ended_at.is_some() {
2280 return Ok(());
2281 }
2282 if update.get("title").is_some() {
2283 item.summary = label(update.get("title"), &item.summary.clone());
2284 }
2285 let output = content_text(update.get("content"));
2286 let raw = bounded_json(update.get("rawOutput"))
2287 .map(|value| match value {
2288 Value::String(text) => clean_text(&text),
2289 other => other.to_string(),
2290 })
2291 .unwrap_or_default();
2292 let detail = item.detail.get_or_insert_default();
2293 push_bounded(detail, &output);
2294 if !raw.is_empty() {
2295 push_bounded(detail, &raw);
2296 detail.push('\n');
2297 }
2298 match tool_status(update) {
2299 Some(TurnItemLifecycleStatus::InProgress)
2300 if item.status == TurnItemLifecycleStatus::Queued =>
2301 {
2302 item.status = TurnItemLifecycleStatus::InProgress;
2303 item.started_at = Some(Utc::now());
2304 self.save_streaming_item(item).await?;
2305 self.emit_event(
2306 thread_id,
2307 Some(turn_id),
2308 Some(&item.id),
2309 "tool.execution_started",
2310 json!({ "execution_id": call_id, "item": item }),
2311 )
2312 .await?;
2313 }
2314 Some(
2315 status @ (TurnItemLifecycleStatus::Completed | TurnItemLifecycleStatus::Failed),
2316 ) => {
2317 let now = Utc::now();
2318 if item.status == TurnItemLifecycleStatus::Queued {
2319 item.started_at = Some(now);
2320 }
2321 item.status = status;
2322 item.ended_at = Some(now);
2323 self.save_streaming_item(item).await?;
2324 self.emit_event(
2325 thread_id,
2326 Some(turn_id),
2327 Some(&item.id),
2328 item_terminal_event(status),
2329 json!({ "item": item }),
2330 )
2331 .await?;
2332 }
2333 _ => self.save_streaming_item(item).await?,
2334 }
2335 Ok(())
2336 }
2337
2338 async fn bridge_external_permission(
2339 &self,
2340 thread: &ThreadRecord,
2341 turn_id: &str,
2342 permission: ApprovalMode,
2343 plan_mode: bool,
2344 params: &Value,
2345 ) -> PermissionAnswer {
2346 let accepting = self
2347 .active
2348 .lock()
2349 .await
2350 .external
2351 .get(&thread.id)
2352 .and_then(|state| state.active_turn.as_ref())
2353 .is_some_and(|turn| turn.turn_id == turn_id && !turn.cancel.is_cancelled());
2354 if !accepting {
2355 return PermissionAnswer::Cancelled;
2356 }
2357 let agent_id = thread
2358 .executor
2359 .as_ref()
2360 .map(|record| record.agent_id.clone())
2361 .unwrap_or_default();
2362 let tool = params.get("toolCall").cloned().unwrap_or(Value::Null);
2363 let tool_call_id = bounded_id(tool.get("toolCallId"));
2364 let title = label(tool.get("title"), "The agent wants to use a tool");
2365 let kind = tool_kind(&tool);
2366 let paths = locations(&tool);
2367 let permission_paths = tool
2368 .get("locations")
2369 .and_then(Value::as_array)
2370 .filter(|all| all.len() == paths.len())
2371 .map(|_| paths.as_slice())
2372 .unwrap_or_default();
2373 let input = bounded_json(tool.get("rawInput"));
2374 let options = permission_options(params);
2375 let option_names: Vec<Value> = options
2376 .iter()
2377 .map(|option| json!({ "id": option.id, "name": option.name, "kind": option.kind }))
2378 .collect();
2379
2380 if let Some((allow, answer)) = posture_answer(
2381 thread,
2382 permission,
2383 plan_mode,
2384 kind,
2385 permission_paths,
2386 &options,
2387 )
2388 .await
2389 {
2390 let approval_id = Self::mint_approval_id();
2391 let option_id = match &answer {
2392 PermissionAnswer::Selected(id) => Some(id.clone()),
2393 PermissionAnswer::Cancelled => None,
2394 };
2395 if let Err(error) = self
2396 .emit_event(
2397 &thread.id,
2398 Some(turn_id),
2399 None,
2400 "approval.decided",
2401 json!({
2402 "approval_id": approval_id, "tool_call_id": tool_call_id,
2403 "decision": if allow { "allow" } else { "deny" },
2404 "remember": false, "auto": true, "decided_by": "policy",
2405 "posture": codewhale_runtime::runtime_policy::approval_wire(permission),
2406 "plan_mode": plan_mode, "option_id": option_id,
2407 "external_agent": agent_id, "summary": title,
2408 }),
2409 )
2410 .await
2411 {
2412 tracing::warn!(%error, "recording an automatic external approval failed");
2413 return PermissionAnswer::Cancelled;
2414 }
2415 return answer;
2416 }
2417
2418 let request = PendingApprovalRequest {
2419 id: String::new(),
2420 turn_id: turn_id.to_string(),
2421 tool_name: format!("{agent_id}:{kind}"),
2422 input: input.clone(),
2423 description: title.clone(),
2424 intent_summary: None,
2425 tool_call_id: tool_call_id.clone(),
2426 summary: Some(title.clone()),
2427 approval_kind: None,
2428 };
2429 let (approval_id, decision, settled) = {
2430 let active = self.active.lock().await;
2431 let accepting = active
2432 .external
2433 .get(&thread.id)
2434 .and_then(|state| state.active_turn.as_ref())
2435 .is_some_and(|turn| turn.turn_id == turn_id && !turn.interrupt_requested);
2436 if !accepting {
2437 return PermissionAnswer::Cancelled;
2438 }
2439 self.register_agent_approval(&thread.id, request)
2440 };
2441 if let Err(error) = self
2442 .emit_event(
2443 &thread.id,
2444 Some(turn_id),
2445 None,
2446 "approval.required",
2447 json!({
2448 "id": approval_id, "approval_id": approval_id, "tool_call_id": tool_call_id,
2449 "tool_name": format!("{agent_id}:{kind}"), "input": input, "summary": title,
2450 "description": title, "intent_summary": Value::Null,
2451 "external_agent": agent_id, "options": option_names, "locations": paths,
2452 }),
2453 )
2454 .await
2455 {
2456 tracing::warn!(%error, "publishing an external approval failed");
2457 self.cancel_pending_approval(&approval_id);
2458 let _ = settled.send(Some(false));
2459 return PermissionAnswer::Cancelled;
2460 }
2461 let (answer, mut payload) = match decision.await {
2462 Ok(decision) => {
2463 let answer = answer_for(decision, &options);
2464 let (allow, remember) = match decision {
2465 ExternalApprovalDecision::Allow { remember } => (true, remember),
2466 ExternalApprovalDecision::Deny { remember } => (false, remember),
2467 };
2468 let option_id = match &answer {
2469 PermissionAnswer::Selected(id) => Some(id.clone()),
2470 PermissionAnswer::Cancelled => None,
2471 };
2472 (
2473 answer,
2474 json!({
2475 "approval_id": approval_id, "tool_call_id": tool_call_id,
2476 "decision": if allow { "allow" } else { "deny" },
2477 "remember": remember, "decided_by": "user",
2478 "option_id": option_id, "external_agent": agent_id,
2479 }),
2480 )
2481 }
2482 Err(_) => (
2483 PermissionAnswer::Cancelled,
2484 json!({
2485 "approval_id": approval_id, "tool_call_id": tool_call_id,
2486 "decision": "deny", "remember": false, "cancelled": true,
2487 "decided_by": "host", "external_agent": agent_id,
2488 }),
2489 ),
2490 };
2491 if let Some(responder) = self
2492 .pending_approvals
2493 .lock()
2494 .get(&approval_id)
2495 .and_then(|entry| entry.responder)
2496 {
2497 payload["responder"] = json!(responder);
2498 }
2499 let recorded = self
2500 .emit_event(&thread.id, Some(turn_id), None, "approval.decided", payload)
2501 .await;
2502 self.cancel_pending_approval(&approval_id);
2503 match recorded {
2504 Ok(_) => {
2505 let _ = settled.send(Some(true));
2506 answer
2507 }
2508 Err(error) => {
2509 tracing::warn!(%error, "recording an external approval decision failed");
2510 let _ = settled.send(Some(false));
2511 PermissionAnswer::Cancelled
2512 }
2513 }
2514 }
2515
2516 pub(in crate::runtime_threads) async fn settle_external_turn(
2517 &self,
2518 thread: &ThreadRecord,
2519 turn_id: &str,
2520 mut projection: ExternalProjection,
2521 outcome: Result<String, String>,
2522 ) -> Result<()> {
2523 if outcome.is_ok()
2524 && let Some(executor) = thread.executor.as_ref()
2525 {
2526 crate::fleet::agents::record_sign_in(&executor.agent_id, true);
2527 }
2528 let (interrupted, killed) = self
2529 .active
2530 .lock()
2531 .await
2532 .external
2533 .get(&thread.id)
2534 .and_then(|state| state.active_turn.as_ref())
2535 .filter(|turn| turn.turn_id == turn_id)
2536 .map_or((false, false), |turn| {
2537 (turn.interrupt_requested, turn.killed)
2538 });
2539 let projection_failed = projection.failure.is_some();
2540 let (status, error) = match (&outcome, projection.failure.take()) {
2541 (_, Some(failure)) => (RuntimeTurnStatus::Failed, Some(failure)),
2542 (Ok(reason), None) if interrupted || reason == "cancelled" => {
2543 (RuntimeTurnStatus::Interrupted, None)
2544 }
2545 (Ok(reason), None) if reason == "end_turn" => (RuntimeTurnStatus::Completed, None),
2546 (Ok(reason), None) => (
2547 RuntimeTurnStatus::Failed,
2548 Some(format!(
2549 "The agent stopped: {}",
2550 label(Some(&Value::String(reason.clone())), "unknown")
2551 )),
2552 ),
2553 (Err(_), None) if killed => (
2554 RuntimeTurnStatus::Interrupted,
2555 Some(KILLED_REASON.to_string()),
2556 ),
2557 (Err(_), None) if interrupted => (RuntimeTurnStatus::Interrupted, None),
2558 (Err(reason), None) => (RuntimeTurnStatus::Failed, Some(reason.clone())),
2559 };
2560 self.pending_approvals
2561 .lock()
2562 .retain(|_, entry| entry.thread_id != thread.id || entry.request.turn_id != turn_id);
2563 let item_status = terminal_item_status(status);
2564 self.close_streaming_item(&thread.id, turn_id, &mut projection.message, item_status)
2565 .await?;
2566 self.close_streaming_item(&thread.id, turn_id, &mut projection.reasoning, item_status)
2567 .await?;
2568 let mut plan = projection.plan.take();
2569 self.close_streaming_item(
2570 &thread.id,
2571 turn_id,
2572 &mut plan,
2573 TurnItemLifecycleStatus::Completed,
2574 )
2575 .await?;
2576 let open_tools: Vec<TurnItemRecord> = projection
2577 .tools
2578 .into_values()
2579 .filter(|item| item.ended_at.is_none())
2580 .collect();
2581 for item in open_tools {
2582 let tool_status = if status == RuntimeTurnStatus::Failed {
2583 TurnItemLifecycleStatus::Failed
2584 } else {
2585 TurnItemLifecycleStatus::Interrupted
2586 };
2587 let mut slot = Some(item);
2588 self.close_streaming_item(&thread.id, turn_id, &mut slot, tool_status)
2589 .await?;
2590 }
2591
2592 let lock = self.projection_lock(&thread.id);
2593 let boundary = lock.lock().await;
2594 let store = self.store.clone();
2595 let settled_turn = turn_id.to_string();
2596 let settled_thread = thread.id.clone();
2597 let title = projection.title.take();
2598 let (turn, thread_update) = tokio::task::spawn_blocking(move || -> Result<_> {
2599 let now = Utc::now();
2600 let turn = {
2601 let _turn_mutation = store.turn_mutation.lock();
2602 let mut turn = store.load_turn(&settled_turn)?;
2603 if turn.status.is_active_work() {
2604 turn.status = status;
2605 turn.error = error;
2606 turn.ended_at = Some(now);
2607 turn.duration_ms = turn.started_at.map(|started| {
2608 now.signed_duration_since(started).num_milliseconds().max(0) as u64
2609 });
2610 store.save_turn(&turn)?;
2611 }
2612 turn
2613 };
2614 let thread_update = (|| {
2615 let _thread_mutation = store.thread_mutation.lock();
2616 let mut current = store.load_thread(&settled_thread)?;
2617 current.updated_at = now;
2618 if current.title.is_none() {
2619 current.title = title;
2620 }
2621 store.save_thread(&current)
2622 })();
2623 Ok((turn, thread_update))
2624 })
2625 .await
2626 .context("external turn settlement worker failed")??;
2627 let completion = self.emit_turn_completed_if_missing(&turn, false).await;
2628 if completion.is_err() {
2629 self.queue_recovery_receipt(RecoveredTurnReceipt {
2630 turn,
2631 unresolved_dynamic_tools: Vec::new(),
2632 });
2633 }
2634 let removed = {
2635 let mut active = self.active.lock().await;
2636 match active.external.get_mut(&thread.id) {
2637 Some(state)
2638 if state
2639 .active_turn
2640 .as_ref()
2641 .is_some_and(|live| live.turn_id == turn_id) =>
2642 {
2643 if outcome.is_err() || projection_failed {
2644 active.external.remove(&thread.id)
2645 } else {
2646 state.active_turn = None;
2647 None
2648 }
2649 }
2650 _ => None,
2651 }
2652 };
2653 self.turn_settled.notify_waiters();
2654 drop(boundary);
2655 let stopped = removed.is_some();
2656 if let Some(state) = removed {
2657 let _ = tokio::task::spawn_blocking(move || state.session.stop_blocking()).await;
2658 }
2659 completion?;
2660 if stopped {
2661 let reason = match &outcome {
2662 Err(reason) => label(Some(&Value::String(reason.clone())), "the agent exited"),
2663 Ok(_) => "the agent exited".to_string(),
2664 };
2665 self.emit_event(
2666 &thread.id,
2667 None,
2668 None,
2669 "executor.stopped",
2670 json!({ "reason": reason }),
2671 )
2672 .await?;
2673 }
2674 thread_update
2675 }
2676
2677 pub(super) async fn interrupt_external_turn_in_workspace(
2678 &self,
2679 thread_id: &str,
2680 turn_id: &str,
2681 expected_workspace: Option<&std::path::Path>,
2682 ) -> Result<TurnRecord> {
2683 let session = {
2684 let mut active = self.active.lock().await;
2685 if expected_workspace.is_some() {
2686 let _thread_mutation = self.store.thread_mutation.lock();
2687 super::require_thread_workspace(
2688 &self.store.load_thread(thread_id)?,
2689 expected_workspace,
2690 )?;
2691 }
2692 let Some(state) = active.external.get_mut(thread_id) else {
2693 bail!("Thread is not loaded");
2694 };
2695 let Some(active_turn) = state.active_turn.as_mut() else {
2696 bail!("No active turn on thread {thread_id}");
2697 };
2698 if active_turn.turn_id != turn_id {
2699 bail!("Turn {turn_id} is not active on thread {thread_id}");
2700 }
2701 active_turn.interrupt_requested = true;
2702 active_turn.cancel.cancel();
2703 self.pending_approvals.lock().retain(|_, entry| {
2704 entry.thread_id != thread_id || entry.request.turn_id != turn_id
2705 });
2706 Arc::clone(&state.session)
2707 };
2708 let canceller = session.canceller.clone();
2709 let active = Arc::clone(&self.active);
2710 let watched_thread = thread_id.to_string();
2711 let watched_turn = turn_id.to_string();
2712 tokio::spawn(async move {
2713 tokio::time::sleep(CANCEL_GRACE).await;
2714 let still_running = {
2715 let mut active = active.lock().await;
2716 active
2717 .external
2718 .get_mut(&watched_thread)
2719 .and_then(|state| state.active_turn.as_mut())
2720 .filter(|turn| turn.turn_id == watched_turn)
2721 .map(|turn| turn.killed = true)
2722 .is_some()
2723 };
2724 if still_running {
2725 let _ = tokio::task::spawn_blocking(move || {
2726 if let Some(host) = &session.host {
2727 let _ = host.stop(&session.worker_id);
2728 }
2729 })
2730 .await;
2731 }
2732 });
2733 if let Some(canceller) = canceller {
2734 match tokio::time::timeout(
2735 CANCEL_GRACE,
2736 tokio::task::spawn_blocking(move || canceller.cancel()),
2737 )
2738 .await
2739 {
2740 Ok(Ok(Ok(()))) => {}
2741 Ok(Ok(Err(error))) => {
2742 tracing::warn!(thread_id, %error, "sending session/cancel failed")
2743 }
2744 Ok(Err(error)) => {
2745 tracing::warn!(thread_id, %error, "external agent cancel worker failed")
2746 }
2747 Err(_) => tracing::warn!(thread_id, "sending session/cancel timed out"),
2748 }
2749 }
2750 self.emit_event(
2751 thread_id,
2752 Some(turn_id),
2753 None,
2754 "turn.interrupt_requested",
2755 json!({ "thread_id": thread_id, "turn_id": turn_id }),
2756 )
2757 .await?;
2758 let store = self.store.clone();
2759 let turn_id = turn_id.to_string();
2760 tokio::task::spawn_blocking(move || store.load_turn(&turn_id))
2761 .await
2762 .context("external interrupted turn read failed")?
2763 }
2764
2765 pub(in crate::runtime_threads) fn register_agent_approval(
2766 &self,
2767 thread_id: &str,
2768 mut request: PendingApprovalRequest,
2769 ) -> (
2770 String,
2771 oneshot::Receiver<ExternalApprovalDecision>,
2772 watch::Sender<Option<bool>>,
2773 ) {
2774 let mut pending = self.pending_approvals.lock();
2775 loop {
2776 let id = Self::mint_approval_id();
2777 if let std::collections::hash_map::Entry::Vacant(entry) = pending.entry(id.clone()) {
2778 request.id = id.clone();
2779 let (tx, rx) = oneshot::channel();
2780 let (settled_tx, settled_rx) = watch::channel(None);
2781 entry.insert(PendingApprovalEntry {
2782 thread_id: thread_id.to_string(),
2783 request,
2784 sender: Some(tx),
2785 publication: None,
2786 proposed: None,
2787 responder: None,
2788 agent_settled: Some(settled_rx),
2789 owner_only: false,
2790 standing_rules: None,
2791 });
2792 return (id, rx, settled_tx);
2793 }
2794 }
2795 }
2796 }
2797
2798 pub(super) async fn await_agent_settlement(
2799 mut settled: watch::Receiver<Option<bool>>,
2800 ) -> Result<bool> {
2801 let result = tokio::time::timeout(APPROVAL_SETTLE_TIMEOUT, async {
2802 settled
2803 .wait_for(|outcome| outcome.is_some())
2804 .await
2805 .map(|outcome| *outcome)
2806 })
2807 .await;
2808 match result {
2809 Ok(Ok(Some(true))) => Ok(true),
2810 Ok(Ok(Some(false))) => bail!("the agent's approval decision could not be recorded"),
2811 Ok(Ok(None)) => Ok(false),
2812 Ok(Err(_)) => {
2813 bail!("the agent's approval settlement channel closed before a decision was recorded")
2814 }
2815 Err(_) => bail!("the agent's approval decision was not recorded in time"),
2816 }
2817 }
2818
2819 #[cfg(test)]
2820 mod tests {
2821 use super::*;
2822 use crate::external_agents::acp::SessionOffer;
2823
2824 fn mode_control(current: &str, modes: &[&str]) -> Option<Control> {
2825 let available: Vec<Value> = modes
2826 .iter()
2827 .map(|id| json!({"id": id, "name": id}))
2828 .collect();
2829 SessionOffer::from_session_result(
2830 &json!({"modes": {"currentModeId": current, "availableModes": available}}),
2831 )
2832 .control("mode")
2833 .cloned()
2834 }
2835
2836 #[test]
2837 fn ask_posture_picks_an_agent_mode_that_cannot_edit_unasked() {
2838 let ask = posture_modes(ApprovalMode::Suggest, false).unwrap();
2839 let devin = mode_control("accept-edits", &["accept-edits", "ask"]);
2840 assert_eq!(posture_choice(devin.as_ref(), &ask).as_deref(), Some("ask"));
2841 let claude = mode_control("acceptEdits", &["default", "acceptEdits", "plan"]);
2842 assert_eq!(
2843 posture_choice(claude.as_ref(), &ask).as_deref(),
2844 Some("default")
2845 );
2846 let codex = mode_control("auto", &["read-only", "auto", "full-access"]);
2847 assert_eq!(
2848 posture_choice(codex.as_ref(), &ask).as_deref(),
2849 Some("read-only")
2850 );
2851 let plan = posture_modes(ApprovalMode::Suggest, true).unwrap();
2852 assert_eq!(
2853 posture_choice(claude.as_ref(), &plan).as_deref(),
2854 Some("plan")
2855 );
2856 let yolo = mode_control("yolo", &["yolo"]);
2857 assert_eq!(posture_choice(yolo.as_ref(), &ask), None);
2858 assert_eq!(posture_choice(None, &ask), None);
2859 assert!(posture_modes(ApprovalMode::Bypass, false).is_none());
2860 }
2861
2862 #[test]
2863 fn push_bounded_keeps_the_marker_inside_the_cap() {
2864 let mut detail = String::new();
2865 push_bounded(&mut detail, &"x".repeat(MAX_DETAIL_BYTES * 2));
2866 assert!(detail.len() <= MAX_DETAIL_BYTES, "{}", detail.len());
2867 assert!(detail.ends_with(TRUNCATED_MARKER));
2868 }
2869
2870 #[test]
2871 fn push_bounded_truncates_near_cap_without_exceeding_limit() {
2872 let mut detail = "a".repeat(MAX_DETAIL_BYTES - 1);
2873 push_bounded(&mut detail, "中文补充内容");
2874 assert!(detail.len() <= MAX_DETAIL_BYTES, "{}", detail.len());
2875 assert!(detail.ends_with(TRUNCATED_MARKER));
2876
2877 let mut multibyte_detail = "中".repeat((MAX_DETAIL_BYTES - 4) / 3);
2878 assert!(multibyte_detail.len() > MAX_DETAIL_BYTES - TRUNCATED_MARKER.len());
2879 assert!(multibyte_detail.len() < MAX_DETAIL_BYTES);
2880 push_bounded(&mut multibyte_detail, "更多文本");
2881 assert!(
2882 multibyte_detail.len() <= MAX_DETAIL_BYTES,
2883 "{}",
2884 multibyte_detail.len()
2885 );
2886 assert!(multibyte_detail.ends_with(TRUNCATED_MARKER));
2887 }
2888
2889 #[test]
2890 fn push_bounded_multibyte_truncation_stays_idempotent() {
2891 let mut detail = String::new();
2892 push_bounded(&mut detail, &"中".repeat(MAX_DETAIL_BYTES));
2893 assert!(detail.len() <= MAX_DETAIL_BYTES, "{}", detail.len());
2894 assert!(detail.ends_with(TRUNCATED_MARKER));
2895 let after_first = detail.clone();
2896
2897 push_bounded(&mut detail, "follow-up update");
2898 push_bounded(&mut detail, "!");
2899 assert_eq!(detail, after_first);
2900 assert_eq!(detail.matches(TRUNCATED_MARKER).count(), 1);
2901 }
2902
2903 #[test]
2904 fn push_bounded_delta_handles_multibyte_truncation_near_cap_without_panic() {
2905 let max_body = MAX_DETAIL_BYTES - TRUNCATED_MARKER.len();
2906 let mut detail = format!("{}🚀{}", "a".repeat(max_body - 3), "b".repeat(10));
2907 assert!(detail.len() > max_body);
2908 assert!(detail.len() < MAX_DETAIL_BYTES);
2909 let before = detail.len();
2910
2911 let delta = push_bounded_delta(&mut detail, "overflow text");
2912 assert_eq!(delta.as_deref(), Some(TRUNCATED_MARKER));
2913 assert!(detail.len() < before);
2914 assert!(detail.len() <= MAX_DETAIL_BYTES);
2915 assert!(detail.ends_with(TRUNCATED_MARKER));
2916 assert_eq!(push_bounded_delta(&mut detail, "more"), None);
2917
2918 let mut near_cap = "a".repeat(MAX_DETAIL_BYTES - 4);
2919 assert!(near_cap.len() > max_body);
2920 assert_eq!(
2921 push_bounded_delta(&mut near_cap, "hi").as_deref(),
2922 Some("hi")
2923 );
2924 assert_eq!(near_cap.len(), MAX_DETAIL_BYTES - 2);
2925 assert_eq!(
2926 push_bounded_delta(&mut near_cap, "overflow").as_deref(),
2927 Some(TRUNCATED_MARKER)
2928 );
2929 assert!(near_cap.ends_with(TRUNCATED_MARKER));
2930 }
2931
2932 #[tokio::test]
2933 async fn await_agent_settlement_errors_when_channel_closes_without_outcome() {
2934 let (tx, rx) = watch::channel(None);
2935 drop(tx);
2936 let error = await_agent_settlement(rx)
2937 .await
2938 .expect_err("closed settlement channel must fail")
2939 .to_string();
2940 assert!(error.contains("closed"), "{error}");
2941
2942 let (tx, rx) = watch::channel(Some(true));
2943 assert!(await_agent_settlement(rx).await.expect("settled true"));
2944 drop(tx);
2945
2946 let (tx, rx) = watch::channel(Some(false));
2947 let failed = await_agent_settlement(rx)
2948 .await
2949 .expect_err("settled false must fail")
2950 .to_string();
2951 assert!(failed.contains("could not be recorded"), "{failed}");
2952 drop(tx);
2953 }
2954
2955 #[test]
2956 fn bounded_json_omits_oversized_input() {
2957 let big = serde_json::json!({ "text": "y".repeat(MAX_INPUT_BYTES * 4) });
2958 assert_eq!(
2959 bounded_json(Some(&big)),
2960 Some(Value::String(format!(
2961 "[more than {MAX_INPUT_BYTES} bytes of tool input omitted]"
2962 )))
2963 );
2964 let small = serde_json::json!({ "text": "ok" });
2965 assert_eq!(bounded_json(Some(&small)), Some(small.clone()));
2966 }
2967
2968 #[test]
2969 fn bounded_json_drops_a_search_consent_marker_from_agent_input() {
2970 let forged = serde_json::json!({
2971 "query": "rust",
2972 "third_party_search": {"version": 1, "selected": "any", "providers": []}
2973 });
2974 assert_eq!(
2975 bounded_json(Some(&forged)),
2976 Some(serde_json::json!({ "query": "rust" }))
2977 );
2978 }
2979
2980 #[test]
2981 fn labels_and_text_drop_bidi_and_format_characters() {
2982 let value = Value::String("safe\u{202e}txt.exe\u{200b}".to_string());
2983 assert_eq!(label(Some(&value), "agent"), "safetxt.exe");
2984 assert_eq!(clean_text("a\u{2066}b\nc"), "ab\nc");
2985 }
2986 }
2987
2987 lines RUST