Skip to documentation
GUIDES / VEHICLES / AIRCRAFT / API

Build with QRoadScan.

A practical API guide for route intelligence, private garages and aircraft briefings. Authenticate, send your first request, then build around clear schemas and limits.

ONE REQUEST · ONE FEATURE

Check destination approach risk.

Send a start and destination. Read the modeled risk of the last mapped section approaching your destination.

Set QRS_API_KEY to a server-side key with routes:write. Set QRS_REQUEST_ID to a UUID once; reuse it with the same body if you retry.

One route attemptServer-side

The API needs both endpoints to assess an approach. This is a modeled road-section score, not a verified driveway inspection or accident probability. A null score means no supported assessment.

Relevant response fields · illustrative

{"status":"proposal","destination":{
  "adjacent_section_risk_score":13,
  "access_verified":false
}}
Full route setup & reusable clients →
Loading the destination risk example…

This handbook describes the deployed QRoadScan application and its versioned HTTP API. It covers the browser workspace, private vehicle garage, road proposals, aircraft briefings, account security, and server integration. Examples use illustrative vehicles and public airport coordinates. Example performance values are not manufacturer recommendations, flight-planning standards, or observations about your vehicle.

The visible interface and the machine-readable OpenAPI specification serve different purposes. This handbook explains the workflows, assumptions, failure cases, and integration decisions. The specification lists request fields and endpoint contracts. Use both when building an integration. Keep your API key on your own server, and begin with the smallest permissions needed for the job.

API quick start

Start with the focused destination approach risk example above. For reusable server clients, see the complete route integration examples.

Choose a server client: Python httpx, async httpx, Python requests, JavaScript fetch, Axios, TypeScript, Go, C#/.NET, or PHP cURL. The complete examples below read credentials from server environment settings and include timeout, redirect, and error handling.

The versioned API uses the production base URL below. The URL path remains /api/v1/ for compatibility, while the capabilities response identifies the current additive API contract. Existing clients can continue using established endpoints. New clients should discover capabilities and key permissions before starting expensive work.

https://ride.qroadscan.com/api/v1

Create a named, expiring API key in Settings → API access. Choose Read-only, Road planner, or Full user API according to your integration’s needs. Copy the key once and put it in your trusted server’s secret store. The app does not show the raw key again. Changing a password ends browser sessions; it does not automatically replace every integration key, so revoke keys explicitly when required.

For a local server-side experiment, set the environment variable without committing it to a repository. The value below is a placeholder, not a usable key. Shell history, logs, shared terminals, build output, and crash reports can expose credentials, so use your normal secret-management practices.

export QRS_API_KEY='YOUR_PRIVATE_QRS_API_KEY'
export QRS_BASE='https://ride.qroadscan.com'

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/account" \
  -H "Authorization: Bearer $QRS_API_KEY"

A successful account response includes the current plan, account status, and available scan credits. Reading an account does not reserve a credit. If this first request fails, solve authentication or scope issues before submitting a scan, image, or route request. Do not debug authentication by repeatedly making paid model calls.

Next, inspect capabilities and the permissions on your current key:

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/capabilities" \
  -H "Authorization: Bearer $QRS_API_KEY"

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/key" \
  -H "Authorization: Bearer $QRS_API_KEY"

Capabilities describe supported surfaces, quotas, documentation links, and advisory scope. Key introspection returns the key’s identifier, scopes, and expiry metadata, not its secret. These discovery calls authenticate your key but do not require a separate content scope. They are useful when diagnosing why a valid Read-only key cannot create a vehicle or start a model analysis.

Delivery driver demo

See how one API feature fits into a small delivery app: the driver reviews the destination approach, inspects the returned instructions, and completes a mock delivery.

Parcel delivery-driver demo showing the route diagram, destination-approach risk and driver briefing

Open the interactive demo · Get the complete example source

The hosted preview uses a recorded response from a real API test at public Fifth Avenue endpoints. Opening it and switching its mock states do not send model requests or spend credits. The diagram draws the returned GeoJSON; its decorative city blocks are not a geographic basemap. The order and driver are fictional. It does not track GPS, provide live traffic or contact a dispatch service.

Run it locally

Requires Node.js 22 or later. No packages are needed:

git clone https://github.com/ornab74/roadscanner.git
cd roadscanner/examples/delivery-driver
node server.mjs
# Open http://127.0.0.1:8899

Without a key, it previews the recorded response. For a live request, configure a QRoadScan key with routes:write as QRS_API_KEY in the server environment before starting the server. The additional Run live API · 1 attempt button then appears. The key stays in Node; it is never included in browser HTML, JavaScript or storage. The local server posts to /api/v1/routes, and the UI reads endpoint_inspections.destination, steps, risk_summary and route_geojson.

Each new live analysis uses an eligible trial attempt or paid credit; failed free attempts still count. The local example permits at most three new upstream attempts per process, retains the browser's operation ID for retries, and returns cached successful responses on replay. This local guard is not an account-wide billing cap. The hosted preview has no live proxy endpoint.

This is a loopback-only teaching server, not a production deployment template. Before exposing a similar service publicly, add your own authenticated users, per-user ownership, CSRF protection appropriate to your session design, durable idempotency and budgets. Keep the existing QRoadScan account limits and permission checks. The app explicitly distinguishes unknown scores and unsupported connections from accepted route results.

More API demo apps

Explore two more complete example interfaces. Hosted previews use illustrative fixtures, not live observations or actual vehicle-clearance/flight decisions. Switching preview states uses no API calls or credits.

Haul — truck dispatch review

Truck-dispatch demo with vehicle dimensions, section caution and turn-review checks

Open truck demo · Source and local setup

Shows an articulated-truck profile, section-level caution, high-attention maneuvers and unknown restriction/clearance states. Live mode sends an owned truck vehicle_id to POST /api/v1/routes and reads truck_turn_review. Turn reviews are checks to perform, not approved swept paths or verified access.

# Node.js 22+, no packages required. Run from the repository root.
node examples/truck-dispatch/server.mjs
# http://127.0.0.1:8900

For live mode, configure QRS_API_KEY with routes:write and QRS_DEMO_TRUCK_ID with the UUID of an owned truck profile before starting. Each new analysis uses an eligible route attempt; the existing free/paid limits apply. Vehicle dimensions come from that profile, not from the illustrative preview.

Aero — aircraft briefing review

Aircraft-briefing demo with missing-provider states, illustrative wind samples and a review checklist

Open aircraft demo · Source and local setup

Combines airport-weather availability, surveillance availability, corridor wind samples, incomplete fuel assumptions and a human-review checklist. The preview's wind values are explicitly fictional fixtures. Unavailable traffic never becomes “clear airspace”; missing fuel inputs never become a zero-fuel estimate. This is an advisory evidence interface, not ATC, collision avoidance, flight authorization or verified routing.

node examples/aircraft-briefing/server.mjs
# http://127.0.0.1:8901

For live mode, configure QRS_API_KEY with aviation:review and QRS_DEMO_AIRCRAFT_ID with an owned aircraft UUID. The server calls POST /api/v1/aviation/briefing for the fixed KGSP–KAVL scenario. No usable-fuel amount is assumed; incomplete aircraft assumptions remain incomplete. Aviation provider/AI quotas apply independently of the road trial, and upstream availability varies.

Both servers keep keys and profile IDs server-side, bind only to loopback, require the exact local Origin for requests, limit body sizes, cache results within the process and allow at most three new upstream attempts per process. No hosted live proxy is enabled. The aircraft endpoint does not promise upstream idempotency: after a transport failure its local operation is marked uncertain and is not automatically sent again. These are teaching apps; add authentication, ownership, durable operation storage and production budgets before any public deployment.

Create a route from endpoints

POST /api/v1/routes is the recommended route-creation endpoint for server integrations. Supply coordinates; the server assembles the primary labeled overview, street and satellite endpoint close-ups, corridor imagery and available weather. You do not need to upload a browser map capture. The existing /api/v1/route/analyze interface remains available for integrations that explicitly supply georeferenced imagery.

This performs a real request through the mapping, weather and model pipeline. It is a review of available mapped data and imagery—not a live camera inspection, traffic feed, legal-turn certification or guaranteed safe route. Satellite image dates can be unknown. Coordinates identify the chosen endpoints; they do not prove that a particular driveway is usable.

Request contract

Field Required Meaning
start Yes Object with numeric latitude and longitude only
destination Yes Same coordinate shape as start
mode No driving (default) or walking
objective No balanced (default), fastest, simplest, caution, or fuel
vehicle_id No UUID of an owned car, motorcycle or truck profile
notes No At most 1,200 characters of route preferences and endpoint details

Latitude is limited to −84.8 through 84.8; longitude to −180 through 180. Endpoints must be at least one meter apart and no more than 90 km apart by direct distance. The bounded road-data coverage can impose a smaller usable area. Cross-antimeridian routes are not currently supported. Unsupported requests fail validation before a scan reservation or provider work. Unknown fields, arbitrary URLs and client-supplied model instructions are not accepted as configuration.

If you start from addresses, call POST /api/v1/route/geocode with {"query":"YOUR ADDRESS, CITY, POSTCODE"}, inspect the returned candidate labels and precision, and choose the correct coordinates. Do not silently use the first ambiguous or street-only result as an exact home entrance. Geocoding uses provider data; it does not consume a model scan allowance, but search rate limits apply.

cURL: create one route

Set QRS_API_KEY on your trusted server first. The example endpoints are public locations in Manhattan, not a private residential address.

# Generate this once; retain it if you need to retry the same operation.
QRS_ROUTE_ID="$(python3 -c 'import uuid; print(uuid.uuid4())')"
curl --fail-with-body --silent --show-error --max-time 240 \
  'https://ride.qroadscan.com/api/v1/routes' \
  -H "Authorization: Bearer $QRS_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $QRS_ROUTE_ID" \
  --data '{
    "start":{"latitude":40.75854190779626,"longitude":-73.97720754146576},
    "destination":{"latitude":40.753478752021245,"longitude":-73.98087680339813},
    "mode":"driving",
    "objective":"balanced",
    "notes":"Review visible crossings and the final public entrance."
  }'

Python httpx: inspect geometry and section risk

import os
import uuid
import httpx

operation_key = str(uuid.uuid4())  # Persist with the unchanged request for recovery.
journey = {
    "start": {"latitude": 40.75854190779626, "longitude": -73.97720754146576},
    "destination": {"latitude": 40.753478752021245, "longitude": -73.98087680339813},
    "mode": "driving",
    "objective": "balanced",
}
with httpx.Client(timeout=httpx.Timeout(240, connect=10), follow_redirects=False) as client:
    response = client.post(
        "https://ride.qroadscan.com/api/v1/routes",
        headers={
            "Authorization": f"Bearer {os.environ['QRS_API_KEY']}",
            "Idempotency-Key": operation_key,
        },
        json=journey,
    )
    response.raise_for_status()
    route = response.json()

if route["status"] != "proposal" or route.get("geometry_alignment", {}).get("status") != "matched":
    print("More context needed:", route["summary"])
    print(route["endpoint_inspections"]["guidance"])
else:
    print("Modeled caution index:", route["risk_summary"]["distance_weighted_score"])
    print("Scored-distance fraction:", route["risk_summary"]["scored_distance_fraction"])
    for step in route["steps"]:
        print(step["index"], step["instruction"], step["distance_m"], step["risk_score"])
    # Render route["route_geojson"] with a GeoJSON-capable map library.
    # GeoJSON coordinate order is [longitude, latitude].

JavaScript: server-side request

// Node.js server only. Retain the idempotency key and body for recovery.
const operationKey = crypto.randomUUID();
const response = await fetch("https://ride.qroadscan.com/api/v1/routes", {
  method: "POST",
  redirect: "error",
  signal: AbortSignal.timeout(240_000),
  headers: {
    Authorization: "Bearer " + process.env.QRS_API_KEY,
    "Content-Type": "application/json",
    "Idempotency-Key": operationKey
  },
  body: JSON.stringify({
    start: {latitude: 40.75854190779626, longitude: -73.97720754146576},
    destination: {latitude: 40.753478752021245, longitude: -73.98087680339813},
    mode: "driving"
  })
});
if (!response.ok) throw new Error("Route HTTP " + response.status);
const route = await response.json();
if (route.status === "proposal" && route.geometry_alignment?.status === "matched") {
  console.log(route.route_geojson, route.steps, route.risk_summary);
} else {
  console.log("No connected route accepted:", route.summary);
}

What the response provides

Property Use it for Interpretation
route_geojson Draw one connected proposal with independently styled sections FeatureCollection; each feature is a section LineString in longitude/latitude order
steps Build a turn-instruction list Instruction, street, section distance, modeled score, reason and provenance; not verified lane navigation
risk_summary Compare modeled caution and score coverage Distance-weighted score, peak, unknown sections and illustrative-baseline distance fraction
segments Access the original mapped review Includes section geometry, components and supporting explanation
endpoint_inspections Review the first and last approach Chosen coordinates, mapped offsets, adjacent section scores, relevant imagery IDs and guidance
weather Display source estimates and their validity Missing estimates remain missing; they are not street-surface observations
imagery_manifest Explain the captured views and their bounds Includes the server overview; raw image bytes are not retained in the report
route_metrics Display distance and time/fuel scenarios Class-based estimates, not measured traffic or guaranteed arrival/consumption
operation_id, report_id Recover work and load a saved result Use owned operation/report endpoints and least-required read scopes

The summary score averages only scored section distance. Always display scored_distance_fraction alongside it: a low index with poor coverage does not describe the whole journey. peak_score describes the largest available section index. Null scores stay unknown; do not replace them with zero. illustrative_baseline_distance_fraction tells you how much route length uses a modeled baseline rather than a weather/map-specific scoring basis. Scores are indices on a 0–100 scale, not accident probabilities or a measured percentage of safety.

For a chromographic ribbon, style each feature using its own risk_score and score_basis. One display convention is green below 40, amber from 40 to 74, red from 75, and gray for null/unsupported. Keep the explanation available on selection. A visual color does not turn a hypothesis into observed evidence.

An endpoint's adjacent_section_risk_score is the score of the accepted first/last mapped section, not a separate certified driveway hazard scan. access_verified remains false. Review the entrance imagery, mapped offset and endpoint guidance. Apartment numbers, indoor access, current obstacles and private permissions need independent confirmation.

A needs_context result contains empty steps and empty GeoJSON features with a null route summary score. No straight line is substituted for a missing road connection. If imagery or the model is unavailable, an error can be returned instead. Paid credits follow the refund rules; an admitted free attempt remains counted. One call requests one objective; comparisons require separate calls with separate idempotency keys and separate attempts.

Free access and usage limits

Registration is open. Create an account at Register, accept the Terms, then sign in. The first dashboard visit offers a four-step guide that you can reopen with Quick start. You do not need to provide an API-provider key to use the browser trial.

Allowance Per account Shared service ceiling Reset
Browser scene/route analysis Up to 5 free attempts 50 free attempts per UTC day; 500 per UTC month, combined with API trials Midnight UTC; unused attempts do not accumulate
API scene/route trial 3 free attempts total, across all keys Same shared ceilings No daily or monthly refill
Account, capabilities and key reads No scan allowance Ordinary request rate limits See response headers
Vehicle image generation Not included in free scans Requires an existing paid balance and PHF approval Existing image-specific limits

These are attempt allowances. An admitted free request still counts if the model fails, needs more context, or the request's reservation expires: upstream work can cost money even when no route is saved. Replaying a completed request with the same key and idempotency key does not create a new attempt. A new idempotency key represents new work. Paid credits retain their existing debit/refund rules.

The browser allowance cannot be moved into an API key. Creating another key does not refill the API trial. Four-objective comparisons can consume four attempts. A balance can change between checking it and submitting: the database makes the final reservation atomically, including concurrent requests. Shared limits may stop free access before an individual allowance is exhausted. Existing paid credits may fund work after a trial limit is reached; payments and automatic overages remain disabled.

Check GET /api/v1/account before metered API work. api_credits is paid balance plus currently available API trial attempts; browser_scan_credits is paid balance plus currently available browser attempts. These two totals overlap in the paid balance: do not add them together. paid_credits is the actual stored paid balance. free_allowance describes the trial limits and remaining amounts.

{
  "plan": "free",
  "status": "active",
  "api_credits": 3,
  "paid_credits": 0,
  "browser_scan_credits": 5,
  "free_allowance": {
    "enabled": true,
    "reset_timezone": "UTC",
    "browser_daily_limit": 5,
    "browser_remaining": 5,
    "api_trial_limit": 3,
    "api_trial_remaining": 3,
    "shared_daily_limit": 50,
    "shared_monthly_limit": 500,
    "shared_remaining": 50,
    "failed_attempts_count": true
  }
}

This illustrative response omits the server's current day field. An exhausted allowance without paid funds returns 402 insufficient_api_credits. A rate limit can independently return 429. Do not poll either failure in a tight loop. These limits control free scan admission, not a guaranteed dollar ceiling on Cloudflare or AI-provider invoices. Homepage previews, speech, aircraft evidence and other features retain their own separate controls.

Authentication and request lifecycle

  1. Create an account in the browser and sign in. If you enroll a security key, keep a spare: password-plus-key sign-in is required thereafter.
  2. In Settings → API access, create a named, expiring key. Start with Road planner for road work, or Read-only for inspection.
  3. Store the raw value once as QRS_API_KEY in your server's secret store. It is a QRoadScan key, not your OpenAI, Grok or Cloudflare credential.
  4. Send Authorization: Bearer ... over HTTPS. Do not put credentials in query strings, frontend bundles, mobile source code or analytics logs.
  5. Verify GET /api/v1/key and GET /api/v1/account before metered work. Choose the least required scope below.
  6. For scans, route analysis and image generation, generate an idempotency key of 16–128 allowed characters. Reuse the same key and unchanged payload only when recovering that same operation.
  7. Use a bounded request timeout. A transport timeout is not proof that provider work stopped. Check operation status where an operation ID is available, or retry with the original idempotency key.
  8. Inspect semantic status as well as HTTP status. A route can return needs_context without a usable navigation proposal. Never treat that as a connected road route.
  9. Save owned report IDs, request IDs and safe error codes. Redact keys, private images and full home-address payloads in logs.

