rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! The tools of rho's that a daemon session serves the agent that runs it
//! on another runtime, over the ACP connection or, for agy, which takes no
//! MCP server there, a stdio bridge
//! ([`crate::acp_runtime::agent_tools`]). Each call runs in the session as
//! the session's own tool call would: under its permission mode and its
//! hooks, with what needs approval and what a tool asks put to the person
//! as the session's input requests (see `acp_asks.rs`).
//!
//! The tools live with the session, not the turn, as a Rho session's do:
//! its subagents, processes and browser tabs outlive the turn that started
//! them, and an allow for the session holds for its later turns. Each turn
//! serves them from a tool host wired for the mode the turn runs in
//! ([`ServedTools::turn`]), and rewired when the agent leaves plan mode
//! mid-turn ([`TurnTools::leave_plan`]).
//!
//! The agent gets `questionnaire`, `process`, `agent` and `agents`,
//! `sessions` without recall (it compacts its own context), `workflow`,
//! `rho`, `skill`, the browser tools, the pull request links,
//! `fetch_content` and `get_search_content`, and `ui` where the session's
//! clients draw A2UI surfaces, as a Rho session gets it. It keeps its own
//! files, shell, web search and plan. What needs rho's own loop (`codemode`,
//! `tool_search`, plan exit, MCP reloads) stays out. What needs the daemon
//! to wake the idle session (`watch_pull_request`) is served only where its
//! client takes the turns the daemon starts (`idle_wake: turn`), as for a
//! Rho session: there the session also hears of the turns its `sessions`
//! calls start in other sessions (see `peer_wake`), and every description
//! that tells how results reach the agent promises the wake
//! ([`IdleDelivery`]).
//!
//! No tool grants the agent more than its definition does: what reaches
//! beyond the session is served only to a definition that gives the agent
//! the same reach ([`Reach`], `SERVED`). What runs any command or starts
//! agents or sessions that do (`process`, `agent`, `agents`, `sessions`,
//! `workflow`, the browser) needs commands: Claude's `Bash`, listed bare,
//! or agy's `run_command`; `get_search_content`, which reads what the web
//! gave, needs web reads: Claude's `WebFetch` or agy's `search_web`;
//! `fetch_content`, which also reads GitHub signed in with the session's
//! token and clones with `git`, needs both.
//!
//! Each call draws the card a Rho session draws for its call of the same
//! tool, in place of the agent's own (see `acp_tools/cards.rs`). The
//! session's A2UI surfaces are the served tools': a client's action on
//! one reaches the `ui` call waiting on it, and one no call waits on waits
//! for a turn to deliver it, as the results of the work the tools start do
//! (see `acp_background.rs`). The questions the session's subagents ask
//! are the session's input requests (see `child_questions.rs`).

use std::{collections::HashMap, ffi::OsString, path::PathBuf, sync::Arc};

use rho_sdk::{
    tool::{Tool, ToolInvocationSource},
    ApprovalRequestReceiver, ApprovalSession, SessionId, ToolHost, Workspace,
};
use tokio::sync::{mpsc, watch};

use super::{
    acp_background::{self, TurnDelivery, TurnMailbox},
    budget::ModelSlot,
    open::RunServices,
};
use crate::{
    acp_runtime::agent_tools::{AgentTools, McpToolNaming},
    added_dirs::AddedDirs,
    agent::{AgentCapabilities, AntigravityTool, ToolCapability},
    app::{
        agent_binding::{BoundRuntime, ExternalAgent},
        background_delivery::HeldNotices,
        peer_sessions::PeerInbox,
        policy::AppPolicy,
        sdk_config::WorkspaceOptions,
        session_assembly::{ApprovalInputs, SessionApproval},
        session_events::{runtime_model, LinkSources},
        session_runtime::{ApprovalPolicy, ModeMove, QuestionSupport, SameMode, SessionPermission},
        subagent_host_input::{SubagentHostInputBridge, SubagentHostInputRequest},
        subagent_pool::SubagentPool,
        workflow_cli::workflow_tool_service,
    },
    config::Config,
    diagnostics::RuntimeDiagnostics,
    hooks::HookPipeline,
    permission::PermissionMode,
    prompt::agent_session::ServedToolGuide,
    session::{Session as StoredSession, SessionPersistence},
    session_environment::SessionEnvironment,
    tools::{
        sdk_registry::{AppToolSet, DelegationConfig, IdleDelivery, ToolCaller, ToolSetOptions},
        ui::SurfaceHost,
        workflow_tracker::WorkflowRunTracker,
    },
};

