NuGuard Python Library Reference

NuGuard exposes its platform-facing interfaces as async Python functions with JSON-safe Pydantic request/response models. This includes:

  • SBOM generation/serialization APIs
  • SBOM toolbox APIs
  • Static analysis APIs
  • Behavior APIs
  • Redteam APIs
  • Streaming contracts used by streaming APIs
  • Target verification and target-session resolution APIs
  • Report rendering/export APIs
pip install nuguard

Core pattern

Browser chat discovery settings

TargetVerifyRequest, TargetSessionResolveRequest, and RedteamRunRequest accept an optional browser_discovery configuration. Behavior requests use config.browser_discovery. Existing requests remain valid without this field.

from nuguard.common.browser_login.config import BrowserDiscoveryConfig
from nuguard.common.target_verify_public_api import TargetVerifyRequest

request = TargetVerifyRequest(
    target_url="https://app.example.com",
    browser_discovery=BrowserDiscoveryConfig(
        chat_opener_selector="#open-chat",
        chat_input_selector="#chat-input",
        send_button_selector="#chat-send",
        chat_ui_timeout_ms=10000,
    ),
)

The readiness timeout accepts 1-60000 milliseconds and defaults to 10000. It covers widget opening and input readiness, not navigation or request capture. Visible but disabled inputs are awaited without toggling their widget. Settings do not enable a new browser-discovery mode; existing fallback activation remains unchanged. Playwright and Chromium are required only when browser discovery runs. Expected UI failures become warnings or discovery notes; cancellation propagates. An observed request still needs HTTP reply validation before endpoint confirmation.

Most public entry points follow this shape:

  • A *Request Pydantic model for JSON-safe run settings.
  • One async entry point function that takes the request, plus domain objects as keyword args.
  • A *Result Pydantic model.

Large domain objects such as SBOM and policy, and stateful collaborators like LLM clients, stay out of request models by design and are passed separately.

Error handling behavior is intentional:

  • Full runs (analysis, behavior, redteam, verify) propagate meaningful runtime exceptions.
  • Remediation-plan synthesis propagates failures too: it returns [] only when there's no SBOM or no findings to synthesize against — an actual synthesis failure (e.g. a broken LLM client) surfaces as a visible run error rather than a silently empty plan.

Prerequisites

AI-SBOM

from pathlib import Path
from nuguard.sbom.generator import SbomGenerator
from nuguard.sbom.serializer import AiSbomSerializer

sbom = SbomGenerator().from_path(Path("./my_app"))
# or
sbom = AiSbomSerializer.from_json(Path("app.sbom.json").read_text())

Cognitive policy

from pathlib import Path
from nuguard.policy.loader import ensure_policy_controls

policy, controls = await ensure_policy_controls(Path("cognitive-policy.md"))

LLM client

from nuguard.common.llm_client import LLMClient

llm_client = LLMClient(model="azure/gpt-5.4-mini", api_key="...")

If no API key is provided, the client may return placeholder output. Validate client configuration before relying on LLM-dependent results.

SBOM generation and serialization APIs

Module: nuguard.sbom.public_api

  • SbomGenerateRequest
  • SbomGenerateResult
  • SbomParseRequest
  • SbomParseResult
  • SbomRenderRequest
  • SbomRenderResult
  • SbomExportRequest
  • SbomExportResult
  • SbomEnrichmentLlmConfig
  • SbomProbeAuthConfig
  • SbomEnrichmentRequest
  • SbomEnrichmentResult
  • generate_sbom(request)
  • parse_sbom_json(request)
  • render_sbom(request, *, sbom)
  • export_sbom(request, *, sbom)
  • enrich_sbom(request)

SbomRenderRequest.format supports:

  • json
  • cyclonedx
  • cyclonedx-ext
  • markdown

Example:

from nuguard.sbom.public_api import SbomGenerateRequest, SbomRenderRequest, generate_sbom, render_sbom

generated = await generate_sbom(SbomGenerateRequest(source_path="./my_app"))
rendered = await render_sbom(SbomRenderRequest(format="json"), sbom=generated.sbom)

enrich_sbom() accepts an existing validated AiSbomDocument, operates on a deep copy, and performs no filesystem writes unless output_path is set. Its cache fingerprint excludes LLM API keys and probe authorization values; use the caller-controlled opaque cache_version when auth or external state must invalidate a platform-managed cache. Secret inputs use SecretStr and are never copied into the result.

Cognitive policy API

