oxi-sdk 0.52.1

oxi AI agent SDK — build isolated, multi-agent AI systems
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
//! AgentBuilder — Fluent API for creating agents

use std::path::PathBuf;
use std::sync::Arc;

use oxi_agent::{
    Agent, AgentConfig, AgentTool, AgentToolResult, ProviderResolver, ToolContext, ToolRegistry,
    tools::browse::{BrowseConfig, BrowseExtractTool, BrowseTool, BrowserEngine},
};

use crate::builder::Oxi;
use crate::middleware::{Middleware, MiddlewarePipeline};
use crate::observability::{AuditLog, CostTracker, Tracer};
use crate::security::{Authorizer, CapabilitySet};

/// Wrapper that makes Arc<Oxi> usable as ProviderResolver.
/// This is needed because Agent stores Arc<dyn ProviderResolver + 'static>.
pub(crate) struct OxiResolver {
    oxi: Arc<OxiCore>,
}

/// Type-erased Oxi inner for the resolver.
/// We can't use `Oxi` directly because it's in the same crate.
/// Instead we use a trait object approach.
pub(crate) struct OxiCore {
    #[allow(clippy::type_complexity)]
    resolve_provider_fn: Box<dyn Fn(&str) -> Option<Arc<dyn oxi_ai::Provider>> + Send + Sync>,
    #[allow(clippy::type_complexity)]
    resolve_model_fn: Box<dyn Fn(&str) -> Option<oxi_ai::Model> + Send + Sync>,
}

impl ProviderResolver for OxiResolver {
    fn resolve_provider(&self, name: &str) -> Option<Arc<dyn oxi_ai::Provider>> {
        (self.oxi.resolve_provider_fn)(name)
    }

    fn resolve_model(&self, model_id: &str) -> Option<oxi_ai::Model> {
        (self.oxi.resolve_model_fn)(model_id)
    }
}

/// Builder for creating an agent with custom configuration.
#[allow(dead_code)]
pub struct AgentBuilder<'a> {
    oxi: &'a Oxi,
    config: AgentConfig,
    tools: ToolRegistry,
    workspace_dir: Option<PathBuf>,
    system_prompt: Option<String>,
    // ── Security ──
    capabilities: Option<CapabilitySet>,
    authorizer: Option<Arc<Authorizer>>,
    // ── Observability ──
    tracer: Option<Arc<Tracer>>,
    audit_log: Option<Arc<AuditLog>>,
    cost_tracker: Option<Arc<CostTracker>>,
    // ── Middleware ──
    middlewares: Vec<Arc<dyn Middleware>>,
}

impl<'a> AgentBuilder<'a> {
    /// Create a new builder bound to the given [`Oxi`] instance with the provided agent config.
    pub fn new(oxi: &'a Oxi, config: AgentConfig) -> Self {
        Self {
            oxi,
            config,
            tools: ToolRegistry::new(),
            workspace_dir: None,
            system_prompt: None,
            capabilities: None,
            authorizer: None,
            tracer: None,
            audit_log: None,
            cost_tracker: None,
            middlewares: Vec::new(),
        }
    }

    /// Set the working directory for file tools.
    pub fn workspace(mut self, dir: impl Into<PathBuf>) -> Self {
        self.workspace_dir = Some(dir.into());
        self
    }

