> This is the Markdown version of the page. For the complete Lattice Developers documentation index, fetch https://developer.anduril.com/llms.txt. Append .md to any page URL for its clean Markdown.

# Cue and monitor

> Fetch, stream, and filter entities to follow a target track from an effector

Effectors, such as interceptors, jammers, and other weapons systems, act on tracks that other
sensors publish to Lattice. A typical engagement has two phases:

* **Cue**: The effector receives the entity ID of a target track, for example from a task or an operator's selection.
* **Monitor**: Until the engagement ends, the effector follows that track's newest position and velocity, and reacts when the track disappears.

This page shows how to get a single entity, how to stream entity events, and how to filter a stream
down to exactly the tracks an effector cares about. The examples use the following APIs:

* [`GetEntity`](/reference/rest/entities/get-entity): Retrieves the current state of one entity.
* [`StreamEntities`](/reference/rest/entities/stream-entities): Opens a persistent stream of entity events over REST, which you can filter on the server.
* [`StreamEntityComponents`](/reference/grpc/anduril-entitymanager-v-1/entity-manager-api/anduril-entitymanager-v-1-stream-entity-components): Opens the same filtered stream over gRPC, with optional per-entity rate limits.

## Before you begin

* To get and stream entities, [set up the Lattice SDK](/guides/getting-started/set-up) and set up a Lattice environment.
* Publish your effector as an asset, so operators can see and task it. For more information, see [Create an asset](/guides/entities/create-an-asset).
* Learn how tracks carry position and velocity in [Create a track](/guides/entities/create-a-track).

> **gRPC authentication**
>
> These gRPC examples authenticate with a static environment token attached as request metadata.
> If you are using OAuth 2.0 client credentials instead, [set up the token refresh module](/guides/getting-started/authenticate#client-credentials) before running the examples on this page.

## Get an entity

When an effector is cued, it first needs the target's current state. Use the
[`GetEntity`](/reference/rest/entities/get-entity) API method with the target's
[`entity_id`](/reference/rest/entities/publish-entity#request.body.entityId) to retrieve a snapshot
of the entity:

#### Get the entity ID

The entity ID usually arrives with the cue, such as in a task's specification. To find an
entity ID manually, open the Lattice UI, find the entity in the Entity Explorer, and copy
its ID from the **Entity ID** column:

![Shows the Entity Explorer in the Lattice Developer Console.](/_fern-files/_img/72c242c7f0277f5a308bd2efb784cfcd9675f4dab9d1790bd9b195c6df74c7d0.webp)

#### Get the entity object

Replace `<ENTITY_ID>` in the following example with the entity ID, then run the example to
retrieve the entity from Lattice:

```go title={"Go (REST)"} startLine={35} maxLines={20}
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"time"

	Lattice "github.com/anduril/lattice-sdk-go/v5"
	"github.com/anduril/lattice-sdk-go/v5/client"
	"github.com/anduril/lattice-sdk-go/v5/option"
)

func main() {
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		fmt.Println("Missing required environment variables")
		os.Exit(1)
	}

	headers := http.Header{}
	headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))

	LatticeClient := client.NewClient(
		option.WithToken(environmentToken),
		option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
		option.WithHTTPHeader(headers),
	)

	for {
		ctx := context.Background()
		entity, err := LatticeClient.Entities.GetEntity(ctx, &Lattice.GetEntityRequest{EntityID: "<ENTITY_ID>"})
		if err != nil {
			fmt.Printf("Error fetching entity: %v\n", err)
		} else {
			name := "<none>"
			if n := entity.GetAliases().GetName(); n != nil {
				name = *n
			}
			location := "<none>"
			pos := entity.GetLocation().GetPosition()
			if pos != nil && pos.GetLatitudeDegrees() != nil && pos.GetLongitudeDegrees() != nil {
				location = fmt.Sprintf("%f, %f", *pos.GetLatitudeDegrees(), *pos.GetLongitudeDegrees())
			}
			fmt.Printf("Asset name     | %s\n", name)
			fmt.Printf("Asset location | %s\n", location)
		}
		time.Sleep(5 * time.Second)
	}
}

```

```java title={"Java (REST)"} startLine={28} maxLines={15}
package org.example;
import com.anduril.Lattice;
import com.anduril.types.Entity;
import java.time.LocalDateTime;

public class GetEntityEnvToken {
    private static final String ENTITY_ID = "<ENTITY_ID>";

    public static void main(String[] args) {
        String endpoint = System.getenv("LATTICE_ENDPOINT");
        String environmentToken = System.getenv("ENVIRONMENT_TOKEN");
        // Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
        String sandboxesToken = System.getenv("SANDBOXES_TOKEN");

        if (endpoint == null || environmentToken == null || sandboxesToken == null) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        try {
            Lattice client = Lattice.builder()
                .url(endpoint)
                .token(environmentToken)
                .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
                .build();

            while (true) {
                try {
                    Entity entity = client.entities().getEntity(ENTITY_ID);
                    System.out.println("Timestamp: " + LocalDateTime.now());
                    System.out.println("Asset name: " + entity.getAliases());
                    if (entity.getLocation() != null) {
                        System.out.println("Location: " + entity.getLocation());
                    }
                    System.out.println("---------------");
                    Thread.sleep(5000);
                } catch (Exception e) {
                    System.err.println("Error: " + e.getMessage());
                    Thread.sleep(10000);
                }
            }
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
    }
}

```

```py title={"Python (REST)"} startLine={21} maxLines={9}
from anduril import Lattice
import asyncio
import os
import sys

lattice_endpoint = os.getenv('LATTICE_ENDPOINT')
environment_token = os.getenv('ENVIRONMENT_TOKEN')

# Remove sandboxes_token from the following statements if you are not developing on Sandboxes.
sandboxes_token = os.getenv('SANDBOXES_TOKEN')
if not environment_token or not lattice_endpoint or not sandboxes_token:
    print("Missing required environment variables.")
    sys.exit(1)

client = Lattice(
    base_url=f"https://{lattice_endpoint}",
    token=lambda: str(environment_token),
    headers={ "anduril-sandbox-authorization": f"Bearer {sandboxes_token}" }
)

async def app(entity_id):
    try:
        while(True):
            entity = client.entities.get_entity(entity_id=entity_id)
            if entity.aliases:
                print(f"Asset name     | {entity.aliases.name}")
            if entity.location and entity.location.position:
                print(f"Asset location | {entity.location.position.latitude_degrees}, {entity.location.position.longitude_degrees}")
            await asyncio.sleep(5)
    except (asyncio.CancelledError, KeyboardInterrupt):
        print(">>>Exiting...")
    except Exception as error:
        print(f"Exception: {error}")

if __name__ == "__main__":
    asyncio.run(app("<ENTITY_ID>"))

```

```ts title={"TypeScript (REST)"} startLine={17} maxLines={18}
import { LatticeClient } from "@anduril-industries/lattice-sdk";

const latticeEndpoint = process.env.LATTICE_ENDPOINT;
const environmentToken = process.env.ENVIRONMENT_TOKEN;
// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
const sandboxesToken = process.env.SANDBOXES_TOKEN;
if (!latticeEndpoint || !environmentToken || !sandboxesToken) {
    console.log('Missing required environment variables.');
    process.exit(1);
}
const client = new LatticeClient({
    baseUrl: `https://${latticeEndpoint}`,
    token: environmentToken,
    headers: { "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}` }
});

async function App(entityId: string) {
    try {
        const entity = await client.entities.getEntity({ entityId });
        if (entity && Object.keys(entity).length > 0) {
            console.log(`Asset name     | ${entity.aliases?.name}`);
            console.log(`Asset location | ${entity.location?.position?.latitudeDegrees}, ${entity.location?.position?.longitudeDegrees}`);
        } else {
            console.log('Entity object is empty.');
        }
    } catch (error) {
        console.log(`Encountered the following error while fetching entity: ${error}`);
    }
}

(async function runIndefinitely() {
    while (true) {
        await App("<ENTITY_ID>");
        await new Promise(resolve => setTimeout(resolve, 1000));
    }
})();

```

```rs title={"Rust (REST)"} startLine={36} maxLines={27}
use anduril_lattice_sdk::prelude::*;

use std::env;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    // Remove sandboxes_token if you are not developing on Sandboxes.
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables:");
        eprintln!("  LATTICE_ENDPOINT");
        eprintln!("  ENVIRONMENT_TOKEN");
        eprintln!("  SANDBOXES_TOKEN");
        std::process::exit(1);
    }

    let config = ClientConfig {
        base_url: format!("https://{}", lattice_endpoint),
        token: Some(environment_token),
        // Remove custom_headers if you are not developing on Sandboxes.
        custom_headers: HashMap::from([(
            "anduril-sandbox-authorization".to_string(),
            format!("Bearer {}", sandboxes_token),
        )]),
        ..Default::default()
    };
    let client = Lattice::new(config)?;

    loop {
        match get_entity(&client).await {
            Ok(_) => {}
            Err(e) => {
                eprintln!("Error getting entity: {}", e);
            }
        }

        tokio::time::sleep(Duration::from_secs(5)).await;
    }
}

async fn get_entity(client: &Lattice) -> Result<(), Box<dyn std::error::Error>> {
    // Replace <ENTITY_ID> with the entity ID of the entity you want to get.
    let entity = client.entities.get_entity("<ENTITY_ID>", None).await?;

    if let Some(location) = entity.location.as_ref() {
        if let Some(position) = location.position.as_ref() {
            if let (Some(latitude), Some(longitude)) =
                (position.latitude_degrees, position.longitude_degrees)
            {
                println!("Fetching entity at location: {} {}", latitude, longitude);
            }
        }
    }

    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={63} maxLines={13}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
package main

import (
	"context"
	"log"
	"os"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

type BearerTokenAuth struct {
	Token          string
	SandboxesToken string
}

func (b *BearerTokenAuth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{
		"authorization":                 "Bearer " + b.Token,
		"anduril-sandbox-authorization": "Bearer " + b.SandboxesToken,
	}, nil
}

func (b *BearerTokenAuth) RequireTransportSecurity() bool {
	return true
}

func main() {
	ctx := context.Background()

	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatalf("Missing required environment variables")
	}
	auth := &BearerTokenAuth{
		Token:          environmentToken,
		SandboxesToken: sandboxesToken,
	}

	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}
	conn, err := grpc.NewClient(latticeEndpoint, opts...)

	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	// Periodically get the latest entity state
	for {
		entity, err := client.GetEntity(ctx, &entitymanagerv1.GetEntityRequest{
			EntityId: "<ENTITY_ID>",
		})
		if err != nil {
			log.Fatalf("Error getting entity: %v", err)
		}

		// Process each entity.
		log.Printf("Fetching entity at location: %f %f", entity.GetEntity().GetLocation().GetPosition().LatitudeDegrees, entity.GetEntity().GetLocation().GetPosition().LongitudeDegrees)

		time.Sleep(5 * time.Second)
	}
}

```

```py title={"Python (gRPC)"} startLine={58} maxLines={23}
# This Python example is compatible with artifacts generated using the following
# Buf plugins: https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:bufbuild/py
# and https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:connectrpc/py

import os
import sys
import time
from connectrpc.interceptor import MetadataInterceptorSync
from connectrpc.protocol import ProtocolType
from connectrpc.request import RequestContext
from pyqwest import SyncClient, SyncHTTPTransport

from anduril.entitymanager.v1.entity_manager_api_pub_pb import GetEntityRequest
from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync


class BearerTokenInterceptor(MetadataInterceptorSync):
    """Connect interceptor that adds bearer token headers to requests."""

    def __init__(self, token: str, sandboxes_token: str):
        self.token = token
        self.sandboxes_token = sandboxes_token

    def on_start_sync(self, ctx: RequestContext) -> None:
        ctx.request_headers["authorization"] = f"Bearer {self.token}"
        ctx.request_headers["anduril-sandbox-authorization"] = (
            f"Bearer {self.sandboxes_token}"
        )
        return None

    def on_end_sync(self, token, ctx: RequestContext, error) -> None:
        return


def main():
    # Load environment variables
    environment_token = os.getenv("ENVIRONMENT_TOKEN")
    lattice_endpoint = os.getenv("LATTICE_ENDPOINT")
    # Remove sandboxes_token from the following statements if you are not developing on Sandboxes.
    sandboxes_token = os.getenv("SANDBOXES_TOKEN")

    if not environment_token or not lattice_endpoint or not sandboxes_token:
        print("Missing required environment variables", file=sys.stderr)
        sys.exit(1)

    # Create the EntityManager API client over Connect gRPC with a bearer token
    # interceptor. pyqwest trusts no certificates by default, so enable the
    # system certificate pool for TLS.
    http_client = SyncClient(transport=SyncHTTPTransport(tls_include_system_certs=True))
    client = EntityManagerAPIClientSync(
        f"https://{lattice_endpoint}",
        http_client=http_client,
        interceptors=[BearerTokenInterceptor(environment_token, sandboxes_token)],
        protocol=ProtocolType.GRPC,
    )

    # Periodically get the latest entity state
    while True:
        try:
            request = GetEntityRequest(entity_id="<ENTITY_ID>")

            # Call the GetEntity RPC
            response = client.get_entity(request)

            # Log entity location if available
            if (
                response.entity
                and response.entity.location
                and response.entity.location.position
            ):
                position = response.entity.location.position
                print(
                    f"Fetching entity at location: "
                    f"{position.latitude_degrees} {position.longitude_degrees}"
                )

        except Exception as error:
            print(f"Error getting entity: {error}", file=sys.stderr)

        time.sleep(5)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={62} maxLines={26}
// This Rust example is compatible with artifacts generated using
// the following grpc/rust plugin: https://buf.build/anduril/lattice-sdk/sdks/main:community/neoeinstein-tonic

use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::GetEntityRequest;
use tonic::metadata::MetadataValue;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::Request;

use std::env;
use std::time::Duration;

/// Main application entry point
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load environment variables
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    // Remove sandboxes_token from the following statements if you are not developing on Sandboxes.
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    // Validate required environment variables
    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables:");
        eprintln!("  ENVIRONMENT_TOKEN");
        eprintln!("  LATTICE_ENDPOINT");
        eprintln!("  SANDBOXES_TOKEN");
        std::process::exit(1);
    }

    // Parse tokens into metadata values
    let auth_header: MetadataValue<_> = format!("Bearer {}", environment_token).parse()?;
    let sandbox_header: MetadataValue<_> = format!("Bearer {}", sandboxes_token).parse()?;

    // Create gRPC channel with TLS
    let tls_config = ClientTlsConfig::new().with_native_roots();
    let channel = Channel::from_shared(format!("https://{}", lattice_endpoint))?
        .tls_config(tls_config)?
        .connect()
        .await?;

    // Create EntityManager API client with authentication interceptor
    let mut client = EntityManagerApiClient::with_interceptor(
        channel,
        move |mut req: Request<()>| {
            req.metadata_mut()
                .insert("authorization", auth_header.clone());
            req.metadata_mut()
                .insert("anduril-sandbox-authorization", sandbox_header.clone());
            Ok(req)
        },
    );

    println!("Starting EntityManager API client...");
    println!("Connected to: {}", lattice_endpoint);
    println!();

    // Periodically get the latest entity state
    loop {
        let request = Request::new(GetEntityRequest {
            entity_id: "<ENTITY_ID>".to_string(),
        });

        match client.get_entity(request).await {
            Ok(response) => {
                // Log entity location if available
                if let Some(entity) = response.get_ref().entity.as_ref() {
                    if let Some(location) = entity.location.as_ref() {
                        if let Some(position) = location.position.as_ref() {
                            println!(
                                "Fetching entity at location: {} {}",
                                position.latitude_degrees, position.longitude_degrees
                            );
                        }
                    }
                }
            }
            Err(e) => {
                eprintln!("Error getting entity: {}", e);
            }
        }

        // Wait 5 seconds before next request
        tokio::time::sleep(Duration::from_secs(5)).await;
    }
}

```

#### Verify the response

If successful, you see the entity's `aliases.name` and its location logged in the console:

```bash maxLines=3
Asset name     | Demo-Sim-Asset1
Asset location | 37.7749, -122.4194
```

A single `GetEntity` call is useful to confirm that a cued target exists before you commit to an
engagement. To follow the target over time, open a stream instead of calling `GetEntity` in a loop.
A stream delivers each update as soon as Lattice receives it, without polling delays or extra load.

## Stream entities

The [`StreamEntities`](/reference/rest/entities/stream-entities) API method opens a persistent
connection and sends two kinds of messages:
[`entity`](/reference/rest/entities/stream-entities#response.body.entity) events and
[`heartbeat`](/reference/rest/entities/stream-entities#response.body.heartbeat) messages.
Each entity event carries an `eventType` that tells you what happened to the entity:

* `EVENT_TYPE_PREEXISTING`: The entity already existed when the stream opened, so treat it as the initial state.
* `EVENT_TYPE_CREATED`: The entity was published for the first time, or it started matching your filter, so start tracking it.
* `EVENT_TYPE_UPDATE`: The entity changed, so replace your copy with the new state.
* `EVENT_TYPE_DELETED`: The entity expired, was deleted, or stopped matching your filter, so remove every reference to it.
* `EVENT_TYPE_POST_EXPIRY_OVERRIDE`: An override was set on the entity after it expired, so apply it only if you still keep the expired entity.

Use the following request options to control what the stream sends:

**`heartbeatIntervalMS`** `integer`

How often Lattice sends a heartbeat. Heartbeats let you detect a silent connection even when no
entity changes. Over gRPC, set `heartbeat_period_millis`.

---

**`preExistingOnly`** `boolean`

When `true`, Lattice sends the entities that already exist and then closes the stream. Defaults
to `false`, which keeps the stream open for new events.

---

**`componentsToInclude`** `string[]`

The components to populate in each event, in `snake_case`, such as `location_uncertainty`.
Lattice omits every other component. Leave empty to receive all components.

---

**`filter`** `Statement`

A filter expression that limits the stream to matching entities. For more information, see
[Monitor a target track](#monitor-a-target-track).

---

To stream entities from Lattice, do the following:

#### Stream all components

To stream every entity in your environment with all of its components, use the default
options:

```go title={"Go (REST)"} startLine={39} maxLines={37}
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	Lattice "github.com/anduril/lattice-sdk-go/v5"
	"github.com/anduril/lattice-sdk-go/v5/client"
	"github.com/anduril/lattice-sdk-go/v5/option"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatal("Required environment variables not set.")
	}

	headers := http.Header{}
	headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))

	latticeClient := client.NewClient(
		option.WithToken(environmentToken),
		option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
		option.WithHTTPHeader(headers),
	)

	// Create the entity stream.
	stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
		PreExistingOnly: Lattice.Bool(false),
	})
	if err != nil {
		log.Fatalf("Failed to create entity stream: %v", err)
	}
	defer stream.Close()

	for {
		select {
		case <-ctx.Done():
			log.Printf("Context canceled: %v", ctx.Err())
			return
		default:
			// Continue processing
		}
		message, err := stream.Recv()

		if errors.Is(err, io.EOF) {
			log.Println("Stream completed successfully.")
			return
		}

		if err != nil {
			log.Printf("Error receiving message: %v", err)
			continue
		}

		// Process the message based on its type
		switch message.Event {
		case "heartbeat":
			timestamp := *message.Heartbeat.Timestamp
			log.Printf("Heartbeat: %s", timestamp)
		case "entity":
			log.Printf("Entity: %s", *message.Entity.Entity.EntityID)
		default:
			log.Printf("Unknown event type: %s", message.Event)
		}
	}
}

```

```java title={"Java (REST)"} startLine={37} maxLines={20}
package org.example;

import com.anduril.AsyncLattice;
import com.anduril.resources.entities.requests.EntityStreamRequest;
import com.anduril.resources.entities.types.StreamEntitiesResponse;
import com.anduril.types.EntityStreamEvent;



/**
 * Example application that streams all entities using the Lattice SDK.
 */
public class StreamAllEntities {
    
