rho-coding-agent 1.26.0

A lightweight agent harness inspired by Pi
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
use std::{path::PathBuf, sync::Arc};

use {
    crate::agent::{AgentCapabilities, AgentDefinition, ToolCapability},
    crate::cli::OutputFormat,
    crate::config::Config,
    crate::diagnostics::RuntimeDiagnostics,
    crate::herdr::HerdrReporter,
    crate::subagent::{self, RunState, RunStatus},
    rho_tools::cancellation::RunCancellation,
};

use super::{
    agent_binding::{AgentBinder, AgentInvocation, AgentRole, CapacityClass},
    automation::{self, RunReporter},
    subagent_host_input::{SubagentHostInputBridge, SubagentHostInputResponder},
};

/// Default total concurrency across all delegated agents (Rho + Claude).
const DEFAULT_TOTAL_CONCURRENCY: usize = 4;
/// Default Claude-specific concurrency. Always nested under the total pool so
/// Claude fan-out cannot exceed this even when Rho capacity remains.
const DEFAULT_CLAUDE_CONCURRENCY: usize = 2;

#[derive(Clone)]
pub(crate) struct AgentExecutor {
    config: Arc<std::sync::RwLock<Config>>,
    config_path: PathBuf,
    cwd: PathBuf,
    /// Global permit pool for every delegated agent (Rho and Claude).
    ///
    /// `RHO_AGENT_CONCURRENCY` overrides this total. Claude runs also take a
    /// permit from [`Self::claude_permits`] (Claude pool first, then global) so
    /// one env override never opens a 2N fan-out window and queued Claude work
    /// cannot starve Rho of spare global capacity.
    /// `RHO_CLAUDE_AGENT_CONCURRENCY` overrides the Claude nested cap and is
    /// clamped to the total.
    total_permits: Arc<tokio::sync::Semaphore>,
    /// Claude-only nested pool. Sized to min(total, Claude default/override).
    /// Acquired before the global pool for Claude runs.
    claude_permits: Arc<tokio::sync::Semaphore>,
    host_input: SubagentHostInputBridge,
    approval_session: Option<rho_sdk::ApprovalSession>,
}

pub(crate) struct AgentLaunchRequest {
    pub(crate) definition: Arc<AgentDefinition>,
    pub(crate) prompt: String,
    pub(crate) run_id: String,
    pub(crate) background: bool,
    pub(crate) parent_session_id: Option<rho_sdk::SessionId>,
    pub(crate) output_file: PathBuf,
}

/// Launch request whose agent definition was resolved and frozen at plan time.
pub(crate) struct FrozenAgentLaunchRequest {
    pub(crate) agent: crate::workflow::ResolvedAgent,
    pub(crate) prompt: String,
    pub(crate) run_id: String,
    pub(crate) output_file: PathBuf,
    pub(crate) hook_host_labels: rho_sdk::hooks::HookHostLabels,
}

#[derive(Clone)]
pub(crate) struct AgentRunHandle {
    cancellation: RunCancellation,
    status: tokio::sync::watch::Receiver<RunStatus>,
    completion: tokio::sync::watch::Receiver<bool>,
}

impl AgentRunHandle {
    pub(crate) fn cancel(&self) {
        self.cancellation.cancel();
    }

    pub(crate) fn status(&self) -> RunStatus {
        self.status.borrow().clone()
    }

    pub(crate) fn is_complete(&self) -> bool {
        *self.completion.borrow()
    }

    pub(crate) async fn wait(&mut self) -> RunStatus {
        while !*self.completion.borrow() {
            if self.completion.changed().await.is_err() {
                break;
            }
        }
        self.status()
    }

    /// Clone of the live status watch used while the run is in flight.
    pub(crate) fn clone_status_watch(&self) -> tokio::sync::watch::Receiver<RunStatus> {
        self.status.clone()
    }

    #[cfg(test)]
    pub(crate) fn completed_for_test(status: RunStatus) -> Self {
        let (_status_tx, status_rx) = tokio::sync::watch::channel(status);
        let (_completion_tx, completion_rx) = tokio::sync::watch::channel(true);
        Self {
            cancellation: RunCancellation::new(),
            status: status_rx,
            completion: completion_rx,
        }
    }
}

impl AgentExecutor {
    pub(crate) fn new(
        config: Config,
        config_path: PathBuf,
        cwd: PathBuf,
        host_input: SubagentHostInputBridge,
    ) -> Self {
        let limits = concurrency_limits();
        Self {
            config: Arc::new(std::sync::RwLock::new(config)),
            config_path,
            cwd,
            total_permits: Arc::new(tokio::sync::Semaphore::new(limits.total)),
            claude_permits: Arc::new(tokio::sync::Semaphore::new(limits.claude)),
            host_input,
            approval_session: None,
        }
    }