mod calls;
mod cards;

pub(super) use calls::{ServedApproval, ServedAsk, ServedQuestion};
use calls::{ToolsByName, TurnCalls, TurnHost};
use cards::CardScope;

/// What a definition's own tools let its agent reach beyond the session,
/// which bounds what rho serves it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Reach {
    /// Any command: Claude's bare `Bash`, agy's `run_command`.
    Commands,
    /// What the web gives: Claude's bare `WebFetch`, agy's `search_web`.
    WebReads,
}

/// The capabilities whose tools the agent is served, as far as the
/// session's config leaves them, each with the reach a definition must
/// grant for its agent to get them: none for a tool that only reaches the
/// person or reads rho's own state and the skills rho lists.
const SERVED: [(ToolCapability, &[Reach]); 13] = [
    (ToolCapability::Questionnaire, &[]),
    (ToolCapability::Ui, &[]),
    (ToolCapability::Rho, &[]),
    (ToolCapability::Skill, &[]),
    (ToolCapability::PullRequests, &[]),
    // They run any command, or start agents or sessions that do.
    (ToolCapability::Process, &[Reach::Commands]),
    (ToolCapability::Agent, &[Reach::Commands]),
    (ToolCapability::Agents, &[Reach::Commands]),
    (ToolCapability::Sessions, &[Reach::Commands]),
    (ToolCapability::Workflow, &[Reach::Commands]),
    (ToolCapability::Browser, &[Reach::Commands]),
    // It reads what the web gave.
    (ToolCapability::GetSearchContent, &[Reach::WebReads]),
    // It reads the web, and GitHub signed in with the session's token,
    // cloning with `git`: what `gh` and `git` do through a shell.
    (
        ToolCapability::FetchContent,
        &[Reach::Commands, Reach::WebReads],
    ),
];

/// The reach of a Claude definition with `tools`. A grant counts only
/// bare: `Bash(git *)` runs some commands, not any.
fn claude_reach(tools: &[String]) -> Vec<Reach> {
    let granted = |grant: &str| tools.iter().any(|tool| tool == grant);
    [("Bash", Reach::Commands), ("WebFetch", Reach::WebReads)]
        .into_iter()
        .filter(|(grant, _)| granted(grant))
        .map(|(_, reach)| reach)
        .collect()
}

/// The reach of an Antigravity definition with `tools`.
fn antigravity_reach(tools: &[AntigravityTool]) -> Vec<Reach> {
    [
        (AntigravityTool::RunCommand, Reach::Commands),
        (AntigravityTool::SearchWeb, Reach::WebReads),
    ]
    .into_iter()
    .filter(|(tool, _)| tools.contains(tool))
    .map(|(_, reach)| reach)
    .collect()
}

/// Whether a session's clients draw A2UI surfaces, which `ui` shows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SurfaceSupport {
    Available,
    Unavailable,
}

/// What the agent of a definition that grants `reach` is served of
/// `available`, the host tools the session's config leaves it, on clients
/// that show `questions` and draw `surfaces` or not: no wider grant than
/// its definition's.
fn served_capabilities(
    available: &AgentCapabilities,
    questions: QuestionSupport,
    surfaces: SurfaceSupport,
    reach: &[Reach],
) -> AgentCapabilities {
    AgentCapabilities::new(
        SERVED
            .into_iter()
            .filter(|(_, needs)| needs.iter().all(|need| reach.contains(need)))
            .map(|(capability, _)| capability)
            .filter(|capability| available.contains(capability))
            .filter(|capability| match questions {
                QuestionSupport::Available => true,
                // A client that shows no questions gets no tool that asks
                // them.
                QuestionSupport::Unavailable => *capability != ToolCapability::Questionnaire,
            })
            .filter(|capability| match surfaces {
                SurfaceSupport::Available => true,
                // Clients that draw no surfaces get no `ui`, as in a Rho
                // session.
                SurfaceSupport::Unavailable => *capability != ToolCapability::Ui,
            })
            .collect(),
    )
}