    public static void main(String[] args) {
        // Get environment variables
        String endpoint = System.getenv("LATTICE_ENDPOINT");
        String environmentToken = System.getenv("ENVIRONMENT_TOKEN");
        String sandboxesToken = System.getenv("SANDBOXES_TOKEN");
        
        // Check required variables
        if (endpoint == null || environmentToken == null || sandboxesToken == null) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;
        
        try {
            AsyncLattice client = AsyncLattice.builder()
                .url(endpoint)
                .token(environmentToken)
                .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
                .build();
            
            System.out.println("Starting entity stream...");
            try {
                EntityStreamRequest request = EntityStreamRequest
                    .builder()
                    .preExistingOnly(false)
                    .build();

                client.entities().streamEntities(request)
                    .thenAccept(responses -> {
                        for (StreamEntitiesResponse response : responses) {
                            // If the event is of type heartbeat, log the timestamp.
                            if (response.getHeartbeat() != null && response.getHeartbeat().isPresent()) {
                                System.out.println("Heartbeat received: " + response.getHeartbeat().get().getTimestamp().get());
                            } 
                            // If the event is of type entity, log the entity ID.
                            else if (response.getEntity() != null && response.getEntity().isPresent()) {
                                EntityStreamEvent event = response.getEntity().get();
                                System.out.println("Entity: " + event.getEntity().get().getEntityId().get());
                            }
                        }
                    })
                    .exceptionally(ex -> {
                        System.err.println("Exception while streaming entities: " + ex.getMessage());
                        return null;
                    })
                    .join();
            } catch (Exception e) {
                System.err.println("Error in streaming loop: " + e.getMessage());
            }
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
    }
}
```

```py title={"Python (REST)"} startLine={24} maxLines={8}
from anduril import AsyncLattice
import asyncio
import os
import sys

lattice_endpoint = os.getenv('LATTICE_ENDPOINT')
environment_token = os.getenv('ENVIRONMENT_TOKEN')

# Remove sandboxes_token from the following statements if you are not developing on Sandboxes.
sandboxes_token = os.getenv('SANDBOXES_TOKEN')
if not environment_token or not lattice_endpoint or not sandboxes_token:
    print("Missing environment variables.")
    sys.exit(1)
    
client = AsyncLattice(
    base_url=f"https://{lattice_endpoint}",
    token=lambda: str(environment_token),
    # Remove the following header if you are not developing on Sandboxes.
    headers={ "anduril-sandbox-authorization": f"Bearer {sandboxes_token}" }
)

async def app():
    try:
        event_stream = client.entities.stream_entities(pre_existing_only=False)
        async for event in event_stream:
            # If the event is of type heartbeat, log the timestamp.
            if event.event == "heartbeat":
                print(f'Heartbeat: {event.timestamp}')
            # If the event is of type entity, log the entity ID.
            elif event.entity:
                print(f'Entity: {event.entity.entity_id}')
    except asyncio.CancelledError:
        print("Streaming cancelled...")
    except Exception as error:
        print(f"Exception: {error}")
        
if __name__ == "__main__":
    asyncio.run(app())

```

```ts title={"TypeScript (REST)"} startLine={25} maxLines={15}
import { LatticeClient } from "@anduril-industries/lattice-sdk";

const latticeEndpoint = process.env.LATTICE_ENDPOINT;
const environmentToken = process.env.ENVIRONMENT_TOKEN;

// Remove sandboxesToken from the following statement if you are not developing on Sandboxes.
const sandboxesToken = process.env.SANDBOXES_TOKEN;
if (!latticeEndpoint || !environmentToken || !sandboxesToken) {
    console.log('Missing required environment variables.');
    process.exit(1);
}

const client = new LatticeClient(
    {
        baseUrl: `https://${latticeEndpoint}`,
        token: environmentToken,
        // Remove the following statement if you are not developing on Sandboxes.
        headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}` }
    }
);

async function App() {
    try {
        // Start streaming entities
        const eventStream = await client.entities.streamEntities({ preExistingOnly: false });
        
        // Process the stream
        for await (const event of eventStream) {
            // Check if it's a heartbeat event.
            if (event.event === "heartbeat") {
                console.log(`Heartbeat received: ${event.timestamp}`);
                continue;
            }
            // Process entity event.
            const entity = event.entity;
            if (entity) {
                console.log(`Entity: ${entity.entityId}`);
            }
        }
    } catch (error) {
        console.log(`Exception while streaming entities: ${error}`);
    }
}

App();
```

```rs title={"Rust (REST)"} startLine={37} maxLines={26}
use anduril_lattice_sdk::prelude::*;

use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    // Remove sandboxes_token if you are not developing on Sandboxes.
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables:");
        eprintln!("  LATTICE_ENDPOINT");
        eprintln!("  ENVIRONMENT_TOKEN");
        eprintln!("  SANDBOXES_TOKEN");
        std::process::exit(1);
    }

    let config = ClientConfig {
        base_url: format!("https://{}", lattice_endpoint),
        token: Some(environment_token),
        // Remove custom_headers if you are not developing on Sandboxes.
        custom_headers: HashMap::from([(
            "anduril-sandbox-authorization".to_string(),
            format!("Bearer {}", sandboxes_token),
        )]),
        ..Default::default()
    };
    let client = Lattice::new(config)?;

    // Stream every entity in the environment. Set pre_existing_only to true to
    // receive a one-time snapshot of current entities and then close the stream.
    let request = EntityStreamRequest {
        pre_existing_only: Some(false),
        ..Default::default()
    };

    // stream_entities returns a Server-Sent Events (SSE) stream of typed
    // StreamEntitiesResponse events. Pin it so it can be polled with the
    // `StreamExt` combinators.
    let stream = client.entities.stream_entities(&request, None).await?;
    let mut stream = std::pin::pin!(stream);

    while let Some(result) = stream.next().await {
        match result {
            // Log the typed response. The Debug representation shows the event
            // variant and every field the SDK deserialized from the stream.
            Ok(event) => match event {
                StreamEntitiesResponse::Heartbeat { .. } => {
                    println!("Heartbeat: {:?}", event);
                }
                StreamEntitiesResponse::Entity { .. } => {
                    println!("Entity: {:?}", event);
                }
                other => {
                    println!("Event: {:?}", other);
                }
            },
            Err(error) => eprintln!("Exception: {}", error),
        }
    }

    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={45} maxLines={21}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
package main

import (
	"context"
	"io"
	"log"
	"os"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

func main() {
	ctx := context.Background()

	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatalf("Missing required environment variables")
	}
	auth := &BearerTokenAuth{
		Token:          environmentToken,
		SandboxesToken: sandboxesToken,
	}

	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}
	conn, err := grpc.NewClient(latticeEndpoint, opts...)

	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	stream, err := client.StreamEntityComponents(ctx, &entitymanagerv1.StreamEntityComponentsRequest{
		IncludeAllComponents: true,
	})
	if err != nil {
		log.Fatalf("Error creating stream: %v", err)
	}

	log.Println("Starting to receive stream data...")
	for {
		response, err := stream.Recv()
		if err == io.EOF {
			log.Println("End of stream reached")
			break
		}
		if err != nil {
			log.Fatalf("Error receiving stream data: %v", err)
		}

		// Process each entity.
		log.Printf("Streaming entity ID: %s", response.GetEntityEvent().GetEntity().EntityId)
	}
}

```

```py title={"Python (gRPC)"} startLine={27} maxLines={18}
# This Python example is compatible with artifacts generated using the following
# Buf plugins: https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:bufbuild/py
# and https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:connectrpc/py

import os
import sys
from bearer_auth import create_client

from anduril.entitymanager.v1.entity_manager_api_pub_pb import (
    StreamEntityComponentsRequest,
)
from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync


def main():
    environment_token = os.getenv("ENVIRONMENT_TOKEN")
    lattice_endpoint = os.getenv("LATTICE_ENDPOINT")
    sandboxes_token = os.getenv("SANDBOXES_TOKEN")

    if not environment_token or not lattice_endpoint or not sandboxes_token:
        print("Missing required environment variables", file=sys.stderr)
        sys.exit(1)

    # Create the API client over Connect gRPC with authentication
    client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    request = StreamEntityComponentsRequest(include_all_components=True)

    try:
        stream = client.stream_entity_components(request)
    except Exception as error:
        print(f"Error creating stream: {error}", file=sys.stderr)
        sys.exit(1)

    print("Starting to receive stream data...")

    try:
        for response in stream:
            # Heartbeat messages carry no entity_event, so skip them.
            if not response.entity_event or not response.entity_event.entity:
                continue
            entity = response.entity_event.entity
            print(f"Streaming entity ID: {entity.entity_id}")
        print("End of stream reached")
    except Exception as error:
        print(f"Error receiving stream data: {error}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={56} maxLines={14}
// This Rust example is compatible with artifacts generated using
// the following grpc/rust plugin: https://buf.build/anduril/lattice-sdk/sdks/main:community/neoeinstein-tonic
mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::StreamEntityComponentsRequest;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use tonic::metadata::MetadataValue;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::Request;

use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load environment variables
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    // Set up authentication handler
    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

    // Create gRPC channel with TLS
    let tls_config = ClientTlsConfig::new().with_native_roots();
    let channel = Channel::from_shared(format!("https://{}", lattice_endpoint))?
        .tls_config(tls_config)?
        .connect()
        .await?;

    // Fetch a fresh access token and build metadata values
    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<_> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<_> = format!("Bearer {}", sandboxes_token).parse()?;

    // Create EntityManager API client with authentication interceptor
    let mut client = EntityManagerApiClient::with_interceptor(
        channel,
        move |mut req: Request<()>| {
            req.metadata_mut()
                .insert("authorization", auth_header.clone());
            req.metadata_mut()
                .insert("anduril-sandbox-authorization", sandbox_header.clone());
            Ok(req)
        },
    );

    // Subscribe to all components on every entity
    let request = Request::new(StreamEntityComponentsRequest {
        include_all_components: true,
        ..Default::default()
    });

    let mut stream = client.stream_entity_components(request).await?.into_inner();

    println!("Starting to receive stream data...");
    while let Some(response) = stream.message().await? {
        if let Some(entity) = response.entity_event.and_then(|e| e.entity) {
            println!("Streaming entity ID: {}", entity.entity_id);
        }
    }
    println!("End of stream reached");

    Ok(())
}

```

If successful, you get a stream of entities as they change in Lattice:

```bash maxLines=3
Entity: Demo-Sim-Asset2
Entity: adsbEntity
Entity: esim.adsb.aus-4005
```

#### Stream specific components

To reduce bandwidth, list the components you need in `componentsToInclude`, such as `aliases`
and `location`:

```go title={"Go (REST)"} startLine={39} maxLines={41}
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	Lattice "github.com/anduril/lattice-sdk-go/v5"
	"github.com/anduril/lattice-sdk-go/v5/client"
	"github.com/anduril/lattice-sdk-go/v5/option"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatal("Required environment variables not set.")
	}

	headers := http.Header{}
	headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))

	latticeClient := client.NewClient(
		option.WithToken(environmentToken),
		option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
		option.WithHTTPHeader(headers),
	)

	// Create the entity stream.
	stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
		PreExistingOnly: Lattice.Bool(false),
		// Define a list of components to control which entities are fetched.
		// If set, Lattice streams only entities with the components you provide.
		ComponentsToInclude: []string{"aliases", "location_uncertainty"},
	})
	if err != nil {
		log.Fatalf("Failed to create entity stream: %v", err)
	}
	defer stream.Close()

	for {
		select {
		case <-ctx.Done():
			log.Printf("Context canceled: %v", ctx.Err())
			return
		default:
			// Continue processing
		}
		message, err := stream.Recv()

		// Handle stream completion
		if errors.Is(err, io.EOF) {
			log.Println("Stream completed successfully.")
			return
		}

		if err != nil {
			log.Printf("Error receiving message: %v", err)
			continue
		}

		// Process the event based whether it is a heartbeat or entity event.
		switch message.Event {
		case "heartbeat":
			timestamp := *message.Heartbeat.Timestamp
			log.Printf("Heartbeat: %s", timestamp)
		case "entity":
			log.Printf("Entity: %s", *message.Entity.Entity.Aliases.Name)
		default:
			log.Printf("Unknown event type: %s", message.Event)
		}
	}
}

```

```java title={"Java (REST)"} startLine={40} maxLines={20}
package org.example;
import java.util.Arrays;
import java.util.Optional;

import com.anduril.AsyncLattice;
import com.anduril.resources.entities.requests.EntityStreamRequest;
import com.anduril.resources.entities.types.StreamEntitiesResponse;
import com.anduril.types.EntityStreamEvent;



/**
 * Example application that streams all entities using the Lattice SDK.
 */
public class StreamSpecificComponents {
    
    public static void main(String[] args) {
        // Get environment variables
        String endpoint = System.getenv("LATTICE_ENDPOINT");
        String environmentToken = System.getenv("ENVIRONMENT_TOKEN");
        String sandboxesToken = System.getenv("SANDBOXES_TOKEN");
        
        // Check required variables
        if (endpoint == null || environmentToken == null || sandboxesToken == null) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;
        
        try {
            AsyncLattice client = AsyncLattice.builder()
                .url(endpoint)
                .token(environmentToken)
                .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
                .build();
            
            System.out.println("Starting entity stream...");
            
            try {
                EntityStreamRequest request = EntityStreamRequest.builder()
                    .preExistingOnly(false)
                    .componentsToInclude(Optional.of(Arrays.asList("aliases", "location_uncertainty")))
                    .build();

                client.entities().streamEntities(request)
                    .thenAccept(responses -> {
                        for (StreamEntitiesResponse response : responses) {
                            // If the event is of type heartbeat, log the timestamp.
                            if (response.getHeartbeat() != null && response.getHeartbeat().isPresent()) {
                                System.out.println("Heartbeat received: " + response.getHeartbeat().get().getTimestamp().get());
                            } 
                            // If the event is of type entity, log the entity ID.
                            else if (response.getEntity() != null && response.getEntity().isPresent()) {
                                EntityStreamEvent event = response.getEntity().get();
                                System.out.println("Entity: " + event.getEntity().get().getAliases().get().getName().get());
                            }
                        }
                    })
                    .exceptionally(ex -> {
                        System.err.println("Exception while streaming entities: " + ex.getMessage());
                        return null;
                    })
                    .join();
            } catch (Exception e) {
                System.err.println("Error in streaming loop: " + e.getMessage());
            }
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
    }
}
```

```py title={"Python (REST)"} startLine={24} maxLines={11}
from anduril import AsyncLattice
import asyncio
import os
import sys

lattice_endpoint = os.getenv('LATTICE_ENDPOINT')
environment_token = os.getenv('ENVIRONMENT_TOKEN')

# Remove sandboxes_token from the following statements if you are not developing on Sandboxes.
sandboxes_token = os.getenv('SANDBOXES_TOKEN')
if not environment_token or not lattice_endpoint or not sandboxes_token:
    print("Missing environment variables.")
    sys.exit(1)

client = AsyncLattice(
    base_url=f"https://{lattice_endpoint}",
    token=lambda: str(environment_token),
    # Remove the following header if you are not developing on Sandboxes.
    headers={ "anduril-sandbox-authorization": f"Bearer {sandboxes_token}" }
)

async def app():
    try:
        event_stream = client.entities.stream_entities(
            pre_existing_only=False,
            components_to_include=["aliases", "location_uncertainty"]
        )
        async for event in event_stream:
            # If the event is of type heartbeat, log the timestamp.
            if event.event == "heartbeat":
                print(f'Heartbeat: {event.timestamp}')
            # If the event is of type entity, log the entity name.
            elif event.entity and event.entity.aliases:
                print(f'Entity: {event.entity.aliases.name}')
    except asyncio.CancelledError:
        print("Streaming cancelled...")
    except Exception as error:
        print(f"Exception: {error}")

if __name__ == "__main__":
    asyncio.run(app())
    
```

```ts title={"TypeScript (REST)"} startLine={25} maxLines={20}
import { LatticeClient } from "@anduril-industries/lattice-sdk";

const latticeEndpoint = process.env.LATTICE_ENDPOINT;
const environmentToken = process.env.ENVIRONMENT_TOKEN;

// Remove sandboxesToken from the following statement if you are not developing on Sandboxes.
const sandboxesToken = process.env.SANDBOXES_TOKEN;
if (!latticeEndpoint || !environmentToken || !sandboxesToken) {
    console.log('Missing required environment variables.');
    process.exit(1);
}

const client = new LatticeClient(
    {
        baseUrl: `https://${latticeEndpoint}`,
        token: environmentToken,
        // Remove the following statement if you are not developing on Sandboxes.
        headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}` }
    }
);

async function App() {
    try {
        // Start streaming entities
        const eventStream = await client.entities.streamEntities(
            {
                preExistingOnly: false,
                componentsToInclude: ["aliases", "location_uncertainty"]
            }
        );
        
        // Process the stream
        for await (const event of eventStream) {
            // Check if it's a heartbeat event.
            if (event.event === "heartbeat") {
                console.log(`Heartbeat received: ${event.timestamp}`);
                continue;
            }
            // Process entity event.
            const entity = event.entity;
            if (entity) {
                console.log(`Entity: ${entity.aliases?.name}`);
            }
        }
    } catch (error) {
        console.log(`Exception while streaming entities: ${error}`);
    }
}

App();
```

```rs title={"Rust (REST)"} startLine={37} maxLines={30}
use anduril_lattice_sdk::prelude::*;

use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    // Remove sandboxes_token if you are not developing on Sandboxes.
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables:");
        eprintln!("  LATTICE_ENDPOINT");
        eprintln!("  ENVIRONMENT_TOKEN");
        eprintln!("  SANDBOXES_TOKEN");
        std::process::exit(1);
    }

    let config = ClientConfig {
        base_url: format!("https://{}", lattice_endpoint),
        token: Some(environment_token),
        // Remove custom_headers if you are not developing on Sandboxes.
        custom_headers: HashMap::from([(
            "anduril-sandbox-authorization".to_string(),
            format!("Bearer {}", sandboxes_token),
        )]),
        ..Default::default()
    };
    let client = Lattice::new(config)?;

    // Stream entities, requesting only a subset of components on each entity.
    // Leave components_to_include unset to receive all components.
    let request = EntityStreamRequest {
        pre_existing_only: Some(false),
        components_to_include: Some(vec![
            "aliases".to_string(),
            "location_uncertainty".to_string(),
        ]),
        ..Default::default()
    };

    // stream_entities returns a Server-Sent Events (SSE) stream of typed
    // StreamEntitiesResponse events. Pin it so it can be polled with the
    // `StreamExt` combinators.
    let stream = client.entities.stream_entities(&request, None).await?;
    let mut stream = std::pin::pin!(stream);

    while let Some(result) = stream.next().await {
        match result {
            // Log the typed response. The Debug representation shows the event
            // variant and every field the SDK deserialized from the stream.
            Ok(event) => match event {
                StreamEntitiesResponse::Heartbeat { .. } => {
                    println!("Heartbeat: {:?}", event);
                }
                StreamEntitiesResponse::Entity { .. } => {
                    println!("Entity: {:?}", event);
                }
                other => {
                    println!("Event: {:?}", other);
                }
            },
            Err(error) => eprintln!("Exception: {}", error),
        }
    }

    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={45} maxLines={27}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
package main

import (
	"context"
	"io"
	"log"
	"os"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

func main() {
	ctx := context.Background()

	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatalf("Missing required environment variables")
	}
	auth := &BearerTokenAuth{
		Token:          environmentToken,
		SandboxesToken: sandboxesToken,
	}

	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}
	conn, err := grpc.NewClient(latticeEndpoint, opts...)

	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	stream, err := client.StreamEntityComponents(ctx, &entitymanagerv1.StreamEntityComponentsRequest{
		ComponentsToInclude: []string{"aliases", "location"},
	})
	if err != nil {
		log.Fatalf("Error creating stream: %v", err)
	}

	log.Println("Starting to receive stream data...")
	for {
		response, err := stream.Recv()
		if err == io.EOF {
			// End of stream
			log.Println("End of stream reached.")
			break
		}
		if err != nil {
			log.Fatalf("Error receiving stream data: %v", err)
		}

		entity := response.GetEntityEvent().GetEntity()
		if position := entity.GetLocation().GetPosition(); position != nil {
			log.Printf("Entity %s at location: %f, %f",
				entity.EntityId,
				position.LatitudeDegrees,
				position.LongitudeDegrees,
			)
		}
	}
}

```

```py title={"Python (gRPC)"} startLine={27} maxLines={25}
# This Python example is compatible with artifacts generated using the following
# Buf plugins: https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:bufbuild/py
# and https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:connectrpc/py

import os
import sys
from bearer_auth import create_client

from anduril.entitymanager.v1.entity_manager_api_pub_pb import (
    StreamEntityComponentsRequest,
)
from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync


def main():
    environment_token = os.getenv("ENVIRONMENT_TOKEN")
    lattice_endpoint = os.getenv("LATTICE_ENDPOINT")
    sandboxes_token = os.getenv("SANDBOXES_TOKEN")

    if not environment_token or not lattice_endpoint or not sandboxes_token:
        print("Missing required environment variables", file=sys.stderr)
        sys.exit(1)

    # Create the API client over Connect gRPC with authentication
    client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    request = StreamEntityComponentsRequest(components_to_include=["aliases", "location"])

    try:
        stream = client.stream_entity_components(request)
    except Exception as error:
        print(f"Error creating stream: {error}", file=sys.stderr)
        sys.exit(1)

    print("Starting to receive stream data...")

    try:
        for response in stream:
            # Heartbeat messages carry no entity_event, so skip them.
            if not response.entity_event or not response.entity_event.entity:
                continue
            entity = response.entity_event.entity
            if not entity.location or not entity.location.position:
                continue
            position = entity.location.position
            if position.latitude_degrees or position.longitude_degrees:
                print(
                    f"Entity {entity.entity_id} at location: "
                    f"{position.latitude_degrees}, {position.longitude_degrees}"
                )
        print("End of stream reached.")
    except Exception as error:
        print(f"Error receiving stream data: {error}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={56} maxLines={19}
// This Rust example is compatible with artifacts generated using
// the following grpc/rust plugin: https://buf.build/anduril/lattice-sdk/sdks/main:community/neoeinstein-tonic
mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::StreamEntityComponentsRequest;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use tonic::metadata::MetadataValue;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::Request;

use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load environment variables
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    // Set up authentication handler
    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

    // Create gRPC channel with TLS
    let tls_config = ClientTlsConfig::new().with_native_roots();
    let channel = Channel::from_shared(format!("https://{}", lattice_endpoint))?
        .tls_config(tls_config)?
        .connect()
        .await?;

    // Fetch a fresh access token and build metadata values
    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<_> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<_> = format!("Bearer {}", sandboxes_token).parse()?;

    // Create EntityManager API client with authentication interceptor
    let mut client = EntityManagerApiClient::with_interceptor(
        channel,
        move |mut req: Request<()>| {
            req.metadata_mut()
                .insert("authorization", auth_header.clone());
            req.metadata_mut()
                .insert("anduril-sandbox-authorization", sandbox_header.clone());
            Ok(req)
        },
    );

    // Subscribe to only the aliases and location components on every entity
    let request = Request::new(StreamEntityComponentsRequest {
        components_to_include: vec!["aliases".to_string(), "location".to_string()],
        ..Default::default()
    });

    let mut stream = client.stream_entity_components(request).await?.into_inner();

    println!("Starting to receive stream data...");
    while let Some(response) = stream.message().await? {
        if let Some(entity) = response.entity_event.and_then(|e| e.entity) {
            if let Some(position) = entity.location.and_then(|l| l.position) {
                println!(
                    "Entity {} at location: {}, {}",
                    entity.entity_id, position.latitude_degrees, position.longitude_degrees
                );
            }
        }
    }
    println!("End of stream reached.");

    Ok(())
}

```

> **Note**
>
> List component names in `snake_case`, such as `location_uncertainty`, even when you
> call the [`StreamEntities`](/reference/rest/entities/stream-entities) REST API directly
> with `curl` or a similar tool. Lattice ignores `camelCase` names, such as
> `locationUncertainty`, without returning an error.

> **Warning**
>
> `componentsToInclude` doesn't filter entities. Lattice still streams every matching
> entity, with only the listed components populated. Tracks can report their position in
> either `location` or `kinematics`, so requesting only `location` streams tracks that use
> `kinematics` with no position.

## Monitor a target track

An interceptor that's engaging a target needs every update for that one track, and nothing else.
Instead of streaming every entity and discarding most of them, send a `filter` with the stream
request so Lattice sends only the target. Lattice evaluates the filter continuously: when the
target stops matching, such as when it expires, you receive an `EVENT_TYPE_DELETED` event.

A filter is a tree of statements. The simplest statement is a single predicate that compares a
field to a value. Field paths use `snake_case` and start at the entity, without an `entity.` prefix:

**`REST`**

```json title="REST"
{
  "predicate": {
    "fieldPath": "entity_id",
    "value": { "stringType": { "value": "<ENTITY_ID>" } },
    "comparator": "COMPARATOR_EQUALITY"
  }
}
```

**`gRPC`**

```protobuf title="gRPC"
filter {
  predicate {
    field_path: "entity_id"
    value { string_type { value: "<ENTITY_ID>" } }
    comparator: COMPARATOR_EQUALITY
  }
}
```

To monitor a target track, do the following:

#### Build the filter

Build a predicate that matches the target's entity ID:

```go title={"Go (REST)"} startLine={28} maxLines={13}
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"sync/atomic"
	"time"

	Lattice "github.com/anduril/lattice-sdk-go/v5"
	"github.com/anduril/lattice-sdk-go/v5/client"
	"github.com/anduril/lattice-sdk-go/v5/option"
)

const (
	// Replace with the entity ID of the track you want to monitor.
	targetEntityID = "<ENTITY_ID>"
	// Request a heartbeat every 5 seconds so silence is detectable.
	heartbeatInterval = 5 * time.Second
	// Warn if nothing arrives within three heartbeat intervals.
	staleAfter = 3 * heartbeatInterval
)

// targetFilter matches only the entity with the given ID. The filter is
// evaluated continuously: if the entity stops matching, you receive DELETED.
func targetFilter(entityID string) *Lattice.Statement {
	return &Lattice.Statement{
		Predicate: &Lattice.Predicate{
			FieldPath: Lattice.String("entity_id"),
			Value: &Lattice.Value{
				StringType: &Lattice.StringType{Value: Lattice.String(entityID)},
			},
			Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
		},
	}
}

// trackPosition is the newest position of a track, with velocity if known.
type trackPosition struct {
	lat, lon, hae float64
	velocityENU   *[3]float64
}

// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *Lattice.Entity) *trackPosition {
	if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic != nil && geodetic.Location != nil {
		loc := geodetic.Location
		pos := &trackPosition{
			lat: deref(loc.LatitudeDegrees),
			lon: deref(loc.LongitudeDegrees),
			hae: deref(loc.GetUniversalAltitudeHae().GetValueMeters()),
		}
		if v := geodetic.VelocityEnuMPerS; v != nil {
			pos.velocityENU = &[3]float64{deref(v.X), deref(v.Y), deref(v.Z)}
		}
		return pos
	}
	if loc := entity.GetLocation(); loc != nil && loc.Position != nil {
		pos := &trackPosition{
			lat: deref(loc.Position.LatitudeDegrees),
			lon: deref(loc.Position.LongitudeDegrees),
			hae: deref(loc.Position.AltitudeHaeMeters),
		}
		if v := loc.VelocityEnu; v != nil {
			pos.velocityENU = &[3]float64{deref(v.E), deref(v.N), deref(v.U)}
		}
		return pos
	}
	return nil
}

// deref returns the value of an optional field, or the zero value if unset.
func deref[T any](p *T) T {
	var zero T
	if p == nil {
		return zero
	}
	return *p
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatal("Required environment variables not set.")
	}

	headers := http.Header{}
	headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))

	latticeClient := client.NewClient(
		option.WithToken(environmentToken),
		option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
		option.WithHTTPHeader(headers),
	)

	// Stream only the target. Omit ComponentsToInclude to receive all components,
	// because listing components drops the others, which can include the position.
	stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
		Filter:              targetFilter(targetEntityID),
		HeartbeatIntervalMs: Lattice.Int(int(heartbeatInterval.Milliseconds())),
	})
	if err != nil {
		log.Fatalf("Failed to create entity stream: %v", err)
	}
	defer stream.Close()

	// Watchdog: warn when neither entity updates nor heartbeats arrive.
	var lastMessage atomic.Int64
	lastMessage.Store(time.Now().UnixNano())
	go func() {
		ticker := time.NewTicker(heartbeatInterval)
		defer ticker.Stop()
		for {
			select {
			case <-ctx.Done():
				return
			case <-ticker.C:
				silence := time.Since(time.Unix(0, lastMessage.Load()))
				if silence > staleAfter {
					log.Printf("WARNING: no message for %.1fs (expected a heartbeat every %.0fs)",
						silence.Seconds(), heartbeatInterval.Seconds())
				}
			}
		}
	}()

	log.Printf("Monitoring target %s", targetEntityID)
	var lastSourceTime time.Time

	for {
		message, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			log.Println("Stream completed successfully.")
			return
		}
		if err != nil {
			log.Fatalf("Error receiving message: %v", err)
		}
		lastMessage.Store(time.Now().UnixNano())

		switch message.Event {
		case "heartbeat":
			log.Printf("Heartbeat: %s", *message.Heartbeat.Timestamp)
		case "entity":
			event := message.Entity
			eventType := deref(event.EventType)
			switch eventType {
			case Lattice.EntityEventEventTypeEventTypeCreated,
				Lattice.EntityEventEventTypeEventTypePreexisting,
				Lattice.EntityEventEventTypeEventTypeUpdate:
				entity := event.Entity
				pos := extractPosition(entity)
				if pos == nil {
					continue
				}
				// Ignore updates that are not newer than the last one seen.
				sourceTime := deref(entity.GetProvenance().GetSourceUpdateTime())
				if sourceTime.IsZero() {
					sourceTime = deref(event.Time)
				}
				if !sourceTime.After(lastSourceTime) {
					continue
				}
				lastSourceTime = sourceTime

				line := fmt.Sprintf("%s lat=%.6f lon=%.6f hae=%.1fm", eventType, pos.lat, pos.lon, pos.hae)
				if v := pos.velocityENU; v != nil {
					line += fmt.Sprintf(" vel_enu=(%.1f,%.1f,%.1f)m/s", v[0], v[1], v[2])
				}
				log.Printf("%s age=%.1fs", line, time.Since(sourceTime).Seconds())
			case Lattice.EntityEventEventTypeEventTypeDeleted:
				// The target expired, was deleted, or stopped matching the filter.
				// A real interceptor would abort the engagement or request a new cue.
				log.Printf("Target lost: %s", targetEntityID)
				return
			}
		}
	}
}

```

```java title={"Java (REST)"} startLine={55} maxLines={13}
package org.example;

import com.anduril.AsyncLattice;
import com.anduril.resources.entities.requests.EntityStreamRequest;
import com.anduril.resources.entities.types.StreamEntitiesResponse;
import com.anduril.types.Entity;
import com.anduril.types.EntityEventEventType;
import com.anduril.types.EntityStreamEvent;
import com.anduril.types.Enu;
import com.anduril.types.KinematicsGeodetic;
import com.anduril.types.Location;
import com.anduril.types.LocationGeodetic;
import com.anduril.types.Position;
import com.anduril.types.Predicate;
import com.anduril.types.PredicateComparator;
import com.anduril.types.Statement;
import com.anduril.types.StringType;
import com.anduril.types.Value;
import com.anduril.types.Vec3;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Example application that monitors a single cued target track using the Lattice SDK.
 */
public class StreamTargetTrack {

    // Replace with the entity ID of the track you want to monitor.
    private static final String TARGET_ENTITY_ID = "<ENTITY_ID>";
    // Request a heartbeat every 5 seconds so silence is detectable.
    private static final int HEARTBEAT_INTERVAL_MS = 5000;
    // Warn if nothing arrives within three heartbeat intervals.
    private static final long STALE_AFTER_MS = 3L * HEARTBEAT_INTERVAL_MS;

    /** The newest position of a track, with velocity if known. */
    private static final class TrackPosition {
        final double lat;
        final double lon;
        final double hae;
        final double[] velocityEnu;

        TrackPosition(double lat, double lon, double hae, double[] velocityEnu) {
            this.lat = lat;
            this.lon = lon;
            this.hae = hae;
            this.velocityEnu = velocityEnu;
        }
    }

    /**
     * Match only the entity with the given ID. The filter is evaluated continuously:
     * if the entity stops matching, you receive a DELETED event.
     */
    static Statement targetFilter(String entityId) {
        return Statement.builder()
            .predicate(Predicate.builder()
                .fieldPath("entity_id")
                .value(Value.builder().stringType(StringType.builder().value(entityId).build()).build())
                .comparator(PredicateComparator.COMPARATOR_EQUALITY)
                .build())
            .build();
    }

    /**
     * Return the newest position, preferring kinematics over location. Kinematics is the
     * recommended source for tracks. Fall back to location if the entity has no kinematics.
     */
    static Optional<TrackPosition> extractPosition(Entity entity) {
        Optional<KinematicsGeodetic> geodetic = entity.getKinematics().flatMap(k -> k.getKinematicsGeodetic());
        if (geodetic.isPresent() && geodetic.get().getLocation().isPresent()) {
            LocationGeodetic loc = geodetic.get().getLocation().get();
            double[] velocity = geodetic.get().getVelocityEnuMPerS()
                .map((Vec3 v) -> new double[] {v.getX().orElse(0.0), v.getY().orElse(0.0), v.getZ().orElse(0.0)})
                .orElse(null);
            return Optional.of(new TrackPosition(
                loc.getLatitudeDegrees().orElse(0.0),
                loc.getLongitudeDegrees().orElse(0.0),
                loc.getUniversalAltitudeHae().flatMap(a -> a.getValueMeters()).orElse(0.0),
                velocity));
        }
        Optional<Location> location = entity.getLocation();
        if (location.isPresent() && location.get().getPosition().isPresent()) {
            Position position = location.get().getPosition().get();
            double[] velocity = location.get().getVelocityEnu()
                .map((Enu v) -> new double[] {v.getE().orElse(0.0), v.getN().orElse(0.0), v.getU().orElse(0.0)})
                .orElse(null);
            return Optional.of(new TrackPosition(
                position.getLatitudeDegrees().orElse(0.0),
                position.getLongitudeDegrees().orElse(0.0),
                position.getAltitudeHaeMeters().orElse(0.0),
                velocity));
        }
        return Optional.empty();
    }

    public static void main(String[] args) {
        // Get environment variables
        String endpoint = System.getenv("LATTICE_ENDPOINT");
        String environmentToken = System.getenv("ENVIRONMENT_TOKEN");
        String sandboxesToken = System.getenv("SANDBOXES_TOKEN");

        // Check required variables
        if (endpoint == null || environmentToken == null || sandboxesToken == null) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        // Watchdog: warn when neither entity updates nor heartbeats arrive.
        AtomicLong lastMessage = new AtomicLong(System.currentTimeMillis());
        ScheduledExecutorService watchdog = Executors.newSingleThreadScheduledExecutor(r -> {
            Thread thread = new Thread(r);
            thread.setDaemon(true);
            return thread;
        });
        watchdog.scheduleAtFixedRate(() -> {
            long silence = System.currentTimeMillis() - lastMessage.get();
            if (silence > STALE_AFTER_MS) {
                System.out.printf("WARNING: no message for %.1fs (expected a heartbeat every %ds)%n",
                    silence / 1000.0, HEARTBEAT_INTERVAL_MS / 1000);
            }
        }, HEARTBEAT_INTERVAL_MS, HEARTBEAT_INTERVAL_MS, TimeUnit.MILLISECONDS);

        try {
            AsyncLattice client = AsyncLattice.builder()
                .url(endpoint)
                .token(environmentToken)
                .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
                .build();

            // Omit componentsToInclude to receive all components, because listing
            // components drops the others, which can include the position.
            EntityStreamRequest request = EntityStreamRequest
                .builder()
                .filter(targetFilter(TARGET_ENTITY_ID))
                .heartbeatIntervalMs(HEARTBEAT_INTERVAL_MS)
                .build();

            System.out.println("Monitoring target " + TARGET_ENTITY_ID);
            client.entities().streamEntities(request)
                .thenAccept(responses -> {
                    OffsetDateTime lastSourceTime = null;
                    for (StreamEntitiesResponse response : responses) {
                        lastMessage.set(System.currentTimeMillis());

                        if (response.getHeartbeat().isPresent()) {
                            System.out.println("Heartbeat: " + response.getHeartbeat().get().getTimestamp().orElse(""));
                            continue;
                        }
                        if (!response.getEntity().isPresent()) {
                            continue;
                        }
                        EntityStreamEvent event = response.getEntity().get();
                        EntityEventEventType.Value type = event.getEventType()
                            .map(EntityEventEventType::getEnumValue)
                            .orElse(EntityEventEventType.Value.EVENT_TYPE_INVALID);

                        switch (type) {
                            case EVENT_TYPE_CREATED:
                            case EVENT_TYPE_PREEXISTING:
                            case EVENT_TYPE_UPDATE: {
                                Optional<Entity> entity = event.getEntity();
                                Optional<TrackPosition> position = entity.flatMap(StreamTargetTrack::extractPosition);
                                if (!position.isPresent()) {
                                    break;
                                }
                                // Ignore updates that are not newer than the last one seen.
                                Optional<OffsetDateTime> sourceTime = entity.get().getProvenance()
                                    .flatMap(p -> p.getSourceUpdateTime());
                                if (!sourceTime.isPresent()) {
                                    sourceTime = event.getTime();
                                }
                                if (!sourceTime.isPresent()
                                        || (lastSourceTime != null && !sourceTime.get().isAfter(lastSourceTime))) {
                                    break;
                                }
                                lastSourceTime = sourceTime.get();

                                TrackPosition p = position.get();
                                StringBuilder line = new StringBuilder(String.format(
                                    "%s lat=%.6f lon=%.6f hae=%.1fm", type, p.lat, p.lon, p.hae));
                                if (p.velocityEnu != null) {
                                    line.append(String.format(" vel_enu=(%.1f,%.1f,%.1f)m/s",
                                        p.velocityEnu[0], p.velocityEnu[1], p.velocityEnu[2]));
                                }
                                double ageSeconds = Duration.between(sourceTime.get(), OffsetDateTime.now()).toMillis() / 1000.0;
                                System.out.printf("%s age=%.1fs%n", line, ageSeconds);
                                break;
                            }
                            case EVENT_TYPE_DELETED:
                                // The target expired, was deleted, or stopped matching the filter.
                                // A real interceptor would abort the engagement or request a new cue.
                                System.out.println("Target lost: " + TARGET_ENTITY_ID);
                                System.exit(0);
                                return;
                            default:
                                break;
                        }
                    }
                })
                .exceptionally(ex -> {
                    System.err.println("Exception while streaming entities: " + ex.getMessage());
                    return null;
                })
                .join();
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
        watchdog.shutdownNow();
    }
}

```

```py title={"Python (REST)"} startLine={40} maxLines={13}
from anduril import (
    AsyncLattice,
    Entity,
    Predicate,
    Statement,
    StringType,
    Value,
)
from datetime import datetime, timezone
from typing import NamedTuple, Optional, Tuple
import asyncio
import os
import sys
import time

# Replace with the entity ID of the track you want to monitor.
TARGET_ENTITY_ID = "<ENTITY_ID>"
# Request a heartbeat every 5 seconds so silence is detectable.
HEARTBEAT_INTERVAL_MS = 5000
# Warn if nothing arrives within three heartbeat intervals.
STALE_AFTER_S = 3 * HEARTBEAT_INTERVAL_MS / 1000

lattice_endpoint = os.getenv('LATTICE_ENDPOINT')
environment_token = os.getenv('ENVIRONMENT_TOKEN')

# Remove sandboxes_token from the following statements if you are not developing on Sandboxes.
sandboxes_token = os.getenv('SANDBOXES_TOKEN')
if not environment_token or not lattice_endpoint or not sandboxes_token:
    print("Missing environment variables.")
    sys.exit(1)

client = AsyncLattice(
    base_url=f"https://{lattice_endpoint}",
    token=lambda: str(environment_token),
    # Remove the following header if you are not developing on Sandboxes.
    headers={ "anduril-sandbox-authorization": f"Bearer {sandboxes_token}" }
)


def target_filter(entity_id: str) -> Statement:
    """Match only the entity with the given ID.

    The filter is evaluated continuously: if the entity stops matching, you
    receive a DELETED event.
    """
    return Statement(
        predicate=Predicate(
            field_path="entity_id",
            value=Value(string_type=StringType(value=entity_id)),
            comparator="COMPARATOR_EQUALITY",
        )
    )


class TrackPosition(NamedTuple):
    lat: float
    lon: float
    hae: float
    velocity_enu: Optional[Tuple[float, float, float]]


def extract_position(entity: Entity) -> Optional[TrackPosition]:
    """Return the newest position, preferring kinematics over location.

    Kinematics is the recommended source for tracks. Fall back to location if
    the entity has no kinematics. Return None if neither has a position.
    """
    geodetic = entity.kinematics.kinematics_geodetic if entity.kinematics else None
    if geodetic and geodetic.location:
        loc = geodetic.location
        altitude = loc.universal_altitude_hae
        v = geodetic.velocity_enu_m_per_s
        return TrackPosition(
            lat=loc.latitude_degrees or 0.0,
            lon=loc.longitude_degrees or 0.0,
            hae=(altitude.value_meters if altitude else None) or 0.0,
            velocity_enu=(v.x or 0.0, v.y or 0.0, v.z or 0.0) if v else None,
        )
    if entity.location and entity.location.position:
        position = entity.location.position
        v = entity.location.velocity_enu
        return TrackPosition(
            lat=position.latitude_degrees or 0.0,
            lon=position.longitude_degrees or 0.0,
            hae=position.altitude_hae_meters or 0.0,
            velocity_enu=(v.e or 0.0, v.n or 0.0, v.u or 0.0) if v else None,
        )
    return None


async def watchdog(last_message: list[float]):
    """Warn when neither entity updates nor heartbeats arrive."""
    while True:
        await asyncio.sleep(HEARTBEAT_INTERVAL_MS / 1000)
        silence = time.monotonic() - last_message[0]
        if silence > STALE_AFTER_S:
            print(f"WARNING: no message for {silence:.1f}s "
                  f"(expected a heartbeat every {HEARTBEAT_INTERVAL_MS / 1000:.0f}s)")


async def app():
    last_message = [time.monotonic()]
    watchdog_task = asyncio.create_task(watchdog(last_message))
    last_source_time: Optional[datetime] = None

    try:
        # Omit components_to_include to receive all components, because listing
        # components drops the others, which can include the position.
        event_stream = client.entities.stream_entities(
            filter=target_filter(TARGET_ENTITY_ID),
            heartbeat_interval_ms=HEARTBEAT_INTERVAL_MS,
        )
        print(f"Monitoring target {TARGET_ENTITY_ID}")
        async for event in event_stream:
            last_message[0] = time.monotonic()

            if event.event == "heartbeat":
                print(f"Heartbeat: {event.timestamp}")
                continue
            if event.event != "entity":
                continue

            if event.event_type in ("EVENT_TYPE_CREATED", "EVENT_TYPE_PREEXISTING", "EVENT_TYPE_UPDATE"):
                entity = event.entity
                if not entity:
                    continue
                position = extract_position(entity)
                if not position:
                    continue
                # Ignore updates that are not newer than the last one seen.
                source_time = (entity.provenance.source_update_time if entity.provenance else None) or event.time
                if not source_time:
                    continue
                if last_source_time and source_time <= last_source_time:
                    continue
                last_source_time = source_time

                line = f"{event.event_type} lat={position.lat:.6f} lon={position.lon:.6f} hae={position.hae:.1f}m"
                if position.velocity_enu:
                    e, n, u = position.velocity_enu
                    line += f" vel_enu=({e:.1f},{n:.1f},{u:.1f})m/s"
                age = (datetime.now(timezone.utc) - source_time).total_seconds()
                print(f"{line} age={age:.1f}s")
            elif event.event_type == "EVENT_TYPE_DELETED":
                # The target expired, was deleted, or stopped matching the filter.
                # An interceptor would abort the engagement or request a new cue.
                print(f"Target lost: {TARGET_ENTITY_ID}")
                return
    except asyncio.CancelledError:
        print("Streaming cancelled...")
    except Exception as error:
        print(f"Exception: {error}")
    finally:
        watchdog_task.cancel()

if __name__ == "__main__":
    asyncio.run(app())

```

```ts title={"TypeScript (REST)"} startLine={29} maxLines={11}
import { Lattice, LatticeClient } from "@anduril-industries/lattice-sdk";

// Replace with the entity ID of the track you want to monitor.
const targetEntityId = "<ENTITY_ID>";
// Request a heartbeat every 5 seconds so silence is detectable.
const heartbeatIntervalMs = 5000;
// Warn if nothing arrives within three heartbeat intervals.
const staleAfterMs = 3 * heartbeatIntervalMs;

const latticeEndpoint = process.env.LATTICE_ENDPOINT;
const environmentToken = process.env.ENVIRONMENT_TOKEN;

// Remove sandboxesToken from the following statement if you are not developing on Sandboxes.
const sandboxesToken = process.env.SANDBOXES_TOKEN;
if (!latticeEndpoint || !environmentToken || !sandboxesToken) {
    console.log('Missing required environment variables.');
    process.exit(1);
}

const client = new LatticeClient(
    {
        baseUrl: `https://${latticeEndpoint}`,
        token: environmentToken,
        // Remove the following statement if you are not developing on Sandboxes.
        headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}` }
    }
);

// Match only the entity with the given ID. The filter is evaluated continuously:
// if the entity stops matching, you receive a DELETED event.
function targetFilter(entityId: string): Lattice.Statement {
    return {
        predicate: {
            fieldPath: "entity_id",
            value: { stringType: { value: entityId } },
            comparator: "COMPARATOR_EQUALITY",
        },
    };
}

interface TrackPosition {
    lat: number;
    lon: number;
    hae: number;
    velocityEnu?: [number, number, number];
}

// Return the newest position, preferring kinematics over location. Kinematics
// is the recommended source for tracks. Fall back to location if the entity
// has no kinematics. Return undefined if neither has a position.
function extractPosition(entity: Lattice.Entity): TrackPosition | undefined {
    const geodetic = entity.kinematics?.kinematicsGeodetic;
    if (geodetic?.location) {
        const v = geodetic.velocityEnuMPerS;
        return {
            lat: geodetic.location.latitudeDegrees ?? 0,
            lon: geodetic.location.longitudeDegrees ?? 0,
            hae: geodetic.location.universalAltitudeHae?.valueMeters ?? 0,
            velocityEnu: v ? [v.x ?? 0, v.y ?? 0, v.z ?? 0] : undefined,
        };
    }
    const position = entity.location?.position;
    if (position) {
        const v = entity.location?.velocityEnu;
        return {
            lat: position.latitudeDegrees ?? 0,
            lon: position.longitudeDegrees ?? 0,
            hae: position.altitudeHaeMeters ?? 0,
            velocityEnu: v ? [v.e ?? 0, v.n ?? 0, v.u ?? 0] : undefined,
        };
    }
    return undefined;
}

async function App() {
    // Watchdog: warn when neither entity updates nor heartbeats arrive.
    let lastMessage = Date.now();
    const watchdog = setInterval(() => {
        const silence = Date.now() - lastMessage;
        if (silence > staleAfterMs) {
            console.log(`WARNING: no message for ${(silence / 1000).toFixed(1)}s (expected a heartbeat every ${heartbeatIntervalMs / 1000}s)`);
        }
    }, heartbeatIntervalMs);

    let lastSourceTime = 0;
    try {
        // Omit componentsToInclude to receive all components, because listing
        // components drops the others, which can include the position.
        const eventStream = await client.entities.streamEntities({
            filter: targetFilter(targetEntityId),
            heartbeatIntervalMS: heartbeatIntervalMs,
        });
        console.log(`Monitoring target ${targetEntityId}`);

        for await (const event of eventStream) {
            lastMessage = Date.now();

            if (event.event === "heartbeat") {
                console.log(`Heartbeat: ${event.timestamp}`);
                continue;
            }

            switch (event.eventType) {
                case "EVENT_TYPE_CREATED":
                case "EVENT_TYPE_PREEXISTING":
                case "EVENT_TYPE_UPDATE": {
                    const entity = event.entity;
                    const position = entity && extractPosition(entity);
                    if (!entity || !position) {
                        break;
                    }
                    // Ignore updates that are not newer than the last one seen.
                    const sourceTime = Date.parse(entity.provenance?.sourceUpdateTime ?? event.time ?? "");
                    if (Number.isNaN(sourceTime) || sourceTime <= lastSourceTime) {
                        break;
                    }
                    lastSourceTime = sourceTime;

                    let line = `${event.eventType} lat=${position.lat.toFixed(6)} lon=${position.lon.toFixed(6)} hae=${position.hae.toFixed(1)}m`;
                    if (position.velocityEnu) {
                        const [e, n, u] = position.velocityEnu;
                        line += ` vel_enu=(${e.toFixed(1)},${n.toFixed(1)},${u.toFixed(1)})m/s`;
                    }
                    console.log(`${line} age=${((Date.now() - sourceTime) / 1000).toFixed(1)}s`);
                    break;
                }
                case "EVENT_TYPE_DELETED":
                    // The target expired, was deleted, or stopped matching the filter.
                    // A real interceptor would abort the engagement or request a new cue.
                    console.log(`Target lost: ${targetEntityId}`);
                    clearInterval(watchdog);
                    return;
            }
        }
    } catch (error) {
        console.log(`Exception while streaming entities: ${error}`);
    }
    clearInterval(watchdog);
}

App();

```

