Repository navigation
AI Providers
Every model call in the pipeline goes through one interface. Swapping providers changes no analysis code.
BaseAIProvider (ai/base_provider.py):
analyze(prompt, system_message=None, schema=None, images=None, max_tokens=None, session_key=None) -> dict
list_models() -> list[str]
validate_credentials() -> bool
default_model() -> str
supports_vision() -> bool
has_session(session_key) -> bool # default False
close_session(session_key) -> None # default no-opanalyze returns {"response": "<raw JSON string>"} or {"error": "<message>"}. It never raises for a provider-side problem, which is what lets the agent loops treat a failed call as a step rather than a crash.
session_key is how a caller (the agent loop's per-region key) asks for a multi-turn conversation on a provider that can hold one. has_session/close_session are duck-typed capability hooks, not asserted: callers reach them through getattr(provider, "has_session", None) rather than a direct call, because test fakes and some callers pass a bare object implementing only analyze(). Only the subscription-CLI providers act on session_key today; see Subscription CLI providers.
schema is a JSON Schema for the expected reply. Each provider maps it to its own structured-output mechanism:
| Provider | Mechanism |
|---|---|
| Ollama |
format=<schema> on a streamed chat call |
| OpenAI |
response_format JSON schema, array wrapped in an object under vulnerabilities
|
| Claude | A tool named report_vulnerabilities whose input_schema wraps the array the same way |
| Gemini |
generationConfig.responseSchema with responseMimeType: application/json
|
| Custom | Plain OpenAI-compatible chat completion; schema is advisory |
images carries raw PNG bytes for vision-capable models. Used by the device visual check; ignored by providers that cannot accept images.
build_provider(name) and get_active_provider() (ai/provider_factory.py) are the only places a provider is instantiated. They read the provider's config block from settings and its key pool from the credential store, so no call site handles secrets.
A provider holds a list of API keys, not one. BaseAIProvider(api_keys=[...]) takes the pool; api_key (singular) remains the primary constructor parameter and becomes the pool's first entry.
-
self.api_keypoints at the currently active key. Subclasses read it exactly as before; rotation just changes what it points to. -
advance_key(kind, reason)switches to the next unused key and returnsFalseonce the pool is spent. -
_handle_exception(exc)classifies the failure. A fatal one (exhausted quota, rejected key) rotates; the circuit opens only when the whole pool has failed. - A key that failed fatally is remembered for the process (
mark_key_spent, in memory only and never logged), and a provider built later starts on the first key not known to be spent (first_live_key). A scan builds several providers - agents, file review, review pass, chains, device verifier - and each used to start on key 1 and walk the dead keys again: one Ghera scan spent 10 of 21 calls that way. The memory expires after an hour (SPENT_KEY_RETRY_SECONDS) andreset_circuitclears it for the pool, so a key whose quota has reset, or a user's resume, gets tried again. -
self._fatalis set once every key has failed unrecoverably. Every later call on that instance returns immediately. A scan has roughly ten LLM call sites, and each independently rediscovering a dead quota costs wall clock to learn nothing.
Each provider's retry loop is bounded by max(len(self._keys), 1): one attempt per key, continue only when the key actually rotated.
Manage the pool at POST /api/settings/credentials (append, optionally with a label), PUT /api/settings/credentials/{provider}/{index}/label (label one), DELETE /api/settings/credentials/{provider}/{index} (remove one) and POST /api/settings/credentials/{provider}/reveal (read one back). A label only helps a person tell keys apart; the provider never sees it. See Configuration.
ai/errors.py classifies a failure by whether retrying can possibly help.
| Class | Meaning | Retry? |
|---|---|---|
TRANSIENT |
Connection reset, stalled stream, 5xx | Yes |
THROTTLED |
Per-minute or per-second rate limit | Yes, but not soon |
FATAL_QUOTA |
Account/session quota | No; rotate the key or stop |
FATAL_AUTH |
Missing, invalid or unauthorized credentials | No |
A failure that means the host could not be reached at all (DNS failure, no network, connection refused; errors.is_unreachable) stays TRANSIENT for the retry loop, since a dropped connection often comes back within one call's retries. The provider also records it (note_reachability) until its next successful call, and usage_summary() reports it as unreachable: a scan that ends while the host is still unreachable is paused for a short retry rather than finished (see Reports).
A bare 429 is per-minute throttling and worth waiting out. A 429 carrying session usage limit, insufficient_quota, quota exceeded, credit balance is too low, billing, monthly limit, out of credits, payment required and similar is an account-level limit that no wait inside one scan will clear.
The distinguishing phrase is in the response body. httpx.HTTPStatusError, raised by raise_for_status() in the OpenAI, Gemini and custom providers, stringifies to the status line and URL only, so _body_of reads the response directly. _status_of takes the HTTP status from whichever attribute the client happens to use (status_code, status, code, or response.status_code).
The fan-out runs one agent thread per code region against a shared provider instance. Two mechanisms bound that.
max_concurrent_requests (per provider, default 2, range 1–20) becomes a threading.BoundedSemaphore held for the whole call. Without it, one long call lets every other thread pile requests up behind it with nothing on this side aware of it. On Ollama Cloud, sibling regions get 429s for the whole window while the account's one slot is held.
Waiting locally and instantly for a slot is strictly better than discovering the same fact from the server minutes later.
The configured width is a starting estimate; a 429 is the measurement. On the first real throttle, on_throttled → _shrink_gate_to_one permanently drops the in-flight ceiling to 1. BoundedSemaphore cannot be resized, so surplus permits are absorbed on a daemon thread rather than released, because the caller that observed the throttle is itself holding a permit, so acquiring both permits of a width-2 semaphore inline would deadlock unconditionally. Guarded by _gate_shrink_started so concurrent throttles from sibling threads do not each launch their own absorption.
reset_circuit() releases exactly what was absorbed (never more) so a later scan does not inherit the previous one's throttle response.
add_throttle_observer(fn) registers fn(blocked_seconds), called on every throttle. The agent fan-out uses it to credit stalled time back to the wall-clock budget; see analyzers/agent/budget.py and Static analysis. A provider outage must not silently become the user's coverage loss.
The blocked time recorded is the failing attempt's own duration, not the backoff: the server holds the connection open waiting for a slot and only returns 429 once it gives up, so the backoff is a small fraction of the real stall.
self.usage aggregates across every call site of one scan:
| Field | Meaning |
|---|---|
calls, failed
|
Completed analyze() calls |
wall_clock_s |
Total, including failed attempts |
prompt_tokens, completion_tokens
|
Where the provider reports them |
cache_read_tokens, cache_creation_tokens
|
Server-side prefix-cache hit/write counts, where the provider reports them (Claude's cache_read_input_tokens/cache_creation_input_tokens, OpenAI/custom's prompt_tokens_details.cached_tokens, Gemini's cachedContentTokenCount, claude_cli/antigravity_cli's JSON envelope): this is the number that actually proves a stable system prompt is being cached rather than re-processed every turn |
cost_usd |
Reported spend for the call, where the provider's own envelope carries it (claude_cli's total_cost_usd) |
throttled_attempts, transient_attempts
|
Every failed HTTP attempt, whether or not the call later succeeded |
failed_attempt_seconds |
Wall time of those attempts (also folded into wall_clock_s) |
retried_calls, truncation_retries, transient_retries, throttle_retries
|
Retry causes |
slow_calls |
A single analyze() that ran past the request timeout across its retries |
unparseable_responses |
Replies no parsing layer could use |
blocked_seconds |
Time spent stalled on throttles |
unavailable |
Added by usage_summary(): why the circuit opened (fatal_quota: …, fatal_auth: …), or null |
unreachable |
Added by usage_summary(): the last unreachable-host failure, cleared by any later successful call, or null |
provider, model, mode, keys_total, keys_used
|
Added by usage_summary(); keys_used is the position reached in the key rotation |
Counters are guarded by _usage_lock, since read-modify-write on an int is not atomic under the GIL and the fan-out increments from several threads.
record_call_metrics additionally appends one JSONL row per call to the scan's metrics file (<apk>_llm_calls.jsonl, every provider). It is written only when the provider has an output manager, and the analyzers attach one only under --verbose, so a non-verbose scan writes no metrics file. Each row holds: timestamp, region (the calling thread's name), server-side per-call counts including cache_read_tokens/cache_creation_tokens/cost_usd, done_reason, and error for failed attempts. Summing cannot show whether server-side prefix caching is working turn to turn; the per-call rows can: prompt_eval_count/cache_read_tokens should fall off a cliff after a region's first turn and stay there.
log_exchange(system_message, prompt, response, *, elapsed=None, metrics=None, thinking="", error=None, session_key=None, resumed=False) on BaseAIProvider is the one place every concrete provider (Ollama, Claude, OpenAI, Gemini, Custom, and all five CLI providers) records a call, on both its success path and its failure path. A failed call is exactly when the prompt is worth reading, and previously only Ollama wrote anything down at all (_save_request_response_log, since moved onto the base class and renamed).
Two effects, from one call:
- A
record_call_metricsJSONL row (see above), whenever an output manager is attached. - When
--verboseand an output manager is attached: a markdown transcript at<apk>_<provider>_Request_Response_<timestamp>[_<thread>].md(the provider key, lowercase:DIVA_ollama_Request_Response_…), viaoutput_manager.get_llm_log_path(provider_label, timestamp), the path helper generalised from Ollama-only (get_ollama_log_path, kept as a deprecated alias) to take a provider label, disambiguated by thread name so the parallel fan-out's regions don't overwrite each other's file.
session_key/resumed are recorded when given, so a saved transcript shows whether a turn was a full seed or a delta-only resume: the only way to see a CLI session's input-token saving actually happening in a real scan's output.
Every other provider spends a pay-per-token API key. Most users of a mobile-security tool have a subscription instead (Claude Pro/Max, GitHub Copilot Pro, Kimi Plus/Pro/Max/Ultra, ChatGPT Plus/Pro, Google AI Pro/Ultra), and every one of those vendors ships a headless coding CLI that authenticates over OAuth (a one-time interactive login the user runs themselves, outside this tool) and bills the call against subscription quota rather than a metered API. Shelling out to that CLI is the sanctioned way to reach that quota; there is no public API for it.
ai/cli_provider.py implements one provider class, CLIBackedProvider, driven by a small per-vendor CLISpec, rather than five near-duplicate provider files:
| Provider key | Binary | Display |
|---|---|---|
claude_cli |
claude |
Claude Code CLI (Claude Pro/Max) |
copilot_cli |
copilot |
GitHub Copilot CLI (Copilot Pro) |
kimi_cli |
kimi |
Kimi CLI (Kimi Plus/Pro/Max/Ultra) |
codex_cli |
codex |
Codex CLI (ChatGPT Plus/Pro) |
antigravity_cli |
agy |
Antigravity CLI (Google AI Pro/Ultra, replaced Gemini CLI's consumer OAuth) |
A spec is binary, signin_hint, build_argv/extract, native_schema (whether the CLI itself enforces the JSON Schema, vs. it being appended to the prompt text and salvaged downstream), prompt_via_stdin (see below), and the resume fields covered next. resolved_binary prefers a user-set binary_path override, then PATH; needed for a CLI installed somewhere PATH won't reach from a subprocess, e.g. kimi at ~/.kimi-code/bin/kimi.
The prompt rides stdin by default: it can be tens of KB of system prompt plus skills, and argv is visible to every other process via ps. Three CLIs have no stdin fallback on their non-interactive flag at all: copilot --prompt, kimi -p (confirmed live: "a value is required" when given no argument), and agy -p, so those specs carry prompt_via_stdin=False and embed the text in argv instead, the only way to reach them.
copilot also auto-loads its full built-in coding-agent toolset (bash, apply_patch, write, the GitHub MCP server, …) with no opt-out flag; a scan analysing an untrusted APK's unpacked contents should never have live command execution or file editing available to it. --disable-builtin-mcps plus --deny-tool on each of bash, apply_patch, write, write_agent, session_store_sql, sql blocks them from running (it does not reduce the ~10-17K prompt-token floor those tool schemas cost; no flag removes that).
Codex's --output-schema rejects any object node with no additionalProperties key at all (the shape every schema in this codebase is written in), so requires_additional_properties_false on its spec recursively adds "additionalProperties": false to every object node before the schema is handed over.
Each CLI can hold a conversation across separate process invocations, so the loop doesn't have to re-send the whole conversation from scratch every turn:
| CLI | Resume | Id | Continue-in-cwd |
|---|---|---|---|
claude |
--resume <uuid> |
assigned (--session-id) |
-c |
copilot |
--continue |
captured from the result event's sessionId
|
--continue |
codex |
exec resume <thread_id> (a subcommand, not a flag) |
captured from thread.started
|
exec resume --last |
agy |
--conversation <id> |
captured from conversation_id
|
-c |
kimi |
-c |
none (resumes by cwd alone) | -c |
Copilot never emits a --session-id flag on either call — its continuation is entirely cwd-based, the same mechanism kimi uses; the id captured from sessionId is read back only for bookkeeping, not for resuming.
On the region's first turn (session_key given, no session recorded yet): the full system prompt, initial context and schema go out as today, in a scratch cwd created with tempfile.mkdtemp() (a plain path with no auto-cleanup, unlike the one-shot path's TemporaryDirectory), because Claude Code and Codex key a session to the cwd it started in and that cwd has to outlive this one call. On every later turn on that key: only the newest observation is sent, using the CLI's resume shape above, in the same cwd. close_session(session_key) (called by the agent loop when a region finishes, or by the provider itself on any exception during a conversational call) removes the scratch dir and forgets the id: a failed turn leaves nothing worth resuming, so the next call re-seeds from full context rather than repeating a broken resume forever.
--no-session-persistence (claude) and codex's --ephemeral are passed only on a one-shot, no-session_key call; a session-seeding call omits them so the conversation can actually be resumed later.
Per-turn input on a resumed turn drops from tens of thousands of tokens (system prompt + skills + full rolling context, re-sent byte-identical every turn) to roughly the size of one observation. The agent loop wires this in: provider.has_session(region_key) (duck-typed, see above) decides whether a turn sends transcript[-1] alone or the full initial_context + history.
A spec with no resume_argv (none currently) or a session_key-less call (the model-listing probe, validate_credentials()) behaves exactly as before: fresh process, fresh TemporaryDirectory, no history kept.
Vision is not supported by any CLI bridge: piping image bytes alongside a text prompt has no shared envelope across the five tools, so supports_vision() is False and only the device screenshot-diff check is skipped for these providers.
Two modes:
-
Cloud (
mode: "cloud"): host defaults tohttps://api.ollama.com, requires an API key sent as a bearer token. -
Local (
mode: "local"): host defaults tohttp://localhost:11434, no key. Readiness is a health request to/.
Requests stream and are retried up to 3 times, delay starting at 2 s and multiplying by 1.5 up to 10 s. Read timeout OLLAMA_REQUEST_TIMEOUT = 600 s, connect timeout 30 s. A bounded timeout is necessary: the ollama client defaults to none, so a stalled cloud stream would hang a scan indefinitely.
options={"num_predict": …} bounds total generated tokens, thinking and content together, since the server does not budget them separately: the caller's max_tokens plus OLLAMA_THINKING_ALLOWANCE (4096), else OLLAMA_NUM_PREDICT (16384). A caller's cap sizes its answer, and thinking is always on, so the trace needs room on top. Sized for the answer alone, the review pass's 500-1,000-token batch caps truncated on 301 of 373 calls across a week of scans and ran out of attempts on 77 (those batches kept their mechanical verdicts), chain confirmation truncated on 32 of 86, and the device triage's 300-token cap failed on every scan. 4,096 covers the whole output of nine in ten review and device calls measured. Without it a model that fails to converge runs to the server's own ceiling. A response cut off at the cap (done_reason == "length") is retried with the cap doubled each time up to OLLAMA_MAX_NUM_PREDICT (65536), because the thinking trace is what overran and the same cap fails the same way; each attempt's cap is written to the trace and the transcript.
Model listing (ai/ollama_models.py): local mode returns whatever the local server's /api/tags reports. Cloud mode fetches Ollama's live catalogue from the configured cloud host's /api/tags, which is public, so no API key is sent. Entries that declare capabilities without completion (embedding-only models) are dropped. Cloud models already pulled into a local Ollama come first, renamed from the local form (gpt-oss:120b-cloud) to the cloud API's (gpt-oss:120b), and dropped if the catalogue no longer lists them; the rest is sorted, since the catalogue's own order changes between requests. If the catalogue cannot be fetched the list is empty and the Settings field still accepts a typed name.
Nothing is curated for Ollama any more: a hardcoded list went entirely stale within months, offering retired models that answered HTTP 410. The catalogue does not say which models a plan includes, though; on the free plan most cloud models answer HTTP 402, so the list can include models that will fail for a free account.
ai/ollama_lifecycle.py detects, starts, selects and stops a local Ollama server for one run: ollama serve with a 30-second startup wait, polled every 0.5 s.
Vision support is inferred from the model name (llava, vision, -vl, moondream, minicpm-v, gemma3, pixtral, llama3.2-vision, …).
In verbose mode with an output manager attached, each request and response is written to <apk>_ollama_Request_Response_<timestamp>[_<thread>].md in the scan folder. The thread-name suffix keeps parallel regions from overwriting each other's file.
Thinking is always enabled (think=True); it is not a knob.
Optional dependency: pip install "lu77U-MobileSec[claude]". The SDK is imported lazily, so the package works without it as long as Claude is not active.
Findings come back through a tool call rather than free text. Curated models: claude-opus-4-8, claude-opus-4-7, claude-sonnet-4-6, claude-haiku-4-5. All accept images.
Chat Completions against https://api.openai.com/v1, 120-second timeout, JSON-schema response format. Curated models: gpt-4o, gpt-4o-mini, gpt-4.1, o4-mini.
https://generativelanguage.googleapis.com/v1beta. The API key goes in the x-goog-api-key header, never the URL query string, because httpx repeats the request URL in exception text that gets logged and returned. Curated models: gemini-2.5-pro, gemini-2.5-flash, gemini-2.0-flash.
Any OpenAI-compatible endpoint. Set base_url; the API key is optional and sent as a bearer token when present. Model listing calls the endpoint's own /models; on any failure it falls back to whatever single model is configured ([self.model], or [] if none is set) — there is no curated list for a provider with no fixed vendor.
The base URL is validated when saved: scheme must be http or https, localhost is rejected, and the host is resolved and rejected if it lands in a private, loopback, link-local or unique-local range (which covers cloud metadata at 169.254.0.0/16). A name that does not resolve at save time is allowed through and fails at request time.
| Provider | Default model |
|---|---|
| ollama |
gpt-oss:120b (served on the free plan; the previous default was retired upstream). A fresh install's settings leave the model blank, so this is what a first scan uses |
| claude | claude-opus-4-8 |
| openai | gpt-4o |
| gemini | gemini-2.5-flash |
| custom | none; must be set |
| claude_cli | opus |
| copilot_cli, kimi_cli, codex_cli, antigravity_cli | none; the CLI's own default applies |
Display names, curated lists (Claude, OpenAI, Gemini) and defaults live in ai/registry.py. The same file's PROVIDER_VENDORS groups these ten provider keys into the seven real vendors the Settings page presents: Claude, OpenAI and Google each reachable two ways (an API key, or their _cli sibling); see Web UI.
Each of the five API-key providers also has a cheap_model field alongside model: build_provider(..., cheap=True) substitutes it for the high-volume grading and triage calls the validator makes, falling back transparently to model when it is blank. Configuration-only today — no PUT /api/settings field or Settings-page control reaches it; see Configuration.
check_ai_provider_configured() decides whether /api/status reports the provider ready:
- Ollama local: always ready; server and model selection happen at request time.
- Ollama cloud, Claude, OpenAI, Gemini: at least one stored key.
- Custom: a base URL.
- A CLI provider: no key to check.
GET /api/settings/cli-status/{provider}reportscli_found(a cheapPATH/binary_pathlookup) andsigned_in(a live, cheap probe call viavalidate_credentials()) separately, so the Settings page can show "installed but not signed in" distinctly from "not found"; the one-time interactive sign-in itself always happens outside this tool.
This is a configuration check, not a liveness check. POST /api/settings/test constructs the provider and calls validate_credentials().
VULNERABILITY_SCHEMA (ai/schema.py) is an array of finding objects.
| Field | Notes |
|---|---|
title |
Short, specific name |
cvss_vector |
Required. CVSS v3.1 base vector. Severity is computed from this, not chosen |
severity |
Fallback only, used when the vector is missing or invalid |
file, line
|
Must point at real decompiled source. line accepts "8", "6-7", "lines 6 to 9" or an integer |
vuln_class |
Catalogue code; the schema description is generated from validation/taxonomy.py
|
description, impact, exploitation, recommendation
|
Prose fields |
cwe, owasp_mobile
|
Classification |
Required: title, cvss_vector, file, line, description, recommendation. A confidence field is not in the schema but is passed through the finding whitelists when a model emits one, and the confidence gate reads it.
Code snippets are deliberately not requested. The tool reads the cited lines from disk, which removes transcription errors and shortens responses.
Two helpers absorb model sloppiness: parse_line_span extracts the first two integers from whatever the model wrote and orders them; coerce_to_vuln_list unwraps a JSON string, or a dict keyed by vulnerabilities / results / findings / issues, into a plain list. It also takes the document out of a markdown code fence first, and reads an object keyed by the request's ids ({"0": {...}, "1": {...}}) as the list it is. Without the fence handling, every review, title and chain answer from gemma4:31b was discarded with no log line, because the model fences its JSON even with a schema set; see Validation and chains.
The schema asks for short fields (a 240-character description, a 120-character impact) so the model writes concisely, and models overrun those by a few words. The response normalizer used to cut each field at exactly that length with "...", which published descriptions ending "... to read hidd..." on a third of one scan's agent findings. response_parser.fit_field now keeps the text whole up to three times the asked length, and past that cuts at the last sentence end, or at a word with an ellipsis. An exploitation field that holds only a libapp.so offset, which the Flutter prompt asks for as the function to hook, becomes "Frida hook point: libapp.so offset 0x…" (hook_point), and the prompt now asks for the function's name with it.
NEXT_ACTION_SCHEMA (in analyzers/agent/agent_loop.py) is the per-turn action schema; see Static analysis for the action list.
The agent loops need a model that reliably emits one JSON object per turn and follows a step budget. Practical requirements:
- Structured output. Providers without it drift into prose and force the salvage paths.
- Context window large enough for the initial context (objective, leads, orientation file, code map) re-sent every turn, plus up to 60000 characters of transcript.
-
Latency. Each turn is one round trip. Phase 1 defaults to 40 steps per region and 45 minutes wall clock; the file review after it makes up to 40 more calls (
max_review_parts), four at a time; phase 2 adds a 20–60 step loop. A model that reports once it has enough evidence keeps a scan short. -
Concurrency headroom. The fan-out launches up to 8 regions at once, on top of two concurrent scans. Set
max_concurrent_requeststo what the account can actually sustain. A local Ollama will not cope with eight simultaneous requests.
Small local models generally fail to drive the loop and fall through to the full-dump path (Java/Kotlin only).
lu77U-MobileSec · Live demo · Benchmarks · Report an issue · Documents version 0.1.5
Start
Results
How a scan works
Reference
Help and contributing