/// What a session's served tools are built from as it opens.
pub(super) struct ToolsSetup<'a> {
    pub(super) config: Config,
    pub(super) config_path: PathBuf,
    pub(super) environment: SessionEnvironment,
    /// Where the delegated agents take capacity: the session's pool.
    pub(super) subagent_pool: SubagentPool,
    pub(super) services: RunServices<'a>,
    /// The host tools the session's config leaves it.
    pub(super) available: AgentCapabilities,
    pub(super) questions: QuestionSupport,
    /// The session's A2UI surfaces, when its clients draw them.
    pub(super) surfaces: Option<SurfaceHost>,
    /// Whether the daemon wakes the idle session for its results (see
    /// `acp_background::idle_delivery`).
    pub(super) idle: IdleDelivery,
    /// The session's slot in the agent budget, which each of the agent's
    /// requests to the tools takes back for a turn that lent it before the
    /// request's answer goes back (see `budget`), and whose activity the
    /// tools count (see `agent_activity`).
    pub(super) model_slot: Arc<ModelSlot>,
}

impl ToolsSetup<'_> {
    /// The tools session `id`, saved as `file`, serves `agent`.
    pub(super) fn serve(
        self,
        id: &SessionId,
        file: &StoredSession,
        agent: &ExternalAgent,
    ) -> Option<ServedTools> {
        let (reach, client) = match agent.agent().runtime() {
            BoundRuntime::ClaudeCli { tools, .. } => (claude_reach(tools), McpClient::ClaudeCode),
            // Over the stdio bridge: agy takes no MCP server over its
            // connection.
            BoundRuntime::Antigravity { tools, .. } => {
                (antigravity_reach(tools), McpClient::Antigravity)
            }
            // Rho's loop serves its own tools.
            BoundRuntime::Rho { .. } => return None,
        };
        let identity = agent.agent().artifact_identity();
        let Self {
            config,
            config_path,
            environment,
            subagent_pool,
            services,
            available,
            questions,
            surfaces,
            idle,
            model_slot,
        } = self;
        let cwd = file.cwd().to_path_buf();
        let surface_support = match surfaces {
            Some(_) => SurfaceSupport::Available,
            None => SurfaceSupport::Unavailable,
        };
        let capabilities = served_capabilities(&available, questions, surface_support, &reach);
        // What the `rho` tool reports the session running on.
        let diagnostics = RuntimeDiagnostics::new(&config);
        diagnostics.update_identity(
            &identity.provider,
            runtime_model(identity.model.as_deref()),
            config.reasoning,
        );
        diagnostics.update_agent(&identity.agent_id, &identity.agent_fingerprint);
        // The session's hooks gate and hear the calls, as a Rho session's.
        let hooks = crate::hooks::start_for_cwd(&cwd, environment.clone());
        if let Some(hooks) = &hooks {
            diagnostics.attach_hooks(hooks);
        }
        let tracker = WorkflowRunTracker::new();
        let options = ToolSetOptions::new(capabilities)
            .caller(ToolCaller::ExternalAgent(idle))
            .environment(environment.clone())
            .surfaces(surfaces)
            .pull_requests(Some(services.pull_requests.inbox(id, &cwd)))
            .browser(crate::browser::Browsers::session(services.browsers, id))
            .workflow_tracker(tracker.clone())
            .delegation(DelegationConfig::new(
                cwd.clone(),
                config_path.clone(),
                /*catalog*/ None,
                subagent_pool.clone(),
            ))
            .workflow(workflow_tool_service(
                cwd.clone(),
                Some(config_path),
                tracker,
                subagent_pool,
                environment.clone(),
            ));
        let set = AppToolSet::new(&config, diagnostics, options);
        set.bind_session_search(id.as_str());
        // Only a session the daemon wakes hears of the turns it starts in
        // other sessions, as a Rho session (see `peer_wake`).
        let peers = match idle {
            IdleDelivery::WakeTurn => Some(PeerInbox::default()),
            IdleDelivery::NextPrompt => None,
        };
        if let Some(inbox) = &peers {
            set.bind_peer_sessions(inbox.clone());
        }
        if let Some(manager) = set.subagents() {
            manager.bind_parent_session(id.to_string(), Some(file), SessionPersistence::Saved);
        }
        // The session asks a person its subagents' questions, as a Rho
        // session does, when its clients show questions.
        let child_questions = match (questions, set.subagents()) {
            (QuestionSupport::Available, Some(manager)) => {
                let (sender, receiver) = SubagentHostInputBridge::queue();
                manager.bind_host_input_to(sender);
                Some(receiver)
            }
            (QuestionSupport::Unavailable, _) | (QuestionSupport::Available, None) => None,
        };
        set.workflow_tracker().bind_parent_session(id.to_string());
        let served: Vec<Arc<dyn Tool>> = set.tools().to_vec();
        let listed: Arc<[rmcp::model::Tool]> = served.iter().map(listed).collect();
        // A description past what the agent keeps reaches the model cut;
        // the `agent` tool's lists the user's agents, which can run past it.
        let limit = client.description_limit();
        for tool in listed.iter() {
            let chars = tool
                .description
                .as_deref()
                .map_or(0, |text| text.chars().count());
            if chars > limit {
                tracing::warn!(
                    session = %id,
                    tool = %tool.name,
                    chars,
                    limit,
                    "a served tool's description is longer than the agent is known to keep; the rest may be cut"
                );
            }
        }
        let by_name: HashMap<String, Arc<dyn Tool>> = served
            .iter()
            .map(|tool| (tool.spec().name, Arc::clone(tool)))
            .collect();
        let workspace = WorkspaceOptions { root: cwd.clone() }
            .build_workspace(&AddedDirs::default())
            .map_err(|error| format!("could not open the session's workspace: {error}"));
        let cards = CardScope {
            cwd: cwd.clone(),
            links: LinkSources::new(set.processes().cloned(), set.subagents().cloned()),
        };
        Some(ServedTools {
            cards,
            set,
            served,
            listed,
            by_name: Arc::new(by_name),
            session: id.clone(),
            workspace,
            cwd,
            config,
            environment,
            hooks,
            wired: None,
            held: None,
            model_slot,
            child_questions,
            idle,
            peers,
            client,
        })
    }
}