    /// Routes workflow-agent capability requests through the workflow run's
    /// host and exact-request approval memory.
    pub(crate) fn with_approval_session(mut self, session: rho_sdk::ApprovalSession) -> Self {
        self.approval_session = Some(session);
        self
    }

    pub(crate) fn host_input(&self) -> &SubagentHostInputBridge {
        &self.host_input
    }

    /// Atomically updates the parent session's provider selection inherited by
    /// future **Rho** runtime delegated agents.
    ///
    /// Claude-cli agents never read this snapshot for spawn: binding copies
    /// Claude model/tools/inherit from the definition only, byte-for-byte.
    pub(crate) fn update_selection(
        &self,
        provider: &str,
        model: &str,
        reasoning: rho_sdk::ReasoningLevel,
        auth: &str,
    ) {
        let mut config = self.config.write().expect("delegated config lock");
        config.provider = provider.to_string();
        config.model = model.to_string();
        config.reasoning = reasoning;
        config.auth = auth.to_string();
    }

    pub(crate) fn update_permission_mode(&self, mode: crate::permission::PermissionMode) {
        self.config
            .write()
            .expect("delegated config lock")
            .permission_mode = mode;
    }

    #[cfg(test)]
    pub(crate) fn launch_permission_mode(&self) -> crate::permission::PermissionMode {
        self.config
            .read()
            .expect("delegated config lock")
            .permission_mode
    }

    pub(crate) fn spawn(&self, request: AgentLaunchRequest) -> anyhow::Result<AgentRunHandle> {
        let config = self.config.read().expect("delegated config lock").clone();
        let mut capabilities = AgentCapabilities::all_host_tools();
        // web_search is gated after bind against the agent provider/model.
        #[cfg(windows)]
        capabilities.remove(&ToolCapability::Bash);
        #[cfg(not(windows))]
        capabilities.remove(&ToolCapability::Powershell);
        // A foreground child runs inside the parent tool call, so waiting for
        // that parent to present a questionnaire would deadlock both runs.
        let questionnaire_available =
            request.background && request.parent_session_id.is_some() && self.host_input.is_bound();
        if !questionnaire_available {
            capabilities.remove(&ToolCapability::Questionnaire);
        }
        let bound = AgentBinder::bind(
            request.definition,
            AgentInvocation {
                role: AgentRole::Delegated,
                available_tools: capabilities,
            },
            &config,
        )?;

        self.spawn_bound(BoundLaunchRequest {
            bound,
            prompt: request.prompt,
            run_id: request.run_id,
            parent_session_id: request.parent_session_id,
            output_file: request.output_file,
            questionnaire_available,
            frozen_claude: None,
            hook_host_labels: rho_sdk::hooks::HookHostLabels::new(),
        })
    }

    /// Starts a workflow node from persisted launch metadata without looking up
    /// or rebinding an agent definition.
    pub(crate) fn spawn_frozen(
        &self,
        request: FrozenAgentLaunchRequest,
    ) -> anyhow::Result<AgentRunHandle> {
        let config = self.config.read().expect("delegated config lock").clone();
        let mut current_tools = AgentCapabilities::all_host_tools();
        #[cfg(windows)]
        current_tools.remove(&ToolCapability::Bash);
        #[cfg(not(windows))]
        current_tools.remove(&ToolCapability::Powershell);
        current_tools.remove(&ToolCapability::Questionnaire);
        let bound = AgentBinder::bind_frozen(&request.agent, &config, &current_tools)?;
        let frozen_claude = if request.agent.runtime == crate::workflow::AgentRuntime::ClaudeCli {
            let identity = request.agent.executable_identity.as_ref().ok_or_else(|| {
                anyhow::anyhow!("frozen Claude launch has no executable identity")
            })?;
            let verified_executable = crate::workflow::verify_executable_identity(identity)?;
            let script_path = crate::workflow::verified_handle_path(
                &verified_executable.executable.file,
                std::path::Path::new(&identity.file.canonical_path),
            )?;
            let mut arguments = request.agent.arguments;
            let executable = if let Some(interpreter) = &verified_executable.interpreter {
                let interpreter_path = crate::workflow::verified_handle_path(
                    &interpreter.file,
                    std::path::Path::new(&interpreter.identity.canonical_path),
                )?;
                let mut interpreter_arguments = verified_executable.interpreter_arguments.clone();
                interpreter_arguments.push(crate::paths::display(&script_path));
                interpreter_arguments.extend(arguments);
                arguments = interpreter_arguments;
                interpreter_path
            } else {
                script_path
            };
            Some(FrozenClaudeLaunch {
                executable,
                arguments,
                executable_identity: identity.clone(),
                _verified_executable: verified_executable,
            })
        } else {
            None
        };
        self.spawn_bound(BoundLaunchRequest {
            bound,
            prompt: request.prompt,
            run_id: request.run_id,
            parent_session_id: None,
            output_file: request.output_file,
            questionnaire_available: false,
            frozen_claude,
            hook_host_labels: request.hook_host_labels,
        })
    }