    /// Set a custom system prompt.
    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.system_prompt = Some(prompt.into());
        self
    }
    /// Register a [`TodoStateProvider`](crate::TodoStateProvider) so the agent's `todo` tool works.
    ///
    /// The provider is shared between the agent (writer) and the host
    /// application (reader), so you can observe phase changes in real time
    /// by calling [`TodoStateProvider::get_phases()`](crate::TodoStateProvider::get_phases) periodically.
    ///
    /// Use [`InMemoryTodoState`](crate::inmem::InMemoryTodoState) for a
    /// ready-to-go in-memory implementation:
    ///
    /// ```no_run
    /// use std::sync::Arc;
    /// use oxi_sdk::{AgentConfig, OxiBuilder, inmem::InMemoryTodoState};
    ///
    /// let todo = Arc::new(InMemoryTodoState::new());
    /// let oxi = OxiBuilder::new().with_builtins().build();
    /// let agent = oxi.agent(AgentConfig {
    ///     model_id: "anthropic/claude-sonnet-4-20250514".into(),
    ///     ..Default::default()
    /// })
    /// .with_todo(todo.clone())
    /// .build()
    /// .unwrap();
    ///
    /// // Observe later:
    /// let phases = todo.get_phases();
    /// ```
    pub fn with_todo(
        mut self,
        todo: std::sync::Arc<dyn oxi_agent::tools::TodoStateProvider>,
    ) -> Self {
        self.config.todo = Some(todo);
        self.tools.register(oxi_agent::tools::todo::TodoTool);
        self
    }

    /// Register the standard coding tools (read, write, edit, bash, grep, find, ls, ...).
    pub fn coding_tools(self) -> Self {
        let cwd = self
            .workspace_dir
            .clone()
            .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
        let tools = crate::tool_factory::coding_tools(&cwd);
        for name in tools.names() {
            if let Some(tool) = tools.get(&name) {
                self.tools.register_arc(tool);
            }
        }
        self
    }

    /// Register read-only tools (read, ls).
    pub fn readonly_tools(self) -> Self {
        let cwd = self
            .workspace_dir
            .clone()
            .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
        let tools = crate::tool_factory::readonly_tools(&cwd);
        for name in tools.names() {
            if let Some(tool) = tools.get(&name) {
                self.tools.register_arc(tool);
            }
        }
        self
    }

    /// Register a tool.
    pub fn tool(self, tool: impl AgentTool + 'static) -> Self {
        self.tools.register(tool);
        self
    }

    /// Register a custom tool from a closure (synchronous handler).
    ///
    /// Creates a `ClosureTool` internally.
    ///
    /// # Example
    /// ```rust
    /// use oxi_sdk::{ClosureTool, AgentToolResult};
    ///
    /// // custom_tool creates a tool from a closure
    /// let tool = ClosureTool::new_sync(
    ///     "memory_recall",
    ///     "Search long-term memory",
    ///     serde_json::json!({"type": "object", "properties": {"query": {"type": "string"}}}),
    ///     |params, _ctx| {
    ///         let query = params["query"].as_str().unwrap();
    ///         Ok(AgentToolResult::success(format!("Recalled: {}", query)))
    ///     },
    /// );
    /// ```
    pub fn custom_tool(
        self,
        name: impl Into<String>,
        description: impl Into<String>,
        schema: serde_json::Value,
        handler: impl Fn(
            serde_json::Value,
            &ToolContext,
        ) -> Result<AgentToolResult, oxi_agent::ToolError>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.tool(crate::closure_tool::ClosureTool::new_sync(
            name,
            description,
            schema,
            handler,
        ))
    }

    /// Register multiple tools.
    pub fn tools(self, tools: impl IntoIterator<Item = impl AgentTool + 'static>) -> Self {
        for tool in tools {
            self.tools.register(tool);
        }
        self
    }

    /// Register browser tools (browse, browse_extract) with the given engine.
    ///
    /// This is the primary entry point for SDK consumers that want built-in
    /// web browsing. Pass any [`BrowserEngine`] implementation — when the
    /// `native-browser` feature is enabled on `oxi-agent`, use
    /// `oxi_agent::tools::browse::OxiBrowserEngine` for
    /// the built-in headless browser.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use oxi_sdk::prelude::*;
    ///
    /// // Requires a BrowserEngine implementation
    /// let engine: Arc<dyn BrowserEngine> = /* ... */;
    /// let agent = oxi.agent(config)
    ///     .workspace("/project")
    ///     .coding_tools()
    ///     .browsing(engine)
    ///     .build()?;
    /// ```
    pub fn browsing(self, engine: Arc<dyn BrowserEngine>) -> Self {
        self.tools.register(BrowseTool::new(Arc::clone(&engine)));
        self.tools.register(BrowseExtractTool::new(engine));
        self
    }

    /// Register browser tools with custom configuration.
    ///
    /// Like [`browsing()`](Self::browsing) but allows tuning timeouts,
    /// cache, tab limits, etc. via [`BrowseConfig`].
    pub fn browsing_with_config(
        self,
        engine: Arc<dyn BrowserEngine>,
        config: BrowseConfig,
    ) -> Self {
        self.tools
            .register(BrowseTool::with_config(Arc::clone(&engine), config.clone()));
        self.tools
            .register(BrowseExtractTool::with_config(engine, config));
        self
    }

    /// Register the native browser tools using `oxibrowser-core`.
    ///
    /// Convenience method that creates an `OxiBrowserEngine` and registers
    /// all browser tools. Only available when the `native-browser` feature
    /// is enabled.
    #[cfg(feature = "native-browser")]
    #[cfg_attr(docsrs, doc(cfg(feature = "native-browser")))]
    pub async fn native_browser(self) -> anyhow::Result<Self> {
        let engine = oxi_agent::tools::browse::OxiBrowserEngine::new().await?;
        Ok(self.browsing(Arc::new(engine)))
    }

    /// Register all browser tools including persistent session support.
    ///
    /// Like [`browsing()`](Self::browsing) but also registers `browse_script`
    /// and `browse_session` for multi-step interactive sessions with a
    /// persistent tab. Only available when the `native-browser` feature
    /// is enabled.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use oxi_sdk::prelude::*;
    ///
    /// // Requires the native-browser feature and OxiBrowserEngine
    /// let engine: Arc<dyn BrowserEngine> = /* ... */;
    /// let agent = oxi.agent(config)
    ///     .browsing_with_session(engine)
    ///     .build()?;
    /// ```
    #[cfg(feature = "native-browser")]
    #[cfg_attr(docsrs, doc(cfg(feature = "native-browser")))]
    pub fn browsing_with_session(self, engine: Arc<dyn BrowserEngine>) -> Self {
        use oxi_agent::tools::browse::{BrowseScriptTool, BrowseSessionTool};

        self.tools.register(BrowseTool::new(Arc::clone(&engine)));
        self.tools
            .register(BrowseExtractTool::new(Arc::clone(&engine)));
        self.tools
            .register(BrowseScriptTool::new(Arc::clone(&engine)));
        self.tools.register(BrowseSessionTool::new(engine));
        self
    }

    /// Register kernel tools from a [`KernelToolProvider`].
    ///
    /// This is the bridge for oxios kernel tools (exec, memory, browser, etc.).
    /// The kernel implements `KernelToolProvider` and registers its tools
    /// into the agent's tool registry.
    ///
    /// [`KernelToolProvider`]: crate::KernelToolProvider
    pub fn kernel_tools(
        self,
        provider: &dyn crate::KernelToolProvider,
        context: &crate::KernelToolContext,
    ) -> Self {
        provider.register_tools(&self.tools, context);
        self
    }

    // ── Security ──────────────────────────────────────────

    /// Set the capability set for this agent.
    pub fn capabilities(mut self, caps: CapabilitySet) -> Self {
        self.capabilities = Some(caps);
        self
    }

    /// Use standard coding capabilities.
    pub fn coding_capabilities(self) -> Self {
        let ws = self
            .workspace_dir
            .clone()
            .unwrap_or_else(|| PathBuf::from("."));
        self.capabilities(CapabilitySet::coding(ws.to_str().unwrap_or(".")))
    }

    /// Use read-only capabilities.
    pub fn readonly_capabilities(self) -> Self {
        let ws = self
            .workspace_dir
            .clone()
            .unwrap_or_else(|| PathBuf::from("."));
        self.capabilities(CapabilitySet::read_only(ws.to_str().unwrap_or(".")))
    }

    /// Attach an authorizer for capability enforcement.
    pub fn authorizer(mut self, authorizer: Arc<Authorizer>) -> Self {
        self.authorizer = Some(authorizer);
        self
    }

    // ── Observability ──────────────────────────────────────

    /// Attach a tracer for distributed tracing.
    pub fn tracer(mut self, tracer: Arc<Tracer>) -> Self {
        self.tracer = Some(tracer);
        self
    }

    /// Attach an audit log for security and tool audit trail.
    pub fn audit_log(mut self, audit: Arc<AuditLog>) -> Self {
        self.audit_log = Some(audit);
        self
    }

    /// Attach a cost tracker for token and cost monitoring.
    pub fn cost_tracker(mut self, tracker: Arc<CostTracker>) -> Self {
        self.cost_tracker = Some(tracker);
        self
    }

    // ── Middleware ─────────────────────────────────────────

    /// Add a middleware to the pipeline.
    pub fn middleware(mut self, mw: impl Middleware + 'static) -> Self {
        self.middlewares.push(Arc::new(mw));
        self
    }

    /// Add a rate limit middleware (convenience shortcut).
    pub fn with_rate_limit(self, max_per_minute: usize) -> Self {
        self.middleware(crate::middleware::RateLimitMiddleware::new(max_per_minute))
    }

    /// Add a token budget middleware (convenience shortcut).
    pub fn with_token_budget(self, max_tokens: usize) -> Self {
        self.middleware(crate::middleware::TokenBudgetMiddleware::new(max_tokens))
    }

    /// Add a logging middleware (convenience shortcut).
    pub fn with_logging(self) -> Self {
        self.middleware(crate::middleware::LoggingMiddleware::new(
            tracing::Level::INFO,
        ))
    }

    /// Build the agent.
    ///
    /// Uses the Oxi engine's `ProviderResolver` for isolated provider/model
    /// lookups, so `switch_model()` and compaction stay within the engine's
    /// registry — no global state pollution.
    pub fn build(self) -> anyhow::Result<Agent> {
        // 1. Resolve model from Oxi's instance registry
        let model = self.oxi.resolve_model(&self.config.model_id)?;

        // 2. Create provider via Oxi's engine (custom → built-in fallback)
        let provider: Arc<dyn oxi_ai::Provider> = self.oxi.create_provider(&model.provider)?;

        // 3. Merge workspace_dir into config
        let mut config = self.config.clone();
        config.workspace_dir = self.workspace_dir.or(config.workspace_dir);
        if let Some(ref prompt) = self.system_prompt {
            config.system_prompt = Some(prompt.clone());
        }

        // 4. Create resolver that captures Oxi's resolution functions
        let oxi_providers = self.oxi.providers_arc();
        let oxi_models = self.oxi.models_arc();
        let include_builtins = self.oxi.has_builtins();

        let resolver: Arc<dyn ProviderResolver> = Arc::new(OxiResolver {
            oxi: Arc::new(OxiCore {
                resolve_provider_fn: Box::new(move |name: &str| {
                    // Custom providers first
                    if let Some(p) = oxi_providers.get_custom(name) {
                        return Some(p);
                    }
                    // Built-in fallback
                    if include_builtins && let Some(p) = oxi_ai::create_builtin_provider(name) {
                        return Some(Arc::from(p));
                    }
                    None
                }),
                resolve_model_fn: Box::new(move |model_id: &str| {
                    let parts: Vec<&str> = model_id.splitn(2, '/').collect();
                    let (provider, model) = if parts.len() == 2 {
                        (parts[0], parts[1])
                    } else {
                        ("anthropic", parts[0])
                    };
                    oxi_models.lookup(provider, model)
                }),
            }),
        });

        // 5. Create agent with the isolated resolver
        let agent = Agent::new_with_resolver(provider, config, Arc::new(self.tools), resolver);

        // 6. Authorizer: grant capabilities.
        //
        // The authorizer middleware (`AuthorizerMiddleware`) checks
        // `Capability::ToolUse { tool_name }` against the granted
        // capabilities — type-specific, no cross-variant
        // implication. Without a `ToolUse` grant, every tool
        // call would be denied by the middleware regardless of
        // whether the agent has fine-grained FileRead/Bash caps.
        //
        // Coarse-grant fallback: when the granted capability set
        // contains no `ToolUse` variant, auto-add a wildcard
        // `ToolUse { tool_name: "*" }`. This makes the SDK's
        // authorizer integration usable out of the box with
        // `CapabilitySet::coding()` / `read_only()` / `research()` /
        // `browser()` (none of which contain `ToolUse`).
        //
        // Fine-grained enforcement (command/path restrictions)
        // would require tool-specific arg parsing inside the
        // middleware to derive `Bash`/`FileRead` capabilities
        // from the call's JSON args. That's a follow-up; see
        // design doc at
        // docs/designs/2026-06-30-observability-wiring.md.
        if let Some(authorizer) = &self.authorizer {
            let agent_id = resolved_agent_id(&agent);
            if let Some(mut caps) = self.capabilities.clone() {
                let has_tool_use = caps
                    .capabilities()
                    .iter()
                    .any(|c| matches!(c, crate::security::Capability::ToolUse { .. }));
                if !has_tool_use {
                    caps.add(crate::security::Capability::ToolUse {
                        tool_name: "*".into(),
                    });
                }
                let subject = crate::security::CapabilitySubject::Agent(agent_id);
                authorizer.grant(subject, caps);
            }
        }

        // 7. Build a single unified middleware pipeline that includes
        //    user middlewares, the audit-log adapter, and the
        //    authorizer adapter. Order matters: audit fires FIRST
        //    (records all attempts), authorizer fires SECOND (denies
        //    if needed — short-circuits before user mws run), user
        //    middlewares fire LAST.
        //
        //    The pipeline is wrapped into AgentHooks via
        //    `build_hooks` once, so `set_hooks()` is called exactly
        //    once. This avoids the replace-semantics bug class
        //    documented in docs/audits/2026-06-30-sdk-coverage.md
        //    Gap-0 ("observability silently overwritten when
        //    composes with user middlewares").
        let has_observability_mws = self.audit_log.is_some() || self.authorizer.is_some();
        let has_user_mws = !self.middlewares.is_empty();
        if has_user_mws || has_observability_mws {
            let agent_id = resolved_agent_id(&agent);
            let mut pipeline = MiddlewarePipeline::new();

            // Audit fires first so every attempt (allowed or denied) is logged.
            if let Some(audit) = &self.audit_log {
                pipeline = pipeline.add_arc(Arc::new(
                    crate::middleware::observability_adapters::AuditLogMiddleware::new(
                        Arc::clone(audit),
                        agent_id.clone(),
                    ),
                ));
            }

            // Authorizer fires second — its denial short-circuits the
            // pipeline via `MiddlewareAction::Block`, which the
            // existing bridge maps to `BeforeToolCallResult { block: true }`.
            if let Some(authorizer) = &self.authorizer {
                let mut mw = crate::middleware::observability_adapters::AuthorizerMiddleware::new(
                    Arc::clone(authorizer),
                    agent_id.clone(),
                );
                if let Some(audit) = &self.audit_log {
                    mw = mw.with_audit(Arc::clone(audit));
                }
                pipeline = pipeline.add_arc(Arc::new(mw));
            }

            // User middlewares fire last so audit/auth observe their
            // calls and Authorizer denials short-circuit before them.
            for mw in self.middlewares.into_iter() {
                pipeline = pipeline.add_arc(mw);
            }

            let pipeline = Arc::new(pipeline);
            let terminate_flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
            let hooks = crate::middleware::build_hooks(pipeline, agent_id, terminate_flag);
            agent.set_hooks(hooks);
        }

        // 8. CostTracker → event-tap path (accumulate, not replace).
        //    Tracer is intentionally deferred — see the doc comment on
        //    `install_observability_dispatch` below for the SpanGuard
        //    lifetime root cause and the deferred-fix plan.
        if let Some(ct) = self.cost_tracker.clone() {
            install_observability_dispatch(&agent, Some(ct));
        }

        Ok(agent)
    }
}