/// The longest MCP tool description Claude Code keeps whole; it cuts the
/// rest. Receipt: the Claude Agent SDK bundled with claude-agent-acp
/// 0.114.0 (`@anthropic-ai/claude-agent-sdk-linux-x64/claude`) caps a
/// description at `Q3r = 4096` characters by default, `Z3r = 16384` for a
/// tool its tool search defers (`Jle(deferred)`), unless
/// `CLAUDE_CODE_MAX_MCP_DESCRIPTION_LENGTH` says otherwise. Whether a tool
/// is deferred is Claude's choice, so every served tool fits the default.
pub(super) const CLAUDE_MCP_DESCRIPTION_LIMIT: usize = 4096;

/// The longest MCP tool description agy is known to keep whole: no cap,
/// as far as measured. Receipt: agy 1.5.21 (ACP server 1.5.21) handed its
/// model a stdio server's 20,000-character description whole, the model
/// quoting the code at its end. A tripwire for a description past what was
/// seen, not a cut agy makes.
const ANTIGRAVITY_MCP_DESCRIPTION_KEPT: usize = 20_000;

/// The MCP client of the agent's runtime, which names the served tools
/// and keeps as much of their descriptions as it does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum McpClient {
    ClaudeCode,
    Antigravity,
}

impl McpClient {
    /// How the agent names the served tools.
    fn naming(self) -> McpToolNaming {
        match self {
            Self::ClaudeCode => crate::claude_runtime::MCP_TOOL_NAMING,
            Self::Antigravity => crate::antigravity_runtime::policy::MCP_TOOL_NAMING,
        }
    }