```rs title={"Rust (REST)"} startLine={23} maxLines={13}
use anduril_lattice_sdk::prelude::*;

use chrono::Utc;
use std::env;
use std::time::Duration;
use tokio::time::{timeout_at, Instant};

// Replace with the entity ID of the track you want to monitor.
const TARGET_ENTITY_ID: &str = "<ENTITY_ID>";
// Request a heartbeat every 5 seconds so silence is detectable.
const HEARTBEAT_INTERVAL_MS: i64 = 5000;
// Warn if nothing arrives within three heartbeat intervals.
const STALE_AFTER: Duration = Duration::from_millis(3 * HEARTBEAT_INTERVAL_MS as u64);

/// The newest position of a track, with velocity if known.
struct TrackPosition {
    lat: f64,
    lon: f64,
    hae: f64,
    velocity_enu: Option<(f64, f64, f64)>,
}

/// Matches only the entity with the given ID. The filter is evaluated
/// continuously: if the entity stops matching, you receive DELETED.
fn target_filter(entity_id: &str) -> Statement {
    Statement {
        predicate: Some(Predicate {
            field_path: Some("entity_id".to_string()),
            // The SDK models the predicate value as free-form JSON.
            value: Some(json!({ "stringType": { "value": entity_id } })),
            comparator: Some(PredicateComparator::ComparatorEquality),
        }),
        ..Default::default()
    }
}

/// Returns the newest position, preferring kinematics over location. Kinematics
/// is the recommended source for tracks. Falls back to location if the entity
/// has no kinematics. Returns None if neither has a position.
fn extract_position(entity: &Entity) -> Option<TrackPosition> {
    if let Some(geodetic) = entity
        .kinematics
        .as_ref()
        .and_then(|k| k.kinematics_geodetic.as_ref())
    {
        if let Some(loc) = &geodetic.location {
            return Some(TrackPosition {
                lat: loc.latitude_degrees.unwrap_or(0.0),
                lon: loc.longitude_degrees.unwrap_or(0.0),
                hae: loc
                    .universal_altitude_hae
                    .as_ref()
                    .and_then(|a| a.value_meters)
                    .unwrap_or(0.0),
                velocity_enu: geodetic.velocity_enu_m_per_s.as_ref().map(|v| {
                    (v.x.unwrap_or(0.0), v.y.unwrap_or(0.0), v.z.unwrap_or(0.0))
                }),
            });
        }
    }
    let location = entity.location.as_ref()?;
    let position = location.position.as_ref()?;
    Some(TrackPosition {
        lat: position.latitude_degrees.unwrap_or(0.0),
        lon: position.longitude_degrees.unwrap_or(0.0),
        hae: position.altitude_hae_meters.unwrap_or(0.0),
        velocity_enu: location
            .velocity_enu
            .as_ref()
            .map(|v| (v.e.unwrap_or(0.0), v.n.unwrap_or(0.0), v.u.unwrap_or(0.0))),
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    // Remove sandboxes_token if you are not developing on Sandboxes.
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables:");
        eprintln!("  LATTICE_ENDPOINT");
        eprintln!("  ENVIRONMENT_TOKEN");
        eprintln!("  SANDBOXES_TOKEN");
        std::process::exit(1);
    }

    let config = ClientConfig {
        base_url: format!("https://{}", lattice_endpoint),
        token: Some(environment_token),
        // Remove custom_headers if you are not developing on Sandboxes.
        custom_headers: HashMap::from([(
            "anduril-sandbox-authorization".to_string(),
            format!("Bearer {}", sandboxes_token),
        )]),
        ..Default::default()
    };
    let client = Lattice::new(config)?;

    // Stream only the target. Leave components_to_include unset to receive all
    // components, because listing components drops the others, which can include the position.
    let request = EntityStreamRequest {
        filter: Some(target_filter(TARGET_ENTITY_ID)),
        heartbeat_interval_ms: Some(HEARTBEAT_INTERVAL_MS),
        ..Default::default()
    };
    let stream = client.entities.stream_entities(&request, None).await?;
    let mut stream = std::pin::pin!(stream);

    println!("Monitoring target {}", TARGET_ENTITY_ID);
    let mut last_source_time: Option<DateTime<FixedOffset>> = None;
    // Watchdog: the deadline moves forward each time a message arrives.
    let mut deadline = Instant::now() + STALE_AFTER;

    loop {
        let result = match timeout_at(deadline, stream.next()).await {
            Ok(Some(result)) => result,
            Ok(None) => break,
            Err(_) => {
                println!(
                    "WARNING: no message for {}s (expected a heartbeat every {}s)",
                    STALE_AFTER.as_secs(),
                    HEARTBEAT_INTERVAL_MS / 1000
                );
                deadline = Instant::now() + STALE_AFTER;
                continue;
            }
        };
        deadline = Instant::now() + STALE_AFTER;

        let event = match result {
            Ok(event) => event,
            Err(error) => {
                eprintln!("Exception: {}", error);
                continue;
            }
        };

        match event {
            StreamEntitiesResponse::Heartbeat { data, .. } => {
                println!(
                    "Heartbeat: {}",
                    data.heartbeat_object_fields.timestamp.unwrap_or_default()
                );
            }
            StreamEntitiesResponse::Entity { data, .. } => {
                let event = data.entity_event_fields;
                match event.event_type {
                    Some(
                        EntityEventEventType::EventTypeCreated
                        | EntityEventEventType::EventTypePreexisting
                        | EntityEventEventType::EventTypeUpdate,
                    ) => {
                        let Some(entity) = &event.entity else { continue };
                        let Some(position) = extract_position(entity) else { continue };
                        // Ignore updates that are not newer than the last one seen.
                        let source_time = entity
                            .provenance
                            .as_ref()
                            .and_then(|p| p.source_update_time)
                            .or(event.time);
                        let Some(source_time) = source_time else { continue };
                        if last_source_time.is_some_and(|last| source_time <= last) {
                            continue;
                        }
                        last_source_time = Some(source_time);

                        let mut line = format!(
                            "{} lat={:.6} lon={:.6} hae={:.1}m",
                            event.event_type.as_ref().map(|t| t.to_string()).unwrap_or_default(),
                            position.lat,
                            position.lon,
                            position.hae
                        );
                        if let Some((e, n, u)) = position.velocity_enu {
                            line.push_str(&format!(" vel_enu=({:.1},{:.1},{:.1})m/s", e, n, u));
                        }
                        let age = (Utc::now() - source_time.with_timezone(&Utc)).num_milliseconds()
                            as f64
                            / 1000.0;
                        println!("{} age={:.1}s", line, age);
                    }
                    Some(EntityEventEventType::EventTypeDeleted) => {
                        // The target expired, was deleted, or stopped matching the filter.
                        // A real interceptor would abort the engagement or request a new cue.
                        println!("Target lost: {}", TARGET_ENTITY_ID);
                        return Ok(());
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }

    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={29} maxLines={17}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"os"
	"sync/atomic"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

const (
	// Replace with the entity ID of the track you want to monitor.
	targetEntityID = "<ENTITY_ID>"
	// Request a heartbeat every 5 seconds so silence is detectable.
	heartbeatInterval = 5 * time.Second
	// Warn if nothing arrives within three heartbeat intervals.
	staleAfter = 3 * heartbeatInterval
)

// targetFilter matches only the entity with the given ID. The filter is
// evaluated continuously: if the entity stops matching, you receive DELETED.
func targetFilter(entityID string) *entitymanagerv1.Statement {
	return &entitymanagerv1.Statement{
		Operation: &entitymanagerv1.Statement_Predicate{
			Predicate: &entitymanagerv1.Predicate{
				FieldPath: "entity_id",
				Value: &entitymanagerv1.Value{
					Type: &entitymanagerv1.Value_StringType{
						StringType: &entitymanagerv1.StringType{Value: entityID},
					},
				},
				Comparator: entitymanagerv1.Comparator_COMPARATOR_EQUALITY,
			},
		},
	}
}

// trackPosition is the newest position of a track, with velocity if known.
type trackPosition struct {
	lat, lon, hae float64
	velocityENU   *[3]float64
}

// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *entitymanagerv1.Entity) *trackPosition {
	if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic.GetLocation() != nil {
		loc := geodetic.GetLocation()
		pos := &trackPosition{
			lat: loc.GetLatitudeDegrees(),
			lon: loc.GetLongitudeDegrees(),
			hae: loc.GetUniversalAltitudeHae().GetValueMeters(),
		}
		if v := geodetic.GetVelocityEnuMPerS(); v != nil {
			pos.velocityENU = &[3]float64{v.GetX(), v.GetY(), v.GetZ()}
		}
		return pos
	}
	if loc := entity.GetLocation(); loc.GetPosition() != nil {
		position := loc.GetPosition()
		pos := &trackPosition{
			lat: position.GetLatitudeDegrees(),
			lon: position.GetLongitudeDegrees(),
			hae: position.GetAltitudeHaeMeters().GetValue(),
		}
		if v := loc.GetVelocityEnu(); v != nil {
			pos.velocityENU = &[3]float64{v.GetE(), v.GetN(), v.GetU()}
		}
		return pos
	}
	return nil
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatalf("Missing required environment variables")
	}
	auth := &BearerTokenAuth{
		Token:          environmentToken,
		SandboxesToken: sandboxesToken,
	}

	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}
	conn, err := grpc.NewClient(latticeEndpoint, opts...)
	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	// Stream only the target, with all components. Don't set components_to_include,
	// because listing components drops the others, which can include the position.
	stream, err := client.StreamEntityComponents(ctx, &entitymanagerv1.StreamEntityComponentsRequest{
		Filter:                targetFilter(targetEntityID),
		IncludeAllComponents:  true,
		HeartbeatPeriodMillis: uint32(heartbeatInterval.Milliseconds()),
	})
	if err != nil {
		log.Fatalf("Error creating stream: %v", err)
	}

	// Watchdog: warn when neither entity updates nor heartbeats arrive.
	var lastMessage atomic.Int64
	lastMessage.Store(time.Now().UnixNano())
	go func() {
		ticker := time.NewTicker(heartbeatInterval)
		defer ticker.Stop()
		for {
			select {
			case <-ctx.Done():
				return
			case <-ticker.C:
				silence := time.Since(time.Unix(0, lastMessage.Load()))
				if silence > staleAfter {
					log.Printf("WARNING: no message for %.1fs (expected a heartbeat every %.0fs)",
						silence.Seconds(), heartbeatInterval.Seconds())
				}
			}
		}
	}()

	log.Printf("Monitoring target %s", targetEntityID)
	var lastSourceTime time.Time

	for {
		response, err := stream.Recv()
		if err == io.EOF {
			log.Println("Stream completed successfully.")
			return
		}
		if err != nil {
			log.Fatalf("Error receiving stream data: %v", err)
		}
		lastMessage.Store(time.Now().UnixNano())

		if response.GetHeartbeat() != nil {
			log.Printf("Heartbeat: %s", response.GetHeartbeat().GetTimestamp().AsTime().Format(time.RFC3339))
			continue
		}
		event := response.GetEntityEvent()
		eventType := event.GetEventType()

		switch eventType {
		case entitymanagerv1.EventType_EVENT_TYPE_CREATED,
			entitymanagerv1.EventType_EVENT_TYPE_PREEXISTING,
			entitymanagerv1.EventType_EVENT_TYPE_UPDATE:
			entity := event.GetEntity()
			pos := extractPosition(entity)
			if pos == nil {
				continue
			}
			// Ignore updates that are not newer than the last one seen.
			sourceTime := entity.GetProvenance().GetSourceUpdateTime().AsTime()
			if entity.GetProvenance().GetSourceUpdateTime() == nil {
				sourceTime = event.GetTime().AsTime()
			}
			if !sourceTime.After(lastSourceTime) {
				continue
			}
			lastSourceTime = sourceTime

			line := fmt.Sprintf("%s lat=%.6f lon=%.6f hae=%.1fm", eventType, pos.lat, pos.lon, pos.hae)
			if v := pos.velocityENU; v != nil {
				line += fmt.Sprintf(" vel_enu=(%.1f,%.1f,%.1f)m/s", v[0], v[1], v[2])
			}
			log.Printf("%s age=%.1fs", line, time.Since(sourceTime).Seconds())
		case entitymanagerv1.EventType_EVENT_TYPE_DELETED:
			// The target expired, was deleted, or stopped matching the filter.
			// A real interceptor would abort the engagement or request a new cue.
			log.Printf("Target lost: %s", targetEntityID)
			return
		}
	}
}

```

```py title={"Python (gRPC)"} startLine={31} maxLines={16}
# This Python example is compatible with artifacts generated using the following
# Buf plugins: https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:bufbuild/py
# and https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:connectrpc/py

import os
import sys
import threading
import time
from datetime import datetime, timezone
from typing import NamedTuple, Optional, Tuple

from bearer_auth import create_client
from protobuf import Oneof

from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.entity_manager_api_pub_pb import (
    EventType,
    StreamEntityComponentsRequest,
)
from anduril.entitymanager.v1.entity_pub_pb import Entity
from anduril.entitymanager.v1.filter_pub_pb import Comparator, Predicate, Statement, StringType, Value

# Replace with the entity ID of the track you want to monitor.
TARGET_ENTITY_ID = "<ENTITY_ID>"
# Request a heartbeat every 5 seconds so silence is detectable.
HEARTBEAT_PERIOD_MS = 5000
# Warn if nothing arrives within three heartbeat intervals.
STALE_AFTER_S = 3 * HEARTBEAT_PERIOD_MS / 1000


def target_filter(entity_id: str) -> Statement:
    """Match only the entity with the given ID.

    The filter is evaluated continuously: if the entity stops matching, you
    receive a DELETED event.
    """
    return Statement(
        operation=Oneof(
            "predicate",
            Predicate(
                field_path="entity_id",
                value=Value(type=Oneof("string_type", StringType(value=entity_id))),
                comparator=Comparator.EQUALITY,
            ),
        )
    )


class TrackPosition(NamedTuple):
    lat: float
    lon: float
    hae: float
    velocity_enu: Optional[Tuple[float, float, float]]


def extract_position(entity: Entity) -> Optional[TrackPosition]:
    """Return the newest position, preferring kinematics over location.

    Kinematics is the recommended source for tracks. Fall back to location if
    the entity has no kinematics. Return None if neither has a position.
    """
    if entity.has_field("kinematics") and entity.kinematics.has_field("kinematics_geodetic"):
        geodetic = entity.kinematics.kinematics_geodetic
        if geodetic.has_field("location"):
            loc = geodetic.location
            v = geodetic.velocity_enu_m_per_s if geodetic.has_field("velocity_enu_m_per_s") else None
            return TrackPosition(
                lat=loc.latitude_degrees,
                lon=loc.longitude_degrees,
                hae=loc.universal_altitude_hae.value_meters,
                velocity_enu=(v.x, v.y, v.z) if v else None,
            )
    if entity.has_field("location") and entity.location.has_field("position"):
        position = entity.location.position
        v = entity.location.velocity_enu if entity.location.has_field("velocity_enu") else None
        return TrackPosition(
            lat=position.latitude_degrees,
            lon=position.longitude_degrees,
            hae=position.altitude_hae_meters.value if position.has_field("altitude_hae_meters") else 0.0,
            velocity_enu=(v.e, v.n, v.u) if v else None,
        )
    return None


def watch_for_silence(last_message: list[float]) -> None:
    """Warn when neither entity updates nor heartbeats arrive."""
    while True:
        time.sleep(HEARTBEAT_PERIOD_MS / 1000)
        silence = time.monotonic() - last_message[0]
        if silence > STALE_AFTER_S:
            print(f"WARNING: no message for {silence:.1f}s "
                  f"(expected a heartbeat every {HEARTBEAT_PERIOD_MS / 1000:.0f}s)")


def main():
    environment_token = os.getenv("ENVIRONMENT_TOKEN")
    lattice_endpoint = os.getenv("LATTICE_ENDPOINT")
    sandboxes_token = os.getenv("SANDBOXES_TOKEN")

    if not environment_token or not lattice_endpoint or not sandboxes_token:
        print("Missing required environment variables", file=sys.stderr)
        sys.exit(1)

    # Create the API client over Connect gRPC with authentication
    client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    # Stream only the target, with all components. Don't set components_to_include,
    # because listing components drops the others, which can include the position.
    request = StreamEntityComponentsRequest(
        filter=target_filter(TARGET_ENTITY_ID),
        include_all_components=True,
        heartbeat_period_millis=HEARTBEAT_PERIOD_MS,
    )

    try:
        stream = client.stream_entity_components(request)
    except Exception as error:
        print(f"Error creating stream: {error}", file=sys.stderr)
        sys.exit(1)

    last_message = [time.monotonic()]
    threading.Thread(target=watch_for_silence, args=(last_message,), daemon=True).start()
    last_source_time: Optional[datetime] = None

    print(f"Monitoring target {TARGET_ENTITY_ID}")
    try:
        for response in stream:
            last_message[0] = time.monotonic()

            if response.has_field("heartbeat"):
                print(f"Heartbeat: {response.heartbeat.timestamp.to_datetime().isoformat()}")
                continue
            if not response.has_field("entity_event"):
                continue
            event = response.entity_event

            if event.event_type in (EventType.CREATED, EventType.PREEXISTING, EventType.UPDATE):
                entity = event.entity
                position = extract_position(entity) if entity else None
                if not entity or not position:
                    continue
                # Ignore updates that are not newer than the last one seen.
                if entity.has_field("provenance") and entity.provenance.has_field("source_update_time"):
                    source_time = entity.provenance.source_update_time.to_datetime()
                else:
                    source_time = event.time.to_datetime()
                if last_source_time and source_time <= last_source_time:
                    continue
                last_source_time = source_time

                line = f"EVENT_TYPE_{event.event_type.name} lat={position.lat:.6f} lon={position.lon:.6f} hae={position.hae:.1f}m"
                if position.velocity_enu:
                    e, n, u = position.velocity_enu
                    line += f" vel_enu=({e:.1f},{n:.1f},{u:.1f})m/s"
                age = (datetime.now(timezone.utc) - source_time).total_seconds()
                print(f"{line} age={age:.1f}s")
            elif event.event_type == EventType.DELETED:
                # The target expired, was deleted, or stopped matching the filter.
                # A real interceptor would abort the engagement or request a new cue.
                print(f"Target lost: {TARGET_ENTITY_ID}")
                return
        print("End of stream reached.")
    except Exception as error:
        print(f"Error receiving stream data: {error}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={34} maxLines={15}
// This Rust example is compatible with artifacts generated using
// the following grpc/rust plugin: https://buf.build/anduril/lattice-sdk/sdks/main:community/neoeinstein-tonic
mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    statement, value, Comparator, Entity, EventType, Predicate, Statement,
    StreamEntityComponentsRequest, StringType, Value,
};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use tonic::metadata::MetadataValue;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::Request;

use std::env;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::time::{timeout_at, Instant};

// Replace with the entity ID of the track you want to monitor.
const TARGET_ENTITY_ID: &str = "<ENTITY_ID>";
// Request a heartbeat every 5 seconds so silence is detectable.
const HEARTBEAT_PERIOD_MS: u32 = 5000;
// Warn if nothing arrives within three heartbeat intervals.
const STALE_AFTER: Duration = Duration::from_millis(3 * HEARTBEAT_PERIOD_MS as u64);

/// The newest position of a track, with velocity if known.
struct TrackPosition {
    lat: f64,
    lon: f64,
    hae: f64,
    velocity_enu: Option<(f64, f64, f64)>,
}

/// Matches only the entity with the given ID. The filter is evaluated
/// continuously: if the entity stops matching, you receive DELETED.
fn target_filter(entity_id: &str) -> Statement {
    Statement {
        operation: Some(statement::Operation::Predicate(Predicate {
            field_path: "entity_id".to_string(),
            value: Some(Value {
                r#type: Some(value::Type::StringType(StringType {
                    value: entity_id.to_string(),
                })),
            }),
            comparator: Comparator::Equality as i32,
        })),
    }
}

/// Returns the newest position, preferring kinematics over location. Kinematics
/// is the recommended source for tracks. Falls back to location if the entity
/// has no kinematics. Returns None if neither has a position.
fn extract_position(entity: &Entity) -> Option<TrackPosition> {
    if let Some(geodetic) = entity
        .kinematics
        .as_ref()
        .and_then(|k| k.kinematics_geodetic.as_ref())
    {
        if let Some(loc) = &geodetic.location {
            return Some(TrackPosition {
                lat: loc.latitude_degrees,
                lon: loc.longitude_degrees,
                hae: loc
                    .universal_altitude_hae
                    .as_ref()
                    .map_or(0.0, |a| a.value_meters),
                velocity_enu: geodetic
                    .velocity_enu_m_per_s
                    .as_ref()
                    .map(|v| (v.x, v.y, v.z)),
            });
        }
    }
    let location = entity.location.as_ref()?;
    let position = location.position.as_ref()?;
    Some(TrackPosition {
        lat: position.latitude_degrees,
        lon: position.longitude_degrees,
        hae: position.altitude_hae_meters.unwrap_or(0.0),
        velocity_enu: location.velocity_enu.as_ref().map(|v| (v.e, v.n, v.u)),
    })
}

/// Converts a protobuf timestamp to seconds since the Unix epoch.
fn timestamp_secs(ts: &prost_types::Timestamp) -> f64 {
    ts.seconds as f64 + f64::from(ts.nanos) / 1e9
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load environment variables
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    // Set up authentication handler
    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

    // Create gRPC channel with TLS
    let tls_config = ClientTlsConfig::new().with_native_roots();
    let channel = Channel::from_shared(format!("https://{}", lattice_endpoint))?
        .tls_config(tls_config)?
        .connect()
        .await?;

    // Fetch a fresh access token and build metadata values
    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<_> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<_> = format!("Bearer {}", sandboxes_token).parse()?;

    // Create EntityManager API client with authentication interceptor
    let mut client = EntityManagerApiClient::with_interceptor(
        channel,
        move |mut req: Request<()>| {
            req.metadata_mut()
                .insert("authorization", auth_header.clone());
            req.metadata_mut()
                .insert("anduril-sandbox-authorization", sandbox_header.clone());
            Ok(req)
        },
    );

    // Stream only the target, with all components. Don't set components_to_include,
    // because listing components drops the others, which can include the position.
    let request = Request::new(StreamEntityComponentsRequest {
        filter: Some(target_filter(TARGET_ENTITY_ID)),
        include_all_components: true,
        heartbeat_period_millis: HEARTBEAT_PERIOD_MS,
        ..Default::default()
    });

    let mut stream = client.stream_entity_components(request).await?.into_inner();

    println!("Monitoring target {}", TARGET_ENTITY_ID);
    let mut last_source_secs: Option<f64> = None;
    // Watchdog: the deadline moves forward each time a message arrives.
    let mut deadline = Instant::now() + STALE_AFTER;

    loop {
        let response = match timeout_at(deadline, stream.message()).await {
            Ok(message) => match message? {
                Some(response) => response,
                None => break,
            },
            Err(_) => {
                println!(
                    "WARNING: no message for {}s (expected a heartbeat every {}s)",
                    STALE_AFTER.as_secs(),
                    HEARTBEAT_PERIOD_MS / 1000
                );
                deadline = Instant::now() + STALE_AFTER;
                continue;
            }
        };
        deadline = Instant::now() + STALE_AFTER;

        if let Some(heartbeat) = response.heartbeat {
            let secs = heartbeat.timestamp.as_ref().map_or(0.0, timestamp_secs);
            println!("Heartbeat: {:.3}", secs);
            continue;
        }
        let Some(event) = response.entity_event else { continue };

        match EventType::try_from(event.event_type) {
            Ok(EventType::Created | EventType::Preexisting | EventType::Update) => {
                let Some(entity) = &event.entity else { continue };
                let Some(position) = extract_position(entity) else { continue };
                // Ignore updates that are not newer than the last one seen.
                let source_time = entity
                    .provenance
                    .as_ref()
                    .and_then(|p| p.source_update_time.as_ref())
                    .or(event.time.as_ref());
                let Some(source_secs) = source_time.map(timestamp_secs) else { continue };
                if last_source_secs.is_some_and(|last| source_secs <= last) {
                    continue;
                }
                last_source_secs = Some(source_secs);

                let mut line = format!(
                    "{} lat={:.6} lon={:.6} hae={:.1}m",
                    EventType::try_from(event.event_type)?.as_str_name(),
                    position.lat,
                    position.lon,
                    position.hae
                );
                if let Some((e, n, u)) = position.velocity_enu {
                    line.push_str(&format!(" vel_enu=({:.1},{:.1},{:.1})m/s", e, n, u));
                }
                let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs_f64();
                println!("{} age={:.1}s", line, now - source_secs);
            }
            Ok(EventType::Deleted) => {
                // The target expired, was deleted, or stopped matching the filter.
                // A real interceptor would abort the engagement or request a new cue.
                println!("Target lost: {}", TARGET_ENTITY_ID);
                return Ok(());
            }
            _ => {}
        }
    }
    println!("End of stream reached");

    Ok(())
}

```

To monitor several targets on one stream, match a set of IDs with the `COMPARATOR_IN`
comparator and a `listType` value:

**`filter.json`**

```json title="filter.json"
{
  "predicate": {
    "fieldPath": "entity_id",
    "value": {
      "listType": {
        "values": [
          { "stringType": { "value": "<TARGET_1_ID>" } },
          { "stringType": { "value": "<TARGET_2_ID>" } }
        ]
      }
    },
    "comparator": "COMPARATOR_IN"
  }
}
```

#### Read the target's position

Tracks report their position in one of two components. `kinematics` is the preferred
component for tracks, and `location` is the general-purpose alternative. Read `kinematics`
when it's present, and fall back to `location`:

```go title={"Go (REST)"} startLine={48} maxLines={28}
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"sync/atomic"
	"time"

	Lattice "github.com/anduril/lattice-sdk-go/v5"
	"github.com/anduril/lattice-sdk-go/v5/client"
	"github.com/anduril/lattice-sdk-go/v5/option"
)

const (
	// Replace with the entity ID of the track you want to monitor.
	targetEntityID = "<ENTITY_ID>"
	// Request a heartbeat every 5 seconds so silence is detectable.
	heartbeatInterval = 5 * time.Second
	// Warn if nothing arrives within three heartbeat intervals.
	staleAfter = 3 * heartbeatInterval
)

// targetFilter matches only the entity with the given ID. The filter is
// evaluated continuously: if the entity stops matching, you receive DELETED.
func targetFilter(entityID string) *Lattice.Statement {
	return &Lattice.Statement{
		Predicate: &Lattice.Predicate{
			FieldPath: Lattice.String("entity_id"),
			Value: &Lattice.Value{
				StringType: &Lattice.StringType{Value: Lattice.String(entityID)},
			},
			Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
		},
	}
}

// trackPosition is the newest position of a track, with velocity if known.
type trackPosition struct {
	lat, lon, hae float64
	velocityENU   *[3]float64
}

// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *Lattice.Entity) *trackPosition {
	if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic != nil && geodetic.Location != nil {
		loc := geodetic.Location
		pos := &trackPosition{
			lat: deref(loc.LatitudeDegrees),
			lon: deref(loc.LongitudeDegrees),
			hae: deref(loc.GetUniversalAltitudeHae().GetValueMeters()),
		}
		if v := geodetic.VelocityEnuMPerS; v != nil {
			pos.velocityENU = &[3]float64{deref(v.X), deref(v.Y), deref(v.Z)}
		}
		return pos
	}
	if loc := entity.GetLocation(); loc != nil && loc.Position != nil {
		pos := &trackPosition{
			lat: deref(loc.Position.LatitudeDegrees),
			lon: deref(loc.Position.LongitudeDegrees),
			hae: deref(loc.Position.AltitudeHaeMeters),
		}
		if v := loc.VelocityEnu; v != nil {
			pos.velocityENU = &[3]float64{deref(v.E), deref(v.N), deref(v.U)}
		}
		return pos
	}
	return nil
}

// deref returns the value of an optional field, or the zero value if unset.
func deref[T any](p *T) T {
	var zero T
	if p == nil {
		return zero
	}
	return *p
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatal("Required environment variables not set.")
	}

	headers := http.Header{}
	headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))

	latticeClient := client.NewClient(
		option.WithToken(environmentToken),
		option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
		option.WithHTTPHeader(headers),
	)

	// Stream only the target. Omit ComponentsToInclude to receive all components,
	// because listing components drops the others, which can include the position.
	stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
		Filter:              targetFilter(targetEntityID),
		HeartbeatIntervalMs: Lattice.Int(int(heartbeatInterval.Milliseconds())),
	})
	if err != nil {
		log.Fatalf("Failed to create entity stream: %v", err)
	}
	defer stream.Close()

	// Watchdog: warn when neither entity updates nor heartbeats arrive.
	var lastMessage atomic.Int64
	lastMessage.Store(time.Now().UnixNano())
	go func() {
		ticker := time.NewTicker(heartbeatInterval)
		defer ticker.Stop()
		for {
			select {
			case <-ctx.Done():
				return
			case <-ticker.C:
				silence := time.Since(time.Unix(0, lastMessage.Load()))
				if silence > staleAfter {
					log.Printf("WARNING: no message for %.1fs (expected a heartbeat every %.0fs)",
						silence.Seconds(), heartbeatInterval.Seconds())
				}
			}
		}
	}()

	log.Printf("Monitoring target %s", targetEntityID)
	var lastSourceTime time.Time

	for {
		message, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			log.Println("Stream completed successfully.")
			return
		}
		if err != nil {
			log.Fatalf("Error receiving message: %v", err)
		}
		lastMessage.Store(time.Now().UnixNano())

		switch message.Event {
		case "heartbeat":
			log.Printf("Heartbeat: %s", *message.Heartbeat.Timestamp)
		case "entity":
			event := message.Entity
			eventType := deref(event.EventType)
			switch eventType {
			case Lattice.EntityEventEventTypeEventTypeCreated,
				Lattice.EntityEventEventTypeEventTypePreexisting,
				Lattice.EntityEventEventTypeEventTypeUpdate:
				entity := event.Entity
				pos := extractPosition(entity)
				if pos == nil {
					continue
				}
				// Ignore updates that are not newer than the last one seen.
				sourceTime := deref(entity.GetProvenance().GetSourceUpdateTime())
				if sourceTime.IsZero() {
					sourceTime = deref(event.Time)
				}
				if !sourceTime.After(lastSourceTime) {
					continue
				}
				lastSourceTime = sourceTime

				line := fmt.Sprintf("%s lat=%.6f lon=%.6f hae=%.1fm", eventType, pos.lat, pos.lon, pos.hae)
				if v := pos.velocityENU; v != nil {
					line += fmt.Sprintf(" vel_enu=(%.1f,%.1f,%.1f)m/s", v[0], v[1], v[2])
				}
				log.Printf("%s age=%.1fs", line, time.Since(sourceTime).Seconds())
			case Lattice.EntityEventEventTypeEventTypeDeleted:
				// The target expired, was deleted, or stopped matching the filter.
				// A real interceptor would abort the engagement or request a new cue.
				log.Printf("Target lost: %s", targetEntityID)
				return
			}
		}
	}
}

```

```java title={"Java (REST)"} startLine={69} maxLines={31}
package org.example;

import com.anduril.AsyncLattice;
import com.anduril.resources.entities.requests.EntityStreamRequest;
import com.anduril.resources.entities.types.StreamEntitiesResponse;
import com.anduril.types.Entity;
import com.anduril.types.EntityEventEventType;
import com.anduril.types.EntityStreamEvent;
import com.anduril.types.Enu;
import com.anduril.types.KinematicsGeodetic;
import com.anduril.types.Location;
import com.anduril.types.LocationGeodetic;
import com.anduril.types.Position;
import com.anduril.types.Predicate;
import com.anduril.types.PredicateComparator;
import com.anduril.types.Statement;
import com.anduril.types.StringType;
import com.anduril.types.Value;
import com.anduril.types.Vec3;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Example application that monitors a single cued target track using the Lattice SDK.
 */
public class StreamTargetTrack {

    // Replace with the entity ID of the track you want to monitor.
    private static final String TARGET_ENTITY_ID = "<ENTITY_ID>";
    // Request a heartbeat every 5 seconds so silence is detectable.
    private static final int HEARTBEAT_INTERVAL_MS = 5000;
    // Warn if nothing arrives within three heartbeat intervals.
    private static final long STALE_AFTER_MS = 3L * HEARTBEAT_INTERVAL_MS;

    /** The newest position of a track, with velocity if known. */
    private static final class TrackPosition {
        final double lat;
        final double lon;
        final double hae;
        final double[] velocityEnu;

        TrackPosition(double lat, double lon, double hae, double[] velocityEnu) {
            this.lat = lat;
            this.lon = lon;
            this.hae = hae;
            this.velocityEnu = velocityEnu;
        }
    }

    /**
     * Match only the entity with the given ID. The filter is evaluated continuously:
     * if the entity stops matching, you receive a DELETED event.
     */
    static Statement targetFilter(String entityId) {
        return Statement.builder()
            .predicate(Predicate.builder()
                .fieldPath("entity_id")
                .value(Value.builder().stringType(StringType.builder().value(entityId).build()).build())
                .comparator(PredicateComparator.COMPARATOR_EQUALITY)
                .build())
            .build();
    }

    /**
     * Return the newest position, preferring kinematics over location. Kinematics is the
     * recommended source for tracks. Fall back to location if the entity has no kinematics.
     */
    static Optional<TrackPosition> extractPosition(Entity entity) {
        Optional<KinematicsGeodetic> geodetic = entity.getKinematics().flatMap(k -> k.getKinematicsGeodetic());
        if (geodetic.isPresent() && geodetic.get().getLocation().isPresent()) {
            LocationGeodetic loc = geodetic.get().getLocation().get();
            double[] velocity = geodetic.get().getVelocityEnuMPerS()
                .map((Vec3 v) -> new double[] {v.getX().orElse(0.0), v.getY().orElse(0.0), v.getZ().orElse(0.0)})
                .orElse(null);
            return Optional.of(new TrackPosition(
                loc.getLatitudeDegrees().orElse(0.0),
                loc.getLongitudeDegrees().orElse(0.0),
                loc.getUniversalAltitudeHae().flatMap(a -> a.getValueMeters()).orElse(0.0),
                velocity));
        }
        Optional<Location> location = entity.getLocation();
        if (location.isPresent() && location.get().getPosition().isPresent()) {
            Position position = location.get().getPosition().get();
            double[] velocity = location.get().getVelocityEnu()
                .map((Enu v) -> new double[] {v.getE().orElse(0.0), v.getN().orElse(0.0), v.getU().orElse(0.0)})
                .orElse(null);
            return Optional.of(new TrackPosition(
                position.getLatitudeDegrees().orElse(0.0),
                position.getLongitudeDegrees().orElse(0.0),
                position.getAltitudeHaeMeters().orElse(0.0),
                velocity));
        }
        return Optional.empty();
    }

    public static void main(String[] args) {
        // Get environment variables
        String endpoint = System.getenv("LATTICE_ENDPOINT");
        String environmentToken = System.getenv("ENVIRONMENT_TOKEN");
        String sandboxesToken = System.getenv("SANDBOXES_TOKEN");

        // Check required variables
        if (endpoint == null || environmentToken == null || sandboxesToken == null) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        // Watchdog: warn when neither entity updates nor heartbeats arrive.
        AtomicLong lastMessage = new AtomicLong(System.currentTimeMillis());
        ScheduledExecutorService watchdog = Executors.newSingleThreadScheduledExecutor(r -> {
            Thread thread = new Thread(r);
            thread.setDaemon(true);
            return thread;
        });
        watchdog.scheduleAtFixedRate(() -> {
            long silence = System.currentTimeMillis() - lastMessage.get();
            if (silence > STALE_AFTER_MS) {
                System.out.printf("WARNING: no message for %.1fs (expected a heartbeat every %ds)%n",
                    silence / 1000.0, HEARTBEAT_INTERVAL_MS / 1000);
            }
        }, HEARTBEAT_INTERVAL_MS, HEARTBEAT_INTERVAL_MS, TimeUnit.MILLISECONDS);

        try {
            AsyncLattice client = AsyncLattice.builder()
                .url(endpoint)
                .token(environmentToken)
                .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
                .build();

            // Omit componentsToInclude to receive all components, because listing
            // components drops the others, which can include the position.
            EntityStreamRequest request = EntityStreamRequest
                .builder()
                .filter(targetFilter(TARGET_ENTITY_ID))
                .heartbeatIntervalMs(HEARTBEAT_INTERVAL_MS)
                .build();

            System.out.println("Monitoring target " + TARGET_ENTITY_ID);
            client.entities().streamEntities(request)
                .thenAccept(responses -> {
                    OffsetDateTime lastSourceTime = null;
                    for (StreamEntitiesResponse response : responses) {
                        lastMessage.set(System.currentTimeMillis());

                        if (response.getHeartbeat().isPresent()) {
                            System.out.println("Heartbeat: " + response.getHeartbeat().get().getTimestamp().orElse(""));
                            continue;
                        }
                        if (!response.getEntity().isPresent()) {
                            continue;
                        }
                        EntityStreamEvent event = response.getEntity().get();
                        EntityEventEventType.Value type = event.getEventType()
                            .map(EntityEventEventType::getEnumValue)
                            .orElse(EntityEventEventType.Value.EVENT_TYPE_INVALID);

                        switch (type) {
                            case EVENT_TYPE_CREATED:
                            case EVENT_TYPE_PREEXISTING:
                            case EVENT_TYPE_UPDATE: {
                                Optional<Entity> entity = event.getEntity();
                                Optional<TrackPosition> position = entity.flatMap(StreamTargetTrack::extractPosition);
                                if (!position.isPresent()) {
                                    break;
                                }
                                // Ignore updates that are not newer than the last one seen.
                                Optional<OffsetDateTime> sourceTime = entity.get().getProvenance()
                                    .flatMap(p -> p.getSourceUpdateTime());
                                if (!sourceTime.isPresent()) {
                                    sourceTime = event.getTime();
                                }
                                if (!sourceTime.isPresent()
                                        || (lastSourceTime != null && !sourceTime.get().isAfter(lastSourceTime))) {
                                    break;
                                }
                                lastSourceTime = sourceTime.get();

                                TrackPosition p = position.get();
                                StringBuilder line = new StringBuilder(String.format(
                                    "%s lat=%.6f lon=%.6f hae=%.1fm", type, p.lat, p.lon, p.hae));
                                if (p.velocityEnu != null) {
                                    line.append(String.format(" vel_enu=(%.1f,%.1f,%.1f)m/s",
                                        p.velocityEnu[0], p.velocityEnu[1], p.velocityEnu[2]));
                                }
                                double ageSeconds = Duration.between(sourceTime.get(), OffsetDateTime.now()).toMillis() / 1000.0;
                                System.out.printf("%s age=%.1fs%n", line, ageSeconds);
                                break;
                            }
                            case EVENT_TYPE_DELETED:
                                // The target expired, was deleted, or stopped matching the filter.
                                // A real interceptor would abort the engagement or request a new cue.
                                System.out.println("Target lost: " + TARGET_ENTITY_ID);
                                System.exit(0);
                                return;
                            default:
                                break;
                        }
                    }
                })
                .exceptionally(ex -> {
                    System.err.println("Exception while streaming entities: " + ex.getMessage());
                    return null;
                })
                .join();
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
        watchdog.shutdownNow();
    }
}

```

