Skip to content

A spy satellite simulator in your browser, except the data is real. Live open source spatial intelligence on a photorealistic 3D globe.

refactor(agent): preserve compact voice contract in World Packet extraction

Kevin Rajancefbad3c2a16
diff --cc changelog.d/880-world-packet-boundary.md
index 000000000,000000000..f1bedb614
new file mode 100644
--- /dev/null
+++ b/changelog.d/880-world-packet-boundary.md
@@@ -1,0 -1,0 +1,6 @@@
++- Extract a reusable model-free World Packet from the existing voice
++ `get_current_view_state` owner without restoring disabled layers to the
++ model context. Keep the enabled-only payload, disabled-layer count, source
++ provenance, action result and view-state contract; read the layer roster once
++ per packet. The semantic fingerprint is for change detection, not authority.
++ Credits: original GEV voice/layer contributors and #880 implementation.
diff --cc package.json
index 0a299b51d,99e35c0c5..a6396db73
--- a/package.json
+++ b/package.json
@@@ -251,6 -266,17 +266,18 @@@
"./layers/transit/source": "./src/layers/transit/source.js",
"./sources/transit-service": "./src/sources/transitService.js",
"./sources/map-features": "./src/sources/overpassFeatures.js",
+ "./server/providers/mapillary": {
+ "node": "./server/providers/mapillary.js"
+ },
+ "./layers/street-level": "./src/layers/streetLevel/index.js",
+ "./layers/street-level/mapillary": "./src/layers/streetLevel/providers/mapillary/index.js",
+ "./layers/street-level/mapillary/source": "./src/layers/streetLevel/providers/mapillary/source.js",
+ "./layers/street-level/google": "./src/layers/streetLevel/providers/google/index.js",
+ "./tools": "./src/tools/index.js",
+ "./tools/mcp": "./src/tools/mcp/index.js",
+ "./tools/panel": "./src/tools/panel.js",
+ "./tools/services": "./src/tools/services.js",
- "./view": "./src/view/index.js"
++ "./view": "./src/view/index.js",
+ "./agent/world-packet": "./src/agent/worldPacket.js"
}
}
diff --cc scripts/format-scope.json
index cd836a5cb,8bcc4c04d..bc2e49b2a
--- a/scripts/format-scope.json
+++ b/scripts/format-scope.json
@@@ -603,6 -635,6 +635,7 @@@
"src/voice/control.js",
"src/voice/realtimeBackend.js",
"src/voice/realtimeBackend.test.mjs",
++ "src/agent/worldPacket.test.mjs",
"src/voice/layerSummary.js",
"build/application-html.js",
"src/app/sourceSlot.js",
diff --cc scripts/package-boundaries.json
index fa4f872a4,40090ba19..aa45274d8
--- a/scripts/package-boundaries.json
+++ b/scripts/package-boundaries.json
@@@ -1851,9 -2206,18 +2206,19 @@@
"src/voice/commands.js",
"src/voice/control.js",
"src/voice/gevActions.js",
+ "src/agent/worldPacket.js",
+ "src/voice/speech.js",
+ "src/ui/layerNames.js",
+ "src/voice/earcon.js",
+ "src/voice/narration.js",
+ "src/voice/turnMetrics.js",
+ "src/voice/speechLint.js",
+ "src/voice/voiceCard.js",
+ "src/voice/voiceCardPresentation.js",
+ "src/voice/resultDisplay.js",
"src/voice/gevRealtime.js",
"src/voice/layerSummary.js",
+ "src/voice/cloudVoiceAuth.js",
"src/voice/realtimeBackend.js",
"src/voice/realtimeController.js",
"src/voice/voiceCost.js",
@@@ -3074,16 -3744,185 +3745,197 @@@
],
"external": []
},
+ "tools": {
+ "exports": ["./tools"],
+ "modules": [
+ "src/tools/index.js",
+ "src/tools/catalog.js",
+ "src/tools/schema.js",
+ "src/tools/area.js",
+ "src/tools/results.js",
+ "src/tools/places.js",
+ "src/tools/queries/hazards.js",
+ "src/tools/queries/space.js",
+ "src/tools/queries/aviation.js",
+ "src/tools/queries/media.js",
+ "src/tools/queries/places.js",
+ "src/tools/queries/mobility.js",
+ "src/tools/queries/environment.js",
+ "src/tools/queries/brief.js",
+ "src/tools/queries/maritime.js",
+ "src/tools/queries/share.js",
+ "src/data/idSwitches.js",
+ "src/data/layerState.js",
+ "src/data/layerStateTokenReservations.json",
+ "src/sources/gbfsStations.js",
+ "src/sources/tle.js",
+ "src/data/satellitePass.js",
+ "src/tools/queries/atmosphere.js",
+ "src/layers/wind/inspection.js",
+ "src/layers/wind/model.js",
+ "src/layers/wind/fields.js",
+ "src/i18n/marker.js",
+ "src/tools/queries/imagery.js",
+ "src/tools/queries/cables.js",
+ "src/tools/queries/surveillance.js",
+ "src/tools/queries/infrastructure.js",
+ "src/tools/queries/events.js",
+ "src/data/bhoteKoshiFloodPath.js",
+ "src/tools/functions.js",
+ "src/tools/surfaces.js",
+ "src/layers/transit/policy.js",
+ "src/data/transitFeeds.js",
+ "src/layers/transit/movement.js",
+ "src/data/contactPlayback.js",
+ "src/data/layerSnapshot.js",
+ "src/data/feedState.js",
+ "src/loadingFeedback.js",
+ "src/data/installationFeedback.js",
+ "src/view/index.js",
+ "src/tools/views.js",
+ "src/tools/globePanel.js",
+ "src/tools/queries/panelRequest.js"
+ ],
+ "external": ["satellite.js"]
+ },
+ "tools-mcp": {
+ "exports": ["./tools/mcp"],
+ "modules": [
+ "src/tools/mcp/index.js",
+ "src/tools/mcp/protocol.js",
+ "src/tools/mcp/http.js",
+ "src/tools/catalog.js",
+ "src/tools/schema.js"
+ ],
+ "external": []
+ },
+ "tools-panel": {
+ "exports": ["./tools/panel"],
+ "modules": [
+ "src/tools/panel.js",
+ "src/tools/globePanel.js",
+ "src/app/globePanelRuntime.js"
+ ],
+ "external": []
+ },
+ "tools-services": {
+ "exports": ["./tools/services"],
+ "modules": [
+ "src/tools/services.js",
+ "src/layers/bikeshare/registry.js",
+ "src/layers/bikeshare/source.js",
+ "src/layers/cctv/source.js",
+ "src/layers/cctv/sourcePolicy.js",
+ "src/layers/cyclones/source.js",
+ "src/sources/httpBody.js",
+ "src/i18n/marker.js",
+ "src/layers/earthquakes/source.js",
+ "src/layers/earthquakes/records.js",
+ "src/layers/firms/source.js",
+ "src/layers/installations/source.js",
+ "src/sources/requestDeadline.js",
+ "src/data/militaryNames.js",
+ "src/sources/militaryTileGeometry.js",
+ "src/data/bundledJson.js",
+ "src/data/retryableLoad.js",
+ "src/data/local_data/osm_military_names/names.json",
+ "src/sources/openFreeMap.js",
+ "src/data/installationNames.js",
+ "src/sources/vectorTiles.js",
+ "src/sources/phaseTiming.js",
+ "src/data/tomtomTiles.js",
+ "src/sources/capability.js",
+ "src/data/militaryInstallationData.js",
+ "src/layers/launches/source.js",
+ "src/layers/perimeters/source.js",
+ "src/layers/radio/source.js",
+ "src/layers/radio/policy.js",
+ "src/layers/satellites/source.js",
+ "src/layers/traffic/source.js",
+ "src/layers/traffic/roadModes.js",
+ "src/data/flowMatch.js",
+ "src/layers/traffic/flowSource.js",
+ "src/layers/traffic/flowDecode.js",
+ "src/sources/overpassRoads.js",
+ "src/layers/transit/source.js",
+ "src/sources/transitHistory.js",
+ "src/services/requests.js",
+ "src/sources/overpassFeatures.js",
+ "src/sources/featureSource.js",
+ "src/sources/overpassFeaturesRecords.js",
+ "src/sources/featureGeometry.js",
+ "src/sources/live/standalone.js",
+ "src/sources/live/contract.js",
+ "src/data/aircraftEmergency.js",
+ "src/sources/live/aircraft.js",
+ "src/sources/live/vessels.js",
+ "src/tools/places.js",
+ "src/tools/catalog.js",
+ "src/tools/schema.js",
+ "src/layers/weather/source.js",
+ "src/layers/wind/source.js",
+ "src/sources/windBody.js",
+ "src/layers/wind/fields.js",
+ "src/layers/wind/model.js",
+ "src/layers/recentImagery/catalog.js",
+ "src/layers/recentImagery/model.js",
+ "src/layers/submarineCables/bundledSource.js",
+ "src/layers/alpr/source.js",
+ "src/layers/alpr/policy.js",
+ "src/layers/alpr/records.js",
+ "src/layers/alpr/tileRecords.js",
+ "src/sources/infrastructureData.js",
+ "src/sources/eventPacks.js"
+ ],
+ "external": ["@mapbox/vector-tile", "pbf"]
+ },
+ "view": {
+ "exports": ["./view"],
+ "modules": [
+ "src/view/index.js",
+ "src/data/idSwitches.js",
+ "src/data/layerState.js",
+ "src/data/layerStateTokenReservations.json"
+ ],
+ "external": []
+ },
+ "air-quality": {
+ "exports": ["./layers/air-quality"],
+ "modules": [
+ "src/layers/airQuality/index.js",
+ "src/layers/airQuality/model.js",
+ "src/layers/airQuality/source.js",
+ "src/sources/httpBody.js",
+ "src/i18n/marker.js",
+ "src/i18n/index.js",
+ "src/i18n/locale.js",
+ "src/i18n/locales/es.json",
+ "src/i18n/locales/ru.json",
+ "src/ui/statusText.js",
+ "src/ui/layerNames.js"
+ ],
+ "external": ["cesium"]
+ },
+ "air-quality-source": {
+ "exports": ["./layers/air-quality/source"],
+ "modules": [
+ "src/layers/airQuality/model.js",
+ "src/layers/airQuality/source.js",
+ "src/sources/httpBody.js",
+ "src/i18n/marker.js"
+ ],
+ "external": []
++ },
+ "agent-world-packet": {
+ "exports": ["./agent/world-packet"],
+ "modules": [
+ "src/agent/worldPacket.js",
+ "src/data/layerSnapshot.js",
+ "src/data/feedState.js",
+ "src/contextModePolicy.js",
+ "src/loadingFeedback.js",
+ "src/data/installationFeedback.js"
+ ],
+ "external": ["cesium"]
}
}
diff --cc src/agent/worldPacket.js
index e8c522caa,000000000..7315656b6
mode 100644,000000..100644
--- a/src/agent/worldPacket.js
+++ b/src/agent/worldPacket.js
@@@ -1,180 -1,0 +1,197 @@@
+import * as Cesium from 'cesium';
+import {
+ feedProvenanceEnvelope,
++ layerSnapshot,
+ layerSnapshots,
- viewStateLayerRow,
+} from '../data/layerSnapshot.js';
+import { contextModeWord } from '../contextModePolicy.js';
+
+const TRACKABLE_FAMILIES = Object.freeze([
+ { layerId: 'flights', kind: 'aircraft' },
+ { layerId: 'military', kind: 'aircraft' },
+ { layerId: 'ais-live-vessels', kind: 'vessel' },
+ { layerId: 'satellites', kind: 'satellite' },
+]);
+
+const CONTEXT_MODE_RESULT_FIELDS = Object.freeze([
+ { field: 'mode', emptyAs: 'off' },
+ { field: 'entering', emptyAs: null },
+ { field: 'priorMode', emptyAs: null },
+]);
+
+const NESTED_CONTEXT_RESULT_FIELDS = Object.freeze([
+ 'context',
+ 'contextRollback',
+]);
+
+const NON_SEMANTIC_PACKET_KEYS = new Set(['note', 'ageLabel', 'generatedAt']);
+
+function semanticPacketValue(value) {
+ if (Array.isArray(value)) return value.map(semanticPacketValue);
+ if (!value || typeof value !== 'object') return value;
+ const out = {};
+ for (const key of Object.keys(value).sort()) {
+ if (NON_SEMANTIC_PACKET_KEYS.has(key)) continue;
+ out[key] = semanticPacketValue(value[key]);
+ }
+ return out;
+}
+
+/**
+ * Stable semantic fingerprint for change detection, not authentication.
+ *
+ * Presentation-only narration/age labels are excluded. Feed state, source,
+ * lastUpdate, camera, context, tracked entities, and other semantic state stay
+ * inside the digest.
+ */
+export function semanticWorldPacketFingerprint(packet) {
+ const canonical = JSON.stringify(semanticPacketValue(packet));
+ let hash = 0xcbf29ce484222325n;
+ const prime = 0x100000001b3n;
+ for (let i = 0; i < canonical.length; i += 1) {
+ hash ^= BigInt(canonical.charCodeAt(i));
+ hash = BigInt.asUintN(64, hash * prime);
+ }
+ return `fnv1a64:${hash.toString(16).padStart(16, '0')}`;
+}
+
+/**
+ * Translate context-mode payloads into the public tool vocabulary while
+ * retaining the internal id beside each translated field.
+ */
+export function withContextModeVocabulary(state) {
+ if (!state || typeof state !== 'object') return state;
+ let out = state;
+ const mutable = () => {
+ if (out === state) out = { ...state };
+ return out;
+ };
+ for (const { field, emptyAs } of CONTEXT_MODE_RESULT_FIELDS) {
+ if (!(field in state)) continue;
+ const internal = state[field] ?? null;
+ const target = mutable();
+ target[field] = contextModeWord(internal, { emptyAs });
+ target[`${field}Internal`] = internal;
+ }
+ for (const field of NESTED_CONTEXT_RESULT_FIELDS) {
+ const nested = state[field];
+ if (!nested || typeof nested !== 'object') continue;
+ const translated = withContextModeVocabulary(nested);
+ if (translated !== nested) mutable()[field] = translated;
+ }
+ return out;
+}
+
+/** Read tracked entities from their canonical layer owners. */
+export function collectTrackedEntities(dataManager) {
+ const tracked = [];
+ for (const family of TRACKABLE_FAMILIES) {
+ const module = dataManager?.layers?.get(family.layerId)?.module;
+ if (!module) continue;
+ try {
+ const info =
+ family.kind === 'vessel'
+ ? module.getSelectedInfo?.()
+ : module.getTrackedInfo?.();
+ if (info)
+ tracked.push({
+ kind: family.kind,
+ layerId: family.layerId,
+ ...info,
+ });
+ } catch {
+ // A not-yet-ready layer contributes no tracked observation.
+ }
+ }
+ return tracked;
+}
+
+/** Read the active Contacts window from its owning awareness layer. */
+export function activeContactsWindow(dataManager) {
+ try {
+ const layer = dataManager?.layers?.get('military-awareness')?.module;
+ return (
+ layer?.contactsWindowFromSnapshot?.(layer.getContextSnapshot?.()) ?? null
+ );
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Build the model-free fast World Packet from existing application owners.
+ *
+ * This performs no network requests and intentionally mirrors the historical
+ * get_current_view_state payload so voice can delegate without behavior drift.
+ */
+export function getWorldPacket({
+ viewer,
+ styleManager,
+ dataManager,
+ sceneDirector = null,
+ now = Date.now(),
+} = {}) {
+ if (!viewer?.camera?.positionWC)
+ throw new TypeError('World Packet requires a viewer camera');
+ if (!dataManager || typeof dataManager.getAll !== 'function')
+ throw new TypeError('World Packet requires a data manager');
+
+ const cartographic = Cesium.Cartographic.fromCartesian(
+ viewer.camera.positionWC,
+ );
++ // Read the roster once. Voice must not rewalk disabled layers: preserving the
++ // current enabled-only view keeps the model's context budget bounded.
+ const rows = dataManager.getAll();
++ const enabledRows = rows.filter((layer) => layer.enabled);
+ const contactsWindow = activeContactsWindow(dataManager);
+ const contextState =
+ typeof styleManager?.getContextModeState === 'function'
+ ? withContextModeVocabulary(styleManager.getContextModeState())
+ : null;
+
+ return {
+ ok: true,
+ action: 'get_current_view_state',
+ camera: {
+ latitude: Cesium.Math.toDegrees(cartographic.latitude),
+ longitude: Cesium.Math.toDegrees(cartographic.longitude),
+ heightM: cartographic.height,
+ },
+ style: styleManager?.activeStyle || 'normal',
+ context: contextState
+ ? {
+ ...contextState,
+ ...(contactsWindow ? { contactsWindow } : {}),
+ }
+ : null,
+ cockpit:
+ typeof styleManager?.getCockpitState === 'function'
+ ? styleManager.getCockpitState()
+ : null,
+ controls:
+ typeof styleManager?.getControlState === 'function'
+ ? styleManager.getControlState()
+ : null,
+ scenePlayback: sceneDirector?.getPlaybackStatus?.() || null,
+ tracked: collectTrackedEntities(dataManager),
- layers: rows.map((layer) => viewStateLayerRow(layer, { now })),
++ disabledLayerCount: rows.length - enabledRows.length,
++ // Preserve get_current_view_state's existing compact enabled-only shape.
++ layers: enabledRows.map((layer) => {
++ const snapshot = layerSnapshot(layer, { now });
++ return {
++ id: layer.id,
++ name: layer.name,
++ enabled: layer.enabled,
++ count: layer.stats?.count || 0,
++ error: layer.stats?.error || null,
++ feedState: snapshot.feedState,
++ source: snapshot.source,
++ lastUpdate: snapshot.lastUpdate,
++ };
++ }),
+ feedProvenance: feedProvenanceEnvelope(
+ layerSnapshots(rows, { now }).filter((layer) => layer.enabled),
+ { now },
+ ),
+ };
+}
diff --cc src/agent/worldPacket.test.mjs
index 9d9e0bd7d,000000000..76c41400a
mode 100644,000000..100644
--- a/src/agent/worldPacket.test.mjs
+++ b/src/agent/worldPacket.test.mjs
@@@ -1,110 -1,0 +1,152 @@@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import * as Cesium from 'cesium';
+
+import {
+ getWorldPacket,
+ semanticWorldPacketFingerprint,
+} from './worldPacket.js';
+import { createGevActionRunner } from '../voice/gevActions.js';
+
+function harness() {
+ const position = Cesium.Cartesian3.fromDegrees(-97.74, 30.26, 500);
+ const viewer = {
+ trackedEntity: undefined,
+ clock: { onTick: { addEventListener: () => () => {} } },
+ scene: {
+ canvas: {
+ clientWidth: 1200,
+ clientHeight: 800,
+ addEventListener() {},
+ removeEventListener() {},
+ },
+ globe: { getHeight: () => 0 },
+ tweens: [],
+ },
+ camera: {
+ positionWC: position,
+ positionCartographic: Cesium.Cartographic.fromCartesian(position),
+ heading: 0,
+ pitch: Cesium.Math.toRadians(-45),
+ moveEnd: { addEventListener: () => () => {} },
+ cancelFlight() {},
+ lookAtTransform() {},
+ },
+ };
+ const rows = [
+ {
+ id: 'traffic',
+ name: 'Traffic',
+ enabled: true,
+ stats: {
+ count: 3,
+ source: 'fixture',
+ lastUpdate: null,
+ },
+ },
+ ];
+ const dataManager = {
+ layers: new Map([['traffic', { module: null }]]),
+ getAll: () => rows,
+ };
+ const styleManager = {
+ activeStyle: 'normal',
+ getContextModeState: () => ({ mode: 'flights' }),
+ getCockpitState: () => null,
+ getControlState: () => ({ hud: { visible: 'auto' } }),
+ };
+ return { viewer, dataManager, styleManager };
+}
+
+test('World Packet preserves get_current_view_state parity', async () => {
+ const { viewer, dataManager, styleManager } = harness();
+ const packet = getWorldPacket({ viewer, dataManager, styleManager });
+ const runner = createGevActionRunner({ viewer, dataManager, styleManager });
+ const voice = await runner('get_current_view_state');
+
+ assert.deepEqual(voice, packet);
+ assert.equal(packet.context.mode, 'contacts');
+ assert.equal(packet.context.modeInternal, 'flights');
+ assert.equal(packet.layers[0].feedState, 'nominal');
+ assert.equal(packet.feedProvenance.overall, 'nominal');
+});
+
+test('World Packet keeps stale/unavailable feed semantics distinct from empty', () => {
+ const { viewer, dataManager, styleManager } = harness();
+ dataManager.getAll = () => [
+ {
+ id: 'traffic',
+ name: 'Traffic',
+ enabled: true,
+ stats: {
+ count: 0,
+ source: 'fixture',
+ error: 'fixture unavailable',
+ lastUpdate: null,
+ },
+ },
+ ];
+
+ const packet = getWorldPacket({ viewer, dataManager, styleManager });
+ assert.equal(packet.layers[0].count, 0);
+ assert.notEqual(packet.layers[0].feedState, 'nominal');
+ assert.notEqual(packet.feedProvenance.overall, 'nominal');
+ assert.match(packet.feedProvenance.note, /fixture unavailable/i);
+});
+
-
+test('semantic fingerprint ignores narration prose but changes with observed state', () => {
+ const { viewer, dataManager, styleManager } = harness();
+ const packet = getWorldPacket({ viewer, dataManager, styleManager });
+ const original = semanticWorldPacketFingerprint(packet);
+
+ const proseOnly = structuredClone(packet);
+ proseOnly.feedProvenance.note = 'different generated narration';
+ assert.equal(semanticWorldPacketFingerprint(proseOnly), original);
+
+ const changed = structuredClone(packet);
+ changed.layers[0].count += 1;
+ assert.notEqual(semanticWorldPacketFingerprint(changed), original);
+});
++
++// The 2026-10 main voice contract omits disabled layers from the model payload.
++test('World Packet and voice preserve enabled-only payload and count disabled layers', async () => {
++ const { viewer, dataManager, styleManager } = harness();
++ const rows = dataManager.getAll();
++ rows.push({
++ id: 'earthquakes',
++ name: 'Earthquakes',
++ enabled: false,
++ stats: { count: 99, source: 'fixture', error: 'stale' },
++ });
++ let reads = 0;
++ dataManager.getAll = () => {
++ reads += 1;
++ return rows;
++ };
++ const packet = getWorldPacket({ viewer, dataManager, styleManager });
++ assert.equal(reads, 1, 'collect the roster once rather than repeatedly');
++ assert.equal(packet.disabledLayerCount, 1);
++ assert.deepEqual(packet.layers.map((layer) => layer.id), ['traffic']);
++ assert.equal(packet.feedProvenance.overall, 'nominal');
++
++ const runner = createGevActionRunner({ viewer, dataManager, styleManager });
++ const voice = await runner('get_current_view_state');
++ assert.deepEqual(voice, packet);
++});
++
++test('World Packet fingerprints distinguish enabled state but ignore narrative churn', () => {
++ const { viewer, dataManager, styleManager } = harness();
++ const first = getWorldPacket({ viewer, dataManager, styleManager });
++ const prose = structuredClone(first);
++ prose.feedProvenance.note = 'new narration only';
++ assert.equal(
++ semanticWorldPacketFingerprint(first),
++ semanticWorldPacketFingerprint(prose),
++ );
++ const hidden = structuredClone(first);
++ hidden.disabledLayerCount += 1;
++ assert.notEqual(
++ semanticWorldPacketFingerprint(first),
++ semanticWorldPacketFingerprint(hidden),
++ );
++});