Module: nuguard.policy.public_api

  • CognitivePolicyParseRequest
  • CognitivePolicyParseDetail
  • CognitivePolicyParseResult
  • parse_cognitive_policy(request)

The parse result contains a validated policy or stable sanitized errors. Pass a successful result directly as policy= to public behavior and red-team entry points. The existing parse_policy(text) API remains supported.

SBOM toolbox APIs

Module: nuguard.sbom.toolbox.public_api

  • ToolboxListPluginsRequest
  • ToolboxListPluginsResult
  • ToolboxRunPluginRequest
  • ToolboxRunPluginResult
  • ToolboxRunAllRequest
  • ToolboxRunAllResult
  • list_toolbox_plugins(request)
  • run_toolbox_plugin(request, *, sbom)
  • run_toolbox_all(request, *, sbom)

Example:

from nuguard.sbom.toolbox.public_api import ToolboxRunPluginRequest, run_toolbox_plugin

result = await run_toolbox_plugin(
    ToolboxRunPluginRequest(plugin_name="dependency_analyze"),
    sbom=generated.sbom,
)

Static analysis API

Module: nuguard.analysis.public_api

  • AnalysisRunRequest
  • AnalysisRunResult
  • run_analysis(request, *, sbom, policy=None, llm_client=None)

Example:

from nuguard.analysis.public_api import AnalysisRunRequest, run_analysis

result = await run_analysis(
    AnalysisRunRequest(min_severity="medium"),
    sbom=sbom,
    policy=policy,
    llm_client=llm_client,
)

AnalysisRunResult includes findings, tool_status, nga_audit, sc_audit, token_usage, and remediation_plan.

Source rules use Opengrep when available and fall back to Semgrep. The enable_semgrep parameter, semgrep_* settings, and semgrep finding-source and tool-status keys are retained for compatibility.

AnalysisRunRequest accepts checkov_timeout and semgrep_timeout (120 seconds per process), plus checkov_total_timeout and semgrep_total_timeout (300 seconds per scanner across all paths). pip_audit_timeout (300 seconds per process) and pip_audit_total_timeout (600 seconds across all manifests) control the pip-audit deep scan, enable_pip_audit (default True) turns it off. gitleaks_timeout (120 seconds per process) and gitleaks_total_timeout (300 seconds across all source paths) control the gitleaks secret scan, and enable_gitleaks (default True) turns it off. Values must be finite and positive. StaticAnalyzer accepts the same arguments. CLI flags use hyphens, for example --checkov-total-timeout 180; YAML places these keys under analyze.

Timeouts terminate scanner workers and reap the parent, with bounded cleanup beyond the scan deadline. Launch, exit, output, and scanner-reported parsing errors set the tool's status to error; partial findings remain available. The CLI writes the report and exits with code 2 for incomplete Checkov, Opengrep (Semgrep fallback), or Gitleaks scans. Missing binaries or paths are skipped. Logs identify each path, duration, return code, and outcome, with a heartbeat every 15 seconds during execution. Raw scanner output is omitted from error logs. Cancelling the async caller does not immediately cancel scanner threads; their configured deadlines still apply.

Behavior APIs

Module: nuguard.behavior.public_api

  • BehaviorAnalysisRequest
  • BehaviorRunRequest
  • analyze_behavior(request, *, sbom=None, policy=None, controls=None, llm_client=None, remediation_llm_client=None)
  • run_behavior_scenarios(request, *, sbom=None, policy=None, intent=None, llm_client=None, remediation_llm_client=None, judge_cache=None)
  • discover_behavior_profile(config, *, sbom=None, policy=None, intent=None, llm_client=None)
  • analyze_behavior_stream(...)
  • analyze_behavior_analysis_stream(...)

Example (full analysis):

from nuguard.behavior.public_api import BehaviorAnalysisRequest, analyze_behavior
from nuguard.config import BehaviorConfig

result = await analyze_behavior(
    BehaviorAnalysisRequest(
        config=BehaviorConfig(target="https://my-app.example.com"),
        mode="static+dynamic",
    ),
    sbom=sbom,
    policy=policy,
    controls=controls,
    llm_client=llm_client,
)

Use analyze_behavior_analysis_stream(BehaviorAnalysisRequest(...)) for the same complete intent, policy, discovery, planning, execution, remediation, and final-result lifecycle with incremental events. Its final_result() is a BehaviorAnalysisResult.

Example (scenario-level run):

from nuguard.behavior.models import BehaviorScenario, BehaviorScenarioType
from nuguard.behavior.public_api import BehaviorRunRequest, run_behavior_scenarios
from nuguard.config import BehaviorConfig