    /// The longest description the agent is known to keep whole.
    fn description_limit(self) -> usize {
        match self {
            Self::ClaudeCode => CLAUDE_MCP_DESCRIPTION_LIMIT,
            Self::Antigravity => ANTIGRAVITY_MCP_DESCRIPTION_KEPT,
        }
    }
}

/// `tool` as an MCP server lists it.
fn listed(tool: &Arc<dyn Tool>) -> rmcp::model::Tool {
    let spec = tool.spec();
    let schema = match spec.input_schema {
        serde_json::Value::Object(schema) => schema,
        _ => serde_json::Map::new(),
    };
    rmcp::model::Tool::new(spec.name, spec.description, schema)
}

/// What a turn's run takes of the served tools' background work (see
/// [`ServedTools::deliver_into_turn`]): the turn's side of its delivery,
/// and the run's.
pub(super) type TurnBackground = (TurnDelivery, TurnMailbox);

/// The tools a session serves its agent, for as long as it is loaded.
pub(super) struct ServedTools {
    /// Owns the tools and what they started.
    set: AppToolSet,
    served: Vec<Arc<dyn Tool>>,
    listed: Arc<[rmcp::model::Tool]>,
    by_name: ToolsByName,
    session: SessionId,
    cwd: PathBuf,
    /// What its calls' cards draw with.
    cards: CardScope,
    /// The workspace calls run in, or why the session has none.
    workspace: Result<Workspace, String>,
    /// The session's config, whatever mode it names.
    config: Config,
    environment: SessionEnvironment,
    /// The session's hooks, if it has any.
    hooks: Option<HookPipeline>,
    /// The approvals and grants of the mode the calls last ran in; none
    /// before the first turn.
    wired: Option<Wired>,
    /// The children's notices the last turn left undelivered, for the next
    /// (see `acp_background`).
    held: Option<HeldNotices>,
    /// The session's slot in the agent budget (see `budget`), whose
    /// activity counts the calls running, whatever turn made them, and the
    /// agent's requests to them outstanding, which hold back the background
    /// results a turn is sent and let a budgeted turn lend its slot.
    model_slot: Arc<ModelSlot>,
    /// The questions the session's subagents ask, until the session takes
    /// them.
    child_questions: Option<mpsc::Receiver<SubagentHostInputRequest>>,
    /// Whether the daemon wakes the idle session for the tools' results.
    idle: IdleDelivery,
    /// Notices of the turns the session's `sessions` calls start in other
    /// sessions, where the daemon wakes it for them.
    peers: Option<PeerInbox>,
    /// The agent's MCP client.
    client: McpClient,
}

/// The served tools' wiring for one mode.
struct Wired {
    /// The mode, and the write grants its policy remembers.
    permission: SessionPermission,
    /// Who answers the calls' approvals: none in a mode whose policy
    /// decides alone.
    session: Option<ApprovalSession>,
    /// The approvals a person answers, in a mode that asks them.
    receiver: Option<ApprovalRequestReceiver>,
}

impl ServedTools {
    /// What the instructions say of the tools, and the skills they list,
    /// found off the async runtime: finding them reads the skill folders.
    pub(super) async fn guide(&self) -> ServedToolGuide {
        let tools: Vec<String> = self.served.iter().map(|tool| tool.spec().name).collect();
        if !tools.iter().any(|name| name == "skill") {
            return ServedToolGuide {
                tools,
                skills: Vec::new(),
                idle: self.idle,
                naming: self.client.naming(),
            };
        }
        let cwd = self.cwd.clone();
        let trust = self.environment.project_trust();
        let skills = tokio::task::spawn_blocking(move || {
            crate::skills::discover_with_home(&cwd, crate::paths::home_dir().as_deref(), trust)
        })
        .await
        .unwrap_or_else(|error| {
            tracing::warn!(%error, "could not find the session's skills");
            Vec::new()
        });
        ServedToolGuide {
            tools,
            skills,
            idle: self.idle,
            naming: self.client.naming(),
        }
    }