API Bearer requests do not use the browser CSRF-token flow. Browser session mutations do require the signed CSRF token and same-origin checks. An API key never grants admin publishing rights, account password changes or security-key management.

Endpoint reference

The table below is generated from the deployed OpenAPI source. Use the workflow guides below for request bodies, examples and interpretation. Download OpenAPI 3.1 to import the full schemas into your API tooling. No browser “try it” widget sends private keys or spends your allowance implicitly.

Method Endpoint Required scope Purpose
POST /api/v1/scans scans:write Run and store one road-risk scan
GET /api/v1/account account:read Read the authenticated API account and credit balance
GET /api/v1/garage/vehicles garage:read List your private garage and active vehicle
POST /api/v1/garage/vehicles garage:write Create an encrypted vehicle profile (maximum 20 active vehicles)
PUT /api/v1/garage/active garage:write Set active garage vehicle (null clears selection)
GET /api/v1/garage/vehicles/{vehicle_id} garage:read Read an owned vehicle
PUT /api/v1/garage/vehicles/{vehicle_id} garage:write Replace a vehicle using its current version; clears illustration when appearance changes
DELETE /api/v1/garage/vehicles/{vehicle_id} garage:write Delete an owned vehicle and schedule its encrypted illustration for removal
GET /api/v1/garage/vehicles/{vehicle_id}/image images:read Retrieve owned private PNG illustration
POST /api/v1/garage/vehicles/{vehicle_id}/image images:write Generate GPT Image 2 illustration, gated by input/output PHF, costing one scan credit
POST /api/v1/garage/vehicles/{vehicle_id}/guidance garage:read Read mode-specific advisory checklist and optional area weather
GET /api/v1/aviation/config aviation:read Providers, quotas and advisory scope (no secrets)
POST /api/v1/aviation/snapshot aviation:read Aircraft briefing snapshot with OpenSky traffic, AWC METAR/TAF, winds aloft and fuel scenario
POST /api/v1/aviation/briefing aviation:review Refresh aircraft evidence, modeled caution report and hypothetical traffic scenarios
GET /api/v1/capabilities Authenticated key Discover supported features, quotas and scopes
GET /api/v1/key Authenticated key Inspect the current key without exposing its secret
GET /api/v1/reports scans:read List owned reports with signed cursor pagination
GET /api/v1/reports/{report_id} scans:read Read an owned completed report within retention
GET /api/v1/operations/{operation_id} operations:read Inspect owned metered operation state
GET /api/v1/garage/vehicles/{vehicle_id}/marker garage:read Retrieve a free transparent type/color SVG map marker
POST /api/v1/route/geocode routes:write Search candidates with precision and source metadata
POST /api/v1/route/atlas routes:write Preview automatic endpoint/corridor imagery metadata without model credit
POST /api/v1/route/analyze routes:write Analyze real georeferenced map imagery into an unverified road proposal
POST /api/v1/routes routes:write Create one mapped route and modeled section-risk review from endpoints

Common request headers

Header When to use Notes
Authorization: Bearer $QRS_API_KEY Every versioned API request Keep it on your trusted server
Content-Type: application/json JSON request bodies Unsupported content types are rejected
Idempotency-Key: UUID Metered mutations Same operation, same body, same key
Accept: application/json Optional Errors may use application/problem+json

Response envelopes and pagination

Account and key endpoints return objects directly. Report lists return data, pagination and meta. Follow the signed pagination.next_cursor with the same account; do not edit the cursor or assume a numerical offset. Report ownership is enforced even if another ID is guessed. Image and marker endpoints return image bytes, so do not parse those bodies as JSON.

API versioning and compatibility

The URL prefix is /api/v1. The capabilities document reports the additive API contract version; that number is distinct from the path prefix. Clients should tolerate extra response fields, handle documented enum/status cases, and reject unsafe assumptions about unknown proposal states. The machine-readable specification documents HTTP contracts; the guides explain data provenance and workflow limits.

Quick start in the app

Start at Home, create an account if registration is open, and sign in. Your account can have a garage, private API keys, security keys, signed-in sessions, and saved scan reports. Creating an account does not purchase credits or automatically grant administrator access. Purchases are currently disabled. If your account has no scan credits, you can still manage its settings and inspect the available briefing tools; metered analyses and generated illustrations require an existing credit balance.

Open Settings → Garage and add a vehicle. Choose its actual vehicle type explicitly. A motorcycle should be saved as motorcycle, an articulated truck as truck, and an airplane as aircraft. The make or model text does not silently override the type. This matters because the type selects the appropriate workspace, advisory language, specifications, and transparent map icon. The garage highlights the known Kawasaki Z125/type mismatch and offers a correction that you must choose yourself.

For a road journey, select your garage vehicle in Dashboard, choose a start and destination, and inspect the map. You may type coordinates, search for an address, or choose points on the map. Confirm the returned address precision before continuing. Select Streets for labeled road context. Satellite imagery can help inspect an entrance, but it does not establish that a private road, loading bay, doorway, or apartment corridor is legally accessible.

Run a route analysis only after confirming both endpoints. The application captures an overview and a bounded atlas of endpoint and corridor images, requests a model proposal, and tries to align that proposal to imported mapped road shapes. A completed route proposal normally uses one credit. A request for more context returns the reserved credit. Read the limitations and review the proposed street sections before using fullscreen GPS preview.

For an aircraft, use Aircraft briefing. Select a saved aircraft profile, provide the airport codes and coordinates, enter the scenario altitude and usable fuel, then refresh the evidence. Airport codes and map coordinates are separate user inputs; the application does not verify that they refer to the same airport. Review traffic availability, airport observations and forecasts, pressure-level winds, and the explicit fuel assumptions. An optional AI review explains the supplied evidence; it does not authorize a flight.

What the different outputs mean

QRoadScan has several distinct surfaces. They should not be treated as interchangeable measurements. The homepage’s Grok guess-mode colorwheel creates a fictional road scene and a modeled score. It is not a live sensor reading, a location-specific accident probability, or proof that a road is safe. Refreshing that simulation calls the configured provider rather than reusing a stored simulated reading.

A scene scan assesses observations supplied by the user or API client. If you submit “rain,” “heavy traffic,” or “construction,” the model considers those statements as inputs. It does not independently prove them. The returned report identifies the supplied observations and provider provenance so an integration can preserve that distinction.

A visual road proposal uses map images, selected endpoints, available weather estimates, and a model-generated corridor. Imported road geometry improves how a ribbon follows mapped streets. It does not validate every turn restriction, bridge capacity, property boundary, road closure, lane, or legal maneuver. Weather caution scores are modeled severity indices, not calibrated accident probabilities.

A garage illustration is artwork. It can reflect a make, model, color, year, and holiday theme, but it is not a verified photograph or a record of a vehicle’s mechanical configuration. Never derive aircraft performance, truck clearance, tire condition, braking capability, or manufacturer specifications from that artwork. The tiny map marker is a separate transparent vector representation based on the saved type and color; it does not require another image-generation credit.

An aircraft briefing combines independently timestamped external sources with user-supplied assumptions. OpenSky positions can be incomplete or delayed. METARs describe airport observations. TAFs describe airport forecasts. Winds aloft are model samples at pressure levels. Fuel figures are deterministic scenario arithmetic. AI commentary is interpretation of that evidence, not certified ATC, separation, collision avoidance, dispatch authority, or a go/no-go decision.

Account, credits, and privacy basics

Account resources are private to their owner. A garage profile, private illustration, saved report, or active vehicle selection cannot be read merely by guessing its identifier. API keys inherit the owning account’s resource boundary, and the server enforces permissions on every relevant endpoint. An administrator’s browser role does not turn an ordinary API key into an administrator credential.

Credit reservations occur before a metered provider operation. A successful scene scan, completed road proposal, or delivered garage illustration uses one credit. Provider failures and blocked illustration checks refund the reservation. A route response with needs_context also refunds it. A network timeout on your client is different from an explicit failure: the server may still be processing. Keep the same idempotency key when checking the same logical operation so you do not unintentionally create another charge.

The browser uses Secure, HttpOnly, host-only session cookies. State-changing browser requests require a signed CSRF token and the correct origin. API requests under /api/v1/ use an explicit Bearer key and do not fall back to a browser session. Do not copy the browser’s session cookie into a server integration, and do not put a server API key in a public JavaScript bundle or a query string.

Vehicle profiles and stored reports are encrypted at rest. Generated image blobs are encrypted with an owner/vehicle/image binding. Private image responses use no-store and require authentication. The application does not publish a public bucket URL for your illustration. Provider services necessarily receive the bounded input needed to fulfill an explicit model request; their own processing terms and retention policies also apply.

Do not include a VIN, home address, license plate, account password, provider key, or other unnecessary personal information in a vehicle’s appearance notes. A descriptive phrase such as “olive camouflage panels with a black seat” is useful. A registration document or secret key is not. Appearance fields are descriptive data, not a place to instruct the application to change its security policy.

Garage profiles and vehicle types

The garage supports up to twenty active vehicles per account. Each vehicle has a display name, kind, optional make and model, optional year, color description, holiday theme, appearance notes, and a type-specific specifications object. The display name is for your organization; it is not an authentication identifier. The server assigns a UUID and an optimistic version to each saved profile.

Choose a vehicle type before saving a new profile. A model name can be ambiguous, and several manufacturers sell cars, motorcycles, boats, industrial equipment, or multiple aircraft categories. QRoadScan does not silently turn a manufacturer name into an operating classification. If a profile was saved under the wrong type, correct it explicitly. A type-only correction retains existing artwork when the descriptive appearance fields remain unchanged; the map marker updates from the corrected type.

A car profile can carry a mass assumption. A motorcycle profile can carry engine displacement and mass. A truck profile can carry height, width, length, gross mass, axle count, and a hazmat flag. A train profile can carry length, mass, rail gauge, and traction type. An aircraft profile can carry true airspeed, cruise fuel burn, usable capacity, fuel unit, scenario reserve, ICAO type designator, and optional OpenSky ICAO24 identifier.

These fields are user-supplied. The application validates their type and broad bounds, but that is not a verification against a manufacturer database. A plausible-looking number can still be wrong. Use the appropriate manual, operator records, or other authoritative vehicle documentation. Do not guess a truck’s loaded mass or an aircraft’s usable fuel capacity from its model name.

Editing a profile requires its current version. If another tab or client updates it first, a stale replacement returns 409 vehicle_changed. Reload the current profile, reconcile your edits, and submit a new replacement with the new version. Do not blindly resubmit a stale body, because that could overwrite a legitimate change made elsewhere.

Appearance changes clear an obsolete illustration so the garage does not display old artwork as if it represented the new description. Changing the display name or performance assumptions does not require regenerating the art. Deleting a vehicle clears its active selection, makes its private resources unavailable, clears the encrypted profile contents, and schedules retained image objects for cleanup.

Vehicle illustrations, PHF, and holiday themes

The garage’s Generate image action uses the configured GPT Image 2 model. It is explicit: saving a vehicle, selecting a theme, viewing a card, or opening the map does not generate an illustration. A successful delivered image costs one existing scan credit. Generation attempts have daily account and global limits, including failed attempts; this bounds provider spending and discourages repeated filter probes.

PHF means Probabilistic Harm Filtering in this project. The Cloudflare image workflow uses bounded local instruction checks plus structured provider moderation. The description must pass before generation, and the generated image must pass before delivery. A missing, malformed, flagged, or unavailable filter result is not treated as approval. The reserved scan credit is refunded when filtering or image generation fails.

The generation prompt asks for the entire vehicle, realistic model proportions, and empty space around outer extremities. The garage card fits the full image inside its display box rather than allowing the image’s intrinsic dimensions to stretch and crop it. Select the illustration to open a larger view. The card is a display of artwork, not a measurement of vehicle dimensions.

Themes include Original, Winter, Halloween, Autumn, Festive lights, and Lunar New Year. Themes are visual: they should not imply that decorations are safe to install on a real vehicle. The prompt requests that decorations avoid obstructing lights, windows, wheels, propellers, intakes, rails, and controls. Actual installations remain a separate real-world engineering and operating decision.

If the image seems to describe a different kind of vehicle, first inspect the saved vehicle type and model. A Z125 entered as a car is a profile mismatch even if a model recognizes the motorcycle name and draws a motorcycle. Correct the type so guidance and markers agree with the actual vehicle. You do not need to spend another image credit merely to fix how an already-generated picture is framed in the card.

Generated images remain private and expire after ninety days. A successful response includes a browser image_url for the app, but a server API client should download through the corresponding /api/v1/garage/vehicles/{id}/image endpoint with its Bearer key. Do not remove authentication simply to make a third-party image tag load. Instead, fetch the image on your trusted server and apply your own authorized delivery policy.

Transparent map markers and GPS position

The small vehicle marker is designed for legibility over a map. It has a transparent background, a type-specific top-down shape, a color selected from the garage profile, and limited holiday accents. Cars, motorcycles, trucks, trains, and aircraft have distinct silhouettes. Camouflage descriptions receive an illustrative camouflage palette. The marker is not a tiny crop of the garage’s full-size studio image, which would retain a background and become unreadable at navigation scale.

A marker with an A badge identifies the selected start point. It is a preview of where you chose to begin, not proof that your device or vehicle is physically there. Actual road GPS position uses the device’s geolocation updates during fullscreen guidance. When the device reports a valid heading, the vehicle icon can rotate with that heading. If heading is missing, the drawing’s default orientation should not be interpreted as a compass measurement.

GPS guidance is available only for supported mapped road proposals and only in fullscreen mode. It displays distance to the next proposed section, time at current speed, remaining proposed distance, speed, and reported accuracy. It stops when fullscreen closes, the page is hidden, the user stops it, or the route context changes. An old queued geolocation callback must not restart a stopped session.

The fullscreen cockpit separates the next maneuver from journey progress. The maneuver card shows a large distance, the upcoming instruction, the current road and a subsequent “then” instruction. The journey card shows the current matched section, its caution index, remaining distance and progress. Tap the caution button to inspect that section’s explanation on the map.

Arrival time and remaining travel time are current-pace estimates, calculated from remaining proposed distance and a usable device-reported or derived speed. They do not include traffic, future stops, speed-limit changes or road restrictions. When speed is unavailable or below 1.5 m/s, the arrival estimate is withheld rather than extrapolating a stationary position.

Overview fits the proposed route and pauses automatic following. Recenter returns to the device marker and restores following. Dragging the map or inspecting a route section also pauses following so it does not fight manual inspection. The GPS accuracy ring represents the reported location uncertainty; it does not identify obstacles or a safe clearance zone.

Voice is optional and off by default. In fullscreen, open Voice settings, choose GPT natural voice, and select Atlas · warm & reflective or Clear · focused. Preview voice plays a fixed introduction; Read route overview reads the saved route summary. Check Voice to enable automatic maneuver cues. Mute disables automatic speech and stops current audio.

Atlas is an original delivery preset using OpenAI's built-in cedar voice with gpt-4o-mini-tts. It is not a cloned person, an impersonation, or a separately trained custom voice. The warm preset uses relaxed phrasing and punctuation pauses for summaries; turn and arrival instructions prohibit added fillers and invented directions. The focused preset uses a more direct delivery. The interface explicitly labels GPT speech as AI-generated.

Automatic cues follow section changes and distance bands rather than speaking on every GPS update. Cloud audio arriving too late for its cue is discarded. Stopping, hiding the page, leaving fullscreen, or losing a usable fix aborts pending audio and cancels playback. A changed maneuver also cancels the prior cue. Arrival speech is distinct from approaching the final section; entering that section alone does not claim arrival.

Device voice uses browser speech. When GPT generation or playback fails, the app uses device speech if supported and stops trying GPT on each subsequent cue. Use Preview voice, change a voice setting, or re-enable Voice to retry GPT deliberately. Browser speech, autoplay and audio support vary by device.

GPT TTS uses the operator's existing OpenAI key and provider billing; it does not deduct application scan credits. Requests are bounded to 12 per minute and 120 per hour per account, with global hourly and daily caps. API keys remain on the server. Generated audio is delivered with Cache-Control: no-store; it is not retained in R2 or saved reports. Browser object URLs are revoked when playback ends or is canceled. The server accepts fixed previews or owner-scoped saved route text, not arbitrary user-supplied speech or voice instructions.

The browser endpoint is POST /api/route/voice with the signed session cookie and X-CSRF-Token. It returns audio/mpeg. Example bodies are {"cue":"preview","preset":"atlas"}, {"cue":"summary","preset":"atlas","report_id":123} and {"cue":"turn","preset":"clear","report_id":123,"section_index":1,"distance_m":160}. The section index identifies the upcoming saved section to enter; the distance is a device-derived estimate, not server verification of vehicle location. This browser endpoint does not accept bearer API keys. GET /api/route/voice returns availability and preset metadata to the signed-in browser.

Freshness is checked along with accuracy: positions older than 15 seconds pause turn cues and clear travel estimates until a fresh usable fix arrives. The UI distinguishes tracking, low accuracy, stale GPS, off-route and near-endpoint states. A stale or inaccurate position does not produce an invented reroute.

Poor reported accuracy and off-route positions pause turn cues. The app does not use a pretend GPS position when a desktop cannot provide location. You can still choose endpoints, inspect a route proposal, or view weather evidence without a live position. Do not interpret the selected start marker as a substitute for a valid GPS fix.

The aircraft page’s surveillance positions come from OpenSky when that feed is available, not from the decorative garage icon or the road GPS watch. Reported aircraft positions are a different data source with different latency, coverage, altitude references, and limitations. No aircraft maneuvering or separation instructions are generated by moving a marker.

Car route workflow