```py title={"Python (REST)"} startLine={62} maxLines={27}
from anduril import (
    AsyncLattice,
    Entity,
    Predicate,
    Statement,
    StringType,
    Value,
)
from datetime import datetime, timezone
from typing import NamedTuple, Optional, Tuple
import asyncio
import os
import sys
import time

# Replace with the entity ID of the track you want to monitor.
TARGET_ENTITY_ID = "<ENTITY_ID>"
# Request a heartbeat every 5 seconds so silence is detectable.
HEARTBEAT_INTERVAL_MS = 5000
# Warn if nothing arrives within three heartbeat intervals.
STALE_AFTER_S = 3 * HEARTBEAT_INTERVAL_MS / 1000

lattice_endpoint = os.getenv('LATTICE_ENDPOINT')
environment_token = os.getenv('ENVIRONMENT_TOKEN')

# Remove sandboxes_token from the following statements if you are not developing on Sandboxes.
sandboxes_token = os.getenv('SANDBOXES_TOKEN')
if not environment_token or not lattice_endpoint or not sandboxes_token:
    print("Missing environment variables.")
    sys.exit(1)

client = AsyncLattice(
    base_url=f"https://{lattice_endpoint}",
    token=lambda: str(environment_token),
    # Remove the following header if you are not developing on Sandboxes.
    headers={ "anduril-sandbox-authorization": f"Bearer {sandboxes_token}" }
)


def target_filter(entity_id: str) -> Statement:
    """Match only the entity with the given ID.

    The filter is evaluated continuously: if the entity stops matching, you
    receive a DELETED event.
    """
    return Statement(
        predicate=Predicate(
            field_path="entity_id",
            value=Value(string_type=StringType(value=entity_id)),
            comparator="COMPARATOR_EQUALITY",
        )
    )


class TrackPosition(NamedTuple):
    lat: float
    lon: float
    hae: float
    velocity_enu: Optional[Tuple[float, float, float]]


def extract_position(entity: Entity) -> Optional[TrackPosition]:
    """Return the newest position, preferring kinematics over location.

    Kinematics is the recommended source for tracks. Fall back to location if
    the entity has no kinematics. Return None if neither has a position.
    """
    geodetic = entity.kinematics.kinematics_geodetic if entity.kinematics else None
    if geodetic and geodetic.location:
        loc = geodetic.location
        altitude = loc.universal_altitude_hae
        v = geodetic.velocity_enu_m_per_s
        return TrackPosition(
            lat=loc.latitude_degrees or 0.0,
            lon=loc.longitude_degrees or 0.0,
            hae=(altitude.value_meters if altitude else None) or 0.0,
            velocity_enu=(v.x or 0.0, v.y or 0.0, v.z or 0.0) if v else None,
        )
    if entity.location and entity.location.position:
        position = entity.location.position
        v = entity.location.velocity_enu
        return TrackPosition(
            lat=position.latitude_degrees or 0.0,
            lon=position.longitude_degrees or 0.0,
            hae=position.altitude_hae_meters or 0.0,
            velocity_enu=(v.e or 0.0, v.n or 0.0, v.u or 0.0) if v else None,
        )
    return None


async def watchdog(last_message: list[float]):
    """Warn when neither entity updates nor heartbeats arrive."""
    while True:
        await asyncio.sleep(HEARTBEAT_INTERVAL_MS / 1000)
        silence = time.monotonic() - last_message[0]
        if silence > STALE_AFTER_S:
            print(f"WARNING: no message for {silence:.1f}s "
                  f"(expected a heartbeat every {HEARTBEAT_INTERVAL_MS / 1000:.0f}s)")


async def app():
    last_message = [time.monotonic()]
    watchdog_task = asyncio.create_task(watchdog(last_message))
    last_source_time: Optional[datetime] = None

    try:
        # Omit components_to_include to receive all components, because listing
        # components drops the others, which can include the position.
        event_stream = client.entities.stream_entities(
            filter=target_filter(TARGET_ENTITY_ID),
            heartbeat_interval_ms=HEARTBEAT_INTERVAL_MS,
        )
        print(f"Monitoring target {TARGET_ENTITY_ID}")
        async for event in event_stream:
            last_message[0] = time.monotonic()

            if event.event == "heartbeat":
                print(f"Heartbeat: {event.timestamp}")
                continue
            if event.event != "entity":
                continue

            if event.event_type in ("EVENT_TYPE_CREATED", "EVENT_TYPE_PREEXISTING", "EVENT_TYPE_UPDATE"):
                entity = event.entity
                if not entity:
                    continue
                position = extract_position(entity)
                if not position:
                    continue
                # Ignore updates that are not newer than the last one seen.
                source_time = (entity.provenance.source_update_time if entity.provenance else None) or event.time
                if not source_time:
                    continue
                if last_source_time and source_time <= last_source_time:
                    continue
                last_source_time = source_time

                line = f"{event.event_type} lat={position.lat:.6f} lon={position.lon:.6f} hae={position.hae:.1f}m"
                if position.velocity_enu:
                    e, n, u = position.velocity_enu
                    line += f" vel_enu=({e:.1f},{n:.1f},{u:.1f})m/s"
                age = (datetime.now(timezone.utc) - source_time).total_seconds()
                print(f"{line} age={age:.1f}s")
            elif event.event_type == "EVENT_TYPE_DELETED":
                # The target expired, was deleted, or stopped matching the filter.
                # An interceptor would abort the engagement or request a new cue.
                print(f"Target lost: {TARGET_ENTITY_ID}")
                return
    except asyncio.CancelledError:
        print("Streaming cancelled...")
    except Exception as error:
        print(f"Exception: {error}")
    finally:
        watchdog_task.cancel()

if __name__ == "__main__":
    asyncio.run(app())

```

```ts title={"TypeScript (REST)"} startLine={48} maxLines={26}
import { Lattice, LatticeClient } from "@anduril-industries/lattice-sdk";

// Replace with the entity ID of the track you want to monitor.
const targetEntityId = "<ENTITY_ID>";
// Request a heartbeat every 5 seconds so silence is detectable.
const heartbeatIntervalMs = 5000;
// Warn if nothing arrives within three heartbeat intervals.
const staleAfterMs = 3 * heartbeatIntervalMs;

const latticeEndpoint = process.env.LATTICE_ENDPOINT;
const environmentToken = process.env.ENVIRONMENT_TOKEN;

// Remove sandboxesToken from the following statement if you are not developing on Sandboxes.
const sandboxesToken = process.env.SANDBOXES_TOKEN;
if (!latticeEndpoint || !environmentToken || !sandboxesToken) {
    console.log('Missing required environment variables.');
    process.exit(1);
}

const client = new LatticeClient(
    {
        baseUrl: `https://${latticeEndpoint}`,
        token: environmentToken,
        // Remove the following statement if you are not developing on Sandboxes.
        headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}` }
    }
);

// Match only the entity with the given ID. The filter is evaluated continuously:
// if the entity stops matching, you receive a DELETED event.
function targetFilter(entityId: string): Lattice.Statement {
    return {
        predicate: {
            fieldPath: "entity_id",
            value: { stringType: { value: entityId } },
            comparator: "COMPARATOR_EQUALITY",
        },
    };
}

interface TrackPosition {
    lat: number;
    lon: number;
    hae: number;
    velocityEnu?: [number, number, number];
}

// Return the newest position, preferring kinematics over location. Kinematics
// is the recommended source for tracks. Fall back to location if the entity
// has no kinematics. Return undefined if neither has a position.
function extractPosition(entity: Lattice.Entity): TrackPosition | undefined {
    const geodetic = entity.kinematics?.kinematicsGeodetic;
    if (geodetic?.location) {
        const v = geodetic.velocityEnuMPerS;
        return {
            lat: geodetic.location.latitudeDegrees ?? 0,
            lon: geodetic.location.longitudeDegrees ?? 0,
            hae: geodetic.location.universalAltitudeHae?.valueMeters ?? 0,
            velocityEnu: v ? [v.x ?? 0, v.y ?? 0, v.z ?? 0] : undefined,
        };
    }
    const position = entity.location?.position;
    if (position) {
        const v = entity.location?.velocityEnu;
        return {
            lat: position.latitudeDegrees ?? 0,
            lon: position.longitudeDegrees ?? 0,
            hae: position.altitudeHaeMeters ?? 0,
            velocityEnu: v ? [v.e ?? 0, v.n ?? 0, v.u ?? 0] : undefined,
        };
    }
    return undefined;
}

async function App() {
    // Watchdog: warn when neither entity updates nor heartbeats arrive.
    let lastMessage = Date.now();
    const watchdog = setInterval(() => {
        const silence = Date.now() - lastMessage;
        if (silence > staleAfterMs) {
            console.log(`WARNING: no message for ${(silence / 1000).toFixed(1)}s (expected a heartbeat every ${heartbeatIntervalMs / 1000}s)`);
        }
    }, heartbeatIntervalMs);

    let lastSourceTime = 0;
    try {
        // Omit componentsToInclude to receive all components, because listing
        // components drops the others, which can include the position.
        const eventStream = await client.entities.streamEntities({
            filter: targetFilter(targetEntityId),
            heartbeatIntervalMS: heartbeatIntervalMs,
        });
        console.log(`Monitoring target ${targetEntityId}`);

        for await (const event of eventStream) {
            lastMessage = Date.now();

            if (event.event === "heartbeat") {
                console.log(`Heartbeat: ${event.timestamp}`);
                continue;
            }

            switch (event.eventType) {
                case "EVENT_TYPE_CREATED":
                case "EVENT_TYPE_PREEXISTING":
                case "EVENT_TYPE_UPDATE": {
                    const entity = event.entity;
                    const position = entity && extractPosition(entity);
                    if (!entity || !position) {
                        break;
                    }
                    // Ignore updates that are not newer than the last one seen.
                    const sourceTime = Date.parse(entity.provenance?.sourceUpdateTime ?? event.time ?? "");
                    if (Number.isNaN(sourceTime) || sourceTime <= lastSourceTime) {
                        break;
                    }
                    lastSourceTime = sourceTime;

                    let line = `${event.eventType} lat=${position.lat.toFixed(6)} lon=${position.lon.toFixed(6)} hae=${position.hae.toFixed(1)}m`;
                    if (position.velocityEnu) {
                        const [e, n, u] = position.velocityEnu;
                        line += ` vel_enu=(${e.toFixed(1)},${n.toFixed(1)},${u.toFixed(1)})m/s`;
                    }
                    console.log(`${line} age=${((Date.now() - sourceTime) / 1000).toFixed(1)}s`);
                    break;
                }
                case "EVENT_TYPE_DELETED":
                    // The target expired, was deleted, or stopped matching the filter.
                    // A real interceptor would abort the engagement or request a new cue.
                    console.log(`Target lost: ${targetEntityId}`);
                    clearInterval(watchdog);
                    return;
            }
        }
    } catch (error) {
        console.log(`Exception while streaming entities: ${error}`);
    }
    clearInterval(watchdog);
}

App();

```

```rs title={"Rust (REST)"} startLine={37} maxLines={36}
use anduril_lattice_sdk::prelude::*;

use chrono::Utc;
use std::env;
use std::time::Duration;
use tokio::time::{timeout_at, Instant};

// Replace with the entity ID of the track you want to monitor.
const TARGET_ENTITY_ID: &str = "<ENTITY_ID>";
// Request a heartbeat every 5 seconds so silence is detectable.
const HEARTBEAT_INTERVAL_MS: i64 = 5000;
// Warn if nothing arrives within three heartbeat intervals.
const STALE_AFTER: Duration = Duration::from_millis(3 * HEARTBEAT_INTERVAL_MS as u64);

/// The newest position of a track, with velocity if known.
struct TrackPosition {
    lat: f64,
    lon: f64,
    hae: f64,
    velocity_enu: Option<(f64, f64, f64)>,
}

/// Matches only the entity with the given ID. The filter is evaluated
/// continuously: if the entity stops matching, you receive DELETED.
fn target_filter(entity_id: &str) -> Statement {
    Statement {
        predicate: Some(Predicate {
            field_path: Some("entity_id".to_string()),
            // The SDK models the predicate value as free-form JSON.
            value: Some(json!({ "stringType": { "value": entity_id } })),
            comparator: Some(PredicateComparator::ComparatorEquality),
        }),
        ..Default::default()
    }
}

/// Returns the newest position, preferring kinematics over location. Kinematics
/// is the recommended source for tracks. Falls back to location if the entity
/// has no kinematics. Returns None if neither has a position.
fn extract_position(entity: &Entity) -> Option<TrackPosition> {
    if let Some(geodetic) = entity
        .kinematics
        .as_ref()
        .and_then(|k| k.kinematics_geodetic.as_ref())
    {
        if let Some(loc) = &geodetic.location {
            return Some(TrackPosition {
                lat: loc.latitude_degrees.unwrap_or(0.0),
                lon: loc.longitude_degrees.unwrap_or(0.0),
                hae: loc
                    .universal_altitude_hae
                    .as_ref()
                    .and_then(|a| a.value_meters)
                    .unwrap_or(0.0),
                velocity_enu: geodetic.velocity_enu_m_per_s.as_ref().map(|v| {
                    (v.x.unwrap_or(0.0), v.y.unwrap_or(0.0), v.z.unwrap_or(0.0))
                }),
            });
        }
    }
    let location = entity.location.as_ref()?;
    let position = location.position.as_ref()?;
    Some(TrackPosition {
        lat: position.latitude_degrees.unwrap_or(0.0),
        lon: position.longitude_degrees.unwrap_or(0.0),
        hae: position.altitude_hae_meters.unwrap_or(0.0),
        velocity_enu: location
            .velocity_enu
            .as_ref()
            .map(|v| (v.e.unwrap_or(0.0), v.n.unwrap_or(0.0), v.u.unwrap_or(0.0))),
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    // Remove sandboxes_token if you are not developing on Sandboxes.
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables:");
        eprintln!("  LATTICE_ENDPOINT");
        eprintln!("  ENVIRONMENT_TOKEN");
        eprintln!("  SANDBOXES_TOKEN");
        std::process::exit(1);
    }

    let config = ClientConfig {
        base_url: format!("https://{}", lattice_endpoint),
        token: Some(environment_token),
        // Remove custom_headers if you are not developing on Sandboxes.
        custom_headers: HashMap::from([(
            "anduril-sandbox-authorization".to_string(),
            format!("Bearer {}", sandboxes_token),
        )]),
        ..Default::default()
    };
    let client = Lattice::new(config)?;

    // Stream only the target. Leave components_to_include unset to receive all
    // components, because listing components drops the others, which can include the position.
    let request = EntityStreamRequest {
        filter: Some(target_filter(TARGET_ENTITY_ID)),
        heartbeat_interval_ms: Some(HEARTBEAT_INTERVAL_MS),
        ..Default::default()
    };
    let stream = client.entities.stream_entities(&request, None).await?;
    let mut stream = std::pin::pin!(stream);

    println!("Monitoring target {}", TARGET_ENTITY_ID);
    let mut last_source_time: Option<DateTime<FixedOffset>> = None;
    // Watchdog: the deadline moves forward each time a message arrives.
    let mut deadline = Instant::now() + STALE_AFTER;

    loop {
        let result = match timeout_at(deadline, stream.next()).await {
            Ok(Some(result)) => result,
            Ok(None) => break,
            Err(_) => {
                println!(
                    "WARNING: no message for {}s (expected a heartbeat every {}s)",
                    STALE_AFTER.as_secs(),
                    HEARTBEAT_INTERVAL_MS / 1000
                );
                deadline = Instant::now() + STALE_AFTER;
                continue;
            }
        };
        deadline = Instant::now() + STALE_AFTER;

        let event = match result {
            Ok(event) => event,
            Err(error) => {
                eprintln!("Exception: {}", error);
                continue;
            }
        };

        match event {
            StreamEntitiesResponse::Heartbeat { data, .. } => {
                println!(
                    "Heartbeat: {}",
                    data.heartbeat_object_fields.timestamp.unwrap_or_default()
                );
            }
            StreamEntitiesResponse::Entity { data, .. } => {
                let event = data.entity_event_fields;
                match event.event_type {
                    Some(
                        EntityEventEventType::EventTypeCreated
                        | EntityEventEventType::EventTypePreexisting
                        | EntityEventEventType::EventTypeUpdate,
                    ) => {
                        let Some(entity) = &event.entity else { continue };
                        let Some(position) = extract_position(entity) else { continue };
                        // Ignore updates that are not newer than the last one seen.
                        let source_time = entity
                            .provenance
                            .as_ref()
                            .and_then(|p| p.source_update_time)
                            .or(event.time);
                        let Some(source_time) = source_time else { continue };
                        if last_source_time.is_some_and(|last| source_time <= last) {
                            continue;
                        }
                        last_source_time = Some(source_time);

                        let mut line = format!(
                            "{} lat={:.6} lon={:.6} hae={:.1}m",
                            event.event_type.as_ref().map(|t| t.to_string()).unwrap_or_default(),
                            position.lat,
                            position.lon,
                            position.hae
                        );
                        if let Some((e, n, u)) = position.velocity_enu {
                            line.push_str(&format!(" vel_enu=({:.1},{:.1},{:.1})m/s", e, n, u));
                        }
                        let age = (Utc::now() - source_time.with_timezone(&Utc)).num_milliseconds()
                            as f64
                            / 1000.0;
                        println!("{} age={:.1}s", line, age);
                    }
                    Some(EntityEventEventType::EventTypeDeleted) => {
                        // The target expired, was deleted, or stopped matching the filter.
                        // A real interceptor would abort the engagement or request a new cue.
                        println!("Target lost: {}", TARGET_ENTITY_ID);
                        return Ok(());
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }

    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={53} maxLines={29}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"os"
	"sync/atomic"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

const (
	// Replace with the entity ID of the track you want to monitor.
	targetEntityID = "<ENTITY_ID>"
	// Request a heartbeat every 5 seconds so silence is detectable.
	heartbeatInterval = 5 * time.Second
	// Warn if nothing arrives within three heartbeat intervals.
	staleAfter = 3 * heartbeatInterval
)

// targetFilter matches only the entity with the given ID. The filter is
// evaluated continuously: if the entity stops matching, you receive DELETED.
func targetFilter(entityID string) *entitymanagerv1.Statement {
	return &entitymanagerv1.Statement{
		Operation: &entitymanagerv1.Statement_Predicate{
			Predicate: &entitymanagerv1.Predicate{
				FieldPath: "entity_id",
				Value: &entitymanagerv1.Value{
					Type: &entitymanagerv1.Value_StringType{
						StringType: &entitymanagerv1.StringType{Value: entityID},
					},
				},
				Comparator: entitymanagerv1.Comparator_COMPARATOR_EQUALITY,
			},
		},
	}
}

// trackPosition is the newest position of a track, with velocity if known.
type trackPosition struct {
	lat, lon, hae float64
	velocityENU   *[3]float64
}

// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *entitymanagerv1.Entity) *trackPosition {
	if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic.GetLocation() != nil {
		loc := geodetic.GetLocation()
		pos := &trackPosition{
			lat: loc.GetLatitudeDegrees(),
			lon: loc.GetLongitudeDegrees(),
			hae: loc.GetUniversalAltitudeHae().GetValueMeters(),
		}
		if v := geodetic.GetVelocityEnuMPerS(); v != nil {
			pos.velocityENU = &[3]float64{v.GetX(), v.GetY(), v.GetZ()}
		}
		return pos
	}
	if loc := entity.GetLocation(); loc.GetPosition() != nil {
		position := loc.GetPosition()
		pos := &trackPosition{
			lat: position.GetLatitudeDegrees(),
			lon: position.GetLongitudeDegrees(),
			hae: position.GetAltitudeHaeMeters().GetValue(),
		}
		if v := loc.GetVelocityEnu(); v != nil {
			pos.velocityENU = &[3]float64{v.GetE(), v.GetN(), v.GetU()}
		}
		return pos
	}
	return nil
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatalf("Missing required environment variables")
	}
	auth := &BearerTokenAuth{
		Token:          environmentToken,
		SandboxesToken: sandboxesToken,
	}

	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}
	conn, err := grpc.NewClient(latticeEndpoint, opts...)
	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	// Stream only the target, with all components. Don't set components_to_include,
	// because listing components drops the others, which can include the position.
	stream, err := client.StreamEntityComponents(ctx, &entitymanagerv1.StreamEntityComponentsRequest{
		Filter:                targetFilter(targetEntityID),
		IncludeAllComponents:  true,
		HeartbeatPeriodMillis: uint32(heartbeatInterval.Milliseconds()),
	})
	if err != nil {
		log.Fatalf("Error creating stream: %v", err)
	}

	// Watchdog: warn when neither entity updates nor heartbeats arrive.
	var lastMessage atomic.Int64
	lastMessage.Store(time.Now().UnixNano())
	go func() {
		ticker := time.NewTicker(heartbeatInterval)
		defer ticker.Stop()
		for {
			select {
			case <-ctx.Done():
				return
			case <-ticker.C:
				silence := time.Since(time.Unix(0, lastMessage.Load()))
				if silence > staleAfter {
					log.Printf("WARNING: no message for %.1fs (expected a heartbeat every %.0fs)",
						silence.Seconds(), heartbeatInterval.Seconds())
				}
			}
		}
	}()

	log.Printf("Monitoring target %s", targetEntityID)
	var lastSourceTime time.Time

	for {
		response, err := stream.Recv()
		if err == io.EOF {
			log.Println("Stream completed successfully.")
			return
		}
		if err != nil {
			log.Fatalf("Error receiving stream data: %v", err)
		}
		lastMessage.Store(time.Now().UnixNano())

		if response.GetHeartbeat() != nil {
			log.Printf("Heartbeat: %s", response.GetHeartbeat().GetTimestamp().AsTime().Format(time.RFC3339))
			continue
		}
		event := response.GetEntityEvent()
		eventType := event.GetEventType()

		switch eventType {
		case entitymanagerv1.EventType_EVENT_TYPE_CREATED,
			entitymanagerv1.EventType_EVENT_TYPE_PREEXISTING,
			entitymanagerv1.EventType_EVENT_TYPE_UPDATE:
			entity := event.GetEntity()
			pos := extractPosition(entity)
			if pos == nil {
				continue
			}
			// Ignore updates that are not newer than the last one seen.
			sourceTime := entity.GetProvenance().GetSourceUpdateTime().AsTime()
			if entity.GetProvenance().GetSourceUpdateTime() == nil {
				sourceTime = event.GetTime().AsTime()
			}
			if !sourceTime.After(lastSourceTime) {
				continue
			}
			lastSourceTime = sourceTime

			line := fmt.Sprintf("%s lat=%.6f lon=%.6f hae=%.1fm", eventType, pos.lat, pos.lon, pos.hae)
			if v := pos.velocityENU; v != nil {
				line += fmt.Sprintf(" vel_enu=(%.1f,%.1f,%.1f)m/s", v[0], v[1], v[2])
			}
			log.Printf("%s age=%.1fs", line, time.Since(sourceTime).Seconds())
		case entitymanagerv1.EventType_EVENT_TYPE_DELETED:
			// The target expired, was deleted, or stopped matching the filter.
			// A real interceptor would abort the engagement or request a new cue.
			log.Printf("Target lost: %s", targetEntityID)
			return
		}
	}
}

```

```py title={"Python (gRPC)"} startLine={56} maxLines={27}
# This Python example is compatible with artifacts generated using the following
# Buf plugins: https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:bufbuild/py
# and https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:connectrpc/py

import os
import sys
import threading
import time
from datetime import datetime, timezone
from typing import NamedTuple, Optional, Tuple

from bearer_auth import create_client
from protobuf import Oneof

from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.entity_manager_api_pub_pb import (
    EventType,
    StreamEntityComponentsRequest,
)
from anduril.entitymanager.v1.entity_pub_pb import Entity
from anduril.entitymanager.v1.filter_pub_pb import Comparator, Predicate, Statement, StringType, Value

# Replace with the entity ID of the track you want to monitor.
TARGET_ENTITY_ID = "<ENTITY_ID>"
# Request a heartbeat every 5 seconds so silence is detectable.
HEARTBEAT_PERIOD_MS = 5000
# Warn if nothing arrives within three heartbeat intervals.
STALE_AFTER_S = 3 * HEARTBEAT_PERIOD_MS / 1000


def target_filter(entity_id: str) -> Statement:
    """Match only the entity with the given ID.

    The filter is evaluated continuously: if the entity stops matching, you
    receive a DELETED event.
    """
    return Statement(
        operation=Oneof(
            "predicate",
            Predicate(
                field_path="entity_id",
                value=Value(type=Oneof("string_type", StringType(value=entity_id))),
                comparator=Comparator.EQUALITY,
            ),
        )
    )


class TrackPosition(NamedTuple):
    lat: float
    lon: float
    hae: float
    velocity_enu: Optional[Tuple[float, float, float]]


def extract_position(entity: Entity) -> Optional[TrackPosition]:
    """Return the newest position, preferring kinematics over location.

    Kinematics is the recommended source for tracks. Fall back to location if
    the entity has no kinematics. Return None if neither has a position.
    """
    if entity.has_field("kinematics") and entity.kinematics.has_field("kinematics_geodetic"):
        geodetic = entity.kinematics.kinematics_geodetic
        if geodetic.has_field("location"):
            loc = geodetic.location
            v = geodetic.velocity_enu_m_per_s if geodetic.has_field("velocity_enu_m_per_s") else None
            return TrackPosition(
                lat=loc.latitude_degrees,
                lon=loc.longitude_degrees,
                hae=loc.universal_altitude_hae.value_meters,
                velocity_enu=(v.x, v.y, v.z) if v else None,
            )
    if entity.has_field("location") and entity.location.has_field("position"):
        position = entity.location.position
        v = entity.location.velocity_enu if entity.location.has_field("velocity_enu") else None
        return TrackPosition(
            lat=position.latitude_degrees,
            lon=position.longitude_degrees,
            hae=position.altitude_hae_meters.value if position.has_field("altitude_hae_meters") else 0.0,
            velocity_enu=(v.e, v.n, v.u) if v else None,
        )
    return None


def watch_for_silence(last_message: list[float]) -> None:
    """Warn when neither entity updates nor heartbeats arrive."""
    while True:
        time.sleep(HEARTBEAT_PERIOD_MS / 1000)
        silence = time.monotonic() - last_message[0]
        if silence > STALE_AFTER_S:
            print(f"WARNING: no message for {silence:.1f}s "
                  f"(expected a heartbeat every {HEARTBEAT_PERIOD_MS / 1000:.0f}s)")


def main():
    environment_token = os.getenv("ENVIRONMENT_TOKEN")
    lattice_endpoint = os.getenv("LATTICE_ENDPOINT")
    sandboxes_token = os.getenv("SANDBOXES_TOKEN")

    if not environment_token or not lattice_endpoint or not sandboxes_token:
        print("Missing required environment variables", file=sys.stderr)
        sys.exit(1)

    # Create the API client over Connect gRPC with authentication
    client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    # Stream only the target, with all components. Don't set components_to_include,
    # because listing components drops the others, which can include the position.
    request = StreamEntityComponentsRequest(
        filter=target_filter(TARGET_ENTITY_ID),
        include_all_components=True,
        heartbeat_period_millis=HEARTBEAT_PERIOD_MS,
    )

    try:
        stream = client.stream_entity_components(request)
    except Exception as error:
        print(f"Error creating stream: {error}", file=sys.stderr)
        sys.exit(1)

    last_message = [time.monotonic()]
    threading.Thread(target=watch_for_silence, args=(last_message,), daemon=True).start()
    last_source_time: Optional[datetime] = None

    print(f"Monitoring target {TARGET_ENTITY_ID}")
    try:
        for response in stream:
            last_message[0] = time.monotonic()

            if response.has_field("heartbeat"):
                print(f"Heartbeat: {response.heartbeat.timestamp.to_datetime().isoformat()}")
                continue
            if not response.has_field("entity_event"):
                continue
            event = response.entity_event

            if event.event_type in (EventType.CREATED, EventType.PREEXISTING, EventType.UPDATE):
                entity = event.entity
                position = extract_position(entity) if entity else None
                if not entity or not position:
                    continue
                # Ignore updates that are not newer than the last one seen.
                if entity.has_field("provenance") and entity.provenance.has_field("source_update_time"):
                    source_time = entity.provenance.source_update_time.to_datetime()
                else:
                    source_time = event.time.to_datetime()
                if last_source_time and source_time <= last_source_time:
                    continue
                last_source_time = source_time

                line = f"EVENT_TYPE_{event.event_type.name} lat={position.lat:.6f} lon={position.lon:.6f} hae={position.hae:.1f}m"
                if position.velocity_enu:
                    e, n, u = position.velocity_enu
                    line += f" vel_enu=({e:.1f},{n:.1f},{u:.1f})m/s"
                age = (datetime.now(timezone.utc) - source_time).total_seconds()
                print(f"{line} age={age:.1f}s")
            elif event.event_type == EventType.DELETED:
                # The target expired, was deleted, or stopped matching the filter.
                # A real interceptor would abort the engagement or request a new cue.
                print(f"Target lost: {TARGET_ENTITY_ID}")
                return
        print("End of stream reached.")
    except Exception as error:
        print(f"Error receiving stream data: {error}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={50} maxLines={33}
// This Rust example is compatible with artifacts generated using
// the following grpc/rust plugin: https://buf.build/anduril/lattice-sdk/sdks/main:community/neoeinstein-tonic
mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    statement, value, Comparator, Entity, EventType, Predicate, Statement,
    StreamEntityComponentsRequest, StringType, Value,
};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use tonic::metadata::MetadataValue;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::Request;

use std::env;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::time::{timeout_at, Instant};

// Replace with the entity ID of the track you want to monitor.
const TARGET_ENTITY_ID: &str = "<ENTITY_ID>";
// Request a heartbeat every 5 seconds so silence is detectable.
const HEARTBEAT_PERIOD_MS: u32 = 5000;
// Warn if nothing arrives within three heartbeat intervals.
const STALE_AFTER: Duration = Duration::from_millis(3 * HEARTBEAT_PERIOD_MS as u64);

/// The newest position of a track, with velocity if known.
struct TrackPosition {
    lat: f64,
    lon: f64,
    hae: f64,
    velocity_enu: Option<(f64, f64, f64)>,
}

/// Matches only the entity with the given ID. The filter is evaluated
/// continuously: if the entity stops matching, you receive DELETED.
fn target_filter(entity_id: &str) -> Statement {
    Statement {
        operation: Some(statement::Operation::Predicate(Predicate {
            field_path: "entity_id".to_string(),
            value: Some(Value {
                r#type: Some(value::Type::StringType(StringType {
                    value: entity_id.to_string(),
                })),
            }),
            comparator: Comparator::Equality as i32,
        })),
    }
}

/// Returns the newest position, preferring kinematics over location. Kinematics
/// is the recommended source for tracks. Falls back to location if the entity
/// has no kinematics. Returns None if neither has a position.
fn extract_position(entity: &Entity) -> Option<TrackPosition> {
    if let Some(geodetic) = entity
        .kinematics
        .as_ref()
        .and_then(|k| k.kinematics_geodetic.as_ref())
    {
        if let Some(loc) = &geodetic.location {
            return Some(TrackPosition {
                lat: loc.latitude_degrees,
                lon: loc.longitude_degrees,
                hae: loc
                    .universal_altitude_hae
                    .as_ref()
                    .map_or(0.0, |a| a.value_meters),
                velocity_enu: geodetic
                    .velocity_enu_m_per_s
                    .as_ref()
                    .map(|v| (v.x, v.y, v.z)),
            });
        }
    }
    let location = entity.location.as_ref()?;
    let position = location.position.as_ref()?;
    Some(TrackPosition {
        lat: position.latitude_degrees,
        lon: position.longitude_degrees,
        hae: position.altitude_hae_meters.unwrap_or(0.0),
        velocity_enu: location.velocity_enu.as_ref().map(|v| (v.e, v.n, v.u)),
    })
}

/// Converts a protobuf timestamp to seconds since the Unix epoch.
fn timestamp_secs(ts: &prost_types::Timestamp) -> f64 {
    ts.seconds as f64 + f64::from(ts.nanos) / 1e9
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load environment variables
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    // Set up authentication handler
    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

    // Create gRPC channel with TLS
    let tls_config = ClientTlsConfig::new().with_native_roots();
    let channel = Channel::from_shared(format!("https://{}", lattice_endpoint))?
        .tls_config(tls_config)?
        .connect()
        .await?;

    // Fetch a fresh access token and build metadata values
    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<_> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<_> = format!("Bearer {}", sandboxes_token).parse()?;

    // Create EntityManager API client with authentication interceptor
    let mut client = EntityManagerApiClient::with_interceptor(
        channel,
        move |mut req: Request<()>| {
            req.metadata_mut()
                .insert("authorization", auth_header.clone());
            req.metadata_mut()
                .insert("anduril-sandbox-authorization", sandbox_header.clone());
            Ok(req)
        },
    );

    // Stream only the target, with all components. Don't set components_to_include,
    // because listing components drops the others, which can include the position.
    let request = Request::new(StreamEntityComponentsRequest {
        filter: Some(target_filter(TARGET_ENTITY_ID)),
        include_all_components: true,
        heartbeat_period_millis: HEARTBEAT_PERIOD_MS,
        ..Default::default()
    });

    let mut stream = client.stream_entity_components(request).await?.into_inner();

    println!("Monitoring target {}", TARGET_ENTITY_ID);
    let mut last_source_secs: Option<f64> = None;
    // Watchdog: the deadline moves forward each time a message arrives.
    let mut deadline = Instant::now() + STALE_AFTER;

    loop {
        let response = match timeout_at(deadline, stream.message()).await {
            Ok(message) => match message? {
                Some(response) => response,
                None => break,
            },
            Err(_) => {
                println!(
                    "WARNING: no message for {}s (expected a heartbeat every {}s)",
                    STALE_AFTER.as_secs(),
                    HEARTBEAT_PERIOD_MS / 1000
                );
                deadline = Instant::now() + STALE_AFTER;
                continue;
            }
        };
        deadline = Instant::now() + STALE_AFTER;

        if let Some(heartbeat) = response.heartbeat {
            let secs = heartbeat.timestamp.as_ref().map_or(0.0, timestamp_secs);
            println!("Heartbeat: {:.3}", secs);
            continue;
        }
        let Some(event) = response.entity_event else { continue };

        match EventType::try_from(event.event_type) {
            Ok(EventType::Created | EventType::Preexisting | EventType::Update) => {
                let Some(entity) = &event.entity else { continue };
                let Some(position) = extract_position(entity) else { continue };
                // Ignore updates that are not newer than the last one seen.
                let source_time = entity
                    .provenance
                    .as_ref()
                    .and_then(|p| p.source_update_time.as_ref())
                    .or(event.time.as_ref());
                let Some(source_secs) = source_time.map(timestamp_secs) else { continue };
                if last_source_secs.is_some_and(|last| source_secs <= last) {
                    continue;
                }
                last_source_secs = Some(source_secs);

                let mut line = format!(
                    "{} lat={:.6} lon={:.6} hae={:.1}m",
                    EventType::try_from(event.event_type)?.as_str_name(),
                    position.lat,
                    position.lon,
                    position.hae
                );
                if let Some((e, n, u)) = position.velocity_enu {
                    line.push_str(&format!(" vel_enu=({:.1},{:.1},{:.1})m/s", e, n, u));
                }
                let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs_f64();
                println!("{} age={:.1}s", line, now - source_secs);
            }
            Ok(EventType::Deleted) => {
                // The target expired, was deleted, or stopped matching the filter.
                // A real interceptor would abort the engagement or request a new cue.
                println!("Target lost: {}", TARGET_ENTITY_ID);
                return Ok(());
            }
            _ => {}
        }
    }
    println!("End of stream reached");

    Ok(())
}

```

