diff --git a/README.md b/README.md index ab43a02..6f3c2a4 100644 --- a/README.md +++ b/README.md @@ -239,7 +239,7 @@ charting or document tools to create figures and analysis. Custom chart renderin in the agent's tools. The API supplies comparisons, scenario calculations, provenance and JSON. Configuration/model-year data and VIN-specific facts retain their distinct scopes. -VIN recall repair status: Tesla and Ford open/completed statuses, GM open/completed or administratively closed records, Honda and Acura active safety recalls, Subaru completed/incomplete safety recalls, Volkswagen, Audi, Land Rover and Jaguar recalls as reported by each maker, positive Nissan open safety recalls, and Mopar VIN-matched open recall/campaign records are included in reports and comparisons, with `vin_recall_status`, `GET /api/vin/{vin}/recall-status` and `VinClient.recallStatus(vin)`. Mopar safety-recall count and completed history remain unknown because its feed mixes campaign types. GM repair dates are shown only when explicitly supplied; administrative closing dates remain separate. Ford customer-satisfaction and GM non-recall programs stay separate from recall counts. Honda covers active safety recalls from the past 15 calendar years and does not supply completed history. Nissan requires matching full VINs and verified safety classifications; empty results remain unknown. Toyota/Lexus/Scion, Hyundai and Kia require interactive official verification. Other makes remain unknown. See the [source and coverage notes](docs/data-sources.md#vin-specific-recall-repair-status). +VIN recall repair status: Tesla and Ford open/completed statuses, GM open/completed or administratively closed records, Honda and Acura active safety recalls, Subaru completed/incomplete safety recalls, Volkswagen, Audi, Land Rover and Jaguar recalls as reported by each maker, positive Nissan open safety recalls, and Mopar VIN-matched open recall/campaign records are included in reports and comparisons, with `vin_recall_status`, `GET /api/vin/{vin}/recall-status` and `VinClient.recallStatus(vin)`. Mopar safety-recall count and completed history remain unknown because its feed mixes campaign types. GM repair dates are shown only when explicitly supplied; administrative closing dates remain separate. Ford customer-satisfaction and GM non-recall programs stay separate from recall counts. Honda covers active safety recalls from the past 15 calendar years and does not supply completed history. Nissan requires matching full VINs and verified safety classifications; empty results remain unknown. Toyota/Lexus/Scion, Hyundai and Kia require interactive official verification. Other makes remain unknown. A report waits up to 2 s for the maker's lookup (MCP `decode_vin`: 6 s); a slower maker (Ford's lookup usually takes about 10 s) gives `recall_status.pending: true`, unknown rather than zero, with `status_url` to fetch the complete status from the same running lookup, or ask with `?recall_wait=full` (`VinClient.decode(vin, {recallWait: 'full'})`). NHTSA's complaint list (5-17 s for a common model) arrives the same way: `complaints.pending: true` with `status_url` `/api/vin/{vin}/complaints`. See the [source and coverage notes](docs/data-sources.md#vin-specific-recall-repair-status). Deployment caching: HTML must revalidate, API responses must not be stored by shared caches, and changed JavaScript/PDF links use a content-hash query version generated by `node scripts/version-assets.mjs`. API clients also bypass stored browser responses. Preserve these policies in any reverse proxy so updated recall records are rendered by the matching client code. diff --git a/docs/data-sources.md b/docs/data-sources.md index 1a2bb85..9f64869 100644 --- a/docs/data-sources.md +++ b/docs/data-sources.md @@ -187,6 +187,29 @@ Tesla Service's [official VIN recall search](https://service.tesla.com/en-US/vin `GET /api/vin/{vin}/recall-status`, `VinClient.recallStatus(vin)` and MCP `vin_recall_status` expose this data. VIN reports and printable comparisons include the summary. Tesla and Ford supply open/completed states. Subaru supplies completed and incomplete safety recalls, with emissions campaigns listed separately. Volkswagen, Audi and Land Rover report open recalls, and completed ones only where their lookup returns them. Acura is covered through the Honda lookup. (Added 2026-11-16 in `lib/more-manufacturer-recalls.mjs`; open records have been seen live for Volkswagen and Audi; completed records for those two, and any Land Rover or Jaguar record, have only been read from the makers' page code. Jaguar shares Land Rover's lookup. BMW's lookup did not answer plain requests and is not used.) GM supplies open/completed or administratively closed records, and explicit repair dates where supplied. Honda supplies active safety recalls; Nissan supplies positive open safety recalls and Mopar supplies VIN-matched open recall/campaign records, with the limitations below. Toyota, Lexus, Scion, Hyundai and Kia require interactive verification; other manufacturers return unknown with an official lookup link. Unknown response statuses never count as zero open recalls; recall dates never become repair completion dates. Results are not a complete service history or a guarantee of safety. Successful results are cached for up to 15 minutes; failures are retried. Public manufacturer interfaces are undocumented for third-party integration and can change. +#### When the maker answers slowly: `pending` + +A report does not wait the whole time for a slow maker. The lookup starts as soon as the VIN is decoded, beside NHTSA's calls, and the report waits for it up to a budget counted from that start: 2 s for the website and `GET /api/vin/{vin}` (`RECALL_WAIT_MS.report` in `lib/reports.mjs`), 6 s for MCP `decode_vin` (`RECALL_WAIT_MS.mcp`). Comparisons wait for the full answer (they are printed and exported). A maker still answering after the budget gives: + +```json +"recall_status": {"vin": "1FMCU0G61LUA27504", "scope": "vin", "vin_specific": true, "available": false, + "pending": true, "reason": "lookup_in_progress", "maker": "Ford", "waited_ms": 2000, + "open_count": null, "completed_count": null, "recalls": [], + "source": {"provider": "Ford Owner Support VIN Recalls", "reference_url": "https://www.ford.com/support/recalls-details/..."}, + "verification_url": "https://www.ford.com/support/recalls-details/...", + "status_url": "/api/vin/1FMCU0G61LUA27504/recall-status", "note": "..."} +``` + +Pending is unknown, never "no open recalls" (`available: false`, counts null). The lookup keeps running in the background and fills the 15-minute cache; one lookup per VIN runs at a time and every request for that VIN shares it (`createRecallStatusLookup`). `GET status_url`, MCP `vin_recall_status` and `GET /api/vin/{vin}?recall_wait=full` (MCP: `recall_wait: "full"`) wait for that same lookup. A background lookup that fails is caught: nothing is cached and the next request asks the maker again. In MCP output a pending status also carries `next_step: {tool: "vin_recall_status", arguments: {vin}}`. `decode_checks.sources.manufacturer_record.status` is `pending` meanwhile; the checks that use the maker's description of the VIN run when the status arrives. + +The website shows "Checking with Ford…" in the recall card, the car sheet's recall row and the decode-checks source line, then requests the report again with `?recall_wait=full` and redraws only the blocks that changed (the status block, the car sheet's recall section and footer, and the decode checks, fuel economy and test-vehicle blocks only if the maker's record changed a checked value), keeping typed text, open forms, focus, the transmission choice and the scroll position (`public/keep-state.js`). Printed while pending, the car sheet's row reads "Unknown: Ford had not answered when this sheet was printed" and the recall card "Not loaded: Ford had not answered when this page was printed"; printing does not wait. If the second request fails twice, the status reads as not loaded (unknown). + +Why Ford is slow (measured 2026-11-18 from the web server, 4 requests): Ford's CDN (Akamai) holds each request about 9-10 s before answering (`server-timing` edge duration 9,000-10,002 ms; origin about 120 ms), even for a no-VIN page, a cached redirect and a reused connection, so the delay is per request and a client cannot shorten it. The VIN page is also about 1.3 MB, with the recall data about 81% of the way through. Reports for other makes took 0.4-2 s in all before this change. + +#### NHTSA's complaint list: `pending` the same way + +NHTSA's `complaintsByVehicle` sends a model year's whole list at once: 1-2 MB of JSON for a common model, which took 17.3 s for a 2020 Ford Escape, 5.0 s for a 2017 Honda CR-V and 6.4 s for a 2003 Honda Accord (from the web server, 2026-11-18; time to first byte, so NHTSA's own time). It used to be awaited with the rest under a 10 s timeout, so the Escape's list always failed and its report was never cached. Now (`modelYearComplaints` in `lib/reports.mjs`) one request per make, model and year runs at a time, shared by every report and `GET /api/vin/{vin}/complaints`, for up to 30 s; successful lists are cached 6 hours. The report is assembled without waiting for it and waits up to the same budgets (2 s website and REST, 6 s MCP; comparisons wait). Still arriving, `complaints` is `{"available": false, "pending": true, "reason": "lookup_in_progress", "count": null, "complaints": [], "summary": null, "status_url": "/api/vin/{vin}/complaints", "note": ...}`: unknown, never zero. When the list arrives the complete report is built and cached for the next request. The server-rendered VIN page (`/{vin}`) no longer waits for the list (it leaves the complaint count out of its description while pending). The website shows "Loading NHTSA's owner complaints…" and fills the card and the car sheet's row in place from `status_url`; printed while pending they say the list had not arrived. In MCP output a pending list says to call `decode_vin` again (there is no complaints tool). + ### Ford: open/completed recalls and separate programs The [official Ford VIN page](https://www.ford.com/support/recalls/) serves its VIN-specific status in the same public page used by the browser. The adapter parses the serialized data as JSON; it never executes downloaded JavaScript. Both the page VIN and the returned vehicle VIN must match. The success flag, validation flag, arrays and declared record counts must agree. `O` means open and `C` means completed; other values remain unknown. Safety/environmental recall records and customer-satisfaction programs are separate. Coverage begins January 1, 2004. No repair date is supplied, so `repair_completed_at` remains null. The same official checker accepts Ford, Lincoln and Mercury; upstream confirmation still controls availability. @@ -674,7 +697,8 @@ tires and capacities) use the checked values. Code: `lib/decode-checks.mjs`, `li disagree leave the field unset; "e-tron", "PZEV", "FED", a lone "A" and Subaru's "2.5X" are never read as powertrain, transmission or drive. The VIN page is drawn before the maker replies and never waits for it (`sources.manufacturer_record.status: "not_checked"`); the REST report, MCP `decode_vin` and comparisons - re-run the checks with it (`used`, `not_available` or `not_supported`). In a gentle sample of 16 NHTSA test + re-run the checks with it (`used`, `not_available` or `not_supported`), or say `pending` when the maker had not + answered within the report's wait (see "When the maker answers slowly" above; the website then fills them in). In a gentle sample of 16 NHTSA test vehicles the description agreed with vPIC on every stated field except drive on both 2018 Atlases (vPIC AWD, Volkswagen "FWD", both test reports FWD), and named "MULTITRONIC" (a CVT) where vPIC said "Automatic". - **NHTSA test-vehicle evidence.** `data-src/decode-evidence.jsonl` (built offline by the audit, imported with diff --git a/lib/cache.mjs b/lib/cache.mjs index 26f1943..c4572ca 100644 --- a/lib/cache.mjs +++ b/lib/cache.mjs @@ -63,3 +63,4 @@ export const vinCache = new LRUCache(1000, 60 * 60 * 1000); // 1hr for full export const recallCache = new LRUCache(500, 6 * 60 * 60 * 1000); // 6hr for recalls (change less often) export const ratingCache = new LRUCache(500, 24 * 60 * 60 * 1000); // 24hr for safety ratings (static) export const fuelCache = new LRUCache(500, 24 * 60 * 60 * 1000); // 24hr for fuel economy (static) +export const complaintCache = new LRUCache(200, 6 * 60 * 60 * 1000); // 6hr for NHTSA complaints (1-2 MB for a common model) diff --git a/lib/mcp/research-tools.mjs b/lib/mcp/research-tools.mjs index dbefb25..ddc6525 100644 --- a/lib/mcp/research-tools.mjs +++ b/lib/mcp/research-tools.mjs @@ -5,7 +5,7 @@ import { rateBenchmarks } from '../rate-benchmarks.mjs'; import { scenario } from '../scenario.mjs'; import { communications } from '../communications.mjs'; import { capabilities } from '../capabilities.mjs'; -import { vinRecallStatus } from '../recall-status.mjs'; +import { vinRecallStatusFor } from '../reports.mjs'; import { compareVehicles } from '../reports.mjs'; export function researchTools(add) { @@ -15,7 +15,7 @@ export function researchTools(add) { }); const vehicleQuery={year:z.number().int(),make:z.string().min(1).max(100),model:z.string().min(1).max(100)}; researchTool('explore_capabilities','Discover supported features and explicit coverage gaps.',{},()=>capabilities); - researchTool('vin_recall_status','VIN-specific manufacturer-reported open and completed recall status. Tesla and Ford open/completed states; GM completed/closed states with explicit repair dates where supplied; Honda and Acura active safety recalls; Subaru completed/incomplete safety recalls; Volkswagen, Audi, Land Rover and Jaguar recalls as reported by each maker; Nissan positive open safety recalls; Mopar positive open records matched to the full VIN. Service programs are separate. Toyota, Hyundai and Kia require interactive official verification. Unknowns are never zero. Not a complete service history. Where the maker\'s reply describes the VIN (Volkswagen, Audi, Land Rover, Jaguar, Subaru, Honda/Acura), manufacturer_description gives the raw text and only the fields it states.',{vin:z.string()},({vin})=>vinRecallStatus(vin)); + researchTool('vin_recall_status','VIN-specific manufacturer-reported open and completed recall status. Tesla and Ford open/completed states; GM completed/closed states with explicit repair dates where supplied; Honda and Acura active safety recalls; Subaru completed/incomplete safety recalls; Volkswagen, Audi, Land Rover and Jaguar recalls as reported by each maker; Nissan positive open safety recalls; Mopar positive open records matched to the full VIN. Service programs are separate. Toyota, Hyundai and Kia require interactive official verification. Unknowns are never zero. Not a complete service history. Where the maker\'s reply describes the VIN (Volkswagen, Audi, Land Rover, Jaguar, Subaru, Honda/Acura), manufacturer_description gives the raw text and only the fields it states. When a decode_vin report has recall_status.pending, this waits for that same lookup (up to about 15 s).',{vin:z.string()},({vin})=>vinRecallStatusFor(vin)); researchTool('vehicle_catalog','Browse EPA year, make, model and configuration menus. Not sale listings.',{level:z.enum(['year','make','model','options']),year:z.number().int().optional(),make:z.string().optional(),model:z.string().optional()},({level,...query})=>catalog(level,query)); researchTool('epa_vehicle','Get an explicitly selected EPA test configuration; not an exact VIN match.',{id:z.string()},({id})=>epaRecord(id)); researchTool('vehicle_emissions','Get EPA emissions for an explicit EPA vehicle ID.',{id:z.string()},({id})=>emissions(id)); diff --git a/lib/mcp/vehicle-tools.mjs b/lib/mcp/vehicle-tools.mjs index 0a2c944..c763fee 100644 --- a/lib/mcp/vehicle-tools.mjs +++ b/lib/mcp/vehicle-tools.mjs @@ -1,16 +1,17 @@ import * as z from 'zod/v4'; import { validateVin, normalizeVin } from '../validate.mjs'; import { decodeVin as nhtsaDecode, batchDecode } from '../nhtsa.mjs'; -import { fullReport, mcpReport, modelYearRecalls } from '../reports.mjs'; +import { fullReport, mcpReport, modelYearRecalls, RECALL_WAIT_MS } from '../reports.mjs'; import { applyOwnerDetails } from '../transmission-choice.mjs'; export function vehicleTools(add) { add('decode_vin', - 'Decode a VIN and return a vehicle report: specs, recalls (with manufacturer build-date ranges), a complaint summary with the most recent complaints, safety ratings, fuel economy, EPA test-vehicle data, parts content and origin (MY2020+), historical production and theft (MY1998-2012), and photo URLs. decode_checks checks the official decode field by field (drive, engine, electrification, transmission, speeds, seats, GVWR) against the manufacturer\'s description of this VIN, NHTSA test vehicles with the same VIN pattern and EPA\'s configurations: confirmed, corrected, doubtful or filled, with vPIC\'s original value kept.', + 'Decode a VIN and return a vehicle report: specs, recalls (with manufacturer build-date ranges), a complaint summary with the most recent complaints, safety ratings, fuel economy, EPA test-vehicle data, parts content and origin (MY2020+), historical production and theft (MY1998-2012), and photo URLs. decode_checks checks the official decode field by field (drive, engine, electrification, transmission, speeds, seats, GVWR) against the manufacturer\'s description of this VIN, NHTSA test vehicles with the same VIN pattern and EPA\'s configurations: confirmed, corrected, doubtful or filled, with vPIC\'s original value kept. recall_status is the manufacturer\'s VIN-specific recall status; a maker that has not answered within about 6 s (Ford\'s lookup takes 10 s or more) gives recall_status.pending true: unknown, not "no open recalls"; call vin_recall_status with the VIN for the complete answer, or pass recall_wait "full". NHTSA\'s complaint list for a common model can take 15 s or more: complaints.pending true is unknown, not zero; call decode_vin again in a minute (cached once it arrives).', { vin: z.string().describe('17-character Vehicle Identification Number'), - transmission: z.optional(z.enum(['automatic', 'manual'])).describe('Transmission, when the owner knows it and the VIN does not say. Applies to fuel economy only when EPA lists the model with both; without it an automatic is assumed and marked (fuel_economy.assumed, alternatives).') }, - async ({ vin, transmission }) => { - const report = mcpReport(applyOwnerDetails(await fullReport(vin), { transmission }, { by: 'request' })); + transmission: z.optional(z.enum(['automatic', 'manual'])).describe('Transmission, when the owner knows it and the VIN does not say. Applies to fuel economy only when EPA lists the model with both; without it an automatic is assumed and marked (fuel_economy.assumed, alternatives).'), + recall_wait: z.optional(z.enum(['full'])).describe('"full": wait for the manufacturer\'s VIN recall lookup (up to about 15 s) instead of returning recall_status.pending after about 6 s.') }, + async ({ vin, transmission, recall_wait }) => { + const report = mcpReport(applyOwnerDetails(await fullReport(vin, { recallWaitMs: recall_wait === 'full' ? Infinity : RECALL_WAIT_MS.mcp, complaintsWaitMs: RECALL_WAIT_MS.mcp }), { transmission }, { by: 'request' })); return { content: [{ type: 'text', text: JSON.stringify(report, null, 2) }] }; } ); diff --git a/lib/nhtsa.mjs b/lib/nhtsa.mjs index edb2681..1a21bd3 100644 --- a/lib/nhtsa.mjs +++ b/lib/nhtsa.mjs @@ -369,6 +369,23 @@ const RELATED_NOTE = 'Campaigns NHTSA files for the same make and year under ano * Labels come from NHTSA's /products/vehicle/models reply, which lists only part of a make's * labels (checked 2026-11-16), and from the local flat-file label index when it is installed. */ +/** Run `fn` over `items`, at most `limit` at a time; results in input order. */ +export async function mapLimit(items, limit, fn) { + const out = new Array(items.length); + let next = 0; + const worker = async () => { while (next < items.length) { const i = next++; out[i] = await fn(items[i], i); } }; + await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker)); + return out; +} + +// Related-name campaign lookups in flight at once (one recallsByVehicle call each; results cached 6 hours per +// make/model/year by lib/reports.mjs). Was one at a time; three keeps the same requests gentle and cuts the wait. +const RELATED_CONCURRENCY = 3; + +/** + * `exactRecalls`: the exact-name campaigns, or a promise of them (the label search then runs while the exact lookup + * is still out); null (or a promise of null) when the exact lookup failed: no per-name lookup is made then. + */ export async function getRelatedModelRecalls(make, model, year, exactRecalls = [], { labelIndex = lookupRecallLabels } = {}) { const unavailable = { available: false, scope: 'make_related_model_year', vin_specific: false, count: null, models: [] }; try { @@ -386,14 +403,11 @@ export async function getRelatedModelRecalls(make, model, year, exactRecalls = [ const decodedNameUsed = index?.available ? decodedNameForms(model).some(n => index.used_names.has(n)) : true; const matches = relatedModelMatches(model, labels, { make, decodedNameUsed }); const checked = matches.slice(0, MAX_RELATED_LABELS), unchecked = matches.slice(MAX_RELATED_LABELS); - const known = new Set(exactRecalls.map(r => r?.campaign_number).filter(Boolean)); - // One label at a time, as before: gentle on api.nhtsa.gov, and the result is cached per make/model/year. - const results = []; - for (const m of checked) { - const r = await getRecalls(make, m.label, year); - if (r.available === false) return unavailable; - results.push(r); - } + const exact = await exactRecalls; + if (!Array.isArray(exact)) return unavailable; + const known = new Set(exact.map(r => r?.campaign_number).filter(Boolean)); + const results = await mapLimit(checked, RELATED_CONCURRENCY, m => getRecalls(make, m.label, year)); + if (results.some(r => r.available === false)) return unavailable; const models = [], seen = new Set(); checked.forEach((m, i) => { const extra = results[i].recalls.filter(c => c.campaign_number && !known.has(c.campaign_number) && !seen.has(c.campaign_number)); @@ -437,9 +451,12 @@ export async function getRelatedModelRecalls(make, model, year, exactRecalls = [ * @param {string} make * @param {string} model * @param {number|string} year + * @param {{timeoutMs?: number}} [options] NHTSA can take 5-17 s to send a common model's list (1-2 MB); + * reports ask through modelYearComplaints (lib/reports.mjs) with COMPLAINTS_TIMEOUT_MS. * @returns {object} { count, complaints, summary } */ -export async function getComplaints(make, model, year) { +export const COMPLAINTS_TIMEOUT_MS = 30_000; +export async function getComplaints(make, model, year, { timeoutMs = FETCH_TIMEOUT } = {}) { try { const params = new URLSearchParams({ make: String(make), @@ -447,7 +464,7 @@ export async function getComplaints(make, model, year) { modelYear: String(year), }); const url = `${COMPLAINTS_BASE}?${params}`; - const res = await fetch(url, { signal: timeoutSignal() }); + const res = await fetch(url, { signal: timeoutSignal(timeoutMs) }); if (!res.ok) { console.error(`[nhtsa] getComplaints HTTP ${res.status}`); @@ -538,23 +555,22 @@ export async function getSafetyRatings(make, model, year) { return empty; } - // Step 2: Fetch details for each variant - const detailedVariants = []; - for (const variant of variants) { + // Step 2: Fetch details for each variant, three at a time (was one after another), kept in NHTSA's order + const details = await mapLimit(variants, 3, async variant => { const vehicleId = variant.VehicleId; - if (!vehicleId) continue; + if (!vehicleId) return null; try { const detailUrl = `${SAFETY_BASE}/VehicleId/${vehicleId}?format=json`; const detailRes = await fetch(detailUrl, { signal: timeoutSignal() }); - if (!detailRes.ok) continue; + if (!detailRes.ok) return null; const detailData = await detailRes.json(); const r = detailData?.Results?.[0]; - if (!r) continue; + if (!r) return null; - detailedVariants.push({ + return { vehicle_id: vehicleId, description: clean(r.VehicleDescription), overall: num(r.OverallRating), @@ -564,11 +580,13 @@ export async function getSafetyRatings(make, model, year) { side_passenger: num(r.SideCrashPassengersideRating), rollover: num(r.RolloverRating), side_pole: num(r.SidePoleCrashRating), - }); + }; } catch (innerErr) { console.error(`[nhtsa] getSafetyRatings detail error for ${vehicleId}:`, innerErr.message); + return null; } - } + }); + const detailedVariants = details.filter(Boolean); if (detailedVariants.length === 0) { return empty; diff --git a/lib/recall-status.mjs b/lib/recall-status.mjs index 2fd9271..c3e1b00 100644 --- a/lib/recall-status.mjs +++ b/lib/recall-status.mjs @@ -32,6 +32,37 @@ function documentUrl(value) { catch { return null; } } +const BY_WMI=[[TESLA_WMIS,'tesla'],[MOPAR_WMIS,'mopar'],[TOYOTA_WMIS,'toyota'],[FORD_WMIS,'ford'],[GM_WMIS,'gm'],[HONDA_WMIS,'honda'],[NISSAN_WMIS,'nissan'],[HYUNDAI_WMIS,'hyundai'],[KIA_WMIS,'kia'],[SUBARU_WMIS,'subaru'],[VW_WMIS,'vw'],[AUDI_WMIS,'audi'],[LAND_ROVER_WMIS,'landrover'],[JAGUAR_WMIS,'jaguar']]; +const BY_BRAND={TESLA:'tesla',CHRYSLER:'mopar',DODGE:'mopar',JEEP:'mopar',RAM:'mopar',FIAT:'mopar','ALFA ROMEO':'mopar',PLYMOUTH:'mopar',TOYOTA:'toyota',LEXUS:'toyota',SCION:'toyota',FORD:'ford',LINCOLN:'ford',MERCURY:'ford',CHEVROLET:'gm',BUICK:'gm',GMC:'gm',CADILLAC:'gm',PONTIAC:'gm',OLDSMOBILE:'gm',SATURN:'gm',HUMMER:'gm',SAAB:'gm',GEO:'gm',BRIGHTDROP:'gm',HONDA:'honda', + NISSAN:'nissan',HYUNDAI:'hyundai',KIA:'kia',ACURA:'honda',SUBARU:'subaru',VOLKSWAGEN:'vw',AUDI:'audi','LAND ROVER':'landrover',JAGUAR:'jaguar'}; +const OFFICIAL={nissan:NISSAN_LOOKUP,hyundai:HYUNDAI_LOOKUP,kia:KIA_LOOKUP,subaru:SUBARU_LOOKUP,vw:VW_LOOKUP,audi:AUDI_LOOKUP,landrover:LAND_ROVER_LOOKUP,jaguar:JAGUAR_LOOKUP}; +// Lookups that make a request to the maker (the others answer at once: interactive verification or not supported). +const NETWORK=new Set(['tesla','mopar','ford','gm','honda','nissan','subaru','vw','audi','landrover','jaguar']); +const MAKER={tesla:'Tesla',mopar:'Mopar',ford:'Ford',gm:'GM',honda:'Honda',nissan:'Nissan',subaru:'Subaru',vw:'Volkswagen',audi:'Audi',landrover:'Land Rover',jaguar:'Jaguar',toyota:'Toyota',hyundai:'Hyundai',kia:'Kia'}; +const PROVIDER_NAME={nissan:'Nissan U.S. VIN Recall Search',mopar:'Mopar Fleet Recall/Rapid Response Inquiry',tesla:'Tesla Service VIN Recall Search',ford:'Ford Owner Support VIN Recalls',gm:'GM Recall and Warranty Center',honda:'Honda MyGarage VIN Recall Search', + subaru:'Subaru U.S. VIN Recall Lookup',vw:'Volkswagen U.S. VIN Recall Lookup',audi:'Audi U.S. VIN Recall Lookup',landrover:'Land Rover U.S. Product Recall Search',jaguar:'Jaguar U.S. Product Recall Search'}; + +/** Which maker lookup serves a VIN: by its WMI first, else by the decoded make. No request is made. */ +function resolveProvider(vin,make=''){ + const brand=String(make||'').toUpperCase(); + const provider=BY_WMI.find(([set])=>set.has(vin.slice(0,3)))?.[1]||(Object.hasOwn(BY_BRAND,brand)?BY_BRAND[brand]:null); + const verification_url = provider==='tesla' ? `${LOOKUP}?VIN=${encodeURIComponent(vin)}` : provider==='mopar' ? MOPAR_LOOKUP : provider==='toyota' ? 'https://www.toyota.com/recall/' : provider==='ford'?FORD_LOOKUP+vin+'/':provider==='gm'?GM_LOOKUP+'?vin='+vin:provider==='honda'?HONDA_LOOKUP:'https://www.nhtsa.gov/recalls'; + return {provider,verification_url}; +} + +/** + * The maker lookup for a VIN without making it: `provider` (null when no maker is supported), `maker` (short name for + * "Checking with Ford…"), `name` (the lookup, as recall_status.source.provider names it), `verification_url` (as + * recall_status gives it), `network` (true when the lookup asks the maker; false when it answers at once) and + * `by_wmi` (the WMI alone names the maker, so the decoded make is not needed). + */ +export function recallLookupInfo(input,make=''){ + const vin=normalizeVin(input); + const {provider,verification_url}=resolveProvider(vin,make); + return {provider,maker:provider?MAKER[provider]:null,name:provider?PROVIDER_NAME[provider]??null:null,verification_url:OFFICIAL[provider]||verification_url, + network:NETWORK.has(provider),by_wmi:BY_WMI.some(([set])=>set.has(vin.slice(0,3)))}; +} + // The upstream returns an application error to Node fetch; its public endpoint // works with the standard HTTPS client. Bound response size and request duration. function manufacturerRequest(url, {signal,method='GET',headers={},body}) { @@ -67,14 +98,7 @@ export function createRecallStatusLookup(request=manufacturerRequest) { return async function vinRecallStatus(input, make = '') { const vin = normalizeVin(input); if (!validateVin(vin).valid) throw new InputError('Provide a valid 17-character VIN including checksum'); - const brand=String(make).toUpperCase(),wmi=vin.slice(0,3); - const byWmi=[[TESLA_WMIS,'tesla'],[MOPAR_WMIS,'mopar'],[TOYOTA_WMIS,'toyota'],[FORD_WMIS,'ford'],[GM_WMIS,'gm'],[HONDA_WMIS,'honda'],[NISSAN_WMIS,'nissan'],[HYUNDAI_WMIS,'hyundai'],[KIA_WMIS,'kia'],[SUBARU_WMIS,'subaru'],[VW_WMIS,'vw'],[AUDI_WMIS,'audi'],[LAND_ROVER_WMIS,'landrover'],[JAGUAR_WMIS,'jaguar']].find(([set])=>set.has(wmi))?.[1]; - const byBrand={TESLA:'tesla',CHRYSLER:'mopar',DODGE:'mopar',JEEP:'mopar',RAM:'mopar',FIAT:'mopar','ALFA ROMEO':'mopar',PLYMOUTH:'mopar',TOYOTA:'toyota',LEXUS:'toyota',SCION:'toyota',FORD:'ford',LINCOLN:'ford',MERCURY:'ford',CHEVROLET:'gm',BUICK:'gm',GMC:'gm',CADILLAC:'gm',PONTIAC:'gm',OLDSMOBILE:'gm',SATURN:'gm',HUMMER:'gm',SAAB:'gm',GEO:'gm',BRIGHTDROP:'gm',HONDA:'honda'}; - Object.assign(byBrand,{NISSAN:'nissan',HYUNDAI:'hyundai',KIA:'kia'}); - Object.assign(byBrand,{ACURA:'honda',SUBARU:'subaru',VOLKSWAGEN:'vw',AUDI:'audi','LAND ROVER':'landrover',JAGUAR:'jaguar'}); - const provider=byWmi||(Object.hasOwn(byBrand,brand)?byBrand[brand]:null); - const verification_url = provider==='tesla' ? `${LOOKUP}?VIN=${encodeURIComponent(vin)}` : provider==='mopar' ? MOPAR_LOOKUP : provider==='toyota' ? 'https://www.toyota.com/recall/' : provider==='ford'?FORD_LOOKUP+vin+'/':provider==='gm'?GM_LOOKUP+'?vin='+vin:provider==='honda'?HONDA_LOOKUP:'https://www.nhtsa.gov/recalls'; - const official={nissan:NISSAN_LOOKUP,hyundai:HYUNDAI_LOOKUP,kia:KIA_LOOKUP,subaru:SUBARU_LOOKUP,vw:VW_LOOKUP,audi:AUDI_LOOKUP,landrover:LAND_ROVER_LOOKUP,jaguar:JAGUAR_LOOKUP}; + const {provider,verification_url}=resolveProvider(vin,make),official=OFFICIAL; const added={subaru:{name:'Subaru U.S. VIN Recall Lookup',url:SUBARU_API+vin,parse:b=>parseSubaru(b,vin)},vw:{name:'Volkswagen U.S. VIN Recall Lookup',url:VW_API+vin,parse:b=>parseVw(b,vin)},audi:{name:'Audi U.S. VIN Recall Lookup',url:AUDI_API,options:()=>audiRequest(vin),parse:b=>parseAudi(b)},landrover:{name:'Land Rover U.S. Product Recall Search',url:LAND_ROVER_API+vin,parse:b=>parseLandRover(b,vin)},jaguar:{name:'Jaguar U.S. Product Recall Search',url:JAGUAR_API+vin,parse:b=>parseLandRover(b,vin,'Jaguar')}}[provider]; const base = {vin, scope:'vin', vin_specific:true, verification_url:official[provider]||verification_url, note}; if (provider==='toyota') return {...base,available:false,reason:'interactive_verification_required',open_count:null,completed_count:null,recalls:[], diff --git a/lib/reports.mjs b/lib/reports.mjs index 932bfa6..7d03ce1 100644 --- a/lib/reports.mjs +++ b/lib/reports.mjs @@ -1,10 +1,10 @@ /** Shared vehicle reports for REST, MCP and comparisons. */ import { validateVin, normalizeVin } from './validate.mjs'; -import { decodeVin as nhtsaDecode, getRecalls, getComplaints, getSafetyRatings, getRelatedModelRecalls } from './nhtsa.mjs'; +import { decodeVin as nhtsaDecode, getRecalls, getComplaints, getSafetyRatings, getRelatedModelRecalls, COMPLAINTS_TIMEOUT_MS } from './nhtsa.mjs'; import { getFuelEconomy } from './epa.mjs'; import { getPhotoUrls } from './photo.mjs'; -import { vinCache, recallCache, ratingCache, fuelCache } from './cache.mjs'; -import { vinRecallStatus } from './recall-status.mjs'; +import { vinCache, recallCache, ratingCache, fuelCache, complaintCache } from './cache.mjs'; +import { vinRecallStatus as defaultRecallLookup, recallLookupInfo } from './recall-status.mjs'; import { InputError } from './research.mjs'; import { withBuildDates } from './recall-build-dates.mjs'; import { extraReportBlocks, compactExtraBlocks } from './more-sources.mjs'; @@ -21,18 +21,56 @@ import { withManufacturerRecord, compactDecodeChecks } from './decode-report.mjs */ export async function modelYearRecalls(make, model, year) { const cacheKey = `${make}|${model}|${year}`; - const recalls = recallCache.has(cacheKey) ? recallCache.get(cacheKey) - : await getRecalls(make, model, year).then(r => { if (r?.available !== false) recallCache.set(cacheKey, r); return r; }); - if (!recalls || recalls.available === false || !make || !model || !year) return recalls; + const exact = recallCache.has(cacheKey) ? Promise.resolve(recallCache.get(cacheKey)) + : getRecalls(make, model, year).then(r => { if (r?.available !== false) recallCache.set(cacheKey, r); return r; }); + if (!make || !model || !year) return exact; const relatedKey = cacheKey + '|related'; - let related = recallCache.get(relatedKey); + // The related-name search starts beside the exact lookup: it needs the exact campaigns only before its per-name + // lookups (to skip them when the exact lookup failed) and to drop duplicates. It never rejects. + const cachedRelated = recallCache.get(relatedKey); + const relatedTask = cachedRelated ? null + : getRelatedModelRecalls(make, model, year, exact.then(r => (!r || r.available === false ? null : r.recalls))); + const recalls = await exact; + if (!recalls || recalls.available === false) return recalls; + let related = cachedRelated; if (!related) { - related = await getRelatedModelRecalls(make, model, year, recalls.recalls); + related = await relatedTask; if (related.available) recallCache.set(relatedKey, related); } return withBuildDates(withRelatedRecalls(recalls, related), make, model, year); } +/** + * NHTSA's owner complaints for a make, model and year: one request per model at a time, shared by every caller + * (reports, /api/vin/{vin}/complaints), and successful answers cached 6 hours. NHTSA can take 5-17 s to send a + * common model's list (1-2 MB of JSON; a 2020 Ford Escape took 17 s from the web server on 2026-11-18), so the + * request may run COMPLAINTS_TIMEOUT_MS (30 s); reports wait for it only up to their budget (fullReport). Never rejects. + */ +const complaintLookups = new Map(); +export function modelYearComplaints(make, model, year) { + const key = `${make}|${model}|${year}`; + if (complaintCache.has(key)) return Promise.resolve(complaintCache.get(key)); + if (complaintLookups.has(key)) return complaintLookups.get(key); + const lookup = Promise.resolve() + .then(() => getComplaints(make, model, year, { timeoutMs: COMPLAINTS_TIMEOUT_MS })) + .catch(err => { console.error('[reports] complaint lookup failed:', err?.message || err); return null; }) + .then(c => c || { available: false, count: null, complaints: [], summary: null, error: 'Complaint lookup unavailable' }) + .then(c => { if (c.available !== false) complaintCache.set(key, c); return c; }) + .finally(() => complaintLookups.delete(key)); + complaintLookups.set(key, lookup); + return lookup; +} + +/** + * complaints while NHTSA's list is still arriving: unknown, never zero (count null, available false), with where + * to get it. + */ +export function pendingComplaints(vin) { + return { available: false, pending: true, reason: 'lookup_in_progress', scope: 'make_model_year', count: null, complaints: [], summary: null, + status_url: `/api/vin/${vin}/complaints`, + note: 'NHTSA had not sent its owner-complaint list for this make, model and year when this report was sent (a common model\'s list is 1-2 MB and can take 15 s or more), so the count is unknown here; it is not zero. The request keeps running: GET status_url waits for it, and the next report includes it.' }; +} + /** Attach related-label campaigns without changing the exact-label count. */ export function withRelatedRecalls(recalls, related) { const flatOnly = related?.flat_file_only?.count || 0; @@ -53,32 +91,164 @@ export function withRelatedRecalls(recalls, related) { return { ...recalls, related_models: related, related_campaigns_found: found, count_note: parts.length ? parts.join(' ') : null }; } +/** + * How long a report waits for the manufacturer's VIN recall lookup, counted from the moment the lookup starts (right + * after the decode, beside NHTSA's calls). Some makers' lookups are slow: Ford's CDN holds every request ~9-10 s + * (measured 2026-11-18, research notes fast-first-report-2026-11-18). Past the wait the report goes out with + * recall_status {pending: true} and the lookup keeps running; its result is cached (lib/recall-status.mjs, 15 minutes) + * for the next request, GET /api/vin/{vin}/recall-status and MCP vin_recall_status, which wait for the same lookup. + * report: the website and REST /api/vin/{vin}; mcp: MCP decode_vin (agents rarely come back for a second call). + * `recallWaitMs: Infinity` waits for the lookup's own end (REST ?recall_wait=full, MCP recall_wait "full"). + */ +export const RECALL_WAIT_MS = Object.freeze({ report: 2000, mcp: 6000 }); + +let recallLookup = defaultRecallLookup; +/** + * Tests and scripts: the recall-status lookup reports use, e.g. createRecallStatusLookup(stubRequest), so no live + * maker request is made. Returns the previous one; no argument restores the default. + */ +export function useRecallStatusLookup(lookup) { + const previous = recallLookup; + recallLookup = lookup || defaultRecallLookup; + return previous; +} + +/** + * The manufacturer's VIN recall status for a VIN (REST /api/vin/{vin}/recall-status, MCP vin_recall_status). When + * the WMI alone does not name the maker, the decoded make does (the cached report's, else a decode), as in reports, + * so this joins a lookup a report started. Throws InputError for an invalid VIN. + */ +export async function vinRecallStatusFor(input) { + const vin = normalizeVin(input); + if (!validateVin(vin).valid) return recallLookup(vin); // the lookup's own InputError + let make = ''; + if (!recallLookupInfo(vin).by_wmi) { + make = vinCache.get(vin)?.vehicle?.make || ''; + if (!make) { try { make = (await nhtsaDecode(vin))?.vehicle?.make || ''; } catch { make = ''; } } + } + return recallLookup(vin, make); +} + +/** + * Start (or join) the maker's lookup. The returned promise never rejects, so a lookup that outlives the report and + * then fails is contained (no unhandled rejection): a failure becomes recall status unknown, never "no recalls". + */ +function startRecallLookup(vin, make) { + const at = Date.now(); + let promise; + try { promise = Promise.resolve(recallLookup(vin, make)); } catch (err) { promise = Promise.reject(err); } + promise = promise.catch(err => { + console.error('[reports] manufacturer recall lookup failed:', err?.message || err); + const info = recallLookupInfo(vin, make); + return { vin, scope: 'vin', vin_specific: true, verification_url: info.verification_url, available: false, reason: 'upstream_unavailable', + open_count: null, completed_count: null, recalls: [], note: 'The manufacturer recall lookup failed. Repair status for this VIN is unknown. Check the official source.' }; + }); + return { at, promise }; +} + +const WAITED = Symbol('waited'); +/** The promise's value if it settles within `ms`, else WAITED. Infinity waits for it. */ +function within(promise, ms) { + if (ms === Infinity) return promise; + let timer; + const timeout = new Promise(resolve => { timer = setTimeout(resolve, Math.max(0, ms), WAITED); }); + return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)); +} + +/** + * recall_status while the maker's lookup is still running: unknown, never "no open recalls" (open_count and + * completed_count null, available false), with where to get the answer. + */ +export function pendingRecallStatus(vin, make, waitedMs) { + const info = recallLookupInfo(vin, make), maker = info.maker || 'The manufacturer'; + return { vin, scope: 'vin', vin_specific: true, verification_url: info.verification_url, + available: false, pending: true, reason: 'lookup_in_progress', maker: info.maker, waited_ms: waitedMs, + source: { provider: info.name, reference_url: info.verification_url }, + open_count: null, completed_count: null, recalls: [], + status_url: `/api/vin/${vin}/recall-status`, + note: `${maker}'s VIN recall lookup had not answered after ${(waitedMs / 1000).toFixed(1)} s, so this VIN's repair status is unknown in this response; it is not "no open recalls". The lookup keeps running: GET status_url waits for it, and this report includes it once it has answered (add ?recall_wait=full to wait for it).` }; +} + +/** The decode checks while the maker's record is still loading (the base report's checks, record marked pending). */ +function pendingDecodeChecks(dc, maker) { + if (!dc?.sources) return dc; + return { ...dc, sources: { ...dc.sources, manufacturer_record: { status: 'pending', reason: 'lookup_in_progress', maker: maker || null, + note: 'The manufacturer\'s record of this VIN comes from its recall lookup, which had not answered when this report was sent; the checks ran without it.' } } }; +} + +// The report with a given recall status, computed once per base report, status result and owner values: the +// lookup caches its result object for 15 minutes, so repeated requests reuse the decode checks and any re-match. +const withStatusMemo = new WeakMap(); +function reportWithStatus(base, status, owner) { + const ownerKey = JSON.stringify(owner ?? null), hit = withStatusMemo.get(base); + if (hit && hit.status === status && hit.ownerKey === ownerKey) return hit.report; + const report = withManufacturerRecord({ ...base, recall_status: status }, { owner }); + withStatusMemo.set(base, { status, ownerKey, report }); + return report; +} + /** * The report with the manufacturer's VIN recall status. The decode checks then run again with the manufacturer's * own description of the VIN when its reply carries one (lib/decode-report.mjs). `owner`: values the reader states - * about their own vehicle ({transmission: 'manual'}), the top tier of the decode checks. + * about their own vehicle ({transmission: 'manual'}), the top tier of the decode checks. `recallWaitMs`: see + * RECALL_WAIT_MS; past it, recall_status is {pending: true} (pendingRecallStatus) and the lookup finishes in the + * background. */ -export async function fullReport(vin, {owner = null} = {}) { - const report = await fullReportBase(vin); - if (!report.vehicle) return report; - return withManufacturerRecord({...report, recall_status: await vinRecallStatus(report.vin, report.vehicle.make)}, {owner}); +export async function fullReport(vin, {owner = null, recallWaitMs = RECALL_WAIT_MS.report, complaintsWaitMs = RECALL_WAIT_MS.report} = {}) { + const entry = reportEntry(vin); + // The maker's lookup starts as soon as the decode names the make, in parallel with NHTSA's calls. + const early = entry.decoded.then(d => d?.vehicle ? { make: d.vehicle.make, ...startRecallLookup(entry.vin, d.vehicle.make) } : null); + const base = await entry.report; + if (!base.vehicle) return base; + let lookup = await early; + if (!lookup || lookup.make !== base.vehicle.make) lookup = { make: base.vehicle.make, ...startRecallLookup(base.vin, base.vehicle.make) }; + const status = await within(lookup.promise, lookup.at + recallWaitMs - Date.now()); + // Both waits run against deadlines counted from each request's start, so waiting for one after the other takes + // as long as the later deadline; complaints that arrived while the recall status was awaited are included. + const report = await withComplaints(base, complaintsWaitMs); + if (status === WAITED) { + const pending = pendingRecallStatus(report.vin, report.vehicle.make, recallWaitMs); + return { ...report, recall_status: pending, decode_checks: pendingDecodeChecks(report.decode_checks, pending.maker) }; + } + return reportWithStatus(report, status, owner); +} + +// A report assembled before NHTSA's complaints arrived (complaints pending) → {at, promise}: the request's start +// and the complete report it becomes (the same object for every caller; null if it could not be built). +const completions = new WeakMap(); +/** `report` with NHTSA's complaints if they arrive within `ms` of their request's start; else as given (pending). */ +async function withComplaints(report, ms) { + const completion = completions.get(report); + if (!completion) return report; + const complete = await within(completion.promise, completion.at + ms - Date.now()); + return complete === WAITED || !complete ? report : complete; } const pendingReports = new Map(); -/** The report without manufacturer VIN recall lookups; shares the cache with fullReport. */ -export function baseReport(vin) { return fullReportBase(vin); } -function fullReportBase(vin) { +/** + * The report without manufacturer VIN recall lookups; shares the cache with fullReport. It does not wait for NHTSA's + * complaints: when they had not arrived with the rest, `complaints` is pending (pendingComplaints). + */ +export function baseReport(vin) { return reportEntry(vin).report; } +/** + * One assembly per VIN at a time, shared by concurrent callers: `report`, and `decoded`, which resolves with + * {vehicle} as soon as the decode (or the cache) names the vehicle, or null when there is none. + */ +function reportEntry(vin) { const key = normalizeVin(vin); if (pendingReports.has(key)) return pendingReports.get(key); - const pending = assembleReport(key).finally(() => pendingReports.delete(key)); - pendingReports.set(key, pending); - return pending; + let named; + const decoded = new Promise(resolve => { named = resolve; }); + const report = assembleReport(key, named).finally(() => { named(null); pendingReports.delete(key); }); + const entry = { vin: key, report, decoded }; + pendingReports.set(key, entry); + return entry; } -async function assembleReport(vin) { +async function assembleReport(vin, named = () => {}) { vin = normalizeVin(vin); const cached = vinCache.get(vin); - if (cached) return cached; + if (cached) { named(cached.vehicle ? { vehicle: cached.vehicle } : null); return cached; } const validation = validateVin(vin); if (!validation.valid) { @@ -89,6 +259,7 @@ async function assembleReport(vin) { if (!decoded) { return { valid: true, vin, validation, vehicle: null, engine: null, error: 'NHTSA decode failed', recalls: null, complaints: null, safety_ratings: null, fuel_economy: null, photos: null }; } + named({ vehicle: decoded.vehicle }); const { year, make, model } = decoded.vehicle; const cacheKey = `${make}|${model}|${year}`; @@ -98,9 +269,11 @@ async function assembleReport(vin) { const raw = used.raw || {}; const fuelKey = `${cacheKey}|${JSON.stringify([used.engine, used.transmission, used.vehicle, used.dimensions?.gvwr, raw.Series, raw.Series2, raw.Trim2, raw.Doors, raw.BatteryKWh, raw.BatteryKWh_to, raw.FuelTypeSecondary])}`; - const [recalls, complaints, ratings, fuel, testVehicle] = await Promise.all([ + // NHTSA's complaints can take much longer than the rest (modelYearComplaints): the report is assembled without + // waiting for them, and completes when they arrive (completions). + const complaintsAt = Date.now(), complaintsTask = modelYearComplaints(make, model, year); + const [recalls, ratings, fuel, testVehicle] = await Promise.all([ modelYearRecalls(make, model, year), - getComplaints(make, model, year), ratingCache.has(cacheKey) ? ratingCache.get(cacheKey) : getSafetyRatings(make, model, year).then(r => { if (r) ratingCache.set(cacheKey, r); return r; }), fuelCache.has(fuelKey) ? fuelCache.get(fuelKey) : getFuelEconomy(year, make, model, used).then(r => { if (r?.available || (r?.match === 'multiple_configurations' && !r.incomplete)) fuelCache.set(fuelKey, r); return r; }), // Local index of NHTSA's crash-test vehicles: closest match, never this VIN's own values (lib/tire-placards.mjs). @@ -116,7 +289,7 @@ async function assembleReport(vin) { vehicle: decoded.vehicle, engine: decoded.engine, transmission: decoded.transmission, dimensions: decoded.dimensions, plant: decoded.plant, safety_equipment: decoded.safety, recalls: recallBlock || { count: 0, recalls: [] }, - complaints: complaints || { count: 0, complaints: [], summary: { crashes: 0, fires: 0, injuries: 0, deaths: 0 } }, + complaints: null, // set below (complete) or pending safety_ratings: ratings || { rated: false }, fuel_economy: fuel || { available: false }, tire_placard: testVehicle.tire_placard, @@ -132,8 +305,18 @@ async function assembleReport(vin) { }; const transientFuelFailure = ['upstream_error', 'invalid_response'].includes(fuel?.reason) || fuel?.incomplete === true; - if (recalls?.available !== false && complaints?.available !== false && !transientFuelFailure) vinCache.set(vin, report); - return report; + const complete = complaints => { + const done = { ...report, complaints: complaints || { count: 0, complaints: [], summary: { crashes: 0, fires: 0, injuries: 0, deaths: 0 } } }; + if (recalls?.available !== false && complaints?.available !== false && !transientFuelFailure) vinCache.set(vin, done); + return done; + }; + const arrived = await within(complaintsTask, 0); + if (arrived !== WAITED) return complete(arrived); + // Still arriving: a report with complaints pending now; the complete one is built (and cached) when they arrive. + const partial = { ...report, complaints: pendingComplaints(vin) }; + completions.set(partial, { at: complaintsAt, promise: complaintsTask.then(complete).catch(err => { + console.error('[reports] completing report with complaints failed:', err?.message || err); return null; }) }); + return partial; } /** Where the specifications came from: the local decoder (vPIC release, rule fixes) or NHTSA's live API. */ @@ -178,6 +361,8 @@ function compactComplaints(complaints) { ...c, summary: c.summary && c.summary.length > MCP_SUMMARY_CHARS ? c.summary.slice(0, MCP_SUMMARY_CHARS) + '...' : c.summary, })); + if (complaints?.pending) return { ...complaints, complaints: undefined, recent: [], top_components: [], + note: 'NHTSA had not sent its owner-complaint list for this make, model and year in time (a common model\'s list can take 15 s or more), so the count is unknown here, not zero. The request keeps running; call decode_vin again in a minute for the list (cached once it arrives).' }; return { ...complaints, complaints: undefined, @@ -215,7 +400,15 @@ export function restReport(report, { allComplaints = false } = {}) { export function mcpReport(report) { if (!report?.vehicle) return report; const { raw_nhtsa, ...rest } = report; - return { ...rest, ...compactExtraBlocks(rest), complaints: compactComplaints(report.complaints), ...(rest.decode_checks ? { decode_checks: compactDecodeChecks(rest.decode_checks) } : {}) }; + return { ...rest, ...compactExtraBlocks(rest), complaints: compactComplaints(report.complaints), ...(rest.decode_checks ? { decode_checks: compactDecodeChecks(rest.decode_checks) } : {}), + ...(rest.recall_status?.pending ? { recall_status: mcpPendingStatus(rest.recall_status) } : {}) }; +} + +/** The pending recall status for MCP clients: the next step is a tool call, not a URL. */ +function mcpPendingStatus(s) { + const maker = s.maker || 'The manufacturer'; + return { ...s, next_step: { tool: 'vin_recall_status', arguments: { vin: s.vin } }, + note: `${maker}'s VIN recall lookup had not answered after ${((s.waited_ms || 0) / 1000).toFixed(1)} s, so this VIN's repair status is unknown in this result; it is not "no open recalls". For the complete answer call vin_recall_status with this VIN (it waits for the same lookup), or call decode_vin again with recall_wait "full".` }; } export async function compareVehicles(vins) { @@ -223,7 +416,8 @@ export async function compareVehicles(vins) { const normalized=vins.map(normalizeVin); if (new Set(normalized).size !== normalized.length) throw new InputError('Choose distinct VINs'); const results=await Promise.all(normalized.map(async vin=>{ - try {return {vin,report:mcpReport(await fullReport(vin))};} + // A comparison waits for every maker's lookup (no pending status): it is printed and exported as one table. + try {return {vin,report:mcpReport(await fullReport(vin,{recallWaitMs:Infinity,complaintsWaitMs:Infinity}))};} catch {return {vin,error:'Report unavailable; retry later'};} })); return {results,note:'Recall and complaint counts are model-year data, not a ranking of individual vehicle safety. Missing data is not zero.'}; diff --git a/lib/tire-placards.mjs b/lib/tire-placards.mjs index bb62c7f..533335c 100644 --- a/lib/tire-placards.mjs +++ b/lib/tire-placards.mjs @@ -387,11 +387,13 @@ async function lookup(vin, {file = TIRE_PLACARDS_FILE, dims = transportCanadaDim const generations = new Map(); if (needs(placards, rules.tires) || needs(specsPool, rules.specs) || needs(specsPool, rules.tank)) { const years = [...new Set([...placards, ...specsPool].filter(r => r.year !== year && inReach(r)).map(r => r.year))]; - const vinWb = await wheelbases(vin.make, vin.model, year, dims); - await Promise.all(years.map(async y => { + // The VIN's year and the tested years are asked at once (was the VIN's year first): one round trip instead of two. + // A tested year's record is used only when the VIN's year has one; wheelbases() never rejects. + const [vinWb, ...testedWb] = await Promise.all([year, ...years].map(y => wheelbases(vin.make, vin.model, y, dims))); + years.forEach((y, i) => { const measured = (data.specs || []).filter(r => r.year === y && r.data.wheelbase_mm).map(r => r.data.wheelbase_mm); - generations.set(y, compareWheelbases(vinWb, vinWb?.length ? await wheelbases(vin.make, vin.model, y, dims) : null, measured)); - })); + generations.set(y, compareWheelbases(vinWb, vinWb?.length ? testedWb[i] : null, measured)); + }); } const source = {provider: 'NHTSA vehicle crash-test and compliance test reports', indexed_at: data.source.indexed_at ?? null, dataset_generated_at: data.source.dataset_generated_at ?? null}; diff --git a/public/app.js b/public/app.js index 4bd2f39..42abfb5 100644 --- a/public/app.js +++ b/public/app.js @@ -106,7 +106,8 @@ form.addEventListener('submit', async (e) => { // Compact hero hero.classList.add('compact'); results.hidden = false; - $('#decode-status').textContent = 'Report ready. Review source coverage in each section.'; + $('#decode-status').textContent = readyMessage(report); + followPending(report); if (!location.hash || location.hash === '#report') { history.replaceState(null, '', '/' + encodeURIComponent(vin) + location.search + '#report'); results.scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth', block: 'start' }); @@ -326,7 +327,7 @@ function renderFuel(r) { function rerenderOwnerView(focusChoice) { if (!currentReport) return; const view = window.OwnerDetails?.applyToReport(currentReport) || currentReport; - renderFuel(view); window.CarSheet?.render(view); window.VinWorkspace?.reportUpdated(view); + renderFuel(view); window.CarSheet?.update ? CarSheet.update(view) : window.CarSheet?.render(view); window.VinWorkspace?.reportUpdated(view); if (focusChoice) $('#fuel-body [data-owner-transmission]')?.focus(); } $('#fuel-body').addEventListener('click', async e => { @@ -381,19 +382,132 @@ function renderFuelBody(r) { } // ── Recalls Card ── +// The VIN-specific status is its own block (#recall-status-block), so it can be filled in alone when the maker's +// lookup answers after the report is drawn (followRecallStatus). function renderRecalls(r) { renderCampaigns(r); + $('#recalls-body').innerHTML = `
${esc(x.record_kind.replaceAll('_',' '))}
` : ''}${esc(x.summary || x.title || '')}
${x.completion_description ? `Completion basis: ${esc(x.completion_description)}
` : ''}${x.repair_completed_at ? `Reported repair date: ${esc(x.repair_completed_at)}
` : ''}${x.manufacturer_closed_at ? `Manufacturer closing date: ${esc(x.manufacturer_closed_at)}
` : ''}${x.remedy ? `Remedy: ${esc(x.remedy)}
` : ''}${x.document_url ? `Manufacturer bulletin` : ''}Checking with ${maker}… Its VIN lookup is still answering; this part fills in by itself.
Not loaded: ${maker} had not answered when this page was printed, so this VIN’s repair status is unknown here.
` + : s?.available ? `${s.open_record_count!==undefined ? esc(s.open_record_count)+' open recall/campaign records · '+esc(s.open_count ?? 'Unknown')+' verified safety-recall count' : esc(s.open_count ?? 'Unknown')+' open recalls'} · ${esc(s.completed_count ?? 'Unknown')} manufacturer-reported completed/closed${s.unknown_count ? ' · '+esc(s.unknown_count)+' unknown status' : ''}
Checked ${esc(s.source.retrieved_at)} · ${esc(s.source.provider)}
${renderStatusRecords(s.campaigns || s.recalls)} ${!s.campaigns && s.service_campaigns?.length ? `${esc(s.note)}
` : `VIN-specific repair status is unavailable. ${esc(s?.note || 'Check the official source. Model-year campaigns do not establish completed repairs.')}
`; - $('#recalls-body').innerHTML = `Verify this VIN with the official source
`; +} + +// ── Parts that arrive after the report ── +// The server does not hold a report back for its two slow sources (lib/reports.mjs): the maker's VIN recall status +// (recall_status.pending) and NHTSA's complaint list (complaints.pending). The page asks for each again and fills it +// in place. +function readyMessage(report) { + const later = []; + if (report.recall_status?.pending) later.push(`${report.recall_status.maker || 'The manufacturer'}’s VIN recall status`); + if (report.complaints?.pending) later.push('NHTSA’s complaint list'); + if (!later.length) return 'Report ready. Review source coverage in each section.'; + return later.length > 1 ? `Report ready. ${later.join(' and ')} are still loading; they fill in by themselves.` : `Report ready. ${later[0]} is still loading; it fills in by itself.`; +} +function followPending(report) { + if (report.recall_status?.pending) followRecallStatus(report); + if (report.complaints?.pending) followComplaints(report); +} +// Fetch `url` as JSON until `done(data)` accepts it, at most twice (3 s apart), while `live()` holds; null if not. +async function fetchFollowUp(url, done, live) { + for (let attempt = 0; attempt < 2; attempt++) { + if (attempt) await new Promise(resolve => setTimeout(resolve, 3000)); + if (!live()) return null; + try { + const res = await apiFetch(url); + const data = res.ok ? await res.json() : null; + if (done(data)) return data; + } catch { /* tried again once, then shown as not loaded */ } + } + return null; +} + +// NHTSA's complaint list: /api/vin/{vin}/complaints joins the request the report started (cached once it arrives). +let complaintsFollow = 0; +async function followComplaints(report) { + const token = ++complaintsFollow, vin = report.vin; + const live = () => token === complaintsFollow && currentReport?.vin === vin && currentReport.complaints?.pending === true; + let next = await fetchFollowUp(`/api/vin/${encodeURIComponent(vin)}/complaints`, data => data && typeof data.available === 'boolean' && !data.pending, live); + if (!live()) return; + if (!next) next = {...currentReport.complaints, pending: false, available: false, reason: 'lookup_not_loaded', + note: 'NHTSA’s complaint list could not be loaded here. The count is unknown; reload the report.'}; + currentReport = {...currentReport, complaints: next}; + const view = window.OwnerDetails?.applyToReport(currentReport) || currentReport; + const around = window.KeepState ? KeepState.around : (roots, fn) => fn(); + around([$('#complaints-body')], () => { + renderComplaints(view); + window.CarSheet?.update ? CarSheet.update(view) : window.CarSheet?.render(view); + window.VinWorkspace?.reportUpdated(view); + // inside the redraw: a shorter status line moves the page too + $('#decode-status').textContent = next.available ? 'NHTSA’s owner complaints have loaded.' : 'NHTSA’s owner complaints could not be loaded; see the complaints section.'; + }, [$('#sheet-body'), $('#sheet-foot')]); +} + +// ── The maker's VIN recall status, when it answers after the report ── +// A report can arrive with recall_status.pending (lib/reports.mjs: the maker's lookup was still answering). The page +// asks again with ?recall_wait=full, which waits for that same lookup, and fills in only what it changes: the status +// block, the car sheet's recall row and footer, and, when the maker's description of the VIN changed the decode checks +// or the fuel and tire matches, those blocks. Typed text, open forms, focus, the transmission choice and the place on +// screen are kept (public/keep-state.js). +const MAKER_BLOCKS = ['recall_status', 'decode_checks', 'fuel_economy', 'tire_placard', 'test_vehicle_specs', 'epa_test_vehicles', 'parts_content', 'production_theft']; +let recallFollow = 0; +async function followRecallStatus(report) { + // Still wanted while this VIN's report is shown with the status pending (typing the same VIN again keeps it). + const token = ++recallFollow, vin = report.vin; + const live = () => token === recallFollow && currentReport?.vin === vin && currentReport.recall_status?.pending === true; + let next = await fetchFollowUp(`/api/vin/${encodeURIComponent(vin)}?recall_wait=full`, data => data?.vehicle && data.recall_status && !data.recall_status.pending, live); + if (!live()) return; + if (!next) { + const s = currentReport.recall_status || {}; + next = {...currentReport, recall_status: {...s, pending: false, available: false, reason: 'lookup_not_loaded', + note: `${s.maker || 'The manufacturer'}’s answer could not be loaded. VIN-specific repair status is unknown; reload the report or check the official source.`}}; + } + applyMakerUpdate(next); +} + +function applyMakerUpdate(next) { + const prev = currentReport; + if (!prev || prev.vin !== next.vin) return; + const same = (a, b) => JSON.stringify(a) === JSON.stringify(b); + const merged = {...prev}; + for (const k of MAKER_BLOCKS) { if (k in next) merged[k] = next[k]; else delete merged[k]; } + // The maker's record only changes the "checked against" line, unless it changed a checked value (then the + // fuel-economy, tire and test-car matches may have changed too). + const checks = dc => dc && dc.sources ? {...dc, sources: {...dc.sources, manufacturer_record: null}} : dc; + const valuesChanged = !same(checks(prev.decode_checks), checks(next.decode_checks)) || MAKER_BLOCKS.slice(2).some(k => !same(prev[k], next[k])); + currentReport = merged; + const view = window.OwnerDetails?.applyToReport(merged) || merged; + const statusBlock = $('#recall-status-block'); + const cards = valuesChanged ? ['#overview-body', '#engine-body', '#decode-checks-body', '#safety-ratings-body', '#fuel-body'].map(id => $(id)) : []; + const around = window.KeepState ? KeepState.around : (roots, fn) => fn(); + around([statusBlock, ...cards], () => { + if (statusBlock) statusBlock.innerHTML = recallStatusHtml(view); + if (valuesChanged) { + renderOverview(view); renderEngine(view); renderDecodeChecks(view); renderSafetyRatings(view); + window.TestVehicle?.render(view); renderFuel(view); window.MoreSources?.render(view); + } else if (!same(prev.decode_checks, next.decode_checks)) { + const line = $('#decode-checks-body .dc-sources'); + if (line && window.DecodeChecks?.sourcesHtml) line.outerHTML = DecodeChecks.sourcesHtml(view); + } + window.CarSheet?.update ? CarSheet.update(view) : window.CarSheet?.render(view); + window.VinWorkspace?.reportUpdated(view); + // inside the redraw: a shorter status line moves the page too + const s = merged.recall_status || {}, maker = prev.recall_status?.maker || s.maker || 'The manufacturer'; + $('#decode-status').textContent = s.available ? `${maker}’s VIN recall status has loaded.` : `${maker}’s VIN recall status is not available; see the recall section.`; + }, [$('#sheet-body'), $('#sheet-foot')]); } function renderCampaigns(r) { @@ -492,10 +606,19 @@ function renderComplaints(r) { const count = c?.count || 0; const badge = $('#complaint-count'); + if (c?.pending) { + // Still arriving (followComplaints fills it in): unknown, never zero; on paper it was not loaded. + badge.textContent = '…'; + badge.className = 'count-badge'; + $('#complaints-body').innerHTML = 'Loading NHTSA’s owner complaints… The list for a common model is large and can take 15 seconds or more; this card fills in by itself.
Not loaded: NHTSA’s complaint list had not arrived when this page was printed.
Sources: ${esc(sources.join('; '))}.${assembled ? ` Data gathered ${esc(assembled)}.` : ''}
Decoded from the VIN and public records; options, repairs and later changes are not shown. Check the placard, the manual and the official recall links.
Live report: ${url}${dagger}
Transport Canada model data, ${esc(which)}. Not specific to this VIN.
`; } - let current = null; + // current: the report drawn; drawn: its sections and footer as drawn, so update() can swap only what changed; + // dimsToken: the Transport Canada request in flight belongs to the vehicle drawn last by render(). + let current = null, drawn = null, dimsToken = 0; async function loadDimensions(r) { - const target = typeof document !== 'undefined' && document.querySelector('#sheet-body [data-dims]'); + const token = ++dimsToken; + const dimsTarget = () => typeof document !== 'undefined' && document.querySelector('#sheet-body [data-dims]'); + const target = dimsTarget(); const v = r.vehicle || {}; if (!target || !present(v.year) || !present(v.make) || !present(v.model)) { if (target) target.innerHTML = ''; return; } const ask = async model => { @@ -565,10 +584,11 @@ const CarSheet = (() => { // vPIC and Transport Canada name some models differently ("Bolt EV" / "BOLT 4DR HATCHBACK"). // Retry with the first word only; the matched record names are printed so the reader can judge. if (data.available && !data.data.length && /\s/.test(String(v.model).trim())) data = await ask(String(v.model).trim().split(/\s+/)[0]); - if (current !== r) return; - target.innerHTML = data.available ? dimensionsHtml(dimensionSummary(data.data), r) : 'Transport Canada dimensions are unavailable right now.
'; + // update() may have swapped the size section meanwhile: write into the one on the page now + if (token !== dimsToken || !dimsTarget()) return; + dimsTarget().innerHTML = data.available ? dimensionsHtml(dimensionSummary(data.data), current || r) : 'Transport Canada dimensions are unavailable right now.
'; } catch { - if (current === r) target.innerHTML = 'Transport Canada dimensions are unavailable right now.
'; + if (token === dimsToken && dimsTarget()) dimsTarget().innerHTML = 'Transport Canada dimensions are unavailable right now.
'; } } @@ -581,11 +601,38 @@ const CarSheet = (() => { if (title) title.textContent = [v.year, makeName(v.make), v.model, v.trim].filter(present).join(' '); body.innerHTML = out.body; if (foot) foot.innerHTML = out.foot; + drawn = { vin: r.vin, sections: sections(r), foot: out.foot }; const assembled = fmtDate(r.provenance && r.provenance.assembled_at), prepared = document.querySelector('#sheet-prepared'); if (prepared) prepared.textContent = assembled ? `Data gathered ${assembled} from public NHTSA, EPA, Transport Canada and maker records.` : 'From public NHTSA, EPA, Transport Canada and maker records.'; loadDimensions(r); } + /** + * Redraw only the sections of the drawn sheet whose HTML changed for `r` (the same vehicle, e.g. once the maker's + * recall status arrives or the owner states the transmission). Copied-in values, open forms, focus and the Transport + * Canada dimensions already loaded are kept (public/keep-state.js). Falls back to render() for another vehicle. + */ + function update(r) { + const body = typeof document !== 'undefined' && document.querySelector('#sheet-body'), foot = document.querySelector('#sheet-foot'); + if (!body || !r || !r.vehicle) return; + if (!drawn || drawn.vin !== r.vin || typeof KeepState === 'undefined') { render(r); return; } + const next = sections(r); + for (const [i, [name, h]] of next.entries()) { + if (h === drawn.sections[i][1]) continue; + const old = drawn.sections[i][1] ? body.querySelector(`:scope > .${name}`) : null; + if (!old || !h) { render(r); return; } // a section appeared or went away: draw the sheet again + const dims = old.querySelector('[data-dims]'); + const swapped = KeepState.replace(old, h); + if (!swapped) { render(r); return; } + const newDims = swapped.querySelector('[data-dims]'); + if (dims && newDims) newDims.replaceWith(dims); // vehicle dimensions do not depend on what changed + } + const f = footer(r); + if (foot && f !== drawn.foot) foot.innerHTML = f; + drawn = { vin: r.vin, sections: next, foot: f }; + current = r; + } + // "Print this sheet" prints one page; the toolbar's "Print view" prints the sheet followed by the full report. if (typeof document !== 'undefined' && document.addEventListener) { const root = document.documentElement; @@ -632,6 +679,6 @@ const CarSheet = (() => { }); } - return { manualFor, html, dimensionSummary, dimensionsHtml, fmtDate, render, testedPlacards, testedSpecs, matchText }; + return { manualFor, html, dimensionSummary, dimensionsHtml, fmtDate, render, update, testedPlacards, testedSpecs, matchText }; })(); if (typeof window !== 'undefined') window.CarSheet = CarSheet; diff --git a/public/client.mjs b/public/client.mjs index ffe423c..1552285 100644 --- a/public/client.mjs +++ b/public/client.mjs @@ -1,7 +1,8 @@ export class VinClient { constructor({baseUrl='http://127.0.0.1:3200',fetchImpl=globalThis.fetch,timeout=45000}={}){this.baseUrl=baseUrl.replace(/\/$/,'');this.fetch=(...args)=>fetchImpl(...args);this.timeout=timeout;} async request(path,body){const r=await this.fetch(this.baseUrl+path,{cache:'no-store',method:body===undefined?'GET':'POST',headers:body===undefined?{}:{'Content-Type':'application/json'},...(body===undefined?{}:{body:JSON.stringify(body)}),signal:AbortSignal.timeout(this.timeout)});const data=await r.json();if(!r.ok){const e=new Error(data.error||data.reason||`HTTP ${r.status}`);e.status=r.status;e.data=data;throw e;}return data;} - decode(vin){return this.request('/api/vin/'+encodeURIComponent(vin));} + // recallWait 'full': wait for the maker's VIN recall lookup instead of getting recall_status.pending after 2 s. + decode(vin,{recallWait}={}){return this.request('/api/vin/'+encodeURIComponent(vin)+(recallWait?'?recall_wait='+encodeURIComponent(recallWait):''));} recallStatus(vin){return this.request('/api/vin/'+encodeURIComponent(vin)+'/recall-status');} validate(vin){return this.request('/api/vin/'+encodeURIComponent(vin)+'/validate');} batch(vins){return this.request('/api/batch',{vins});} diff --git a/public/decode-checks.js b/public/decode-checks.js index 5bdc0f9..72b8028 100644 --- a/public/decode-checks.js +++ b/public/decode-checks.js @@ -104,15 +104,26 @@ const DecodeChecks = (() => { return `Checked against ${used}. ${esc(dc.note || '')}
${formHtml(r)}`; + return `Checked against ${used}. ${esc(dc.note || '')}
`; } /** "Report a decode error": screen only, for review, never applied. */ @@ -156,6 +167,6 @@ const DecodeChecks = (() => { }); } - return { check, marker, shown, valueHtml, checkedValue, combinedHtml, cardHtml, formHtml, fields }; + return { check, marker, shown, valueHtml, checkedValue, combinedHtml, cardHtml, sourcesHtml, formHtml, fields }; })(); if (typeof window !== 'undefined') window.DecodeChecks = DecodeChecks; diff --git a/public/index.html b/public/index.html index 6d5abd1..01818a4 100644 --- a/public/index.html +++ b/public/index.html @@ -95,7 +95,7 @@ } - + @@ -333,14 +333,14 @@Generated from the server’s registered tools; the same list is served as JSON at /api/tools. Public research is available without an account; saved vehicles and preferences require authentication.
decode_vin (vin, transmission)Decode a VIN and return a vehicle report: specs, recalls (with manufacturer build-date ranges), a complaint summary with the most recent complaints, safety ratings, fuel economy, EPA test-vehicle data, parts content and origin (MY2020+), historical production and theft (MY1998-2012), and photo URLs. decode_checks checks the official decode field by field (drive, engine, electrification, transmission, speeds, seats, GVWR) against the manufacturer's description of this VIN, NHTSA test vehicles with the same VIN pattern and EPA's configurations: confirmed, corrected, doubtful or filled, with vPIC's original value kept.
decode_vin (vin, transmission, recall_wait)Decode a VIN and return a vehicle report: specs, recalls (with manufacturer build-date ranges), a complaint summary with the most recent complaints, safety ratings, fuel economy, EPA test-vehicle data, parts content and origin (MY2020+), historical production and theft (MY1998-2012), and photo URLs. decode_checks checks the official decode field by field (drive, engine, electrification, transmission, speeds, seats, GVWR) against the manufacturer's description of this VIN, NHTSA test vehicles with the same VIN pattern and EPA's configurations: confirmed, corrected, doubtful or filled, with vPIC's original value kept. recall_status is the manufacturer's VIN-specific recall status; a maker that has not answered within about 6 s (Ford's lookup takes 10 s or more) gives recall_status.pending true: unknown, not "no open recalls"; call vin_recall_status with the VIN for the complete answer, or pass recall_wait "full". NHTSA's complaint list for a common model can take 15 s or more: complaints.pending true is unknown, not zero; call decode_vin again in a minute (cached once it arrives).
validate_vin (vin)Quickly validate a VIN without calling any external APIs.
lookup_recalls (vin, make, model, year)Look up recalls for a vehicle. Provide either a VIN or make/model/year.
batch_decode (vins)Decode multiple VINs at once (up to 50).
explore_capabilitiesDiscover supported features and explicit coverage gaps.
vin_recall_status (vin)VIN-specific manufacturer-reported open and completed recall status. Tesla and Ford open/completed states; GM completed/closed states with explicit repair dates where supplied; Honda and Acura active safety recalls; Subaru completed/incomplete safety recalls; Volkswagen, Audi, Land Rover and Jaguar recalls as reported by each maker; Nissan positive open safety recalls; Mopar positive open records matched to the full VIN. Service programs are separate. Toyota, Hyundai and Kia require interactive official verification. Unknowns are never zero. Not a complete service history. Where the maker's reply describes the VIN (Volkswagen, Audi, Land Rover, Jaguar, Subaru, Honda/Acura), manufacturer_description gives the raw text and only the fields it states.
vin_recall_status (vin)VIN-specific manufacturer-reported open and completed recall status. Tesla and Ford open/completed states; GM completed/closed states with explicit repair dates where supplied; Honda and Acura active safety recalls; Subaru completed/incomplete safety recalls; Volkswagen, Audi, Land Rover and Jaguar recalls as reported by each maker; Nissan positive open safety recalls; Mopar positive open records matched to the full VIN. Service programs are separate. Toyota, Hyundai and Kia require interactive official verification. Unknowns are never zero. Not a complete service history. Where the maker's reply describes the VIN (Volkswagen, Audi, Land Rover, Jaguar, Subaru, Honda/Acura), manufacturer_description gives the raw text and only the fields it states. When a decode_vin report has recall_status.pending, this waits for that same lookup (up to about 15 s).
vehicle_catalog (level, year, make, model)Browse EPA year, make, model and configuration menus. Not sale listings.
epa_vehicle (id)Get an explicitly selected EPA test configuration; not an exact VIN match.
vehicle_emissions (id)Get EPA emissions for an explicit EPA vehicle ID.
The response will appear here.
Download JavaScript client · Machine-readable endpoint guide
+The response will appear here.
Download JavaScript client · Machine-readable endpoint guide
YOUR WORKSPACE
Your saved vehicles stay with your account. Recent reports are stored only in this browser.
Available on this browser