For a car journey, start with a correctly typed car profile or the generic road profile. Select both endpoints and verify that the map includes them. If an address search returns a street or area rather than a mapped house number, adjust the point manually and inspect the intended entrance. An apartment or suite identifier may be removed for address matching; that does not locate the unit inside a building.

The road workspace combines a labeled overview with automatic endpoint street and satellite views and overlapping corridor panels. The image manifest identifies the role, bounds, dimensions, and provider of each automatic view. The model is instructed to reconcile those views rather than relying solely on a zoomed-out overview or remembered street knowledge.

Imported map geometry supplies the road coordinates used for a solid ribbon when a supported connection is found. The model reviews the candidate and annotates its sections. The alignment process is conditioned on the visual corridor; it is not an independent legal routing engine. A road shape in a map can still be closed, private, incorrectly connected, grade-separated, or subject to a restriction not represented in the imported data.

The initial model corridor is a suggestion, not a user requirement. The final review evaluates the connected mapped candidate itself and can describe a reasonable alternative street sequence. A road mentioned by the first model does not become mandatory merely because it appeared in that summary. Explicit preferences you supply, such as via or avoid a named road, still constrain the review. If a route cannot be completed, the status beside the planning controls shows the specific summary as well as the returned-credit notice.

Read each proposed maneuver and its evidence. “Turn left” in a proposal is not proof that the turn is currently permitted. Follow actual signs, signals, closures, road markings, and applicable rules. The application does not certify lane selection, right of way, speed choice, or access to a private driveway. Use the proposal as reviewable context, not an authority that overrides the road.

When the system returns needs_context, it should identify missing evidence or an unsupported connection. The reserved credit is returned, and no completed route report is saved for that failed proposal. Improve the endpoint placement, use a shorter corridor, or provide a readable site plan or directory. Do not fabricate a connection through a building or across a barrier to force a colored ribbon.

Road alignment failures include alignment_failure.code and an operation_id reference. The message distinguishes a service/tile outage, timeout, endpoint offset beyond 150 m, unsupported distance/area, a graph with no directed connection, corridor-name mismatch, excessive detour, a 60-section limit, and resource limits. A service or tile download failure receives at most one automatic retry; a rejected graph or corridor is not retried by relaxing its validation. No additional model call or scan credit is used for that download retry. Fixed diagnostic codes are retained with the refunded operation and logged without addresses, coordinates, images or raw provider errors. Older failures did not retain their underlying alignment exception, so their generic message cannot establish the precise historical cause.

Road color and severity interpretation

New approved mapped routes use NAZA-inspired mandatory classification: the model returns an integer index from 0 to 100 for every section, even when weather, traffic or a street name is missing. Missing conditions no longer force the whole route to grey. Each section shows a numeric badge and its score_basis: weather_estimate (weather-informed model), map_context (mapped features and vehicle context), or illustrative_baseline (an explicitly illustrative estimate when observations are sparse). The baseline is chosen by the model, not a fixed fallback percentage, random color, CPU reading or simulated quantum measurement. This follows NAZA's classify-despite-unknown-inputs approach, without presenting synthetic signals as real-world evidence.

An illustrative score is not a measurement, calibrated accident probability, known road condition or clearance certificate. Weather, surface, access and traffic gaps remain explicit even when a numeric index is displayed. A weather estimate near a street is an area forecast, not a measurement of grip on that exact lane. Color differences need a stated modeling reason, rather than cosmetic variety.

New reports use risk_scoring.version: section-components-v2 and probability: false. The LLM assigns five integer risk_components to each section; the application computes risk_score as the rounded weighted sum below. These are modeling weights, not empirically calibrated accident statistics. The raw model's overall score is superseded by this explicit calculation.

Component Weight Basis
geometry 25% Mapped bends and bending per kilometer; length alone does not imply difficulty.
maneuver 25% Entry heading change and supported connection complexity; legal turns remain unverified.
weather 20% Available time-specific area forecasts; unavailable conditions require an illustrative hypothesis.
vehicle 20% Additional demand for the selected vehicle, using supplied specifications and evidence.
uncertainty 10% Missing or ambiguous section context, kept distinct from an observed hazard.

The component rubric uses low, moderate and high anchors and does not stretch the scores to fill the available color range. Similar sections can still receive similar indices. Each section card and map popup displays the breakdown, rationale and basis. Saved reports keep their original scoring version; run a new analysis to apply the revised rubric.

Click a ribbon to highlight and inspect that section. Clicking close to a ribbon also selects it; background clicks do not reposition endpoints. Choose Pick start on map or Pick destination to enable one endpoint-placement click. That mode stops after placement. These endpoint pins are planning inputs, separate from the GPS position.

Road shape and road labels are imported separately. Label-only vector features now supply names rather than being treated as drivable roads. Names may be recovered from a sufficiently close, aligned map-label segment and carry name_provenance: DERIVED_FROM_MAPPED_LABEL. Ambiguous labels are left unresolved; an actual missing name is shown as a road-class connector, never filled with an invented street name. Old saved reports keep their original scores and labels. Re-analyze to apply the updated matching and scoring; a previously grey report is not silently rewritten.

The optional NAZA-inspired state layer is a labeled two-qubit simulation. It changes a decorative fringe or pulse and has a baseline off switch. It does not change mapped coordinates, reported weather, risk scores, or vehicle performance. A reproducibility receipt identifies a simulation state; it is not a signature proving real-world safety or evidence of a physical quantum sensor.

Motorcycle guidance

Garage profiles now accept an optional boolean specs.abs. Leave it unspecified when unknown. Selecting No saves false; an empty selector omits the field. ABS is equipment context and does not prove traction. The route profile panel summarizes the motorcycle-specific focus, and the same structured focus reaches both visual planning and the mapped-section annotation pass.

Save a motorcycle as motorcycle so the garage icon and route context reflect two-wheel exposure. Engine displacement and mass are descriptive assumptions, not a complete handling or braking model. A motorcycle’s real behavior also depends on tires, loading, suspension, road surface, rider skill, maintenance, and conditions that the application does not measure.

The model’s motorcycle context emphasizes wind exposure, precipitation, visibility, temperature, and uncertainty about surface grip. A weather forecast does not establish that a particular corner is dry, wet, icy, contaminated, or free of gravel. A low weather caution score is therefore not permission to select a particular lean angle, entry speed, following distance, or braking technique.

Use the satellite and street context to inspect a proposed entrance or intersection, but remember that imagery may be old. Small obstacles can be invisible, and a route image does not show whether a driver has yielded. If the model cannot support a street connection, the correct result is a request for more context, not a confident motorcycle shortcut.

For the Kawasaki Z125 example, distinguish the model description from the saved type. The garage can highlight that specific mismatch and offer a type correction. The user chooses whether to apply it; the application does not silently rewrite every manufacturer/model entry. After changing operating specifications, re-analyze a route when you need guidance to reflect the new profile.

Trucks, 18-wheelers, and commercial loads

Choose specs.configuration as articulated for a tractor/trailer combination or rigid for a rigid truck. The label “18-wheeler” never fills in dimensions, mass or axle count automatically. length_m describes the entire combination; trailer_length_m describes the trailer. The dashboard's expandable guidance panel lists relevant missing fields so you can update Garage before re-analysis. The prompts emphasize off-tracking, trailer swing, junction geometry, loading-site access, and the evidence needed to verify restrictions.

Illustrative API profile, with deliberately explicit values rather than model-derived specifications:

{
  "name": "Example combination",
  "kind": "truck",
  "specs": {
    "configuration": "articulated",
    "height_m": 4.0,
    "width_m": 2.5,
    "length_m": 22,
    "trailer_length_m": 16,
    "mass_kg": 35000,
    "axles": 5,
    "hazmat": false
  }
}

These numbers are examples, not defaults or legal dimensions. Car profiles also accept overall dimensions, optional towing, and trailer_length_m, so a car towing a trailer can carry its own combination context without being mislabeled as a commercial truck.

POST /api/v1/garage/vehicles/{id}/guidance now includes navigation_profile alongside the existing checklist. It contains the profile label, supplied specifications, vehicle-specific focus, missing profile fields, instruction style and geometry policy. Aviation snapshots include the same field. Integrations can present these checks without making a model call; the actual route analysis and AI briefing continue to use their existing scoped endpoints.

Use truck for an 18-wheeler or other heavy road vehicle. Enter the actual operating height, width, length, loaded mass, axle count, and hazmat status when known. A tractor’s brochure mass is not the same as the gross loaded combination mass. A nominal trailer length does not fully describe articulation or turning envelope.

The supplied dimensions become model context. They do not turn the imported road graph into a verified truck-restriction database. Bridge capacity, overhead clearance, seasonal load limits, axle restrictions, hazmat permissions, loading-zone rules, and turning clearance remain unknown unless independently verified from appropriate current sources.

The app should not certify clearance because a road looks wide in satellite imagery. Shadows, canopy, perspective, image age, and unmapped infrastructure can all make such an inference unreliable. A mapped road connection can be unsuitable for an articulated vehicle even when a car could use it. Treat a proposal’s restriction checks as items to verify with official signs, a truck-appropriate routing source, or the operator.

Hazmat is a profile flag, not a complete dangerous-goods classification. The application does not receive a full manifest, regulated class, tunnel category, jurisdictional permit, or emergency-response plan through that boolean. Do not infer that a route is authorized for a particular cargo merely because hazmat was set to true and an analysis completed.

Train and rail advisory

Use train for a rail vehicle or consist. Length, mass, rail gauge, and traction type help organize the advisory context. They do not establish the actual track gauge, axle-load limit, loading gauge, electrical compatibility, or braking rules along a railway.

Rail mode provides an advisory checklist rather than road turn-by-turn navigation. Dispatcher authority, signals, switches, track possession, electrification, and railway operating procedures require official information and qualified operating decisions. A road map or aerial image cannot issue movement authority or prove that a switch is aligned for a train.

Electric traction requires appropriate verification of supply, clearance, and operating procedures. Diesel, steam, and hybrid traction have their own operator requirements. The app does not choose a braking curve, authorize passing a signal, or infer that track is unoccupied from an image or an absent public feed. The rail advisory API returns the vehicle’s scope and checklist so an integration can present those limits with the data.

Aircraft briefing workflow

Create a correctly typed aircraft profile before opening the aircraft workspace. Enter only performance assumptions you can substantiate for your scenario. The application deliberately does not invent cruise TAS, burn, usable fuel capacity, or reserve from a model name. A registration or ICAO type label is not a performance table.

Provide departure and arrival airport codes and coordinates separately. Codes are syntax-checked, but code-to-coordinate matching is not verified. Confirm that both inputs represent your intended locations. The map’s dashed line is a direct geographic corridor. It is not a filed flight plan, an airway clearance, a terrain-clear route, a recommended altitude, or an approved track through controlled airspace.

Choose a scenario altitude and enter usable fuel in the unit saved with the aircraft. Refresh weather and traffic, then inspect the individual provider statuses. A successful HTTP response can contain an unavailable traffic feed and available weather feeds. Do not replace those independent status fields with one green “everything is safe” badge.

The optional AI review receives the same snapshot and explicit assumptions. It can summarize airport weather, wind samples, surveillance gaps, fuel arithmetic, and questions to verify with the pilot, dispatcher, or official briefing. It must not issue takeoff/landing clearances, separation instructions, movement commands, regulatory fuel approval, or a go/no-go decision. No connection to an autopilot, flight-control system, radio transmitter, or certified avionics is provided.

Monitoring is a user-started refresh at two-minute intervals. It stops when inputs change, the page is hidden, or the user stops it. It is not a real-time traffic service. The UI removes stale surveillance positions and clears previous scenario figures when you change the inputs, so old calculations are not silently presented as current results for a new aircraft or corridor.

Helicopter and fixed-wing profiles

Both remain kind: aircraft in the API. Choose specs.airframe as fixed_wing or helicopter; existing aircraft without this field remain unspecified. The garage uses “Airplane / helicopter” as the vehicle-type label and shows the category selector with aircraft specifications. A helicopter profile uses a distinct transparent rotorcraft map icon. Changing the aircraft category invalidates an existing generated portrait so a previous airplane illustration is not reused as the new helicopter illustration.

{
  "name": "Example helicopter",
  "kind": "aircraft",
  "specs": {
    "airframe": "helicopter",
    "rotor_diameter_m": 10,
    "true_airspeed_kt": 100,
    "fuel_burn_per_hour": 15,
    "fuel_capacity": 60,
    "fuel_unit": "gal",
    "reserve_minutes": 30
  }
}

This is an illustrative scenario, not a real aircraft's performance data. Helicopter briefing prompts focus on rotor/wire/obstacle evidence, landing-site permission and dimensions, density altitude, IGE/OGE hover performance, gusts and terrain winds. Rotor diameter alone cannot establish landing-site suitability. Satellite imagery cannot authorize a landing or show every wire. The existing fuel calculation remains a direct-corridor cruise scenario: it excludes hovering, rotor start, ground running, reconnaissance and landing maneuvers, and the interface reports that limitation explicitly.

Fixed-wing prompts instead focus on runway/performance, crosswind and alternate questions. In either category, use appropriate nearby weather-station codes separately from the actual endpoint coordinates, and confirm their relevance. Traffic remains a limited-area OpenSky snapshot. This update does not add ATC commands, hover navigation, aircraft control or certified aviation routing.

Airport weather: METAR and TAF

Airport weather is requested from NOAA Aviation Weather Center. A METAR is an airport observation with an observation time. A TAF is an airport forecast with an issue time and validity interval. The interface preserves the raw report text so a qualified reader can compare the AI interpretation with the source.

A station’s weather does not establish conditions at every point between airports. Terrain, local precipitation, cloud, wind, and visibility can vary substantially away from the reporting station. The application does not treat a clear airport report as proof that a mountain corridor or an entire flight path is clear.

Check issue and validity times. A record can be present but stale, outside its validity interval, or missing a trustworthy timestamp. Missing stations are reported explicitly. If only one product or one station is current, the overall airport weather can be partial. Do not silently substitute a prior successful result and label it fresh.

The current briefing does not supply a complete official aviation weather package. NOTAMs, approved charts, terrain, airspace restrictions, icing analysis, turbulence analysis, and convective-avoidance products are not established by these METAR/TAF and pressure-wind calls. Obtain the appropriate current official briefing and operational information separately.

Winds aloft, jet-stream context, and units

Open-Meteo provides forecast winds at pressure levels near the requested scenario altitude. The application samples the start, midpoint, and destination corridor locations. Coordinates are rounded for weather queries; the output states the sample point, forecast time, pressure level, and approximate standard pressure altitude.

A pressure level is not the same as an exact geometric height above terrain. Atmospheric conditions and local elevation affect that relationship. A value shown near the requested altitude should therefore be read as a model sample at a named pressure level, not a measured wind at the aircraft’s exact flight level or height above the ground.

Wind direction is reported as the direction the wind comes from. This matters when interpreting headwind and crosswind components. Winds from opposite directions must not be compared as if both were directions of travel. The deterministic scenario calculation uses vector components and the corridor’s true course; it does not issue a magnetic heading command.

The 250 hPa samples provide upper-air context relevant to discussions of strong upper-level flow. They do not map the complete jet axis, diagnose turbulence, predict clear-air turbulence along a flight, or establish a safe passage around weather. A strong wind sample is evidence of a model wind value at that pressure and time, not a complete aviation hazard product.

Units are explicit: scenario altitude is feet; aircraft TAS and modeled wind speeds are knots; geographic distance is nautical miles; time is hours or minutes as labeled. Provider wind units are validated before arithmetic. An integration should retain units in its own UI and storage rather than inferring them from a numeric field name alone.

Fuel and wind scenario arithmetic

The fuel scenario is deterministic arithmetic, separate from the model’s commentary. It uses user-supplied TAS, cruise burn, usable fuel, declared usable capacity, fuel unit, and scenario reserve. The direct corridor is split into two geographic legs, and the endpoint wind components are averaged for each leg. An unsolvable wind triangle or unsuitable groundspeed produces an incomplete result rather than an invented travel time.

The calculation uses constant TAS and burn. It does not add taxi, takeoff, climb, descent, approach, alternates, holding, terrain routing, airspace detours, performance changes with weight, or other operating allowances. The weather samples refer to the current forecast hour, not a time-marched forecast at every expected point of passage. These assumptions can materially change a real trip’s fuel requirement.

Fuel quantities remain in the saved unit: gal, l, or kg. Burn per hour must use that same unit. The application does not silently convert gallons to kilograms or invent a fuel density. If you change the unit in the profile, verify every associated quantity yourself. The data validation ensures consistent types and bounds, not that you have converted a real aircraft’s figures correctly.

The reserve entered by the user is a scenario assumption, not a regulatory minimum or approval. A positive scenario margin does not certify legal or adequate fuel. A negative margin indicates that the stated simple scenario falls below the entered reserve; it is an item to verify, not an automated flight command. Missing required inputs, fuel above declared capacity, or a corridor too short for useful trip estimates leaves fuel figures incomplete.

OpenSky traffic, coverage, and failures

OpenSky Network supplies crowdsourced aircraft state vectors when its API is reachable. The application requests a limited geographic box around the start/monitoring point rather than a worldwide feed. The response includes the box bounds and source snapshot time. It is not a corridor-wide surveillance guarantee.

The normalized output can include ICAO24, callsign, position, reported barometric and geometric altitude, groundspeed, track, vertical rate, position time, and last contact. These references are not interchangeable. Barometric altitude should not be casually substituted for geometric height, and track is not necessarily the aircraft’s heading. The UI labels reported values instead of treating them as certified onboard measurements.

Old or invalid positions are filtered. Stale cached snapshots are withheld, and the browser removes positions that age beyond its display threshold. An empty array means no supported positions were available in that response; it does not mean the airspace is clear. Coverage can be limited by receivers, geography, transmitter behavior, filtering, provider delays, and outages.