result = await run_behavior_scenarios(
    BehaviorRunRequest(
        config=BehaviorConfig(target="https://my-app.example.com"),
        scenarios=[
            BehaviorScenario(
                scenario_type=BehaviorScenarioType.INTENT_HAPPY_PATH,
                name="check-balance",
                messages=["What is my account balance?"],
            )
        ],
    ),
    sbom=sbom,
    policy=policy,
    llm_client=llm_client,
)

Redteam APIs

Module: nuguard.redteam.public_api

  • RedteamAuthConfig
  • RedteamLoginFlowConfig
  • RedteamRunRequest
  • RedteamRunResult
  • RedteamExecutionResult
  • run_redteam(request, *, sbom, policy=None, policy_controls=None, redteam_llm=None, eval_llm=None, remediation_llm_client=None, app_log_reader=None, catalog=None, log_path=None, prompt_cache_dir=None)
  • run_redteam_stream(...)

Example:

from nuguard.redteam.public_api import RedteamRunRequest, run_redteam

result = await run_redteam(
    RedteamRunRequest(target_url="https://my-app.example.com", profile="ci"),
    sbom=sbom,
    policy=policy,
    policy_controls=controls,
    redteam_llm=llm_client,
    eval_llm=llm_client,
)

RedteamRunRequest additively exposes defence_regressions, defence_regression_paraphrases, asm_max_probe_requests, asm_extra_inventory_paths, and trust_context_confirmation_cells; see the agentic-surface notes in the platform integration guide. Findings carry optional evasion_differential, decorator_name, callback_evidence, regression_paraphrase_kind, dual_path_verdict, and state_diff_outcome evidence fields.

RedteamRunRequest.auth_config uses the secret-safe public RedteamAuthConfig and remains compatible with internal AuthConfig and application AppAuthConfig inputs. Bearer, API-key, basic, login-flow, cookie-file, and no-auth configurations are normalized without placing resolved credentials in serialized requests or result models. Request JSON dumps are redacted diagnostic representations and must not be persisted or replayed as executable credential transport. Platforms should resolve secret references server-side before constructing a request.

RedteamRunRequest.mode is concurrent, progressive or campaign; campaign accepts a CampaignConfig (turn/token limits, retry budget, fresh-session confirmation, optional run budgets). RedteamRunResult additively carries campaign_coverage, campaign_plan, objective_records, reproduction_records, branch_summaries, capability_observations and efficiency (all empty/None outside campaign mode); Finding gains catalog_id, reproduction_status, evidence_kind, effect_verified and framework_versions. These models carry counts, ids and statuses only — never headers, cookies or raw transcripts.

RedteamRunResult.scan_outcome is one of:

  • critical_findings
  • high_findings
  • findings
  • aborted_target_unavailable
  • inconclusive_target_errors
  • no_findings

Pentest APIs

Module: nuguard.pentest.public_api

  • PentestAuthConfig
  • PentestLoginFlowConfig
  • PentestRunRequest
  • PentestRunResult
  • PentestExecutionResult
  • run_pentest_async(request, *, resolver=None)
  • run_pentest_stream(request, *, resolver=None)

Example:

from nuguard.pentest.public_api import PentestRunRequest, run_pentest_async

result = await run_pentest_async(
    PentestRunRequest(
        targets=["https://staging.example.com"],
        authorized=True,
    ),
)

Same secret-safe pattern as RedteamAuthConfig: PentestRunRequest.auth_config uses SecretStr fields, credentials are never placed in serialized requests or result models, and diagnostic JSON dumps are redacted. run_pentest_async never catches or suppresses exceptions from a failed scan — only EngineExecutionError messages are sanitized when authentication was configured, matching the CLI's behavior exactly.

run_pentest_stream returns a typed StreamRunHandle[PentestExecutionResult] and follows the same streaming contract as run_redteam_stream/run_behavior_scenarios — see Streaming contracts below. Reduce events with apply_event_to_pentest_state into a PentestProgressState.

Streaming contracts

Module: nuguard.common.streaming_models

  • StreamEvent
  • StreamProgressPayload
  • StreamDeltaPayload
  • StreamTerminalPayload
  • RedteamProgressState
  • BehaviorProgressState
  • PentestProgressState (module: nuguard.pentest.public_api)

Behavior and redteam streaming APIs return a typed StreamRunHandle that emits StreamEvent envelopes and resolves to the final result model.