    /// The tools for one turn in `mode`, whose commands find executables on
    /// `search_path`.
    pub(super) async fn turn(
        &mut self,
        mode: PermissionMode,
        search_path: Option<OsString>,
    ) -> TurnTools<'_> {
        let host = self.host_in(mode, search_path.clone()).await;
        let (hosts, host) = watch::channel(host);
        let (asks, asked) = mpsc::unbounded_channel();
        let calls = TurnCalls::new(
            Arc::clone(&self.listed),
            Arc::clone(&self.by_name),
            self.cards.clone(),
            host,
            asks,
            Arc::clone(&self.model_slot),
        );
        TurnTools {
            tools: self,
            hosts,
            calls: Arc::new(calls),
            asked,
            search_path,
        }
    }

    /// Runs later calls in `mode` under `config`, read as a client sets the
    /// mode: Auto set again rewires, so a classifier model picked since
    /// takes effect, as in a Rho session. A mode that cannot run keeps the
    /// wiring as it was; each turn in it then tells its calls why.
    pub(super) async fn reapply(&mut self, mode: PermissionMode, config: Config) {
        self.config = config;
        if let Err(why) = self.rewire(mode, SameMode::RebuildAuto).await {
            tracing::debug!(session = %self.session, %why, "rho's tools keep their mode");
        }
    }

    /// The host calls in `mode` run on, rewired first if the last wiring
    /// was of another mode.
    async fn host_in(&mut self, mode: PermissionMode, search_path: Option<OsString>) -> TurnHost {
        self.rewire(mode, SameMode::Keep).await?;
        self.host(search_path)
    }

    /// Wires the approvals and policy of `mode`, keeping the last wiring
    /// when it is of the same mode and `same` keeps it: an allow for the
    /// session holds while the mode does. Write grants carry over as a Rho
    /// session's do. Fails, keeping the wiring as it was, for Auto when no
    /// classifier model can run.
    async fn rewire(&mut self, mode: PermissionMode, same: SameMode) -> Result<(), String> {
        let credentials = self.environment.credentials();
        let moved = match &self.wired {
            Some(wired) => wired
                .permission
                .move_to(mode, &self.config, credentials.as_ref(), same),
            None => ModeMove::first(mode, &self.config, credentials.as_ref()).map(Some),
        }
        .map_err(|error| format!("rho's tools cannot run in this mode: {error}"))?;
        let Some(moved) = moved else {
            return Ok(());
        };
        let SessionApproval { session, receiver } = ApprovalPolicy::Host.wire(ApprovalInputs {
            config: moved.config.clone(),
            workspace_root: self.cwd.clone(),
            usage_recording: crate::usage::default_recording().await,
            session_writes: moved.writes.clone(),
            credentials,
        });
        // Children the session starts from here on run in its mode, as a
        // Rho session's do.
        if let Some(manager) = self.set.subagents() {
            manager.update_permission_mode(mode);
        }
        let permission = match self.wired.take() {
            Some(Wired { mut permission, .. }) => {
                permission.take(moved);
                permission
            }
            None => moved.into_permission(self.cwd.clone()),
        };
        self.wired = Some(Wired {
            permission,
            session,
            receiver,
        });
        Ok(())
    }

    /// A host for calls as wired, whose commands find executables on
    /// `search_path`.
    fn host(&self, search_path: Option<OsString>) -> TurnHost {
        let workspace = self.workspace.clone()?;
        let Some(wired) = &self.wired else {
            return Err("rho's tools have no approvals wired".to_owned());
        };
        let permission = &wired.permission;
        let mut builder = ToolHost::builder()
            .workspace(workspace)
            .workspace_policy(AppPolicy::for_mode(
                permission.mode,
                permission.writes.clone(),
                search_path,
            ))
            .session_id(self.session.clone())
            // The agent's model made the call: a tool holds back what only
            // a person may start, as for a Rho model's call.
            .invocation_source(ToolInvocationSource::Model);
        if let Some(session) = &wired.session {
            builder = builder.approval_session(session.clone());
        }
        if let Some(hooks) = &self.hooks {
            builder = hooks.attach_tool_host(builder);
        }
        for tool in &self.served {
            builder = builder.tool_shared(Arc::clone(tool));
        }
        builder.build().map_err(|error| error.to_string())
    }

    /// The tools, and what they started, whose background work
    /// `acp_background` reads.
    pub(super) fn set(&self) -> &AppToolSet {
        &self.set
    }

    /// Whether the daemon wakes the idle session for the tools' results.
    pub(super) fn idle(&self) -> IdleDelivery {
        self.idle
    }

    /// Where the session hears of the turns its `sessions` calls start in
    /// other sessions, if the daemon wakes it for them.
    pub(super) fn peers(&self) -> Option<&PeerInbox> {
        self.peers.as_ref()
    }

    /// The children's notices the last turn left undelivered, held for the
    /// next.
    pub(super) fn held_notices(&self) -> Option<&HeldNotices> {
        self.held.as_ref()
    }

    /// Starts delivering the tools' background results into a turn,
    /// resuming the children's notices the last turn kept; give what the
    /// turn's run left back with [`Self::keep_notices`], or the whole of it
    /// with [`Self::put_back`] when the turn never ran.
    pub(super) fn deliver_into_turn(&mut self) -> TurnBackground {
        let held = self.held.take();
        let delivery = acp_background::bind(self.session.to_string(), self, held);
        TurnDelivery::start(delivery, self.model_slot.activity().clone())
    }

    /// Keeps the children's notice binding a turn left, for the next.
    pub(super) fn keep_notices(&mut self, held: Option<HeldNotices>) {
        self.held = held;
    }

    /// Puts back the results `background` reserved for a turn that never
    /// ran, keeping the children's notice binding for the next.
    pub(super) fn put_back(&mut self, (delivery, mailbox): TurnBackground) {
        // The run never took its inbox or prompt: nothing was delivered.
        drop(mailbox);
        self.keep_notices(delivery.finish());
    }

    /// The questions the session's subagents ask, for the session to take
    /// once: `None` when its clients show no questions.
    pub(super) fn take_child_questions(
        &mut self,
    ) -> Option<mpsc::Receiver<SubagentHostInputRequest>> {
        self.child_questions.take()
    }

    /// Stops what the tools started (subagents, processes, browser tabs),
    /// then the session's hooks, once they ran what they heard.
    pub(super) async fn shutdown(self) {
        let Self { set, hooks, .. } = self;
        set.shutdown().await;
        if let Some(hooks) = hooks {
            hooks.shutdown(crate::hooks::DRAIN_GRACE).await;
        }
    }
}