Anonymous OpenSky access has limited upstream capacity. The deployment applies a daily global budget and a short shared cache. Optional OAuth client credentials can be configured securely by the operator. OAuth may change authentication and quotas; it does not guarantee network reachability or service availability. During testing, the endpoint timed out from Cloudflare even when a workspace request succeeded, so the production UI correctly reported traffic unavailable.

An aircraft integration must preserve status, snapshot time, coverage text, and failure information. Do not animate invented aircraft during an outage to make the map appear populated. Do not infer that a highlighted aircraft is your physical ownship unless you have independently established its identifier. QRoadScan provides no TCAS substitute, ADS-B In certification, conflict detection, separation service, or ATC authority.

RainViewer controls and basemap troubleshooting

RainViewer is a precipitation overlay, independent of the basemap and the aircraft traffic feed. Use Play to cycle through the available recent frames. Stop holds the current frame. Moving the frame slider stops playback so your selection stays put. Turning off radar or hiding/leaving the page also stops the animation.

A transparent radar tile can mean no detected precipitation in that tile, incomplete coverage, or another source limitation. It does not establish an absence of all weather hazards. Precipitation imagery does not provide aircraft icing clearance, turbulence avoidance, road grip, or a safety forecast for a particular street.

The basemap uses hosted OpenStreetMap tiles with attribution. Those servers require a legitimate application referrer and compliance with their usage policy. The aircraft and road maps set a map-specific cross-origin referrer policy so the provider receives the site origin without a private page path. The application does not disguise itself as another site or proxy around a provider block.

If you see a tile reading “403 Access blocked,” refresh the page so the latest map code is loaded, then check the actual map request and referrer in your browser’s developer tools. A network or provider block can also occur independently of radar. Keep required attribution visible. Do not bulk-download or prefetch tile regions, and use an appropriate hosted or licensed service when application scale exceeds a public provider’s intended use.

Authentication, permissions, and key lifecycle

Every versioned request sends Authorization: Bearer …. A browser session cookie is not a substitute. The server hashes API-key material for lookup and checks revocation and expiry. A missing, malformed, revoked, or expired token returns 401. An authenticated key that lacks a required permission returns 403 insufficient_scope and identifies the missing scope.

Scope Purpose
account:read Read account plan, status, and credits.
scans:read List and retrieve owned scene or visual-route reports.
scans:write Submit metered scene scans.
routes:write Search route endpoints, preview automatic imagery, and submit visual road analyses.
garage:read Read garage profiles, marker SVGs, and mode advisory checklists.
garage:write Create, replace, delete, or activate owned vehicle profiles.
images:read Retrieve owned generated PNG illustrations.
images:write Request a metered, PHF-gated illustration.
aviation:read Read aviation configuration and request advisory evidence snapshots.
aviation:review Request an AI review of a refreshed aviation snapshot.
operations:read Inspect owned metered-operation status and resource links.

Read-only keys are suitable for dashboards that retrieve existing resources and advisory snapshots without changing garage profiles or generating art. Road planner keys include road analysis permissions while avoiding image generation and aircraft AI review. Full user API keys include the currently supported user API scopes. None of these presets grants browser administrator privileges.

Existing keys retain their former user-level capabilities when scopes are introduced. For backward compatibility, omitting scopes in the authenticated key-creation request retains the full user scope set. The Settings interface sends an explicit preset; new integrations should do the same through that managed UI. Review and rotate legacy broad keys when you can narrow their permissions.

Use a separate key for each integration or environment. Give it a meaningful name, an appropriate expiry, and only the required permissions. A development script that reads reports does not need permission to spend image credits. Revoke a compromised key immediately. Recreating a key is safer than trying to recover a secret that may have entered logs or a public bundle.

Endpoint reference and response shapes

All paths in this table are relative to the production origin. Unless noted otherwise, requests with a body use Content-Type: application/json. Resource ownership is enforced independently of scopes: a key with garage:read cannot read another account’s vehicle by guessing its UUID.

Method and path Required scope Main result
GET /api/v1/capabilities Valid key Feature and quota discovery.
GET /api/v1/key Valid key Current key metadata and scopes.
GET /api/v1/account account:read Plan, status, available credits.
POST /api/v1/scans scans:write Metered scene report and operation ID.
POST /api/v1/route/geocode routes:write Candidate places with precision/source labels.
POST /api/v1/route/atlas routes:write Automatic imagery manifest and warnings, without a route-model analysis.
POST /api/v1/route/analyze routes:write Metered visual proposal; paid-credit refund for a context-only result.
GET /api/v1/reports scans:read Paginated owned report metadata.
GET /api/v1/reports/{id} scans:read An owned, unexpired encrypted-at-rest report.
GET /api/v1/operations/{id} operations:read Reserved/completed/refunded state and resource link.
GET /api/v1/garage/vehicles garage:read Owned vehicles and active vehicle ID.
POST /api/v1/garage/vehicles garage:write A new owned vehicle profile.
GET /api/v1/garage/vehicles/{id} garage:read Current profile and version.
PUT /api/v1/garage/vehicles/{id} garage:write Version-checked profile replacement.
DELETE /api/v1/garage/vehicles/{id} garage:write Logical deletion and cleanup scheduling.
PUT /api/v1/garage/active garage:write Active vehicle selection or clearing.
GET /api/v1/garage/vehicles/{id}/marker garage:read Transparent type/color SVG; no model credit.
GET /api/v1/garage/vehicles/{id}/image images:read Current private generated PNG.
POST /api/v1/garage/vehicles/{id}/image images:write PHF-gated GPT Image 2 result; one credit on success.
POST /api/v1/garage/vehicles/{id}/guidance garage:read Mode-specific checklist and optional area weather.
GET /api/v1/aviation/config aviation:read Provider and advisory configuration.
POST /api/v1/aviation/snapshot aviation:read Traffic/weather/wind/fuel evidence snapshot.
POST /api/v1/aviation/briefing aviation:review Refreshed snapshot plus bounded AI review.

The garage list retains its established {vehicles, active_vehicle_id} response. A single profile is a profile object, not a generic list envelope. The new reports collection uses {data, pagination, meta} because it can grow over time. Binary image and marker endpoints return image bodies rather than JSON. Check response status and content type before deciding how to parse a response.

Create and update vehicles through the API

Use a Full user API key or another key with garage:write for the write examples in this section. A Read-only key is intentionally denied. The following request creates an illustrative car profile. Replace the example values with your own verified information. name and kind are required; optional text fields can be omitted. Unsupported specification fields for the chosen kind are rejected instead of silently stored.

cat > vehicle.json <<'JSON'
{
  "name": "City car",
  "kind": "car",
  "make": "Example",
  "model": "Compact",
  "year": 2025,
  "color": "blue",
  "theme": "none",
  "appearance_notes": "Plain body panels and black wheels",
  "specs": {"mass_kg": 1300}
}
JSON

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/garage/vehicles" \
  -X POST \
  -H "Authorization: Bearer $QRS_API_KEY" \
  -H 'Content-Type: application/json' \
  --data-binary @vehicle.json

Save the returned id and version in your own application. The UUID is not a secret credential, but it still identifies a private resource. An integration must not infer authorization from knowing that ID; it should always use the correct account’s key.

For a motorcycle, use kind: motorcycle and the motorcycle fields. Do not label a motorcycle as a car merely because a car was the first option in an older form.

{
  "name": "Small motorcycle",
  "kind": "motorcycle",
  "make": "Kawasaki",
  "model": "Z125 Pro",
  "year": 2025,
  "color": "olive camouflage",
  "theme": "none",
  "specs": {"engine_cc": 125}
}

For a truck or rail vehicle, keep operating quantities explicit. The following snippets are examples of request shape, not validated operating data:

{
  "name": "Illustrative articulated truck",
  "kind": "truck",
  "specs": {
    "height_m": 4.0,
    "width_m": 2.6,
    "length_m": 22,
    "mass_kg": 36000,
    "axles": 5,
    "hazmat": false
  }
}
{
  "name": "Illustrative rail consist",
  "kind": "train",
  "specs": {
    "length_m": 500,
    "mass_kg": 200000,
    "rail_gauge_mm": 1435,
    "traction": "diesel"
  }
}

To update a vehicle, fetch the latest object, construct a replacement containing supported profile fields, and include the current version. Do not send server-generated fields such as id, image_url, or timestamps back as if they were editable profile properties. The server rejects unknown fields.

export VEHICLE_ID='YOUR_VEHICLE_UUID'

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/garage/vehicles/$VEHICLE_ID" \
  -H "Authorization: Bearer $QRS_API_KEY"

# Put the editable fields and current version in vehicle-update.json.
curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/garage/vehicles/$VEHICLE_ID" \
  -X PUT \
  -H "Authorization: Bearer $QRS_API_KEY" \
  -H 'Content-Type: application/json' \
  --data-binary @vehicle-update.json

A holiday change is an ordinary versioned profile replacement. It does not automatically spend an image credit. The current PNG endpoint refers to the profile’s current illustration, not an immutable historical art archive. Deleting a vehicle or changing its appearance can make a previously observed image link unavailable.

Activate a vehicle, retrieve a marker, and request advice