Streams emit run_started, scenario_plan_ready, scenario_started, scenario_progress, findings_delta, optional idle heartbeat events, and exactly one terminal completed or failed event. Progress payloads contain monotonic sequence and completion counts. Apply every event through the matching shared reducer; the final result remains authoritative. Under bounded queue pressure, heartbeats and progress updates may be dropped, but lifecycle and terminal events are retained.

Call handle.cancel() to request non-blocking cancellation, then await handle.wait_closed(timeout=5.0) to wait for shutdown without cancelling the worker if the wait expires. Cancellation emits sanitized stable metadata and final_result() raises an asyncio.CancelledError subclass. Other worker failures emit only stable public error metadata and raise StreamExecutionError; raw target responses and credentials are not exposed.

Target verify and session APIs

Module: nuguard.common.target_verify_public_api

  • TargetVerifyRequest
  • TargetVerifyCheck
  • TargetVerifyResult
  • TargetSessionResolveRequest
  • TargetSessionResolveResult
  • TargetVerifyStatus (ok, auth_failed, target_unavailable, endpoint_not_found, skipped)
  • verify_target(request, *, sbom=None)
  • resolve_target_session_public(request, *, sbom=None)

These APIs handle endpoint selection (config/SBOM/probe/default), auth bootstrapping, and target health checks before scans.

HTTP discovery and runtime use shared reply extraction, including nonempty outputs[].text, message lists, completion envelopes, and configured nested paths such as chat_response_key="outputs[0].text". Empty or error-only bodies and metadata alone do not validate a chat reply. Raw JSON retained for reporting is not reply-validation evidence.

When the message field is unknown, blind HTTP discovery checks whether omitting the candidate field causes a validation rejection naming that field. Generic empty-body errors and errors naming other fields remain inconclusive. The control keeps configured payload extras and adds at most one request per distinct omitted-field body on a candidate route. A greeting that also appears without the field leaves the candidate unconfirmed. SBOM/OpenAPI declarations or observed browser requests can provide field evidence; browser observation is followed by HTTP reply validation. This validates the request contract, not the semantic correctness of an AI answer. For API-only targets that accept missing fields, explicitly provide chat_payload_key and, for custom replies, chat_response_key.

Unconfirmed candidates are not cached as validated endpoints. Older endpoint confirmations are revalidated once under the updated contract rules; unrelated profile caches are retained. Browser discovery remains subject to the caller's existing enablement rules, and explicitly configured endpoints are not rotated.

When an SBOM is supplied, resolve_target_session_public() resolves a static-hosting target URL to the SBOM deployment URL before endpoint probing and session bootstrap. The returned effective_target_url reports the URL used for the resolved session.

For targets that obtain a token through a login request, set auth_type="login_flow" and pass the nested LoginFlowConfig model. Its endpoint, payload, token_response_key, token_header, and refresh_on_401 fields configure the complete login flow. No-login callers can omit both fields; auth_type defaults to "none".

from nuguard.common.auth import LoginFlowConfig
from nuguard.common.target_verify_public_api import TargetVerifyRequest, verify_target

request = TargetVerifyRequest(
    target_url="https://example-app",
    chat_path="/chat",
    auth_type="login_flow",
    login_flow=LoginFlowConfig(
        endpoint="/api/auth/login",
        payload={"username": "${APP_USERNAME}", "password": "${APP_PASSWORD}"},
        token_response_key="access_token",
        token_header="Authorization: Bearer",
        refresh_on_401=True,
    ),
)
result = await verify_target(request)

Output report/export APIs

Module: nuguard.output.public_api

  • ValidationReportMetaModel
  • RedteamReportRenderRequest
  • RedteamReportRenderResult
  • BehaviorReportRenderRequest
  • BehaviorReportRenderResult
  • ValidationReportExportRequest
  • ValidationReportExportResult
  • render_redteam_report(request, *, run_result)
  • render_behavior_report(request, *, run_result)
  • export_validation_report(request, *, redteam_run_result=None, behavior_run_result=None)

These provide stable in-process report rendering/export contracts without requiring CLI execution.

Schema contract and anti-drift

Public Pydantic surface is frozen by the contract test in tests/contracts/test_public_api_schema_contract.py against tests/contracts/public_api.schema.json.

When intentional public-model changes are made, regenerate the snapshot:

uv run python -c "import json; from tests.contracts.test_public_api_schema_contract import _live_schema_snapshot; open('tests/contracts/public_api.schema.json','w',encoding='utf-8').write(json.dumps(_live_schema_snapshot(), indent=2) + '\\n')"

Then run:

uv run pytest tests/contracts/test_public_api_schema_contract.py -v