#### Stream and handle events

Open the stream with the filter and a heartbeat interval, then handle each event type:

* On `EVENT_TYPE_PREEXISTING`, `EVENT_TYPE_CREATED`, or `EVENT_TYPE_UPDATE`, read the newest position. Skip any update whose `provenance.source_update_time` isn't newer than the last one you used, so the effector never steers toward stale data.
* On `EVENT_TYPE_DELETED`, treat the target as lost. A real interceptor aborts the engagement or requests a new cue.
* On every message, including heartbeats, record the time. If nothing arrives for several heartbeat intervals, warn that the connection might be stale.

Request all components, rather than listing them in `componentsToInclude`, so the target's
position arrives whichever component carries it, `location` or `kinematics`:

```go title={"Go (REST)"} startLine={107} maxLines={75}
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"sync/atomic"
	"time"

	Lattice "github.com/anduril/lattice-sdk-go/v5"
	"github.com/anduril/lattice-sdk-go/v5/client"
	"github.com/anduril/lattice-sdk-go/v5/option"
)

const (
	// Replace with the entity ID of the track you want to monitor.
	targetEntityID = "<ENTITY_ID>"
	// Request a heartbeat every 5 seconds so silence is detectable.
	heartbeatInterval = 5 * time.Second
	// Warn if nothing arrives within three heartbeat intervals.
	staleAfter = 3 * heartbeatInterval
)

// targetFilter matches only the entity with the given ID. The filter is
// evaluated continuously: if the entity stops matching, you receive DELETED.
func targetFilter(entityID string) *Lattice.Statement {
	return &Lattice.Statement{
		Predicate: &Lattice.Predicate{
			FieldPath: Lattice.String("entity_id"),
			Value: &Lattice.Value{
				StringType: &Lattice.StringType{Value: Lattice.String(entityID)},
			},
			Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
		},
	}
}

// trackPosition is the newest position of a track, with velocity if known.
type trackPosition struct {
	lat, lon, hae float64
	velocityENU   *[3]float64
}

// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *Lattice.Entity) *trackPosition {
	if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic != nil && geodetic.Location != nil {
		loc := geodetic.Location
		pos := &trackPosition{
			lat: deref(loc.LatitudeDegrees),
			lon: deref(loc.LongitudeDegrees),
			hae: deref(loc.GetUniversalAltitudeHae().GetValueMeters()),
		}
		if v := geodetic.VelocityEnuMPerS; v != nil {
			pos.velocityENU = &[3]float64{deref(v.X), deref(v.Y), deref(v.Z)}
		}
		return pos
	}
	if loc := entity.GetLocation(); loc != nil && loc.Position != nil {
		pos := &trackPosition{
			lat: deref(loc.Position.LatitudeDegrees),
			lon: deref(loc.Position.LongitudeDegrees),
			hae: deref(loc.Position.AltitudeHaeMeters),
		}
		if v := loc.VelocityEnu; v != nil {
			pos.velocityENU = &[3]float64{deref(v.E), deref(v.N), deref(v.U)}
		}
		return pos
	}
	return nil
}

// deref returns the value of an optional field, or the zero value if unset.
func deref[T any](p *T) T {
	var zero T
	if p == nil {
		return zero
	}
	return *p
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatal("Required environment variables not set.")
	}

	headers := http.Header{}
	headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))

	latticeClient := client.NewClient(
		option.WithToken(environmentToken),
		option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
		option.WithHTTPHeader(headers),
	)

	// Stream only the target. Omit ComponentsToInclude to receive all components,
	// because listing components drops the others, which can include the position.
	stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
		Filter:              targetFilter(targetEntityID),
		HeartbeatIntervalMs: Lattice.Int(int(heartbeatInterval.Milliseconds())),
	})
	if err != nil {
		log.Fatalf("Failed to create entity stream: %v", err)
	}
	defer stream.Close()

	// Watchdog: warn when neither entity updates nor heartbeats arrive.
	var lastMessage atomic.Int64
	lastMessage.Store(time.Now().UnixNano())
	go func() {
		ticker := time.NewTicker(heartbeatInterval)
		defer ticker.Stop()
		for {
			select {
			case <-ctx.Done():
				return
			case <-ticker.C:
				silence := time.Since(time.Unix(0, lastMessage.Load()))
				if silence > staleAfter {
					log.Printf("WARNING: no message for %.1fs (expected a heartbeat every %.0fs)",
						silence.Seconds(), heartbeatInterval.Seconds())
				}
			}
		}
	}()

	log.Printf("Monitoring target %s", targetEntityID)
	var lastSourceTime time.Time

	for {
		message, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			log.Println("Stream completed successfully.")
			return
		}
		if err != nil {
			log.Fatalf("Error receiving message: %v", err)
		}
		lastMessage.Store(time.Now().UnixNano())

		switch message.Event {
		case "heartbeat":
			log.Printf("Heartbeat: %s", *message.Heartbeat.Timestamp)
		case "entity":
			event := message.Entity
			eventType := deref(event.EventType)
			switch eventType {
			case Lattice.EntityEventEventTypeEventTypeCreated,
				Lattice.EntityEventEventTypeEventTypePreexisting,
				Lattice.EntityEventEventTypeEventTypeUpdate:
				entity := event.Entity
				pos := extractPosition(entity)
				if pos == nil {
					continue
				}
				// Ignore updates that are not newer than the last one seen.
				sourceTime := deref(entity.GetProvenance().GetSourceUpdateTime())
				if sourceTime.IsZero() {
					sourceTime = deref(event.Time)
				}
				if !sourceTime.After(lastSourceTime) {
					continue
				}
				lastSourceTime = sourceTime

				line := fmt.Sprintf("%s lat=%.6f lon=%.6f hae=%.1fm", eventType, pos.lat, pos.lon, pos.hae)
				if v := pos.velocityENU; v != nil {
					line += fmt.Sprintf(" vel_enu=(%.1f,%.1f,%.1f)m/s", v[0], v[1], v[2])
				}
				log.Printf("%s age=%.1fs", line, time.Since(sourceTime).Seconds())
			case Lattice.EntityEventEventTypeEventTypeDeleted:
				// The target expired, was deleted, or stopped matching the filter.
				// A real interceptor would abort the engagement or request a new cue.
				log.Printf("Target lost: %s", targetEntityID)
				return
			}
		}
	}
}

```

```java title={"Java (REST)"} startLine={138} maxLines={63}
package org.example;

import com.anduril.AsyncLattice;
import com.anduril.resources.entities.requests.EntityStreamRequest;
import com.anduril.resources.entities.types.StreamEntitiesResponse;
import com.anduril.types.Entity;
import com.anduril.types.EntityEventEventType;
import com.anduril.types.EntityStreamEvent;
import com.anduril.types.Enu;
import com.anduril.types.KinematicsGeodetic;
import com.anduril.types.Location;
import com.anduril.types.LocationGeodetic;
import com.anduril.types.Position;
import com.anduril.types.Predicate;
import com.anduril.types.PredicateComparator;
import com.anduril.types.Statement;
import com.anduril.types.StringType;
import com.anduril.types.Value;
import com.anduril.types.Vec3;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Example application that monitors a single cued target track using the Lattice SDK.
 */
public class StreamTargetTrack {

    // Replace with the entity ID of the track you want to monitor.
    private static final String TARGET_ENTITY_ID = "<ENTITY_ID>";
    // Request a heartbeat every 5 seconds so silence is detectable.
    private static final int HEARTBEAT_INTERVAL_MS = 5000;
    // Warn if nothing arrives within three heartbeat intervals.
    private static final long STALE_AFTER_MS = 3L * HEARTBEAT_INTERVAL_MS;

    /** The newest position of a track, with velocity if known. */
    private static final class TrackPosition {
        final double lat;
        final double lon;
        final double hae;
        final double[] velocityEnu;

        TrackPosition(double lat, double lon, double hae, double[] velocityEnu) {
            this.lat = lat;
            this.lon = lon;
            this.hae = hae;
            this.velocityEnu = velocityEnu;
        }
    }

    /**
     * Match only the entity with the given ID. The filter is evaluated continuously:
     * if the entity stops matching, you receive a DELETED event.
     */
    static Statement targetFilter(String entityId) {
        return Statement.builder()
            .predicate(Predicate.builder()
                .fieldPath("entity_id")
                .value(Value.builder().stringType(StringType.builder().value(entityId).build()).build())
                .comparator(PredicateComparator.COMPARATOR_EQUALITY)
                .build())
            .build();
    }

    /**
     * Return the newest position, preferring kinematics over location. Kinematics is the
     * recommended source for tracks. Fall back to location if the entity has no kinematics.
     */
    static Optional<TrackPosition> extractPosition(Entity entity) {
        Optional<KinematicsGeodetic> geodetic = entity.getKinematics().flatMap(k -> k.getKinematicsGeodetic());
        if (geodetic.isPresent() && geodetic.get().getLocation().isPresent()) {
            LocationGeodetic loc = geodetic.get().getLocation().get();
            double[] velocity = geodetic.get().getVelocityEnuMPerS()
                .map((Vec3 v) -> new double[] {v.getX().orElse(0.0), v.getY().orElse(0.0), v.getZ().orElse(0.0)})
                .orElse(null);
            return Optional.of(new TrackPosition(
                loc.getLatitudeDegrees().orElse(0.0),
                loc.getLongitudeDegrees().orElse(0.0),
                loc.getUniversalAltitudeHae().flatMap(a -> a.getValueMeters()).orElse(0.0),
                velocity));
        }
        Optional<Location> location = entity.getLocation();
        if (location.isPresent() && location.get().getPosition().isPresent()) {
            Position position = location.get().getPosition().get();
            double[] velocity = location.get().getVelocityEnu()
                .map((Enu v) -> new double[] {v.getE().orElse(0.0), v.getN().orElse(0.0), v.getU().orElse(0.0)})
                .orElse(null);
            return Optional.of(new TrackPosition(
                position.getLatitudeDegrees().orElse(0.0),
                position.getLongitudeDegrees().orElse(0.0),
                position.getAltitudeHaeMeters().orElse(0.0),
                velocity));
        }
        return Optional.empty();
    }

    public static void main(String[] args) {
        // Get environment variables
        String endpoint = System.getenv("LATTICE_ENDPOINT");
        String environmentToken = System.getenv("ENVIRONMENT_TOKEN");
        String sandboxesToken = System.getenv("SANDBOXES_TOKEN");

        // Check required variables
        if (endpoint == null || environmentToken == null || sandboxesToken == null) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        // Watchdog: warn when neither entity updates nor heartbeats arrive.
        AtomicLong lastMessage = new AtomicLong(System.currentTimeMillis());
        ScheduledExecutorService watchdog = Executors.newSingleThreadScheduledExecutor(r -> {
            Thread thread = new Thread(r);
            thread.setDaemon(true);
            return thread;
        });
        watchdog.scheduleAtFixedRate(() -> {
            long silence = System.currentTimeMillis() - lastMessage.get();
            if (silence > STALE_AFTER_MS) {
                System.out.printf("WARNING: no message for %.1fs (expected a heartbeat every %ds)%n",
                    silence / 1000.0, HEARTBEAT_INTERVAL_MS / 1000);
            }
        }, HEARTBEAT_INTERVAL_MS, HEARTBEAT_INTERVAL_MS, TimeUnit.MILLISECONDS);

        try {
            AsyncLattice client = AsyncLattice.builder()
                .url(endpoint)
                .token(environmentToken)
                .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
                .build();

            // Omit componentsToInclude to receive all components, because listing
            // components drops the others, which can include the position.
            EntityStreamRequest request = EntityStreamRequest
                .builder()
                .filter(targetFilter(TARGET_ENTITY_ID))
                .heartbeatIntervalMs(HEARTBEAT_INTERVAL_MS)
                .build();

            System.out.println("Monitoring target " + TARGET_ENTITY_ID);
            client.entities().streamEntities(request)
                .thenAccept(responses -> {
                    OffsetDateTime lastSourceTime = null;
                    for (StreamEntitiesResponse response : responses) {
                        lastMessage.set(System.currentTimeMillis());

                        if (response.getHeartbeat().isPresent()) {
                            System.out.println("Heartbeat: " + response.getHeartbeat().get().getTimestamp().orElse(""));
                            continue;
                        }
                        if (!response.getEntity().isPresent()) {
                            continue;
                        }
                        EntityStreamEvent event = response.getEntity().get();
                        EntityEventEventType.Value type = event.getEventType()
                            .map(EntityEventEventType::getEnumValue)
                            .orElse(EntityEventEventType.Value.EVENT_TYPE_INVALID);

                        switch (type) {
                            case EVENT_TYPE_CREATED:
                            case EVENT_TYPE_PREEXISTING:
                            case EVENT_TYPE_UPDATE: {
                                Optional<Entity> entity = event.getEntity();
                                Optional<TrackPosition> position = entity.flatMap(StreamTargetTrack::extractPosition);
                                if (!position.isPresent()) {
                                    break;
                                }
                                // Ignore updates that are not newer than the last one seen.
                                Optional<OffsetDateTime> sourceTime = entity.get().getProvenance()
                                    .flatMap(p -> p.getSourceUpdateTime());
                                if (!sourceTime.isPresent()) {
                                    sourceTime = event.getTime();
                                }
                                if (!sourceTime.isPresent()
                                        || (lastSourceTime != null && !sourceTime.get().isAfter(lastSourceTime))) {
                                    break;
                                }
                                lastSourceTime = sourceTime.get();

                                TrackPosition p = position.get();
                                StringBuilder line = new StringBuilder(String.format(
                                    "%s lat=%.6f lon=%.6f hae=%.1fm", type, p.lat, p.lon, p.hae));
                                if (p.velocityEnu != null) {
                                    line.append(String.format(" vel_enu=(%.1f,%.1f,%.1f)m/s",
                                        p.velocityEnu[0], p.velocityEnu[1], p.velocityEnu[2]));
                                }
                                double ageSeconds = Duration.between(sourceTime.get(), OffsetDateTime.now()).toMillis() / 1000.0;
                                System.out.printf("%s age=%.1fs%n", line, ageSeconds);
                                break;
                            }
                            case EVENT_TYPE_DELETED:
                                // The target expired, was deleted, or stopped matching the filter.
                                // A real interceptor would abort the engagement or request a new cue.
                                System.out.println("Target lost: " + TARGET_ENTITY_ID);
                                System.exit(0);
                                return;
                            default:
                                break;
                        }
                    }
                })
                .exceptionally(ex -> {
                    System.err.println("Exception while streaming entities: " + ex.getMessage());
                    return null;
                })
                .join();
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
        watchdog.shutdownNow();
    }
}

```

```py title={"Python (REST)"} startLine={107} maxLines={43}
from anduril import (
    AsyncLattice,
    Entity,
    Predicate,
    Statement,
    StringType,
    Value,
)
from datetime import datetime, timezone
from typing import NamedTuple, Optional, Tuple
import asyncio
import os
import sys
import time

# Replace with the entity ID of the track you want to monitor.
TARGET_ENTITY_ID = "<ENTITY_ID>"
# Request a heartbeat every 5 seconds so silence is detectable.
HEARTBEAT_INTERVAL_MS = 5000
# Warn if nothing arrives within three heartbeat intervals.
STALE_AFTER_S = 3 * HEARTBEAT_INTERVAL_MS / 1000

lattice_endpoint = os.getenv('LATTICE_ENDPOINT')
environment_token = os.getenv('ENVIRONMENT_TOKEN')

# Remove sandboxes_token from the following statements if you are not developing on Sandboxes.
sandboxes_token = os.getenv('SANDBOXES_TOKEN')
if not environment_token or not lattice_endpoint or not sandboxes_token:
    print("Missing environment variables.")
    sys.exit(1)

client = AsyncLattice(
    base_url=f"https://{lattice_endpoint}",
    token=lambda: str(environment_token),
    # Remove the following header if you are not developing on Sandboxes.
    headers={ "anduril-sandbox-authorization": f"Bearer {sandboxes_token}" }
)


def target_filter(entity_id: str) -> Statement:
    """Match only the entity with the given ID.

    The filter is evaluated continuously: if the entity stops matching, you
    receive a DELETED event.
    """
    return Statement(
        predicate=Predicate(
            field_path="entity_id",
            value=Value(string_type=StringType(value=entity_id)),
            comparator="COMPARATOR_EQUALITY",
        )
    )


class TrackPosition(NamedTuple):
    lat: float
    lon: float
    hae: float
    velocity_enu: Optional[Tuple[float, float, float]]


def extract_position(entity: Entity) -> Optional[TrackPosition]:
    """Return the newest position, preferring kinematics over location.

    Kinematics is the recommended source for tracks. Fall back to location if
    the entity has no kinematics. Return None if neither has a position.
    """
    geodetic = entity.kinematics.kinematics_geodetic if entity.kinematics else None
    if geodetic and geodetic.location:
        loc = geodetic.location
        altitude = loc.universal_altitude_hae
        v = geodetic.velocity_enu_m_per_s
        return TrackPosition(
            lat=loc.latitude_degrees or 0.0,
            lon=loc.longitude_degrees or 0.0,
            hae=(altitude.value_meters if altitude else None) or 0.0,
            velocity_enu=(v.x or 0.0, v.y or 0.0, v.z or 0.0) if v else None,
        )
    if entity.location and entity.location.position:
        position = entity.location.position
        v = entity.location.velocity_enu
        return TrackPosition(
            lat=position.latitude_degrees or 0.0,
            lon=position.longitude_degrees or 0.0,
            hae=position.altitude_hae_meters or 0.0,
            velocity_enu=(v.e or 0.0, v.n or 0.0, v.u or 0.0) if v else None,
        )
    return None


async def watchdog(last_message: list[float]):
    """Warn when neither entity updates nor heartbeats arrive."""
    while True:
        await asyncio.sleep(HEARTBEAT_INTERVAL_MS / 1000)
        silence = time.monotonic() - last_message[0]
        if silence > STALE_AFTER_S:
            print(f"WARNING: no message for {silence:.1f}s "
                  f"(expected a heartbeat every {HEARTBEAT_INTERVAL_MS / 1000:.0f}s)")


async def app():
    last_message = [time.monotonic()]
    watchdog_task = asyncio.create_task(watchdog(last_message))
    last_source_time: Optional[datetime] = None

    try:
        # Omit components_to_include to receive all components, because listing
        # components drops the others, which can include the position.
        event_stream = client.entities.stream_entities(
            filter=target_filter(TARGET_ENTITY_ID),
            heartbeat_interval_ms=HEARTBEAT_INTERVAL_MS,
        )
        print(f"Monitoring target {TARGET_ENTITY_ID}")
        async for event in event_stream:
            last_message[0] = time.monotonic()

            if event.event == "heartbeat":
                print(f"Heartbeat: {event.timestamp}")
                continue
            if event.event != "entity":
                continue

            if event.event_type in ("EVENT_TYPE_CREATED", "EVENT_TYPE_PREEXISTING", "EVENT_TYPE_UPDATE"):
                entity = event.entity
                if not entity:
                    continue
                position = extract_position(entity)
                if not position:
                    continue
                # Ignore updates that are not newer than the last one seen.
                source_time = (entity.provenance.source_update_time if entity.provenance else None) or event.time
                if not source_time:
                    continue
                if last_source_time and source_time <= last_source_time:
                    continue
                last_source_time = source_time

                line = f"{event.event_type} lat={position.lat:.6f} lon={position.lon:.6f} hae={position.hae:.1f}m"
                if position.velocity_enu:
                    e, n, u = position.velocity_enu
                    line += f" vel_enu=({e:.1f},{n:.1f},{u:.1f})m/s"
                age = (datetime.now(timezone.utc) - source_time).total_seconds()
                print(f"{line} age={age:.1f}s")
            elif event.event_type == "EVENT_TYPE_DELETED":
                # The target expired, was deleted, or stopped matching the filter.
                # An interceptor would abort the engagement or request a new cue.
                print(f"Target lost: {TARGET_ENTITY_ID}")
                return
    except asyncio.CancelledError:
        print("Streaming cancelled...")
    except Exception as error:
        print(f"Exception: {error}")
    finally:
        watchdog_task.cancel()

if __name__ == "__main__":
    asyncio.run(app())

```

```ts title={"TypeScript (REST)"} startLine={87} maxLines={46}
import { Lattice, LatticeClient } from "@anduril-industries/lattice-sdk";

// Replace with the entity ID of the track you want to monitor.
const targetEntityId = "<ENTITY_ID>";
// Request a heartbeat every 5 seconds so silence is detectable.
const heartbeatIntervalMs = 5000;
// Warn if nothing arrives within three heartbeat intervals.
const staleAfterMs = 3 * heartbeatIntervalMs;

const latticeEndpoint = process.env.LATTICE_ENDPOINT;
const environmentToken = process.env.ENVIRONMENT_TOKEN;

// Remove sandboxesToken from the following statement if you are not developing on Sandboxes.
const sandboxesToken = process.env.SANDBOXES_TOKEN;
if (!latticeEndpoint || !environmentToken || !sandboxesToken) {
    console.log('Missing required environment variables.');
    process.exit(1);
}

const client = new LatticeClient(
    {
        baseUrl: `https://${latticeEndpoint}`,
        token: environmentToken,
        // Remove the following statement if you are not developing on Sandboxes.
        headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}` }
    }
);

// Match only the entity with the given ID. The filter is evaluated continuously:
// if the entity stops matching, you receive a DELETED event.
function targetFilter(entityId: string): Lattice.Statement {
    return {
        predicate: {
            fieldPath: "entity_id",
            value: { stringType: { value: entityId } },
            comparator: "COMPARATOR_EQUALITY",
        },
    };
}

interface TrackPosition {
    lat: number;
    lon: number;
    hae: number;
    velocityEnu?: [number, number, number];
}

// Return the newest position, preferring kinematics over location. Kinematics
// is the recommended source for tracks. Fall back to location if the entity
// has no kinematics. Return undefined if neither has a position.
function extractPosition(entity: Lattice.Entity): TrackPosition | undefined {
    const geodetic = entity.kinematics?.kinematicsGeodetic;
    if (geodetic?.location) {
        const v = geodetic.velocityEnuMPerS;
        return {
            lat: geodetic.location.latitudeDegrees ?? 0,
            lon: geodetic.location.longitudeDegrees ?? 0,
            hae: geodetic.location.universalAltitudeHae?.valueMeters ?? 0,
            velocityEnu: v ? [v.x ?? 0, v.y ?? 0, v.z ?? 0] : undefined,
        };
    }
    const position = entity.location?.position;
    if (position) {
        const v = entity.location?.velocityEnu;
        return {
            lat: position.latitudeDegrees ?? 0,
            lon: position.longitudeDegrees ?? 0,
            hae: position.altitudeHaeMeters ?? 0,
            velocityEnu: v ? [v.e ?? 0, v.n ?? 0, v.u ?? 0] : undefined,
        };
    }
    return undefined;
}

async function App() {
    // Watchdog: warn when neither entity updates nor heartbeats arrive.
    let lastMessage = Date.now();
    const watchdog = setInterval(() => {
        const silence = Date.now() - lastMessage;
        if (silence > staleAfterMs) {
            console.log(`WARNING: no message for ${(silence / 1000).toFixed(1)}s (expected a heartbeat every ${heartbeatIntervalMs / 1000}s)`);
        }
    }, heartbeatIntervalMs);

    let lastSourceTime = 0;
    try {
        // Omit componentsToInclude to receive all components, because listing
        // components drops the others, which can include the position.
        const eventStream = await client.entities.streamEntities({
            filter: targetFilter(targetEntityId),
            heartbeatIntervalMS: heartbeatIntervalMs,
        });
        console.log(`Monitoring target ${targetEntityId}`);

        for await (const event of eventStream) {
            lastMessage = Date.now();

            if (event.event === "heartbeat") {
                console.log(`Heartbeat: ${event.timestamp}`);
                continue;
            }

            switch (event.eventType) {
                case "EVENT_TYPE_CREATED":
                case "EVENT_TYPE_PREEXISTING":
                case "EVENT_TYPE_UPDATE": {
                    const entity = event.entity;
                    const position = entity && extractPosition(entity);
                    if (!entity || !position) {
                        break;
                    }
                    // Ignore updates that are not newer than the last one seen.
                    const sourceTime = Date.parse(entity.provenance?.sourceUpdateTime ?? event.time ?? "");
                    if (Number.isNaN(sourceTime) || sourceTime <= lastSourceTime) {
                        break;
                    }
                    lastSourceTime = sourceTime;

                    let line = `${event.eventType} lat=${position.lat.toFixed(6)} lon=${position.lon.toFixed(6)} hae=${position.hae.toFixed(1)}m`;
                    if (position.velocityEnu) {
                        const [e, n, u] = position.velocityEnu;
                        line += ` vel_enu=(${e.toFixed(1)},${n.toFixed(1)},${u.toFixed(1)})m/s`;
                    }
                    console.log(`${line} age=${((Date.now() - sourceTime) / 1000).toFixed(1)}s`);
                    break;
                }
                case "EVENT_TYPE_DELETED":
                    // The target expired, was deleted, or stopped matching the filter.
                    // A real interceptor would abort the engagement or request a new cue.
                    console.log(`Target lost: ${targetEntityId}`);
                    clearInterval(watchdog);
                    return;
            }
        }
    } catch (error) {
        console.log(`Exception while streaming entities: ${error}`);
    }
    clearInterval(watchdog);
}

App();

```