/// One turn's side of the session's served tools.
pub(super) struct TurnTools<'a> {
    tools: &'a mut ServedTools,
    /// Swaps the host the turn's calls start on.
    hosts: watch::Sender<TurnHost>,
    calls: Arc<TurnCalls>,
    asked: mpsc::UnboundedReceiver<ServedAsk>,
    search_path: Option<OsString>,
}

impl TurnTools<'_> {
    /// What the turn's run serves its agent.
    pub(super) fn agent_tools(&self) -> Arc<dyn AgentTools> {
        Arc::clone(&self.calls) as Arc<dyn AgentTools>
    }

    /// The person approved the agent's plan into `mode`: the calls the
    /// turn starts from now on run in it, as the rest of the agent's turn
    /// does, and so do the children they start. Called before the agent
    /// hears of the approval, so none of its later calls runs in plan mode;
    /// calls under way keep the mode they started in. Plan mode requests
    /// no approvals (its policy denies what it would ask), so they lose
    /// none with the old wiring; their questions go to the turn as before.
    pub(super) async fn leave_plan(&mut self, mode: PermissionMode) {
        let host = self.tools.host_in(mode, self.search_path.clone()).await;
        // The plan-mode host it replaces is dropped; calls under way hold their own.
        drop(self.hosts.send_replace(host));
    }

    /// The next thing a call asks or tells the turn.
    pub(super) async fn next(&mut self) -> Option<ServedAsk> {
        // The approvals of the mode wired now, in a mode a person answers.
        let approvals = self
            .tools
            .wired
            .as_mut()
            .and_then(|wired| wired.receiver.as_mut());
        let asked = &mut self.asked;
        tokio::select! {
            Some(approval) = async { approvals?.recv().await } => {
                Some(ServedAsk::Approval(approval))
            }
            Some(told) = asked.recv() => Some(told),
            else => None,
        }
    }
}

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