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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
//! 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};
/// 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. Use Oxi directly as the resolver. Oxi implements ProviderResolver
// with catalog→static model resolution (builder.rs:106-123) and
// credential-aware provider creation (builder.rs:131-148).
//
// The previous hand-rolled OxiResolver/OxiCore closure only
// consulted the static ModelRegistry via lookup(), silently
// dropping the catalog port — so catalog-known models (e.g.
// newer Z.AI models from models.dev) resolved at build() time
// via Oxi::resolve_model but failed inside the agent loop's
// own resolve_model(), causing "Failed to resolve model" at
// stream time.
let resolver: Arc<dyn ProviderResolver> = Arc::new(self.oxi.clone());
// 4b. Capability gate: drop the `lsp` tool when no `LspProvider`
// is configured on the agent config. This avoids the
// "LSP not configured" runtime error path entirely — the
// tool simply isn't visible to the model when LSP is off.
// See docs/designs/2026-07-18-stub-completion.md §4.3.
if config.lsp.is_none() {
self.tools.unregister("lsp");
}
// 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. Tracer and CostTracker → event-tap path (accumulate, not replace).
if self.tracer.is_some() || self.cost_tracker.is_some() {
install_observability_dispatch(&agent, self.tracer.clone(), self.cost_tracker.clone());
}
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 records short lifecycle spans and drives
/// `CostTracker` from the agent's emitted events.
fn install_observability_dispatch(
agent: &Agent,
tracer: Option<Arc<Tracer>>,
cost_tracker: Option<Arc<crate::observability::CostTracker>>,
) {
use crate::observability::{SpanKind, TokenUsage};
use oxi_agent::AgentEvent;
if tracer.is_none() && cost_tracker.is_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| match event {
AgentEvent::AgentStart {
prompts,
session_id,
} => {
if let Some(tracer) = &tracer {
let mut span = tracer.start("run", SpanKind::Agent);
span.set_attribute("agent.id", serde_json::json!(agent_id));
span.set_attribute("model.id", serde_json::json!(model_id));
span.set_attribute("prompt.count", serde_json::json!(prompts.len()));
if let Some(session_id) = session_id {
span.set_attribute("session.id", serde_json::json!(session_id));
}
}
}
AgentEvent::TurnStart { turn_number } => {
if let Some(tracer) = &tracer {
let mut span = tracer.start("turn_start", SpanKind::Agent);
span.set_attribute("turn.number", serde_json::json!(turn_number));
}
}
AgentEvent::TurnEnd {
turn_number,
tool_results,
..
} => {
if let Some(tracer) = &tracer {
let mut span = tracer.start("turn_end", SpanKind::Agent);
span.set_attribute("turn.number", serde_json::json!(turn_number));
span.set_attribute("tool.result.count", serde_json::json!(tool_results.len()));
}
}
AgentEvent::ToolExecutionStart {
tool_call_id,
tool_name,
..
} => {
if let Some(tracer) = &tracer {
let mut span = tracer.start("tool_start", SpanKind::Tool);
span.set_attribute("tool.call.id", serde_json::json!(tool_call_id));
span.set_attribute("tool.name", serde_json::json!(tool_name));
}
}
AgentEvent::ToolExecutionEnd {
tool_call_id,
tool_name,
is_error,
..
} => {
if let Some(tracer) = &tracer {
let mut span = tracer.start("tool_end", SpanKind::Tool);
span.set_attribute("tool.call.id", serde_json::json!(tool_call_id));
span.set_attribute("tool.name", serde_json::json!(tool_name));
span.set_attribute("error", serde_json::json!(is_error));
if is_error {
span.set_error("tool execution failed");
}
}
}
AgentEvent::Usage {
input_tokens,
output_tokens,
} => {
let Some(cost_tracker) = &cost_tracker else {
return;
};
if let Some(model) = resolver.resolve_model(&model_id) {
cost_tracker.record(
&agent_id,
&model,
TokenUsage {
input: input_tokens as u64,
output: output_tokens as u64,
cache_read: 0,
cache_write: 0,
},
);
}
}
_ => {}
});
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ports::catalog::{
CatalogEvent, CatalogModelEntry, CatalogProtocol, CatalogSource, ModelCatalog,
};
use crate::{OxiBuilder, SdkResult};
use std::future::Future;
use std::pin::Pin;
use tokio::sync::broadcast;
/// Minimal catalog with a single model that exists ONLY in the catalog
/// port — not in the static ModelRegistry. This reproduces the desync
/// where `Oxi::resolve_model()` (catalog→static) finds the model but
/// the old `OxiResolver`'s `lookup()` (static-only) did not.
struct SingleModelCatalog {
entry: CatalogModelEntry,
tx: broadcast::Sender<CatalogEvent>,
}
impl std::fmt::Debug for SingleModelCatalog {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SingleModelCatalog").finish_non_exhaustive()
}
}
impl ModelCatalog for SingleModelCatalog {
fn list_providers(
&self,
) -> Pin<Box<dyn Future<Output = SdkResult<Vec<String>>> + Send + '_>> {
let p = self.entry.provider.clone();
Box::pin(async move { Ok(vec![p]) })
}
fn get_provider(
&self,
_: &str,
) -> Pin<
Box<
dyn Future<Output = SdkResult<Option<crate::ports::catalog::CatalogProviderEntry>>>
+ Send
+ '_,
>,
> {
Box::pin(async { Ok(None) })
}
fn list_models(
&self,
_: &str,
) -> Pin<Box<dyn Future<Output = SdkResult<Vec<CatalogModelEntry>>> + Send + '_>> {
let e = self.entry.clone();
Box::pin(async move { Ok(vec![e]) })
}
fn get_model(
&self,
provider: &str,
model_id: &str,
) -> Pin<Box<dyn Future<Output = SdkResult<Option<CatalogModelEntry>>> + Send + '_>>
{
let hit = self.get_model_sync(provider, model_id);
Box::pin(async move { Ok(hit) })
}
fn search(
&self,
_: &str,
) -> Pin<Box<dyn Future<Output = SdkResult<Vec<CatalogModelEntry>>> + Send + '_>> {
let e = self.entry.clone();
Box::pin(async move { Ok(vec![e]) })
}
fn model_count(&self) -> Pin<Box<dyn Future<Output = SdkResult<usize>> + Send + '_>> {
Box::pin(async { Ok(1) })
}
fn refresh(
&self,
) -> Pin<
Box<dyn Future<Output = SdkResult<crate::ports::catalog::RefreshOutcome>> + Send + '_>,
> {
Box::pin(async { Ok(crate::ports::catalog::RefreshOutcome::Unchanged) })
}
fn subscribe(&self) -> broadcast::Receiver<CatalogEvent> {
self.tx.subscribe()
}
// ── Sync overrides ──
fn get_model_sync(&self, provider: &str, model_id: &str) -> Option<CatalogModelEntry> {
if provider == self.entry.provider && model_id == self.entry.model_id {
Some(self.entry.clone())
} else {
None
}
}
}
/// Regression: AgentBuilder must wire the catalog-aware `Oxi` as the
/// agent loop's resolver, not a static-only closure.
///
/// Pre-fix, the resolver consulted only the static `ModelRegistry`
/// via `lookup()`, silently dropping the catalog port. Catalog-known
/// models (e.g. newer Z.AI models from models.dev) resolved at
/// `build()` time via `Oxi::resolve_model` but failed inside the
/// agent loop's `resolve_model()` → "Failed to resolve model".
#[test]
fn agent_builder_resolver_consults_catalog() {
const MODEL_ID: &str = "anthropic/test-catalog-only-model";
let catalog = Arc::new(SingleModelCatalog {
entry: CatalogModelEntry {
provider: "anthropic".into(),
model_id: "test-catalog-only-model".into(),
name: "Test Catalog-Only Model".into(),
protocol: CatalogProtocol::AnthropicMessages,
source: CatalogSource::Embedded,
base_url: None,
reasoning: false,
supports_vision: false,
cost_input: 0.0,
cost_output: 0.0,
cost_cache_read: 0.0,
cost_cache_write: 0.0,
context_window: 200_000,
max_tokens: 8_192,
input_modalities: vec!["text".into()],
release_date: None,
status: Some("ga".into()),
},
tx: broadcast::channel(16).0,
});
let oxi = OxiBuilder::new()
.with_builtins()
.with_catalog(catalog)
.build();
// Sanity: model resolves via Oxi (catalog→static).
assert!(oxi.resolve_model(MODEL_ID).is_ok());
// Sanity: model is NOT in the static registry (proves the desync).
assert!(
oxi.models_arc()
.lookup("anthropic", "test-catalog-only-model")
.is_none()
);
// Build an agent with the catalog-only model.
let config = AgentConfig {
model_id: MODEL_ID.to_string(),
..Default::default()
};
let agent = oxi.agent(config).build().unwrap();
// THE REGRESSION: the agent's loop resolver must also find the
// catalog-only model.
// Pre-fix (OxiResolver): lookup() → None.
// Post-fix (Oxi clone): resolve_model() → catalog hit → Some.
assert!(
agent.resolver().resolve_model(MODEL_ID).is_some(),
"AgentBuilder's resolver must consult the catalog port, \
not just the static registry"
);
}
}