```rs title={"Rust (REST)"} startLine={106} maxLines={75}
use anduril_lattice_sdk::prelude::*;

use chrono::Utc;
use std::env;
use std::time::Duration;
use tokio::time::{timeout_at, Instant};

// Replace with the entity ID of the track you want to monitor.
const TARGET_ENTITY_ID: &str = "<ENTITY_ID>";
// Request a heartbeat every 5 seconds so silence is detectable.
const HEARTBEAT_INTERVAL_MS: i64 = 5000;
// Warn if nothing arrives within three heartbeat intervals.
const STALE_AFTER: Duration = Duration::from_millis(3 * HEARTBEAT_INTERVAL_MS as u64);

/// The newest position of a track, with velocity if known.
struct TrackPosition {
    lat: f64,
    lon: f64,
    hae: f64,
    velocity_enu: Option<(f64, f64, f64)>,
}

/// Matches only the entity with the given ID. The filter is evaluated
/// continuously: if the entity stops matching, you receive DELETED.
fn target_filter(entity_id: &str) -> Statement {
    Statement {
        predicate: Some(Predicate {
            field_path: Some("entity_id".to_string()),
            // The SDK models the predicate value as free-form JSON.
            value: Some(json!({ "stringType": { "value": entity_id } })),
            comparator: Some(PredicateComparator::ComparatorEquality),
        }),
        ..Default::default()
    }
}

/// Returns the newest position, preferring kinematics over location. Kinematics
/// is the recommended source for tracks. Falls back to location if the entity
/// has no kinematics. Returns None if neither has a position.
fn extract_position(entity: &Entity) -> Option<TrackPosition> {
    if let Some(geodetic) = entity
        .kinematics
        .as_ref()
        .and_then(|k| k.kinematics_geodetic.as_ref())
    {
        if let Some(loc) = &geodetic.location {
            return Some(TrackPosition {
                lat: loc.latitude_degrees.unwrap_or(0.0),
                lon: loc.longitude_degrees.unwrap_or(0.0),
                hae: loc
                    .universal_altitude_hae
                    .as_ref()
                    .and_then(|a| a.value_meters)
                    .unwrap_or(0.0),
                velocity_enu: geodetic.velocity_enu_m_per_s.as_ref().map(|v| {
                    (v.x.unwrap_or(0.0), v.y.unwrap_or(0.0), v.z.unwrap_or(0.0))
                }),
            });
        }
    }
    let location = entity.location.as_ref()?;
    let position = location.position.as_ref()?;
    Some(TrackPosition {
        lat: position.latitude_degrees.unwrap_or(0.0),
        lon: position.longitude_degrees.unwrap_or(0.0),
        hae: position.altitude_hae_meters.unwrap_or(0.0),
        velocity_enu: location
            .velocity_enu
            .as_ref()
            .map(|v| (v.e.unwrap_or(0.0), v.n.unwrap_or(0.0), v.u.unwrap_or(0.0))),
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    // Remove sandboxes_token if you are not developing on Sandboxes.
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables:");
        eprintln!("  LATTICE_ENDPOINT");
        eprintln!("  ENVIRONMENT_TOKEN");
        eprintln!("  SANDBOXES_TOKEN");
        std::process::exit(1);
    }

    let config = ClientConfig {
        base_url: format!("https://{}", lattice_endpoint),
        token: Some(environment_token),
        // Remove custom_headers if you are not developing on Sandboxes.
        custom_headers: HashMap::from([(
            "anduril-sandbox-authorization".to_string(),
            format!("Bearer {}", sandboxes_token),
        )]),
        ..Default::default()
    };
    let client = Lattice::new(config)?;

    // Stream only the target. Leave components_to_include unset to receive all
    // components, because listing components drops the others, which can include the position.
    let request = EntityStreamRequest {
        filter: Some(target_filter(TARGET_ENTITY_ID)),
        heartbeat_interval_ms: Some(HEARTBEAT_INTERVAL_MS),
        ..Default::default()
    };
    let stream = client.entities.stream_entities(&request, None).await?;
    let mut stream = std::pin::pin!(stream);

    println!("Monitoring target {}", TARGET_ENTITY_ID);
    let mut last_source_time: Option<DateTime<FixedOffset>> = None;
    // Watchdog: the deadline moves forward each time a message arrives.
    let mut deadline = Instant::now() + STALE_AFTER;

    loop {
        let result = match timeout_at(deadline, stream.next()).await {
            Ok(Some(result)) => result,
            Ok(None) => break,
            Err(_) => {
                println!(
                    "WARNING: no message for {}s (expected a heartbeat every {}s)",
                    STALE_AFTER.as_secs(),
                    HEARTBEAT_INTERVAL_MS / 1000
                );
                deadline = Instant::now() + STALE_AFTER;
                continue;
            }
        };
        deadline = Instant::now() + STALE_AFTER;

        let event = match result {
            Ok(event) => event,
            Err(error) => {
                eprintln!("Exception: {}", error);
                continue;
            }
        };

        match event {
            StreamEntitiesResponse::Heartbeat { data, .. } => {
                println!(
                    "Heartbeat: {}",
                    data.heartbeat_object_fields.timestamp.unwrap_or_default()
                );
            }
            StreamEntitiesResponse::Entity { data, .. } => {
                let event = data.entity_event_fields;
                match event.event_type {
                    Some(
                        EntityEventEventType::EventTypeCreated
                        | EntityEventEventType::EventTypePreexisting
                        | EntityEventEventType::EventTypeUpdate,
                    ) => {
                        let Some(entity) = &event.entity else { continue };
                        let Some(position) = extract_position(entity) else { continue };
                        // Ignore updates that are not newer than the last one seen.
                        let source_time = entity
                            .provenance
                            .as_ref()
                            .and_then(|p| p.source_update_time)
                            .or(event.time);
                        let Some(source_time) = source_time else { continue };
                        if last_source_time.is_some_and(|last| source_time <= last) {
                            continue;
                        }
                        last_source_time = Some(source_time);

                        let mut line = format!(
                            "{} lat={:.6} lon={:.6} hae={:.1}m",
                            event.event_type.as_ref().map(|t| t.to_string()).unwrap_or_default(),
                            position.lat,
                            position.lon,
                            position.hae
                        );
                        if let Some((e, n, u)) = position.velocity_enu {
                            line.push_str(&format!(" vel_enu=({:.1},{:.1},{:.1})m/s", e, n, u));
                        }
                        let age = (Utc::now() - source_time.with_timezone(&Utc)).num_milliseconds()
                            as f64
                            / 1000.0;
                        println!("{} age={:.1}s", line, age);
                    }
                    Some(EntityEventEventType::EventTypeDeleted) => {
                        // The target expired, was deleted, or stopped matching the filter.
                        // A real interceptor would abort the engagement or request a new cue.
                        println!("Target lost: {}", TARGET_ENTITY_ID);
                        return Ok(());
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }

    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={111} maxLines={75}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"os"
	"sync/atomic"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

const (
	// Replace with the entity ID of the track you want to monitor.
	targetEntityID = "<ENTITY_ID>"
	// Request a heartbeat every 5 seconds so silence is detectable.
	heartbeatInterval = 5 * time.Second
	// Warn if nothing arrives within three heartbeat intervals.
	staleAfter = 3 * heartbeatInterval
)

// targetFilter matches only the entity with the given ID. The filter is
// evaluated continuously: if the entity stops matching, you receive DELETED.
func targetFilter(entityID string) *entitymanagerv1.Statement {
	return &entitymanagerv1.Statement{
		Operation: &entitymanagerv1.Statement_Predicate{
			Predicate: &entitymanagerv1.Predicate{
				FieldPath: "entity_id",
				Value: &entitymanagerv1.Value{
					Type: &entitymanagerv1.Value_StringType{
						StringType: &entitymanagerv1.StringType{Value: entityID},
					},
				},
				Comparator: entitymanagerv1.Comparator_COMPARATOR_EQUALITY,
			},
		},
	}
}

// trackPosition is the newest position of a track, with velocity if known.
type trackPosition struct {
	lat, lon, hae float64
	velocityENU   *[3]float64
}

// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *entitymanagerv1.Entity) *trackPosition {
	if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic.GetLocation() != nil {
		loc := geodetic.GetLocation()
		pos := &trackPosition{
			lat: loc.GetLatitudeDegrees(),
			lon: loc.GetLongitudeDegrees(),
			hae: loc.GetUniversalAltitudeHae().GetValueMeters(),
		}
		if v := geodetic.GetVelocityEnuMPerS(); v != nil {
			pos.velocityENU = &[3]float64{v.GetX(), v.GetY(), v.GetZ()}
		}
		return pos
	}
	if loc := entity.GetLocation(); loc.GetPosition() != nil {
		position := loc.GetPosition()
		pos := &trackPosition{
			lat: position.GetLatitudeDegrees(),
			lon: position.GetLongitudeDegrees(),
			hae: position.GetAltitudeHaeMeters().GetValue(),
		}
		if v := loc.GetVelocityEnu(); v != nil {
			pos.velocityENU = &[3]float64{v.GetE(), v.GetN(), v.GetU()}
		}
		return pos
	}
	return nil
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatalf("Missing required environment variables")
	}
	auth := &BearerTokenAuth{
		Token:          environmentToken,
		SandboxesToken: sandboxesToken,
	}

	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}
	conn, err := grpc.NewClient(latticeEndpoint, opts...)
	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	// Stream only the target, with all components. Don't set components_to_include,
	// because listing components drops the others, which can include the position.
	stream, err := client.StreamEntityComponents(ctx, &entitymanagerv1.StreamEntityComponentsRequest{
		Filter:                targetFilter(targetEntityID),
		IncludeAllComponents:  true,
		HeartbeatPeriodMillis: uint32(heartbeatInterval.Milliseconds()),
	})
	if err != nil {
		log.Fatalf("Error creating stream: %v", err)
	}

	// Watchdog: warn when neither entity updates nor heartbeats arrive.
	var lastMessage atomic.Int64
	lastMessage.Store(time.Now().UnixNano())
	go func() {
		ticker := time.NewTicker(heartbeatInterval)
		defer ticker.Stop()
		for {
			select {
			case <-ctx.Done():
				return
			case <-ticker.C:
				silence := time.Since(time.Unix(0, lastMessage.Load()))
				if silence > staleAfter {
					log.Printf("WARNING: no message for %.1fs (expected a heartbeat every %.0fs)",
						silence.Seconds(), heartbeatInterval.Seconds())
				}
			}
		}
	}()

	log.Printf("Monitoring target %s", targetEntityID)
	var lastSourceTime time.Time

	for {
		response, err := stream.Recv()
		if err == io.EOF {
			log.Println("Stream completed successfully.")
			return
		}
		if err != nil {
			log.Fatalf("Error receiving stream data: %v", err)
		}
		lastMessage.Store(time.Now().UnixNano())

		if response.GetHeartbeat() != nil {
			log.Printf("Heartbeat: %s", response.GetHeartbeat().GetTimestamp().AsTime().Format(time.RFC3339))
			continue
		}
		event := response.GetEntityEvent()
		eventType := event.GetEventType()

		switch eventType {
		case entitymanagerv1.EventType_EVENT_TYPE_CREATED,
			entitymanagerv1.EventType_EVENT_TYPE_PREEXISTING,
			entitymanagerv1.EventType_EVENT_TYPE_UPDATE:
			entity := event.GetEntity()
			pos := extractPosition(entity)
			if pos == nil {
				continue
			}
			// Ignore updates that are not newer than the last one seen.
			sourceTime := entity.GetProvenance().GetSourceUpdateTime().AsTime()
			if entity.GetProvenance().GetSourceUpdateTime() == nil {
				sourceTime = event.GetTime().AsTime()
			}
			if !sourceTime.After(lastSourceTime) {
				continue
			}
			lastSourceTime = sourceTime

			line := fmt.Sprintf("%s lat=%.6f lon=%.6f hae=%.1fm", eventType, pos.lat, pos.lon, pos.hae)
			if v := pos.velocityENU; v != nil {
				line += fmt.Sprintf(" vel_enu=(%.1f,%.1f,%.1f)m/s", v[0], v[1], v[2])
			}
			log.Printf("%s age=%.1fs", line, time.Since(sourceTime).Seconds())
		case entitymanagerv1.EventType_EVENT_TYPE_DELETED:
			// The target expired, was deleted, or stopped matching the filter.
			// A real interceptor would abort the engagement or request a new cue.
			log.Printf("Target lost: %s", targetEntityID)
			return
		}
	}
}

```

```py title={"Python (gRPC)"} startLine={109} maxLines={54}
# This Python example is compatible with artifacts generated using the following
# Buf plugins: https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:bufbuild/py
# and https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:connectrpc/py

import os
import sys
import threading
import time
from datetime import datetime, timezone
from typing import NamedTuple, Optional, Tuple

from bearer_auth import create_client
from protobuf import Oneof

from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.entity_manager_api_pub_pb import (
    EventType,
    StreamEntityComponentsRequest,
)
from anduril.entitymanager.v1.entity_pub_pb import Entity
from anduril.entitymanager.v1.filter_pub_pb import Comparator, Predicate, Statement, StringType, Value

# Replace with the entity ID of the track you want to monitor.
TARGET_ENTITY_ID = "<ENTITY_ID>"
# Request a heartbeat every 5 seconds so silence is detectable.
HEARTBEAT_PERIOD_MS = 5000
# Warn if nothing arrives within three heartbeat intervals.
STALE_AFTER_S = 3 * HEARTBEAT_PERIOD_MS / 1000


def target_filter(entity_id: str) -> Statement:
    """Match only the entity with the given ID.

    The filter is evaluated continuously: if the entity stops matching, you
    receive a DELETED event.
    """
    return Statement(
        operation=Oneof(
            "predicate",
            Predicate(
                field_path="entity_id",
                value=Value(type=Oneof("string_type", StringType(value=entity_id))),
                comparator=Comparator.EQUALITY,
            ),
        )
    )


class TrackPosition(NamedTuple):
    lat: float
    lon: float
    hae: float
    velocity_enu: Optional[Tuple[float, float, float]]


def extract_position(entity: Entity) -> Optional[TrackPosition]:
    """Return the newest position, preferring kinematics over location.

    Kinematics is the recommended source for tracks. Fall back to location if
    the entity has no kinematics. Return None if neither has a position.
    """
    if entity.has_field("kinematics") and entity.kinematics.has_field("kinematics_geodetic"):
        geodetic = entity.kinematics.kinematics_geodetic
        if geodetic.has_field("location"):
            loc = geodetic.location
            v = geodetic.velocity_enu_m_per_s if geodetic.has_field("velocity_enu_m_per_s") else None
            return TrackPosition(
                lat=loc.latitude_degrees,
                lon=loc.longitude_degrees,
                hae=loc.universal_altitude_hae.value_meters,
                velocity_enu=(v.x, v.y, v.z) if v else None,
            )
    if entity.has_field("location") and entity.location.has_field("position"):
        position = entity.location.position
        v = entity.location.velocity_enu if entity.location.has_field("velocity_enu") else None
        return TrackPosition(
            lat=position.latitude_degrees,
            lon=position.longitude_degrees,
            hae=position.altitude_hae_meters.value if position.has_field("altitude_hae_meters") else 0.0,
            velocity_enu=(v.e, v.n, v.u) if v else None,
        )
    return None


def watch_for_silence(last_message: list[float]) -> None:
    """Warn when neither entity updates nor heartbeats arrive."""
    while True:
        time.sleep(HEARTBEAT_PERIOD_MS / 1000)
        silence = time.monotonic() - last_message[0]
        if silence > STALE_AFTER_S:
            print(f"WARNING: no message for {silence:.1f}s "
                  f"(expected a heartbeat every {HEARTBEAT_PERIOD_MS / 1000:.0f}s)")


def main():
    environment_token = os.getenv("ENVIRONMENT_TOKEN")
    lattice_endpoint = os.getenv("LATTICE_ENDPOINT")
    sandboxes_token = os.getenv("SANDBOXES_TOKEN")

    if not environment_token or not lattice_endpoint or not sandboxes_token:
        print("Missing required environment variables", file=sys.stderr)
        sys.exit(1)

    # Create the API client over Connect gRPC with authentication
    client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    # Stream only the target, with all components. Don't set components_to_include,
    # because listing components drops the others, which can include the position.
    request = StreamEntityComponentsRequest(
        filter=target_filter(TARGET_ENTITY_ID),
        include_all_components=True,
        heartbeat_period_millis=HEARTBEAT_PERIOD_MS,
    )

    try:
        stream = client.stream_entity_components(request)
    except Exception as error:
        print(f"Error creating stream: {error}", file=sys.stderr)
        sys.exit(1)

    last_message = [time.monotonic()]
    threading.Thread(target=watch_for_silence, args=(last_message,), daemon=True).start()
    last_source_time: Optional[datetime] = None

    print(f"Monitoring target {TARGET_ENTITY_ID}")
    try:
        for response in stream:
            last_message[0] = time.monotonic()

            if response.has_field("heartbeat"):
                print(f"Heartbeat: {response.heartbeat.timestamp.to_datetime().isoformat()}")
                continue
            if not response.has_field("entity_event"):
                continue
            event = response.entity_event

            if event.event_type in (EventType.CREATED, EventType.PREEXISTING, EventType.UPDATE):
                entity = event.entity
                position = extract_position(entity) if entity else None
                if not entity or not position:
                    continue
                # Ignore updates that are not newer than the last one seen.
                if entity.has_field("provenance") and entity.provenance.has_field("source_update_time"):
                    source_time = entity.provenance.source_update_time.to_datetime()
                else:
                    source_time = event.time.to_datetime()
                if last_source_time and source_time <= last_source_time:
                    continue
                last_source_time = source_time

                line = f"EVENT_TYPE_{event.event_type.name} lat={position.lat:.6f} lon={position.lon:.6f} hae={position.hae:.1f}m"
                if position.velocity_enu:
                    e, n, u = position.velocity_enu
                    line += f" vel_enu=({e:.1f},{n:.1f},{u:.1f})m/s"
                age = (datetime.now(timezone.utc) - source_time).total_seconds()
                print(f"{line} age={age:.1f}s")
            elif event.event_type == EventType.DELETED:
                # The target expired, was deleted, or stopped matching the filter.
                # A real interceptor would abort the engagement or request a new cue.
                print(f"Target lost: {TARGET_ENTITY_ID}")
                return
        print("End of stream reached.")
    except Exception as error:
        print(f"Error receiving stream data: {error}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={132} maxLines={74}
// This Rust example is compatible with artifacts generated using
// the following grpc/rust plugin: https://buf.build/anduril/lattice-sdk/sdks/main:community/neoeinstein-tonic
mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    statement, value, Comparator, Entity, EventType, Predicate, Statement,
    StreamEntityComponentsRequest, StringType, Value,
};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use tonic::metadata::MetadataValue;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::Request;

use std::env;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::time::{timeout_at, Instant};

// Replace with the entity ID of the track you want to monitor.
const TARGET_ENTITY_ID: &str = "<ENTITY_ID>";
// Request a heartbeat every 5 seconds so silence is detectable.
const HEARTBEAT_PERIOD_MS: u32 = 5000;
// Warn if nothing arrives within three heartbeat intervals.
const STALE_AFTER: Duration = Duration::from_millis(3 * HEARTBEAT_PERIOD_MS as u64);

/// The newest position of a track, with velocity if known.
struct TrackPosition {
    lat: f64,
    lon: f64,
    hae: f64,
    velocity_enu: Option<(f64, f64, f64)>,
}

/// Matches only the entity with the given ID. The filter is evaluated
/// continuously: if the entity stops matching, you receive DELETED.
fn target_filter(entity_id: &str) -> Statement {
    Statement {
        operation: Some(statement::Operation::Predicate(Predicate {
            field_path: "entity_id".to_string(),
            value: Some(Value {
                r#type: Some(value::Type::StringType(StringType {
                    value: entity_id.to_string(),
                })),
            }),
            comparator: Comparator::Equality as i32,
        })),
    }
}

/// Returns the newest position, preferring kinematics over location. Kinematics
/// is the recommended source for tracks. Falls back to location if the entity
/// has no kinematics. Returns None if neither has a position.
fn extract_position(entity: &Entity) -> Option<TrackPosition> {
    if let Some(geodetic) = entity
        .kinematics
        .as_ref()
        .and_then(|k| k.kinematics_geodetic.as_ref())
    {
        if let Some(loc) = &geodetic.location {
            return Some(TrackPosition {
                lat: loc.latitude_degrees,
                lon: loc.longitude_degrees,
                hae: loc
                    .universal_altitude_hae
                    .as_ref()
                    .map_or(0.0, |a| a.value_meters),
                velocity_enu: geodetic
                    .velocity_enu_m_per_s
                    .as_ref()
                    .map(|v| (v.x, v.y, v.z)),
            });
        }
    }
    let location = entity.location.as_ref()?;
    let position = location.position.as_ref()?;
    Some(TrackPosition {
        lat: position.latitude_degrees,
        lon: position.longitude_degrees,
        hae: position.altitude_hae_meters.unwrap_or(0.0),
        velocity_enu: location.velocity_enu.as_ref().map(|v| (v.e, v.n, v.u)),
    })
}

/// Converts a protobuf timestamp to seconds since the Unix epoch.
fn timestamp_secs(ts: &prost_types::Timestamp) -> f64 {
    ts.seconds as f64 + f64::from(ts.nanos) / 1e9
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load environment variables
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    // Set up authentication handler
    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

    // Create gRPC channel with TLS
    let tls_config = ClientTlsConfig::new().with_native_roots();
    let channel = Channel::from_shared(format!("https://{}", lattice_endpoint))?
        .tls_config(tls_config)?
        .connect()
        .await?;

    // Fetch a fresh access token and build metadata values
    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<_> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<_> = format!("Bearer {}", sandboxes_token).parse()?;

    // Create EntityManager API client with authentication interceptor
    let mut client = EntityManagerApiClient::with_interceptor(
        channel,
        move |mut req: Request<()>| {
            req.metadata_mut()
                .insert("authorization", auth_header.clone());
            req.metadata_mut()
                .insert("anduril-sandbox-authorization", sandbox_header.clone());
            Ok(req)
        },
    );

    // Stream only the target, with all components. Don't set components_to_include,
    // because listing components drops the others, which can include the position.
    let request = Request::new(StreamEntityComponentsRequest {
        filter: Some(target_filter(TARGET_ENTITY_ID)),
        include_all_components: true,
        heartbeat_period_millis: HEARTBEAT_PERIOD_MS,
        ..Default::default()
    });

    let mut stream = client.stream_entity_components(request).await?.into_inner();

    println!("Monitoring target {}", TARGET_ENTITY_ID);
    let mut last_source_secs: Option<f64> = None;
    // Watchdog: the deadline moves forward each time a message arrives.
    let mut deadline = Instant::now() + STALE_AFTER;

    loop {
        let response = match timeout_at(deadline, stream.message()).await {
            Ok(message) => match message? {
                Some(response) => response,
                None => break,
            },
            Err(_) => {
                println!(
                    "WARNING: no message for {}s (expected a heartbeat every {}s)",
                    STALE_AFTER.as_secs(),
                    HEARTBEAT_PERIOD_MS / 1000
                );
                deadline = Instant::now() + STALE_AFTER;
                continue;
            }
        };
        deadline = Instant::now() + STALE_AFTER;

        if let Some(heartbeat) = response.heartbeat {
            let secs = heartbeat.timestamp.as_ref().map_or(0.0, timestamp_secs);
            println!("Heartbeat: {:.3}", secs);
            continue;
        }
        let Some(event) = response.entity_event else { continue };

        match EventType::try_from(event.event_type) {
            Ok(EventType::Created | EventType::Preexisting | EventType::Update) => {
                let Some(entity) = &event.entity else { continue };
                let Some(position) = extract_position(entity) else { continue };
                // Ignore updates that are not newer than the last one seen.
                let source_time = entity
                    .provenance
                    .as_ref()
                    .and_then(|p| p.source_update_time.as_ref())
                    .or(event.time.as_ref());
                let Some(source_secs) = source_time.map(timestamp_secs) else { continue };
                if last_source_secs.is_some_and(|last| source_secs <= last) {
                    continue;
                }
                last_source_secs = Some(source_secs);

                let mut line = format!(
                    "{} lat={:.6} lon={:.6} hae={:.1}m",
                    EventType::try_from(event.event_type)?.as_str_name(),
                    position.lat,
                    position.lon,
                    position.hae
                );
                if let Some((e, n, u)) = position.velocity_enu {
                    line.push_str(&format!(" vel_enu=({:.1},{:.1},{:.1})m/s", e, n, u));
                }
                let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs_f64();
                println!("{} age={:.1}s", line, now - source_secs);
            }
            Ok(EventType::Deleted) => {
                // The target expired, was deleted, or stopped matching the filter.
                // A real interceptor would abort the engagement or request a new cue.
                println!("Target lost: {}", TARGET_ENTITY_ID);
                return Ok(());
            }
            _ => {}
        }
    }
    println!("End of stream reached");

    Ok(())
}

```

If successful, you see each new position and how old the measurement is:

```bash maxLines=4
Monitoring target 2f6a0d1c-4b7e-4c3a-9d55-1e8f0a7b9c21
EVENT_TYPE_PREEXISTING lat=34.045000 lon=-117.990000 hae=512.1m vel_enu=(4.8,-31.6,-11.7)m/s age=0.4s
EVENT_TYPE_UPDATE lat=34.044715 lon=-117.989957 hae=500.4m vel_enu=(4.8,-31.6,-11.7)m/s age=0.3s
Target lost: 2f6a0d1c-4b7e-4c3a-9d55-1e8f0a7b9c21
```

> **Info**
>
> Over gRPC, `StreamEntityComponents` also accepts a `rate_limit` that sets the minimum time
> between updates for each entity, with a floor of 500 milliseconds. A rate limit only reduces the
> update rate, so leave it unset when an effector needs every update for its target.

## Watch for threat tracks

Before it's cued, an effector can watch for the tracks it might be asked to engage. Combine
predicates with an `and` statement to stream only hostile or suspicious air tracks:

**`ontology.template`** `EnumType`

Equal to `TEMPLATE_TRACK`, so the stream excludes assets and geo-entities.

---

**`mil_view.environment`** `EnumType`

Equal to `ENVIRONMENT_AIR`, so the stream excludes surface and subsurface tracks.

---

**`mil_view.disposition`** `EnumType`

In the set `DISPOSITION_HOSTILE` and `DISPOSITION_SUSPICIOUS`, using the `COMPARATOR_IN` comparator.

---

Filters compare enum fields by their integer values, as defined in the Lattice protobuf
definitions. This filter uses `1` for `TEMPLATE_TRACK` and `ENVIRONMENT_AIR`, `2` for
`DISPOSITION_HOSTILE`, and `3` for `DISPOSITION_SUSPICIOUS`:

**`REST`**

```json title="REST"
{
  "and": {
    "predicateSet": {
      "predicates": [
        {
          "fieldPath": "ontology.template",
          "value": { "enumType": { "value": 1 } },
          "comparator": "COMPARATOR_EQUALITY"
        },
        {
          "fieldPath": "mil_view.environment",
          "value": { "enumType": { "value": 1 } },
          "comparator": "COMPARATOR_EQUALITY"
        },
        {
          "fieldPath": "mil_view.disposition",
          "value": {
            "listType": {
              "values": [
                { "enumType": { "value": 2 } },
                { "enumType": { "value": 3 } }
              ]
            }
          },
          "comparator": "COMPARATOR_IN"
        }
      ]
    }
  }
}
```

**`gRPC`**

```protobuf title="gRPC"
filter {
  and {
    predicate_set {
      predicates {
        field_path: "ontology.template"
        value { enum_type { value: 1 } }
        comparator: COMPARATOR_EQUALITY
      }
      predicates {
        field_path: "mil_view.environment"
        value { enum_type { value: 1 } }
        comparator: COMPARATOR_EQUALITY
      }
      predicates {
        field_path: "mil_view.disposition"
        value { list_type { values { enum_type { value: 2 } } values { enum_type { value: 3 } } } }
        comparator: COMPARATOR_IN
      }
    }
  }
}
```

To watch for threat tracks, do the following:

#### Build the filter

```go title={"Go (REST)"} startLine={23} maxLines={33}
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	Lattice "github.com/anduril/lattice-sdk-go/v5"
	"github.com/anduril/lattice-sdk-go/v5/client"
	"github.com/anduril/lattice-sdk-go/v5/option"
)

// enumValue builds an enum filter value. Filters take the integer value of
// an ontology enum, for example DISPOSITION_HOSTILE is 2.
func enumValue(v int) *Lattice.Value {
	return &Lattice.Value{EnumType: &Lattice.EnumType{Value: Lattice.Int(v)}}
}

// threatFilter matches air tracks that are hostile or suspicious. The filter is
// evaluated continuously: an entity that starts matching arrives as CREATED, and
// one that stops matching arrives as DELETED.
func threatFilter() *Lattice.Statement {
	return &Lattice.Statement{
		And: &Lattice.AndOperation{
			PredicateSet: &Lattice.PredicateSet{
				Predicates: []*Lattice.Predicate{
					{
						FieldPath:  Lattice.String("ontology.template"),
						Value:      enumValue(1), // TEMPLATE_TRACK
						Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
					},
					{
						FieldPath:  Lattice.String("mil_view.environment"),
						Value:      enumValue(1), // ENVIRONMENT_AIR
						Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
					},
					{
						FieldPath: Lattice.String("mil_view.disposition"),
						Value: &Lattice.Value{ListType: &Lattice.ListType{
							Values: []*Lattice.Value{
								enumValue(2), // DISPOSITION_HOSTILE
								enumValue(3), // DISPOSITION_SUSPICIOUS
							},
						}},
						Comparator: Lattice.PredicateComparatorComparatorIn.Ptr(),
					},
				},
			},
		},
	}
}

// trackPosition is the newest position of a track.
type trackPosition struct {
	lat, lon, hae float64
}

// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *Lattice.Entity) *trackPosition {
	if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic != nil && geodetic.Location != nil {
		loc := geodetic.Location
		pos := &trackPosition{
			lat: deref(loc.LatitudeDegrees),
			lon: deref(loc.LongitudeDegrees),
			hae: deref(loc.GetUniversalAltitudeHae().GetValueMeters()),
		}
		return pos
	}
	if loc := entity.GetLocation(); loc != nil && loc.Position != nil {
		pos := &trackPosition{
			lat: deref(loc.Position.LatitudeDegrees),
			lon: deref(loc.Position.LongitudeDegrees),
			hae: deref(loc.Position.AltitudeHaeMeters),
		}
		return pos
	}
	return nil
}

// deref returns the value of an optional field, or the zero value if unset.
func deref[T any](p *T) T {
	var zero T
	if p == nil {
		return zero
	}
	return *p
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatal("Required environment variables not set.")
	}

	headers := http.Header{}
	headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))

	latticeClient := client.NewClient(
		option.WithToken(environmentToken),
		option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
		option.WithHTTPHeader(headers),
	)

	// Stream every entity that matches the threat filter, with all components.
	stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
		Filter: threatFilter(),
	})
	if err != nil {
		log.Fatalf("Failed to create entity stream: %v", err)
	}
	defer stream.Close()

	// Candidate table: entity ID to last known position.
	candidates := map[string]trackPosition{}
	log.Println("Watching for threat tracks...")

	for {
		message, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			log.Println("Stream completed successfully.")
			return
		}
		if err != nil {
			log.Fatalf("Error receiving message: %v", err)
		}

		if message.Event != "entity" {
			continue
		}
		event := message.Entity
		entity := event.Entity
		if entity == nil {
			continue
		}
		id := deref(entity.EntityID)

		switch deref(event.EventType) {
		case Lattice.EntityEventEventTypeEventTypeCreated,
			Lattice.EntityEventEventTypeEventTypePreexisting,
			Lattice.EntityEventEventTypeEventTypeUpdate:
			pos := extractPosition(entity)
			if pos == nil {
				continue
			}
			action := "UPDATED"
			if _, known := candidates[id]; !known {
				action = "ADDED"
			}
			candidates[id] = *pos
			log.Printf("%s %s lat=%.6f lon=%.6f hae=%.1fm candidates=%d",
				action, id, pos.lat, pos.lon, pos.hae, len(candidates))
		case Lattice.EntityEventEventTypeEventTypeDeleted:
			// The entity expired, was deleted, or no longer matches the filter.
			if _, known := candidates[id]; known {
				delete(candidates, id)
				log.Printf("REMOVED %s candidates=%d", id, len(candidates))
			}
		}
	}
}

```

```java title={"Java (REST)"} startLine={57} maxLines={29}
package org.example;

import com.anduril.AsyncLattice;
import com.anduril.resources.entities.requests.EntityStreamRequest;
import com.anduril.resources.entities.types.StreamEntitiesResponse;
import com.anduril.types.AndOperation;
import com.anduril.types.Entity;
import com.anduril.types.EntityEventEventType;
import com.anduril.types.EntityStreamEvent;
import com.anduril.types.EnumType;
import com.anduril.types.KinematicsGeodetic;
import com.anduril.types.ListType;
import com.anduril.types.Location;
import com.anduril.types.LocationGeodetic;
import com.anduril.types.Position;
import com.anduril.types.Predicate;
import com.anduril.types.PredicateComparator;
import com.anduril.types.PredicateSet;
import com.anduril.types.Statement;
import com.anduril.types.Value;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Example application that watches for hostile or suspicious air tracks using the Lattice SDK.
 */
public class StreamThreatTracks {

    /** The newest position of a track. */
    private static final class TrackPosition {
        final double lat;
        final double lon;
        final double hae;

        TrackPosition(double lat, double lon, double hae) {
            this.lat = lat;
            this.lon = lon;
            this.hae = hae;
        }
    }

    /** Filters take the integer value of an ontology enum, for example DISPOSITION_HOSTILE is 2. */
    static Value enumValue(int value) {
        return Value.builder().enumType(EnumType.builder().value(value).build()).build();
    }

    static Predicate enumEquals(String fieldPath, int value) {
        return Predicate.builder()
            .fieldPath(fieldPath)
            .value(enumValue(value))
            .comparator(PredicateComparator.COMPARATOR_EQUALITY)
            .build();
    }

    /**
     * Match air tracks that are hostile or suspicious. The filter is evaluated continuously:
     * an entity that starts matching arrives as CREATED, and one that stops matching
     * arrives as DELETED.
     */
    static Statement threatFilter() {
        Predicate dispositionIn = Predicate.builder()
            .fieldPath("mil_view.disposition")
            .value(Value.builder()
                .listType(ListType.builder()
                    .values(Arrays.asList(
                        enumValue(2), // DISPOSITION_HOSTILE
                        enumValue(3))) // DISPOSITION_SUSPICIOUS
                    .build())
                .build())
            .comparator(PredicateComparator.COMPARATOR_IN)
            .build();

        return Statement.builder()
            .and(AndOperation.builder()
                .predicateSet(PredicateSet.builder()
                    .predicates(Arrays.asList(
                        enumEquals("ontology.template", 1), // TEMPLATE_TRACK
                        enumEquals("mil_view.environment", 1), // ENVIRONMENT_AIR
                        dispositionIn))
                    .build())
                .build())
            .build();
    }

    /**
     * Return the newest position, preferring kinematics over location. Kinematics is the
     * recommended source for tracks. Fall back to location if the entity has no kinematics.
     */
    static Optional<TrackPosition> extractPosition(Entity entity) {
        Optional<KinematicsGeodetic> geodetic = entity.getKinematics().flatMap(k -> k.getKinematicsGeodetic());
        if (geodetic.isPresent() && geodetic.get().getLocation().isPresent()) {
            LocationGeodetic loc = geodetic.get().getLocation().get();
            return Optional.of(new TrackPosition(
                loc.getLatitudeDegrees().orElse(0.0),
                loc.getLongitudeDegrees().orElse(0.0),
                loc.getUniversalAltitudeHae().flatMap(a -> a.getValueMeters()).orElse(0.0)));
        }
        Optional<Location> location = entity.getLocation();
        if (location.isPresent() && location.get().getPosition().isPresent()) {
            Position position = location.get().getPosition().get();
            return Optional.of(new TrackPosition(
                position.getLatitudeDegrees().orElse(0.0),
                position.getLongitudeDegrees().orElse(0.0),
                position.getAltitudeHaeMeters().orElse(0.0)));
        }
        return Optional.empty();
    }

    public static void main(String[] args) {
        // Get environment variables
        String endpoint = System.getenv("LATTICE_ENDPOINT");
        String environmentToken = System.getenv("ENVIRONMENT_TOKEN");
        String sandboxesToken = System.getenv("SANDBOXES_TOKEN");

        // Check required variables
        if (endpoint == null || environmentToken == null || sandboxesToken == null) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        try {
            AsyncLattice client = AsyncLattice.builder()
                .url(endpoint)
                .token(environmentToken)
                .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
                .build();

            // Stream every entity that matches the threat filter, with all components.
            EntityStreamRequest request = EntityStreamRequest
                .builder()
                .filter(threatFilter())
                .build();

            // Candidate table: entity ID to last known position.
            Map<String, TrackPosition> candidates = new HashMap<>();
            System.out.println("Watching for threat tracks...");

            client.entities().streamEntities(request)
                .thenAccept(responses -> {
                    for (StreamEntitiesResponse response : responses) {
                        if (!response.getEntity().isPresent()) {
                            continue;
                        }
                        EntityStreamEvent event = response.getEntity().get();
                        if (!event.getEntity().isPresent()) {
                            continue;
                        }
                        Entity entity = event.getEntity().get();
                        String id = entity.getEntityId().orElse("");
                        EntityEventEventType.Value type = event.getEventType()
                            .map(EntityEventEventType::getEnumValue)
                            .orElse(EntityEventEventType.Value.EVENT_TYPE_INVALID);

                        switch (type) {
                            case EVENT_TYPE_CREATED:
                            case EVENT_TYPE_PREEXISTING:
                            case EVENT_TYPE_UPDATE: {
                                Optional<TrackPosition> position = extractPosition(entity);
                                if (!position.isPresent()) {
                                    break;
                                }
                                String action = candidates.containsKey(id) ? "UPDATED" : "ADDED";
                                candidates.put(id, position.get());
                                TrackPosition p = position.get();
                                System.out.printf("%s %s lat=%.6f lon=%.6f hae=%.1fm candidates=%d%n",
                                    action, id, p.lat, p.lon, p.hae, candidates.size());
                                break;
                            }
                            case EVENT_TYPE_DELETED:
                                // The entity expired, was deleted, or no longer matches the filter.
                                if (candidates.remove(id) != null) {
                                    System.out.printf("REMOVED %s candidates=%d%n", id, candidates.size());
                                }
                                break;
                            default:
                                break;
                        }
                    }
                })
                .exceptionally(ex -> {
                    System.err.println("Exception while streaming entities: " + ex.getMessage());
                    return null;
                })
                .join();
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
    }
}

```