Active selection helps the browser choose a profile when opening the road workspace. It does not teleport a GPS position, start monitoring, generate an image, or authorize a route. A profile must belong to the same account as the key.

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/garage/active" \
  -X PUT \
  -H "Authorization: Bearer $QRS_API_KEY" \
  -H 'Content-Type: application/json' \
  --data "{\"vehicle_id\":\"$VEHICLE_ID\"}"

Send {"vehicle_id":null} to clear the active selection. A deleted profile cannot be activated by retaining its UUID. The server checks current ownership and deletion state before changing the preference.

The marker endpoint returns a small, transparent vector illustration without a model call or image credit. Store or serve it only according to your own authenticated account policy; the production endpoint remains private.

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/garage/vehicles/$VEHICLE_ID/marker" \
  -H "Authorization: Bearer $QRS_API_KEY" \
  --output vehicle-marker.svg

For a mode-specific advisory checklist, submit an empty JSON object or a supported optional location. The location is used for a coarse area-weather estimate when available. A train advisory does not become movement authority because a weather estimate was returned.

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/garage/vehicles/$VEHICLE_ID/guidance" \
  -X POST \
  -H "Authorization: Bearer $QRS_API_KEY" \
  -H 'Content-Type: application/json' \
  --data '{"location":{"latitude":34.85,"longitude":-82.60}}'

Generate and retrieve a private vehicle illustration

Image generation requires images:write, an owned vehicle, an existing credit, and an idempotency key. The body is the empty object {}. The application constructs the image description from the saved profile; a request cannot replace the server’s prompt, choose arbitrary provider URLs, disable PHF, or supply a different provider credential.

export IMAGE_IDEMPOTENCY_KEY="$(python3 -c 'import uuid; print(uuid.uuid4())')"

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/garage/vehicles/$VEHICLE_ID/image" \
  -X POST \
  -H "Authorization: Bearer $QRS_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $IMAGE_IDEMPOTENCY_KEY" \
  --data '{}'

Keep the same key if your client loses the response and needs to retry that same logical generation. A completed replay should not invoke the provider or debit another credit. Generate a new key only for a genuinely new request, such as a new illustration after editing the theme. Do not turn a failed attempt into a retry loop that manufactures fresh keys to evade limits.

A successful JSON response identifies the operation, vehicle, model, PHF results, and credit use. The server-side download endpoint requires images:read:

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/garage/vehicles/$VEHICLE_ID/image" \
  -H "Authorization: Bearer $QRS_API_KEY" \
  --output vehicle.png

Check Content-Type: image/png if your client handles multiple response types. A JSON error must not be saved as if it were a PNG and subsequently treated as a corrupted image. A missing or expired illustration returns a resource error; it should not cause your UI to show another user’s cached picture as a fallback.

A browser user performs the same generation through the signed-in settings flow with recent identity verification and CSRF. API keys authenticate explicitly instead; they do not submit the browser’s password or a CSRF cookie with every call. Protect an image-generation key because its permission can spend the owning account’s available image credits within the published limits.

Submit a scene scan

A scene scan accepts observations, coordinates, model selection, and language. It is not the visual map-atlas workflow. The application supports the configured OpenAI scene model and local Llama service when available. Unsupported provider/model selections are rejected before charging. English is the supported scan language for this deployment.

cat > scene.json <<'JSON'
{
  "latitude": 40.758,
  "longitude": -73.9855,
  "vehicle_type": "car",
  "destination": "Selected public destination",
  "model": "openai",
  "language": "en",
  "weather": "Light rain reported by the user",
  "traffic": "Slow traffic reported by the user",
  "road_type": "Urban street",
  "obstacles": "None reported; not independently verified",
  "sensor_notes": "Illustrative input, not a live sensor feed"
}
JSON

export SCAN_IDEMPOTENCY_KEY="$(python3 -c 'import uuid; print(uuid.uuid4())')"
curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/scans" \
  -X POST \
  -H "Authorization: Bearer $QRS_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $SCAN_IDEMPOTENCY_KEY" \
  --data-binary @scene.json

The response includes the modeled classification, observations, provider provenance, report identifier, and operation identifier for a newly completed operation. Preserve the observations and limitations beside the result in your own interface. A High classification should not be relabeled as a measured chance of a crash, and a Low classification should not be presented as clearance to drive.

Local Llama container inference is disabled in this deployment to prevent container compute charges. New scene scans default to OpenAI; explicit llama_local requests return unavailable before charging. Other deployments must explicitly enable local inference before advertising it. Provider availability and latency vary. A returned failure with refund is different from a client timing out while the server is still working. Use operation status when you have an operation ID, or retry the same logical request with the same idempotency key rather than creating duplicate paid work.

Visual road-route API

The visual-route endpoints are intended for clients that can provide an actual, correctly georeferenced map capture. They are not a text-only shortcut around missing map evidence. Use routes:write, supply owned vehicle IDs when needed, and preserve the map bounds and image dimensions associated with the pixels you captured.

Find an endpoint

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/route/geocode" \
  -X POST \
  -H "Authorization: Bearer $QRS_API_KEY" \
  -H 'Content-Type: application/json' \
  --data '{"query":"Easley City Hall, Easley SC"}'

The result is a list of candidates with coordinates, labels, source, precision, and an accuracy description. A street-only match is not a resolved house entrance. A Census match can be interpolated. Unit removal means an apartment or suite suffix was removed for address lookup, not that the unit was found inside a complex. Your client should show the precision label and ask the user to confirm the actual endpoint.

Preview the automatic atlas

cat > atlas.json <<'JSON'
{
  "start": {"latitude":34.8298,"longitude":-82.6015},
  "destination": {"latitude":34.8526,"longitude":-82.3940},
  "mode": "driving"
}
JSON

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/route/atlas" \
  -X POST \
  -H "Authorization: Bearer $QRS_API_KEY" \
  -H 'Content-Type: application/json' \
  --data-binary @atlas.json

The atlas response contains role/bounds/dimension metadata and warnings, not a completed route and not the raw image bytes. It does not charge a route-model scan credit, but it is still quota-limited and uses upstream mapping services. Do not call it in a tight loop to harvest imagery or bypass a provider’s use restrictions.

Submit an analysis with a real capture

The request below illustrates the shape. Replace the placeholder with a real PNG or JPEG data URI and use bounds/dimensions that match that exact capture. The server validates media signatures and dimensions, requires both endpoints inside the capture, bounds image sizes and context-image count, and rejects unsupported fields. Do not use a garage illustration as a map capture.

{
  "start": {"latitude":34.8298,"longitude":-82.6015},
  "destination": {"latitude":34.8526,"longitude":-82.3940},
  "mode": "driving",
  "vehicle_id": "YOUR_OWNED_ROAD_VEHICLE_UUID",
  "notes": "Review the visible main-road corridor; verify legal turns separately.",
  "map": {
    "image": "data:image/jpeg;base64,REPLACE_WITH_REAL_IMAGE_BYTES",
    "width": 1000,
    "height": 750,
    "bounds": {"north":35.0,"south":34.7,"east":-82.2,"west":-82.8}
  },
  "context_images": []
}
export ROUTE_IDEMPOTENCY_KEY="$(python3 -c 'import uuid; print(uuid.uuid4())')"
curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/route/analyze" \
  -X POST \
  -H "Authorization: Bearer $QRS_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $ROUTE_IDEMPOTENCY_KEY" \
  --data-binary @route-with-real-capture.json

A completed proposal includes sections, imported/modeled provenance, geometry alignment metadata, image-manifest metadata, weather samples, limitations, and a stored report identifier. A needs_context response can be HTTP 200 while indicating that no supported proposal was completed and any paid credit was refunded; a free attempt still counts. Inspect the semantic status; HTTP success alone does not establish a usable route.

Road analysis currently accepts driving and walking contexts. Aircraft and train profiles are rejected by this road handler. Do not describe an aircraft as a car to force a road ribbon into an aviation UI. For long or unsupported corridors, refine the region or provide better evidence; do not invent a continuous line and label it a verified road trace.

Comparing route proposals

Four-objective route comparison

Use Compare 4 objectives in the road workspace to request fastest estimate, simplest maneuvers, lowest modeled caution, and fuel economy proposals for the same captured overview and endpoints. The comparison runs at most two requests at once. Four available scan credits are required to start; each admitted free attempt counts toward the free limits, while successful paid proposals consume one credit. Completed proposals are saved as separate reports. Context-only responses and failures return paid credits but do not restore free attempts. Finish current requests & stop prevents queued objectives from starting; it does not cancel the two potentially active requests. Review saved reports before retrying after a network interruption.

The existing one-credit planning button remains available. Its Single-proposal objective selector requests only one of the objectives, or a balanced proposal. The API accepts optional objective: balanced | fastest | simplest | caution | fuel on the existing route-analysis request. To compare through an API client, make up to four ordinary requests with distinct idempotency keys; each has its own operation, credit reservation and saved report. Existing owner scopes, CSRF rules for browser calls, quotas and report encryption still apply.

The model receives the objective as a preference; explicit user via/avoid requirements take priority. Map alignment uses objective-dependent road-class weights for time, continuity and fuel preferences. Objectives do not change the caution scoring rubric. The application compares the actual returned distance, substantive entry-heading maneuvers, length-weighted caution and fuel scenario. An objective request does not guarantee that its candidate wins that metric. The same mapped path can be returned for multiple objectives; those paths are merged into one card and labeled with their shared objectives. Alternatives are drawn as muted dashed lines; selecting a card activates that report’s directions, score ribbon, truck review, GPS route and voice source. The comparison tray is hidden during fullscreen guidance. Comparison groups are session UI state; the individual proposals remain in saved reports.

route_metrics records distance, estimated seconds, maneuver count, weighted caution, caution-coverage fraction, fuel proxy, optional fuel gallons/effective MPG, and the modeling assumptions. Time uses assumed km/h by class: motorway 90, trunk 70, primary 55, secondary 45, tertiary 35, minor 25, service 12. Each substantive heading change adds a 12-second scenario delay. These are not posted speeds, live traffic, recommended speeds or calibrated ETAs. The lowest-caution label requires at least 95% scored-distance coverage; missing scores cannot silently win by being omitted.

Add Baseline fuel economy (US MPG) to a road vehicle in Garage to obtain scenario gallons and effective scenario MPG. Without it, the comparison shows only a relative fuel proxy and asks for MPG. Fuel proxy uses distance multiplied by transparent class factors (motorway 1.12, trunk 1, primary 0.95, secondary 1, tertiary 1.1, minor 1.25, service 1.5), plus 0.05 proxy kilometers per substantive maneuver. Scenario gallons equal proxy kilometers divided by 1.609344 and the supplied MPG. This is an explicit comparative heuristic, not measured fuel use; traffic, acceleration, grades, load, wind, idling and actual vehicle efficiency are not resolved by it. Walking proposals have no fuel ranking.

Articulated-truck turn review

Truck reports include truck_turn_review with one entry for every mapped section, entry heading change, attention flags, missing profile fields and verification checks. Large heading changes, small-road turns and substantial turns by a supplied combination at least 18 meters long receive additional attention. A flag is a request to inspect geometry, not a measured swept-path failure. The UI includes per-section truck details in the directions and map popups. Lane width, curb radius and restriction status remain explicitly unknown, and clearance_verified stays false for every turn.

For a vehicle-specific constant-circle axle-path scenario, supply wheelbase, front-axle-center scenario radius, and—on an articulated combination—kingpin-to-trailer-axle-group distance and signed fifth-wheel offset from the tractor rear axle. Enter actual vehicle specifications; do not use overall combination length as wheelbase or a manufacturer’s outer-body curb-to-curb radius as front-axle-center radius. Loaded dimensions, mass, axles and hazmat status remain separate profile inputs.

The steady, low-speed, no-slip model uses rear_radius² = front_radius² − wheelbase²; for an articulated combination, trailer_axle_radius² = rear_radius² + fifth_wheel_offset² − kingpin_to_axle². The reported axle tracking difference is front-axle radius minus the resulting inner axle radius. The user-supplied circular scenario is shown once at route level; it is not a simulation of any actual mapped junction. Non-positive squared radii produce an outside-model result rather than a fabricated answer or a claim that the route is impossible.

This is not a full swept-envelope model: front and rear overhang, transient articulation, tire envelopes, lane boundaries, trailer rear swing and road camber are not resolved. Current official truck restrictions and measured turn layouts are still needed to approve access. No turn is labeled safe, legal, wide enough, or cleared from this review alone.

Reports and signed pagination

Use scans:read to list the owning account’s completed, unexpired scene and visual-route reports. Generated garage images are deliberately excluded from scan history, so selecting a saved scan does not lead to a nonexistent image-as-report resource.

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/reports?limit=20" \
  -H "Authorization: Bearer $QRS_API_KEY"

The reports collection returns data, pagination, and meta. data contains report metadata and per-report URLs, not decrypted contents for every report at once. pagination.next_cursor is either a signed opaque cursor or null. Keep it exactly as returned; do not parse it to implement authorization or build your own cursor from another account’s values.

Cursors are bound to the owning account and report collection, and expire. They order reports by creation time and report ID, which avoids ordinary page-offset drift when newer reports arrive. They are not permanent bookmarks. If a cursor expires, restart the listing from the first page and deduplicate reports by their identifiers in your own application.

# Save the actual next_cursor from the prior response; do not invent one.
export REPORT_CURSOR='CURSOR_FROM_RESPONSE'
curl --fail-with-body --silent --show-error --get \
  "$QRS_BASE/api/v1/reports" \
  -H "Authorization: Bearer $QRS_API_KEY" \
  --data-urlencode 'limit=20' \
  --data-urlencode "cursor=$REPORT_CURSOR"

Retrieve one report through its owned resource URL:

export REPORT_ID='REPORT_ID_FROM_RESPONSE'
curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/reports/$REPORT_ID" \
  -H "Authorization: Bearer $QRS_API_KEY"

Report access checks ownership, completion state, and retention. A guessed identifier does not grant access. Reports older than the supported retention period can become unavailable. Preserve the distinction between your own cached copy and a fresh server retrieval, and apply your own privacy and retention policy if you store copies externally.

Operation status and idempotent recovery

New metered responses include an operation_id. Use operations:read to inspect the status when that identifier is available. Operation status is metadata about the work and credit state; it is not another model call.

export OPERATION_ID='OPERATION_UUID_FROM_RESPONSE'
curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/operations/$OPERATION_ID" \
  -H "Authorization: Bearer $QRS_API_KEY"

reserved means the operation has reserved a credit and has not reached a settled terminal state. It does not mean the model is at a specific percentage. Respect poll_after_seconds rather than polling continuously. completed means settlement finished; the response can include a result resource link. refunded means the operation ended without consuming a paid credit, which can result from a provider failure or an unsupported route requiring more context. Free attempts remain counted even when the operation has this status.

A status resource does not reveal another user’s operation. The server checks the owning account. A result link also does not bypass the scope required to retrieve the actual report or PNG. A key with operation-status permission alone does not automatically gain all report or image contents.

Use a fresh idempotency key for every genuinely new metered operation. Store the key together with the original request body before sending it. When retrying a transport failure, reuse the exact original body and key. Do not reuse a key across different operation kinds or different intended jobs. The key is an operation identity, not permission to swap the inputs after submission.

A request can finish after a client disconnects. If you lost the entire response and do not have an operation ID, retry the same request identity rather than inventing another job. A completed replay should not reserve or debit again. A conflicting or still-processing reservation can return 409. Read the original error and operation state before deciding whether the next action is to wait, correct an input, or create a new logical request.

Aircraft API end-to-end example

First create an aircraft profile with garage:write. These numbers demonstrate field shape only. They are not recommended values for a real aircraft, a legal fuel reserve, or a substitute for the appropriate performance manual.

cat > aircraft.json <<'JSON'
{
  "name": "Illustrative trainer",
  "kind": "aircraft",
  "make": "Example",
  "model": "Trainer",
  "theme": "none",
  "specs": {
    "type_designator": "C172",
    "true_airspeed_kt": 110,
    "fuel_burn_per_hour": 9,
    "fuel_capacity": 45,
    "fuel_unit": "gal",
    "reserve_minutes": 45
  }
}
JSON

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/garage/vehicles" \
  -X POST \
  -H "Authorization: Bearer $QRS_API_KEY" \
  -H 'Content-Type: application/json' \
  --data-binary @aircraft.json

Next use the actual returned vehicle UUID in a snapshot request. This example uses public airport coordinates. You must verify that the airport codes and coordinates match your own intended locations before relying on a scenario.

cat > briefing.json <<'JSON'
{
  "vehicle_id": "YOUR_AIRCRAFT_UUID",
  "start": {"latitude":34.8956,"longitude":-82.2189},
  "destination": {"latitude":35.4362,"longitude":-82.5418},
  "departure_airport": "KGSP",
  "arrival_airport": "KAVL",
  "altitude_ft": 5000,
  "usable_fuel": 35
}
JSON

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/aviation/snapshot" \
  -X POST \
  -H "Authorization: Bearer $QRS_API_KEY" \
  -H 'Content-Type: application/json' \
  --data-binary @briefing.json

Inspect quality, individual source statuses, raw airport records, wind timestamps, and fuel_scenario. Preserve missing, partial, stale, and unavailable distinctions. A fuel scenario can be incomplete even if a weather response exists. A valid airport forecast does not validate the aircraft’s entered burn or capacity.

Requesting an AI review requires aviation:review, uses the same request shape, and refreshes the evidence before asking the configured route model to review it. It is separately quota-limited and currently does not charge a scan credit.

curl --fail-with-body --silent --show-error \
  "$QRS_BASE/api/v1/aviation/briefing" \
  -X POST \
  -H "Authorization: Bearer $QRS_API_KEY" \
  -H 'Content-Type: application/json' \
  --data-binary @briefing.json

The result contains snapshot and briefing. The briefing separates weather review, traffic review, fuel review, and items to verify before flight. Do not transform those advisory text arrays into a stream of automated cockpit commands. Keep the snapshot time and the limitations beside the commentary, especially when a provider is unavailable.

Python with httpx

Use this synchronous client in a trusted Python service or command-line program. It reuses connections, reads the key from the environment, rejects redirects, and attaches idempotency keys only when you supply one. A local timeout does not prove that the server canceled a metered operation. Keep the original body and operation identity if you need to retry.

python -m pip install httpx
# Save the following as qrs_httpx.py, then run:
python qrs_httpx.py
import os
import httpx


class QRSClient:
    def __init__(self):
        self.http = httpx.Client(
            base_url=os.environ.get('QRS_BASE', 'https://ride.qroadscan.com').rstrip('/'),
            headers={'Authorization': 'Bearer ' + os.environ['QRS_API_KEY']},
            timeout=httpx.Timeout(360.0, connect=10.0),
            follow_redirects=False,
        )

    def close(self):
        self.http.close()

    def request(self, method, path, *, body=None, idempotency_key=None, params=None):
        headers = {}
        if idempotency_key:
            headers['Idempotency-Key'] = idempotency_key
        options = {'headers': headers, 'params': params}
        if body is not None:
            options['json'] = body
        response = self.http.request(method, path, **options)
        if not 200 <= response.status_code < 300:
            try:
                problem = response.json()
            except ValueError:
                problem = {}
            raise RuntimeError({
                'status': response.status_code,
                'code': problem.get('code', problem.get('error', 'http_error')),
                'request_id': response.headers.get('X-Request-ID'),
                'retry_after': response.headers.get('Retry-After'),
            })
        return response.json()


if __name__ == '__main__':
    client = QRSClient()
    try:
        account = client.request('GET', '/api/v1/account')
        print('Credits:', account['api_credits'])
        page = client.request('GET', '/api/v1/reports', params={'limit': 5})
        for report in page['data']:
            print('Report:', report['report_id'], report['operation_kind'])
    finally:
        client.close()

A Read-only key with the appropriate account/report scopes is enough for the default calls above. With garage:write, the same client can explicitly create a vehicle. This is a profile write, not an image-generation request:

client = QRSClient()
try:
    vehicle = client.request('POST', '/api/v1/garage/vehicles', body={
        'name': 'Example motorcycle',
        'kind': 'motorcycle',
        'make': 'Example',
        'model': 'Tourer',
        'color': 'blue',
        'specs': {'engine_cc': 650},
    })
    print('Saved vehicle ID:', vehicle['id'])
finally:
    client.close()

For a metered request, supply a stable key such as str(uuid.uuid4()) once per logical job. Save it before sending. Do not put a uuid4() call inside an automatic retry loop, because each iteration would create a new job rather than recover the original one.

Python with async httpx

Use httpx.AsyncClient when your Python server already uses an event loop. Share a client for a batch of work instead of constructing one for every report. The semaphore below bounds concurrent reads, and the example fetches only five report details. This does not remove server quotas: high concurrency still consumes requests and can reach a rate limit quickly.

import asyncio
import os
import httpx


async def main():
    limit = asyncio.Semaphore(3)
    async with httpx.AsyncClient(
        base_url=os.environ.get('QRS_BASE', 'https://ride.qroadscan.com').rstrip('/'),
        headers={'Authorization': 'Bearer ' + os.environ['QRS_API_KEY']},
        timeout=httpx.Timeout(360.0, connect=10.0),
        follow_redirects=False,
    ) as client:
        async def get_json(path, **kwargs):
            async with limit:
                response = await client.get(path, **kwargs)
                if not 200 <= response.status_code < 300:
                    try:
                        problem = response.json()
                    except ValueError:
                        problem = {}
                    raise RuntimeError({
                        'status': response.status_code,
                        'code': problem.get('code', problem.get('error', 'http_error')),
                        'request_id': response.headers.get('X-Request-ID'),
                    })
                return response.json()

        page = await get_json('/api/v1/reports', params={'limit': 5})
        reports = await asyncio.gather(*(
            get_json(item['url']) for item in page['data']
        ))
        for report in reports:
            # Avoid logging the private report text or observations.
            print('Retrieved report:', report['report_id'])


if __name__ == '__main__':
    asyncio.run(main())

If your task is canceled while waiting for a paid model operation, the remote job may continue. Keep its idempotency identity and use the operation resource when available. Do not use task cancellation as a billing or provider-cancellation guarantee. The default async example above performs read-only report requests.

Python with requests

Use a requests.Session for connection reuse. Set timeouts explicitly: Requests does not choose a useful production timeout for you. Disable redirects for credentialed API calls, inspect non-2xx responses, and log only the safe problem fields rather than an entire request object with its Authorization header.

python -m pip install requests
# Save the following as qrs_requests.py, then run:
python qrs_requests.py
import os
import requests


class QRSClient:
    def __init__(self):
        self.base = os.environ.get('QRS_BASE', 'https://ride.qroadscan.com').rstrip('/')
        self.session = requests.Session()
        self.session.headers.update({
            'Authorization': 'Bearer ' + os.environ['QRS_API_KEY'],
            'Accept': 'application/json',
        })

    def close(self):
        self.session.close()

    def request(self, method, path, *, body=None, params=None, idempotency_key=None):
        options = {
            'params': params,
            'timeout': (10, 360),
            'allow_redirects': False,
            'headers': {},
        }
        if body is not None:
            options['json'] = body
        if idempotency_key:
            options['headers']['Idempotency-Key'] = idempotency_key
        response = self.session.request(method, self.base + path, **options)
        if not 200 <= response.status_code < 300:
            try:
                problem = response.json()
            except ValueError:
                problem = {}
            raise RuntimeError({
                'status': response.status_code,
                'code': problem.get('code', problem.get('error', 'http_error')),
                'request_id': response.headers.get('X-Request-ID'),
                'retry_after': response.headers.get('Retry-After'),
            })
        return response.json()


if __name__ == '__main__':
    client = QRSClient()
    try:
        print('Credits:', client.request('GET', '/api/v1/account')['api_credits'])
        cursor = None
        while True:
            params = {'limit': 20}
            if cursor:
                params['cursor'] = cursor
            page = client.request('GET', '/api/v1/reports', params=params)
            for report in page['data']:
                print('Report ID:', report['report_id'])
            cursor = page['pagination']['next_cursor']
            if not cursor:
                break
    finally:
        client.close()

For binary downloads, validate the response before writing the destination file. This example uses the transparent SVG marker endpoint. A JSON problem response should never be saved as though it were a valid image.

import os
from pathlib import Path
import requests

base = os.environ.get('QRS_BASE', 'https://ride.qroadscan.com').rstrip('/')
vehicle_id = os.environ['QRS_VEHICLE_ID']
with requests.Session() as session:
    response = session.get(
        f'{base}/api/v1/garage/vehicles/{vehicle_id}/marker',
        headers={'Authorization': 'Bearer ' + os.environ['QRS_API_KEY']},
        timeout=(10, 60),
        allow_redirects=False,
    )
    if response.status_code != 200:
        raise RuntimeError(f'Marker download failed: HTTP {response.status_code}')
    if 'image/svg+xml' not in response.headers.get('Content-Type', ''):
        raise RuntimeError('Expected SVG, received another content type')
    Path('vehicle-marker.svg').write_bytes(response.content)

The same principle applies to a private generated PNG, with images:read and the image endpoint. Use image/png as the expected media type. Never make an illustration public merely to avoid sending proper authentication from your server.

JavaScript with Axios

This example is for Node.js on your backend, not a public browser bundle. Install Axios in your own project and keep its lockfile. The client disables redirects, sets a timeout, and deliberately avoids logging Axios request configuration because that configuration contains the secret header.

npm install axios
# Save the following as qrs-axios.mjs, then run:
node qrs-axios.mjs
import axios from 'axios';

const key = process.env.QRS_API_KEY;
if (!key) throw new Error('QRS_API_KEY is required');
const client = axios.create({
  baseURL: (process.env.QRS_BASE || 'https://ride.qroadscan.com').replace(/\/$/, ''),
  headers: {Authorization: `Bearer ${key}`},
  timeout: 360_000,
  maxRedirects: 0,
  validateStatus: () => true,
});

async function qrs(method, path, {body, idempotencyKey, params} = {}) {
  const response = await client.request({
    method,
    url: path,
    data: body,
    params,
    headers: idempotencyKey ? {'Idempotency-Key': idempotencyKey} : {},
  });
  if (response.status < 200 || response.status >= 300) {
    const problem = typeof response.data === 'object' ? response.data : {};
    const error = new Error(problem.code || problem.error || `HTTP ${response.status}`);
    error.status = response.status;
    error.requestId = response.headers['x-request-id'];
    error.retryAfter = response.headers['retry-after'];
    throw error;
  }
  return response.data;
}

try {
  const account = await qrs('GET', '/api/v1/account');
  console.log('Credits:', account.api_credits);
} catch (error) {
  console.error({message: error.message, status: error.status, requestId: error.requestId});
  process.exitCode = 1;
}

The existing JavaScript fetch example is an alternative with no HTTP-library dependency. Both clients follow the same server contract. Neither one should automatically generate a new idempotency key when retrying the same paid request.

TypeScript with fetch

TypeScript helps describe expected response shapes, but an interface is not runtime validation. For larger integrations, generate types from the OpenAPI artifact and validate untrusted data at your service boundary. The example below retains a typed result, safe problem details, and request correlation without exposing the secret in a browser bundle.

Save this as qrs-client.mts in a Node.js TypeScript project. Install TypeScript and Node type definitions in that project if needed. A typical build uses npx tsc qrs-client.mts --module nodenext --target es2022 --outDir dist, followed by node dist/qrs-client.mjs.

interface Account {
  plan: string;
  status: string;
  api_credits: number;
}

interface Problem {
  code?: string;
  error?: string;
  required_scope?: string;
  request_id?: string;
}

const key = process.env.QRS_API_KEY;
if (!key) throw new Error('QRS_API_KEY is required');
const base = (process.env.QRS_BASE || 'https://ride.qroadscan.com').replace(/\/$/, '');

async function qrs<T>(
  path: string,
  options: {method?: string; body?: unknown; idempotencyKey?: string} = {},
): Promise<{data: T; requestId: string | null}> {
  const response = await fetch(base + path, {
    method: options.method || 'GET',
    headers: {
      Authorization: `Bearer ${key}`,
      ...(options.body !== undefined ? {'Content-Type': 'application/json'} : {}),
      ...(options.idempotencyKey ? {'Idempotency-Key': options.idempotencyKey} : {}),
    },
    body: options.body === undefined ? undefined : JSON.stringify(options.body),
    redirect: 'error',
    signal: AbortSignal.timeout(360_000),
  });
  const data: unknown = await response.json();
  if (!response.ok) {
    const problem = data as Problem;
    throw new Error(JSON.stringify({
      status: response.status,
      code: problem.code || problem.error || 'http_error',
      requestId: response.headers.get('X-Request-ID'),
    }));
  }
  return {data: data as T, requestId: response.headers.get('X-Request-ID')};
}

const result = await qrs<Account>('/api/v1/account');
console.log('Credits:', result.data.api_credits);

Go client example

This standard-library example uses an HTTP client with an explicit timeout and a redirect policy. It reads only account metadata when run. JSON writes can use the same request pattern with a marshaled body, Content-Type: application/json, and a persisted idempotency key for metered operations.

Save the example as main.go and run it with go run main.go from your own project. Keep the key in your server environment. Do not print an entire request or its headers when handling an error.

package main

import (
    "encoding/json"
    "errors"
    "fmt"
    "net/http"
    "os"
    "strings"
    "time"
)

type Account struct {
    Plan    string `json:"plan"`
    Status  string `json:"status"`
    Credits int    `json:"api_credits"`
}

type Problem struct {
    Code  string `json:"code"`
    Error string `json:"error"`
}

func run() error {
    key := os.Getenv("QRS_API_KEY")
    if key == "" {
        return errors.New("QRS_API_KEY is required")
    }
    base := strings.TrimRight(os.Getenv("QRS_BASE"), "/")
    if base == "" {
        base = "https://ride.qroadscan.com"
    }
    client := &http.Client{
        Timeout: 360 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    req, err := http.NewRequest(http.MethodGet, base+"/api/v1/account", nil)
    if err != nil {
        return err
    }
    req.Header.Set("Authorization", "Bearer "+key)
    req.Header.Set("Accept", "application/json")
    response, err := client.Do(req)
    if err != nil {
        return errors.New("QRoadScan transport failed; check connectivity")
    }
    defer response.Body.Close()
    if response.StatusCode < 200 || response.StatusCode >= 300 {
        var problem Problem
        _ = json.NewDecoder(response.Body).Decode(&problem)
        return fmt.Errorf("HTTP %d code=%s request_id=%s",
            response.StatusCode, problem.Code, response.Header.Get("X-Request-ID"))
    }
    var account Account
    if err := json.NewDecoder(response.Body).Decode(&account); err != nil {
        return errors.New("could not decode account response")
    }
    fmt.Println("Credits:", account.Credits)
    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err.Error())
        os.Exit(1)
    }
}