    fn spawn_bound(&self, request: BoundLaunchRequest) -> anyhow::Result<AgentRunHandle> {
        let BoundLaunchRequest {
            bound,
            prompt,
            run_id,
            parent_session_id,
            output_file,
            questionnaire_available,
            frozen_claude,
            hook_host_labels,
        } = request;

        let labels = bound.runtime().artifact_labels();
        let capacity_class = bound.runtime().capacity_class();

        let initial = RunStatus {
            state: RunState::Starting,
            agent_id: Some(bound.id().to_string()),
            agent_fingerprint: Some(bound.fingerprint().to_string()),
            provider: Some(labels.provider.clone()),
            model: Some(labels.model.clone()),
            parent_session_id: parent_session_id.as_ref().map(ToString::to_string),
            ..RunStatus::default()
        };
        // Executor owns the Starting boundary; sinks continue_from it.
        // Write Starting here so the handle can observe status before the task runs.
        subagent::initialize_status(&output_file, &initial)?;
        let (status_tx, status) = tokio::sync::watch::channel(initial);
        let (completion_tx, completion) = tokio::sync::watch::channel(false);
        let cancellation = RunCancellation::new();
        let task_cancellation = cancellation.clone();
        let config_path = self.config_path.clone();
        let cwd = self.cwd.clone();
        let host_input = self.host_input.clone();
        let persisted_output = output_file.clone();
        let total_permits = Arc::clone(&self.total_permits);
        let claude_permits = Arc::clone(&self.claude_permits);
        let approval_session = self.approval_session.clone();

        let task_status_tx = status_tx.clone();
        let task: tokio::task::JoinHandle<anyhow::Result<()>> = tokio::spawn(async move {
            // Acquire runtime-aware capacity before work starts. Claude runs
            // take Claude capacity first so queued Claude work cannot occupy
            // global permits while waiting on the nested pool; Rho takes only
            // the global pool. Dropping the guard returns every held permit.
            let Some(_runtime_permits) = acquire_runtime_permits(
                total_permits,
                claude_permits,
                capacity_class,
                &task_cancellation,
            )
            .await?
            else {
                let mut stopped = task_status_tx.borrow().clone();
                stopped.state = RunState::Stopped;
                stopped.last_activity = Some("cancelled before execution".into());
                task_status_tx.send_replace(stopped.clone());
                subagent::write_status(&output_file, &stopped)?;
                return Ok(());
            };

            let started_status = task_status_tx.borrow().clone();
            if let Some(mut session) = bound.clone().into_claude_session(
                prompt.clone(),
                output_file.clone(),
                cwd.clone(),
                task_cancellation.clone(),
                Some(task_status_tx.clone()),
                Some(started_status),
            ) {
                if let Some(frozen) = frozen_claude {
                    let expected_identity = frozen.executable_identity;
                    let verified_executable = frozen._verified_executable;
                    session.overrides.executable = Some(
                        crate::claude_runtime::executable::ClaudeExecutable::from_path(
                            frozen.executable,
                        ),
                    );
                    session.set_frozen_argv(frozen.arguments);
                    session.overrides.before_spawn = Some(Box::new(move |command| {
                        crate::workflow::verify_executable_identity(&expected_identity)
                            .map_err(std::io::Error::other)?;
                        let mut files = vec![&verified_executable.executable.file];
                        if let Some(interpreter) = &verified_executable.interpreter {
                            files.push(&interpreter.file);
                        }
                        crate::workflow::configure_handle_inheritance(command, &files)
                            .map_err(std::io::Error::other)
                    }));
                }
                return crate::claude_runtime::session::run_session(session).await;
            }

            let bound_config = bound
                .rho_config()
                .expect("non-Claude bound runtime is Rho")
                .clone();
            run_rho_agent(RhoAgentRun {
                bound,
                config: bound_config,
                config_path,
                cwd,
                prompt,
                output_file,
                run_id,
                parent_session_id,
                questionnaire_available,
                host_input,
                cancellation: task_cancellation,
                status_tx: task_status_tx,
                hook_host_labels,
                approval_session,
            })
            .await
        });

        let failure_status = status.clone();
        tokio::spawn(async move {
            let failure = match task.await {
                Ok(Ok(())) => None,
                Ok(Err(error)) => Some(format!("delegated agent failed: {error:#}")),
                Err(error) if error.is_panic() => Some("delegated agent task panicked".into()),
                Err(error) => Some(format!("delegated agent task failed to join: {error}")),
            };
            if let Some(error) = failure {
                let mut failed = failure_status.borrow().clone();
                if !failed.state.is_terminal() {
                    failed.state = RunState::Error;
                    failed.error = Some(error);
                    status_tx.send_replace(failed.clone());
                    let _ = subagent::write_status(&persisted_output, &failed);
                }
            }
            completion_tx.send_replace(true);
        });

        Ok(AgentRunHandle {
            cancellation,
            status,
            completion,
        })
    }
}