```py title={"Python (REST)"} startLine={39} maxLines={36}
from anduril import (
    AndOperation,
    AsyncLattice,
    Entity,
    EnumType,
    ListType,
    Predicate,
    PredicateSet,
    Statement,
    Value,
)
from typing import NamedTuple, Optional
import asyncio
import os
import sys

lattice_endpoint = os.getenv('LATTICE_ENDPOINT')
environment_token = os.getenv('ENVIRONMENT_TOKEN')

# Remove sandboxes_token from the following statements if you are not developing on Sandboxes.
sandboxes_token = os.getenv('SANDBOXES_TOKEN')
if not environment_token or not lattice_endpoint or not sandboxes_token:
    print("Missing environment variables.")
    sys.exit(1)

client = AsyncLattice(
    base_url=f"https://{lattice_endpoint}",
    token=lambda: str(environment_token),
    # Remove the following header if you are not developing on Sandboxes.
    headers={ "anduril-sandbox-authorization": f"Bearer {sandboxes_token}" }
)


def enum_value(value: int) -> Value:
    """Filters take the integer value of an ontology enum, for example DISPOSITION_HOSTILE is 2."""
    return Value(enum_type=EnumType(value=value))


def threat_filter() -> Statement:
    """Match air tracks that are hostile or suspicious.

    The filter is evaluated continuously: an entity that starts matching arrives
    as CREATED, and one that stops matching arrives as DELETED.
    """
    return Statement(
        and_=AndOperation(
            predicate_set=PredicateSet(
                predicates=[
                    Predicate(
                        field_path="ontology.template",
                        value=enum_value(1),  # TEMPLATE_TRACK
                        comparator="COMPARATOR_EQUALITY",
                    ),
                    Predicate(
                        field_path="mil_view.environment",
                        value=enum_value(1),  # ENVIRONMENT_AIR
                        comparator="COMPARATOR_EQUALITY",
                    ),
                    Predicate(
                        field_path="mil_view.disposition",
                        value=Value(
                            list_type=ListType(
                                values=[
                                    enum_value(2),  # DISPOSITION_HOSTILE
                                    enum_value(3),  # DISPOSITION_SUSPICIOUS
                                ]
                            )
                        ),
                        comparator="COMPARATOR_IN",
                    ),
                ]
            )
        )
    )


class TrackPosition(NamedTuple):
    lat: float
    lon: float
    hae: float


def extract_position(entity: Entity) -> Optional[TrackPosition]:
    """Return the newest position, preferring kinematics over location.

    Kinematics is the recommended source for tracks. Fall back to location if
    the entity has no kinematics. Return None if neither has a position.
    """
    geodetic = entity.kinematics.kinematics_geodetic if entity.kinematics else None
    if geodetic and geodetic.location:
        loc = geodetic.location
        altitude = loc.universal_altitude_hae
        return TrackPosition(
            lat=loc.latitude_degrees or 0.0,
            lon=loc.longitude_degrees or 0.0,
            hae=(altitude.value_meters if altitude else None) or 0.0,
        )
    if entity.location and entity.location.position:
        position = entity.location.position
        return TrackPosition(
            lat=position.latitude_degrees or 0.0,
            lon=position.longitude_degrees or 0.0,
            hae=position.altitude_hae_meters or 0.0,
        )
    return None


async def app():
    # Candidate table: entity ID to last known position.
    candidates: dict[str, TrackPosition] = {}

    try:
        # Stream every entity that matches the threat filter, with all components.
        event_stream = client.entities.stream_entities(filter=threat_filter())
        print("Watching for threat tracks...")
        async for event in event_stream:
            if event.event != "entity" or not event.entity:
                continue
            entity_id = event.entity.entity_id or ""

            if event.event_type in ("EVENT_TYPE_CREATED", "EVENT_TYPE_PREEXISTING", "EVENT_TYPE_UPDATE"):
                position = extract_position(event.entity)
                if not position:
                    continue
                action = "UPDATED" if entity_id in candidates else "ADDED"
                candidates[entity_id] = position
                print(f"{action} {entity_id} lat={position.lat:.6f} lon={position.lon:.6f} "
                      f"hae={position.hae:.1f}m candidates={len(candidates)}")
            elif event.event_type == "EVENT_TYPE_DELETED":
                # The entity expired, was deleted, or no longer matches the filter.
                if candidates.pop(entity_id, None):
                    print(f"REMOVED {entity_id} candidates={len(candidates)}")
    except asyncio.CancelledError:
        print("Streaming cancelled...")
    except Exception as error:
        print(f"Exception: {error}")

if __name__ == "__main__":
    asyncio.run(app())

```

```ts title={"TypeScript (REST)"} startLine={28} maxLines={35}
import { Lattice, LatticeClient } from "@anduril-industries/lattice-sdk";

const latticeEndpoint = process.env.LATTICE_ENDPOINT;
const environmentToken = process.env.ENVIRONMENT_TOKEN;

// Remove sandboxesToken from the following statement if you are not developing on Sandboxes.
const sandboxesToken = process.env.SANDBOXES_TOKEN;
if (!latticeEndpoint || !environmentToken || !sandboxesToken) {
    console.log('Missing required environment variables.');
    process.exit(1);
}

const client = new LatticeClient(
    {
        baseUrl: `https://${latticeEndpoint}`,
        token: environmentToken,
        // Remove the following statement if you are not developing on Sandboxes.
        headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}` }
    }
);

// Filters take the integer value of an ontology enum, for example
// DISPOSITION_HOSTILE is 2.
function enumValue(value: number): Lattice.Value {
    return { enumType: { value } };
}

// Match air tracks that are hostile or suspicious. The filter is evaluated
// continuously: an entity that starts matching arrives as CREATED, and one that
// stops matching arrives as DELETED.
function threatFilter(): Lattice.Statement {
    return {
        and: {
            predicateSet: {
                predicates: [
                    {
                        fieldPath: "ontology.template",
                        value: enumValue(1), // TEMPLATE_TRACK
                        comparator: "COMPARATOR_EQUALITY",
                    },
                    {
                        fieldPath: "mil_view.environment",
                        value: enumValue(1), // ENVIRONMENT_AIR
                        comparator: "COMPARATOR_EQUALITY",
                    },
                    {
                        fieldPath: "mil_view.disposition",
                        value: {
                            listType: {
                                values: [
                                    enumValue(2), // DISPOSITION_HOSTILE
                                    enumValue(3), // DISPOSITION_SUSPICIOUS
                                ],
                            },
                        },
                        comparator: "COMPARATOR_IN",
                    },
                ],
            },
        },
    };
}

interface TrackPosition {
    lat: number;
    lon: number;
    hae: number;
}

// Return the newest position, preferring kinematics over location. Kinematics
// is the recommended source for tracks. Fall back to location if the entity
// has no kinematics. Return undefined if neither has a position.
function extractPosition(entity: Lattice.Entity): TrackPosition | undefined {
    const geodetic = entity.kinematics?.kinematicsGeodetic;
    if (geodetic?.location) {
        return {
            lat: geodetic.location.latitudeDegrees ?? 0,
            lon: geodetic.location.longitudeDegrees ?? 0,
            hae: geodetic.location.universalAltitudeHae?.valueMeters ?? 0,
        };
    }
    const position = entity.location?.position;
    if (position) {
        return {
            lat: position.latitudeDegrees ?? 0,
            lon: position.longitudeDegrees ?? 0,
            hae: position.altitudeHaeMeters ?? 0,
        };
    }
    return undefined;
}

async function App() {
    // Candidate table: entity ID to last known position.
    const candidates = new Map<string, TrackPosition>();

    try {
        // Stream every entity that matches the threat filter, with all components.
        const eventStream = await client.entities.streamEntities({ filter: threatFilter() });
        console.log("Watching for threat tracks...");

        for await (const event of eventStream) {
            if (event.event !== "entity" || !event.entity) {
                continue;
            }
            const entity = event.entity;
            const id = entity.entityId ?? "";

            switch (event.eventType) {
                case "EVENT_TYPE_CREATED":
                case "EVENT_TYPE_PREEXISTING":
                case "EVENT_TYPE_UPDATE": {
                    const position = extractPosition(entity);
                    if (!position) {
                        break;
                    }
                    const action = candidates.has(id) ? "UPDATED" : "ADDED";
                    candidates.set(id, position);
                    console.log(`${action} ${id} lat=${position.lat.toFixed(6)} lon=${position.lon.toFixed(6)} hae=${position.hae.toFixed(1)}m candidates=${candidates.size}`);
                    break;
                }
                case "EVENT_TYPE_DELETED":
                    // The entity expired, was deleted, or no longer matches the filter.
                    if (candidates.delete(id)) {
                        console.log(`REMOVED ${id} candidates=${candidates.size}`);
                    }
                    break;
            }
        }
    } catch (error) {
        console.log(`Exception while streaming entities: ${error}`);
    }
}

App();

```

```rs title={"Rust (REST)"} startLine={11} maxLines={34}
use anduril_lattice_sdk::prelude::*;

use std::env;

/// Builds an enum filter value. Filters take the integer value of an ontology
/// enum, for example DISPOSITION_HOSTILE is 2.
fn enum_value(value: i64) -> Value {
    json!({ "enumType": { "value": value } })
}

/// Matches air tracks that are hostile or suspicious. The filter is evaluated
/// continuously: an entity that starts matching arrives as CREATED, and one that
/// stops matching arrives as DELETED.
fn threat_filter() -> Statement {
    let predicates = vec![
        Predicate {
            field_path: Some("ontology.template".to_string()),
            value: Some(enum_value(1)), // TEMPLATE_TRACK
            comparator: Some(PredicateComparator::ComparatorEquality),
        },
        Predicate {
            field_path: Some("mil_view.environment".to_string()),
            value: Some(enum_value(1)), // ENVIRONMENT_AIR
            comparator: Some(PredicateComparator::ComparatorEquality),
        },
        Predicate {
            field_path: Some("mil_view.disposition".to_string()),
            value: Some(json!({ "listType": { "values": [
                enum_value(2), // DISPOSITION_HOSTILE
                enum_value(3), // DISPOSITION_SUSPICIOUS
            ] } })),
            comparator: Some(PredicateComparator::ComparatorIn),
        },
    ];
    Statement {
        and: Some(Box::new(AndOperation {
            predicate_set: Some(PredicateSet {
                predicates: Some(predicates),
            }),
            ..Default::default()
        })),
        ..Default::default()
    }
}

/// The newest position of a track.
#[derive(Clone, Copy)]
struct TrackPosition {
    lat: f64,
    lon: f64,
    hae: f64,
}

/// Returns the newest position, preferring kinematics over location. Kinematics
/// is the recommended source for tracks. Falls back to location if the entity
/// has no kinematics. Returns None if neither has a position.
fn extract_position(entity: &Entity) -> Option<TrackPosition> {
    if let Some(geodetic) = entity
        .kinematics
        .as_ref()
        .and_then(|k| k.kinematics_geodetic.as_ref())
    {
        if let Some(loc) = &geodetic.location {
            return Some(TrackPosition {
                lat: loc.latitude_degrees.unwrap_or(0.0),
                lon: loc.longitude_degrees.unwrap_or(0.0),
                hae: loc
                    .universal_altitude_hae
                    .as_ref()
                    .and_then(|a| a.value_meters)
                    .unwrap_or(0.0),
            });
        }
    }
    let location = entity.location.as_ref()?;
    let position = location.position.as_ref()?;
    Some(TrackPosition {
        lat: position.latitude_degrees.unwrap_or(0.0),
        lon: position.longitude_degrees.unwrap_or(0.0),
        hae: position.altitude_hae_meters.unwrap_or(0.0),
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    // Remove sandboxes_token if you are not developing on Sandboxes.
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables:");
        eprintln!("  LATTICE_ENDPOINT");
        eprintln!("  ENVIRONMENT_TOKEN");
        eprintln!("  SANDBOXES_TOKEN");
        std::process::exit(1);
    }

    let config = ClientConfig {
        base_url: format!("https://{}", lattice_endpoint),
        token: Some(environment_token),
        // Remove custom_headers if you are not developing on Sandboxes.
        custom_headers: HashMap::from([(
            "anduril-sandbox-authorization".to_string(),
            format!("Bearer {}", sandboxes_token),
        )]),
        ..Default::default()
    };
    let client = Lattice::new(config)?;

    // Stream every entity that matches the threat filter, with all components.
    let request = EntityStreamRequest {
        filter: Some(threat_filter()),
        ..Default::default()
    };
    let stream = client.entities.stream_entities(&request, None).await?;
    let mut stream = std::pin::pin!(stream);

    // Candidate table: entity ID to last known position.
    let mut candidates: HashMap<String, TrackPosition> = HashMap::new();
    println!("Watching for threat tracks...");

    while let Some(result) = stream.next().await {
        let event = match result {
            Ok(event) => event,
            Err(error) => {
                eprintln!("Exception: {}", error);
                continue;
            }
        };
        let StreamEntitiesResponse::Entity { data, .. } = event else {
            continue;
        };
        let event = data.entity_event_fields;
        let Some(entity) = &event.entity else { continue };
        let id = entity.entity_id.clone().unwrap_or_default();

        match event.event_type {
            Some(
                EntityEventEventType::EventTypeCreated
                | EntityEventEventType::EventTypePreexisting
                | EntityEventEventType::EventTypeUpdate,
            ) => {
                let Some(position) = extract_position(entity) else { continue };
                let is_new = candidates.insert(id.clone(), position).is_none();
                println!(
                    "{} {} lat={:.6} lon={:.6} hae={:.1}m candidates={}",
                    if is_new { "ADDED" } else { "UPDATED" },
                    id,
                    position.lat,
                    position.lon,
                    position.hae,
                    candidates.len()
                );
            }
            Some(EntityEventEventType::EventTypeDeleted) => {
                // The entity expired, was deleted, or no longer matches the filter.
                let was_known = candidates.remove(&id).is_some();
                if was_known {
                    println!("REMOVED {} candidates={}", id, candidates.len());
                }
            }
            _ => {}
        }
    }

    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={31} maxLines={32}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
package main

import (
	"context"
	"io"
	"log"
	"os"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

// enumPredicate builds an EQUALITY predicate on an ontology enum. Filters take
// the integer value of the enum.
func enumPredicate(fieldPath string, value int32) *entitymanagerv1.Predicate {
	return &entitymanagerv1.Predicate{
		FieldPath: fieldPath,
		Value: &entitymanagerv1.Value{
			Type: &entitymanagerv1.Value_EnumType{
				EnumType: &entitymanagerv1.EnumType{Value: value},
			},
		},
		Comparator: entitymanagerv1.Comparator_COMPARATOR_EQUALITY,
	}
}

// threatFilter matches air tracks that are hostile or suspicious. The filter is
// evaluated continuously: an entity that starts matching arrives as CREATED, and
// one that stops matching arrives as DELETED.
func threatFilter() *entitymanagerv1.Statement {
	dispositions := []*entitymanagerv1.Value{
		{Type: &entitymanagerv1.Value_EnumType{EnumType: &entitymanagerv1.EnumType{Value: 2}}}, // DISPOSITION_HOSTILE
		{Type: &entitymanagerv1.Value_EnumType{EnumType: &entitymanagerv1.EnumType{Value: 3}}}, // DISPOSITION_SUSPICIOUS
	}
	return &entitymanagerv1.Statement{
		Operation: &entitymanagerv1.Statement_And{
			And: &entitymanagerv1.AndOperation{
				Children: &entitymanagerv1.AndOperation_PredicateSet{
					PredicateSet: &entitymanagerv1.PredicateSet{
						Predicates: []*entitymanagerv1.Predicate{
							enumPredicate("ontology.template", int32(entitymanagerv1.Template_TEMPLATE_TRACK)),
							enumPredicate("mil_view.environment", 1), // ENVIRONMENT_AIR
							{
								FieldPath: "mil_view.disposition",
								Value: &entitymanagerv1.Value{
									Type: &entitymanagerv1.Value_ListType{
										ListType: &entitymanagerv1.ListType{Values: dispositions},
									},
								},
								Comparator: entitymanagerv1.Comparator_COMPARATOR_IN,
							},
						},
					},
				},
			},
		},
	}
}

// trackPosition is the newest position of a track.
type trackPosition struct {
	lat, lon, hae float64
}

// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *entitymanagerv1.Entity) *trackPosition {
	if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic.GetLocation() != nil {
		loc := geodetic.GetLocation()
		pos := &trackPosition{
			lat: loc.GetLatitudeDegrees(),
			lon: loc.GetLongitudeDegrees(),
			hae: loc.GetUniversalAltitudeHae().GetValueMeters(),
		}
		return pos
	}
	if loc := entity.GetLocation(); loc.GetPosition() != nil {
		position := loc.GetPosition()
		pos := &trackPosition{
			lat: position.GetLatitudeDegrees(),
			lon: position.GetLongitudeDegrees(),
			hae: position.GetAltitudeHaeMeters().GetValue(),
		}
		return pos
	}
	return nil
}

func main() {
	ctx := context.Background()

	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatalf("Missing required environment variables")
	}
	auth := &BearerTokenAuth{
		Token:          environmentToken,
		SandboxesToken: sandboxesToken,
	}

	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}
	conn, err := grpc.NewClient(latticeEndpoint, opts...)
	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	// Stream every entity that matches the threat filter, with all components.
	stream, err := client.StreamEntityComponents(ctx, &entitymanagerv1.StreamEntityComponentsRequest{
		Filter:               threatFilter(),
		IncludeAllComponents: true,
	})
	if err != nil {
		log.Fatalf("Error creating stream: %v", err)
	}

	// Candidate table: entity ID to last known position.
	candidates := map[string]trackPosition{}
	log.Println("Watching for threat tracks...")

	for {
		response, err := stream.Recv()
		if err == io.EOF {
			log.Println("Stream completed successfully.")
			return
		}
		if err != nil {
			log.Fatalf("Error receiving stream data: %v", err)
		}

		// Heartbeats carry no entity event.
		event := response.GetEntityEvent()
		entity := event.GetEntity()
		if entity == nil {
			continue
		}
		id := entity.GetEntityId()

		switch event.GetEventType() {
		case entitymanagerv1.EventType_EVENT_TYPE_CREATED,
			entitymanagerv1.EventType_EVENT_TYPE_PREEXISTING,
			entitymanagerv1.EventType_EVENT_TYPE_UPDATE:
			pos := extractPosition(entity)
			if pos == nil {
				continue
			}
			action := "UPDATED"
			if _, known := candidates[id]; !known {
				action = "ADDED"
			}
			candidates[id] = *pos
			log.Printf("%s %s lat=%.6f lon=%.6f hae=%.1fm candidates=%d",
				action, id, pos.lat, pos.lon, pos.hae, len(candidates))
		case entitymanagerv1.EventType_EVENT_TYPE_DELETED:
			// The entity expired, was deleted, or no longer matches the filter.
			if _, known := candidates[id]; known {
				delete(candidates, id)
				log.Printf("REMOVED %s candidates=%d", id, len(candidates))
			}
		}
	}
}

```

```py title={"Python (gRPC)"} startLine={37} maxLines={45}
# This Python example is compatible with artifacts generated using the following
# Buf plugins: https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:bufbuild/py
# and https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:connectrpc/py

import os
import sys
from typing import NamedTuple, Optional

from bearer_auth import create_client
from protobuf import Oneof

from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.entity_manager_api_pub_pb import (
    EventType,
    StreamEntityComponentsRequest,
)
from anduril.entitymanager.v1.entity_pub_pb import Entity
from anduril.entitymanager.v1.filter_pub_pb import (
    AndOperation,
    Comparator,
    EnumType,
    ListType,
    Predicate,
    PredicateSet,
    Statement,
    Value,
)
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.ontology.v1.type_pub_pb import Disposition, Environment


def enum_value(value: int) -> Value:
    """Filters take the integer value of an ontology enum."""
    return Value(type=Oneof("enum_type", EnumType(value=value)))


def threat_filter() -> Statement:
    """Match air tracks that are hostile or suspicious.

    The filter is evaluated continuously: an entity that starts matching arrives
    as CREATED, and one that stops matching arrives as DELETED.
    """
    return Statement(
        operation=Oneof(
            "and",
            AndOperation(
                children=Oneof(
                    "predicate_set",
                    PredicateSet(
                        predicates=[
                            Predicate(
                                field_path="ontology.template",
                                value=enum_value(Template.TRACK.value),
                                comparator=Comparator.EQUALITY,
                            ),
                            Predicate(
                                field_path="mil_view.environment",
                                value=enum_value(Environment.AIR.value),
                                comparator=Comparator.EQUALITY,
                            ),
                            Predicate(
                                field_path="mil_view.disposition",
                                value=Value(
                                    type=Oneof(
                                        "list_type",
                                        ListType(
                                            values=[
                                                enum_value(Disposition.HOSTILE.value),
                                                enum_value(Disposition.SUSPICIOUS.value),
                                            ]
                                        ),
                                    )
                                ),
                                comparator=Comparator.IN,
                            ),
                        ]
                    ),
                )
            ),
        )
    )


class TrackPosition(NamedTuple):
    lat: float
    lon: float
    hae: float


def extract_position(entity: Entity) -> Optional[TrackPosition]:
    """Return the newest position, preferring kinematics over location.

    Kinematics is the recommended source for tracks. Fall back to location if
    the entity has no kinematics. Return None if neither has a position.
    """
    if entity.has_field("kinematics") and entity.kinematics.has_field("kinematics_geodetic"):
        geodetic = entity.kinematics.kinematics_geodetic
        if geodetic.has_field("location"):
            loc = geodetic.location
            return TrackPosition(
                lat=loc.latitude_degrees,
                lon=loc.longitude_degrees,
                hae=loc.universal_altitude_hae.value_meters,
            )
    if entity.has_field("location") and entity.location.has_field("position"):
        position = entity.location.position
        return TrackPosition(
            lat=position.latitude_degrees,
            lon=position.longitude_degrees,
            hae=position.altitude_hae_meters.value if position.has_field("altitude_hae_meters") else 0.0,
        )
    return None


def main():
    environment_token = os.getenv("ENVIRONMENT_TOKEN")
    lattice_endpoint = os.getenv("LATTICE_ENDPOINT")
    sandboxes_token = os.getenv("SANDBOXES_TOKEN")

    if not environment_token or not lattice_endpoint or not sandboxes_token:
        print("Missing required environment variables", file=sys.stderr)
        sys.exit(1)

    # Create the API client over Connect gRPC with authentication
    client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    # Stream every entity that matches the threat filter, with all components.
    request = StreamEntityComponentsRequest(
        filter=threat_filter(),
        include_all_components=True,
    )

    try:
        stream = client.stream_entity_components(request)
    except Exception as error:
        print(f"Error creating stream: {error}", file=sys.stderr)
        sys.exit(1)

    # Candidate table: entity ID to last known position.
    candidates: dict[str, TrackPosition] = {}
    print("Watching for threat tracks...")

    try:
        for response in stream:
            # Heartbeat messages carry no entity_event, so skip them.
            if not response.has_field("entity_event"):
                continue
            event = response.entity_event
            entity = event.entity
            if not entity:
                continue
            entity_id = entity.entity_id

            if event.event_type in (EventType.CREATED, EventType.PREEXISTING, EventType.UPDATE):
                position = extract_position(entity)
                if not position:
                    continue
                action = "UPDATED" if entity_id in candidates else "ADDED"
                candidates[entity_id] = position
                print(f"{action} {entity_id} lat={position.lat:.6f} lon={position.lon:.6f} "
                      f"hae={position.hae:.1f}m candidates={len(candidates)}")
            elif event.event_type == EventType.DELETED:
                # The entity expired, was deleted, or no longer matches the filter.
                if candidates.pop(entity_id, None):
                    print(f"REMOVED {entity_id} candidates={len(candidates)}")
        print("End of stream reached.")
    except Exception as error:
        print(f"Error receiving stream data: {error}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={45} maxLines={28}
// This Rust example is compatible with artifacts generated using
// the following grpc/rust plugin: https://buf.build/anduril/lattice-sdk/sdks/main:community/neoeinstein-tonic
mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    and_operation, statement, value, AndOperation, Comparator, Entity, EnumType, EventType,
    ListType, Predicate, PredicateSet, Statement, StreamEntityComponentsRequest, Template, Value,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{
    Disposition, Environment,
};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use tonic::metadata::MetadataValue;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::Request;

use std::collections::HashMap;
use std::env;

/// The newest position of a track.
#[derive(Clone, Copy)]
struct TrackPosition {
    lat: f64,
    lon: f64,
    hae: f64,
}

/// Builds an enum filter value. Filters take the integer value of an ontology enum.
fn enum_value(value: i32) -> Value {
    Value {
        r#type: Some(value::Type::EnumType(EnumType { value })),
    }
}

/// Builds an EQUALITY predicate on an enum field.
fn enum_equals(field_path: &str, value: i32) -> Predicate {
    Predicate {
        field_path: field_path.to_string(),
        value: Some(enum_value(value)),
        comparator: Comparator::Equality as i32,
    }
}

/// Matches air tracks that are hostile or suspicious. The filter is evaluated
/// continuously: an entity that starts matching arrives as CREATED, and one that
/// stops matching arrives as DELETED.
fn threat_filter() -> Statement {
    let disposition_in = Predicate {
        field_path: "mil_view.disposition".to_string(),
        value: Some(Value {
            r#type: Some(value::Type::ListType(ListType {
                values: vec![
                    enum_value(Disposition::Hostile as i32),
                    enum_value(Disposition::Suspicious as i32),
                ],
            })),
        }),
        comparator: Comparator::In as i32,
    };
    Statement {
        operation: Some(statement::Operation::And(AndOperation {
            children: Some(and_operation::Children::PredicateSet(PredicateSet {
                predicates: vec![
                    enum_equals("ontology.template", Template::Track as i32),
                    enum_equals("mil_view.environment", Environment::Air as i32),
                    disposition_in,
                ],
            })),
        })),
    }
}

/// Returns the newest position, preferring kinematics over location. Kinematics
/// is the recommended source for tracks. Falls back to location if the entity
/// has no kinematics. Returns None if neither has a position.
fn extract_position(entity: &Entity) -> Option<TrackPosition> {
    if let Some(geodetic) = entity
        .kinematics
        .as_ref()
        .and_then(|k| k.kinematics_geodetic.as_ref())
    {
        if let Some(loc) = &geodetic.location {
            return Some(TrackPosition {
                lat: loc.latitude_degrees,
                lon: loc.longitude_degrees,
                hae: loc
                    .universal_altitude_hae
                    .as_ref()
                    .map_or(0.0, |a| a.value_meters),
            });
        }
    }
    let location = entity.location.as_ref()?;
    let position = location.position.as_ref()?;
    Some(TrackPosition {
        lat: position.latitude_degrees,
        lon: position.longitude_degrees,
        hae: position.altitude_hae_meters.unwrap_or(0.0),
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load environment variables
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    // Set up authentication handler
    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

    // Create gRPC channel with TLS
    let tls_config = ClientTlsConfig::new().with_native_roots();
    let channel = Channel::from_shared(format!("https://{}", lattice_endpoint))?
        .tls_config(tls_config)?
        .connect()
        .await?;

    // Fetch a fresh access token and build metadata values
    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<_> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<_> = format!("Bearer {}", sandboxes_token).parse()?;

    // Create EntityManager API client with authentication interceptor
    let mut client = EntityManagerApiClient::with_interceptor(
        channel,
        move |mut req: Request<()>| {
            req.metadata_mut()
                .insert("authorization", auth_header.clone());
            req.metadata_mut()
                .insert("anduril-sandbox-authorization", sandbox_header.clone());
            Ok(req)
        },
    );

    // Stream every entity that matches the threat filter, with all components.
    let request = Request::new(StreamEntityComponentsRequest {
        filter: Some(threat_filter()),
        include_all_components: true,
        ..Default::default()
    });

    let mut stream = client.stream_entity_components(request).await?.into_inner();

    // Candidate table: entity ID to last known position.
    let mut candidates: HashMap<String, TrackPosition> = HashMap::new();
    println!("Watching for threat tracks...");

    while let Some(response) = stream.message().await? {
        // Heartbeat messages carry no entity_event, so skip them.
        let Some(event) = response.entity_event else { continue };
        let Some(entity) = &event.entity else { continue };
        let id = entity.entity_id.clone();

        match EventType::try_from(event.event_type) {
            Ok(EventType::Created | EventType::Preexisting | EventType::Update) => {
                let Some(position) = extract_position(entity) else { continue };
                let is_new = candidates.insert(id.clone(), position).is_none();
                println!(
                    "{} {} lat={:.6} lon={:.6} hae={:.1}m candidates={}",
                    if is_new { "ADDED" } else { "UPDATED" },
                    id,
                    position.lat,
                    position.lon,
                    position.hae,
                    candidates.len()
                );
            }
            Ok(EventType::Deleted) => {
                // The entity expired, was deleted, or no longer matches the filter.
                let was_known = candidates.remove(&id).is_some();
                if was_known {
                    println!("REMOVED {} candidates={}", id, candidates.len());
                }
            }
            _ => {}
        }
    }
    println!("End of stream reached");

    Ok(())
}

```

#### Maintain a candidate list

Keep a table of candidate tracks keyed by entity ID. Add or update a candidate on
`EVENT_TYPE_PREEXISTING`, `EVENT_TYPE_CREATED`, and `EVENT_TYPE_UPDATE`, and remove it on
`EVENT_TYPE_DELETED`. Because Lattice evaluates the filter continuously, a track that an
operator reclassifies as friendly leaves the stream with an `EVENT_TYPE_DELETED` event:

```go title={"Go (REST)"} startLine={115} maxLines={55}
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	Lattice "github.com/anduril/lattice-sdk-go/v5"
	"github.com/anduril/lattice-sdk-go/v5/client"
	"github.com/anduril/lattice-sdk-go/v5/option"
)

// enumValue builds an enum filter value. Filters take the integer value of
// an ontology enum, for example DISPOSITION_HOSTILE is 2.
func enumValue(v int) *Lattice.Value {
	return &Lattice.Value{EnumType: &Lattice.EnumType{Value: Lattice.Int(v)}}
}

// threatFilter matches air tracks that are hostile or suspicious. The filter is
// evaluated continuously: an entity that starts matching arrives as CREATED, and
// one that stops matching arrives as DELETED.
func threatFilter() *Lattice.Statement {
	return &Lattice.Statement{
		And: &Lattice.AndOperation{
			PredicateSet: &Lattice.PredicateSet{
				Predicates: []*Lattice.Predicate{
					{
						FieldPath:  Lattice.String("ontology.template"),
						Value:      enumValue(1), // TEMPLATE_TRACK
						Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
					},
					{
						FieldPath:  Lattice.String("mil_view.environment"),
						Value:      enumValue(1), // ENVIRONMENT_AIR
						Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
					},
					{
						FieldPath: Lattice.String("mil_view.disposition"),
						Value: &Lattice.Value{ListType: &Lattice.ListType{
							Values: []*Lattice.Value{
								enumValue(2), // DISPOSITION_HOSTILE
								enumValue(3), // DISPOSITION_SUSPICIOUS
							},
						}},
						Comparator: Lattice.PredicateComparatorComparatorIn.Ptr(),
					},
				},
			},
		},
	}
}

// trackPosition is the newest position of a track.
type trackPosition struct {
	lat, lon, hae float64
}

// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *Lattice.Entity) *trackPosition {
	if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic != nil && geodetic.Location != nil {
		loc := geodetic.Location
		pos := &trackPosition{
			lat: deref(loc.LatitudeDegrees),
			lon: deref(loc.LongitudeDegrees),
			hae: deref(loc.GetUniversalAltitudeHae().GetValueMeters()),
		}
		return pos
	}
	if loc := entity.GetLocation(); loc != nil && loc.Position != nil {
		pos := &trackPosition{
			lat: deref(loc.Position.LatitudeDegrees),
			lon: deref(loc.Position.LongitudeDegrees),
			hae: deref(loc.Position.AltitudeHaeMeters),
		}
		return pos
	}
	return nil
}

// deref returns the value of an optional field, or the zero value if unset.
func deref[T any](p *T) T {
	var zero T
	if p == nil {
		return zero
	}
	return *p
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatal("Required environment variables not set.")
	}

	headers := http.Header{}
	headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))

	latticeClient := client.NewClient(
		option.WithToken(environmentToken),
		option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
		option.WithHTTPHeader(headers),
	)

	// Stream every entity that matches the threat filter, with all components.
	stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
		Filter: threatFilter(),
	})
	if err != nil {
		log.Fatalf("Failed to create entity stream: %v", err)
	}
	defer stream.Close()

	// Candidate table: entity ID to last known position.
	candidates := map[string]trackPosition{}
	log.Println("Watching for threat tracks...")

	for {
		message, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			log.Println("Stream completed successfully.")
			return
		}
		if err != nil {
			log.Fatalf("Error receiving message: %v", err)
		}

		if message.Event != "entity" {
			continue
		}
		event := message.Entity
		entity := event.Entity
		if entity == nil {
			continue
		}
		id := deref(entity.EntityID)

		switch deref(event.EventType) {
		case Lattice.EntityEventEventTypeEventTypeCreated,
			Lattice.EntityEventEventTypeEventTypePreexisting,
			Lattice.EntityEventEventTypeEventTypeUpdate:
			pos := extractPosition(entity)
			if pos == nil {
				continue
			}
			action := "UPDATED"
			if _, known := candidates[id]; !known {
				action = "ADDED"
			}
			candidates[id] = *pos
			log.Printf("%s %s lat=%.6f lon=%.6f hae=%.1fm candidates=%d",
				action, id, pos.lat, pos.lon, pos.hae, len(candidates))
		case Lattice.EntityEventEventTypeEventTypeDeleted:
			// The entity expired, was deleted, or no longer matches the filter.
			if _, known := candidates[id]; known {
				delete(candidates, id)
				log.Printf("REMOVED %s candidates=%d", id, len(candidates))
			}
		}
	}
}

```