For report pagination in Go, use url.Values for limit and cursor, decode the data and pagination.next_cursor fields, and reuse the returned opaque cursor unchanged. Do not concatenate an unescaped cursor into a URL. Stop when the cursor is null, and preserve ownership boundaries in any downstream service that displays the reports.

C sharp client example

This example targets modern .NET with top-level statements. It uses HttpClient, JSON deserialization, a fixed timeout, and disabled automatic redirects. Reuse an appropriate HttpClient in a long-running service instead of creating a new connection pool for every request. An IHttpClientFactory configuration is useful in ASP.NET applications.

Create a console project with dotnet new console, place the following in Program.cs, and run it with dotnet run. The program performs one account read. Provider credentials and the QRoadScan key belong in your service’s secret configuration, not in the source file.

using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json.Serialization;

var key = Environment.GetEnvironmentVariable("QRS_API_KEY")
    ?? throw new InvalidOperationException("QRS_API_KEY is required");
var origin = Environment.GetEnvironmentVariable("QRS_BASE")
    ?? "https://ride.qroadscan.com";

using var handler = new HttpClientHandler { AllowAutoRedirect = false };
using var client = new HttpClient(handler) {
    BaseAddress = new Uri(origin.TrimEnd('/') + "/"),
    Timeout = TimeSpan.FromSeconds(360)
};
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);
using var response = await client.GetAsync("api/v1/account");
var requestId = response.Headers.TryGetValues("X-Request-ID", out var values)
    ? values.FirstOrDefault() : null;
if (!response.IsSuccessStatusCode) {
    // Keep raw request headers and credentials out of logs.
    throw new HttpRequestException($"QRoadScan HTTP {(int)response.StatusCode}; request_id={requestId}");
}
var account = await response.Content.ReadFromJsonAsync<Account>()
    ?? throw new InvalidOperationException("Missing account response");
Console.WriteLine($"Credits: {account.Credits}");

public sealed record Account(
    [property: JsonPropertyName("plan")] string Plan,
    [property: JsonPropertyName("status")] string Status,
    [property: JsonPropertyName("api_credits")] int Credits
);

For writes, build a request message, use JsonContent.Create(body), and add a stable Idempotency-Key header before sending metered work. Inspect a problem response before retrying. The .NET example does not log a failed response’s entire content, which may contain details that are unsuitable for a general application log.

PHP cURL client example

This example uses PHP 8 with the cURL extension. The helper performs JSON requests, preserves the response’s request ID, disables redirects, and rejects non-2xx status codes. TLS verification remains enabled by the normal cURL defaults. Do not disable certificate checks to solve a deployment problem.

<?php
function qrs(string $method, string $path, ?array $body = null): array {
    $key = getenv('QRS_API_KEY');
    if (!$key) {
        throw new RuntimeException('QRS_API_KEY is required');
    }
    $base = rtrim(getenv('QRS_BASE') ?: 'https://ride.qroadscan.com', '/');
    $requestId = null;
    $headers = ['Authorization: Bearer ' . $key, 'Accept: application/json'];
    if ($body !== null) {
        $headers[] = 'Content-Type: application/json';
    }
    $ch = curl_init($base . $path);
    $options = [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 360,
        CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$requestId): int {
            if (stripos($line, 'X-Request-ID:') === 0) {
                $requestId = trim(substr($line, strlen('X-Request-ID:')));
            }
            return strlen($line);
        },
    ];
    if ($body !== null) {
        $options[CURLOPT_POSTFIELDS] = json_encode($body, JSON_THROW_ON_ERROR);
    }
    curl_setopt_array($ch, $options);
    $raw = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($raw === false) {
        throw new RuntimeException('QRoadScan transport failed');
    }
    $data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
    if ($status < 200 || $status >= 300) {
        $code = $data['code'] ?? $data['error'] ?? 'http_error';
        throw new RuntimeException("HTTP $status code=$code request_id=$requestId");
    }
    return $data;
}

$account = qrs('GET', '/api/v1/account');
echo 'Credits: ' . $account['api_credits'] . PHP_EOL;

The helper intentionally does not enable automatic retries. If you add a metered POST, extend its arguments to accept a stored idempotency key and send that same key for recovery of the same request. Do not generate a new UUID on every retry or execute a model operation whenever a PHP page is simply reloaded.

JavaScript server client example

The following example is intended for Node.js on your trusted server. It reads the API key from an environment variable. Do not paste the key into a browser script or publish it in a static frontend build. The helper checks content type, preserves the server request ID, and distinguishes a JSON problem response from a successful payload.

const origin = process.env.QRS_BASE || 'https://ride.qroadscan.com';
const key = process.env.QRS_API_KEY;
if (!key) throw new Error('QRS_API_KEY is required on the server');

async function qrs(path, {method = 'GET', body, idempotencyKey} = {}) {
  const response = await fetch(origin + path, {
    method,
    headers: {
      Authorization: `Bearer ${key}`,
      ...(body !== undefined ? {'Content-Type': 'application/json'} : {}),
      ...(idempotencyKey ? {'Idempotency-Key': idempotencyKey} : {})
    },
    body: body === undefined ? undefined : JSON.stringify(body),
    redirect: 'error',
    signal: AbortSignal.timeout(360_000)
  });
  const requestId = response.headers.get('x-request-id');
  const contentType = response.headers.get('content-type') || '';
  const value = contentType.includes('json') ? await response.json() : null;
  if (!response.ok) {
    const error = new Error(value?.detail || `HTTP ${response.status}`);
    error.status = response.status;
    error.code = value?.code || value?.error;
    error.requestId = requestId;
    error.retryAfter = response.headers.get('retry-after');
    throw error;
  }
  return {value, requestId, headers: response.headers};
}

const capabilities = await qrs('/api/v1/capabilities');
console.log(capabilities.value.api_version);

let cursor = null;
const seen = new Set();
do {
  const query = new URLSearchParams({limit: '20'});
  if (cursor) query.set('cursor', cursor);
  const page = await qrs('/api/v1/reports?' + query);
  for (const report of page.value.data) {
    if (!seen.has(report.report_id)) {
      seen.add(report.report_id);
      // Process authorized metadata; fetch contents only when needed.
      console.log(report.report_id, report.operation_kind);
    }
  }
  cursor = page.value.pagination.next_cursor;
} while (cursor);

A timeout in this helper is a local timeout, not a guarantee that a metered operation was canceled. Persist the idempotency key and original body outside a transient function scope when you submit paid work. Avoid printing complete request bodies, images, credentials, or sensitive route details into application logs. Log request IDs and safe error codes instead.

Python server client example

This example uses Python’s standard library. It illustrates authentication, JSON requests, and problem handling without requiring a particular HTTP SDK. A production service may use its own connection pooling, secret store, structured logging, and retry framework, but it should preserve the same authorization and idempotency rules.

import json
import os
import urllib.error
import urllib.request

BASE = os.environ.get('QRS_BASE', 'https://ride.qroadscan.com')
KEY = os.environ['QRS_API_KEY']


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, request, fp, code, msg, headers, newurl):
        return None


OPENER = urllib.request.build_opener(NoRedirect())


def qrs(path, method='GET', body=None, idempotency_key=None):
    headers = {'Authorization': 'Bearer ' + KEY}
    payload = None
    if body is not None:
        headers['Content-Type'] = 'application/json'
        payload = json.dumps(body).encode('utf-8')
    if idempotency_key:
        headers['Idempotency-Key'] = idempotency_key
    request = urllib.request.Request(
        BASE + path, data=payload, headers=headers, method=method
    )
    try:
        with OPENER.open(request, timeout=360) as response:
            return json.load(response), response.headers.get('X-Request-ID')
    except urllib.error.HTTPError as error:
        try:
            problem = json.load(error)
        except (ValueError, TypeError):
            problem = {'error': 'non_json_error'}
        # Do not log KEY or an entire private request body.
        raise RuntimeError({
            'status': error.code,
            'code': problem.get('code', problem.get('error')),
            'request_id': error.headers.get('X-Request-ID'),
            'retry_after': error.headers.get('Retry-After')
        }) from None


account, request_id = qrs('/api/v1/account')
print('Available credits:', account['api_credits'])

Binary endpoints need a separate download path in your client. Check the HTTP status and Content-Type, then write authorized bytes to your chosen private storage. Do not run a JSON parser over a PNG or SVG. Conversely, do not write an error problem document into a .png file and later diagnose it as an image-generation defect.

Errors, request IDs, and retries

Versioned errors use a problem-style JSON response while retaining the established error code for compatibility. The document includes status, code, detail, and a request ID. Responses also carry X-Request-ID. Give that identifier and the safe error code when reporting a problem; do not paste a key, session cookie, provider credential, or an entire private image body.

{
  "type": "about:blank",
  "title": "insufficient scope",
  "status": 403,
  "code": "insufficient_scope",
  "error": "insufficient_scope",
  "detail": "insufficient_scope",
  "request_id": "SERVER_GENERATED_REQUEST_UUID",
  "required_scope": "garage:write"
}
Status Typical meaning Appropriate next step
400 Invalid JSON, unsupported field, invalid coordinates, bad cursor, or invalid specs. Correct the request; do not repeat it unchanged.
401 Missing, malformed, expired, or revoked Bearer key. Check the secret and expiry; do not fall back to a browser cookie.
403 Missing scope or a browser security check failed. Use the required permission or correct browser session/CSRF flow.
402 No available credit for a metered operation. Inspect account credits; no purchase flow is currently enabled.
404 Resource absent, deleted, expired, or not owned by the account. Check the owned identifier and retention; do not enumerate other IDs.
409 Version, idempotency, or processing conflict. Reload current state or wait for the same operation; do not blindly overwrite.
413 Request or image body exceeds a bound. Reduce the payload within the documented capture limits.
415 Body does not use the required JSON content type. Send application/json for JSON endpoints.
422 A PHF check rejected the image request or output. Revise the descriptive content; do not attempt to bypass the gate.
429 A baseline or feature-specific quota is exhausted. Respect Retry-After and the applicable reset window.
503 A model or upstream service cannot fulfill the operation. Preserve request identity and inspect operation/refund state before retrying.

Not every unavailable provider produces an HTTP error for an aircraft snapshot. The endpoint can return a successful evidence envelope with a specific provider marked unavailable. This is intentional: partial weather information may still be useful as long as the missing traffic or wind source remains visible. Your client must inspect semantic statuses as well as HTTP status.

Avoid automatic retry loops for validation failures, PHF rejections, insufficient credits, missing permissions, or stale profile versions. A retry cannot fix those by itself. For transient transport failures, use bounded exponential backoff with jitter and the same idempotency key/body for the same metered operation. Never assume that dropping your HTTP connection canceled a provider task already running on the server.

Rate limits, quotas, and cost controls

The API applies a baseline budget of 120 requests per API key per minute. Individual features have additional account, key, global, or daily limits. These are separate controls. Passing the baseline limit does not imply permission to generate 120 images or run 120 route analyses in that minute.

Responses with a known API budget include RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset. The reset is an epoch timestamp. A 429 also carries Retry-After in seconds. When a feature-specific limit is the one that rejects the request, the rate information can describe that limiting feature rather than the baseline minute bucket. Inspect the response instead of hardcoding a universal five-second retry.

Feature Current account/key budget Additional considerations
API baseline 120 requests/key/minute Applies to discovery and ordinary API calls too.
Scene scans 20 attempts/key/minute; 20 new scans/account/minute API keys and browser scans share the account limit. Stored idempotent replays do not consume the new-scan allowance; ordinary per-key request limits still apply. Free attempts count at admission; paid credits retain debit/refund rules.
Visual route analysis 6 attempts/account/hour A separate global route budget also applies.
Atlas preview 6 requests/account/hour No route-model credit, but mapping-provider limits still apply.
Route search 15 requests/account/minute Upstream geocoder pacing and availability also apply.
Vehicle art 2 attempts/account/UTC day Ten global attempts/day; one credit on success.
Aircraft evidence 40 requests/account/hour Monitoring and manual refresh share this budget.
Aircraft AI review 4 requests/account/UTC day Twenty global requests/day; currently no scan credit.

Daily application windows use UTC boundaries, which may not be local midnight for your browser. Do not promise a user that a quota resets at their local midnight unless you have explicitly converted the actual server reset time. Provider quotas can be independent of application budgets and can still cause unavailable responses.

Short shared provider caches reduce repeated upstream requests for nearby traffic, airport weather, and wind samples. They do not turn old source timestamps into current ones. The homepage’s fictional Grok refresh is a different workflow and does not reuse a cached simulated scene. Treat each surface according to its own source and freshness semantics.

Browser sessions, CSRF, and security keys

The signed-in browser app uses its own session flow. Login, registration, logout, password changes, garage mutations, route tools, and administrator actions require the relevant same-origin and CSRF checks. The application’s own API helper obtains a signed token and sends X-CSRF-Token. A valid token refresh preserves the browser cookie so another tab is not unnecessarily invalidated.

GET /api/home/csrf is intentionally accessible: the token is bound to a signed, Secure, HttpOnly, SameSite cookie and is not an authentication credential. It returns Cache-Control: no-store, is checked for foreign origins/cross-site fetches, and is limited per source IP. The browser shares one pending token fetch and reuses the token only in page memory for at most five minutes, stopping reuse before the server-reported expiry. It does not put the token in local storage or cache scan results. An invalid_csrf response triggers one fresh-token retry because the Worker rejects that request before any mutation. Permission failures, network errors and other unsuccessful writes are not automatically replayed. Homepage auto-refresh and normal account actions can therefore legitimately produce CSRF requests; a path count by itself does not establish abuse.

The public homepage uses a limited signed preview cookie for its own token flow. That cookie does not grant account access or administrator rights. Likewise, possessing a CSRF token is not authentication. The server still checks the session, ownership, scope, and any recent-verification requirement appropriate to the endpoint.

