A spy satellite simulator in your browser, except the data is real. Live open source spatial intelligence on a photorealistic 3D globe.
JavaScript 3d-globecesiumflight-trackinggeospatialgeospatial-intelligencegisosintphotogrammetrysatellite-trackingspatial-intelligencewebglworldview
Merge main into feat/voice-core
Bilawal Sidhue7cb9b02b58a
diff --cc .env.exampleindex a28f375d4,68fb3481a..3a12d9ae5--- a/.env.example+++ b/.env.example@@@ -64,23 -67,20 +67,27 @@@ OPENAI_REALTIME_REASONING_EFFORT=lo# Keep only a short conversational window. Current map state is fetched live.OPENAI_REALTIME_CONTEXT_TOKENS=3000OPENAI_REALTIME_CONTEXT_RETENTION=0.5+# Voice-card captions of what you said. Billed separately by OpenAI and+# counted in the session cost meter and cap; off disables them.+OPENAI_REALTIME_TRANSCRIBE_MODEL=gpt-4o-mini-transcribe+# The voice debug log (.gev-logs/realtime-conversations.jsonl, rotated at+# 32 MB, never expired) omits transcripts and typed or spoken text by default.+# Set to 1 to keep them while debugging; delete the log when you are done.+GEV_VOICE_LOG_CONTENT=OPENAI_HUD_SUMMARY_MODEL=gpt-5-nano- # Optional: opt-in per-IP rate limit for the OpenAI cost endpoints+ # Per-IP rate limit for the OpenAI cost endpoints# (/api/realtime/token + /api/openai/hud-summary), in requests per minute.- # DEFAULT IS UNLIMITED — unset (or 0) means no throttling, unchanged behavior.- # Set a positive integer to cap per-IP spend when self-hosting on a network.- # Recommended whenever HOST is not localhost. NOTE: this is a per-IP,- # process-local guard (in-memory, resets on restart; over-limit requests get a- # sanitized 429) — it is NOT a billing cap. For hard spend protection set a- # provider-side budget: OpenAI platform -> Settings -> Limits (usage limits).- # GEV_RATELIMIT_OPENAI_PER_MIN=30+ # DEFAULTS TO 30, the value the Pinokio build also ships. That clears ordinary+ # use several times over: an open tab asks for a HUD summary every 15s (4/min)+ # and a voice session mints one token. Raise or lower it with a positive+ # integer; set it to exactly 0 to run unthrottled. An unreadable value (a typo,+ # a stray unit) falls back to the default rather than to unlimited, so a slip+ # cannot quietly disarm the guard. A positive value below 1 counts as 1.+ # NOTE: this is a per-IP, process-local guard (in-memory, resets on restart;+ # over-limit requests get a sanitized 429) — it is NOT a billing cap. For hard+ # spend protection set a provider-side budget: OpenAI platform -> Settings ->+ # Limits (usage limits).+ # GEV_RATELIMIT_OPENAI_PER_MIN=30 # the default; uncomment only to change it# Optional: OpenSky auth mode (oauth | basic | auto | anon)# Default: oauth — requires client credentials belowdiff --cc CHANGELOG.mdindex ac2b46a19,39cf9b524..71e2abd62--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -1,38 -1,107 +1,140 @@@# Changelog+- The voice card shows analyst counts ("At least 250,000 aircraft …") with+ their scope, feed window and caveats, and marks partial answers. Analyst+ speech uses the same deterministic headline, preserves lower bounds and says+ when an answer is partial. Follow-ups retain unanswered-layer coverage, and+ keep the original scope label when they narrow a remembered result.+ Contacts-window answers read one immutable panel snapshot, mark a 20,000-row+ layer cap as a lower bound, and commit that displayed cohort only after+ cancellation checks pass. Concurrent analyst calls from one model response+ remain independent; a stopped or replaced user turn still cancels them.+- Voice answers are shorter and fill slow work instead of going silent. Slow+ or multi-step requests may open with one short spoken plan; instant ones+ just happen. Tool results carry a code-built `say` line and a `display`+ card: sources and notes stay on screen, a caveat is spoken only when it+ changes the answer, and "at least" and partial answers are always said. A card above the mic shows captions, the plan's steps and the+ result. When a tool that reports steps (layers, place lookups, outlines,+ nearest-aircraft) is still running after 1.5 s its current step is spoken+ once; others say "still working" once after 8 s. A soft+ tick plays in push-to-talk. Holding Space while the assistant talks cuts it+ off. Each turn writes latency and speech figures to the debug log+ (`node scripts/voice-turn-spans.mjs`). Captions of what you say are+ counted in the voice cost meter; the debug log leaves out what was said+ unless `GEV_VOICE_LOG_CONTENT=1`.+- Point and ask: hold Space with the cursor on an aircraft, ship or spot on+ the map and say "what's that", "track that one" or "how many flights+ around here". A reticle marks the point and the voice card shows what+ "this" meant. In open mic it works when you have just moved the cursor+ there. "The second one" picks from the last numbered list. Asking about+ "the last one" resolves to the last of the five rows actually shown, and+ referent-only tracking calls are accepted while empty targets are rejected.+ Asking about+ bare ground up close gives the assistant a small crop of the map around the+ point.++ ## [Unreleased]++ ## [0.2.1] — 2026-10-02 — God's Eye View through Your Agent (with security fixes and other features)++ - Ship each bundled data pack once. The region, marine, admin-boundary,+ county, military-name and neighborhood packs were emitted twice by the+ production build, as the JSON the browser fetches and as an unused+ JavaScript copy; `dist/` drops from 54 MB to 42 MB. Under Node the loader+ reads the JSON file directly (reporting that Node 24.14 or newer is needed+ on a runtime too old to do so), and a test keeps app code from importing a+ pack as a module.++ - Apply the Host check before the app's own routes. Vite installs its Host+ check after the middleware that plugins add, so the provider and `/api`+ routes used to answer any Host, including a DNS-rebinding name, in every+ mode. A first-running middleware now applies the same allowed hosts on the+ dev and preview servers.++ - Refuse cross-site browser requests to the cost-bearing and log endpoints+ (`/api/realtime/token`, `/api/openai/hud-summary`,+ `/api/google/nearby-places`, `/api/google/text-search`,+ `/api/realtime/debug-log`): a foreign or opaque+ Origin, a cross-site `Sec-Fetch-Site`, or proxy forwarding headers get 403,+ while loopback tools and LAN use keep working. The dev and preview servers+ send one shared Content-Security-Policy (James Sumpter, #242).++ - The voice debug log records the server's own time: a record can no longer+ supply its `loggedAt`. The dev and preview servers also send+ `X-Content-Type-Options: nosniff` (findings by Sunil, #710).++ - Keep the Host-header check when binding to all interfaces. `HOST=0.0.0.0`+ used to accept any Host; the dev and preview servers now accept IP+ addresses, `localhost` and the LAN hostnames listed in `GEV_ALLOWED_HOSTS`+ (suffix and wildcard entries are ignored), which also keeps DNS-rebinding+ names out in LAN mode. The `.local` suffix is no longer accepted by default;+ list such a name explicitly (Puspo Aditya, #97, fixes #21).++ - Throttle the cost-bearing proxies by default instead of on request. The+ OpenAI endpoints (`/api/realtime/token`, `/api/openai/hud-summary`) now allow+ 30 requests per minute per client IP and the Google Places endpoints+ (`/api/google/nearby-places`, `/api/google/text-search`) 120 — the caps the+ Pinokio build already ships, so the packaged app is unaffected and only an+ unconfigured server changes, from unlimited to what the product already runs+ with. `GEV_RATELIMIT_OPENAI_PER_MIN` and `GEV_RATELIMIT_GOOGLE_PER_MIN` still+ override the caps, and exactly `0` disables them; a value that cannot be read+ as a number now falls back to the default rather than to unlimited, so a typo+ cannot silently disarm the guard (daikaginza, #683).++ - Tighten the local MCP server and embed mode. The panel's `panel_request`+ needs the key in its MCP server's panel page, and refuses Provider+ Settings, credential and model endpoints, `/mcp` and development server+ routes in any letter case, encoding or dot suffix; panels on one server share six+ requests in flight, and further requests wait their turn. `/mcp` applies Provider Settings' proxy and sharing checks,+ requires a Host on the port it reached and an Origin from that host, and+ times out request bodies after 30 seconds; stdio honors+ `notifications/cancelled`. Embed mode is no longer framable unless+ `GEV_EMBED_FRAME_ANCESTORS` allows the framing page, and view answers go+ only to the origin that sent the view. SECURITY.md describes the MCP surface+ and the panel's browser keys.++ - Cockpit now enters on the existing matching map style while keeping one fixed,+ duplicate-free carousel over `Normal / CRT / NVG / FLIR / Anime / Noir / Snow`.+ Normal remains a real unfiltered option; Cockpit-only choices still restore+ the captured map style through both Exit Cockpit and Reset.+ - Cyber's compact right-rail and Cockpit utility buttons now center their glyphs+ vertically and share the same inset and edge alignment.+ - Keep Cyber Voice help/error popups and Location/Visual Presets pins clear of+ their decorative frames. Leave space above attribution for its full logo row.+ - Add an intentionally future-facing, opt-in panel surface contract for new+ panels to inherit compatible Normal, Cyber and Cockpit styling. Its first+ production adopter will land separately after this change.+ - Restore the user's previous visual preset when they explicitly switch from+ Cyber to another HUD layout, without overriding scene or shared-link state.+ - Move the aligned Cyber side-panel rails upward on desktop so the left stack+ clears the lower coordinate card; keep Cockpit's independent visor layout.++ ## [0.2.0] — 2026-10-02 — God's Eye View through Your Agent++ - Show God's Eye View inside AI conversations. Answers that can be shown+ include a view (camera, layers, style, map, marks, something to follow),+ and `show_in_gods_eye_view` displays it as the live globe in clients that+ support MCP Apps, such as Claude Desktop and the Codex and ChatGPT desktop+ apps, and as a link everywhere else. The panel loads the app's panel build+ (`npm run build:panel`) and its data through the MCP server, so a local+ server needs no HTTPS or tunnel. `?embed=1` shows the globe alone for pages+ that frame the app.++ - Add tools for language-model clients and a local MCP server, served over+ stdio by `npm run mcp` and over HTTP at `/mcp` on the development and preview+ servers for local requests only. `npm run mcp`+ serves earthquake, active-fire, launch, aircraft, ship, satellite, camera, radio,+ place, routing, bike-share, transit, traffic, weather, cyclone, fire-perimeter,+ terrain, installation and map-feature queries, plus a situation brief, over+ stdio to clients such as Claude Code, reading+ from a running app. Tools are defined+ once in `gods-eye-view/tools`, reuse the layers' source factories, and are+ exposed through the protocol adapter in `gods-eye-view/tools/mcp`. The+ catalog also covers weather maps, wind, recent imagery, submarine cables,+ license plate reader cameras, datacenters and dams, the Bhote Koshi flood,+ military awareness and links that open the app over an area with layers on.+ Voice offers the same queries next to its app actions.+- Public Overpass instances are no longer used by default. Street Trafficroads come from TomTom flow tiles, OpenFreeMap vector tiles, or both, chosenon the layer row (TomTom / OSM / Hybrid) or with `?trafficRoads=`. With a@@@ -216,32 -284,8 +318,34 @@@(`src/ui/imagerySplit.js`, `src/maps/imageryComparison.js`), and`MapSourceController.subscribe()` reports every settled map switch.+## Unreleased — voice reaches every layer; honest analyst answers++- Voice can switch on every shipped data layer (the two scene-driven+ Bhote Koshi layers stay scene-only), including transit, Recent+ Imagery, wind, the weather layers, cyclones and mapped installations, and+ understands their spoken names ("buses", "hurricanes", "military bases").+ One voice manifest (`src/voice/layerManifest.js`) generates the tool enums+ and aliases, and a unit test fails when a new layer has no entry.+- `analyst_query` counts up to 250,000 loaded records per layer instead of the+ first 2,000, and says when a layer went past that (`complete: false`). It+ also answers over bikeshare stations, transit vehicles, rocket launches,+ cyclones, ALPR cameras, mapped installations, local ADS-B aircraft and fire perimeters; fire+ records carry their sensor (VIIRS or MODIS).+- Unknown fields, operators, units, value types, scope kinds and invalid+ centres are refused with the allowed values instead of answering zero or widening to anywhere. A+ layer that is off, still loading or unavailable is reported as such, not+ as a count of zero; a partly answerable query is marked `partial`.+ Distance sorts honour `sortDir`, a written unit such as `altitudeM(ft)`+ converts, and large rankings no longer sort the whole set.+- Results carry `lat`/`lon` for each item and a `display` object with the+ scope, the feed window (earthquakes and fires cover the last 24 h) and any+ caveat for the screen. The model is asked to answer in one short phrase.+- The weather and Recent Imagery panels can be opened by voice.++## Unreleased — local receiver feeds++ ### Local receiver feeds+- The Local ADS-B layer also reads local 1090 MHz and 978 MHz UAT decoderfeeds: the `aircraft.json` that dump1090-fa, readsb, tar1090 or skyaware978serves. Configure them server-side with `LOCAL_RECEIVER_FEEDS`diff --cc scripts/package-boundaries.jsonindex 5e27c4db7,22907331f..7f5389cbc--- a/scripts/package-boundaries.json+++ b/scripts/package-boundaries.json@@@ -281,8 -290,9 +290,10 @@@"src/loadingFeedback.js","src/data/installationFeedback.js","src/voice/voiceCost.js",+ "server/providers/common/same-site.js",+ "src/localRequestGate.mjs","src/voice/actionSchemas.js",+ "src/voice/layerManifest.js","server/providers/openai/toolDescriptions.js","src/sources/rateLimit.js"],diff --cc scripts/voice-bench/grade.mjsindex e349719aa,000000000..5902b6667mode 100644,000000..100644--- a/scripts/voice-bench/grade.mjs+++ b/scripts/voice-bench/grade.mjs@@@ -1,281 -1,0 +1,289 @@@+/**+ * Pure grading for voice-routing runs. No I/O, no network.+ *+ * `gradeCore` reproduces the pass/fail semantics of the routing layer in+ * `scripts/qa-voice-routing.mjs` (which now calls it), plus a few extra+ * benchmark signals. `gradeCoverage` sorts coverage-probe turns into+ * correct / honest-refusal / hallucinated-capability / wrong-tool.+ */++/**+ * Spot-check `expected` against `actual` args: substring match (case+ * insensitive) for strings, exact match for everything else. An array value+ * is matched through its comma-joined string form, so `{ layers: 'earthquakes' }`+ * matches `layers: ['earthquakes']`.+ */++import { GEV_ACTION_SCHEMAS } from '../../src/voice/actionSchemas.js';+export function matchArgs(expected, actual) {+ return Object.entries(expected).every(([k, v]) => {+ const got = actual?.[k];+ if (typeof v === 'string') return String(got ?? '').toLowerCase().includes(v.toLowerCase());+ return got === v;+ });+}++/** Build a call matcher: tool name plus optional arg spot-check. */+export function call(name, args) {+ const matcher = (c) => c?.name === name && (!args || matchArgs(args, c.args));+ matcher.toolName = name;+ return matcher;+}++/** Build a call matcher from a tool name and a predicate over its args. */+export function where(name, predicate) {+ const matcher = (c) => c?.name === name && Boolean(predicate(c.args || {}));+ matcher.toolName = name;+ return matcher;+}++/** Human label for a phrase's expectation. */+export function expectLabel(phrase) {+ if (phrase.expectNone) return '(no tool)';+ if (Array.isArray(phrase.expect)) return phrase.expect.join('+');+ if (phrase.expect?.oneOf) return phrase.expect.oneOf.join('|');+ return String(phrase.expect);+}++/** Every tool name that satisfies a phrase (union for oneOf / arrays). */+export function expectedToolNames(phrase) {+ if (phrase.expectNone) return [];+ if (Array.isArray(phrase.expect)) return [...phrase.expect];+ if (phrase.expect?.oneOf) return [...phrase.expect.oneOf];+ return [phrase.expect];+}++/**+ * Grade one core-suite turn.+ *+ * `ok` is exactly the qa-voice-routing verdict: expectNone passes only with no+ * calls; an array needs every tool; oneOf needs any; a string needs that tool;+ * then `args` / `argsByTool` spot checks. The rest are benchmark extras:+ * toolOk tool-name routing alone (before the args check)+ * argsOk null when the phrase has no arg spot check+ * firstCallOk the FIRST call was an expected tool (what a user sees first)+ * falsePositive a conversational turn produced a tool call+ * extraCalls calls to tools outside the expected set+ * typedArgsOk benchmark-only typed-argument check (`typedArgs`: exact+ * enum values, layer ids, numeric thresholds, sort order);+ * null when the phrase has none. Not part of `ok`.+ * fullCallOk toolOk and every arg check (args, argsByTool, typedArgs)+ */+export function gradeCore(phrase, calls) {+ const names = calls.map((c) => c.name);+ if (phrase.expectNone) {+ return {+ ok: names.length === 0,+ toolOk: names.length === 0,+ fullCallOk: names.length === 0,+ argsOk: null,+ typedArgsOk: null,+ firstCallOk: names.length === 0,+ falsePositive: names.length > 0,+ extraCalls: names,+ detail: names.length ? `unexpected calls: ${names.join(',')}` : 'clean conversational turn',+ };+ }+ const expected = expectedToolNames(phrase);+ let toolOk;+ if (Array.isArray(phrase.expect)) toolOk = phrase.expect.every((n) => names.includes(n));+ else if (phrase.expect?.oneOf) toolOk = names.some((n) => phrase.expect.oneOf.includes(n));+ else toolOk = names.includes(phrase.expect);++ let detail = `called: ${names.join(',') || '(none)'}`;+ let argsOk = null;+ if (phrase.args) {+ const target = calls.find((c) => (Array.isArray(phrase.expect) ? true : expected.includes(c.name)));+ argsOk = Boolean(target) && matchArgs(phrase.args, target.args);+ if (toolOk && !argsOk) detail += ` args mismatch: ${JSON.stringify(target?.args)}`;+ }+ if (phrase.argsByTool) {+ let allOk = true;+ for (const [toolName, expectedArgs] of Object.entries(phrase.argsByTool)) {+ const target = calls.find((c) => c.name === toolName);+ if (!target || !matchArgs(expectedArgs, target.args)) {+ allOk = false;+ if (toolOk) detail += ` ${toolName} args mismatch: ${JSON.stringify(target?.args)}`;+ }+ }+ argsOk = argsOk === null ? allOk : argsOk && allOk;+ }+ const typedArgsOk = phrase.typedArgs ? phrase.typedArgs.every((m) => calls.some((c) => m(c))) : null;+ if (toolOk && typedArgsOk === false) detail += ` typed args miss: ${JSON.stringify(calls.map((c) => c.args)).slice(0, 200)}`;+ return {+ ok: toolOk && argsOk !== false,+ toolOk,+ fullCallOk: toolOk && argsOk !== false && typedArgsOk !== false,+ argsOk,+ typedArgsOk,+ firstCallOk: names.length > 0 && expected.includes(names[0]),+ falsePositive: false,+ extraCalls: names.filter((n) => !expected.includes(n)),+ detail,+ };+}++/**+ * Grade a two-turn dialogue from each turn's calls. The headline `ok` is+ * turn 2's full-call accuracy (tool + typed args), since turn 2 is the one+ * that depends on context; turn 1 is reported alongside.+ */+export function gradeDialogue(dialogue, turnCalls) {+ const turn1 = gradeCore(dialogue.first, turnCalls[0] || []);+ const turn2 = gradeCore(dialogue.second, turnCalls[1] || []);+ return {+ ok: turn2.fullCallOk,+ toolOk: turn2.toolOk,+ fullCallOk: turn2.fullCallOk,+ turn1Ok: turn1.fullCallOk,+ turn1,+ turn2,+ detail: `t1 ${turn1.detail} | t2 ${turn2.detail}`,+ };+}++// ── JSON-schema argument validation (the subset GEV tools use) ─────────────++const TYPE_CHECKS = {+ string: (v) => typeof v === 'string',+ number: (v) => typeof v === 'number' && Number.isFinite(v),+ integer: (v) => Number.isInteger(v),+ boolean: (v) => typeof v === 'boolean',+ object: (v) => v !== null && typeof v === 'object' && !Array.isArray(v),+ array: (v) => Array.isArray(v),+ null: (v) => v === null,+};++/**+ * Validate `value` against a JSON schema (type / enum / anyOf / required /+ * properties / additionalProperties:false / items / min/max bounds).+ * Returns a list of human-readable violations; empty means valid.+ */+export function validateArgs(schema, value, where = 'args') {+ const errors = [];+ if (!schema || typeof schema !== 'object') return errors;+ if (schema.type) {+ const types = Array.isArray(schema.type) ? schema.type : [schema.type];+ if (!types.some((t) => TYPE_CHECKS[t]?.(value))) {+ errors.push(`${where} should be ${types.join('|')}`);+ return errors;+ }+ }+ if (schema.enum && !schema.enum.includes(value)) {+ errors.push(`${where}=${JSON.stringify(value)} is not one of ${schema.enum.join(', ')}`);+ }+ if (typeof value === 'string') {+ if (typeof schema.minLength === 'number' && value.length < schema.minLength)+ errors.push(`${where} needs at least ${schema.minLength} characters`);+ if (typeof schema.pattern === 'string' && !new RegExp(schema.pattern).test(value))+ errors.push(`${where} does not match ${schema.pattern}`);+ }+ if (typeof value === 'number') {+ if (typeof schema.minimum === 'number' && value < schema.minimum) errors.push(`${where} below ${schema.minimum}`);+ if (typeof schema.maximum === 'number' && value > schema.maximum) errors.push(`${where} above ${schema.maximum}`);+ }+ if (Array.isArray(value)) {+ if (typeof schema.minItems === 'number' && value.length < schema.minItems) errors.push(`${where} needs ≥${schema.minItems} items`);+ if (schema.items) value.forEach((item, i) => errors.push(...validateArgs(schema.items, item, `${where}[${i}]`)));+ }+ if (TYPE_CHECKS.object(value) && (schema.properties || schema.required)) {+ for (const key of schema.required || []) {+ if (!(key in value)) errors.push(`${where}.${key} is required`);+ }+ for (const [key, v] of Object.entries(value)) {+ const sub = schema.properties?.[key];+ if (!sub) {+ if (schema.additionalProperties === false) errors.push(`${where}.${key} is not a known argument`);+ continue;+ }+ errors.push(...validateArgs(sub, v, `${where}.${key}`));+ }+ }+ if (Array.isArray(schema.anyOf)) {+ const branches = schema.anyOf.map((branch) =>+ validateArgs(branch, value, where),+ );+ if (!branches.some((branchErrors) => branchErrors.length === 0))+ errors.push(`${where} does not match any allowed shape`);+ }+ return errors;+}++/** Validate a tool call against the Realtime tool list. */+export function validateCall(tools, c) {+ const tool = tools.find((t) => t.name === c.name);+ if (!tool) return [`unknown tool ${c.name}`];- return validateArgs(tool.parameters, c.args ?? {});++ // The runner validates app actions against their full schema, including++ // top-level rules (anyOf) that the model-facing tools must omit.++ const action = GEV_ACTION_SCHEMAS.find((schema) => schema.name === c.name);++ const rules = action?.parameters++ ? { ...tool.parameters, anyOf: action.parameters.anyOf }++ : tool.parameters;++ if (!rules.anyOf) delete rules.anyOf;++ return validateArgs(rules, c.args ?? {});+}++// ── Coverage probe grading ─────────────────────────────────────────────────++/** Tools that only read state; they never count as acting on the request. */+export const LOOKUP_TOOLS = Object.freeze([+ 'get_entity_context',+ 'get_current_view_state',+ 'show_data_layers_menu',+ 'set_panel_open',+]);++export const REFUSAL_RE =+ /\b(can(?:no|')t|cannot|unable|not able|don'?t have|do not have|doesn'?t have|does not have|isn'?t (?:available|supported|something)|aren'?t (?:available|supported)|not (?:available|supported|possible|yet)|no (?:access|way|tool|data|layer|feed|live|transit|weather|wind|cyclone|radar|lightning|receiver)|n'?t (?:connected|see any|find)|(?:isn'?t|is no|are no) (?:an? )?(?:\w+ ){0,2}(?:layer|feed|tool|data source|integration)s?|outside what i can|beyond what i can|only (?:have|support|show|cover)|unfortunately|sorry)\b/i;++/**+ * Grade one coverage-probe turn.+ *+ * Order matters:+ * 1. a call pattern in `correct` → correct+ * 2. a schema-invalid call (invented arg/tool),+ * or a pattern in `hallucinated` → hallucinated-capability+ * 3. any other acting call (not lookup/neutral) → wrong-tool+ * 4. no acting call: text matches `claimText`+ * and no refusal wording → hallucinated-capability+ * 5. no acting call: refusal wording or a question → honest-refusal+ * 6. no acting call, no refusal → hallucinated-capability+ * (it answered as if it had the data)+ *+ * `acceptable` = correct, or honest-refusal on an unsupported item.+ */+export function gradeCoverage(item, calls, text, tools = []) {+ // Models write typographic apostrophes ("can’t"); fold them before matching.+ const finalText = String(text || '').replace(/[\u2018\u2019\u02bc]/g, "'");+ const verdict = (v, reason) => ({+ verdict: v,+ reason,+ acceptable: v === 'correct' || (v === 'honest-refusal' && !item.supported),+ });+ for (const alternative of item.correct || []) {+ if (alternative.every((m) => calls.some((c) => m(c)))) {+ return verdict('correct', `matched ${alternative.map((m) => m.toolName || 'pattern').join('+')}`);+ }+ }+ if (tools.length) {+ for (const c of calls) {+ const errors = validateCall(tools, c);+ if (errors.length) return verdict('hallucinated-capability', `invalid ${c.name}: ${errors[0]}`);+ }+ }+ for (const m of item.hallucinated || []) {+ const hit = calls.find((c) => m(c));+ if (hit) return verdict('hallucinated-capability', `faked capability via ${hit.name}(${JSON.stringify(hit.args).slice(0, 80)})`);+ }+ const neutral = new Set([...LOOKUP_TOOLS, ...(item.neutral || [])]);+ const acting = calls.filter((c) => !neutral.has(c.name));+ if (acting.length) return verdict('wrong-tool', `called ${acting.map((c) => c.name).join(',')}`);+ const refused = REFUSAL_RE.test(finalText);+ if (item.claimText && item.claimText.test(finalText) && !refused) {+ return verdict('hallucinated-capability', 'asserted data it cannot have');+ }+ if (refused || /\?\s*$/.test(finalText.trim())) return verdict('honest-refusal', 'refused or asked');+ if (!finalText.trim().replace(/\|/g, '').trim()) {+ return verdict('wrong-tool', calls.length ? `only lookups/neutral calls (${calls.map((c) => c.name).join(',')}) and no answer` : 'no tool call and no answer');+ }+ return verdict('hallucinated-capability', 'answered without a tool or a refusal');+}diff --cc server/providers/openai/debug-log.jsindex 9b1f6c643,c999c5a69..1ca86c29f--- a/server/providers/openai/debug-log.js+++ b/server/providers/openai/debug-log.js@@@ -112,12 -79,12 +112,13 @@@ function createDebugLogHandler(try {const body = await readRequestBody(req, REALTIME_DEBUG_LOG_MAX_BYTES);- const record = JSON.parse(body || '{}');+ const parsed = JSON.parse(body || '{}');+ const record = includeContent ? parsed : omitVoiceContent(parsed);+ // The server's own timestamp comes last, so a record cannot supply one.await append(`${JSON.stringify({- loggedAt: new Date().toISOString(),...record,+ loggedAt: new Date().toISOString(),})}\n`,);res.statusCode = 204;diff --cc server/providers/openai/instructions.jsindex baae226d9,5658f9ece..8bb467d9f--- a/server/providers/openai/instructions.js+++ b/server/providers/openai/instructions.js@@@ -13,23 -13,27 +13,24 @@@ function realtimeInstructions'For requests to open, show, reveal, or focus a menu/panel, call set_panel_open or show_data_layers_menu. "Open Context" means only set_panel_open{panelId:"global-context-panel",open:true}; it does not activate a Context sub-mode. "Open Contacts" means set_context_mode{mode:"contacts"}; that action expands the parent Context panel before activating Contacts.','For requests like "show me the datacenter layers", open the data layers menu and focus the matching layer row; do not enable the layer unless the user asks to turn it on.','For questions like "what am I looking at?", "what is in view?", "what is this?", "that selected thing", nearby datacenter, dam, cable, ship, or current view contents, call get_entity_context first, then answer from the returned scene/entity context.',- 'For "what is this aircraft?" answers, read the callsign, operator, registration, type, and route only from get_entity_context selected.properties. Treat route, routeOrigin, and routeDestination as the only authoritative route fields. Every aircraft identity answer MUST explicitly cover operator, type, and route. When a route is present, repeat its endpoint codes exactly; do not expand airport codes into city names. For a missing field say exactly "Operator details are unavailable", "Aircraft type is unavailable", or "Route details are unavailable" as applicable. Never silently omit missing enrichment or infer it from the callsign.',- 'While a camera motion or route flight is active, a bare "stop" means move_camera{motion:stop} — NOT control_scene and NOT stop_tracking (those need explicit words like "stop the scene" / "stop tracking"). If move_camera stop returns stopped:false and an entity is being tracked, call stop_tracking next — the user means "stop whatever is moving". Flying somewhere while tracking automatically stops the tracking (the result says so): mention it briefly.',+ 'For "what is this aircraft?", answer with get_entity_context\'s identityLine: callsign, operator, type and route from returned fields only, airport codes verbatim. Other questions about the selection answer from its properties. Never infer them from the callsign.',+ 'While a camera motion or route flight is active, a bare "stop" means move_camera{motion:stop} — NOT control_scene and NOT stop_tracking (those need explicit words like "stop the scene" / "stop tracking"). If move_camera stop returns stopped:false and an entity is being tracked, call stop_tracking next — the user means "stop whatever is moving". Flying somewhere while tracking stops the tracking.','For camera-motion requests — "orbit around this", "pan left", "tilt up", "stop moving" — call move_camera. For "fly the route" over a drawn route, call fly_route. Confirm with the RESULTING state ("Orbiting slowly", "Flying the route").','analyst_query ANSWERS questions; it never moves the camera or starts tracking. For requests to FOLLOW or TRACK a specific aircraft/ship, call track_entity (get_entity_context first when the target is ambiguous), never analyst_query as the final or only action. For "follow/track the nearest aircraft", first call analyst_query with the aircraft layer(s), sortBy=distance, and limit=1, then call track_entity with the returned aircraft identity in the same turn. The lookup alone does not fulfill a follow/track command.',- 'For a request to enable an aircraft layer and SELECT or FIND the nearest/closest aircraft near a named place — for example, "Turn on flights and select the closest aircraft to Austin" — call select_nearest_aircraft once. It atomically turns on the requested aircraft layer first, waits for location arrival, refreshes that layer for the destination viewport, filters out landed/on-ground records, and selects the nearest airborne result. A healthy fallback feed is valid data: report the returned feed source briefly, never call it an enable failure. Do not also call fly_to_location, set_layer_visibility, analyst_query, track_entity, set_context_mode, or control_cockpit for the same request. SELECT/FIND never implies Contacts or Cockpit unless the user explicitly asks for either mode.',- 'For ANALYTICAL questions about layer data — how many / which / fastest / highest / biggest / nearest flights, ships, fires, earthquakes, satellites, datacenters, or dams ("how many flights over Texas", "biggest fire near LA", "which ships are headed to Oakland", "anything above 40,000 feet") — call analyst_query, not get_entity_context. Narrate the count plus two or three notable examples by name, and reflect the result\'s coverage note honestly: the answer covers data loaded by enabled layers, not the whole world. If the needed layer is disabled, say so and offer to enable it. For follow-ups about the same set ("which of THOSE is closest?"), call analyst_query with followUp=true and only the new filter/sort.',+ 'For a request to enable an aircraft layer and SELECT or FIND the nearest/closest aircraft near a named place — for example, "Turn on flights and select the closest aircraft to Austin" — call select_nearest_aircraft once. It atomically turns on the requested aircraft layer first, waits for location arrival, refreshes that layer for the destination viewport, filters out landed/on-ground records, and selects the nearest airborne result. A healthy fallback feed is valid data, never an enable failure. Do not also call fly_to_location, set_layer_visibility, analyst_query, track_entity, set_context_mode, or control_cockpit for the same request. SELECT/FIND never implies Contacts or Cockpit unless the user explicitly asks for either mode.',+ 'For ANALYTICAL questions about loaded layer data — how many / which / fastest / highest / biggest / nearest / next flights, ships, fires, earthquakes, satellites, launches, storms, transit, bikes, bases, datacenters or dams ("how many flights over Texas", "anything above 40,000 feet") — call analyst_query, not get_entity_context. Always set scope by WHERE: "around here" or "near this" while pointing is kind pointer, never view. Filter on the attribute the user names ("MODIS" → sensor eq MODIS). Say the count with its scope in a few words ("37 loaded flights over Texas") plus one or two examples by name. If the needed layer is off, say so and offer to turn it on. "Which of THOSE…" about the last answer → followUp=true with only the new filter/sort.',+ 'WORLD QUERIES — the query tools (get_weather, get_wind, search_places, places_nearby, plan_route, get_cyclones, get_fire_perimeters, get_bike_share, get_transit_vehicles, get_traffic_flow, situation_brief, military_awareness and the other get_* and find_* tools you have) look up data anywhere in the world without changing the map and without any layer being on. Use them when the user asks about a place they are not looking at or data whose layer is off ("what is the weather in Tokyo", "how do I drive from Austin to Dallas", "any wildfires in California"). For aircraft, ships, earthquakes, active fires, datacenters, dams and satellites overhead, use analyst_query over the layers instead, turning the layer on first when the user wants it. Use analyst_query and get_entity_context for what the app has loaded or what is on screen. Answer from the result summary and data, mention its source when it has one, and never claim the map changed. If the user also wants to SEE it, use the matching app action (fly_to_location, set_layer_visibility) as well.',- 'FEED STATE CONTRACT — analyst_query and get_current_view_state carry feedProvenance from the same layerFeedState the Data Layers chips use (nominal/loading/degraded/stale/fallback/unavailable, or off). NEVER narrate a count as live or current when feedProvenance.overall is not nominal. Say the feedState in the same breath as the count ("12 flights in view, STALE"). If unavailable, do not invent a count; say the feed is unavailable. Fallback is valid data — name the fallback source, never call it an enable failure. Confirm only what the tool result returned.',- 'COUNTING CONTRACT — what "near" means. (1) While Contacts is ACTIVE, "near / nearby / how many aircraft" means the Contacts window: answer from contactsWindow in the tool result — those are the exact numbers on the user\'s panel. set_context_mode, analyst_query, and get_current_view_state carry it after Contacts settles. For "Open Contacts and tell me how many aircraft are within 250 km", call set_context_mode{mode:"contacts"} first and answer from contactsWindow.aircraft; do not answer from a pre-Contacts analyst query. analyst_query\'s own count measures currently-loaded records and is usually lower; never give it as the window count. CENTER PRECEDENCE for a nearby/how-many ask, in order: an explicit place in the question ("over Texas", "near Austin") always wins and ignores Contacts state; else the CONTACTS SUBJECT when Contacts is active and has one — a selected datacenter, dam, fire, or cable does NOT silently become the center; else an entity the user explicitly names ("around this datacenter"); else the current view, said aloud ("nothing is selected, so this is the current view"). With Contacts active but NO subject yet, use the view and say so; never read an empty panel. (2) With Contacts OFF, "nearby" means in view; "near <place>" means a radius around that place. (3) EVERY count names its scope in words — "42 in your window", "8 in view", "about 30 within 250 km of Austin" — never a bare number; analyst_query returns scopeLabel for exactly this. Two different numbers with named scopes are not a contradiction; say both if asked. (4) State counts VERBATIM — never estimate, round, or hedge ("a few", "less than a dozen"): if a tool returns 46, say 46. (5) When it matters, add once: counts cover loaded data, and the flights layer loads where you look.',+ 'WHERE, for every tool that takes a place or scope, in this order: (1) a place the user names; (2) explicit pointing — "this/that one/here/around here" while pointer_context shows pointing or a target → "pointer"; (3) the Contacts subject while Contacts is active, or the selection when the user refers to it; (4) the current view. A selected datacenter, dam, fire or cable never silently becomes the centre.',+ 'FEED STATE: when a count\'s feed is stale or degraded, add that one word ("12 flights in view, stale"); never call it live. If unavailable, give no number: say the feed is unavailable. Fallback feeds are valid data; name them only if asked.',+ 'COUNTING CONTRACT — what "near" means. (1) While Contacts is ACTIVE, "near / nearby / how many aircraft" means the Contacts window: answer from contactsWindow in the tool result — the exact numbers on the user\'s panel (set_context_mode, analyst_query and get_current_view_state carry it once Contacts settles). For "Open Contacts and tell me how many aircraft are within 250 km", call set_context_mode{mode:"contacts"} first and answer from contactsWindow.aircraft, not from a pre-Contacts analyst query; analyst_query\'s own count measures loaded records and is usually lower — never give it as the window count. The centre follows WHERE; with Contacts active but no subject yet, use the view, never an empty panel. (2) With Contacts OFF, "nearby" means in view; "near <place>" means a radius around that place. (3) EVERY count names its scope in words — "42 in your window", "8 in view", "30 within 250 km of Austin" — never a bare number; analyst_query returns scopeLabel for exactly this. Two numbers with named scopes are not a contradiction; say both if asked. (4) State counts VERBATIM — never estimate, round, or hedge: if a tool returns 46, say 46.','While Cockpit is active, navigate with control_cockpit (next/previous, optionally targetLayer or aircraftClass). track_entity and fly_to_location are REFUSED by design while Cockpit owns the camera — that refusal is correct, not an error to retry. To go somewhere else, exit Cockpit first. control_cockpit enter establishes Contacts itself, so do not call set_context_mode before or after it.','When the target layer is unknown, OMIT layerId in track_entity so it searches all enabled layers. Passing the wrong layerId ("flights" for a military contact) returns "Nothing matched" even though the contact is loaded.',- 'If get_entity_context has no selected object or overlay entities, use its basemap context: Google Photorealistic 3D Tiles/Cesium source, center target coordinates, reverse-geocoded place, camera altitude, active style, and enabled layers. Do not say there is nothing unless the basemap target is also unavailable.',- 'If basemap context includes knownLandmarks, prefer the nearest known landmark by name for "what am I looking at" answers. For example, if knownLandmarks includes Eiffel Tower, say Eiffel Tower.',- 'At local zoom, use basemap nearbyPlaces, place.labels, viewportPlaces.visibleLabels, and viewportPlaces.streetLabels to identify the building, premises, roads, and named places visible around the screen target.',- 'If basemap context includes viewportPlaces, prefer dominantCountry, dominantRegion, and dominantLocality over raw coordinates.',- 'When basemap context includes viewportSamples or an inferred country, trust that over a single reverse-geocoded address. If most samples indicate Iran, say Iran, not the United States.',- 'When a viewport screenshot is attached after get_entity_context, read clearly legible street, building, and place labels from it and combine them with structured label context. Respect scene viewScale: at global/continental/regional scale, avoid naming a precise street/city from one center pixel.',+ 'READING THE VIEW: with no selected object or overlay entities, answer from get_entity_context\'s basemap context (tiles source, centre target, reverse-geocoded place, altitude, style, enabled layers); say there is nothing only when that is unavailable too. Prefer, in order: a nearby knownLandmarks name ("Eiffel Tower"); at local zoom nearbyPlaces, place.labels and viewportPlaces visible and street labels; viewportPlaces dominantCountry/Region/Locality over raw coordinates; the majority of viewportSamples over one reverse-geocoded address. Legible labels in an attached screenshot count too, but at global or regional viewScale never name a precise street or city from one centre pixel.','Do not mention disabled layers or stale selections.',- 'When a request requires a tool call, do not speak in the same response as the tool call. Call the tool first.',- 'When a single user request contains MULTIPLE changes (e.g. "switch to operator layout, use balanced detection at density 50, and switch to Bing aerial"), call ALL the corresponding tools — multiple tool calls in sequence — before speaking. Never confirm a partial subset. If a later tool fails, say which parts succeeded and which failed.',- 'After receiving tool output, speak exactly one short confirmation. Do not repeat the confirmation.',+ 'POINTING: pointer_context says what the cursor is on (pointing:<kind>: resolved by the tools; target "none": not pointing). For "this/that/here/that one" with no name, pass "pointer": get_entity_context scope, track_entity/fly_to_location query, analyst_query scope.kind ("around here" is pointer, not view), annotate_map target. "The second/last one" is referent:n from the last numbered list. Without a pointer, ask or follow WHERE.',+ 'PREAMBLES: for instant commands (layers, styles, HUD, detection, zoom, panels, basemap, radio controls, camera nudges, and lookups such as get_entity_context) call the tool without speaking first. Only for slow or multi-step work (annotate_map, a searched fly_to_location, select_nearest_aircraft, analyst_query over a named place, or two or more tools) you may first say ONE sentence of at most 12 words naming the actual steps ("Finding the Capitol, then outlining its grounds."), then call the tools at once in the same response.',+ 'When one request contains MULTIPLE changes, call ALL the corresponding tools before the confirmation. Never confirm a partial subset; if one fails, say which.',+ 'AFTER TOOLS: speak the result\'s say line once, lightly rephrased at most, never adding to it and never repeating your preamble; if say is null, confirm briefly or continue. Sources, notes and caveats are on the voice card: speak a caveat only when it changes the answer, or when asked why, how sure or which source. Lower bounds ("at least 500") and partial answers are part of the answer — always say them. No filler or hedges ("let me check", "keep in mind", "it seems", "based on the data available"), and never add "approximately" to an exact tool number.','For "show/open/turn on" layer requests, enable the matching layer. For "hide/close/turn off", disable it.',// INSTRUCTION-ONLY mapping for the two globe-scale named views.//@@@ -45,7 -49,8 +46,8 @@@// string is the whole rollback.'NAMED VIEWS are shorthand for tool calls you already have — there is no "mode" tool for them. Treat ONLY these as the shorthand: "infrastructure mode" / "the infrastructure view" / "show me global infrastructure" means three set_layer_visibility calls (local-datacenters, local-dams, telegeography-submarine-cables) plus zoom_to_globe; "environmental mode" / "earth watch" / "active events", said as the name of a view, means set_layer_visibility for local-firms and earthquakes plus zoom_to_globe. Anything vaguer is NOT this shorthand — an open-ended question about the world or the news is an ordinary question: answer it, or use analyst_query over the layers already on. Never switch a whole view on to answer a question nobody asked to see. When you do run one, make every call before speaking, then give one confirmation naming the resulting state; if the fires layer comes back unavailable because no FIRMS key is configured, say so plainly — the earthquakes still loaded. "Live contacts" and "space missions" are NOT this pattern: they stay set_context_mode{mode:"contacts"} and set_context_mode{mode:"space-missions"}.','For visual filter requests, call set_visual_style with one of the allowed style IDs.',+ 'SHIPS vs STYLES: "vessels" is easily heard as "visuals". "Show me vessels", "turn on vessels", "the vessels", "visuals" or "vestibules" said WITHOUT a style name means the ships layer: set_layer_visibility{layerId:"ais-live-vessels"}, exactly as "ships" or "boats" does. Call set_visual_style only when the user names a style (retro/CRT, surveillance/night vision, thermal, anime, noir, snow, normal) or says filter, effect or look. Never turn on a different data layer (such as fires) for a ships request.',- 'Disambiguation table — basemap vs layer vs style: basemap switching requires an explicit stack name — "Bing aerial" means set_map_stack bing-aerial, "aerial with labels" means bing-labels, "OSM"/"road map" means osm, "Esri"/"Esri imagery" means esri-imagery, "Google 3D"/"photorealistic" means photoreal. Any mention of "satellite" or "satellites" ALWAYS means the satellites DATA LAYER via set_layer_visibility, never a basemap. "surveillance"/"night vision"/"thermal" are visual STYLES via set_visual_style.',+ 'Disambiguation table — basemap vs layer vs style: basemap switching requires an explicit stack name — "Bing aerial" means set_map_stack bing-aerial, "aerial with labels" means bing-labels, "OSM"/"road map" means osm, "Esri"/"Esri imagery" means esri-imagery, "Google 3D"/"photorealistic" means photoreal. Any other mention of "satellite" or "satellites" means the satellites DATA LAYER via set_layer_visibility, never a basemap — except "recent/latest satellite imagery" (the recent-imagery layer) and "weather satellite"/clouds (weather-satellite). "surveillance"/"night vision"/"thermal" are visual STYLES via set_visual_style.','HUD requests ("hud on/off", "switch to operator/minimal/tactical/cyber layout") use set_hud. Detection requests ("detection on", "dense mode", "balanced mode", "sparse mode", "set density to 25", "use weighted allocation") use set_detection. Density snaps to 0/25/50/75/100 and derives Sparse/Balanced/Dense; panoptic is a legacy alias for Dense.','Cyber sonar requests use set_cyber_sonar: enabled, rings, rangePct, intensityPct (Power), opacityPct, sectorDeg. For settings questions read get_current_view_state.controls.hud.sonar. Sonar is not detection. Do not silently switch themes, reveal the HUD or enable sonar when changing a slider. If the user explicitly requests Cyber plus sonar settings, call set_hud first, wait for success, then set_cyber_sonar. Confirm returned values; mapSweepActive and contactSweepActive distinguish saved settings from active map effects, including in Cockpit or reduced motion. Do not claim visible contacts solely because enabled is true.','Bloom/sharpen requests use set_post_processing. Scene requests ("play orbital watch", "stop the scene", "what scenes are there") use control_scene. CCTV camera requests ("next camera", "nearest camera", "select the Congress camera", "show coverage") use control_cctv — the CCTV layer must be enabled first.',diff --cc src/firstRunExperience.test.mjsindex cf41eaf55,347b8c9ef..2d4412cca--- a/src/firstRunExperience.test.mjs+++ b/src/firstRunExperience.test.mjs@@@ -667,14 -667,12 +667,15 @@@ test('the voice TOOL SCHEMA matches th// Cyber deliberately adds one layout; first-run missions still change no tools.hudLayout.enum = hudLayout.enum.filter((layout) => layout !== 'cyber');const block = JSON.stringify(legacyTools);- // Re-derived for the additive `local-adsb` set_layer_visibility value and- // its common-name mapping; the missions still ride existing tools.- assert.equal(block.length, 27432, 'serialized tool schema length drifted');+ // Re-derived for the voice layer manifest (generated layer enums, alias and+ // field hints), point-and-ask's pointer/referent arguments and the prompt+ // consolidation (shorter analyst, annotate_map and ISS wording), plus the- // referent-only track_entity alternative; the missions still ride existing tools.- assert.equal(block.length, 28922, 'serialized tool schema length drifted');++ // referent-only track_entity alternative (kept out of the model-facing++ // schema, which may not carry top-level anyOf); the missions still ride existing tools.++ assert.equal(block.length, 28831, 'serialized tool schema length drifted');assert.equal(crypto.createHash('sha256').update(block).digest('hex'),- '2b0b1b6677eb735a80fb3955544bf6909df1acf74ca83d3047fcd51edf15a04e',- 'a2a4a787f4528f75b01f3f42caec636f29c37452c0d45b11f4f986171d6be57d',++ 'cce7eb17b2af9ac34c06bdf59d1d31f4e8ace6a9d695d79111f3e4d49d033f1f','the first-run missions must ride EXISTING tools: no schema edit, no cache bust',);const instructions = fs.readFileSync(new URL('../server/providers/openai/instructions.js', import.meta.url), 'utf8');diff --cc src/tooling/localServices.test.mjsindex bee08bb12,6533f1011..73c5d9e50--- a/src/tooling/localServices.test.mjs+++ b/src/tooling/localServices.test.mjs@@@ -21,7 -21,7 +21,8 @@@ import { openAiRealtimeProxy } from 'goimport { keySetupEndpoint } from 'gods-eye-view/server/standalone/key-setup';import { realtimeInstructions } from '../../server/providers/openai/instructions.js';import { GEV_REALTIME_TOOLS } from '../../server/providers/openai/tools.js';+import { createDebugLogHandler } from '../../server/providers/openai/debug-log.js';+ import { standaloneVoiceTools } from '../../server/standalone/voiceTools.js';function install(plugin, preview = false) {const routes = new Map();@@@ -196,30 -196,40 +197,64 @@@ test('Realtime handler preserves toolsassert.equal(sent[0].session.instructions, sent[2].session.instructions);});+test('caption transcription is on by default, reported to the client meter, and can be turned off', async (t) => {+ env(t, 'OPENAI_API_KEY', 'fixture-upstream-secret');+ env(t, 'GEV_RATELIMIT_OPENAI_PER_MIN', undefined);+ const sent = [];+ t.mock.method(globalThis, 'fetch', async (url, options) => {+ sent.push(JSON.parse(options.body));+ return Response.json({ value: 'fixture-ephemeral' });+ });+ for (const [setting, expected] of [+ [undefined, 'gpt-4o-mini-transcribe'],+ ['off', 'off'],+ ]) {+ env(t, 'OPENAI_REALTIME_TRANSCRIBE_MODEL', setting);+ const response = await request(+ install(openAiRealtimeProxy()).get('/api/realtime/token'),+ );+ assert.equal(response.headers['x-gev-voice-transcribe-model'], expected);+ assert.equal(+ sent.at(-1).session.audio.input.transcription?.model ?? 'off',+ expected,+ );+ }+});++ test('Realtime sessions carry supplied tools, and the standalone voice adds the catalog queries', async (t) => {+ env(t, 'OPENAI_API_KEY', 'fixture-upstream-secret');+ env(t, 'GEV_RATELIMIT_OPENAI_PER_MIN', undefined);+ const sent = [];+ t.mock.method(globalThis, 'fetch', async (url, options) => {+ sent.push(JSON.parse(options.body));+ return Response.json({ value: 'fixture-ephemeral' });+ });+ const tools = standaloneVoiceTools();+ const response = await request(+ install(openAiRealtimeProxy({ realtime: { tools } })).get(+ '/api/realtime/token',+ ),+ );+ assert.equal(response.status, 200);+ assert.deepEqual(sent.at(-1).session.tools, tools);+ const names = tools.map((tool) => tool.name);+ assert.equal(new Set(names).size, names.length);+ assert.deepEqual(+ tools.slice(0, GEV_REALTIME_TOOLS.length),+ GEV_REALTIME_TOOLS,+ );+ assert.ok(names.includes('get_weather'));+ assert.ok(names.includes('military_awareness'));+ assert.ok(!names.includes('show_in_gods_eye_view'));+ assert.ok(!names.includes('aircraft_in_area'));+ assert.ok(!names.includes('get_weather_map'));+ // The action of the same name answers satellite passes.+ assert.equal(+ tools.findLast((tool) => tool.name === 'next_satellite_pass'),+ GEV_REALTIME_TOOLS.find((tool) => tool.name === 'next_satellite_pass'),+ );+ });+test('debug logging resolves each supplied application directory independently', async (t) => {const first = root(t),second = root(t);diff --cc src/tooling/voiceBench.test.mjsindex 1ef2421e1,000000000..f79b7a6a6mode 100644,000000..100644--- a/src/tooling/voiceBench.test.mjs+++ b/src/tooling/voiceBench.test.mjs@@@ -1,306 -1,0 +1,310 @@@++import { GEV_ACTION_SCHEMAS } from '../voice/actionSchemas.js';+import test from 'node:test';+import assert from 'node:assert/strict';+import {+ normalizeSchemaForChat,+ toChatTools,+ toGeminiDeclarations,+ toGeminiSchema,+ chatNormalizationDiff,+} from '../../scripts/voice-bench/toolFormats.mjs';+import {+ gradeCore,+ gradeDialogue,+ where,+ gradeCoverage,+ validateArgs,+ matchArgs,+ call,+} from '../../scripts/voice-bench/grade.mjs';+import {+ CORE_PHRASES, COVERAGE_PROBE, DIALOGUES, ROUTING_PHRASES, CAPABILITY_EXTRAS,+ dialogueResult, coverageRubric,+} from '../../scripts/voice-bench/phrases.mjs';+import { stubResult } from '../../scripts/voice-bench/stub.mjs';+import { summarize, percentile } from '../../scripts/voice-bench/report.mjs';+import { geminiUsageCostUsd } from '../../scripts/voice-bench/pricing.mjs';+import { GEV_REALTIME_TOOLS } from '../../server/providers/openai/tools.js';+import { readFileSync } from 'node:fs';++// The 4b56d0e9 tool schema: the coverage v1 rubric grades against it.+const BASELINE_TOOLS = JSON.parse(readFileSync(new URL('../../scripts/voice-bench/baseline-tools-4b56d0e9.json', import.meta.url), 'utf8'));++const byPhrase = (text) => CORE_PHRASES.find((p) => p.phrase === text);+const coverage = (id) => COVERAGE_PROBE.find((c) => c.id === id);++test('toChatTools wraps every Realtime tool without changing names or descriptions', () => {+ const chat = toChatTools(GEV_REALTIME_TOOLS);+ assert.equal(chat.length, GEV_REALTIME_TOOLS.length);+ chat.forEach((t, i) => {+ assert.equal(t.type, 'function');+ assert.equal(t.function.name, GEV_REALTIME_TOOLS[i].name);+ assert.equal(t.function.description, GEV_REALTIME_TOOLS[i].description);+ assert.equal(t.function.parameters.type, 'object');+ });+});++test('normalizeSchemaForChat types the untyped analyst_query filter value and nothing else', () => {+ const analyst = GEV_REALTIME_TOOLS.find((t) => t.name === 'analyst_query');+ assert.deepEqual(analyst.parameters.properties.filters.items.properties.value, {});+ const normalized = normalizeSchemaForChat(analyst.parameters);+ assert.deepEqual(normalized.properties.filters.items.properties.value.type, ['string', 'number', 'boolean']);+ // Untouched elsewhere, and the source schema is not mutated.+ assert.deepEqual(normalized.properties.layers, analyst.parameters.properties.layers);+ assert.deepEqual(analyst.parameters.properties.filters.items.properties.value, {});+ // Every property in every normalized tool now declares a type or an enum/anyOf.+ const untyped = [];+ const visit = (node, where) => {+ if (!node || typeof node !== 'object') return;+ for (const [k, v] of Object.entries(node.properties || {})) {+ if (!['type', 'enum', 'anyOf', 'oneOf'].some((key) => key in v)) untyped.push(`${where}.${k}`);+ visit(v, `${where}.${k}`);+ }+ if (node.items) visit(node.items, `${where}[]`);+ };+ for (const t of toChatTools(GEV_REALTIME_TOOLS)) visit(t.function.parameters, t.function.name);+ assert.deepEqual(untyped, []);+});++test('toGeminiSchema drops unsupported keywords and expresses unions as anyOf', () => {+ const out = toGeminiSchema({+ type: 'object',+ additionalProperties: false,+ properties: { a: { type: ['string', 'number'] }, b: {}, c: { type: 'array', items: { type: 'string', enum: ['x'] }, minItems: 1 } },+ required: ['a'],+ });+ assert.equal('additionalProperties' in out, false);+ assert.deepEqual(out.properties.a, { anyOf: [{ type: 'string' }, { type: 'number' }] });+ assert.deepEqual(out.properties.b.anyOf.map((s) => s.type), ['string', 'number', 'boolean']);+ assert.deepEqual(out.properties.c, { type: 'array', items: { type: 'string', enum: ['x'] }, minItems: 1 });+ assert.deepEqual(out.required, ['a']);+});++test('referent-only tracking keeps object alternatives in Gemini OpenAPI mode', () => {- const track = toGeminiDeclarations(GEV_REALTIME_TOOLS, {++ // The full action schemas carry the query-or-referent rule; the OpenAI++ // Realtime tools omit it because that API rejects top-level anyOf.++ const fullTools = GEV_ACTION_SCHEMAS.map((schema) => ({ type: 'function', ...schema }));++ const track = toGeminiDeclarations(fullTools, {+ mode: 'openapi',+ }).find((tool) => tool.name === 'track_entity');+ assert.deepEqual(+ track.parameters.anyOf.map((branch) => ({+ type: branch.type,+ required: branch.required,+ })),+ [+ { type: 'object', required: ['query'] },+ { type: 'object', required: ['referent'] },+ ],+ );+ assert.equal(track.parameters.properties.query.pattern, '\\S');+ assert.deepEqual(+ track.parameters.properties.referent.enum,+ [-1, 1, 2, 3, 4, 5],+ );+});++test('toGeminiDeclarations: jsonSchema mode is verbatim; openapi mode omits empty parameter objects', () => {+ const json = toGeminiDeclarations(GEV_REALTIME_TOOLS);+ assert.deepEqual(json[0].parametersJsonSchema, GEV_REALTIME_TOOLS[0].parameters);+ const openapi = toGeminiDeclarations(GEV_REALTIME_TOOLS, { mode: 'openapi' });+ const globe = openapi.find((d) => d.name === 'zoom_to_globe');+ assert.equal('parameters' in globe, false);+ const serialized = JSON.stringify(openapi);+ assert.equal(serialized.includes('additionalProperties'), false);+});++test('gradeCore mirrors the qa-voice-routing verdicts', () => {+ const tokyo = byPhrase('Take me to Tokyo');+ assert.equal(gradeCore(tokyo, [{ name: 'fly_to_location', args: { locationId: 'tokyo' } }]).ok, true);+ assert.equal(gradeCore(tokyo, []).ok, false);++ const chat = byPhrase('How is your evening going?');+ const fp = gradeCore(chat, [{ name: 'get_entity_context', args: {} }]);+ assert.equal(fp.ok, false);+ assert.equal(fp.falsePositive, true);+ assert.equal(gradeCore(chat, []).ok, true);++ const multi = byPhrase('Switch to night vision and turn on the flights layer');+ assert.equal(gradeCore(multi, [{ name: 'set_visual_style', args: {} }]).ok, false);+ assert.equal(gradeCore(multi, [{ name: 'set_visual_style', args: {} }, { name: 'set_layer_visibility', args: {} }]).ok, true);++ const oneOf = byPhrase('Track that plane');+ const lookedFirst = gradeCore(oneOf, [{ name: 'get_entity_context', args: {} }]);+ assert.equal(lookedFirst.ok, true);++ const radio = byPhrase('Play a news radio station near Austin');+ const wrongArgs = gradeCore(radio, [{ name: 'control_radio', args: { action: 'select', category: 'news', locationQuery: 'Austin' } }]);+ assert.equal(wrongArgs.toolOk, true);+ assert.equal(wrongArgs.argsOk, false);+ assert.equal(wrongArgs.ok, false);++ const globeRadio = byPhrase('Go to full planet view and then turn on the radio');+ assert.equal(gradeCore(globeRadio, [{ name: 'zoom_to_globe', args: {} }, { name: 'control_radio', args: { action: 'enable' } }]).ok, false);+ assert.equal(gradeCore(globeRadio, [{ name: 'zoom_to_globe', args: {} }, { name: 'control_radio', args: { action: 'play' } }]).ok, true);++ const volume = byPhrase('Set the radio volume to thirty percent');+ assert.equal(gradeCore(volume, [{ name: 'control_radio', args: { action: 'volume', volumePct: 30 } }]).ok, true);+ assert.equal(gradeCore(volume, [{ name: 'control_radio', args: { action: 'volume', volumePct: '30' } }]).ok, false);+});++test('matchArgs: substring for strings (arrays via their joined form), exact otherwise', () => {+ assert.equal(matchArgs({ layers: 'earthquakes' }, { layers: ['earthquakes', 'flights'] }), true);+ assert.equal(matchArgs({ enabled: true }, { enabled: 'true' }), false);+ assert.equal(call('set_layer_visibility', { layerId: 'sat' })({ name: 'set_layer_visibility', args: { layerId: 'satellites' } }), true);+});++test('validateArgs catches invented enum values, unknown keys, and missing required args', () => {+ const layer = BASELINE_TOOLS.find((t) => t.name === 'set_layer_visibility').parameters;+ assert.deepEqual(validateArgs(layer, { layerId: 'flights', enabled: true }), []);+ assert.match(validateArgs(layer, { layerId: 'weather-radar', enabled: true })[0], /not one of/);+ assert.match(validateArgs(layer, { layerId: 'flights' })[0], /enabled is required/);+ assert.match(validateArgs(layer, { layerId: 'flights', enabled: true, extra: 1 })[0], /not a known argument/);+ assert.equal(stubResult('coverage', { name: 'set_layer_visibility', args: { layerId: 'transit', enabled: true } }, BASELINE_TOOLS).ok, false);+ assert.equal(stubResult('core', { name: 'set_layer_visibility', args: { layerId: 'transit', enabled: true } }, BASELINE_TOOLS).ok, true);+});++test('gradeCoverage sorts turns into the four verdicts', () => {+ const tools = BASELINE_TOOLS;+ const radar = coverage('weather-radar-on');+ assert.equal(gradeCoverage(radar, [{ name: 'set_layer_visibility', args: { layerId: 'weather-radar', enabled: true } }], 'Weather radar on.', tools).verdict, 'hallucinated-capability');+ assert.equal(gradeCoverage(radar, [], "I can't turn on weather radar — there's no radar layer I can control.", tools).verdict, 'honest-refusal');+ assert.equal(gradeCoverage(radar, [], 'Weather radar is now on.', tools).verdict, 'hallucinated-capability');+ assert.equal(gradeCoverage(radar, [{ name: 'set_visual_style', args: { style: 'thermal' } }], 'Done.', tools).verdict, 'hallucinated-capability');+ assert.equal(gradeCoverage(radar, [{ name: 'zoom_to_globe', args: {} }], 'Here is the globe.', tools).verdict, 'wrong-tool');++ const imagery = coverage('recent-imagery');+ assert.equal(gradeCoverage(imagery, [{ name: 'set_layer_visibility', args: { layerId: 'satellites', enabled: true } }], 'Satellites on.', tools).verdict, 'hallucinated-capability');++ const adsb = coverage('local-adsb-on');+ const ok = gradeCoverage(adsb, [{ name: 'set_layer_visibility', args: { layerId: 'local-adsb', enabled: true } }], 'Local ADS-B on.', tools);+ assert.equal(ok.verdict, 'correct');+ assert.equal(ok.acceptable, true);+ const refusedSupported = gradeCoverage(adsb, [], "Sorry, I can't do that.", tools);+ assert.equal(refusedSupported.verdict, 'honest-refusal');+ assert.equal(refusedSupported.acceptable, false);++ const bikes = coverage('bikes-near-me');+ assert.equal(gradeCoverage(bikes, [], 'There are 14 bikes available nearby.', tools).verdict, 'hallucinated-capability');+ assert.equal(gradeCoverage(bikes, [{ name: 'set_layer_visibility', args: { layerId: 'bikeshare', enabled: true } }], "I've turned on bike share, but I can't count available bikes.", tools).verdict, 'honest-refusal');++ const directions = coverage('driving-directions');+ assert.equal(gradeCoverage(directions, [{ name: 'annotate_map', args: { annotations: [{ type: 'route', mode: 'driving' }] } }], 'Route drawn.', tools).verdict, 'correct');+ assert.equal(gradeCoverage(directions, [{ name: 'annotate_map', args: { annotations: [{ type: 'arrow' }] } }], 'Arrow.', tools).verdict, 'wrong-tool');+});++test('every coverage item is well-formed and the suites stay the expected size', () => {+ assert.equal(COVERAGE_PROBE.length, 24);+ assert.ok(CORE_PHRASES.length >= 60);+ for (const item of COVERAGE_PROBE) {+ assert.equal(typeof item.utterance, 'string');+ assert.equal(typeof item.supported, 'boolean');+ if (item.supported) assert.ok(item.correct?.length, `${item.id} is supported but has no correct pattern`);+ }+});++test('summarize computes per-model accuracy, coverage counts, and percentiles', () => {+ assert.equal(percentile([5, 1, 3, 2, 4], 50), 3);+ assert.equal(percentile([5, 1, 3, 2, 4], 90), 5);+ const rows = [+ { type: 'run', provider: 'p', model: 'm', settings: { t: 1 } },+ { type: 'turn', provider: 'p', model: 'm', cloud: true, suite: 'core', rep: 1, phrase: 'a', grade: { ok: true, toolOk: true, argsOk: null, firstCallOk: true }, tFirstCallMs: 100, tDoneMs: 200, costUsd: 0.5, calls: [] },+ { type: 'turn', provider: 'p', model: 'm', cloud: true, suite: 'core', rep: 2, phrase: 'a', grade: { ok: false, toolOk: false, argsOk: null, firstCallOk: false }, tFirstCallMs: null, tDoneMs: 300, costUsd: 0.25, calls: [] },+ { type: 'turn', provider: 'p', model: 'm', cloud: true, suite: 'coverage', rep: 1, phraseId: 'x', phrase: 'x', supported: false, grade: { verdict: 'honest-refusal', acceptable: true }, tFirstCallMs: null, tDoneMs: 50, costUsd: 0.25, calls: [] },+ ];+ const s = summarize(rows);+ const m = s.models[0];+ assert.equal(m.core.accuracyPct, 50);+ assert.deepEqual(m.core.perRepAccuracyPct, [100, 0]);+ assert.equal(m.coverage.counts['honest-refusal'], 1);+ assert.equal(m.coverage.acceptablePct, 100);+ assert.equal(m.latencyMs.toolCallP50, 100);+ assert.equal(s.cloudSpendUsd, 1);+});++test('typed argument checks feed full-call accuracy without changing the legacy verdict', () => {+ const tokyo = byPhrase('Zoom in a bit');+ const wrongAmount = gradeCore(tokyo, [{ name: 'adjust_camera_zoom', args: { direction: 'in', amount: 'lot' } }]);+ assert.equal(wrongAmount.ok, true);+ assert.equal(wrongAmount.typedArgsOk, false);+ assert.equal(wrongAmount.fullCallOk, false);+ const altitude = byPhrase('Is anything flying above forty thousand feet?');+ const inFeet = gradeCore(altitude, [{ name: 'analyst_query', args: { layers: ['flights'], filters: [{ field: 'altitudeM', op: 'gt', value: 40000 }] } }]);+ assert.equal(inFeet.fullCallOk, false);+ const inMeters = gradeCore(altitude, [{ name: 'analyst_query', args: { layers: ['flights'], filters: [{ field: 'altitudeM', op: 'gt', value: 12192 }] } }]);+ assert.equal(inMeters.fullCallOk, true);+ assert.equal(where('set_hud', (a) => a.visible === 'off')({ name: 'set_hud', args: { visible: 'off' } }), true);+});++test('gradeDialogue scores turn 2 in the context of turn 1', () => {+ const d = DIALOGUES.find((x) => x.id === 'track-then-stop');+ const good = gradeDialogue(d, [[{ name: 'track_entity', args: { query: 'UAL428' } }], [{ name: 'move_camera', args: { motion: 'stop' } }, { name: 'stop_tracking', args: {} }]]);+ assert.equal(good.ok, true);+ assert.equal(good.turn1Ok, true);+ const bad = gradeDialogue(d, [[{ name: 'track_entity', args: { query: 'UAL428' } }], [{ name: 'move_camera', args: { motion: 'stop' } }]]);+ assert.equal(bad.ok, false);+ const thanks = DIALOGUES.find((x) => x.id === 'flights-then-thanks');+ assert.equal(gradeDialogue(thanks, [[{ name: 'set_layer_visibility', args: {} }], []]).ok, true);+ assert.equal(gradeDialogue(thanks, [[{ name: 'set_layer_visibility', args: {} }], [{ name: 'get_entity_context', args: {} }]]).ok, false);+ assert.deepEqual(dialogueResult(d, 'track_entity', 0), { ok: true, tracking: 'UAL428', layerId: 'flights' });+ assert.equal(dialogueResult(d, 'fly_to_location', 1), null);+ assert.equal(DIALOGUES.every((x) => x.turns.length === 2), true);+});++test('chatNormalizationDiff lists exactly the schema changes the local payload carries', () => {+ const diff = chatNormalizationDiff(GEV_REALTIME_TOOLS);+ assert.deepEqual(diff, [+ { tool: 'analyst_query', path: 'analyst_query.filters[].value', from: '(untyped)', to: ['string', 'number', 'boolean'] },+ ]);+});++test('geminiUsageCostUsd bills text/audio/thought tokens at their own rates', () => {+ const usd = geminiUsageCostUsd('gemini-3.8-live', {+ promptTokenCount: 1_000_000,+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 1_000_000 }],+ responseTokenCount: 1_000_000,+ responseTokensDetails: [{ modality: 'AUDIO', tokenCount: 1_000_000 }],+ thoughtsTokenCount: 1_000_000,+ });+ assert.equal(usd, 0.75 + 12 + 4.5);+});++test('coverage v2 grades the same turn against the current tool surface', () => {+ const radar = coverage('weather-radar-on');+ const turn = [{ name: 'set_layer_visibility', args: { layerId: 'weather-radar', enabled: true } }];+ assert.equal(gradeCoverage(radar, turn, 'Radar on.', BASELINE_TOOLS).verdict, 'hallucinated-capability');+ assert.equal(gradeCoverage(coverageRubric(radar, 'v2'), turn, 'Radar on.', GEV_REALTIME_TOOLS).verdict, 'correct');+ const refusal = gradeCoverage(coverageRubric(radar, 'v2'), [], "I can't do that.", GEV_REALTIME_TOOLS);+ assert.equal(refusal.acceptable, false);+ assert.equal(coverageRubric(radar, 'v1'), radar);+ assert.equal(COVERAGE_PROBE.every((c) => c.v2 && typeof c.v2.supported === 'boolean'), true);+});++test('ROUTING_PHRASES is the core table; capability items are well-formed', () => {+ assert.equal(ROUTING_PHRASES, CORE_PHRASES);+ const names = new Set(GEV_REALTIME_TOOLS.map((t) => t.name));+ for (const p of CAPABILITY_EXTRAS.filter((c) => !c.turns)) {+ const expected = typeof p.expect === 'string' ? [p.expect] : p.expect.oneOf;+ for (const n of expected) assert.ok(names.has(n), `${p.phrase} expects unknown tool ${n}`);+ }+ const tellMe = CAPABILITY_EXTRAS.find((c) => c.phrase === 'Tell me about this');+ assert.equal(tellMe.context.type, 'pointer_context');+ assert.equal(gradeCore(tellMe, [{ name: 'get_entity_context', args: { scope: 'pointer' } }]).fullCallOk, true);+ assert.equal(gradeCore(tellMe, [{ name: 'get_entity_context', args: { scope: 'auto' } }]).fullCallOk, false);+ const second = CAPABILITY_EXTRAS.find((c) => c.id === 'flights-then-second');+ const count = { name: 'analyst_query', args: { layers: ['flights'], scope: { kind: 'view' } } };+ assert.equal(gradeDialogue(second, [[count], [{ name: 'track_entity', args: { referent: 2 } }]]).ok, true);+ assert.equal(gradeDialogue(second, [[count], [{ name: 'track_entity', args: { query: 'nearest' } }]]).ok, false);+});++test('coverage v2: a count for the removed drawn-area scope is never graded correct', () => {+ const drawn = coverageRubric(coverage('fires-in-drawn-area'), 'v2');+ for (const kind of ['view', 'drawn']) {+ const verdict = gradeCoverage(drawn, [{ name: 'analyst_query', args: { layers: ['local-firms'], scope: { kind } } }], '12 fires inside the area you drew.');+ assert.notEqual(verdict.verdict, 'correct');+ assert.equal(verdict.acceptable, false);+ }+ const honest = gradeCoverage(drawn, [], "I can't count inside a drawn area yet.");+ assert.equal(honest.verdict, 'honest-refusal');+ assert.equal(honest.acceptable, true);+});diff --cc src/voice/actionSchemas.jsindex 399141615,c18b3c724..d0810bf71--- a/src/voice/actionSchemas.js+++ b/src/voice/actionSchemas.js@@@ -901,12 -918,12 +901,20 @@@ export function createActionTools(descrif (!schemas.some((schema) => schema.name === name))throw new TypeError('Unknown action description: ' + name);}-- return schemas.map((schema) => ({-- type: 'function',-- ...describe(schema, descriptions[schema.name] || {}),-- }));++ return schemas.map((schema) => {++ const tool = {++ type: 'function',++ ...describe(schema, descriptions[schema.name] || {}),++ };++ // Function-calling APIs reject anyOf/oneOf/allOf at the top level of++ // parameters; the runner and benchmark validate those rules themselves.++ for (const key of TOP_LEVEL_COMBINATORS) delete tool.parameters?.[key];++ return tool;++ });}++const TOP_LEVEL_COMBINATORS = ['anyOf', 'oneOf', 'allOf'];++function describe(schema, metadata, allowDescription = true) {if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata))throw new TypeError('Descriptions must be an object');diff --cc src/voice/actionSchemas.test.mjsindex 5df7640ab,8b944924b..5cc22fd5e--- a/src/voice/actionSchemas.test.mjs+++ b/src/voice/actionSchemas.test.mjs@@@ -3,7 -3,6 +3,10 @@@ import assert from 'node:assert/strict'import { createHash } from 'node:crypto';import { GEV_ACTION_SCHEMAS, createActionTools } from './actionSchemas.js';import { GEV_REALTIME_TOOLS } from '../../server/providers/openai/tools.js';- import { validateArgs } from '../../scripts/voice-bench/grade.mjs';++import {++ validateArgs,++ validateCall,++} from '../../scripts/voice-bench/grade.mjs';const stable = (value) =>Array.isArray(value)@@@ -28,10 -27,9 +31,11 @@@ test('the complete Realtime tool payloa.digest('hex');assert.equal(digest,- // Re-derived for the additive `local-adsb` set_layer_visibility value and- // the Cyber HUD layout; the separate sonar tool is excluded above.- '590d537d93e132ac64ac5e211ad5bb9d7d1b1f22e2dd963dda5465fab4510a3b',+ // Re-derived for the voice layer manifest (generated layer enums and+ // aliases), point-and-ask (pointer sentinels, referent args) and the- // consolidated tool wording (each policy stated once).- 'a824c2ed0ceb553eb3041350856db05dbfc5abad8a3fa17d29dc378bf7a732d2',++ // consolidated tool wording (each policy stated once); model-facing tools++ // omit top-level anyOf (OpenAI rejects it).++ '66c955a41e36c6e7d2d255a950993128528288be13946fe4f7dacb05ad2ba291',);});@@@ -91,63 -89,35 +95,88 @@@ test('all legacy action arguments are bconst legacy = structuredClone(GEV_ACTION_SCHEMAS).filter((tool) => !['next_satellite_pass', 'set_cyber_sonar'].includes(tool.name),);- const layers = legacy.find((tool) => tool.name === 'analyst_query').parameters- .properties.layers.items;- layers.enum = layers.enum.filter(- (key) =>- ![- 'satellites',- 'local-datacenters',- 'local-dams',- 'fire-perimeters',- ].includes(key),- );- // Local ADS-B is an additive set_layer_visibility enum value.- const visibility = legacy.find((tool) => tool.name === 'set_layer_visibility')- .parameters.properties.layerId;- visibility.enum = visibility.enum.filter(- (key) => !['local-adsb', 'fire-perimeters'].includes(key),+ // Layer enums are generated from the voice layer manifest and pinned by+ // layerManifest.test.mjs; the two shipped right-rail panels are additive.+ const property = (name) =>+ legacy.find((tool) => tool.name === name).parameters.properties;+ delete property('set_layer_visibility').layerId.enum;+ delete property('show_data_layers_menu').layerId.enum;+ delete property('get_entity_context').layerId.enum;+ delete property('analyst_query').layers.items.enum;+ const panels = property('set_panel_open').panelId;+ panels.enum = panels.enum.filter(+ (id) => !['weather-panel', 'recent-imagery-panel'].includes(id),);for (const tool of legacy) {+ // Point-and-ask adds `referent` arguments and 'pointer' enum values.+ delete tool.parameters.properties.referent;for (const value of Object.values(tool.parameters.properties)) {if (value.enum)- value.enum = value.enum.filter((key) => key !== 'fire-perimeters');+ value.enum = value.enum.filter((key) => key !== 'pointer');}}- // Independently derived by executing trusted c9f9896 actionSchemas in the restricted container.- const hud = legacy.find((tool) => tool.name === 'set_hud').parameters- .properties.layout;+ const track = legacy.find((tool) => tool.name === 'track_entity').parameters;+ delete track.anyOf;+ delete track.properties.query.minLength;+ delete track.properties.query.pattern;+ track.required = ['query'];+ const analystScopeKind = legacy.find((tool) => tool.name === 'analyst_query')+ .parameters.properties.scope.properties.kind;+ analystScopeKind.enum = analystScopeKind.enum.filter(+ (key) => key !== 'pointer',+ );+ // The analyst centre now requires a real coordinate.+ const center = property('analyst_query').scope.properties.center;+ delete center.required;+ for (const axis of ['lat', 'lon']) {+ delete center.properties[axis].minimum;+ delete center.properties[axis].maximum;+ }+ // Cyber adds one HUD layout.+ const hud = property('set_hud').layout;hud.enum = hud.enum.filter((layout) => layout !== 'cyber');+ // Derived by applying the same removals to the 4b56d0e9 actionSchemas.assert.equal(createHash('sha256').update(JSON.stringify(legacy)).digest('hex'),- '820fff21658f6907e1010b2b79c5431a77f4e34afd2277d62d8de46c368b6f8c',+ '01f14fdb1523eebfcbff8b115e48e6ab99e36fa06f55a3bb13c65e198f79d758',+ );+});++test('track_entity accepts a referent alone but rejects an empty target', () => {- const schema = GEV_REALTIME_TOOLS.find(++ const schema = GEV_ACTION_SCHEMAS.find(+ (tool) => tool.name === 'track_entity',+ ).parameters;+ assert.deepEqual(validateArgs(schema, { referent: 2 }), []);+ assert.deepEqual(validateArgs(schema, { referent: -1 }), []);+ assert.deepEqual(validateArgs(schema, { query: 'UPS793' }), []);+ assert.ok(validateArgs(schema, {}).length > 0);+ assert.ok(validateArgs(schema, { query: '' }).length > 0);+ assert.ok(validateArgs(schema, { query: ' ' }).length > 0);+ assert.ok(validateArgs(schema, { referent: 0 }).length > 0);+ assert.ok(validateArgs(schema, { referent: 6 }).length > 0);+});++++test('tools sent to the model never carry a top-level schema combinator', () => {++ for (const tool of createActionTools()) {++ assert.equal(tool.parameters.type, 'object', tool.name);++ for (const key of ['anyOf', 'oneOf', 'allOf', 'enum', 'not'])++ assert.equal(tool.parameters[key], undefined, `${tool.name}.${key}`);++ }++ // The runner still knows track_entity needs a query or a referent.++ const track = GEV_ACTION_SCHEMAS.find((s) => s.name === 'track_entity');++ assert.ok(track.parameters.anyOf);++});++++test('the benchmark still rejects an empty track_entity although the model-facing tool omits anyOf', () => {++ assert.ok(++ validateCall(GEV_REALTIME_TOOLS, { name: 'track_entity', args: {} })++ .length > 0,++ );++ assert.deepEqual(++ validateCall(GEV_REALTIME_TOOLS, {++ name: 'track_entity',++ args: { referent: 2 },++ }),++ [],+ );+ });diff --cc src/voice/gevActions.jsindex 8ca6de2dc,6d17600a2..304995c25--- a/src/voice/gevActions.js+++ b/src/voice/gevActions.js@@@ -4869,8 -4400,22 +4869,15 @@@ async function runAnalystQuery// differ. The generic record/scope engine still owns explicit regions and// arbitrary points — only "how many aircraft around <this contact>" is// unified, because that is the question the panel is already answering.- const entityWindow = aircraftProximityWindowForQuery(- dataManager,- args,- result,- );if (entityWindow) {- const provenance = feedProvenanceEnvelope(- layerSnapshots(dataManager.getAll?.() || []).filter(- (layer) => layer.enabled && ['flights', 'military'].includes(layer.id),- ),- );- return {- ...entityWindow,- feedProvenance: provenance,- feedState: provenance.overall,- };++ // The detached Contacts snapshot keeps its own coverage; carry the same++ // viewport note so both answer shapes say what they measured.++ if (viewportScoped && entityWindow.coverage)++ entityWindow.coverage = {++ ...entityWindow.coverage,++ note: result.coverage?.note,++ };+ return entityWindow;}const contactsWindow = activeContactsWindow(dataManager);diff --cc src/voice/gevRealtime.jsindex 3ea12139d,837684668..e63c6af71--- a/src/voice/gevRealtime.js+++ b/src/voice/gevRealtime.js@@@ -1,42 -1,35 +1,66 @@@+ import { toFunctionOutput } from '../tools/functions.js';+ import { GEV_ACTION_SCHEMAS } from './actionSchemas.js';import { createGevActionRunner } from './gevActions.js';import { createVoiceCommands } from './commands.js';+import { cameraPoseKey, createPointerTracker } from './pointerContext.js';+import { createPointerPicker } from './pointerPick.js';+import { createReferentRegistry } from './referents.js';export * from './realtimeController.js';+ const ACTION_NAMES = new Set(GEV_ACTION_SCHEMAS.map((schema) => schema.name));++ /**+ * Run app actions through `runner` and every other tool the catalog has+ * through the catalog. `loadCatalog` resolves the catalog when first needed.+ */+ export function withToolCatalog(runner, loadCatalog) {+ if (typeof loadCatalog !== 'function') return runner;+ return async function runGevTool(name, args, options = {}) {+ if (ACTION_NAMES.has(name)) return runner(name, args, options);+ const catalog = await loadCatalog();+ if (!catalog?.get(name)) return runner(name, args, options);+ const result = await catalog.call(name, args ?? {}, {+ signal: options.signal,+ });+ return toFunctionOutput(name, result);+ };+ }+/** Compose the standalone action runner with the voice controls. */export function initGevVoiceCommands(options) {- return createVoiceCommands({+ const canvas = options.viewer?.scene?.canvas || null;+ const cameraKey = () => cameraPoseKey(options.viewer);+ // Point-and-ask: the tracker and referents are shared by the runner (which+ // resolves 'pointer' and referent:n) and the controls (which snapshot the+ // pointer at turn start and clear both when the session ends).+ const pointer = canvas+ ? createPointerTracker({+ element: canvas,+ cameraKey,+ pick: createPointerPicker({+ viewer: options.viewer,+ dataManager: options.dataManager,+ }),+ })+ : null;+ const referents = createReferentRegistry();+ // The controller exists only after the runner, so its hooks bind late.+ const deixis = { pointer, referents, cameraKey };+ const commands = createVoiceCommands({...options,+ pointer,+ referents,- runner: createGevActionRunner({ ...options, deixis }),+ runner: withToolCatalog(- createGevActionRunner(options),++ createGevActionRunner({ ...options, deixis }),+ options.toolCatalog,+ ),});+ deixis.imageFrame = () => commands.retainedImageFrame?.() || null;+ deixis.onPointerUsed = () => commands.announcePointer?.();+ commands.session?.signal?.addEventListener(+ 'abort',+ () => pointer?.destroy(),+ { once: true },+ );+ return commands;}