```java title={"Java (REST)"} startLine={132} maxLines={46}
package org.example;

import com.anduril.AsyncLattice;
import com.anduril.resources.entities.requests.EntityStreamRequest;
import com.anduril.resources.entities.types.StreamEntitiesResponse;
import com.anduril.types.AndOperation;
import com.anduril.types.Entity;
import com.anduril.types.EntityEventEventType;
import com.anduril.types.EntityStreamEvent;
import com.anduril.types.EnumType;
import com.anduril.types.KinematicsGeodetic;
import com.anduril.types.ListType;
import com.anduril.types.Location;
import com.anduril.types.LocationGeodetic;
import com.anduril.types.Position;
import com.anduril.types.Predicate;
import com.anduril.types.PredicateComparator;
import com.anduril.types.PredicateSet;
import com.anduril.types.Statement;
import com.anduril.types.Value;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Example application that watches for hostile or suspicious air tracks using the Lattice SDK.
 */
public class StreamThreatTracks {

    /** The newest position of a track. */
    private static final class TrackPosition {
        final double lat;
        final double lon;
        final double hae;

        TrackPosition(double lat, double lon, double hae) {
            this.lat = lat;
            this.lon = lon;
            this.hae = hae;
        }
    }

    /** Filters take the integer value of an ontology enum, for example DISPOSITION_HOSTILE is 2. */
    static Value enumValue(int value) {
        return Value.builder().enumType(EnumType.builder().value(value).build()).build();
    }

    static Predicate enumEquals(String fieldPath, int value) {
        return Predicate.builder()
            .fieldPath(fieldPath)
            .value(enumValue(value))
            .comparator(PredicateComparator.COMPARATOR_EQUALITY)
            .build();
    }

    /**
     * Match air tracks that are hostile or suspicious. The filter is evaluated continuously:
     * an entity that starts matching arrives as CREATED, and one that stops matching
     * arrives as DELETED.
     */
    static Statement threatFilter() {
        Predicate dispositionIn = Predicate.builder()
            .fieldPath("mil_view.disposition")
            .value(Value.builder()
                .listType(ListType.builder()
                    .values(Arrays.asList(
                        enumValue(2), // DISPOSITION_HOSTILE
                        enumValue(3))) // DISPOSITION_SUSPICIOUS
                    .build())
                .build())
            .comparator(PredicateComparator.COMPARATOR_IN)
            .build();

        return Statement.builder()
            .and(AndOperation.builder()
                .predicateSet(PredicateSet.builder()
                    .predicates(Arrays.asList(
                        enumEquals("ontology.template", 1), // TEMPLATE_TRACK
                        enumEquals("mil_view.environment", 1), // ENVIRONMENT_AIR
                        dispositionIn))
                    .build())
                .build())
            .build();
    }

    /**
     * Return the newest position, preferring kinematics over location. Kinematics is the
     * recommended source for tracks. Fall back to location if the entity has no kinematics.
     */
    static Optional<TrackPosition> extractPosition(Entity entity) {
        Optional<KinematicsGeodetic> geodetic = entity.getKinematics().flatMap(k -> k.getKinematicsGeodetic());
        if (geodetic.isPresent() && geodetic.get().getLocation().isPresent()) {
            LocationGeodetic loc = geodetic.get().getLocation().get();
            return Optional.of(new TrackPosition(
                loc.getLatitudeDegrees().orElse(0.0),
                loc.getLongitudeDegrees().orElse(0.0),
                loc.getUniversalAltitudeHae().flatMap(a -> a.getValueMeters()).orElse(0.0)));
        }
        Optional<Location> location = entity.getLocation();
        if (location.isPresent() && location.get().getPosition().isPresent()) {
            Position position = location.get().getPosition().get();
            return Optional.of(new TrackPosition(
                position.getLatitudeDegrees().orElse(0.0),
                position.getLongitudeDegrees().orElse(0.0),
                position.getAltitudeHaeMeters().orElse(0.0)));
        }
        return Optional.empty();
    }

    public static void main(String[] args) {
        // Get environment variables
        String endpoint = System.getenv("LATTICE_ENDPOINT");
        String environmentToken = System.getenv("ENVIRONMENT_TOKEN");
        String sandboxesToken = System.getenv("SANDBOXES_TOKEN");

        // Check required variables
        if (endpoint == null || environmentToken == null || sandboxesToken == null) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        try {
            AsyncLattice client = AsyncLattice.builder()
                .url(endpoint)
                .token(environmentToken)
                .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
                .build();

            // Stream every entity that matches the threat filter, with all components.
            EntityStreamRequest request = EntityStreamRequest
                .builder()
                .filter(threatFilter())
                .build();

            // Candidate table: entity ID to last known position.
            Map<String, TrackPosition> candidates = new HashMap<>();
            System.out.println("Watching for threat tracks...");

            client.entities().streamEntities(request)
                .thenAccept(responses -> {
                    for (StreamEntitiesResponse response : responses) {
                        if (!response.getEntity().isPresent()) {
                            continue;
                        }
                        EntityStreamEvent event = response.getEntity().get();
                        if (!event.getEntity().isPresent()) {
                            continue;
                        }
                        Entity entity = event.getEntity().get();
                        String id = entity.getEntityId().orElse("");
                        EntityEventEventType.Value type = event.getEventType()
                            .map(EntityEventEventType::getEnumValue)
                            .orElse(EntityEventEventType.Value.EVENT_TYPE_INVALID);

                        switch (type) {
                            case EVENT_TYPE_CREATED:
                            case EVENT_TYPE_PREEXISTING:
                            case EVENT_TYPE_UPDATE: {
                                Optional<TrackPosition> position = extractPosition(entity);
                                if (!position.isPresent()) {
                                    break;
                                }
                                String action = candidates.containsKey(id) ? "UPDATED" : "ADDED";
                                candidates.put(id, position.get());
                                TrackPosition p = position.get();
                                System.out.printf("%s %s lat=%.6f lon=%.6f hae=%.1fm candidates=%d%n",
                                    action, id, p.lat, p.lon, p.hae, candidates.size());
                                break;
                            }
                            case EVENT_TYPE_DELETED:
                                // The entity expired, was deleted, or no longer matches the filter.
                                if (candidates.remove(id) != null) {
                                    System.out.printf("REMOVED %s candidates=%d%n", id, candidates.size());
                                }
                                break;
                            default:
                                break;
                        }
                    }
                })
                .exceptionally(ex -> {
                    System.err.println("Exception while streaming entities: " + ex.getMessage());
                    return null;
                })
                .join();
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
    }
}

```

```py title={"Python (REST)"} startLine={113} maxLines={22}
from anduril import (
    AndOperation,
    AsyncLattice,
    Entity,
    EnumType,
    ListType,
    Predicate,
    PredicateSet,
    Statement,
    Value,
)
from typing import NamedTuple, Optional
import asyncio
import os
import sys

lattice_endpoint = os.getenv('LATTICE_ENDPOINT')
environment_token = os.getenv('ENVIRONMENT_TOKEN')

# Remove sandboxes_token from the following statements if you are not developing on Sandboxes.
sandboxes_token = os.getenv('SANDBOXES_TOKEN')
if not environment_token or not lattice_endpoint or not sandboxes_token:
    print("Missing environment variables.")
    sys.exit(1)

client = AsyncLattice(
    base_url=f"https://{lattice_endpoint}",
    token=lambda: str(environment_token),
    # Remove the following header if you are not developing on Sandboxes.
    headers={ "anduril-sandbox-authorization": f"Bearer {sandboxes_token}" }
)


def enum_value(value: int) -> Value:
    """Filters take the integer value of an ontology enum, for example DISPOSITION_HOSTILE is 2."""
    return Value(enum_type=EnumType(value=value))


def threat_filter() -> Statement:
    """Match air tracks that are hostile or suspicious.

    The filter is evaluated continuously: an entity that starts matching arrives
    as CREATED, and one that stops matching arrives as DELETED.
    """
    return Statement(
        and_=AndOperation(
            predicate_set=PredicateSet(
                predicates=[
                    Predicate(
                        field_path="ontology.template",
                        value=enum_value(1),  # TEMPLATE_TRACK
                        comparator="COMPARATOR_EQUALITY",
                    ),
                    Predicate(
                        field_path="mil_view.environment",
                        value=enum_value(1),  # ENVIRONMENT_AIR
                        comparator="COMPARATOR_EQUALITY",
                    ),
                    Predicate(
                        field_path="mil_view.disposition",
                        value=Value(
                            list_type=ListType(
                                values=[
                                    enum_value(2),  # DISPOSITION_HOSTILE
                                    enum_value(3),  # DISPOSITION_SUSPICIOUS
                                ]
                            )
                        ),
                        comparator="COMPARATOR_IN",
                    ),
                ]
            )
        )
    )


class TrackPosition(NamedTuple):
    lat: float
    lon: float
    hae: float


def extract_position(entity: Entity) -> Optional[TrackPosition]:
    """Return the newest position, preferring kinematics over location.

    Kinematics is the recommended source for tracks. Fall back to location if
    the entity has no kinematics. Return None if neither has a position.
    """
    geodetic = entity.kinematics.kinematics_geodetic if entity.kinematics else None
    if geodetic and geodetic.location:
        loc = geodetic.location
        altitude = loc.universal_altitude_hae
        return TrackPosition(
            lat=loc.latitude_degrees or 0.0,
            lon=loc.longitude_degrees or 0.0,
            hae=(altitude.value_meters if altitude else None) or 0.0,
        )
    if entity.location and entity.location.position:
        position = entity.location.position
        return TrackPosition(
            lat=position.latitude_degrees or 0.0,
            lon=position.longitude_degrees or 0.0,
            hae=position.altitude_hae_meters or 0.0,
        )
    return None


async def app():
    # Candidate table: entity ID to last known position.
    candidates: dict[str, TrackPosition] = {}

    try:
        # Stream every entity that matches the threat filter, with all components.
        event_stream = client.entities.stream_entities(filter=threat_filter())
        print("Watching for threat tracks...")
        async for event in event_stream:
            if event.event != "entity" or not event.entity:
                continue
            entity_id = event.entity.entity_id or ""

            if event.event_type in ("EVENT_TYPE_CREATED", "EVENT_TYPE_PREEXISTING", "EVENT_TYPE_UPDATE"):
                position = extract_position(event.entity)
                if not position:
                    continue
                action = "UPDATED" if entity_id in candidates else "ADDED"
                candidates[entity_id] = position
                print(f"{action} {entity_id} lat={position.lat:.6f} lon={position.lon:.6f} "
                      f"hae={position.hae:.1f}m candidates={len(candidates)}")
            elif event.event_type == "EVENT_TYPE_DELETED":
                # The entity expired, was deleted, or no longer matches the filter.
                if candidates.pop(entity_id, None):
                    print(f"REMOVED {entity_id} candidates={len(candidates)}")
    except asyncio.CancelledError:
        print("Streaming cancelled...")
    except Exception as error:
        print(f"Exception: {error}")

if __name__ == "__main__":
    asyncio.run(app())

```

```ts title={"TypeScript (REST)"} startLine={98} maxLines={30}
import { Lattice, LatticeClient } from "@anduril-industries/lattice-sdk";

const latticeEndpoint = process.env.LATTICE_ENDPOINT;
const environmentToken = process.env.ENVIRONMENT_TOKEN;

// Remove sandboxesToken from the following statement if you are not developing on Sandboxes.
const sandboxesToken = process.env.SANDBOXES_TOKEN;
if (!latticeEndpoint || !environmentToken || !sandboxesToken) {
    console.log('Missing required environment variables.');
    process.exit(1);
}

const client = new LatticeClient(
    {
        baseUrl: `https://${latticeEndpoint}`,
        token: environmentToken,
        // Remove the following statement if you are not developing on Sandboxes.
        headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}` }
    }
);

// Filters take the integer value of an ontology enum, for example
// DISPOSITION_HOSTILE is 2.
function enumValue(value: number): Lattice.Value {
    return { enumType: { value } };
}

// Match air tracks that are hostile or suspicious. The filter is evaluated
// continuously: an entity that starts matching arrives as CREATED, and one that
// stops matching arrives as DELETED.
function threatFilter(): Lattice.Statement {
    return {
        and: {
            predicateSet: {
                predicates: [
                    {
                        fieldPath: "ontology.template",
                        value: enumValue(1), // TEMPLATE_TRACK
                        comparator: "COMPARATOR_EQUALITY",
                    },
                    {
                        fieldPath: "mil_view.environment",
                        value: enumValue(1), // ENVIRONMENT_AIR
                        comparator: "COMPARATOR_EQUALITY",
                    },
                    {
                        fieldPath: "mil_view.disposition",
                        value: {
                            listType: {
                                values: [
                                    enumValue(2), // DISPOSITION_HOSTILE
                                    enumValue(3), // DISPOSITION_SUSPICIOUS
                                ],
                            },
                        },
                        comparator: "COMPARATOR_IN",
                    },
                ],
            },
        },
    };
}

interface TrackPosition {
    lat: number;
    lon: number;
    hae: number;
}

// Return the newest position, preferring kinematics over location. Kinematics
// is the recommended source for tracks. Fall back to location if the entity
// has no kinematics. Return undefined if neither has a position.
function extractPosition(entity: Lattice.Entity): TrackPosition | undefined {
    const geodetic = entity.kinematics?.kinematicsGeodetic;
    if (geodetic?.location) {
        return {
            lat: geodetic.location.latitudeDegrees ?? 0,
            lon: geodetic.location.longitudeDegrees ?? 0,
            hae: geodetic.location.universalAltitudeHae?.valueMeters ?? 0,
        };
    }
    const position = entity.location?.position;
    if (position) {
        return {
            lat: position.latitudeDegrees ?? 0,
            lon: position.longitudeDegrees ?? 0,
            hae: position.altitudeHaeMeters ?? 0,
        };
    }
    return undefined;
}

async function App() {
    // Candidate table: entity ID to last known position.
    const candidates = new Map<string, TrackPosition>();

    try {
        // Stream every entity that matches the threat filter, with all components.
        const eventStream = await client.entities.streamEntities({ filter: threatFilter() });
        console.log("Watching for threat tracks...");

        for await (const event of eventStream) {
            if (event.event !== "entity" || !event.entity) {
                continue;
            }
            const entity = event.entity;
            const id = entity.entityId ?? "";

            switch (event.eventType) {
                case "EVENT_TYPE_CREATED":
                case "EVENT_TYPE_PREEXISTING":
                case "EVENT_TYPE_UPDATE": {
                    const position = extractPosition(entity);
                    if (!position) {
                        break;
                    }
                    const action = candidates.has(id) ? "UPDATED" : "ADDED";
                    candidates.set(id, position);
                    console.log(`${action} ${id} lat=${position.lat.toFixed(6)} lon=${position.lon.toFixed(6)} hae=${position.hae.toFixed(1)}m candidates=${candidates.size}`);
                    break;
                }
                case "EVENT_TYPE_DELETED":
                    // The entity expired, was deleted, or no longer matches the filter.
                    if (candidates.delete(id)) {
                        console.log(`REMOVED ${id} candidates=${candidates.size}`);
                    }
                    break;
            }
        }
    } catch (error) {
        console.log(`Exception while streaming entities: ${error}`);
    }
}

App();

```

```rs title={"Rust (REST)"} startLine={115} maxLines={51}
use anduril_lattice_sdk::prelude::*;

use std::env;

/// Builds an enum filter value. Filters take the integer value of an ontology
/// enum, for example DISPOSITION_HOSTILE is 2.
fn enum_value(value: i64) -> Value {
    json!({ "enumType": { "value": value } })
}

/// Matches air tracks that are hostile or suspicious. The filter is evaluated
/// continuously: an entity that starts matching arrives as CREATED, and one that
/// stops matching arrives as DELETED.
fn threat_filter() -> Statement {
    let predicates = vec![
        Predicate {
            field_path: Some("ontology.template".to_string()),
            value: Some(enum_value(1)), // TEMPLATE_TRACK
            comparator: Some(PredicateComparator::ComparatorEquality),
        },
        Predicate {
            field_path: Some("mil_view.environment".to_string()),
            value: Some(enum_value(1)), // ENVIRONMENT_AIR
            comparator: Some(PredicateComparator::ComparatorEquality),
        },
        Predicate {
            field_path: Some("mil_view.disposition".to_string()),
            value: Some(json!({ "listType": { "values": [
                enum_value(2), // DISPOSITION_HOSTILE
                enum_value(3), // DISPOSITION_SUSPICIOUS
            ] } })),
            comparator: Some(PredicateComparator::ComparatorIn),
        },
    ];
    Statement {
        and: Some(Box::new(AndOperation {
            predicate_set: Some(PredicateSet {
                predicates: Some(predicates),
            }),
            ..Default::default()
        })),
        ..Default::default()
    }
}

/// The newest position of a track.
#[derive(Clone, Copy)]
struct TrackPosition {
    lat: f64,
    lon: f64,
    hae: f64,
}

/// Returns the newest position, preferring kinematics over location. Kinematics
/// is the recommended source for tracks. Falls back to location if the entity
/// has no kinematics. Returns None if neither has a position.
fn extract_position(entity: &Entity) -> Option<TrackPosition> {
    if let Some(geodetic) = entity
        .kinematics
        .as_ref()
        .and_then(|k| k.kinematics_geodetic.as_ref())
    {
        if let Some(loc) = &geodetic.location {
            return Some(TrackPosition {
                lat: loc.latitude_degrees.unwrap_or(0.0),
                lon: loc.longitude_degrees.unwrap_or(0.0),
                hae: loc
                    .universal_altitude_hae
                    .as_ref()
                    .and_then(|a| a.value_meters)
                    .unwrap_or(0.0),
            });
        }
    }
    let location = entity.location.as_ref()?;
    let position = location.position.as_ref()?;
    Some(TrackPosition {
        lat: position.latitude_degrees.unwrap_or(0.0),
        lon: position.longitude_degrees.unwrap_or(0.0),
        hae: position.altitude_hae_meters.unwrap_or(0.0),
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    // Remove sandboxes_token if you are not developing on Sandboxes.
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables:");
        eprintln!("  LATTICE_ENDPOINT");
        eprintln!("  ENVIRONMENT_TOKEN");
        eprintln!("  SANDBOXES_TOKEN");
        std::process::exit(1);
    }

    let config = ClientConfig {
        base_url: format!("https://{}", lattice_endpoint),
        token: Some(environment_token),
        // Remove custom_headers if you are not developing on Sandboxes.
        custom_headers: HashMap::from([(
            "anduril-sandbox-authorization".to_string(),
            format!("Bearer {}", sandboxes_token),
        )]),
        ..Default::default()
    };
    let client = Lattice::new(config)?;

    // Stream every entity that matches the threat filter, with all components.
    let request = EntityStreamRequest {
        filter: Some(threat_filter()),
        ..Default::default()
    };
    let stream = client.entities.stream_entities(&request, None).await?;
    let mut stream = std::pin::pin!(stream);

    // Candidate table: entity ID to last known position.
    let mut candidates: HashMap<String, TrackPosition> = HashMap::new();
    println!("Watching for threat tracks...");

    while let Some(result) = stream.next().await {
        let event = match result {
            Ok(event) => event,
            Err(error) => {
                eprintln!("Exception: {}", error);
                continue;
            }
        };
        let StreamEntitiesResponse::Entity { data, .. } = event else {
            continue;
        };
        let event = data.entity_event_fields;
        let Some(entity) = &event.entity else { continue };
        let id = entity.entity_id.clone().unwrap_or_default();

        match event.event_type {
            Some(
                EntityEventEventType::EventTypeCreated
                | EntityEventEventType::EventTypePreexisting
                | EntityEventEventType::EventTypeUpdate,
            ) => {
                let Some(position) = extract_position(entity) else { continue };
                let is_new = candidates.insert(id.clone(), position).is_none();
                println!(
                    "{} {} lat={:.6} lon={:.6} hae={:.1}m candidates={}",
                    if is_new { "ADDED" } else { "UPDATED" },
                    id,
                    position.lat,
                    position.lon,
                    position.hae,
                    candidates.len()
                );
            }
            Some(EntityEventEventType::EventTypeDeleted) => {
                // The entity expired, was deleted, or no longer matches the filter.
                let was_known = candidates.remove(&id).is_some();
                if was_known {
                    println!("REMOVED {} candidates={}", id, candidates.len());
                }
            }
            _ => {}
        }
    }

    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={120} maxLines={53}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
package main

import (
	"context"
	"io"
	"log"
	"os"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

// enumPredicate builds an EQUALITY predicate on an ontology enum. Filters take
// the integer value of the enum.
func enumPredicate(fieldPath string, value int32) *entitymanagerv1.Predicate {
	return &entitymanagerv1.Predicate{
		FieldPath: fieldPath,
		Value: &entitymanagerv1.Value{
			Type: &entitymanagerv1.Value_EnumType{
				EnumType: &entitymanagerv1.EnumType{Value: value},
			},
		},
		Comparator: entitymanagerv1.Comparator_COMPARATOR_EQUALITY,
	}
}

// threatFilter matches air tracks that are hostile or suspicious. The filter is
// evaluated continuously: an entity that starts matching arrives as CREATED, and
// one that stops matching arrives as DELETED.
func threatFilter() *entitymanagerv1.Statement {
	dispositions := []*entitymanagerv1.Value{
		{Type: &entitymanagerv1.Value_EnumType{EnumType: &entitymanagerv1.EnumType{Value: 2}}}, // DISPOSITION_HOSTILE
		{Type: &entitymanagerv1.Value_EnumType{EnumType: &entitymanagerv1.EnumType{Value: 3}}}, // DISPOSITION_SUSPICIOUS
	}
	return &entitymanagerv1.Statement{
		Operation: &entitymanagerv1.Statement_And{
			And: &entitymanagerv1.AndOperation{
				Children: &entitymanagerv1.AndOperation_PredicateSet{
					PredicateSet: &entitymanagerv1.PredicateSet{
						Predicates: []*entitymanagerv1.Predicate{
							enumPredicate("ontology.template", int32(entitymanagerv1.Template_TEMPLATE_TRACK)),
							enumPredicate("mil_view.environment", 1), // ENVIRONMENT_AIR
							{
								FieldPath: "mil_view.disposition",
								Value: &entitymanagerv1.Value{
									Type: &entitymanagerv1.Value_ListType{
										ListType: &entitymanagerv1.ListType{Values: dispositions},
									},
								},
								Comparator: entitymanagerv1.Comparator_COMPARATOR_IN,
							},
						},
					},
				},
			},
		},
	}
}

// trackPosition is the newest position of a track.
type trackPosition struct {
	lat, lon, hae float64
}

// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *entitymanagerv1.Entity) *trackPosition {
	if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic.GetLocation() != nil {
		loc := geodetic.GetLocation()
		pos := &trackPosition{
			lat: loc.GetLatitudeDegrees(),
			lon: loc.GetLongitudeDegrees(),
			hae: loc.GetUniversalAltitudeHae().GetValueMeters(),
		}
		return pos
	}
	if loc := entity.GetLocation(); loc.GetPosition() != nil {
		position := loc.GetPosition()
		pos := &trackPosition{
			lat: position.GetLatitudeDegrees(),
			lon: position.GetLongitudeDegrees(),
			hae: position.GetAltitudeHaeMeters().GetValue(),
		}
		return pos
	}
	return nil
}

func main() {
	ctx := context.Background()

	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatalf("Missing required environment variables")
	}
	auth := &BearerTokenAuth{
		Token:          environmentToken,
		SandboxesToken: sandboxesToken,
	}

	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}
	conn, err := grpc.NewClient(latticeEndpoint, opts...)
	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	// Stream every entity that matches the threat filter, with all components.
	stream, err := client.StreamEntityComponents(ctx, &entitymanagerv1.StreamEntityComponentsRequest{
		Filter:               threatFilter(),
		IncludeAllComponents: true,
	})
	if err != nil {
		log.Fatalf("Error creating stream: %v", err)
	}

	// Candidate table: entity ID to last known position.
	candidates := map[string]trackPosition{}
	log.Println("Watching for threat tracks...")

	for {
		response, err := stream.Recv()
		if err == io.EOF {
			log.Println("Stream completed successfully.")
			return
		}
		if err != nil {
			log.Fatalf("Error receiving stream data: %v", err)
		}

		// Heartbeats carry no entity event.
		event := response.GetEntityEvent()
		entity := event.GetEntity()
		if entity == nil {
			continue
		}
		id := entity.GetEntityId()

		switch event.GetEventType() {
		case entitymanagerv1.EventType_EVENT_TYPE_CREATED,
			entitymanagerv1.EventType_EVENT_TYPE_PREEXISTING,
			entitymanagerv1.EventType_EVENT_TYPE_UPDATE:
			pos := extractPosition(entity)
			if pos == nil {
				continue
			}
			action := "UPDATED"
			if _, known := candidates[id]; !known {
				action = "ADDED"
			}
			candidates[id] = *pos
			log.Printf("%s %s lat=%.6f lon=%.6f hae=%.1fm candidates=%d",
				action, id, pos.lat, pos.lon, pos.hae, len(candidates))
		case entitymanagerv1.EventType_EVENT_TYPE_DELETED:
			// The entity expired, was deleted, or no longer matches the filter.
			if _, known := candidates[id]; known {
				delete(candidates, id)
				log.Printf("REMOVED %s candidates=%d", id, len(candidates))
			}
		}
	}
}

```

```py title={"Python (gRPC)"} startLine={128} maxLines={40}
# This Python example is compatible with artifacts generated using the following
# Buf plugins: https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:bufbuild/py
# and https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:connectrpc/py

import os
import sys
from typing import NamedTuple, Optional

from bearer_auth import create_client
from protobuf import Oneof

from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.entity_manager_api_pub_pb import (
    EventType,
    StreamEntityComponentsRequest,
)
from anduril.entitymanager.v1.entity_pub_pb import Entity
from anduril.entitymanager.v1.filter_pub_pb import (
    AndOperation,
    Comparator,
    EnumType,
    ListType,
    Predicate,
    PredicateSet,
    Statement,
    Value,
)
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.ontology.v1.type_pub_pb import Disposition, Environment


def enum_value(value: int) -> Value:
    """Filters take the integer value of an ontology enum."""
    return Value(type=Oneof("enum_type", EnumType(value=value)))


def threat_filter() -> Statement:
    """Match air tracks that are hostile or suspicious.

    The filter is evaluated continuously: an entity that starts matching arrives
    as CREATED, and one that stops matching arrives as DELETED.
    """
    return Statement(
        operation=Oneof(
            "and",
            AndOperation(
                children=Oneof(
                    "predicate_set",
                    PredicateSet(
                        predicates=[
                            Predicate(
                                field_path="ontology.template",
                                value=enum_value(Template.TRACK.value),
                                comparator=Comparator.EQUALITY,
                            ),
                            Predicate(
                                field_path="mil_view.environment",
                                value=enum_value(Environment.AIR.value),
                                comparator=Comparator.EQUALITY,
                            ),
                            Predicate(
                                field_path="mil_view.disposition",
                                value=Value(
                                    type=Oneof(
                                        "list_type",
                                        ListType(
                                            values=[
                                                enum_value(Disposition.HOSTILE.value),
                                                enum_value(Disposition.SUSPICIOUS.value),
                                            ]
                                        ),
                                    )
                                ),
                                comparator=Comparator.IN,
                            ),
                        ]
                    ),
                )
            ),
        )
    )


class TrackPosition(NamedTuple):
    lat: float
    lon: float
    hae: float


def extract_position(entity: Entity) -> Optional[TrackPosition]:
    """Return the newest position, preferring kinematics over location.

    Kinematics is the recommended source for tracks. Fall back to location if
    the entity has no kinematics. Return None if neither has a position.
    """
    if entity.has_field("kinematics") and entity.kinematics.has_field("kinematics_geodetic"):
        geodetic = entity.kinematics.kinematics_geodetic
        if geodetic.has_field("location"):
            loc = geodetic.location
            return TrackPosition(
                lat=loc.latitude_degrees,
                lon=loc.longitude_degrees,
                hae=loc.universal_altitude_hae.value_meters,
            )
    if entity.has_field("location") and entity.location.has_field("position"):
        position = entity.location.position
        return TrackPosition(
            lat=position.latitude_degrees,
            lon=position.longitude_degrees,
            hae=position.altitude_hae_meters.value if position.has_field("altitude_hae_meters") else 0.0,
        )
    return None


def main():
    environment_token = os.getenv("ENVIRONMENT_TOKEN")
    lattice_endpoint = os.getenv("LATTICE_ENDPOINT")
    sandboxes_token = os.getenv("SANDBOXES_TOKEN")

    if not environment_token or not lattice_endpoint or not sandboxes_token:
        print("Missing required environment variables", file=sys.stderr)
        sys.exit(1)

    # Create the API client over Connect gRPC with authentication
    client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    # Stream every entity that matches the threat filter, with all components.
    request = StreamEntityComponentsRequest(
        filter=threat_filter(),
        include_all_components=True,
    )

    try:
        stream = client.stream_entity_components(request)
    except Exception as error:
        print(f"Error creating stream: {error}", file=sys.stderr)
        sys.exit(1)

    # Candidate table: entity ID to last known position.
    candidates: dict[str, TrackPosition] = {}
    print("Watching for threat tracks...")

    try:
        for response in stream:
            # Heartbeat messages carry no entity_event, so skip them.
            if not response.has_field("entity_event"):
                continue
            event = response.entity_event
            entity = event.entity
            if not entity:
                continue
            entity_id = entity.entity_id

            if event.event_type in (EventType.CREATED, EventType.PREEXISTING, EventType.UPDATE):
                position = extract_position(entity)
                if not position:
                    continue
                action = "UPDATED" if entity_id in candidates else "ADDED"
                candidates[entity_id] = position
                print(f"{action} {entity_id} lat={position.lat:.6f} lon={position.lon:.6f} "
                      f"hae={position.hae:.1f}m candidates={len(candidates)}")
            elif event.event_type == EventType.DELETED:
                # The entity expired, was deleted, or no longer matches the filter.
                if candidates.pop(entity_id, None):
                    print(f"REMOVED {entity_id} candidates={len(candidates)}")
        print("End of stream reached.")
    except Exception as error:
        print(f"Error receiving stream data: {error}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={145} maxLines={39}
// This Rust example is compatible with artifacts generated using
// the following grpc/rust plugin: https://buf.build/anduril/lattice-sdk/sdks/main:community/neoeinstein-tonic
mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    and_operation, statement, value, AndOperation, Comparator, Entity, EnumType, EventType,
    ListType, Predicate, PredicateSet, Statement, StreamEntityComponentsRequest, Template, Value,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{
    Disposition, Environment,
};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use tonic::metadata::MetadataValue;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::Request;

use std::collections::HashMap;
use std::env;

/// The newest position of a track.
#[derive(Clone, Copy)]
struct TrackPosition {
    lat: f64,
    lon: f64,
    hae: f64,
}

/// Builds an enum filter value. Filters take the integer value of an ontology enum.
fn enum_value(value: i32) -> Value {
    Value {
        r#type: Some(value::Type::EnumType(EnumType { value })),
    }
}

/// Builds an EQUALITY predicate on an enum field.
fn enum_equals(field_path: &str, value: i32) -> Predicate {
    Predicate {
        field_path: field_path.to_string(),
        value: Some(enum_value(value)),
        comparator: Comparator::Equality as i32,
    }
}

/// Matches air tracks that are hostile or suspicious. The filter is evaluated
/// continuously: an entity that starts matching arrives as CREATED, and one that
/// stops matching arrives as DELETED.
fn threat_filter() -> Statement {
    let disposition_in = Predicate {
        field_path: "mil_view.disposition".to_string(),
        value: Some(Value {
            r#type: Some(value::Type::ListType(ListType {
                values: vec![
                    enum_value(Disposition::Hostile as i32),
                    enum_value(Disposition::Suspicious as i32),
                ],
            })),
        }),
        comparator: Comparator::In as i32,
    };
    Statement {
        operation: Some(statement::Operation::And(AndOperation {
            children: Some(and_operation::Children::PredicateSet(PredicateSet {
                predicates: vec![
                    enum_equals("ontology.template", Template::Track as i32),
                    enum_equals("mil_view.environment", Environment::Air as i32),
                    disposition_in,
                ],
            })),
        })),
    }
}

/// Returns the newest position, preferring kinematics over location. Kinematics
/// is the recommended source for tracks. Falls back to location if the entity
/// has no kinematics. Returns None if neither has a position.
fn extract_position(entity: &Entity) -> Option<TrackPosition> {
    if let Some(geodetic) = entity
        .kinematics
        .as_ref()
        .and_then(|k| k.kinematics_geodetic.as_ref())
    {
        if let Some(loc) = &geodetic.location {
            return Some(TrackPosition {
                lat: loc.latitude_degrees,
                lon: loc.longitude_degrees,
                hae: loc
                    .universal_altitude_hae
                    .as_ref()
                    .map_or(0.0, |a| a.value_meters),
            });
        }
    }
    let location = entity.location.as_ref()?;
    let position = location.position.as_ref()?;
    Some(TrackPosition {
        lat: position.latitude_degrees,
        lon: position.longitude_degrees,
        hae: position.altitude_hae_meters.unwrap_or(0.0),
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load environment variables
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    // Set up authentication handler
    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

    // Create gRPC channel with TLS
    let tls_config = ClientTlsConfig::new().with_native_roots();
    let channel = Channel::from_shared(format!("https://{}", lattice_endpoint))?
        .tls_config(tls_config)?
        .connect()
        .await?;

    // Fetch a fresh access token and build metadata values
    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<_> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<_> = format!("Bearer {}", sandboxes_token).parse()?;

    // Create EntityManager API client with authentication interceptor
    let mut client = EntityManagerApiClient::with_interceptor(
        channel,
        move |mut req: Request<()>| {
            req.metadata_mut()
                .insert("authorization", auth_header.clone());
            req.metadata_mut()
                .insert("anduril-sandbox-authorization", sandbox_header.clone());
            Ok(req)
        },
    );

    // Stream every entity that matches the threat filter, with all components.
    let request = Request::new(StreamEntityComponentsRequest {
        filter: Some(threat_filter()),
        include_all_components: true,
        ..Default::default()
    });

    let mut stream = client.stream_entity_components(request).await?.into_inner();

    // Candidate table: entity ID to last known position.
    let mut candidates: HashMap<String, TrackPosition> = HashMap::new();
    println!("Watching for threat tracks...");

    while let Some(response) = stream.message().await? {
        // Heartbeat messages carry no entity_event, so skip them.
        let Some(event) = response.entity_event else { continue };
        let Some(entity) = &event.entity else { continue };
        let id = entity.entity_id.clone();

        match EventType::try_from(event.event_type) {
            Ok(EventType::Created | EventType::Preexisting | EventType::Update) => {
                let Some(position) = extract_position(entity) else { continue };
                let is_new = candidates.insert(id.clone(), position).is_none();
                println!(
                    "{} {} lat={:.6} lon={:.6} hae={:.1}m candidates={}",
                    if is_new { "ADDED" } else { "UPDATED" },
                    id,
                    position.lat,
                    position.lon,
                    position.hae,
                    candidates.len()
                );
            }
            Ok(EventType::Deleted) => {
                // The entity expired, was deleted, or no longer matches the filter.
                let was_known = candidates.remove(&id).is_some();
                if was_known {
                    println!("REMOVED {} candidates={}", id, candidates.len());
                }
            }
            _ => {}
        }
    }
    println!("End of stream reached");

    Ok(())
}

```

If successful, you see the candidate list change as threat tracks appear and disappear:

```bash maxLines=3
ADDED 2f6a0d1c-4b7e-4c3a-9d55-1e8f0a7b9c21 lat=34.045000 lon=-117.990000 hae=512.1m candidates=1
UPDATED 2f6a0d1c-4b7e-4c3a-9d55-1e8f0a7b9c21 lat=34.044715 lon=-117.989957 hae=500.4m candidates=1
REMOVED 2f6a0d1c-4b7e-4c3a-9d55-1e8f0a7b9c21 candidates=0
```

## Best practices

* **Reconnect automatically**: Streams can drop on unreliable networks. Reopen the stream with backoff, and expect `EVENT_TYPE_PREEXISTING` events for the current state after you reconnect. For more information, see [Retry connections](/guides/best-practices/retry-connections).
* **Extrapolate between updates**: Updates arrive at the rate that sensors detect the target. Between updates, project the last position forward along its velocity, using the age of the measurement.
* **Filter on the server**: Send a `filter` instead of discarding unwanted entities in your code. Server-side filters reduce bandwidth, which matters on tactical networks.

## What's next?

* Learn more about the Entities API in [REST](/reference/rest/entities/stream-entities) and [gRPC](/reference/grpc/anduril-entitymanager-v-1/entity-manager-api/anduril-entitymanager-v-1-stream-entity-components).
* Learn how effectors receive cues as tasks in [Integrate an agent](/guides/tasks/integrate-an-agent).
* Choose between REST and gRPC for streaming in [Choose a protocol](/guides/best-practices/choose-a-protocol).