Passkeys and FIDO2 security keys can be enrolled in Settings after recent identity verification. Once any key is enrolled, browser sign-in requires both the account password and an enrolled key. A key alone cannot sign in, and a correct password alone creates no authenticated session. The password proof expires after five minutes; the key challenge expires after two minutes, requires device verification, and is bound to that browser, password proof and account. Sensitive reauthentication also requires both factors. Adding or removing a key signs out all sessions. Removing the last key returns the account to password-only sign-in. Keep a spare enrolled key: there is no email/password-only recovery bypass for key-protected accounts. Scoped API keys remain separate automation credentials. Challenges are consumed once and checked against the expected origin and relying party. The server stores public credentials, not the authenticator’s private key.

API-key creation/revocation and other sensitive account actions require recent server-side verification in the browser. A normal password login does not automatically unlock all sensitive changes indefinitely. Verified passkey sign-in has its own short elevation window. Removing a security key does not make an existing API key vanish; manage each credential type explicitly.

Static scripts, styles, and module preloads carry Subresource Integrity hashes. The browser should reject altered bytes that do not match the page’s expected digest. CSP restricts script execution and framing. These controls complement authorization; they do not make a leaked API key harmless or prove that a model’s output is correct.

Administrator console and support operations

The administrator console is a separate browser surface available only to operator-provisioned administrator accounts. A signup email, API-key permission, garage type, or client-provided role field cannot grant that role. Server-side role checks apply to each administrator route. API Bearer keys do not act as administrator sessions.

The console can show bounded account search, service configuration status, security posture, and an audit trail. Sensitive user operations require recent verification. Support-credit grants are positive, bounded, idempotent ledger entries with a reason. Session and API-key revocations are audited. Provider status is reported as configuration metadata rather than revealing secret values.

An administrator should identify the correct account before applying an action. A support reason should be meaningful without including a password or provider key. Replaying the same support reference should not duplicate a grant. A revocation action is different from deleting private reports or modifying an aircraft’s entered operating assumptions.

The console does not provide a general tool for reading other users’ decrypted garage profiles, images, or private reports. Cloud infrastructure operators and application administrator sessions are different trust boundaries. Review deployment documentation and your own operational policy before changing secret bindings, database roles, or encryption keys.

Integration architecture and operational checklist

Use a trusted backend between your public frontend and the Bearer API. Store one key per integration, set explicit permissions, and avoid sharing a broad production key among unrelated jobs. Your backend can authenticate its own users and decide which account-owned resources each of them should see. QRoadScan’s account boundary does not automatically implement your own organization’s multi-user authorization rules.

Persist metered request identity before sending work. Store the idempotency key, operation type, a reference to the exact request body, submission time, and eventual server operation/report ID. Keep images and route captures in appropriately private storage. Redact credentials from logs and avoid logging full payloads merely because they are helpful during development.

Separate source data from interpretation in your UI. Display provider timestamps, coverage, missing values, scope, and assumptions beside a score or AI summary. If a feed becomes stale, remove or clearly mark the outdated positions. If a profile changes, do not continue presenting old fuel figures or model context as if they were recomputed for the new profile.

Build bounded retry and polling behavior. Use the server’s operation state and retry headers. Do not create fresh paid work whenever a browser tab rerenders. Stop monitoring when a user leaves the relevant view. Cache only data you are permitted to cache, retain its original source timestamps, and follow provider access and licensing terms before scaling or commercial use.

Before deploying an integration, exercise wrong-key, expired-key, insufficient-scope, bad-body, version-conflict, provider-unavailable, stale-traffic, and client-timeout paths. Test that another account’s resource ID does not work with your key. Verify that a failed illustration does not debit twice and that a successful replay does not call the generator again. An integration that works only on the happy path is not ready for sensitive account data or metered model work.

Troubleshooting and frequently asked questions

Why is the garage picture cut off?

The image may be fine while the card’s layout is using the PNG’s intrinsic size. The current card explicitly contains and centers the full picture, and the larger viewer lets you inspect it without a narrow card crop. Refresh the page to load the latest styling. You do not need to regenerate and spend a credit just to repair the display box.

Why does my motorcycle show a car icon?

Check the saved kind, not just the make/model text. The marker is based on the type you saved. Correct the profile to motorcycle, verify its specifications, and select it in the road workspace. The known Z125 mismatch has an explicit correction action. Type correction is a user choice and does not silently edit all existing profiles.

Does the tiny icon cost another credit?

No. The transparent type/color marker is a vector rendering. The large studio illustration is the metered GPT Image 2 resource. They serve different purposes and have separate rendering paths. Downloading a marker does not trigger PHF or image generation because it is built from constrained local shapes and colors.

Why do I have a key but still get 403?

A valid key can lack a required scope. Inspect the problem response’s required_scope and use /api/v1/key to inspect your permissions. A Read-only key should be denied when it tries to create a profile or spend an image credit. Do not attempt to solve that by sending an administrator email in the request body.

Why did a successful HTTP response return no route?

The semantic route status can be needs_context. The request was processed, but the evidence did not support a completed proposal. The credit is returned. Read the targeted requests for better endpoints or imagery. HTTP 200 is not a claim of route feasibility.

Why is aircraft traffic unavailable while weather works?

Traffic and weather come from independent services and can fail independently. OpenSky may be unreachable, rate-limited, require different access, or return stale data. The current deployment has experienced Cloudflare-to-OpenSky timeouts. The app must not turn an unavailable feed into an invented empty-but-clear traffic picture.

Why is the fuel number incomplete?

Check TAS, fuel burn, capacity, unit, reserve, usable fuel, corridor distance, and wind availability. The calculation avoids inventing missing inputs or converting unrelated units. A simple scenario cannot represent every flight allowance, and an entered reserve is not regulatory approval.

Can I use aircraft mode as ATC or a navigation instrument?

No. The surface is an advisory briefing reader and scenario tool. It provides no clearance, certified surveillance, separation, collision avoidance, flight-control interface, or approved route. Keep official sources and qualified operating decisions in their proper roles. AI commentary does not override them.

Why does a private image URL fail on my external site?

The image is private. A browser-oriented app URL expects the correct session, and a versioned download expects a key with the proper scope. Do not make the bucket public. Fetch authorized bytes on your trusted server and implement an appropriate user access policy there.

What should I include in a useful bug report?

Include the page or endpoint, safe error code, request ID, approximate time with timezone, browser/client version, and the steps that reproduced the problem. Mention whether a source was marked stale or unavailable. Exclude raw keys, cookies, passwords, VINs, personal home addresses, and full private images unless you intentionally choose a secure support channel for them.

Provider attribution and implementation limits

Mapping uses OpenStreetMap data and hosted tiles with attribution; imported road geometry uses OpenFreeMap/OpenMapTiles sources where applicable. Endpoint and corridor imagery can use Esri services with their visible attribution. RainViewer supplies precipitation imagery. NOAA Aviation Weather Center supplies airport weather products. MET Norway and Open-Meteo provide area weather/model forecasts. OpenSky Network supplies public aircraft state vectors when reachable. OpenAI and xAI provide configured model services.

Each provider has its own access, licensing, availability, privacy, and usage terms. A working development request does not establish permission for unlimited production or commercial use. Review the relevant terms and obtain appropriate agreements or paid access before scaling. Keep source attributions visible and preserve provenance rather than relabeling external data as an in-house measurement.

The project’s security tests and browser checks exercise specific implemented controls. They are not a certification of road safety, aviation suitability, cryptographic perfection, or every possible threat. The app has no live vehicle or aircraft hardware validation. Synthetic GPS fixtures and simulated quantum states are explicitly test/simulation data, not evidence that a real route or flight is safe.

For maintainers, the repository includes deployment instructions, implemented security controls, validation records, and the OpenAPI artifact. Build the frontend before deployment so page assets and SRI hashes stay synchronized. Apply required database migrations before publishing a Worker that expects the new columns. Never commit local environment files, provider credentials, private test-account files, or generated customer images to the repository.

Stripe sandbox billing

Approved testers can open User Settings → Billing to purchase a test credit pack or start a test monthly plan through Stripe-hosted Checkout. This deployment accepts test payments only; ordinary accounts cannot mint test credits.

The demonstration fixtures are USD 5 / 100 credits and USD 20 per month / 1,000 credits. These are not the final commercial prices. There are no automatic overages. Monthly sandbox grants accumulate while the live rollover/expiry policy is being decided.

Use only Stripe test cards in Checkout, such as 4242 4242 4242 4242, a future expiry, and a test CVC. On return, refresh credits if Stripe's webhook is still processing. Credits are granted by verified payment events, never by the return URL. The billing portal provides test invoice history, payment-method updates and subscription cancellation at period end.

Browser billing endpoints require a cookie session and CSRF token. Scan API bearer keys do not authorize purchases. Secret keys and webhook signing secrets stay on the server. Public API callers cannot create purchased credit grants themselves. Live payments and automatic tax remain disabled pending commercial configuration and sandbox acceptance. See docs/stripe-sandbox.md in the repository for the operator runbook, event handling, deployment settings and live-launch requirements.

Admin blog publishing

Sign in using an administrator account, then open Blog. The Write a post and Manage blog links appear after your admin session is recognized. They lead to Admin console → Blog editor. You can also open that address directly. An ordinary account or API key cannot use the editor.

Choose Verify admin access and enter your current password when requested. The existing five-minute verification window protects publishing, draft access, configuration changes and support actions. If it expires while you write, saving asks you to verify again; keep the editor open so your unsaved text stays there.

Create a post with New post, add its title, URL slug, description and body, then choose Save draft. Drafts are private to verified administrators and never appear in public listings. The body supports a deliberately limited Markdown format: headings, bold, emphasis, lists, quotes, inline code, fenced code blocks and HTTP(S) links. The toolbar inserts common patterns. Preview uses the same formatter as the public page. Raw HTML and scripts remain text; image embeds and arbitrary HTML attributes are not supported.

Publish now makes the post available at /blog/your-slug. Save published changes updates a post that is already live. Unpublish returns it to a private draft. Archive removes it from the public blog while keeping its contents; Restore draft makes an archived post editable as a private draft again. Changing a published slug changes its URL, so avoid changing slugs that have already been shared. The editor does not create redirects for old slugs.

Concurrent edits use a version check. If someone else saves first, your stale save is rejected rather than overwriting their changes. Copy your unsaved text somewhere safe, reload that post, and reconcile the edits. Publishing and status changes are recorded in the audit trail without copying full post bodies there. Public pages return no-store responses so an unpublished post is not served from an application/CDN cache; previously downloaded or third-party copies cannot be recalled.

Administrator runtime settings

Admin console → Configuration provides 21 persisted settings. Verify your admin access, edit the controls, provide a short operational reason and choose Save configuration. Settings take effect on subsequent requests without redeploying the Worker. Fill default values only fills the form; saving with a reason is still required. Reload settings reads the saved version again.

  • General: public site/blog name, public announcement and HTTPS support URL. Announcements appear in app pages; support links appear in the account navigation.
  • Access: registration and a pause for new AI analyses/generation. Pausing new work preserves login, settings and saved-report access.
  • Features: homepage AI previews, routes/imagery previews, navigation voice, garage illustrations and aircraft AI reviews can be enabled or disabled separately.
  • Publishing: public blog availability. The admin editor remains available when the public blog is disabled, so an admin can restore it.
  • Models: optional model identifier overrides for OpenAI routes/aircraft, OpenAI homepage, Grok homepage and OpenAI scene assessments. Blank values use Cloudflare's operator configuration. Existing provider selection and secrets remain operator-managed. A model must be supported by the configured provider; these controls do not grant provider access or bypass quotas and credit checks.
  • Limits: reduce per-account or global budgets for routes, imagery previews, navigation voice, generated images and aircraft AI reviews. Controls cannot increase the existing operator safety ceilings. Capabilities report the active account limits.

Registration additionally requires Cloudflare's operator registration switch to be on. Runtime controls cannot enable Stripe, reveal or replace provider keys, change provider URLs, grant administrator roles or access private user reports. Stripe remains controlled by the separately configured operator switch and sandbox/live safeguards. Configuration writes are versioned and audited with the admin's reason; a stale browser cannot silently overwrite a newer configuration.

Complete route integration examples

These longer clients cover saved request identity, full route creation, GeoJSON export, directions, risk data and stored-report retrieval. Start with the shorter destination-risk quick start above when exploring the API.

curl full route client

#!/usr/bin/env bash
# Requires Bash, curl, jq, Python 3. Save as route.sh; run: bash route.sh
# Set QRS_API_KEY securely on your server first. Never commit keys or enable set -x.
set -euo pipefail
umask 077
: "${QRS_API_KEY:?Set QRS_API_KEY in your server environment}"
BASE='https://ride.qroadscan.com'
# Save the unchanged body and key before sending. Keep them after a timeout.
if [[ ! -f qrs-operation.json ]]; then
  python3 - <<'PY'
import json, uuid
state = {"idempotency_key": str(uuid.uuid4()), "journey": {
    "start": {"latitude":40.75854190779626,"longitude":-73.97720754146576},
    "destination": {"latitude":40.753478752021245,"longitude":-73.98087680339813},
    "mode":"driving", "objective":"balanced",
    "notes":"Public road journey southbound on Fifth Avenue. Review junctions."
}}
# Optional: state["journey"]["vehicle_id"] = "OWNED_GARAGE_VEHICLE_UUID"
with open("qrs-operation.json", "x") as f: json.dump(state, f, indent=2)
PY
fi
IDEMPOTENCY_KEY=$(jq -er '.idempotency_key' qrs-operation.json)
jq '.journey' qrs-operation.json > journey.json
curl --fail-with-body --silent --show-error --max-time 30 \
  "$BASE/api/v1/account" -H "Authorization: Bearer $QRS_API_KEY" | jq .
curl --fail-with-body --silent --show-error --max-time 240 \
  "$BASE/api/v1/routes" -H "Authorization: Bearer $QRS_API_KEY" \
  -H 'Content-Type: application/json' -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
  --data-binary @journey.json > route-response.json
if jq -e '.status == "proposal" and .geometry_alignment.status == "matched"' route-response.json >/dev/null; then
  jq '.route_geojson' route-response.json > route.geojson
  jq '{risk_summary, steps, endpoint_inspections, route_metrics}' route-response.json
  REPORT_ID=$(jq -er '.report_id' route-response.json)
  curl --fail-with-body --silent --show-error --max-time 30 \
    "$BASE/api/v1/reports/$REPORT_ID" -H "Authorization: Bearer $QRS_API_KEY" \
    > saved-report.json
else
  rm -f -- route.geojson saved-report.json
  jq '{status, summary, endpoint_inspections, limitations}' route-response.json
fi
# Timeout? Rerun the same file/key. 409? Wait if processing; don't create a new key.
# If an operation_id is known: GET /api/v1/operations/{operation_id} (operations:read).
# Inspect its status; do not poll in a tight loop. Paid refunds and free limits differ.

httpx full route client

# Install: python -m pip install httpx
# Run: python route.py (set QRS_API_KEY securely on your server first).
import json
import os
from pathlib import Path
import uuid
import httpx

os.umask(0o077)  # Protect local journey and response files.
BASE = "https://ride.qroadscan.com"
KEY = os.environ["QRS_API_KEY"]
# Persist both files. Rerunning recovers the same operation, not a new scan.
state_file = Path("qrs-operation.json")
if state_file.exists():
    state = json.loads(state_file.read_text())
else:
    journey = {'start': {'latitude': 40.75854190779626, 'longitude': -73.97720754146576}, 'destination': {'latitude': 40.753478752021245, 'longitude': -73.98087680339813}, 'mode': 'driving', 'objective': 'balanced', 'notes': 'Public road journey southbound on Fifth Avenue. Review junctions.'}
    # Optional: journey["vehicle_id"] = "OWNED_GARAGE_VEHICLE_UUID"
    state = {"idempotency_key": str(uuid.uuid4()), "journey": journey}
    with state_file.open("x") as f:
        json.dump(state, f, indent=2)

with httpx.Client(timeout=httpx.Timeout(240, connect=10), follow_redirects=False) as client:
    def api(method, path, body=None, idem=None):
        headers = {"Authorization": "Bearer " + KEY}
        if idem:
            headers["Idempotency-Key"] = idem
        response = client.request(method, BASE + path, headers=headers, json=body, follow_redirects=False)
        if response.status_code >= 300:
            raise RuntimeError(f"HTTP {response.status_code}; request ID: "
                               + response.headers.get("X-Request-ID", "unknown"))
        return response.json()

    account = api("GET", "/api/v1/account")
    print("Available API attempts:", account["api_credits"])
    # Always preserve the same request/key after a timeout, even if balance is zero.
    route = api("POST", "/api/v1/routes", state["journey"], state["idempotency_key"])
    Path("route-response.json").write_text(json.dumps(route, indent=2))
    if route["status"] != "proposal" or route.get("geometry_alignment", {}).get("status") != "matched":
        Path("route.geojson").unlink(missing_ok=True)
        print("No accepted route:", route["summary"])
        print(route["endpoint_inspections"]["guidance"])
    else:
        Path("route.geojson").write_text(json.dumps(route["route_geojson"], indent=2))
        print("Modeled caution (not accident probability):", route["risk_summary"])
        for step in route["steps"]:
            print(step["index"], step["instruction"], step["distance_m"], step["risk_score"])
        # The key also needs scans:read to retrieve the stored report.
        saved = api("GET", "/api/v1/reports/" + str(route["report_id"]))
        print("Saved report:", saved["report_id"])
# Network timeout? Rerun with the saved state. 409? Do not generate a new key:
# wait if processing; inspect /api/v1/operations/{operation_id} when available.
# Delete the state file only when deliberately starting a NEW analysis attempt.

requests full route client

# Install: python -m pip install requests
# Run: python route.py (set QRS_API_KEY securely on your server first).
import json
import os
from pathlib import Path
import uuid
import requests

