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 /// Each expression spread into the call with `**`, in source order:
399 /// its name and the argument names it was read to hold. Empty when
400 /// nothing is spread, or when the extractor does not record them.
401 #[serde(default, skip_serializing_if = "Vec::is_empty")]
402 pub spreads: Vec<Spread>,
403 /// Values for allowlisted keys that resolved to string literals.
404 pub values: Vec<CapturedValue>,
405}
406
407/// An expression spread into a call with `**`: names only, never values.
408#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
409pub struct Spread {
410 /// The expression as written, values elided (`PARAMS`, `kwargs`,
411 /// `self.options`). `None` (omitted from JSON) for an expression with no
412 /// name (`{...}` written inline, a conditional) or a credential-named
413 /// one.
414 #[serde(default, skip_serializing_if = "Option::is_none")]
415 pub name: Option<String>,
416 /// The argument names it sends, in source order, read from a dict
417 /// literal in the same file. A literal key is sent whatever an
418 /// unreadable entry next to it holds, so these are listed even when
419 /// [`Self::complete`] is `false`. Names only, secret-sounding ones
420 /// (`max_tokens`, `api_key`) included: a value is never recorded.
421 #[serde(default, skip_serializing_if = "Vec::is_empty")]
422 pub keys: Vec<String>,
423 /// `keys` are every argument it sends: a same-file dict literal with
424 /// only string keys, each recorded, and no `**` of its own, that is
425 /// never changed or passed on later in that file. `false` for a
426 /// parameter (`**kwargs`), an attribute, a dict with a key Arbor does
427 /// not record (not an identifier, or shaped like a credential) or
428 /// anything else Arbor cannot read. Another module that imports the
429 /// dict and changes it is not seen.
430 pub complete: bool,
431}
432
433/// Why something was reported as a gap instead of a usage.
434#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
435#[serde(rename_all = "snake_case")]
436pub enum GapKind {
437 /// At a request or a model constructor (`GenerativeModel`), an
438 /// allowlisted key's value is not a resolvable string literal
439 /// (environment, config attribute, function call, f-string, parameter,
440 /// `**kwargs`, a name imported from another module...), or a call that
441 /// takes a model passes none (`missing_model`: the SDK or server
442 /// default applies). A value captured next to such a gap is one the code
443 /// names but cannot confirm: an environment fallback, a parameter
444 /// default (`parameter_default`, `parameter_overridden`,
445 /// `unseen_callers`), an attribute a subclass in another module may
446 /// override (`subclass_override`) or a value a dynamic feature of the
447 /// file may change (`dynamic_feature`, which names the feature and its
448 /// line).
449 UnresolvedModel,
450 /// A call shaped like an SDK endpoint whose receiver is not a tracked
451 /// client: built by an unknown factory, passed in as a parameter, or
452 /// imported from another module.
453 UnknownClientFactory,
454 /// A binding assigned more than one kind of client, so routing depends on
455 /// a runtime branch (`multiple_assignments`), or a client known from
456 /// only some of the places it can come from: the in-file callers of a
457 /// function other modules may also call (`in_file_callers`), a client
458 /// whose `base_url` is assigned after it is built (`base_url_assigned`),
459 /// a file that sets the SDK's endpoint variable (`endpoint_env`), a
460 /// `base_url` read from the environment (`base_url_env`) or not resolved
461 /// (`base_url_unresolved`), a Gemini client given an option that may
462 /// send it to Vertex AI or another endpoint (`endpoint_option`), a
463 /// module-level call that passes `engine` or `deployment_id` in a file
464 /// that does not configure the module-level API, or any module-level
465 /// call in a file that configures it outside its top-of-file setup block
466 /// (`module_config`), or a receiver or configuration a dynamic feature of
467 /// the file may change (`dynamic_feature`).
468 AmbiguousClient,
469 /// `getattr` on a tracked binding, or an SDK method stored or passed as a
470 /// value; calls through it are not tracked.
471 DynamicDispatch,
472 /// SDK usage inside a vendored or virtual-environment directory
473 /// (`site-packages`, `venv`, `.venv`, `node_modules`...). Excluded from
474 /// usages and counted as skipped.
475 VendoredPath,
476}
477
478impl GapKind {
479 /// The snake_case name used in JSON.
480 pub fn as_str(self) -> &'static str {
481 match self {
482 GapKind::UnresolvedModel => "unresolved_model",
483 GapKind::UnknownClientFactory => "unknown_client_factory",
484 GapKind::AmbiguousClient => "ambiguous_client",
485 GapKind::DynamicDispatch => "dynamic_dispatch",
486 GapKind::VendoredPath => "vendored_path",
487 }
488 }
489}
490
491impl std::fmt::Display for GapKind {
492 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
493 f.write_str(self.as_str())
494 }
495}
496
497/// Something the extractor saw but could not turn into a confirmed usage.
498#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
499pub struct UsageGap {
500 pub kind: GapKind,
501 /// The provider involved, when known or inferred from the call's shape.
502 pub sdk: Option<Sdk>,
503 pub file: String,
504 /// `None` for a vendored directory.
505 pub span: Option<Span>,
506 pub symbol: Option<String>,
507 /// The callee or expression involved, arguments elided.
508 pub chain: Option<String>,
509 /// For `unresolved_model`: the key whose value did not resolve.
510 pub key: Option<String>,
511 /// A stable short code (`env_var`, `f_string`, `parameter`, `getattr`...).
512 pub reason: String,
513 /// A sentence for people. Never contains a literal value.
514 pub detail: String,
515 /// Allowlisted values seen at an unconfirmed call
516 /// (`unknown_client_factory`), or, for `unresolved_model`, values the key
517 /// may take that are known (what in-file callers pass for a parameter,
518 /// the entries of a dict looked up with a run-time key, the value each
519 /// branch assigns, the items a loop runs over), so it can be triaged.
520 /// Never the call's value. Partial unless [`Self::values_complete`].
521 #[serde(default, skip_serializing_if = "Vec::is_empty")]
522 pub values: Vec<CapturedValue>,
523 /// `values`, together with the value captured for the same key at the
524 /// call (a parameter default, an `env_default` fallback), are every
525 /// value the key can take as far as this file shows. `false` (omitted
526 /// from JSON) whenever the list may be partial: a definition, entry or
527 /// caller did not resolve, some callers cannot be seen, another module
528 /// may call the function, or a limit cut the list.
529 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
530 pub values_complete: bool,
531 /// For an `unknown_client_factory` gap at a call: the call's argument
532 /// names, so the retirement check can apply its argument rules to a call
533 /// whose client was not resolved. `None` (omitted from JSON) when the
534 /// extractor did not record them; the check then says it could not
535 /// check the call's arguments.
536 #[serde(default, skip_serializing_if = "Option::is_none")]
537 pub args: Option<CallArgs>,
538}
539
540/// The argument names of a call, as [`SdkCall`] records them.
541#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
542pub struct CallArgs {
543 /// Argument names in source order (see [`SdkCall::kwargs`]).
544 pub kwargs: Vec<String>,
545 /// Whether arguments were spread into the call (`**kwargs`).
546 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
547 pub splat: bool,
548 /// What each `**` expression is (see [`SdkCall::spreads`]).
549 #[serde(default, skip_serializing_if = "Vec::is_empty")]
550 pub spreads: Vec<Spread>,
551}
552
553/// Everything one file says about tracked SDKs.
554#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
555pub struct FileUsages {
556 pub file: String,
557 pub language: String,
558 pub imports: Vec<SdkImport>,
559 pub clients: Vec<ClientConstruction>,
560 pub calls: Vec<SdkCall>,
561 pub gaps: Vec<UsageGap>,
562 /// The parser recovered from syntax errors: calls inside the broken
563 /// region may be missing. Set only for files that mention an SDK.
564 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
565 pub syntax_errors: bool,
566}
567
568impl FileUsages {
569 /// An empty record for `file`.
570 pub fn new(file: &str, language: &str) -> Self {
571 Self {
572 file: file.to_string(),
573 language: language.to_string(),
574 ..Self::default()
575 }
576 }
577
578 /// Whether the file reported nothing at all.
579 pub fn is_empty(&self) -> bool {
580 self.imports.is_empty()
581 && self.clients.is_empty()
582 && self.calls.is_empty()
583 && self.gaps.is_empty()
584 }
585
586 /// Keeps only records for `sdk`. Gaps whose provider is unknown are kept.
587 pub fn retain_sdk(&mut self, sdk: Sdk) {
588 self.imports.retain(|i| i.sdk == sdk);
589 self.clients.retain(|c| c.sdk == sdk);
590 self.calls.retain(|c| c.sdk == sdk);
591 self.gaps.retain(|g| g.sdk.is_none_or(|s| s == sdk));
592 }
593}
594
595/// Languages that have a usage extractor.
596pub const USAGE_LANGUAGES: &[&str] = &["python"];
597
598/// File extensions that have a usage extractor. `.pyi` stubs are excluded:
599/// they declare types, they do not make requests. Extensionless scripts are
600/// scanned when [`is_python_shebang`] accepts their first line.
601pub const USAGE_EXTENSIONS: &[&str] = &["py"];
602
603/// Whether files with this extension have a usage extractor.
604pub fn is_usage_extension(extension: &str) -> bool {
605 USAGE_EXTENSIONS
606 .iter()
607 .any(|e| e.eq_ignore_ascii_case(extension))
608}
609
610/// Whether the start of an extensionless file is a Python shebang
611/// (`#!/usr/bin/env python3`, `#!/usr/bin/python3.11`).
612pub fn is_python_shebang(head: &[u8]) -> bool {
613 let Some(rest) = head.strip_prefix(b"#!") else {
614 return false;
615 };
616 let line = rest.split(|b| *b == b'\n').next().unwrap_or_default();
617 String::from_utf8_lossy(line)
618 .split(|c: char| c.is_whitespace() || c == '/')
619 .any(|word| word.starts_with("python"))
620}
621
622/// Keys whose string value may be captured. Every other key is recorded by
623/// name only.
624pub const VALUE_KEYS: &[&str] = &["model", "engine", "deployment_id", "model_name"];
625
626/// Name fragments that mark a credential: `api_key`, `auth_token`,
627/// `client_secret`, `PASSWD`, `db_pwd`, `CREDENTIALS`, `private_pem`...
628const SECRET_NEEDLES: &[&str] = &[
629 "key",
630 "token",
631 "secret",
632 "passw",
633 "passphrase",
634 "pwd",
635 "auth",
636 "cred",
637 "private",
638];
639
640/// Whether `key` may hold a credential. Such a value is never captured,
641/// whatever else is configured.
642pub fn is_secret_key(key: &str) -> bool {
643 let lower = key.to_ascii_lowercase();
644 SECRET_NEEDLES.iter().any(|needle| lower.contains(needle))
645}
646
647/// Whether a value for `key` may be captured.
648pub fn is_value_key(key: &str) -> bool {
649 VALUE_KEYS.contains(&key) && !is_secret_key(key)
650}
651
652/// Whether a dict key may appear in a [`CapturedValue::key`] path: an ASCII
653/// identifier of at most 64 characters that is neither secret-named nor
654/// credential-shaped. A dict under any other key is never descended into.
655pub fn is_identifier_key(key: &str) -> bool {
656 is_argument_name(key) && !is_secret_key(key)
657}
658
659/// Whether a key of a dict spread into a call with `**` is recorded as an
660/// argument name ([`Spread::keys`]): an ASCII identifier of at most 64
661/// characters that is not shaped like a credential. Unlike
662/// [`is_identifier_key`], a secret-sounding name such as `max_tokens` or
663/// `api_key` passes: it is a name, never a value, and a call's own keyword
664/// arguments are recorded the same way.
665pub(crate) fn is_argument_name(key: &str) -> bool {
666 let mut chars = key.chars();
667 let Some(first) = chars.next() else {
668 return false;
669 };
670 key.len() <= 64
671 && (first.is_ascii_alphabetic() || first == '_')
672 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
673 && !is_credential_value(key)
674}
675
676/// Prefixes of API keys and tokens (OpenAI, Anthropic, Stripe, Google,
677/// GitHub, Slack, AWS, GitLab, Hugging Face, Replicate, Groq, Perplexity,
678/// NVIDIA, Cerebras), PEM blocks and HTTP authorization values.
679const CREDENTIAL_PREFIXES: &[&str] = &[
680 "sk-",
681 "sk_",
682 "rk_",
683 "pk_live_",
684 "pk_test_",
685 "AIza",
686 "ghp_",
687 "gho_",
688 "ghu_",
689 "ghs_",
690 "ghr_",
691 "github_pat_",
692 "xox",
693 "xapp-",
694 "glpat-",
695 "hf_",
696 "r8_",
697 "gsk_",
698 "pplx-",
699 "nvapi-",
700 "csk-",
701 "-----BEGIN",
702 "Bearer ",
703 "bearer ",
704 "Basic ",
705];
706
707/// Whether a string looks like a credential rather than a model ID: a known
708/// key or token prefix, an AWS key ID, a JWT, a URL with user information
709/// (`postgres://admin:pw@db/prod`, `https://<token>@host`), or a long
710/// random run of alphanumerics (20 or more mixing upper case, lower case
711/// and digits, or 32 or more mixing letters and digits, which covers hex
712/// keys). Model IDs are short words joined by `-`, `.`, `:`, `/` or `@`,
713/// so they do not match.
714pub fn is_credential_value(value: &str) -> bool {
715 let value = value.trim();
716 if CREDENTIAL_PREFIXES.iter().any(|p| value.starts_with(p)) {
717 return true;
718 }
719 if has_url_userinfo(value) {
720 return true;
721 }
722 // An AWS access key ID.
723 if (value.starts_with("AKIA") || value.starts_with("ASIA"))
724 && value.len() == 20
725 && value
726 .chars()
727 .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
728 {
729 return true;
730 }
731 // A JWT: base64url segments, the first a JSON header.
732 if value.starts_with("eyJ") && value.matches('.').count() >= 2 {
733 return true;
734 }
735 value
736 .split(|c: char| !c.is_ascii_alphanumeric())
737 .any(|run| {
738 let upper = run.chars().any(|c| c.is_ascii_uppercase());
739 let lower = run.chars().any(|c| c.is_ascii_lowercase());
740 let digit = run.chars().any(|c| c.is_ascii_digit());
741 (run.len() >= 20 && upper && lower && digit)
742 || (run.len() >= 32 && (upper || lower) && digit)
743 })
744}
745
746/// Whether `value` holds a URL whose authority carries user information
747/// (`scheme://user:password@host`, `scheme://token@host`).
748fn has_url_userinfo(value: &str) -> bool {
749 value.match_indices("://").any(|(at, sep)| {
750 let rest = &value[at + sep.len()..];
751 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
752 authority.contains('@')
753 })
754}
755
756/// Whether a resolved string may be reported as a value: not
757/// credential-shaped, no control or bidirectional-override characters (an
758/// escape sequence must never reach a terminal) and at most 256 bytes.
759pub fn is_capturable_value(value: &str) -> bool {
760 value.len() <= 256 && !value.chars().any(is_unsafe_char) && !is_credential_value(value)
761}
762
763/// Control characters and bidirectional overrides.
764pub fn is_unsafe_char(c: char) -> bool {
765 c.is_control() || matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
766}
767
768/// Which provider's model-ID naming `value` follows, if any.
769///
770/// This is a shape check (`gpt-*`, `o3-mini`, `claude-*`, `gemini-*`...),
771/// not a list of real models. It is applied only to values that reach an
772/// allowlisted key, so a pricing table full of model names reports nothing.
773pub fn model_family(value: &str) -> Option<Sdk> {
774 let lower = value.trim().to_ascii_lowercase();
775 let mut id = lower.as_str();
776 // Fine-tuned ids (`ft:gpt-4o-mini:org::id`) and router prefixes.
777 for prefix in [
778 "ft:",
779 "openai/",
780 "openai.",
781 "models/",
782 "publishers/google/models/",
783 ] {
784 if let Some(rest) = id.strip_prefix(prefix) {
785 id = rest;
786 }
787 }
788
789 // Anthropic: first-party ids, Bedrock ids (with optional region prefix)
790 // and router prefixes.
791 if id.starts_with("claude-")
792 || id.starts_with("anthropic/claude-")
793 || id.contains("anthropic.claude-")
794 {
795 return Some(Sdk::Anthropic);
796 }
797
798 // Google before OpenAI: `text-embedding-004` is Google's, and
799 // `text-embedding-3-small` is OpenAI's.
800 const GOOGLE: &[&str] = &[
801 "gemini-",
802 "gemma-",
803 "text-bison",
804 "chat-bison",
805 "code-bison",
806 "codechat-bison",
807 "text-embedding-00",
808 "text-multilingual-embedding-",
809 "embedding-001",
810 "embedding-gecko",
811 "imagen-",
812 "veo-",
813 ];
814 if GOOGLE.iter().any(|p| id.starts_with(p)) || id == "gemini" {
815 return Some(Sdk::Google);
816 }
817
818 const OPENAI: &[&str] = &[
819 "gpt-",
820 "chatgpt-",
821 "text-davinci-",
822 "text-curie-",
823 "text-babbage-",
824 "text-ada-",
825 "code-davinci-",
826 "code-cushman-",
827 "davinci",
828 "curie",
829 "babbage",
830 "text-embedding-",
831 "text-moderation-",
832 "omni-moderation-",
833 "dall-e-",
834 "whisper-",
835 "tts-",
836 "computer-use-preview",
837 "codex-mini",
838 ];
839 if OPENAI.iter().any(|p| id.starts_with(p)) || id == "ada" || id.starts_with("ada-") {
840 return Some(Sdk::Openai);
841 }
842 // Reasoning models: `o1`, `o3-mini`, `o4-mini-2025-04-16`.
843 let mut chars = id.chars();
844 if chars.next() == Some('o') {
845 let rest: String = chars.collect();
846 let digits = rest.chars().take_while(|c| c.is_ascii_digit()).count();
847 if digits > 0 {
848 let tail = &rest[digits..];
849 if tail.is_empty() || tail.starts_with('-') {
850 return Some(Sdk::Openai);
851 }
852 }
853 }
854 None
855}
856
857#[cfg(test)]
858mod tests {
859 use super::*;
860
861 #[test]
862 fn value_keys_are_never_secret_shaped() {
863 for key in VALUE_KEYS {
864 assert!(!is_secret_key(key), "{key} must not look like a secret");
865 assert!(is_value_key(key));
866 }
867 for key in [
868 "api_key",
869 "API_KEY",
870 "auth_token",
871 "max_tokens",
872 "client_secret",
873 "password",
874 "authorization",
875 "azure_ad_token_provider",
876 "PASSWD",
877 "db_pwd",
878 "credential",
879 "CREDENTIALS",
880 "gcp_cred",
881 "private_pem",
882 "passphrase",
883 ] {
884 assert!(is_secret_key(key), "{key} must be treated as secret");
885 assert!(!is_value_key(key));
886 }
887 assert!(!is_value_key("temperature"));
888 }
889
890 #[test]
891 fn credential_shaped_values_are_refused() {
892 for secret in [
893 "sk-proj-AbCdEf0123456789xyz",
894 "sk-ant-api03-AbCdEf0123456789",
895 "sk-live-SECRET",
896 "sk_live_51H8abc",
897 "AIzaSyD-abcdefghijklmnop",
898 "ghp_0123456789abcdefABCDEF",
899 "xoxb-1234-5678-abcdef",
900 "AKIAIOSFODNN7EXAMPLE",
901 "Bearer abc",
902 "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.sig",
903 "Zx8aB2cD4eF6gH8iJ0kL2mN4",
904 "0123456789abcdef0123456789abcdef",
905 "postgres://admin:hunter2@db/prod",
906 "https://user:pw@gateway.example/v1",
907 "https://tokenvalue@github.com/org/repo",
908 ] {
909 assert!(is_credential_value(secret), "{secret} must be refused");
910 assert!(!is_capturable_value(secret));
911 }
912 for model in [
913 "gpt-4o-2024-08-06",
914 "claude-3-5-sonnet-20241022",
915 "us.anthropic.claude-sonnet-4-5-20250929-v1:0",
916 "ft:gpt-4o-mini-2024-07-18:acme::9xKz3mQp",
917 "models/gemini-1.5-flash-001",
918 "GPT4o-Prod-Deployment-2024",
919 "claude-3-5-sonnet-v2@20241022",
920 "projects/123456789012/locations/us-central1/endpoints/1234567890123456789",
921 "text-embedding-3-small",
922 "o3-mini",
923 "https://openrouter.ai/api/v1",
924 "anthropic/claude-3-opus@latest",
925 ] {
926 assert!(!is_credential_value(model), "{model} is a model ID");
927 assert!(is_capturable_value(model));
928 }
929 assert!(!is_capturable_value("gpt-4\u{1b}]8;;x\u{7}"));
930 assert!(!is_capturable_value("gpt-\u{202E}4"));
931 assert!(!is_capturable_value(&"a".repeat(300)));
932 }
933
934 #[test]
935 fn identifier_keys_only() {
936 for ok in ["model", "fallbacks", "extra_body", "_x1"] {
937 assert!(is_identifier_key(ok), "{ok}");
938 }
939 for bad in [
940 "",
941 "sk-proj-abc",
942 "x-api-key",
943 "api_key",
944 "1model",
945 "has space",
946 "sk_live_abc",
947 "Zx8aB2cD4eF6gH8iJ0kL2mN4",
948 ] {
949 assert!(!is_identifier_key(bad), "{bad}");
950 }
951 }
952
953 #[test]
954 fn python_shebangs() {
955 for yes in [
956 "#!/usr/bin/env python3\nimport openai\n",
957 "#!/usr/bin/python\n",
958 "#! /usr/local/bin/python3.11 -u\n",
959 "#!/usr/bin/env -S python3 -X utf8\n",
960 ] {
961 assert!(is_python_shebang(yes.as_bytes()), "{yes}");
962 }
963 for no in [
964 "#!/bin/sh\n",
965 "import openai\n",
966 "",
967 "#!/usr/bin/env node\n# python\n",
968 ] {
969 assert!(!is_python_shebang(no.as_bytes()), "{no}");
970 }
971 }
972
973 #[test]
974 fn model_family_recognises_shapes() {
975 for (id, sdk) in [
976 ("gpt-3.5-turbo", Sdk::Openai),
977 ("gpt-4o-2024-08-06", Sdk::Openai),
978 ("o1", Sdk::Openai),
979 ("o3-mini", Sdk::Openai),
980 ("o4-mini-2025-04-16", Sdk::Openai),
981 ("text-davinci-003", Sdk::Openai),
982 ("text-embedding-3-small", Sdk::Openai),
983 ("ft:gpt-4o-mini:acme::abc", Sdk::Openai),
984 ("openai/gpt-4", Sdk::Openai),
985 ("openai.gpt-5.4", Sdk::Openai),
986 ("claude-3-5-sonnet-20241022", Sdk::Anthropic),
987 ("anthropic.claude-3-haiku-20240307-v1:0", Sdk::Anthropic),
988 (
989 "us.anthropic.claude-sonnet-4-5-20250929-v1:0",
990 Sdk::Anthropic,
991 ),
992 ("global.anthropic.claude-sonnet-5-5", Sdk::Anthropic),
993 ("gemini-1.5-flash", Sdk::Google),
994 ("models/gemini-pro", Sdk::Google),
995 ("text-embedding-004", Sdk::Google),
996 ] {
997 assert_eq!(model_family(id), Some(sdk), "{id}");
998 }
999 for not_a_model in ["", "my-deployment", "ocean", "o", "orange-1", "hello"] {
1000 assert_eq!(model_family(not_a_model), None, "{not_a_model}");
1001 }
1002 }
1003
1004 #[test]
1005 fn sdk_and_routing_names_round_trip() {
1006 for sdk in Sdk::ALL {
1007 assert_eq!(Sdk::parse(sdk.as_str()), Some(sdk));
1008 let json = serde_json::to_string(&sdk).unwrap();
1009 assert_eq!(json, format!("\"{}\"", sdk.as_str()));
1010 }
1011 assert_eq!(Sdk::parse("Gemini"), Some(Sdk::Google));
1012 assert_eq!(Sdk::parse("cohere"), None);
1013 for routing in [
1014 Routing::OpenaiDirect,
1015 Routing::AzureOpenai,
1016 Routing::CustomBaseUrl,
1017 Routing::AnthropicDirect,
1018 Routing::AnthropicBedrock,
1019 Routing::AnthropicVertex,
1020 Routing::GoogleGenai,
1021 Routing::GoogleGenerativeaiLegacy,
1022 Routing::Unknown,
1023 ] {
1024 let json = serde_json::to_string(&routing).unwrap();
1025 assert_eq!(json, format!("\"{}\"", routing.as_str()));
1026 }
1027 }
1028}