/// Synthesize a stable agent id used as the principal in capability
/// grants, audit-log entries, and observability dispatch. Matches the
/// existing behavior at agent_builder.rs:443-447 (synthesize a UUID
/// only when the config name is empty).
fn resolved_agent_id(agent: &Agent) -> String {
    let cfg = agent.get_config();
    if cfg.name.is_empty() {
        uuid::Uuid::new_v4().to_string()
    } else {
        cfg.name
    }
}

/// Build the event-tap closure that drives CostTracker from the agent's
/// `AgentEvent::Usage` events.
///
/// **Scope: CostTracker ONLY.** Tracer span instrumentation is deferred.
/// The existing `Tracer::start` returns `SpanGuard<'a>` that borrows the
/// `Tracer` and is not `Send + 'static`, which would force an unsafe
/// block to thread through the dispatch closure (the closure is
/// `Fn(AgentEvent) + Send + Sync + 'static`). The proper fix is to
/// change `SpanGuard` to own an `Arc<Tracer>` reference so the guard
/// itself is `'static + Send` — that's a separate `oxi-sdk` design
/// change tracked against the audit's Gap-0 follow-up. Until that
/// lands, `.tracer(...)` on `AgentBuilder` silently does nothing.
///
/// CostTracker / Authorizer / AuditLog ARE all wired correctly and
/// produce runtime effect.
fn install_observability_dispatch(
    agent: &Agent,
    cost_tracker: Option<Arc<crate::observability::CostTracker>>,
) {
    use crate::observability::TokenUsage;
    use oxi_agent::AgentEvent;

    let cost_tracker = match cost_tracker {
        Some(c) => c,
        None => return,
    };
    // Use the same resolved agent_id as the middleware path so
    // AuditLog / Authorizer / CostTracker observations all key
    // by the same principal. Without this, a user-supplied
    // AgentConfig with `name: ""` would create a divergence:
    // `resolved_agent_id` falls back to a UUID for the
    // middleware grants, but `agent.get_config().name`
    // is the empty string — CostTracker would record under
    // `""` while Authorizer grants under the UUID.
    let agent_id = resolved_agent_id(agent);
    let resolver = agent.resolver().clone();
    let model_id = agent.get_config().model_id;
    agent.add_observability_dispatch(move |event: AgentEvent| {
        if let AgentEvent::Usage {
            input_tokens,
            output_tokens,
        } = event
        {
            let model = resolver.resolve_model(&model_id);
            if let Some(m) = model {
                cost_tracker.record(
                    &agent_id,
                    &m,
                    TokenUsage {
                        input: input_tokens as u64,
                        output: output_tokens as u64,
                        cache_read: 0,
                        cache_write: 0,
                    },
                );
            }
        }
    });
}