os.umask(0o077)  # Protect local journey and response files.
BASE = "https://ride.qroadscan.com"
KEY = os.environ["QRS_API_KEY"]
# Persist both files. Rerunning recovers the same operation, not a new scan.
state_file = Path("qrs-operation.json")
if state_file.exists():
    state = json.loads(state_file.read_text())
else:
    journey = {'start': {'latitude': 40.75854190779626, 'longitude': -73.97720754146576}, 'destination': {'latitude': 40.753478752021245, 'longitude': -73.98087680339813}, 'mode': 'driving', 'objective': 'balanced', 'notes': 'Public road journey southbound on Fifth Avenue. Review junctions.'}
    # Optional: journey["vehicle_id"] = "OWNED_GARAGE_VEHICLE_UUID"
    state = {"idempotency_key": str(uuid.uuid4()), "journey": journey}
    with state_file.open("x") as f:
        json.dump(state, f, indent=2)

with requests.Session() as client:
    def api(method, path, body=None, idem=None):
        headers = {"Authorization": "Bearer " + KEY}
        if idem:
            headers["Idempotency-Key"] = idem
        response = client.request(method, BASE + path, headers=headers, json=body, timeout=(10, 240), allow_redirects=False)
        if response.status_code >= 300:
            raise RuntimeError(f"HTTP {response.status_code}; request ID: "
                               + response.headers.get("X-Request-ID", "unknown"))
        return response.json()

    account = api("GET", "/api/v1/account")
    print("Available API attempts:", account["api_credits"])
    # Always preserve the same request/key after a timeout, even if balance is zero.
    route = api("POST", "/api/v1/routes", state["journey"], state["idempotency_key"])
    Path("route-response.json").write_text(json.dumps(route, indent=2))
    if route["status"] != "proposal" or route.get("geometry_alignment", {}).get("status") != "matched":
        Path("route.geojson").unlink(missing_ok=True)
        print("No accepted route:", route["summary"])
        print(route["endpoint_inspections"]["guidance"])
    else:
        Path("route.geojson").write_text(json.dumps(route["route_geojson"], indent=2))
        print("Modeled caution (not accident probability):", route["risk_summary"])
        for step in route["steps"]:
            print(step["index"], step["instruction"], step["distance_m"], step["risk_score"])
        # The key also needs scans:read to retrieve the stored report.
        saved = api("GET", "/api/v1/reports/" + str(route["report_id"]))
        print("Saved report:", saved["report_id"])
# Network timeout? Rerun with the saved state. 409? Do not generate a new key:
# wait if processing; inspect /api/v1/operations/{operation_id} when available.
# Delete the state file only when deliberately starting a NEW analysis attempt.

javascript full route client

// Requires Node.js 22+. Save as route.mjs; run: node route.mjs
// Set QRS_API_KEY in your server's environment. Never embed it in a browser.
import {readFile, writeFile, rm} from 'node:fs/promises';
import {randomUUID} from 'node:crypto';
const base = 'https://ride.qroadscan.com';
const key = process.env.QRS_API_KEY;
if (!key) throw new Error('Set QRS_API_KEY first');
let state;
try { state = JSON.parse(await readFile('qrs-operation.json', 'utf8')); }
catch (error) {
  if (error.code !== 'ENOENT') throw error;
  state = {
    idempotency_key: randomUUID(),
    journey: {
      start: {latitude: 40.75854190779626, longitude: -73.97720754146576},
      destination: {latitude: 40.753478752021245, longitude: -73.98087680339813},
      mode: 'driving', objective: 'balanced',
      notes: 'Public road journey southbound on Fifth Avenue. Review junctions.'
      // Optional: vehicle_id: 'OWNED_GARAGE_VEHICLE_UUID'
    }
  };
  await writeFile('qrs-operation.json', JSON.stringify(state, null, 2), {flag: 'wx', mode: 0o600});
}
async function api(method, path, body, idem) {
  const response = await fetch(base + path, {
    method, redirect: 'error', signal: AbortSignal.timeout(240_000),
    headers: {Authorization: 'Bearer ' + key,
      ...(body ? {'Content-Type': 'application/json'} : {}),
      ...(idem ? {'Idempotency-Key': idem} : {})},
    ...(body ? {body: JSON.stringify(body)} : {})
  });
  if (!response.ok) throw new Error('HTTP ' + response.status + '; request ID: ' + response.headers.get('X-Request-ID'));
  return response.json();
}
console.log('Account:', await api('GET', '/api/v1/account'));
const route = await api('POST', '/api/v1/routes', state.journey, state.idempotency_key);
await writeFile('route-response.json', JSON.stringify(route, null, 2), {mode: 0o600});
if (route.status !== 'proposal' || route.geometry_alignment?.status !== 'matched') {
  await rm('route.geojson', {force: true});
  console.log('No accepted route:', route.summary, route.endpoint_inspections.guidance);
} else {
  await writeFile('route.geojson', JSON.stringify(route.route_geojson), {mode: 0o600});
  console.log('Modeled caution, not accident probability:', route.risk_summary);
  for (const step of route.steps) console.log(step.index, step.instruction, step.distance_m, step.risk_score);
  console.log('Saved report:', await api('GET', '/api/v1/reports/' + route.report_id));
}
// On a timeout, rerun with the saved state; do not change the key or request.
// On 409, wait if processing. Poll /api/v1/operations/{operation_id} when known.
// Only remove qrs-operation.json when deliberately starting a NEW paid/free attempt.

go full route client

// Requires Go 1.22+. Save as route.go; run: go run route.go
// Set QRS_API_KEY securely in your server environment first.
package main
import (
 "bytes"; "crypto/rand"; "encoding/hex"; "encoding/json"; "fmt"; "io"; "net/http"; "os"; "time"
)
type State struct { Key string `json:"idempotency_key"`; Journey json.RawMessage `json:"journey"` }
func main() {
 key := os.Getenv("QRS_API_KEY"); if key == "" { panic("Set QRS_API_KEY") }
 var state State
 data, err := os.ReadFile("qrs-operation.json")
 if os.IsNotExist(err) {
  random := make([]byte, 16); if _,err = rand.Read(random); err != nil { panic(err) }
  state = State{Key:hex.EncodeToString(random), Journey:json.RawMessage(`{
   "start":{"latitude":40.75854190779626,"longitude":-73.97720754146576},
   "destination":{"latitude":40.753478752021245,"longitude":-73.98087680339813},
   "mode":"driving","objective":"balanced",
   "notes":"Public road journey southbound on Fifth Avenue. Review junctions."
  }`)} // Optional: add vehicle_id for an owned garage vehicle.
  data,err = json.MarshalIndent(state,"","  "); if err != nil { panic(err) }
  f,e := os.OpenFile("qrs-operation.json",os.O_CREATE|os.O_EXCL|os.O_WRONLY,0600); if e != nil { panic(e) }
  if _,e=f.Write(data); e != nil { f.Close(); panic(e) }; f.Close()
 } else if err != nil { panic(err) } else if err=json.Unmarshal(data,&state); err != nil { panic(err) }
 client := &http.Client{Timeout:240*time.Second, CheckRedirect:func(*http.Request,[]*http.Request)error{return http.ErrUseLastResponse}}
 api := func(method,path string,body []byte,idem string) map[string]any {
  req,e:=http.NewRequest(method,"https://ride.qroadscan.com"+path,bytes.NewReader(body));if e!=nil{panic(e)}
  req.Header.Set("Authorization","Bearer "+key)
  if body!=nil{req.Header.Set("Content-Type","application/json")};if idem!=""{req.Header.Set("Idempotency-Key",idem)}
  res,e:=client.Do(req);if e!=nil{panic(e)};defer res.Body.Close()
  if res.StatusCode<200||res.StatusCode>=300{panic(fmt.Sprintf("HTTP %d; request ID: %s",res.StatusCode,res.Header.Get("X-Request-ID")))}
  var out map[string]any;if e=json.NewDecoder(io.LimitReader(res.Body,1048576)).Decode(&out);e!=nil{panic(e)};return out
 }
 fmt.Println("Account:",api("GET","/api/v1/account",nil,""))
 route:=api("POST","/api/v1/routes",state.Journey,state.Key)
 save:=func(name string,v any){b,e:=json.MarshalIndent(v,"","  ");if e!=nil{panic(e)};if e=os.WriteFile(name,b,0600);e!=nil{panic(e)}}
 save("route-response.json",route)
 alignment,_:=route["geometry_alignment"].(map[string]any)
 if route["status"]!="proposal"||alignment["status"]!="matched"{os.Remove("route.geojson");os.Remove("saved-report.json");fmt.Println("No accepted route:",route["summary"]);return}
 save("route.geojson",route["route_geojson"])
 fmt.Println("Modeled caution, not accident probability:",route["risk_summary"])
 for _,step:=range route["steps"].([]any){fmt.Println(step)}
 report:=fmt.Sprintf("%.0f",route["report_id"].(float64))
 save("saved-report.json",api("GET","/api/v1/reports/"+report,nil,""))
}
// Timeout? Rerun with the saved state; do not change request or key.
// 409? Wait if processing. Poll /api/v1/operations/{operation_id} when known.
// Remove state only to deliberately start a NEW analysis attempt.

csharp full route client

// Requires .NET 8+. dotnet new console -n QrsRoute; replace Program.cs with this.
// Set QRS_API_KEY in your server environment; run: dotnet run --project QrsRoute
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
var key = Environment.GetEnvironmentVariable("QRS_API_KEY")
    ?? throw new InvalidOperationException("Set QRS_API_KEY");
JsonNode state;
if (File.Exists("qrs-operation.json")) {
    state = JsonNode.Parse(await File.ReadAllTextAsync("qrs-operation.json"))!;
} else {
    state = new JsonObject {
        ["idempotency_key"] = Guid.NewGuid().ToString(),
        ["journey"] = JsonNode.Parse("""
        {"start":{"latitude":40.75854190779626,"longitude":-73.97720754146576},
         "destination":{"latitude":40.753478752021245,"longitude":-73.98087680339813},
         "mode":"driving","objective":"balanced",
         "notes":"Public road journey southbound on Fifth Avenue. Review junctions."}
        """) // Optional: add vehicle_id for an owned garage vehicle.
    };
    await using var file = new FileStream("qrs-operation.json",FileMode.CreateNew);
    await JsonSerializer.SerializeAsync(file,state);
}
using var handler = new HttpClientHandler { AllowAutoRedirect = false };
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(240) };
async Task<JsonNode> Api(HttpMethod method,string path,JsonNode? body=null,string? idem=null) {
    using var request = new HttpRequestMessage(method,"https://ride.qroadscan.com"+path);
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer",key);
    if (idem != null) request.Headers.Add("Idempotency-Key",idem);
    if (body != null) request.Content = new StringContent(body.ToJsonString(),Encoding.UTF8,"application/json");
    using var response = await client.SendAsync(request);
    response.EnsureSuccessStatusCode();
    return JsonNode.Parse(await response.Content.ReadAsStringAsync())!;
}
Console.WriteLine("Account: "+await Api(HttpMethod.Get,"/api/v1/account"));
var route = await Api(HttpMethod.Post,"/api/v1/routes",state["journey"],state["idempotency_key"]!.GetValue<string>());
await File.WriteAllTextAsync("route-response.json",route.ToJsonString());
if (route["status"]?.GetValue<string>() != "proposal" || route["geometry_alignment"]?["status"]?.GetValue<string>() != "matched") {
    File.Delete("route.geojson"); File.Delete("saved-report.json");
    Console.WriteLine("No accepted route: "+route["summary"]);
} else {
    await File.WriteAllTextAsync("route.geojson",route["route_geojson"]!.ToJsonString());
    Console.WriteLine("Modeled caution, not accident probability: "+route["risk_summary"]);
    foreach (var step in route["steps"]!.AsArray()) Console.WriteLine(step);
    var saved = await Api(HttpMethod.Get,"/api/v1/reports/"+route["report_id"]!.GetValue<long>());
    await File.WriteAllTextAsync("saved-report.json",saved.ToJsonString());
}
// On a timeout, rerun with the SAME saved state; no automatic new operation.
// On 409, wait if processing; inspect /api/v1/operations/{operation_id} when known.
// Protect local journey/report files; restrict their filesystem permissions.

php full route client

<?php
// Requires PHP 8.1+ with cURL. Save as route.php; run: php route.php
// Set QRS_API_KEY securely in your server environment first.
$key = getenv('QRS_API_KEY');
if (!$key) throw new RuntimeException('Set QRS_API_KEY');
umask(0077);
if (file_exists('qrs-operation.json')) {
    $state = json_decode(file_get_contents('qrs-operation.json'),true,512,JSON_THROW_ON_ERROR);
} else {
    $state = ['idempotency_key'=>bin2hex(random_bytes(16)), 'journey'=>[
        'start'=>['latitude'=>40.75854190779626,'longitude'=>-73.97720754146576],
        'destination'=>['latitude'=>40.753478752021245,'longitude'=>-73.98087680339813],
        'mode'=>'driving','objective'=>'balanced',
        'notes'=>'Public road journey southbound on Fifth Avenue. Review junctions.'
        // Optional: 'vehicle_id'=>'OWNED_GARAGE_VEHICLE_UUID'
    ]];
    $f = fopen('qrs-operation.json','x');
    if ($f === false) throw new RuntimeException('State already exists or is unwritable');
    fwrite($f,json_encode($state,JSON_THROW_ON_ERROR)); fclose($f);
}
function api(string $method,string $path,?array $body=null,?string $idem=null): array {
    global $key;
    $headers = ['Authorization: Bearer '.$key];
    if ($body !== null) $headers[] = 'Content-Type: application/json';
    if ($idem !== null) $headers[] = 'Idempotency-Key: '.$idem;
    $ch = curl_init('https://ride.qroadscan.com'.$path);
    $options = [CURLOPT_CUSTOMREQUEST=>$method,CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_FOLLOWLOCATION=>false,CURLOPT_TIMEOUT=>240,CURLOPT_CONNECTTIMEOUT=>10,
        CURLOPT_HTTPHEADER=>$headers];
    if ($body !== null) $options[CURLOPT_POSTFIELDS] = json_encode($body,JSON_THROW_ON_ERROR);
    curl_setopt_array($ch,$options);$response = curl_exec($ch);
    if ($response === false) { $error=curl_error($ch);curl_close($ch);throw new RuntimeException($error); }
    $status=curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);
    if ($status<200||$status>=300) throw new RuntimeException('HTTP '.$status);
    return json_decode($response,true,512,JSON_THROW_ON_ERROR);
}
print_r(api('GET','/api/v1/account'));
$route=api('POST','/api/v1/routes',$state['journey'],$state['idempotency_key']);
file_put_contents('route-response.json',json_encode($route,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
if ($route['status']!=='proposal'||($route['geometry_alignment']['status']??null)!=='matched') {
    if (is_file('route.geojson')) unlink('route.geojson');
    if (is_file('saved-report.json')) unlink('saved-report.json');
    echo 'No accepted route: '.$route['summary'].PHP_EOL;
} else {
    file_put_contents('route.geojson',json_encode($route['route_geojson'],JSON_THROW_ON_ERROR));
    echo 'Modeled caution, not accident probability:'.PHP_EOL; print_r($route['risk_summary']);
    foreach ($route['steps'] as $step) print_r($step);
    $saved=api('GET','/api/v1/reports/'.$route['report_id']);
    file_put_contents('saved-report.json',json_encode($saved,JSON_THROW_ON_ERROR));
}
// Timeout? Rerun the SAME saved state. 409? Wait if processing; don't create a new key.
// Inspect /api/v1/operations/{operation_id} when known. Respect poll_after_seconds.
// Delete state only when intentionally requesting a NEW analysis attempt.

Aircraft risk report, observed tracks and hypothetical traffic

POST /api/v1/aviation/briefing now returns snapshot plus briefing.risk_review, briefing.synthetic_tracks, briefing.simulation_summary, and explicit provenance. Use the existing aviation:review scope. The request body is unchanged. Each of the four risk categories (weather, wind, traffic, fuel) has a model caution score from 0–100 or null, a confidence label, evidence basis, and data gaps. The score is not an accident probability, separation assessment, or operational flight approval. Missing/stale surveillance forces the traffic score to null; incomplete fuel assumptions force the fuel score to null. Do not use fictional scenario traffic to fill these gaps.

Live snapshots try OpenSky first, then the public adsb.lol ADS-B feed if OpenSky fails or is limited. snapshot.traffic.provider, snapshot_at, retrieved_at, attempts, and coverage_radius_nm identify the actual source, age, fallback failures and approximate monitoring extent. Coverage is centered on the corridor midpoint and capped at 250 NM radius. Long flights and dateline corridors may not be fully covered. No positions means no reported positions, not clear airspace. Provider and application quotas still apply; refresh at most once per minute in the UI. Monitoring stops when the tab is hidden or inputs change. adsb.lol data attribution: https://www.adsb.lol/ (CC0 (provider data license)).

Cyan planes represent reported positions. Cyan trails connect successive fresh observations in the current browser session, retaining at most ten minutes; gaps over three minutes and implausible jumps are not connected. Trails appear after successive updates, not on the first snapshot. Heading ticks indicate reported direction, not a filed flight path, destination or prediction. All observed map positions and trails are removed once their source snapshot exceeds 90 seconds. Neither public feed supplies verified filed flight plans through this integration.

Purple dotted tracks and SIM- labels are entirely hypothetical LLM traffic scenarios. Their provenance is LLM_SYNTHETIC_SCENARIO. Each track contains two to six bounded points (latitude, longitude, altitude_ft, offset_minutes), strictly increasing within a 0–15 minute scenario horizon. They do not identify real flights or predict real future movement. The scenario slider interpolates the fictional track only within its supplied time range. Toggle this layer independently; it never changes the observed traffic list, source status, or observed-data caution score. Refreshing evidence or changing inputs clears the old scenario and risk report; request a new AI scan to generate a new review. No raw real-user flight history is persisted by this feature.

Terms of Service