trusty_code/permissions/gate.rs
1//! The runtime permission gate: evaluate, ask, await, time out (#7948).
2//!
3//! Why: `config` says what an operator wrote and `matcher` says which rule
4//! applies; this module turns a tool call into "dispatch it" or "refuse it",
5//! including the suspend-and-await path an `ask` rule needs, behind one call
6//! at the agent loop's dispatch site.
7//! What: `PermissionMode` (the headless escape hatch), `Decision` (the pure
8//! evaluation), `Outcome`/`DenySource` (the final answer), `PermissionEvents`
9//! (the emit seam `SessionRegistry` implements), `PermissionContext` (the
10//! session-scoped half), and `PermissionGate` (one agent's gate).
11//!
12//! An agent with no `permissions:` block short-circuits to `Allow` after the
13//! legacy allowlist check, and [`HARNESS_REGISTERED_TOOLS`] skips that check
14//! entirely, so stock bundled agents are unaffected.
15//! Test: `permissions::tests::gate_tests` — the whole module.
16
17use std::path::{Path, PathBuf};
18use std::sync::Arc;
19use std::time::Duration;
20
21use serde_json::Value;
22use uuid::Uuid;
23
24use crate::agents::config::AgentConfig;
25use crate::tools::{
26 CLEAR_GOAL_TOOL_NAME, DELEGATE_TO_AGENT_TOOL_NAME, FINISH_TASK_TOOL_NAME,
27 RECALL_SESSION_TOOL_NAME, SET_GOAL_TOOL_NAME, TODO_WRITE_TOOL_NAME, USE_SKILL_TOOL_NAME,
28};
29
30use super::config::RuleDecision;
31use super::matcher::subjects_for_in_root;
32use super::protocol::PermissionDecision;
33use super::redact::redact_subject;
34use super::session::SessionPermissions;
35
36/// Environment fallback for [`PermissionMode`] when no CLI flag is given.
37pub const PERMISSION_MODE_ENV: &str = "TCODE_PERMISSION_MODE";
38
39/// How long an unanswered `ask` waits before resolving to deny.
40///
41/// Why: an `ask` that never resolves wedges the agent loop. Five minutes lets
42/// an operator read the prompt; a walked-away-from session then fails safe.
43pub const DEFAULT_ASK_TIMEOUT_SECS: u64 = 300;
44
45/// `Event::PermissionResolved.source` for an `ask` that
46/// [`PermissionMode::AllowAsks`] approved without a client (#7948).
47pub const ALLOW_ASKS_SOURCE: &str = "allow_asks";
48
49/// `Event::PermissionResolved.source` for an `ask` a grant this session already
50/// remembers satisfied, with no client round trip (#7948).
51///
52/// Why: distinct from `client` — nobody was asked this time; the decision is
53/// the earlier `allow_for_session` answer being reused.
54/// Test: `remembered_grant_emits_a_resolution_event`.
55pub const REMEMBERED_SOURCE: &str = "remembered";
56
57/// The tools the HARNESS registers on an agent's behalf, exempt from the legacy
58/// `tcode_tools` allowlist (#7948).
59///
60/// Why: `tcode_tools` is the agent author's vocabulary of capabilities the
61/// agent asks for. The run's own machinery — delegation, completion, goal
62/// slots, session recall, skill loading — is wired by
63/// `run_task::execute_run_task` and `task::executor::run_and_record`
64/// unconditionally, whatever the agent file lists. Stock `pm.md` lists neither
65/// `delegate_to_agent` nor `set_goal`, so without this exemption the gate
66/// refuses the PM's own delegation on both run-task paths.
67/// What: consulted ONLY by the allowlist branch of [`PermissionGate::evaluate`],
68/// which waives the allowlist's blanket "absent means denied". The
69/// `permissions:` map still runs afterwards, so a `delegate_to_agent: deny` an
70/// operator wrote still refuses, and a tool NOT named here — `bash`, `edit`,
71/// anything an author deliberately left out — is denied exactly as before.
72/// Test: `harness_registered_tool_bypasses_the_legacy_allowlist`,
73/// `stock_pm_agent_may_call_delegate_to_agent`,
74/// `explicit_deny_beats_the_harness_registered_exemption`,
75/// `harness_exemption_does_not_widen_an_ordinary_tool`,
76/// `stock_pm_agent_may_call_todo_write`.
77pub const HARNESS_REGISTERED_TOOLS: &[&str] = &[
78 DELEGATE_TO_AGENT_TOOL_NAME,
79 FINISH_TASK_TOOL_NAME,
80 SET_GOAL_TOOL_NAME,
81 CLEAR_GOAL_TOOL_NAME,
82 RECALL_SESSION_TOOL_NAME,
83 USE_SKILL_TOOL_NAME,
84 // #8235: the session checklist, wired unconditionally by
85 // `task::executor::run_and_record` exactly as the goal tools above are —
86 // no agent card lists it, so without this the gate refuses the agent's
87 // own plan tracking.
88 TODO_WRITE_TOOL_NAME,
89];
90
91/// Whether `tool` is one [`HARNESS_REGISTERED_TOOLS`] names.
92/// Test: `harness_registered_tool_bypasses_the_legacy_allowlist`.
93fn is_harness_registered(tool: &str) -> bool {
94 HARNESS_REGISTERED_TOOLS.contains(&tool)
95}
96
97/// What a run does with an `ask` it cannot put to a client.
98///
99/// Why: `tcode run-task` and a daemon run with nobody attached cannot prompt.
100/// The default refuses; a scripted run that accepts the risk must say so.
101/// What: `Default` refuses an unanswerable `ask`; `AllowAsks` treats every
102/// `ask` as `allow`, logging and emitting each approval. Neither affects a
103/// `deny`.
104/// Test: `headless_ask_is_denied`, `allow_asks_mode_permits_an_ask`,
105/// `allow_asks_mode_emits_an_audit_event`.
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
107pub enum PermissionMode {
108 #[default]
109 Default,
110 AllowAsks,
111}
112
113impl PermissionMode {
114 /// Parse a mode string leniently (case-insensitive, `_`/`-` interchangeable).
115 /// Test: `permission_mode_parses_allow_asks_spellings`.
116 pub fn parse_lenient(s: &str) -> Option<Self> {
117 match s.trim().to_ascii_lowercase().replace('_', "-").as_str() {
118 "default" => Some(Self::Default),
119 "allow-asks" | "allowasks" => Some(Self::AllowAsks),
120 _ => None,
121 }
122 }
123
124 /// Resolve the effective mode: CLI value, then [`PERMISSION_MODE_ENV`],
125 /// then `Default`.
126 /// Test: `cli_permission_mode_outranks_the_env_var`.
127 pub fn resolve(cli: Option<&str>) -> Self {
128 Self::resolve_from(cli, std::env::var(PERMISSION_MODE_ENV).ok().as_deref())
129 }
130
131 /// [`PermissionMode::resolve`] with both tiers supplied.
132 ///
133 /// Why: tests the precedence without mutating the process environment.
134 /// What: the first tier that parses wins; an unrecognised value contributes
135 /// nothing, and with no usable tier the result is `Default` — never a
136 /// widening.
137 /// Test: `cli_permission_mode_outranks_the_env_var`,
138 /// `env_permission_mode_applies_when_no_flag_is_given`,
139 /// `unrecognised_permission_mode_falls_back_to_default`.
140 pub fn resolve_from(cli: Option<&str>, env: Option<&str>) -> Self {
141 [cli, env]
142 .into_iter()
143 .flatten()
144 .find_map(Self::parse_lenient)
145 .unwrap_or_default()
146 }
147}
148
149/// The pure evaluation of a tool call against an agent's configuration.
150///
151/// Why: `Ask` is kept distinct from `Deny` because the prompt (#3422) must
152/// show the rule text.
153/// What: `Deny`/`Ask` carry the deciding rule in `tool` or `tool[arg]` form.
154/// Test: `legacy_allowlist_denial_precedes_the_map`, `unmatched_tool_is_allowed`.
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub enum Decision {
157 Allow,
158 Deny { rule: String },
159 Ask { rule: String },
160}
161
162/// Why a call was refused, and what `Event::PermissionResolved.source` says.
163/// Test: `headless_ask_is_denied`, `timed_out_ask_is_denied`, `client_deny_is_denied`.
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub enum DenySource {
166 /// A `deny` rule, or the legacy `tcode_tools` allowlist.
167 Policy,
168 /// An `ask` with nobody able to answer it.
169 Headless,
170 /// An `ask` nobody answered in time, or whose request was abandoned.
171 Timeout,
172 /// An `ask` a client answered with `deny`.
173 Client,
174}
175
176impl DenySource {
177 /// The stable wire word for `Event::PermissionResolved.source`.
178 pub fn as_str(self) -> &'static str {
179 match self {
180 Self::Policy => "policy",
181 Self::Headless => "headless",
182 Self::Timeout => "timeout",
183 Self::Client => "client",
184 }
185 }
186}
187
188/// The gate's final answer for one tool call.
189/// Test: `deny_message_names_the_rule`.
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub enum Outcome {
192 Allow,
193 Denied { rule: String, source: DenySource },
194}
195
196impl Outcome {
197 /// The recoverable tool-error text a refusal becomes.
198 ///
199 /// Why: the model must tell "policy says no" from "nobody was there to say
200 /// yes"; the `denied by policy (<rule>)` prefix is stable for grep and tests.
201 /// Test: `deny_message_names_the_rule`, `timed_out_ask_is_denied`.
202 pub fn message(&self) -> Option<String> {
203 match self {
204 Outcome::Allow => None,
205 Outcome::Denied { rule, source } => Some(match source {
206 DenySource::Policy => format!("denied by policy ({rule})"),
207 DenySource::Headless => format!("denied by policy ({rule}): headless run"),
208 DenySource::Timeout => format!("denied by policy ({rule}): no decision"),
209 DenySource::Client => format!("denied by policy ({rule}): denied by client"),
210 }),
211 }
212 }
213}
214
215/// The emit seam for the two permission events.
216///
217/// Why: `SessionRegistry` is the sole assigner of an event's `seq`, so this
218/// module publishes through a trait instead of depending on the session layer
219/// (the same direction `ToolEventSink` points).
220/// Test: `ask_emits_requested_then_resolved`.
221pub trait PermissionEvents: Send + Sync {
222 /// An `ask` is now waiting on a client. The parameters are independent
223 /// event fields, mirroring `SessionRegistry::record_tool_finished`.
224 #[allow(clippy::too_many_arguments)]
225 fn permission_requested(
226 &self,
227 session_id: &str,
228 request_id: &str,
229 agent: &str,
230 agent_id: &str,
231 tool: &str,
232 subject: &str,
233 rule: &str,
234 );
235 /// An `ask` reached a decision (or ran out of time).
236 fn permission_resolved(
237 &self,
238 session_id: &str,
239 request_id: &str,
240 agent: &str,
241 agent_id: &str,
242 decision: &str,
243 source: &str,
244 );
245
246 /// Whether anything is consuming this session's events, and so could see a
247 /// prompt and answer it.
248 ///
249 /// Why (#8100): a daemon `task.run` always holds broker state, so
250 /// `PermissionContext::ask.is_some()` says only that a rendezvous EXISTS —
251 /// never that a client is on the other end of it. A headless run therefore
252 /// sat out the full [`DEFAULT_ASK_TIMEOUT_SECS`] per `ask` rule and then
253 /// denied anyway. This is the question that distinguishes the two, asked of
254 /// the same object that publishes the prompt.
255 /// What: the answer is about `session_id` and no other — a process-wide
256 /// reading is wrong, because one watched PM session dispatching headless
257 /// `task.run` sub-agents would then mark every sub-agent as watched and
258 /// restore the stall for all of them. No default: an implementor must
259 /// answer deliberately, since `true` wrongly restores the 300 s stall and
260 /// `false` wrongly denies an operator who was watching. A sink that cannot
261 /// tell must answer `false` — an event nobody consumes is a prompt nobody
262 /// sees.
263 /// Test: `ask_without_an_attached_prompter_denies_immediately`,
264 /// `an_ask_on_an_unwatched_session_is_headless_while_a_sibling_is_watched`,
265 /// `ask_emits_requested_then_resolved`.
266 fn prompter_attached(&self, session_id: &str) -> bool;
267}
268
269/// The session-scoped, agent-independent half of a gate's configuration.
270///
271/// Why: a gate is per AGENT (its map comes from that agent's config), while
272/// the session, the answering channel, and the timeout are shared by every
273/// agent in one run, so the sub-agent runner mints a gate per delegation from
274/// one cloned context.
275/// What: `ask` is `None` for a headless run; an `ask` rule then resolves
276/// immediately per `mode`. #8100: `ask` being `Some` is NOT the same as a
277/// client being attached — the daemon mints broker state for every `task.run`
278/// — so `events.prompter_attached` is consulted too, and a run nobody is
279/// watching is headless however the broker was wired. #7948: `root` is the
280/// run's working root, which
281/// [`subjects_for_in_root`] needs to decide an absolute in-root path against a
282/// relatively-written rule; `None` restricts matching to the spelling the model
283/// wrote.
284/// Test: `headless_ask_is_denied`, `ask_emits_requested_then_resolved`,
285/// `absolute_in_root_path_meets_a_relative_deny`.
286#[derive(Clone)]
287pub struct PermissionContext {
288 pub mode: PermissionMode,
289 pub timeout: Duration,
290 pub session_id: String,
291 pub ask: Option<Arc<SessionPermissions>>,
292 pub events: Option<Arc<dyn PermissionEvents>>,
293 pub root: Option<PathBuf>,
294}
295
296impl PermissionContext {
297 /// A context that can never prompt — the `tcode run-task` shape.
298 /// Test: `headless_ask_is_denied`.
299 pub fn headless(mode: PermissionMode) -> Self {
300 Self {
301 mode,
302 timeout: Duration::from_secs(DEFAULT_ASK_TIMEOUT_SECS),
303 session_id: String::new(),
304 ask: None,
305 events: None,
306 root: None,
307 }
308 }
309
310 /// Attach the run's working root.
311 ///
312 /// Why (#7948): without it, a relative path rule misses the absolute
313 /// in-root spelling of the same file, which `tools::fs::scoped_path`
314 /// accepts.
315 /// Test: `absolute_in_root_path_meets_a_relative_deny`.
316 pub fn with_root(mut self, root: impl Into<PathBuf>) -> Self {
317 self.root = Some(root.into());
318 self
319 }
320
321 /// Mint a gate for one agent running under this context.
322 /// Test: `gate_for_agent_without_a_map_allows_everything`.
323 pub fn gate_for(&self, agent: Arc<AgentConfig>, agent_id: impl Into<String>) -> PermissionGate {
324 PermissionGate {
325 agent,
326 agent_id: agent_id.into(),
327 ctx: self.clone(),
328 }
329 }
330}
331
332/// One agent's permission gate — the object the agent loop holds.
333///
334/// What: consulted in every harness mode. #7948: `HarnessMode::Parity` is not
335/// exempt — a `deny` the operator wrote holds there too; the tool SCHEMAS a
336/// parity run advertises are unchanged by the gate.
337/// Test: `deny_never_dispatches`.
338pub struct PermissionGate {
339 agent: Arc<AgentConfig>,
340 agent_id: String,
341 ctx: PermissionContext,
342}
343
344impl PermissionGate {
345 /// Evaluate one tool call against `agent`'s configuration — the pure half.
346 ///
347 /// Why: an associated function so precedence is testable with a config and
348 /// a JSON value alone.
349 /// What: the LEGACY `tcode_tools` allowlist runs FIRST — a tool absent from
350 /// it is denied before the map is consulted, so a map cannot widen an
351 /// allowlist. #7948: a tool in [`HARNESS_REGISTERED_TOOLS`] skips that
352 /// branch, because the harness — not the agent's author — put it in the
353 /// registry. Then the map decides over every subject of the call; an
354 /// unmatched call is `Allow`.
355 /// Test: `legacy_allowlist_denial_precedes_the_map`,
356 /// `legacy_allowlist_absent_means_every_tool`, `unmatched_tool_is_allowed`,
357 /// `deny_rule_produces_deny`, `ask_rule_produces_ask`,
358 /// `harness_registered_tool_bypasses_the_legacy_allowlist`,
359 /// `stock_pm_agent_may_call_delegate_to_agent`,
360 /// `explicit_deny_beats_the_harness_registered_exemption`.
361 pub fn evaluate(agent: &AgentConfig, tool: &str, args: &Value) -> Decision {
362 Self::evaluate_in_root(agent, tool, args, None)
363 }
364
365 /// [`PermissionGate::evaluate`] with the run's working root supplied.
366 ///
367 /// Why (#7948): a path rule an operator wrote relative must also decide the
368 /// absolute in-root spelling of the same file — see
369 /// [`subjects_for_in_root`].
370 /// What: identical to [`PermissionGate::evaluate`] but for the extra
371 /// root-relative subject, which `evaluate_call`'s safest-wins fold can only
372 /// use to restrict.
373 /// Test: `absolute_in_root_path_meets_a_relative_deny`,
374 /// `path_deny_holds_for_the_absolute_in_root_spelling`.
375 pub fn evaluate_in_root(
376 agent: &AgentConfig,
377 tool: &str,
378 args: &Value,
379 root: Option<&Path>,
380 ) -> Decision {
381 // #7948: the allowlist speaks for the agent's author, who never sees
382 // the harness-registered tools; only a written `deny` refuses those.
383 if let Some(allowed) = agent.tools.as_ref().and_then(|t| t.allowed.as_ref())
384 && !allowed.iter().any(|a| a == tool)
385 && !is_harness_registered(tool)
386 {
387 return Decision::Deny {
388 rule: "tcode_tools allowlist".to_string(),
389 };
390 }
391 let Some(map) = agent.permissions.as_ref() else {
392 return Decision::Allow;
393 };
394 match map.evaluate_call(tool, &subjects_for_in_root(tool, args, root)) {
395 None => Decision::Allow,
396 Some(m) => match m.decision {
397 RuleDecision::Allow => Decision::Allow,
398 RuleDecision::Deny => Decision::Deny { rule: m.rule },
399 RuleDecision::Ask => Decision::Ask { rule: m.rule },
400 },
401 }
402 }
403
404 /// Decide one tool call, prompting and waiting when the map says `ask`.
405 ///
406 /// Why: the single call the agent loop makes; the caller must not dispatch
407 /// on `Outcome::Denied`.
408 /// What: `evaluate` runs; `Allow`/`Deny` return at once. `Ask` checks this
409 /// session's remembered grants, then `AllowAsks` — both auto-allow paths
410 /// record the approval — then, only with an answering channel AND a client
411 /// watching the session (#8100), emits `PermissionRequested`, awaits an
412 /// answer for `ctx.timeout`, and emits `PermissionResolved`. Missing
413 /// either is `Denied { source: Headless }`, returned at once rather than
414 /// after [`DEFAULT_ASK_TIMEOUT_SECS`].
415 ///
416 /// Test: `headless_ask_is_denied`, `allow_asks_mode_permits_an_ask`,
417 /// `ask_without_an_attached_prompter_denies_immediately`,
418 /// `an_ask_on_an_unwatched_session_is_headless_while_a_sibling_is_watched`,
419 /// `an_ask_with_no_event_sink_is_headless`,
420 /// `allow_asks_mode_emits_an_audit_event`,
421 /// `timed_out_ask_is_denied`, `client_deny_is_denied`,
422 /// `ask_emits_requested_then_resolved`,
423 /// `allow_for_session_is_remembered_for_a_later_matching_call`,
424 /// `remembered_grant_emits_a_resolution_event`.
425 pub async fn resolve(&self, tool: &str, args: &Value) -> Outcome {
426 // #7948: the run's root makes a relative path rule decide the absolute
427 // in-root spelling too.
428 let root = self.ctx.root.as_deref();
429 let rule = match Self::evaluate_in_root(&self.agent, tool, args, root) {
430 Decision::Allow => return Outcome::Allow,
431 Decision::Deny { rule } => {
432 return Outcome::Denied {
433 rule,
434 source: DenySource::Policy,
435 };
436 }
437 Decision::Ask { rule } => rule,
438 };
439
440 let subjects = subjects_for_in_root(tool, args, root);
441 if let Some(state) = &self.ctx.ask
442 && state.is_remembered(tool, &subjects)
443 {
444 // #7948: a grant reused silently is a call an audit cannot see.
445 self.record_auto_allow(
446 tool,
447 &subjects,
448 &rule,
449 "allow_for_session",
450 REMEMBERED_SOURCE,
451 "permission: ask satisfied by a remembered session grant",
452 );
453 return Outcome::Allow;
454 }
455 if self.ctx.mode == PermissionMode::AllowAsks {
456 // #7948: an auto-approved `ask` still leaves an audit trail.
457 self.record_auto_allow(
458 tool,
459 &subjects,
460 &rule,
461 "allow_once",
462 ALLOW_ASKS_SOURCE,
463 "permission: ask auto-approved by allow-asks mode",
464 );
465 return Outcome::Allow;
466 }
467 // #8100: BOTH halves must hold — a rendezvous to wait on, and someone
468 // watching the events who could answer into it. A daemon `task.run`
469 // always has the first, which is why a headless run used to wait out
470 // the whole ask timeout before denying.
471 let Some(state) = self.ctx.ask.clone().filter(|_| self.prompter_attached()) else {
472 return Outcome::Denied {
473 rule,
474 source: DenySource::Headless,
475 };
476 };
477 self.ask(&state, tool, &subjects, rule).await
478 }
479
480 /// Whether a client is watching this session and could answer an `ask`.
481 ///
482 /// Why (#8100): see [`PermissionEvents::prompter_attached`]. No event sink
483 /// at all is headless by the same argument — the `permission_requested`
484 /// event carries the `request_id` a client answers with, so a request that
485 /// is never published can never be answered.
486 /// Test: `ask_without_an_attached_prompter_denies_immediately`,
487 /// `an_ask_with_no_event_sink_is_headless`.
488 fn prompter_attached(&self) -> bool {
489 self.ctx
490 .events
491 .as_ref()
492 .is_some_and(|events| events.prompter_attached(&self.ctx.session_id))
493 }
494
495 /// Record an `ask` this gate allowed WITHOUT putting it to a client —
496 /// `PermissionMode::AllowAsks`, or a grant remembered earlier this session.
497 ///
498 /// Why (#7948): without a record, an operator auditing a run cannot tell an
499 /// auto-allowed `ask` from a call no rule matched. The two auto-allow paths
500 /// differ only in the decision/source words, so they share one emitter.
501 /// What: logs at `info` with the redacted subject, and emits
502 /// `permission_resolved` under a fresh request id that no
503 /// `permission_requested` preceded — the marker of an auto-allow.
504 /// Test: `allow_asks_mode_emits_an_audit_event`,
505 /// `remembered_grant_emits_a_resolution_event`.
506 fn record_auto_allow(
507 &self,
508 tool: &str,
509 subjects: &[String],
510 rule: &str,
511 decision: &str,
512 source: &str,
513 reason: &'static str,
514 ) {
515 let request_id = Uuid::new_v4().to_string();
516 let agent_name = self.agent.agent.name.as_str();
517 tracing::info!(
518 session_id = %self.ctx.session_id,
519 agent = %agent_name,
520 agent_id = %self.agent_id,
521 tool = %tool,
522 subject = %redact_subject(&subjects.join("\n")),
523 rule = %rule,
524 request_id = %request_id,
525 decision = %decision,
526 source = %source,
527 "{reason}"
528 );
529 if let Some(events) = &self.ctx.events {
530 events.permission_resolved(
531 &self.ctx.session_id,
532 &request_id,
533 agent_name,
534 &self.agent_id,
535 decision,
536 source,
537 );
538 }
539 }
540
541 /// Emit the request, await the answer, emit the resolution.
542 /// Test: `ask_emits_requested_then_resolved`, `timed_out_ask_is_denied`,
543 /// `abandoned_request_resolves_to_deny`.
544 async fn ask(
545 &self,
546 state: &Arc<SessionPermissions>,
547 tool: &str,
548 subjects: &[String],
549 rule: String,
550 ) -> Outcome {
551 let request_id = Uuid::new_v4().to_string();
552 let rx = state.register(&request_id);
553 let agent_name = self.agent.agent.name.as_str();
554
555 if let Some(events) = &self.ctx.events {
556 events.permission_requested(
557 &self.ctx.session_id,
558 &request_id,
559 agent_name,
560 &self.agent_id,
561 tool,
562 &redact_subject(&subjects.join("\n")),
563 &rule,
564 );
565 }
566
567 let denied = |source| Outcome::Denied {
568 rule: rule.clone(),
569 source,
570 };
571 let (outcome, decision, source) = match tokio::time::timeout(self.ctx.timeout, rx).await {
572 Ok(Ok(PermissionDecision::AllowOnce)) => (Outcome::Allow, "allow_once", "client"),
573 Ok(Ok(PermissionDecision::AllowForSession { pattern })) => {
574 state.remember(tool, subjects, pattern.as_deref());
575 (Outcome::Allow, "allow_for_session", "client")
576 }
577 Ok(Ok(PermissionDecision::Deny)) => (denied(DenySource::Client), "deny", "client"),
578 // #7948: a dropped sender (abandoned or never registered) produced
579 // no decision, exactly like a timeout — never an allow.
580 Ok(Err(_)) | Err(_) => {
581 state.forget(&request_id);
582 (denied(DenySource::Timeout), "deny", "timeout")
583 }
584 };
585
586 if let Some(events) = &self.ctx.events {
587 events.permission_resolved(
588 &self.ctx.session_id,
589 &request_id,
590 agent_name,
591 &self.agent_id,
592 decision,
593 source,
594 );
595 }
596 outcome
597 }
598}