struct BoundLaunchRequest {
    bound: super::agent_binding::BoundAgent,
    prompt: String,
    run_id: String,
    parent_session_id: Option<rho_sdk::SessionId>,
    output_file: PathBuf,
    questionnaire_available: bool,
    frozen_claude: Option<FrozenClaudeLaunch>,
    hook_host_labels: rho_sdk::hooks::HookHostLabels,
}

struct FrozenClaudeLaunch {
    executable: PathBuf,
    arguments: Vec<String>,
    executable_identity: crate::workflow::ExecutableIdentity,
    // Keep descriptor-backed paths alive until the child has exited.
    _verified_executable: crate::workflow::VerifiedExecutable,
}

/// One delegated run on the Rho runtime, after binding and permit acquisition.
struct RhoAgentRun {
    bound: super::agent_binding::BoundAgent,
    config: Config,
    config_path: PathBuf,
    cwd: PathBuf,
    prompt: String,
    output_file: PathBuf,
    run_id: String,
    parent_session_id: Option<rho_sdk::SessionId>,
    questionnaire_available: bool,
    host_input: SubagentHostInputBridge,
    cancellation: RunCancellation,
    status_tx: tokio::sync::watch::Sender<RunStatus>,
    hook_host_labels: rho_sdk::hooks::HookHostLabels,
    approval_session: Option<rho_sdk::ApprovalSession>,
}

