Skip to main content

arbor_core/usages/
mod.rs

1//! SDK usage extraction: where a file talks to an LLM provider's SDK.
2//!
3//! The call graph drops calls whose target is not defined in the project, so
4//! it cannot answer "which lines call OpenAI, and with which model?". This
5//! module answers that per file, from the same tree-sitter tree
6//! [`crate::parse_source`] builds. It is separate from graph extraction: it
7//! adds no nodes or edges and does not change the cached node schema.
8//!
9//! # What a file reports
10//!
11//! [`FileUsages`] holds four lists:
12//!
13//! - [`SdkImport`]: each local name bound to a tracked SDK
14//!   (`import openai as oa`, `from anthropic import AsyncAnthropic`,
15//!   `from google import genai`).
16//! - [`ClientConstruction`]: each client built from a tracked constructor,
17//!   with its [`Routing`] decided from the constructor and its keyword
18//!   arguments (`AzureOpenAI(...)` is `azure_openai`; `OpenAI(base_url=...)`
19//!   is `custom_base_url` unless the URL is the provider's own host).
20//! - [`SdkCall`]: each call whose member chain is rooted at a tracked binding
21//!   (`client.chat.completions.create`, `openai.ChatCompletion.create`,
22//!   `self.client.messages.create`, `genai.GenerativeModel(...)`). A call
23//!   records keyword-argument *names* only. A *value* is captured only for
24//!   the keys in [`VALUE_KEYS`] (as keyword arguments, as keys of a dict
25//!   literal passed to the call or expanded with `**`), only when it is a
26//!   string literal or a same-file constant that resolves to one.
27//! - [`UsageGap`]: everything the extractor saw but could not resolve. A gap
28//!   is never a silent drop: a model passed from the environment, a client
29//!   from an unknown factory, `getattr` dispatch, or an ambiguous client each
30//!   get a typed record. A model read from the environment or a config
31//!   lookup with a literal fallback (`os.getenv("MODEL", "gpt-4o")`) is both:
32//!   the fallback is captured with origin [`ValueOrigin::EnvDefault`] and the
33//!   call keeps its gap, because the deployed value may differ.
34//!
35//! A value or route with no gap is confirmed only inside a small supported
36//! grammar; everything outside it, and anything a dynamic feature of the file
37//! (`exec`, `globals()`, `setattr` with a run-time name, a class decorator,
38//! ...) may change, keeps a gap. `docs/SDK_USAGES.md` states the grammar, the
39//! dynamic features and the bounds.
40//!
41//! # Credentials
42//!
43//! No credential value is ever captured. A value is refused when any name it
44//! flows through matches [`is_secret_key`] (the keyword, a constant, a
45//! parameter, a `self.attr`, any name in an attribute chain such as
46//! `ApiKeys.openai`, a dict key or an environment variable name), when the
47//! value itself is credential-shaped ([`is_credential_value`]: `sk-`,
48//! `sk-ant-`, `AIza`, `ghp_`, `xox...`, URLs with user information, long
49//! random tokens), and dict
50//! key paths are built only from identifier-shaped keys
51//! ([`is_identifier_key`]). A refused value at a request is an
52//! `unresolved_model` gap with reason `credential`; the gap names the
53//! binding, never the value.
54//!
55//! Positions are [`Span`]s: 1-based lines and 1-based columns counted in
56//! Unicode scalar values, plus 0-based UTF-8 byte offsets for rewriting. A
57//! consumer that needs another column unit (UTF-16 for JS editors) should
58//! derive it from the byte offsets.
59//!
60//! # Scope of this version
61//!
62//! Python only ([`python`]): `.py` files and extensionless scripts with a
63//! Python shebang. The TypeScript/ESM slice will implement
64//! [`crate::LanguageParser::extract_usages`] for its parsers and reuse these
65//! types. Resolution is per file: a client or model constant imported from
66//! another module is a gap, not a usage.
67
68pub mod python;
69
70use serde::{Deserialize, Serialize};
71
72/// A provider whose SDK is tracked.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
74#[serde(rename_all = "lowercase")]
75pub enum Sdk {
76    /// `openai` (v0 module API and v1 clients).
77    Openai,
78    /// `anthropic`.
79    Anthropic,
80    /// `google.genai` and the legacy `google.generativeai`.
81    Google,
82}
83
84impl Sdk {
85    /// Every tracked provider, in display order.
86    pub const ALL: [Sdk; 3] = [Sdk::Openai, Sdk::Anthropic, Sdk::Google];
87
88    /// The lowercase name used in JSON and on the command line.
89    pub fn as_str(self) -> &'static str {
90        match self {
91            Sdk::Openai => "openai",
92            Sdk::Anthropic => "anthropic",
93            Sdk::Google => "google",
94        }
95    }
96
97    /// Parses `openai`, `anthropic` or `google` (case-insensitive).
98    pub fn parse(name: &str) -> Option<Sdk> {
99        match name.trim().to_ascii_lowercase().as_str() {
100            "openai" => Some(Sdk::Openai),
101            "anthropic" => Some(Sdk::Anthropic),
102            "google" | "gemini" => Some(Sdk::Google),
103            _ => None,
104        }
105    }
106}
107
108impl std::fmt::Display for Sdk {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        f.write_str(self.as_str())
111    }
112}
113
114/// Where a client's requests go, decided from its constructor and keyword
115/// argument names. A provider's model retirement date applies only to the
116/// `*_direct` routes and Google's own APIs.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
118#[serde(rename_all = "snake_case")]
119pub enum Routing {
120    /// `OpenAI()` / `AsyncOpenAI()` with no `base_url`, or the module-level API.
121    OpenaiDirect,
122    /// `AzureOpenAI` / `AsyncAzureOpenAI`, or `openai.api_type = "azure"`.
123    AzureOpenai,
124    /// A client given a `base_url` / `api_base` whose host is not the
125    /// provider's own (OpenRouter, LiteLLM, a local server), or a
126    /// module-level `openai.api_base` / `base_url` set that way. A `base_url`
127    /// of `api.openai.com` or `api.anthropic.com` is direct.
128    CustomBaseUrl,
129    /// `Anthropic()` / `AsyncAnthropic()` with no `base_url`.
130    AnthropicDirect,
131    /// `AnthropicBedrock` / `AsyncAnthropicBedrock`.
132    AnthropicBedrock,
133    /// `AnthropicVertex` / `AsyncAnthropicVertex`.
134    AnthropicVertex,
135    /// `google.genai.Client`.
136    GoogleGenai,
137    /// `google.generativeai` (the deprecated SDK).
138    GoogleGenerativeaiLegacy,
139    /// Not decided by this version: `**kwargs` passed to a direct
140    /// constructor, a client typed only by annotation, a binding assigned
141    /// more than one kind of client, a direct client given a `base_url`
142    /// after it is built or built in a file that sets `OPENAI_BASE_URL` /
143    /// `ANTHROPIC_BASE_URL` or writes the environment with a run-time name,
144    /// a `base_url` read from the environment with no fallback or one that
145    /// does not resolve to a string (each with an `ambiguous_client` gap at
146    /// each call), a non-literal or non-Azure
147    /// `openai.api_type`, or a hosted-platform client this list does not name
148    /// (`BedrockOpenAI`, `OpenAI(provider=...)`, `AnthropicAWS`,
149    /// `AnthropicFoundry`, `AnthropicGoogleCloud` and their async variants).
150    /// The construction's `constructor` field still names the class.
151    Unknown,
152}
153
154impl Routing {
155    /// The snake_case name used in JSON.
156    pub fn as_str(self) -> &'static str {
157        match self {
158            Routing::OpenaiDirect => "openai_direct",
159            Routing::AzureOpenai => "azure_openai",
160            Routing::CustomBaseUrl => "custom_base_url",
161            Routing::AnthropicDirect => "anthropic_direct",
162            Routing::AnthropicBedrock => "anthropic_bedrock",
163            Routing::AnthropicVertex => "anthropic_vertex",
164            Routing::GoogleGenai => "google_genai",
165            Routing::GoogleGenerativeaiLegacy => "google_generativeai_legacy",
166            Routing::Unknown => "unknown",
167        }
168    }
169}
170
171impl std::fmt::Display for Routing {
172    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        f.write_str(self.as_str())
174    }
175}
176
177/// A source range. Lines and columns are 1-based; columns count Unicode
178/// scalar values. Bytes are 0-based UTF-8 offsets, end exclusive.
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
180pub struct Span {
181    pub line: u32,
182    pub column: u32,
183    pub end_line: u32,
184    pub end_column: u32,
185    pub start_byte: u32,
186    pub end_byte: u32,
187}
188
189/// What an imported SDK name is.
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
191#[serde(rename_all = "snake_case")]
192pub enum BindingKind {
193    /// A module or package (`import openai`, `from google import genai`).
194    Module,
195    /// A client constructor (`OpenAI`, `AnthropicBedrock`, `GenerativeModel`).
196    ClientClass,
197    /// Any other imported name (`ChatCompletion`, `types`, `HUMAN_PROMPT`).
198    Symbol,
199}
200
201/// A local name bound to a tracked SDK.
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203pub struct SdkImport {
204    pub sdk: Sdk,
205    /// `openai`, `anthropic`, `google.genai` or `google.generativeai`.
206    pub package: String,
207    /// The module named in the statement (`openai.types.chat`).
208    pub module: String,
209    /// The imported name for `from m import name`; `None` for `import m`.
210    pub name: Option<String>,
211    /// The name the file uses (`genai`, `OA`).
212    pub local: String,
213    pub kind: BindingKind,
214    pub file: String,
215    pub span: Span,
216}
217
218/// How a constructed client is held.
219#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
220#[serde(rename_all = "snake_case")]
221pub enum ClientScope {
222    /// A module-level name (including a `global` assigned in a function).
223    Module,
224    /// A function-local name.
225    Local,
226    /// A class-body attribute (`class Bot: client = OpenAI()`).
227    Class,
228    /// An instance attribute (`self.client = OpenAI()`).
229    Attribute,
230    /// Not bound to a name: passed, returned or chained directly.
231    Inline,
232}
233
234/// A client built from a tracked constructor.
235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
236pub struct ClientConstruction {
237    pub sdk: Sdk,
238    pub package: String,
239    /// Package-qualified constructor (`openai.AzureOpenAI`).
240    pub constructor: String,
241    /// The constructor as written, arguments elided (`oa.AzureOpenAI`).
242    pub chain: String,
243    /// The binding it is assigned to (`client`, `self.client`), if any.
244    pub binding: Option<String>,
245    pub scope: ClientScope,
246    pub routing: Routing,
247    pub is_async: bool,
248    /// Keyword argument names, in source order. Values are never recorded.
249    pub kwargs: Vec<String>,
250    /// Whether `**kwargs` was passed (routing may then be `unknown`).
251    pub splat: bool,
252    pub file: String,
253    pub span: Span,
254    /// Enclosing function or method (`Bot.__init__`), `None` at module level.
255    pub symbol: Option<String>,
256    /// For `google.genai.Client(vertexai=...)`: how the argument reads.
257    /// Only this class is recorded, never the expression. `None` when the
258    /// constructor passes no `vertexai=`.
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub vertexai: Option<VertexAi>,
261}
262
263/// How a `google.genai.Client(vertexai=...)` argument reads. The Gemini API
264/// and Vertex AI retire models on different schedules.
265#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
266#[serde(rename_all = "snake_case")]
267pub enum VertexAi {
268    /// `vertexai=True`: requests go to Vertex AI.
269    On,
270    /// `vertexai=False` or `vertexai=None`: requests go to the Gemini API.
271    Off,
272    /// Decided at run time (`vertexai=use_vertex`,
273    /// `vertexai=os.getenv(...) == "true"`).
274    Unknown,
275}
276
277/// What a call's chain is rooted at.
278#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
279#[serde(rename_all = "snake_case")]
280pub enum Receiver {
281    /// The SDK module itself (`openai.ChatCompletion.create`).
282    Module,
283    /// A constructed or annotated client (`client.chat.completions.create`).
284    Client,
285    /// A client constructor or other imported name (`genai.GenerativeModel`,
286    /// `ChatCompletion.create` after `from openai import ChatCompletion`).
287    Symbol,
288}
289
290/// Where a captured value came from.
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
292#[serde(rename_all = "snake_case")]
293pub enum ValueOrigin {
294    /// A string literal at the call.
295    Literal,
296    /// A module-level name assigned exactly one string literal.
297    ModuleConstant,
298    /// A class attribute (`MODEL = ...` in the class body, or a single
299    /// `self.model = "..."`) assigned exactly one string literal.
300    ClassConstant,
301    /// A function-local name assigned exactly one string literal.
302    LocalConstant,
303    /// The default of the enclosing function's parameter: a literal or a
304    /// same-file constant (`def ask(model=GPT_MODEL)`). Callers may pass
305    /// another value. With no gap only when every call of the function is in
306    /// this file and none passes another value; otherwise the call also
307    /// carries an `unresolved_model` gap: `parameter_overridden` (listing the
308    /// values in-file callers pass), `unseen_callers` (some calls cannot be
309    /// seen) or `parameter_default` (a public function another module may
310    /// call).
311    ParameterDefault,
312    /// The literal fallback of an environment or configuration lookup:
313    /// `os.getenv("MODEL", "gpt-4o")`, `os.environ.get(...)`,
314    /// `config("MODEL", default=...)` (python-decouple, django-environ),
315    /// `settings.get("model", "gpt-4o")`, `getattr(cfg, "model", "gpt-4o")`
316    /// or `os.getenv("MODEL") or "gpt-4o"`. The deployed value may differ, so
317    /// the call also carries an `unresolved_model` gap: confirm before
318    /// acting on it.
319    EnvDefault,
320}
321
322impl ValueOrigin {
323    /// The snake_case name used in JSON.
324    pub fn as_str(self) -> &'static str {
325        match self {
326            ValueOrigin::Literal => "literal",
327            ValueOrigin::ModuleConstant => "module_constant",
328            ValueOrigin::ClassConstant => "class_constant",
329            ValueOrigin::LocalConstant => "local_constant",
330            ValueOrigin::ParameterDefault => "parameter_default",
331            ValueOrigin::EnvDefault => "env_default",
332        }
333    }
334}
335
336/// A value captured for an allowlisted key ([`VALUE_KEYS`]).
337#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
338pub struct CapturedValue {
339    /// `model`, `engine`, `deployment_id` or `model_name`; for a key inside a
340    /// dict literal argument, the path to it (`fallbacks.model` for
341    /// `fallbacks=[{"model": ...}]`, `model` when the dict is positional or
342    /// expanded with `**`). Every segment is an identifier-shaped key.
343    pub key: String,
344    pub value: String,
345    pub origin: ValueOrigin,
346    /// The constant or parameter name when the value is not written inline
347    /// (`MODEL`, `self.model`, `MODELS["fast"]`, `model` for a parameter
348    /// default).
349    pub name: Option<String>,
350    /// The value was passed by position rather than by name: the call's
351    /// first positional argument (`GenerativeModel("gemini-pro")`, legacy
352    /// `genai.embed_content(...)`) or a key of a dict literal passed
353    /// positionally. It describes how the call is written, not the SDK
354    /// signature. In a language whose SDK methods take one options object
355    /// (TypeScript `create({ model })`), that object's properties are by
356    /// name: `false`.
357    pub positional: bool,
358    /// The span of the string literal itself, at its definition.
359    pub span: Span,
360    /// Which provider's model-ID shape the value matches, if any.
361    pub model_family: Option<Sdk>,
362}
363
364/// A call whose member chain is rooted at a tracked binding.
365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
366pub struct SdkCall {
367    pub sdk: Sdk,
368    pub package: String,
369    /// The callee as written, arguments elided
370    /// (`self.client.chat.completions.create`).
371    pub chain: String,
372    /// The part after the tracked root (`chat.completions.create`), with the
373    /// response wrappers `with_raw_response` / `with_streaming_response` and
374    /// client copies (`with_options(...)`, `copy(...)`) removed.
375    pub member: String,
376    /// Whether the call sends a request to the provider: its last member is
377    /// a request method (`create`, `stream`, `generate_content`,
378    /// `send_message`...). `false` for SDK helpers and types
379    /// (`genai.configure`, `GenerativeModel(...)`, `types.Part(...)`,
380    /// `ChatCompletion(...)` built from `openai.types`). A name heuristic.
381    pub request: bool,
382    pub receiver: Receiver,
383    pub routing: Routing,
384    /// Line of the same-file construction the receiver came from, if known.
385    pub client_line: Option<u32>,
386    pub file: String,
387    pub span: Span,
388    pub symbol: Option<String>,
389    /// Argument names in source order: Python keyword arguments, or the
390    /// properties of the options object in a language whose SDK methods
391    /// take one (TypeScript `create({ model, messages })`).
392    pub kwargs: Vec<String>,
393    /// Number of positional arguments, the options object excluded.
394    pub positional: u32,
395    /// Whether arguments were spread into the call (`**kwargs`; TypeScript
396    /// `...opts` in the options object).
397    pub splat: bool,
398    /// Values for allowlisted keys that resolved to string literals.
399    pub values: Vec<CapturedValue>,
400}
401
402/// Why something was reported as a gap instead of a usage.
403#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
404#[serde(rename_all = "snake_case")]
405pub enum GapKind {
406    /// At a request or a model constructor (`GenerativeModel`), an
407    /// allowlisted key's value is not a resolvable string literal
408    /// (environment, config attribute, function call, f-string, parameter,
409    /// `**kwargs`, a name imported from another module...), or a call that
410    /// takes a model passes none (`missing_model`: the SDK or server
411    /// default applies). A value captured next to such a gap is one the code
412    /// names but cannot confirm: an environment fallback, a parameter
413    /// default (`parameter_default`, `parameter_overridden`,
414    /// `unseen_callers`), an attribute a subclass in another module may
415    /// override (`subclass_override`) or a value a dynamic feature of the
416    /// file may change (`dynamic_feature`, which names the feature and its
417    /// line).
418    UnresolvedModel,
419    /// A call shaped like an SDK endpoint whose receiver is not a tracked
420    /// client: built by an unknown factory, passed in as a parameter, or
421    /// imported from another module.
422    UnknownClientFactory,
423    /// A binding assigned more than one kind of client, so routing depends on
424    /// a runtime branch (`multiple_assignments`), or a client known from
425    /// only some of the places it can come from: the in-file callers of a
426    /// function other modules may also call (`in_file_callers`), a client
427    /// whose `base_url` is assigned after it is built (`base_url_assigned`),
428    /// a file that sets the SDK's endpoint variable (`endpoint_env`), a
429    /// `base_url` read from the environment (`base_url_env`) or not resolved
430    /// (`base_url_unresolved`), a Gemini client given an option that may
431    /// send it to Vertex AI or another endpoint (`endpoint_option`), a
432    /// module-level call that passes `engine` or `deployment_id` in a file
433    /// that does not configure the module-level API, or any module-level
434    /// call in a file that configures it outside its top-of-file setup block
435    /// (`module_config`), or a receiver or configuration a dynamic feature of
436    /// the file may change (`dynamic_feature`).
437    AmbiguousClient,
438    /// `getattr` on a tracked binding, or an SDK method stored or passed as a
439    /// value; calls through it are not tracked.
440    DynamicDispatch,
441    /// SDK usage inside a vendored or virtual-environment directory
442    /// (`site-packages`, `venv`, `.venv`, `node_modules`...). Excluded from
443    /// usages and counted as skipped.
444    VendoredPath,
445}
446
447impl GapKind {
448    /// The snake_case name used in JSON.
449    pub fn as_str(self) -> &'static str {
450        match self {
451            GapKind::UnresolvedModel => "unresolved_model",
452            GapKind::UnknownClientFactory => "unknown_client_factory",
453            GapKind::AmbiguousClient => "ambiguous_client",
454            GapKind::DynamicDispatch => "dynamic_dispatch",
455            GapKind::VendoredPath => "vendored_path",
456        }
457    }
458}
459
460impl std::fmt::Display for GapKind {
461    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
462        f.write_str(self.as_str())
463    }
464}
465
466/// Something the extractor saw but could not turn into a confirmed usage.
467#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
468pub struct UsageGap {
469    pub kind: GapKind,
470    /// The provider involved, when known or inferred from the call's shape.
471    pub sdk: Option<Sdk>,
472    pub file: String,
473    /// `None` for a vendored directory.
474    pub span: Option<Span>,
475    pub symbol: Option<String>,
476    /// The callee or expression involved, arguments elided.
477    pub chain: Option<String>,
478    /// For `unresolved_model`: the key whose value did not resolve.
479    pub key: Option<String>,
480    /// A stable short code (`env_var`, `f_string`, `parameter`, `getattr`...).
481    pub reason: String,
482    /// A sentence for people. Never contains a literal value.
483    pub detail: String,
484    /// Allowlisted values seen at an unconfirmed call
485    /// (`unknown_client_factory`), or, for `unresolved_model`, values the key
486    /// may take that are known (what in-file callers pass for a parameter,
487    /// the entries of a dict looked up with a run-time key, the value each
488    /// branch assigns, the items a loop runs over), so it can be triaged.
489    /// Never the call's value. Partial unless [`Self::values_complete`].
490    #[serde(default, skip_serializing_if = "Vec::is_empty")]
491    pub values: Vec<CapturedValue>,
492    /// `values`, together with the value captured for the same key at the
493    /// call (a parameter default, an `env_default` fallback), are every
494    /// value the key can take as far as this file shows. `false` (omitted
495    /// from JSON) whenever the list may be partial: a definition, entry or
496    /// caller did not resolve, some callers cannot be seen, another module
497    /// may call the function, or a limit cut the list.
498    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
499    pub values_complete: bool,
500}
501
502/// Everything one file says about tracked SDKs.
503#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
504pub struct FileUsages {
505    pub file: String,
506    pub language: String,
507    pub imports: Vec<SdkImport>,
508    pub clients: Vec<ClientConstruction>,
509    pub calls: Vec<SdkCall>,
510    pub gaps: Vec<UsageGap>,
511    /// The parser recovered from syntax errors: calls inside the broken
512    /// region may be missing. Set only for files that mention an SDK.
513    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
514    pub syntax_errors: bool,
515}
516
517impl FileUsages {
518    /// An empty record for `file`.
519    pub fn new(file: &str, language: &str) -> Self {
520        Self {
521            file: file.to_string(),
522            language: language.to_string(),
523            ..Self::default()
524        }
525    }
526
527    /// Whether the file reported nothing at all.
528    pub fn is_empty(&self) -> bool {
529        self.imports.is_empty()
530            && self.clients.is_empty()
531            && self.calls.is_empty()
532            && self.gaps.is_empty()
533    }
534
535    /// Keeps only records for `sdk`. Gaps whose provider is unknown are kept.
536    pub fn retain_sdk(&mut self, sdk: Sdk) {
537        self.imports.retain(|i| i.sdk == sdk);
538        self.clients.retain(|c| c.sdk == sdk);
539        self.calls.retain(|c| c.sdk == sdk);
540        self.gaps.retain(|g| g.sdk.is_none_or(|s| s == sdk));
541    }
542}
543
544/// Languages that have a usage extractor.
545pub const USAGE_LANGUAGES: &[&str] = &["python"];
546
547/// File extensions that have a usage extractor. `.pyi` stubs are excluded:
548/// they declare types, they do not make requests. Extensionless scripts are
549/// scanned when [`is_python_shebang`] accepts their first line.
550pub const USAGE_EXTENSIONS: &[&str] = &["py"];
551
552/// Whether files with this extension have a usage extractor.
553pub fn is_usage_extension(extension: &str) -> bool {
554    USAGE_EXTENSIONS
555        .iter()
556        .any(|e| e.eq_ignore_ascii_case(extension))
557}
558
559/// Whether the start of an extensionless file is a Python shebang
560/// (`#!/usr/bin/env python3`, `#!/usr/bin/python3.11`).
561pub fn is_python_shebang(head: &[u8]) -> bool {
562    let Some(rest) = head.strip_prefix(b"#!") else {
563        return false;
564    };
565    let line = rest.split(|b| *b == b'\n').next().unwrap_or_default();
566    String::from_utf8_lossy(line)
567        .split(|c: char| c.is_whitespace() || c == '/')
568        .any(|word| word.starts_with("python"))
569}
570
571/// Keys whose string value may be captured. Every other key is recorded by
572/// name only.
573pub const VALUE_KEYS: &[&str] = &["model", "engine", "deployment_id", "model_name"];
574
575/// Name fragments that mark a credential: `api_key`, `auth_token`,
576/// `client_secret`, `PASSWD`, `db_pwd`, `CREDENTIALS`, `private_pem`...
577const SECRET_NEEDLES: &[&str] = &[
578    "key",
579    "token",
580    "secret",
581    "passw",
582    "passphrase",
583    "pwd",
584    "auth",
585    "cred",
586    "private",
587];
588
589/// Whether `key` may hold a credential. Such a value is never captured,
590/// whatever else is configured.
591pub fn is_secret_key(key: &str) -> bool {
592    let lower = key.to_ascii_lowercase();
593    SECRET_NEEDLES.iter().any(|needle| lower.contains(needle))
594}
595
596/// Whether a value for `key` may be captured.
597pub fn is_value_key(key: &str) -> bool {
598    VALUE_KEYS.contains(&key) && !is_secret_key(key)
599}
600
601/// Whether a dict key may appear in a [`CapturedValue::key`] path: an ASCII
602/// identifier of at most 64 characters that is neither secret-named nor
603/// credential-shaped. A dict under any other key is never descended into.
604pub fn is_identifier_key(key: &str) -> bool {
605    let mut chars = key.chars();
606    let Some(first) = chars.next() else {
607        return false;
608    };
609    key.len() <= 64
610        && (first.is_ascii_alphabetic() || first == '_')
611        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
612        && !is_secret_key(key)
613        && !is_credential_value(key)
614}
615
616/// Prefixes of API keys and tokens (OpenAI, Anthropic, Stripe, Google,
617/// GitHub, Slack, AWS, GitLab, Hugging Face, Replicate, Groq, Perplexity,
618/// NVIDIA, Cerebras), PEM blocks and HTTP authorization values.
619const CREDENTIAL_PREFIXES: &[&str] = &[
620    "sk-",
621    "sk_",
622    "rk_",
623    "pk_live_",
624    "pk_test_",
625    "AIza",
626    "ghp_",
627    "gho_",
628    "ghu_",
629    "ghs_",
630    "ghr_",
631    "github_pat_",
632    "xox",
633    "xapp-",
634    "glpat-",
635    "hf_",
636    "r8_",
637    "gsk_",
638    "pplx-",
639    "nvapi-",
640    "csk-",
641    "-----BEGIN",
642    "Bearer ",
643    "bearer ",
644    "Basic ",
645];
646
647/// Whether a string looks like a credential rather than a model ID: a known
648/// key or token prefix, an AWS key ID, a JWT, a URL with user information
649/// (`postgres://admin:pw@db/prod`, `https://<token>@host`), or a long
650/// random run of alphanumerics (20 or more mixing upper case, lower case
651/// and digits, or 32 or more mixing letters and digits, which covers hex
652/// keys). Model IDs are short words joined by `-`, `.`, `:`, `/` or `@`,
653/// so they do not match.
654pub fn is_credential_value(value: &str) -> bool {
655    let value = value.trim();
656    if CREDENTIAL_PREFIXES.iter().any(|p| value.starts_with(p)) {
657        return true;
658    }
659    if has_url_userinfo(value) {
660        return true;
661    }
662    // An AWS access key ID.
663    if (value.starts_with("AKIA") || value.starts_with("ASIA"))
664        && value.len() == 20
665        && value
666            .chars()
667            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
668    {
669        return true;
670    }
671    // A JWT: base64url segments, the first a JSON header.
672    if value.starts_with("eyJ") && value.matches('.').count() >= 2 {
673        return true;
674    }
675    value
676        .split(|c: char| !c.is_ascii_alphanumeric())
677        .any(|run| {
678            let upper = run.chars().any(|c| c.is_ascii_uppercase());
679            let lower = run.chars().any(|c| c.is_ascii_lowercase());
680            let digit = run.chars().any(|c| c.is_ascii_digit());
681            (run.len() >= 20 && upper && lower && digit)
682                || (run.len() >= 32 && (upper || lower) && digit)
683        })
684}
685
686/// Whether `value` holds a URL whose authority carries user information
687/// (`scheme://user:password@host`, `scheme://token@host`).
688fn has_url_userinfo(value: &str) -> bool {
689    value.match_indices("://").any(|(at, sep)| {
690        let rest = &value[at + sep.len()..];
691        let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
692        authority.contains('@')
693    })
694}
695
696/// Whether a resolved string may be reported as a value: not
697/// credential-shaped, no control or bidirectional-override characters (an
698/// escape sequence must never reach a terminal) and at most 256 bytes.
699pub fn is_capturable_value(value: &str) -> bool {
700    value.len() <= 256 && !value.chars().any(is_unsafe_char) && !is_credential_value(value)
701}
702
703/// Control characters and bidirectional overrides.
704pub fn is_unsafe_char(c: char) -> bool {
705    c.is_control() || matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
706}
707
708/// Which provider's model-ID naming `value` follows, if any.
709///
710/// This is a shape check (`gpt-*`, `o3-mini`, `claude-*`, `gemini-*`...),
711/// not a list of real models. It is applied only to values that reach an
712/// allowlisted key, so a pricing table full of model names reports nothing.
713pub fn model_family(value: &str) -> Option<Sdk> {
714    let lower = value.trim().to_ascii_lowercase();
715    let mut id = lower.as_str();
716    // Fine-tuned ids (`ft:gpt-4o-mini:org::id`) and router prefixes.
717    for prefix in [
718        "ft:",
719        "openai/",
720        "openai.",
721        "models/",
722        "publishers/google/models/",
723    ] {
724        if let Some(rest) = id.strip_prefix(prefix) {
725            id = rest;
726        }
727    }
728
729    // Anthropic: first-party ids, Bedrock ids (with optional region prefix)
730    // and router prefixes.
731    if id.starts_with("claude-")
732        || id.starts_with("anthropic/claude-")
733        || id.contains("anthropic.claude-")
734    {
735        return Some(Sdk::Anthropic);
736    }
737
738    // Google before OpenAI: `text-embedding-004` is Google's, and
739    // `text-embedding-3-small` is OpenAI's.
740    const GOOGLE: &[&str] = &[
741        "gemini-",
742        "gemma-",
743        "text-bison",
744        "chat-bison",
745        "code-bison",
746        "codechat-bison",
747        "text-embedding-00",
748        "text-multilingual-embedding-",
749        "embedding-001",
750        "embedding-gecko",
751        "imagen-",
752        "veo-",
753    ];
754    if GOOGLE.iter().any(|p| id.starts_with(p)) || id == "gemini" {
755        return Some(Sdk::Google);
756    }
757
758    const OPENAI: &[&str] = &[
759        "gpt-",
760        "chatgpt-",
761        "text-davinci-",
762        "text-curie-",
763        "text-babbage-",
764        "text-ada-",
765        "code-davinci-",
766        "code-cushman-",
767        "davinci",
768        "curie",
769        "babbage",
770        "text-embedding-",
771        "text-moderation-",
772        "omni-moderation-",
773        "dall-e-",
774        "whisper-",
775        "tts-",
776        "computer-use-preview",
777        "codex-mini",
778    ];
779    if OPENAI.iter().any(|p| id.starts_with(p)) || id == "ada" || id.starts_with("ada-") {
780        return Some(Sdk::Openai);
781    }
782    // Reasoning models: `o1`, `o3-mini`, `o4-mini-2025-04-16`.
783    let mut chars = id.chars();
784    if chars.next() == Some('o') {
785        let rest: String = chars.collect();
786        let digits = rest.chars().take_while(|c| c.is_ascii_digit()).count();
787        if digits > 0 {
788            let tail = &rest[digits..];
789            if tail.is_empty() || tail.starts_with('-') {
790                return Some(Sdk::Openai);
791            }
792        }
793    }
794    None
795}
796
797#[cfg(test)]
798mod tests {
799    use super::*;
800
801    #[test]
802    fn value_keys_are_never_secret_shaped() {
803        for key in VALUE_KEYS {
804            assert!(!is_secret_key(key), "{key} must not look like a secret");
805            assert!(is_value_key(key));
806        }
807        for key in [
808            "api_key",
809            "API_KEY",
810            "auth_token",
811            "max_tokens",
812            "client_secret",
813            "password",
814            "authorization",
815            "azure_ad_token_provider",
816            "PASSWD",
817            "db_pwd",
818            "credential",
819            "CREDENTIALS",
820            "gcp_cred",
821            "private_pem",
822            "passphrase",
823        ] {
824            assert!(is_secret_key(key), "{key} must be treated as secret");
825            assert!(!is_value_key(key));
826        }
827        assert!(!is_value_key("temperature"));
828    }
829
830    #[test]
831    fn credential_shaped_values_are_refused() {
832        for secret in [
833            "sk-proj-AbCdEf0123456789xyz",
834            "sk-ant-api03-AbCdEf0123456789",
835            "sk-live-SECRET",
836            "sk_live_51H8abc",
837            "AIzaSyD-abcdefghijklmnop",
838            "ghp_0123456789abcdefABCDEF",
839            "xoxb-1234-5678-abcdef",
840            "AKIAIOSFODNN7EXAMPLE",
841            "Bearer abc",
842            "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.sig",
843            "Zx8aB2cD4eF6gH8iJ0kL2mN4",
844            "0123456789abcdef0123456789abcdef",
845            "postgres://admin:hunter2@db/prod",
846            "https://user:pw@gateway.example/v1",
847            "https://tokenvalue@github.com/org/repo",
848        ] {
849            assert!(is_credential_value(secret), "{secret} must be refused");
850            assert!(!is_capturable_value(secret));
851        }
852        for model in [
853            "gpt-4o-2024-08-06",
854            "claude-3-5-sonnet-20241022",
855            "us.anthropic.claude-sonnet-4-5-20250929-v1:0",
856            "ft:gpt-4o-mini-2024-07-18:acme::9xKz3mQp",
857            "models/gemini-1.5-flash-001",
858            "GPT4o-Prod-Deployment-2024",
859            "claude-3-5-sonnet-v2@20241022",
860            "projects/123456789012/locations/us-central1/endpoints/1234567890123456789",
861            "text-embedding-3-small",
862            "o3-mini",
863            "https://openrouter.ai/api/v1",
864            "anthropic/claude-3-opus@latest",
865        ] {
866            assert!(!is_credential_value(model), "{model} is a model ID");
867            assert!(is_capturable_value(model));
868        }
869        assert!(!is_capturable_value("gpt-4\u{1b}]8;;x\u{7}"));
870        assert!(!is_capturable_value("gpt-\u{202E}4"));
871        assert!(!is_capturable_value(&"a".repeat(300)));
872    }
873
874    #[test]
875    fn identifier_keys_only() {
876        for ok in ["model", "fallbacks", "extra_body", "_x1"] {
877            assert!(is_identifier_key(ok), "{ok}");
878        }
879        for bad in [
880            "",
881            "sk-proj-abc",
882            "x-api-key",
883            "api_key",
884            "1model",
885            "has space",
886            "sk_live_abc",
887            "Zx8aB2cD4eF6gH8iJ0kL2mN4",
888        ] {
889            assert!(!is_identifier_key(bad), "{bad}");
890        }
891    }
892
893    #[test]
894    fn python_shebangs() {
895        for yes in [
896            "#!/usr/bin/env python3\nimport openai\n",
897            "#!/usr/bin/python\n",
898            "#! /usr/local/bin/python3.11 -u\n",
899            "#!/usr/bin/env -S python3 -X utf8\n",
900        ] {
901            assert!(is_python_shebang(yes.as_bytes()), "{yes}");
902        }
903        for no in [
904            "#!/bin/sh\n",
905            "import openai\n",
906            "",
907            "#!/usr/bin/env node\n# python\n",
908        ] {
909            assert!(!is_python_shebang(no.as_bytes()), "{no}");
910        }
911    }
912
913    #[test]
914    fn model_family_recognises_shapes() {
915        for (id, sdk) in [
916            ("gpt-3.5-turbo", Sdk::Openai),
917            ("gpt-4o-2024-08-06", Sdk::Openai),
918            ("o1", Sdk::Openai),
919            ("o3-mini", Sdk::Openai),
920            ("o4-mini-2025-04-16", Sdk::Openai),
921            ("text-davinci-003", Sdk::Openai),
922            ("text-embedding-3-small", Sdk::Openai),
923            ("ft:gpt-4o-mini:acme::abc", Sdk::Openai),
924            ("openai/gpt-4", Sdk::Openai),
925            ("openai.gpt-5.4", Sdk::Openai),
926            ("claude-3-5-sonnet-20241022", Sdk::Anthropic),
927            ("anthropic.claude-3-haiku-20240307-v1:0", Sdk::Anthropic),
928            (
929                "us.anthropic.claude-sonnet-4-5-20250929-v1:0",
930                Sdk::Anthropic,
931            ),
932            ("global.anthropic.claude-sonnet-5-5", Sdk::Anthropic),
933            ("gemini-1.5-flash", Sdk::Google),
934            ("models/gemini-pro", Sdk::Google),
935            ("text-embedding-004", Sdk::Google),
936        ] {
937            assert_eq!(model_family(id), Some(sdk), "{id}");
938        }
939        for not_a_model in ["", "my-deployment", "ocean", "o", "orange-1", "hello"] {
940            assert_eq!(model_family(not_a_model), None, "{not_a_model}");
941        }
942    }
943
944    #[test]
945    fn sdk_and_routing_names_round_trip() {
946        for sdk in Sdk::ALL {
947            assert_eq!(Sdk::parse(sdk.as_str()), Some(sdk));
948            let json = serde_json::to_string(&sdk).unwrap();
949            assert_eq!(json, format!("\"{}\"", sdk.as_str()));
950        }
951        assert_eq!(Sdk::parse("Gemini"), Some(Sdk::Google));
952        assert_eq!(Sdk::parse("cohere"), None);
953        for routing in [
954            Routing::OpenaiDirect,
955            Routing::AzureOpenai,
956            Routing::CustomBaseUrl,
957            Routing::AnthropicDirect,
958            Routing::AnthropicBedrock,
959            Routing::AnthropicVertex,
960            Routing::GoogleGenai,
961            Routing::GoogleGenerativeaiLegacy,
962            Routing::Unknown,
963        ] {
964            let json = serde_json::to_string(&routing).unwrap();
965            assert_eq!(json, format!("\"{}\"", routing.as_str()));
966        }
967    }
968}