/// Drive a delegated run through Rho's own automation loop.
async fn run_rho_agent(run: RhoAgentRun) -> anyhow::Result<()> {
    let RhoAgentRun {
        bound,
        mut config,
        config_path,
        cwd,
        prompt,
        output_file,
        run_id,
        parent_session_id,
        questionnaire_available,
        host_input,
        cancellation,
        status_tx,
        hook_host_labels,
        approval_session,
    } = run;

    super::cli_config::prepare_model_metadata(
        &config,
        &crate::credential_store::AppCredentialStore,
        &super::cli_config::ProviderRefreshStatus::NotAttempted,
    )
    .await;
    super::cli_config::normalize_reasoning(&mut config);
    let diagnostics = RuntimeDiagnostics::new(&config);
    diagnostics.update_agent(bound.id().as_str(), &bound.fingerprint().to_string());
    let started_status = status_tx.borrow().clone();
    let mut reporter = RunReporter::continue_from(
        output_file,
        started_status,
        cwd.clone(),
        &prompt,
        /* stream_output */ false,
        Some(status_tx),
    )?;
    let agent_id = bound.id().to_string();
    let max_steps = std::num::NonZeroUsize::new(
        bound
            .step_limit()
            .try_into()
            .map_err(|_| anyhow::anyhow!("agent step limit does not fit this platform"))?,
    )
    .ok_or_else(|| anyhow::anyhow!("agent step limit must be positive"))?;
    let startup = automation::Startup {
        config: &config,
        config_path,
        cwd,
        no_system_prompt: false,
        no_tools: false,
        no_subagents: true,
        usage_purpose: "subagent",
        parent_session_id: parent_session_id.clone(),
        agent: bound,
        output_file: None,
        output: OutputFormat::Text,
        max_steps: Some(max_steps),
        timeout: None,
        diagnostics,
        herdr: HerdrReporter::default(),
        host_input: questionnaire_available.then(|| {
            Arc::new(SubagentHostInputResponder::new(
                run_id,
                agent_id,
                parent_session_id.expect("questionnaire bridge requires a parent session"),
                host_input,
            )) as Arc<dyn super::headless_run::HostInputResponder>
        }),
        approval_session,
        hook_host_labels,
    };
    let result =
        automation::run_session(prompt, &startup, Some(&mut reporter), Some(cancellation)).await;
    reporter.finish(&result);
    result.map(|_| ())
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ConcurrencyLimits {
    total: usize,
    claude: usize,
}

fn concurrency_limits() -> ConcurrencyLimits {
    concurrency_limits_from_env(
        std::env::var("RHO_AGENT_CONCURRENCY").ok().as_deref(),
        std::env::var("RHO_CLAUDE_AGENT_CONCURRENCY")
            .ok()
            .as_deref(),
    )
}

/// Parse concurrency env values without reading process environment.
///
/// Both values must be positive `usize` integers when present. Zero, empty,
/// non-numeric, and overflow values fall back to the matching default. The
/// Claude nested cap is always clamped to the resolved total so Claude fan-out
/// cannot exceed the global pool.
fn concurrency_limits_from_env(
    total_raw: Option<&str>,
    claude_raw: Option<&str>,
) -> ConcurrencyLimits {
    let total = parse_positive_concurrency(total_raw).unwrap_or(DEFAULT_TOTAL_CONCURRENCY);
    let claude_requested =
        parse_positive_concurrency(claude_raw).unwrap_or(DEFAULT_CLAUDE_CONCURRENCY);
    // Nested Claude pool never exceeds the global total, so overrides cannot
    // open total + Claude = 2N concurrent delegated runs.
    let claude = claude_requested.min(total);
    ConcurrencyLimits { total, claude }
}

fn parse_positive_concurrency(raw: Option<&str>) -> Option<usize> {
    raw.and_then(|value| value.parse().ok())
        .filter(|limit: &usize| *limit > 0)
}

/// Concurrency capacity held for the lifetime of one delegated run.
///
/// Dropping this value returns every acquired permit. Field drop order is not
/// load-bearing; each permit returns to its own semaphore independently.
struct RuntimePermits {
    _total: tokio::sync::OwnedSemaphorePermit,
    _claude: Option<tokio::sync::OwnedSemaphorePermit>,
}

/// Acquire concurrency for a delegated run in runtime-aware order.
///
/// - Rho: one global permit only.
/// - Claude: Claude nested permit first, then one global permit.
///
/// Claude-first ordering keeps queued Claude tasks off the global pool until
/// Claude capacity exists, so spare global slots stay available for Rho.
/// Cancellation at either wait stage returns `Ok(None)` and drops any permit
/// already held so capacity cannot leak. A closed semaphore surfaces as an
/// error rather than a silent cancel.
async fn acquire_runtime_permits(
    total_permits: Arc<tokio::sync::Semaphore>,
    claude_permits: Arc<tokio::sync::Semaphore>,
    capacity_class: CapacityClass,
    cancellation: &RunCancellation,
) -> anyhow::Result<Option<RuntimePermits>> {
    let claude = match capacity_class {
        CapacityClass::Claude => {
            let Some(permit) = acquire_permit_or_cancel(
                claude_permits,
                cancellation,
                "Claude agent concurrency pool closed before the run could start",
            )
            .await?
            else {
                return Ok(None);
            };
            Some(permit)
        }
        CapacityClass::Rho => None,
    };

    let Some(total) = acquire_permit_or_cancel(
        total_permits,
        cancellation,
        "agent concurrency pool closed before the run could start",
    )
    .await?
    else {
        // Drop any Claude permit acquired above before returning cancelled.
        return Ok(None);
    };

    Ok(Some(RuntimePermits {
        _total: total,
        _claude: claude,
    }))
}

async fn acquire_permit_or_cancel(
    permits: Arc<tokio::sync::Semaphore>,
    cancellation: &RunCancellation,
    closed_message: &str,
) -> anyhow::Result<Option<tokio::sync::OwnedSemaphorePermit>> {
    tokio::select! {
        biased;
        () = cancellation.cancelled() => Ok(None),
        permit = permits.acquire_owned() => {
            // Map a closed semaphore to a clear startup error. Dropping the
            // failed acquire path holds nothing, so no permit can leak here.
            let permit = permit.map_err(|_| anyhow::anyhow!("{closed_message}"))?;
            // Re-check after acquire wins the select so a cancel that arrived
            // in the same poll drops the permit via this None return.
            if cancellation.is_cancelled() {
                Ok(None)
            } else {
                Ok(Some(permit))
            }
        }
    }
}

#[cfg(test)]
#[path = "agent_executor_tests.rs"]
mod tests;