> 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.

# Handle restarts

> Pick up where your integration left off after a restart or a lost connection.

Integrations at the edge restart often: a vehicle powers down, a process crashes, a new version rolls out.
Lattice can't tell a planned shutdown from a failure, so everything your integration created stays as it was:

* **Entities** stay until their `expiry_time` passes.
* **Tasks** stay in their last reported status. Lattice doesn't close a task your agent has started.
* **Video ingress streams** stay, and show `STREAM_STATUS_INACTIVE` once frames stop arriving.

An integration that starts over with new IDs leaves operators with duplicate assets, tasks stuck in `STATUS_EXECUTING`, and several feeds for one camera.
To avoid that, make sure your integration can find everything it owns after a restart, and reconcile it with Lattice before it resumes work.

## Before you begin

* Complete the steps in [Set up](/guides/getting-started/set-up) to configure your environment and install the SDK.
* Review the lifecycle of [entities](/guides/entities/overview#entity-lifecycle), [tasks](/guides/tasks/integrate-an-agent), and [video streams](/guides/video/manage-streams).

## Decide which IDs to keep

You can only reconcile a resource if you know its ID after the restart.
If you choose the ID, derive it from something that never changes for the asset, such as a serial number, so there's nothing to save.
If someone else chooses it, save it as soon as you receive it.

| Resource                      | ID           | Chosen by                                   | Approach                                                                    |
| ----------------------------- | ------------ | ------------------------------------------- | --------------------------------------------------------------------------- |
| Entity                        | `entity_id`  | Your integration                            | Derive it.                                                                  |
| Video ingress stream          | `ingress_id` | Your integration, or Lattice if you omit it | Derive it and pass it to `CreateIngressStream`. Keep it to 4–36 characters. |
| Task your agent executes      | `task_id`    | The task's creator                          | Save it when your agent starts the task.                                    |
| Task your integration creates | `task_id`    | Your integration, or Lattice if you omit it | Save it when you create the task.                                           |

Each step in [Recover on startup](#recover-on-startup) starts with its ID: how the example derives the ingress and entity IDs from one asset name, and how it saves task IDs.

## Recover on startup

Run these steps once at startup, before your publish loop or agent stream starts.
Recovery makes several calls in a row, often while the network is still coming up, so wrap them in a [retry utility](/guides/best-practices/retry-connections).
The code samples are excerpts from one script.

#### Reconnect your video stream

Derive the ingress ID from the asset name. The readable `<group>.<name>` pattern is the one Lattice recommends:

```go title={"Go (REST)"} startLine={24} maxLines={7}
// This Go example uses the Lattice REST SDK (lattice-sdk-go) to recover an integration's video
// stream, entity, and tasks after the integration restarts.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"maps"
	"net/http"
	"os"
	"path/filepath"
	"slices"
	"time"

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

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"

// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"

// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()

const (
	// RTSP source that Lattice pulls video from. Replace before running.
	rtspURL = "rtsp://<rtsp-host>:<port>/cam"
	// Local file that stores the IDs of tasks this agent is executing.
	stateFile = "agent_state.json"
)

var terminalStatuses = map[Lattice.TaskStatusStatus]bool{
	Lattice.TaskStatusStatusStatusDoneOk:    true,
	Lattice.TaskStatusStatusStatusDoneNotOk: true,
}

type agentState struct {
	TaskIDs []string `json:"task_ids"`
}

func loadTaskIDs() (map[string]bool, error) {
	taskIDs := map[string]bool{}
	data, err := os.ReadFile(stateFile)
	if errors.Is(err, os.ErrNotExist) {
		return taskIDs, nil
	}
	if err != nil {
		return nil, err
	}
	var state agentState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	for _, taskID := range state.TaskIDs {
		taskIDs[taskID] = true
	}
	return taskIDs, nil
}

func saveTaskIDs(taskIDs map[string]bool) error {
	ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
	slices.Sort(ids)
	data, err := json.Marshal(agentState{TaskIDs: ids})
	if err != nil {
		return err
	}
	// Write to a temporary file, then rename it over the original. A power loss during the
	// write leaves the previous file intact instead of a truncated one.
	f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	if _, err := f.Write(data); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), stateFile)
}

// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
	taskIDs[taskID] = true
	return saveTaskIDs(taskIDs)
}

// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
	delete(taskIDs, taskID)
	return saveTaskIDs(taskIDs)
}

func reconnectVideo(ctx context.Context, client *client.Client) error {
	response, err := client.Video.GetIngressStream(ctx, &Lattice.GetIngressStreamRequest{
		IngressID: ingressID,
	})
	var apiErr *core.APIError
	if err == nil {
		// The stream survived the restart. Reuse it instead of creating a duplicate.
		status := ""
		if s := response.GetIngressStream().GetStatus(); s != nil {
			status = string(*s)
		}
		fmt.Printf("Reusing stream %s with status %s\n", ingressID, status)
		return nil
	}
	if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
		return err
	}

	// Lattice returns not found both for a stream that never existed and for one that was deleted.
	_, err = client.Video.CreateIngressStream(ctx, &Lattice.CreateIngressStreamRequest{
		IngressID: Lattice.String(ingressID),
		Title:     Lattice.String(assetName),
		Rtsp: &Lattice.RtspSettings{
			URL: Lattice.String(rtspURL),
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Created stream %s\n", ingressID)
	return nil
}

func publishEntity(ctx context.Context, client *client.Client) error {
	now := time.Now().UTC()
	_, err := client.Entities.PublishEntity(ctx, &Lattice.Entity{
		EntityID:   Lattice.String(entityID),
		IsLive:     Lattice.Bool(true),
		ExpiryTime: Lattice.Time(now.Add(5 * time.Minute)),
		Aliases:    &Lattice.Aliases{Name: Lattice.String(assetName)},
		MilView: &Lattice.MilView{
			Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
			Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
		},
		Ontology: &Lattice.Ontology{
			Template:     Lattice.OntologyTemplateTemplateAsset.Ptr(),
			PlatformType: Lattice.String("CAMERA"),
		},
		Location: &Lattice.Location{
			Position: &Lattice.Position{
				LatitudeDegrees:  Lattice.Float64(33.6411),
				LongitudeDegrees: Lattice.Float64(-117.9187),
			},
		},
		// Because ingressID never changes, the entity can reference the stream on every publish.
		Media: &Lattice.Media{Media: []*Lattice.MediaItem{{
			ItemIdentifier: Lattice.String(ingressID),
			Type:           Lattice.MediaItemTypeMediaTypeVideo.Ptr(),
		}}},
		// Include every other component your integration publishes, such as its TaskCatalog.
		Provenance: &Lattice.Provenance{
			IntegrationName:  Lattice.String("my-integration"),
			DataType:         Lattice.String("asset"),
			SourceUpdateTime: Lattice.Time(now),
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Republished entity %s\n", entityID)
	return nil
}

func resolveTrackedTasks(ctx context.Context, client *client.Client, taskIDs map[string]bool) error {
	author := &Lattice.Principal{System: &Lattice.System{EntityID: Lattice.String(entityID)}}
	for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
		task, err := client.Tasks.GetTask(ctx, &Lattice.GetTaskRequest{TaskID: taskID})
		var apiErr *core.APIError
		if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
			// The task no longer exists in Lattice, so there's nothing to resolve.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
		if task.Status == nil || task.Status.Status == nil || task.Version == nil || task.Version.StatusVersion == nil {
			fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
			continue
		}

		status := *task.Status.Status
		if terminalStatuses[status] {
			// An operator or another system closed the task while the agent was offline.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}

		var taskError *Lattice.TaskError
		cancelled := status == Lattice.TaskStatusStatusStatusCancelRequested ||
			(task.GetDeliveryState().GetStatus() != nil &&
				*task.GetDeliveryState().GetStatus() == Lattice.DeliveryStateStatusDeliveryStatusPendingCancel)
		if cancelled {
			// An operator cancelled the task while the agent was offline. Lattice records the cancel
			// in delivery_state, not in the task status. Accept the cancellation.
			taskError = &Lattice.TaskError{
				Code:    Lattice.TaskErrorCodeErrorCodeCancelled.Ptr(),
				Message: Lattice.String("Cancelled while the agent was offline."),
			}
		} else {
			// The agent lost its execution context, so report the task as failed rather than
			// leave it active with nothing working on it.
			taskError = &Lattice.TaskError{
				Code:    Lattice.TaskErrorCodeErrorCodeFailed.Ptr(),
				Message: Lattice.String("Agent restarted and could not resume the task."),
			}
		}

		// Read the status version from GetTask, not from local state: the status might have
		// changed while the agent was offline, and Lattice ignores updates with a stale version.
		statusVersion := *task.Version.StatusVersion + 1
		_, err = client.Tasks.UpdateTaskStatus(ctx, &Lattice.TaskStatusUpdate{
			TaskID:        taskID,
			StatusVersion: &statusVersion,
			NewStatus: &Lattice.TaskStatus{
				Status:    Lattice.TaskStatusStatusStatusDoneNotOk.Ptr(),
				TaskError: taskError,
			},
			Author: author,
		})
		if err != nil {
			return err
		}
		fmt.Printf("Closed task %s with %s\n", taskID, *taskError.Code)
		if err := untrackTask(taskIDs, taskID); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	// Get environment variables
	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")

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

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

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

	ctx := context.Background()

	taskIDs, err := loadTaskIDs()
	if err != nil {
		fmt.Printf("Failed to load saved task IDs: %v\n", err)
		os.Exit(1)
	}
	if err := reconnectVideo(ctx, LatticeClient); err != nil {
		fmt.Printf("Failed to reconnect video: %v\n", err)
		os.Exit(1)
	}
	if err := publishEntity(ctx, LatticeClient); err != nil {
		fmt.Printf("Failed to republish entity: %v\n", err)
		os.Exit(1)
	}
	if err := resolveTrackedTasks(ctx, LatticeClient, taskIDs); err != nil {
		fmt.Printf("Failed to resolve tracked tasks: %v\n", err)
		os.Exit(1)
	}

	// Recovery is complete. Start your regular publish loop and agent stream here, and call
	// trackTask and untrackTask as tasks start and finish.
}

```

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

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.core.LatticeApiException;
import com.anduril.resources.tasks.requests.TaskStatusUpdate;
import com.anduril.resources.video.requests.CreateIngressStreamRequest;
import com.anduril.types.Aliases;
import com.anduril.types.DeliveryState;
import com.anduril.types.DeliveryStateStatus;
import com.anduril.types.Entity;
import com.anduril.types.Location;
import com.anduril.types.Media;
import com.anduril.types.MediaItem;
import com.anduril.types.MediaItemType;
import com.anduril.types.MilView;
import com.anduril.types.MilViewDisposition;
import com.anduril.types.MilViewEnvironment;
import com.anduril.types.Ontology;
import com.anduril.types.OntologyTemplate;
import com.anduril.types.Position;
import com.anduril.types.Principal;
import com.anduril.types.Provenance;
import com.anduril.types.RtspSettings;
import com.anduril.types.Task;
import com.anduril.types.TaskError;
import com.anduril.types.TaskErrorCode;
import com.anduril.types.TaskStatus;
import com.anduril.types.TaskStatusStatus;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * Recovers an integration's video stream, entity, and tasks with the Lattice SDK after the
 * integration restarts.
 */
public class HandleRestarts {
    // A name that is unique to this asset and never changes, such as a serial number read from
    // hardware or configuration. Replace before running.
    private static final String ASSET_NAME = "<ASSET-NAME>";
    // The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
    // so it's the same after every restart.
    private static final String INGRESS_ID = ASSET_NAME + ".cam";
    // The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
    // and in every language.
    // NAMESPACE_URL is the standard RFC 9562 URL namespace.
    private static final UUID NAMESPACE_URL = UUID.fromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8");
    private static final String ENTITY_ID = uuid5(NAMESPACE_URL, "urn:my-integration:" + ASSET_NAME).toString();
    // RTSP source that Lattice pulls video from. Replace before running.
    private static final String RTSP_URL = "rtsp://<rtsp-host>:<port>/cam";
    // Local file that stores the IDs of tasks this agent is executing.
    private static final Path STATE_FILE = Path.of("agent_state.json");

    private static final List<TaskStatusStatus> TERMINAL_STATUSES =
        List.of(TaskStatusStatus.STATUS_DONE_OK, TaskStatusStatus.STATUS_DONE_NOT_OK);

    private static final ObjectMapper JSON = new ObjectMapper();

    private static Set<String> loadTaskIds() throws IOException {
        Set<String> taskIds = new HashSet<>();
        if (!Files.exists(STATE_FILE)) {
            return taskIds;
        }
        for (JsonNode taskId : JSON.readTree(STATE_FILE.toFile()).path("task_ids")) {
            taskIds.add(taskId.asText());
        }
        return taskIds;
    }

    private static void saveTaskIds(Set<String> taskIds) throws IOException {
        // Write to a temporary file, then rename it over the original. A power loss during the
        // write leaves the previous file intact instead of a truncated one.
        Path target = STATE_FILE.toAbsolutePath();
        Path temp = Files.createTempFile(target.getParent(), "agent_state", ".tmp");
        ObjectNode state = JSON.createObjectNode();
        ArrayNode ids = state.putArray("task_ids");
        for (String taskId : new TreeSet<>(taskIds)) {
            ids.add(taskId);
        }
        try (FileChannel channel = FileChannel.open(temp, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(JSON.writeValueAsBytes(state)));
            channel.force(true);
        }
        Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE);
    }

    private static void trackTask(Set<String> taskIds, String taskId) throws IOException {
        // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
        taskIds.add(taskId);
        saveTaskIds(taskIds);
    }

    private static void untrackTask(Set<String> taskIds, String taskId) throws IOException {
        // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
        taskIds.remove(taskId);
        saveTaskIds(taskIds);
    }

    private static void reconnectVideo(Lattice client) {
        try {
            String status = client.video().getIngressStream(INGRESS_ID).getIngressStream()
                .flatMap(stream -> stream.getStatus()).map(Object::toString).orElse("");
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            System.out.println("Reusing stream " + INGRESS_ID + " with status " + status);
            return;
        } catch (LatticeApiException e) {
            if (e.statusCode() != 404) {
                throw e;
            }
        }

        // Lattice returns not found both for a stream that never existed and for one that was deleted.
        client.video().createIngressStream(CreateIngressStreamRequest.builder()
            .ingressId(INGRESS_ID)
            .title(ASSET_NAME)
            .rtsp(RtspSettings.builder()
                .url(RTSP_URL)
                .build())
            .build());
        System.out.println("Created stream " + INGRESS_ID);
    }

    private static void publishEntity(Lattice client) {
        OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
        client.entities().publishEntity(Entity.builder()
            .entityId(ENTITY_ID)
            .isLive(true)
            .expiryTime(now.plusMinutes(5))
            .aliases(Aliases.builder().name(ASSET_NAME).build())
            .milView(MilView.builder()
                .disposition(MilViewDisposition.DISPOSITION_FRIENDLY)
                .environment(MilViewEnvironment.ENVIRONMENT_LAND)
                .build())
            .ontology(Ontology.builder().template(OntologyTemplate.TEMPLATE_ASSET).platformType("CAMERA").build())
            .location(Location.builder()
                .position(Position.builder().latitudeDegrees(33.6411).longitudeDegrees(-117.9187).build())
                .build())
            // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
            .media(Media.builder()
                .media(List.of(MediaItem.builder().itemIdentifier(INGRESS_ID).type(MediaItemType.MEDIA_TYPE_VIDEO).build()))
                .build())
            // Include every other component your integration publishes, such as its TaskCatalog.
            .provenance(Provenance.builder()
                .integrationName("my-integration")
                .dataType("asset")
                .sourceUpdateTime(now)
                .build())
            .build());
        System.out.println("Republished entity " + ENTITY_ID);
    }

    private static void resolveTrackedTasks(Lattice client, Set<String> taskIds) throws IOException {
        Principal author = Principal.builder()
            .system(com.anduril.types.System.builder().entityId(ENTITY_ID).build())
            .build();
        for (String taskId : new TreeSet<>(taskIds)) {
            Task task;
            try {
                task = client.tasks().getTask(taskId);
            } catch (LatticeApiException e) {
                if (e.statusCode() != 404) {
                    throw e;
                }
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrackTask(taskIds, taskId);
                continue;
            }
            if (task.getStatus().isEmpty() || task.getStatus().get().getStatus().isEmpty()
                    || task.getVersion().isEmpty() || task.getVersion().get().getStatusVersion().isEmpty()) {
                System.out.println("Task " + taskId + " is missing its status or version. Skipping.");
                continue;
            }
            TaskStatusStatus status = task.getStatus().get().getStatus().get();
            int statusVersion = task.getVersion().get().getStatusVersion().get();

            if (TERMINAL_STATUSES.contains(status)) {
                // An operator or another system closed the task while the agent was offline.
                untrackTask(taskIds, taskId);
                continue;
            }

            TaskError error;
            boolean pendingCancel = task.getDeliveryState().flatMap(DeliveryState::getStatus)
                .map(DeliveryStateStatus.DELIVERY_STATUS_PENDING_CANCEL::equals).orElse(false);
            if (status.equals(TaskStatusStatus.STATUS_CANCEL_REQUESTED) || pendingCancel) {
                // An operator cancelled the task while the agent was offline. Lattice records the cancel
                // in deliveryState, not in the task status. Accept the cancellation.
                error = TaskError.builder()
                    .code(TaskErrorCode.ERROR_CODE_CANCELLED)
                    .message("Cancelled while the agent was offline.")
                    .build();
            } else {
                // The agent lost its execution context, so report the task as failed rather than
                // leave it active with nothing working on it.
                error = TaskError.builder()
                    .code(TaskErrorCode.ERROR_CODE_FAILED)
                    .message("Agent restarted and could not resume the task.")
                    .build();
            }

            // Read the status version from GetTask, not from local state: the status might have
            // changed while the agent was offline, and Lattice ignores updates with a stale version.
            client.tasks().updateTaskStatus(taskId, TaskStatusUpdate.builder()
                .statusVersion(statusVersion + 1)
                .newStatus(TaskStatus.builder()
                    .status(TaskStatusStatus.STATUS_DONE_NOT_OK)
                    .taskError(error)
                    .build())
                .author(author)
                .build());
            System.out.println("Closed task " + taskId + " with " + error.getCode().map(Object::toString).orElse(""));
            untrackTask(taskIds, taskId);
        }
    }

    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 and ensure the endpoint has its scheme
        if (isBlank(endpoint) || isBlank(environmentToken) || isBlank(sandboxesToken)) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        // Create Lattice client with Sandbox authentication
        Lattice client = Lattice.builder()
            .url(endpoint)
            .token(environmentToken)
            .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
            .build();

        try {
            Set<String> taskIds = loadTaskIds();
            reconnectVideo(client);
            publishEntity(client);
            resolveTrackedTasks(client, taskIds);
        } catch (Exception e) {
            System.err.println("Failed to recover after restart: " + e.getMessage());
            System.exit(1);
        }

        // Recovery is complete. Start your regular publish loop and agent stream here, and call
        // trackTask and untrackTask as tasks start and finish.
    }

    private static boolean isBlank(String value) {
        return value == null || value.isEmpty();
    }

    /**
     * Returns a name-based version 5 UUID, which is the same every time for the same namespace and name.
     */
    private static UUID uuid5(UUID namespace, String name) {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            sha1.update(ByteBuffer.allocate(16)
                .putLong(namespace.getMostSignificantBits())
                .putLong(namespace.getLeastSignificantBits())
                .array());
            sha1.update(name.getBytes(StandardCharsets.UTF_8));
            byte[] hash = sha1.digest();
            hash[6] = (byte) ((hash[6] & 0x0f) | 0x50); // Version 5
            hash[8] = (byte) ((hash[8] & 0x3f) | 0x80); // RFC 9562 variant
            ByteBuffer bytes = ByteBuffer.wrap(hash, 0, 16);
            return new UUID(bytes.getLong(), bytes.getLong());
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("SHA-1 is unavailable", e);
        }
    }
}

```

```py title={"Python (REST)"} startLine={29} maxLines={6}
# This Python example uses the Lattice REST SDK (anduril-lattice-sdk) to recover an integration's
# video stream, entity, and tasks after the integration restarts.

import json
import os
import sys
import tempfile
import uuid
from datetime import datetime, timedelta, timezone

from anduril import (
    Aliases,
    Lattice,
    Location,
    Media,
    MediaItem,
    MilView,
    Ontology,
    Position,
    Principal,
    Provenance,
    RtspSettings,
    System,
    TaskError,
    TaskStatus,
)
from anduril.core import ApiError

# A name that is unique to this asset and never changes, such as a serial number read from
# hardware or configuration. Replace before running.
ASSET_NAME = "<ASSET-NAME>"
# The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
# so it's the same after every restart.
INGRESS_ID = f"{ASSET_NAME}.cam"
# The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
# and in every language.
ENTITY_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:my-integration:{ASSET_NAME}"))
# RTSP source that Lattice pulls video from. Replace before running.
RTSP_URL = "rtsp://<rtsp-host>:<port>/cam"
# Local file that stores the IDs of tasks this agent is executing.
STATE_FILE = "agent_state.json"

TERMINAL_STATUSES = {"STATUS_DONE_OK", "STATUS_DONE_NOT_OK"}


def load_task_ids():
    try:
        with open(STATE_FILE) as f:
            return set(json.load(f)["task_ids"])
    except FileNotFoundError:
        return set()


def save_task_ids(task_ids):
    # Write to a temporary file, then rename it over the original. A power loss during the
    # write leaves the previous file intact instead of a truncated one.
    directory = os.path.dirname(os.path.abspath(STATE_FILE))
    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f:
        json.dump({"task_ids": sorted(task_ids)}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(f.name, STATE_FILE)


def track_task(task_ids, task_id):
    # Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.add(task_id)
    save_task_ids(task_ids)


def untrack_task(task_ids, task_id):
    # Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.discard(task_id)
    save_task_ids(task_ids)


def reconnect_video(client):
    try:
        stream = client.video.get_ingress_stream(INGRESS_ID).ingress_stream
        # The stream survived the restart. Reuse it instead of creating a duplicate.
        print(f"Reusing stream {INGRESS_ID} with status {stream.status}")
        return
    except ApiError as error:
        if error.status_code != 404:
            raise

    # Lattice returns not found both for a stream that never existed and for one that was deleted.
    client.video.create_ingress_stream(
        ingress_id=INGRESS_ID,
        title=ASSET_NAME,
        rtsp=RtspSettings(url=RTSP_URL),
    )
    print(f"Created stream {INGRESS_ID}")


def publish_entity(client):
    now = datetime.now(timezone.utc)
    client.entities.publish_entity(
        entity_id=ENTITY_ID,
        is_live=True,
        expiry_time=now + timedelta(minutes=5),
        aliases=Aliases(name=ASSET_NAME),
        mil_view=MilView(disposition="DISPOSITION_FRIENDLY", environment="ENVIRONMENT_LAND"),
        ontology=Ontology(template="TEMPLATE_ASSET", platform_type="CAMERA"),
        location=Location(position=Position(latitude_degrees=33.6411, longitude_degrees=-117.9187)),
        # Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media=Media(media=[MediaItem(item_identifier=INGRESS_ID, type="MEDIA_TYPE_VIDEO")]),
        # Include every other component your integration publishes, such as its TaskCatalog.
        provenance=Provenance(
            integration_name="my-integration",
            data_type="asset",
            source_update_time=now,
        ),
    )
    print(f"Republished entity {ENTITY_ID}")


def resolve_tracked_tasks(client, task_ids):
    author = Principal(system=System(entity_id=ENTITY_ID))
    for task_id in sorted(task_ids):
        try:
            task = client.tasks.get_task(task_id)
        except ApiError as error:
            if error.status_code != 404:
                raise
            # The task no longer exists in Lattice, so there's nothing to resolve.
            untrack_task(task_ids, task_id)
            continue
        if not task.status or not task.version or task.version.status_version is None:
            print(f"Task {task_id} is missing its status or version. Skipping.")
            continue

        if task.status.status in TERMINAL_STATUSES:
            # An operator or another system closed the task while the agent was offline.
            untrack_task(task_ids, task_id)
            continue

        pending_cancel = task.delivery_state and task.delivery_state.status == "DELIVERY_STATUS_PENDING_CANCEL"
        if task.status.status == "STATUS_CANCEL_REQUESTED" or pending_cancel:
            # An operator cancelled the task while the agent was offline. Lattice records the cancel
            # in delivery_state, not in the task status. Accept the cancellation.
            error = TaskError(code="ERROR_CODE_CANCELLED", message="Cancelled while the agent was offline.")
        else:
            # The agent lost its execution context, so report the task as failed rather than
            # leave it active with nothing working on it.
            error = TaskError(code="ERROR_CODE_FAILED", message="Agent restarted and could not resume the task.")

        # Read status_version from GetTask, not from local state: the status might have
        # changed while the agent was offline, and Lattice ignores updates with a stale version.
        client.tasks.update_task_status(
            task_id,
            status_version=task.version.status_version + 1,
            new_status=TaskStatus(status="STATUS_DONE_NOT_OK", task_error=error),
            author=author,
        )
        print(f"Closed task {task_id} with {error.code}")
        untrack_task(task_ids, task_id)


def main():
    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)

    client = Lattice(
        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}"},
    )

    task_ids = load_task_ids()
    try:
        reconnect_video(client)
        publish_entity(client)
        resolve_tracked_tasks(client, task_ids)
    except Exception as error:
        print(f"Failed to recover after restart: {error}", file=sys.stderr)
        sys.exit(1)

    # Recovery is complete. Start your regular publish loop and agent stream here, and call
    # track_task and untrack_task as tasks start and finish.


if __name__ == "__main__":
    main()

```

```ts title={"TypeScript (REST)"} startLine={9} maxLines={6}
// This TypeScript example uses the Lattice REST SDK (@anduril-industries/lattice-sdk) to recover an
// integration's video stream, entity, and tasks after the integration restarts.

import * as fs from "node:fs";
import * as path from "node:path";
import { Lattice, LatticeClient, LatticeError } from "@anduril-industries/lattice-sdk";
import { v5 as uuidv5 } from "uuid";

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
const INGRESS_ID = `${ASSET_NAME}.cam`;
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
const ENTITY_ID = uuidv5(`urn:my-integration:${ASSET_NAME}`, uuidv5.URL);
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE = "agent_state.json";

const TERMINAL_STATUSES = new Set<string | undefined>(["STATUS_DONE_OK", "STATUS_DONE_NOT_OK"]);

function loadTaskIds(): Set<string> {
    try {
        return new Set<string>(JSON.parse(fs.readFileSync(STATE_FILE, "utf8")).task_ids);
    } catch (error) {
        if ((error as NodeJS.ErrnoException).code === "ENOENT") {
            return new Set<string>();
        }
        throw error;
    }
}

function saveTaskIds(taskIds: Set<string>) {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    const tempFile = path.join(path.dirname(path.resolve(STATE_FILE)), `.${path.basename(STATE_FILE)}.${process.pid}.tmp`);
    const fd = fs.openSync(tempFile, "w");
    try {
        fs.writeSync(fd, JSON.stringify({ task_ids: [...taskIds].sort() }));
        fs.fsyncSync(fd);
    } finally {
        fs.closeSync(fd);
    }
    fs.renameSync(tempFile, STATE_FILE);
}

export function trackTask(taskIds: Set<string>, taskId: string) {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    taskIds.add(taskId);
    saveTaskIds(taskIds);
}

export function untrackTask(taskIds: Set<string>, taskId: string) {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    taskIds.delete(taskId);
    saveTaskIds(taskIds);
}

async function reconnectVideo(client: LatticeClient) {
    try {
        const { ingressStream } = await client.video.getIngressStream({ ingressId: INGRESS_ID });
        // The stream survived the restart. Reuse it instead of creating a duplicate.
        console.log(`Reusing stream ${INGRESS_ID} with status ${ingressStream?.status}`);
        return;
    } catch (error) {
        if (!(error instanceof LatticeError && error.statusCode === 404)) {
            throw error;
        }
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    await client.video.createIngressStream({
        ingressId: INGRESS_ID,
        title: ASSET_NAME,
        rtsp: { url: RTSP_URL },
    });
    console.log(`Created stream ${INGRESS_ID}`);
}

async function publishEntity(client: LatticeClient) {
    const now = new Date();
    await client.entities.publishEntity({
        entityId: ENTITY_ID,
        isLive: true,
        expiryTime: new Date(now.getTime() + 5 * 60 * 1000).toISOString(),
        aliases: { name: ASSET_NAME },
        milView: { disposition: "DISPOSITION_FRIENDLY", environment: "ENVIRONMENT_LAND" },
        ontology: { template: "TEMPLATE_ASSET", platformType: "CAMERA" },
        location: { position: { latitudeDegrees: 33.6411, longitudeDegrees: -117.9187 } },
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: { media: [{ itemIdentifier: INGRESS_ID, type: "MEDIA_TYPE_VIDEO" }] },
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: {
            integrationName: "my-integration",
            dataType: "asset",
            sourceUpdateTime: now.toISOString(),
        },
    });
    console.log(`Republished entity ${ENTITY_ID}`);
}

async function resolveTrackedTasks(client: LatticeClient, taskIds: Set<string>) {
    const author = { system: { entityId: ENTITY_ID } };
    for (const taskId of [...taskIds].sort()) {
        let task: Lattice.Task;
        try {
            task = await client.tasks.getTask({ taskId });
        } catch (error) {
            if (!(error instanceof LatticeError && error.statusCode === 404)) {
                throw error;
            }
            // The task no longer exists in Lattice, so there's nothing to resolve.
            untrackTask(taskIds, taskId);
            continue;
        }
        const statusVersion = task.version?.statusVersion;
        if (!task.status || statusVersion === undefined) {
            console.log(`Task ${taskId} is missing its status or version. Skipping.`);
            continue;
        }

        if (TERMINAL_STATUSES.has(task.status.status)) {
            // An operator or another system closed the task while the agent was offline.
            untrackTask(taskIds, taskId);
            continue;
        }

        let taskError: Lattice.TaskError;
        const pendingCancel = task.deliveryState?.status === "DELIVERY_STATUS_PENDING_CANCEL";
        if (task.status.status === "STATUS_CANCEL_REQUESTED" || pendingCancel) {
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in deliveryState, not in the task status. Accept the cancellation.
            taskError = { code: "ERROR_CODE_CANCELLED", message: "Cancelled while the agent was offline." };
        } else {
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            taskError = { code: "ERROR_CODE_FAILED", message: "Agent restarted and could not resume the task." };
        }

        // Read statusVersion from getTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        await client.tasks.updateTaskStatus({
            taskId,
            statusVersion: statusVersion + 1,
            newStatus: { status: "STATUS_DONE_NOT_OK", taskError },
            author,
        });
        console.log(`Closed task ${taskId} with ${taskError.code}`);
        untrackTask(taskIds, taskId);
    }
}

async function App() {
    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,
            // Remove the following if you are not developing on Sandboxes.
            headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}`  }
        }
    );

    const taskIds = loadTaskIds();
    try {
        await reconnectVideo(client);
        await publishEntity(client);
        await resolveTrackedTasks(client, taskIds);
    } catch (error) {
        console.error(`Failed to recover after restart: ${error}`);
        process.exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // trackTask and untrackTask as tasks start and finish.
}

App();

```

```rs title={"Rust (REST)"} startLine={16} maxLines={6}
// This Rust example uses the Lattice REST SDK (anduril-lattice-sdk) to recover an integration's
// video stream, entity, and tasks after the integration restarts.

// track_task is called from the main loop you add after recovery.
#![allow(dead_code)]

use anduril_lattice_sdk::prelude::*;

use std::collections::BTreeSet;
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::sync::LazyLock;
use uuid::Uuid;

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME: &str = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
static INGRESS_ID: LazyLock<String> = LazyLock::new(|| format!("{}.cam", ASSET_NAME));
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
static ENTITY_ID: LazyLock<String> = LazyLock::new(|| {
    let name = format!("urn:my-integration:{}", ASSET_NAME);
    Uuid::new_v5(&Uuid::NAMESPACE_URL, name.as_bytes()).to_string()
});
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL: &str = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE: &str = "agent_state.json";

fn load_task_ids() -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
    let contents = match fs::read_to_string(STATE_FILE) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(error.into()),
    };
    let state: Value = contents.parse()?;
    let task_ids = state["task_ids"].as_array().ok_or("task_ids is missing")?;
    Ok(task_ids.iter().filter_map(|id| id.as_str().map(String::from)).collect())
}

fn save_task_ids(task_ids: &BTreeSet<String>) -> std::io::Result<()> {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    let temp_path = format!("{}.tmp", STATE_FILE);
    let mut file = File::create(&temp_path)?;
    file.write_all(json!({ "task_ids": task_ids }).to_string().as_bytes())?;
    file.sync_all()?;
    fs::rename(&temp_path, STATE_FILE)
}

fn track_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.insert(task_id.to_string());
    save_task_ids(task_ids)
}

fn untrack_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.remove(task_id);
    save_task_ids(task_ids)
}

async fn reconnect_video(client: &Lattice) -> Result<(), ApiError> {
    match client.video.get_ingress_stream(&INGRESS_ID, None).await {
        Ok(response) => {
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            let status = response
                .ingress_stream
                .and_then(|stream| stream.status)
                .map(|status| status.to_string())
                .unwrap_or_default();
            println!("Reusing stream {} with status {}", *INGRESS_ID, status);
            return Ok(());
        }
        Err(ApiError::NotFoundError { .. }) => {}
        Err(error) => return Err(error),
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    let request = CreateIngressStreamRequest {
        ingress_id: Some(INGRESS_ID.clone()),
        title: Some(ASSET_NAME.to_string()),
        rtsp: Some(RtspSettings {
            url: Some(RTSP_URL.to_string()),
            ..Default::default()
        }),
        ..Default::default()
    };
    client.video.create_ingress_stream(&request, None).await?;
    println!("Created stream {}", *INGRESS_ID);
    Ok(())
}

async fn publish_entity(client: &Lattice) -> Result<(), ApiError> {
    let now = Utc::now();
    let entity = Entity {
        entity_id: Some(ENTITY_ID.clone()),
        is_live: Some(true),
        expiry_time: Some((now + chrono::Duration::minutes(5)).fixed_offset()),
        aliases: Some(Aliases {
            name: Some(ASSET_NAME.to_string()),
            ..Default::default()
        }),
        mil_view: Some(MilView {
            disposition: Some(MilViewDisposition::DispositionFriendly),
            environment: Some(MilViewEnvironment::EnvironmentLand),
            ..Default::default()
        }),
        ontology: Some(Ontology {
            template: Some(OntologyTemplate::TemplateAsset),
            platform_type: Some("CAMERA".to_string()),
            ..Default::default()
        }),
        location: Some(Location {
            position: Some(Position {
                latitude_degrees: Some(33.6411),
                longitude_degrees: Some(-117.9187),
                ..Default::default()
            }),
            ..Default::default()
        }),
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: Some(Media {
            media: Some(vec![MediaItem {
                item_identifier: Some(INGRESS_ID.clone()),
                r#type: Some(MediaItemType::MediaTypeVideo),
                ..Default::default()
            }]),
            ..Default::default()
        }),
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: Some(Provenance {
            integration_name: Some("my-integration".to_string()),
            data_type: Some("asset".to_string()),
            source_update_time: Some(now.fixed_offset()),
            ..Default::default()
        }),
        ..Default::default()
    };
    client.entities.publish_entity(&entity, None).await?;
    println!("Republished entity {}", *ENTITY_ID);
    Ok(())
}

async fn resolve_tracked_tasks(
    client: &Lattice,
    task_ids: &mut BTreeSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let author = Principal {
        system: Some(System {
            entity_id: Some(ENTITY_ID.clone()),
            ..Default::default()
        }),
        ..Default::default()
    };
    for task_id in task_ids.clone() {
        let task = match client.tasks.get_task(&task_id, None).await {
            Ok(task) => task,
            Err(ApiError::NotFoundError { .. }) => {
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            Err(error) => return Err(error.into()),
        };
        let (Some(status), Some(status_version)) = (
            task.status.as_ref(),
            task.version.as_ref().and_then(|version| version.status_version),
        ) else {
            println!("Task {} is missing its status or version. Skipping.", task_id);
            continue;
        };

        let cancelled = matches!(status.status, Some(TaskStatusStatus::StatusCancelRequested))
            || matches!(
                task.delivery_state.as_ref().and_then(|state| state.status.as_ref()),
                Some(DeliveryStateStatus::DeliveryStatusPendingCancel)
            );
        let error = match status.status {
            Some(TaskStatusStatus::StatusDoneOk | TaskStatusStatus::StatusDoneNotOk) => {
                // An operator or another system closed the task while the agent was offline.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in delivery_state, not in the task status. Accept the cancellation.
            _ if cancelled => TaskError {
                code: Some(TaskErrorCode::ErrorCodeCancelled),
                message: Some("Cancelled while the agent was offline.".to_string()),
                ..Default::default()
            },
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            _ => TaskError {
                code: Some(TaskErrorCode::ErrorCodeFailed),
                message: Some("Agent restarted and could not resume the task.".to_string()),
                ..Default::default()
            },
        };
        let code = error.code.as_ref().map(|code| code.to_string()).unwrap_or_default();

        // Read status_version from GetTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        let request = TaskStatusUpdate {
            status_version: Some(status_version + 1),
            new_status: Some(TaskStatus {
                status: Some(TaskStatusStatus::StatusDoneNotOk),
                task_error: Some(error),
                ..Default::default()
            }),
            author: Some(author.clone()),
        };
        client.tasks.update_task_status(&task_id, &request, None).await?;
        println!("Closed task {} with {}", task_id, code);
        untrack_task(task_ids, &task_id)?;
    }
    Ok(())
}

#[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)?;

    let mut task_ids = load_task_ids()?;
    let result: Result<(), Box<dyn std::error::Error>> = async {
        reconnect_video(&client).await?;
        publish_entity(&client).await?;
        resolve_tracked_tasks(&client, &mut task_ids).await?;
        Ok(())
    }
    .await;
    if let Err(error) = result {
        eprintln!("Failed to recover after restart: {}", error);
        std::process::exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // track_task and untrack_task as tasks start and finish.
    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={36} maxLines={7}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
//
// It recovers an integration's video stream, entity, and tasks after the integration restarts.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"maps"
	"os"
	"path/filepath"
	"slices"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/taskmanager/v1/taskmanagerv1grpc"
	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/videomanager/v1/videomanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	ontologyv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/ontology/v1"
	taskmanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/taskmanager/v1"
	videomanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/videomanager/v1"

	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"

// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"

// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()

const (
	// RTSP source that Lattice pulls video from. Replace before running.
	rtspURL = "rtsp://<rtsp-host>:<port>/cam"
	// Local file that stores the IDs of tasks this agent is executing.
	stateFile = "agent_state.json"
)

var terminalStatuses = map[taskmanagerv1.Status]bool{
	taskmanagerv1.Status_STATUS_DONE_OK:     true,
	taskmanagerv1.Status_STATUS_DONE_NOT_OK: true,
}

type agentState struct {
	TaskIDs []string `json:"task_ids"`
}

func loadTaskIDs() (map[string]bool, error) {
	taskIDs := map[string]bool{}
	data, err := os.ReadFile(stateFile)
	if errors.Is(err, os.ErrNotExist) {
		return taskIDs, nil
	}
	if err != nil {
		return nil, err
	}
	var state agentState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	for _, taskID := range state.TaskIDs {
		taskIDs[taskID] = true
	}
	return taskIDs, nil
}

func saveTaskIDs(taskIDs map[string]bool) error {
	ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
	slices.Sort(ids)
	data, err := json.Marshal(agentState{TaskIDs: ids})
	if err != nil {
		return err
	}
	// Write to a temporary file, then rename it over the original. A power loss during the
	// write leaves the previous file intact instead of a truncated one.
	f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	if _, err := f.Write(data); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), stateFile)
}

// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
	taskIDs[taskID] = true
	return saveTaskIDs(taskIDs)
}

// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
	delete(taskIDs, taskID)
	return saveTaskIDs(taskIDs)
}

func reconnectVideo(ctx context.Context, client videomanagerv1grpc.VideoManagerAPIClient) error {
	response, err := client.GetIngressStream(ctx, &videomanagerv1.GetIngressStreamRequest{
		IngressId: ingressID,
	})
	if err == nil {
		// The stream survived the restart. Reuse it instead of creating a duplicate.
		fmt.Printf("Reusing stream %s with status %s\n", ingressID, response.GetIngressStream().GetStatus())
		return nil
	}
	if status.Code(err) != codes.NotFound {
		return err
	}

	// Lattice returns not found both for a stream that never existed and for one that was deleted.
	_, err = client.CreateIngressStream(ctx, &videomanagerv1.CreateIngressStreamRequest{
		IngressId: proto.String(ingressID),
		Title:     assetName,
		Ingress: &videomanagerv1.CreateIngressStreamRequest_Rtsp{
			Rtsp: &videomanagerv1.RtspSettings{
				Url: proto.String(rtspURL),
			},
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Created stream %s\n", ingressID)
	return nil
}

func publishEntity(ctx context.Context, client entitymanagerv1grpc.EntityManagerAPIClient) error {
	now := time.Now().UTC()
	_, err := client.PublishEntity(ctx, &entitymanagerv1.PublishEntityRequest{Entity: &entitymanagerv1.Entity{
		EntityId:   entityID,
		IsLive:     true,
		ExpiryTime: timestamppb.New(now.Add(5 * time.Minute)),
		Aliases:    &entitymanagerv1.Aliases{Name: assetName},
		MilView: &entitymanagerv1.MilView{
			Disposition: ontologyv1.Disposition_DISPOSITION_FRIENDLY,
			Environment: ontologyv1.Environment_ENVIRONMENT_LAND,
		},
		Ontology: &entitymanagerv1.Ontology{
			Template:     entitymanagerv1.Template_TEMPLATE_ASSET,
			PlatformType: "CAMERA",
		},
		Location: &entitymanagerv1.Location{
			Position: &entitymanagerv1.Position{
				LatitudeDegrees:  33.6411,
				LongitudeDegrees: -117.9187,
			},
		},
		// Because ingressID never changes, the entity can reference the stream on every publish.
		Media: &entitymanagerv1.Media{Media: []*entitymanagerv1.MediaItem{{
			ItemIdentifier: ingressID,
			Type:           entitymanagerv1.MediaType_MEDIA_TYPE_VIDEO,
		}}},
		// Include every other component your integration publishes, such as its TaskCatalog.
		Provenance: &entitymanagerv1.Provenance{
			IntegrationName:  "my-integration",
			DataType:         "asset",
			SourceUpdateTime: timestamppb.New(now),
		},
	}})
	if err != nil {
		return err
	}
	fmt.Printf("Republished entity %s\n", entityID)
	return nil
}

func resolveTrackedTasks(ctx context.Context, client taskmanagerv1grpc.TaskManagerAPIClient, taskIDs map[string]bool) error {
	author := &taskmanagerv1.Principal{
		Agent: &taskmanagerv1.Principal_System{
			System: &taskmanagerv1.System{EntityId: entityID},
		},
	}
	for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
		response, err := client.GetTask(ctx, &taskmanagerv1.GetTaskRequest{TaskId: taskID})
		if status.Code(err) == codes.NotFound {
			// The task no longer exists in Lattice, so there's nothing to resolve.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
		task := response.GetTask()
		if task.GetStatus() == nil || task.GetVersion() == nil {
			fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
			continue
		}

		taskStatus := task.GetStatus().GetStatus()
		if terminalStatuses[taskStatus] {
			// An operator or another system closed the task while the agent was offline.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}

		var taskError *taskmanagerv1.TaskError
		cancelled := taskStatus == taskmanagerv1.Status_STATUS_CANCEL_REQUESTED ||
			task.GetDeliveryState().GetStatus() == taskmanagerv1.DeliveryStatus_DELIVERY_STATUS_PENDING_CANCEL
		if cancelled {
			// An operator cancelled the task while the agent was offline. Lattice records the cancel
			// in delivery_state, not in the task status. Accept the cancellation.
			taskError = &taskmanagerv1.TaskError{
				Code:    taskmanagerv1.ErrorCode_ERROR_CODE_CANCELLED,
				Message: "Cancelled while the agent was offline.",
			}
		} else {
			// The agent lost its execution context, so report the task as failed rather than
			// leave it active with nothing working on it.
			taskError = &taskmanagerv1.TaskError{
				Code:    taskmanagerv1.ErrorCode_ERROR_CODE_FAILED,
				Message: "Agent restarted and could not resume the task.",
			}
		}

		// Read the status version from GetTask, not from local state: the status might have
		// changed while the agent was offline, and Lattice ignores updates with a stale version.
		_, err = client.UpdateStatus(ctx, &taskmanagerv1.UpdateStatusRequest{
			StatusUpdate: &taskmanagerv1.StatusUpdate{
				Version: &taskmanagerv1.TaskVersion{
					TaskId:        taskID,
					StatusVersion: task.GetVersion().GetStatusVersion() + 1,
				},
				Status: &taskmanagerv1.TaskStatus{
					Status:    taskmanagerv1.Status_STATUS_DONE_NOT_OK,
					TaskError: taskError,
				},
				Author: author,
			},
		})
		if err != nil {
			return err
		}
		fmt.Printf("Closed task %s with %s\n", taskID, taskError.GetCode())
		if err := untrackTask(taskIDs, taskID); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	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()

	videoClient := videomanagerv1grpc.NewVideoManagerAPIClient(conn)
	entityClient := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)
	taskClient := taskmanagerv1grpc.NewTaskManagerAPIClient(conn)

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	taskIDs, err := loadTaskIDs()
	if err != nil {
		log.Fatalf("Failed to load saved task IDs: %v", err)
	}
	if err := reconnectVideo(ctx, videoClient); err != nil {
		log.Fatalf("Failed to reconnect video: %v", err)
	}
	if err := publishEntity(ctx, entityClient); err != nil {
		log.Fatalf("Failed to republish entity: %v", err)
	}
	if err := resolveTrackedTasks(ctx, taskClient, taskIDs); err != nil {
		log.Fatalf("Failed to resolve tracked tasks: %v", err)
	}

	// Recovery is complete. Start your regular publish loop and agent stream here, and call
	// trackTask and untrackTask as tasks start and finish.
}

```

```py title={"Python (gRPC)"} startLine={44} maxLines={6}
# 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
# It recovers an integration's video stream, entity, and tasks after the integration restarts.

import json
import os
import sys
import tempfile
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from connectrpc.code import Code
from connectrpc.errors import ConnectError
from protobuf import Oneof
from protobuf.wkt import Timestamp

from anduril.entitymanager.v1.entity_pub_pb import Aliases, Entity, Provenance
from anduril.entitymanager.v1.entity_manager_api_pub_pb import PublishEntityRequest
from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.location_pub_pb import Location, Position
from anduril.entitymanager.v1.media_pub_pb import Media, MediaItem, MediaType
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.ontology.v1.type_pub_pb import Disposition, Environment
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.taskmanager.v1.task_pub_pb import (
    DeliveryStatus,
    ErrorCode,
    Principal,
    Status,
    StatusUpdate,
    System,
    TaskError,
    TaskStatus,
    TaskVersion,
)
from anduril.taskmanager.v1.task_manager_api_pub_pb import GetTaskRequest, UpdateStatusRequest
from anduril.taskmanager.v1.task_manager_api_pub_connect import TaskManagerAPIClientSync
from anduril.videomanager.v1.create_ingress_stream_request_pub_pb import CreateIngressStreamRequest
from anduril.videomanager.v1.get_ingress_stream_request_pub_pb import GetIngressStreamRequest
from anduril.videomanager.v1.rtsp_settings_pub_pb import RtspSettings
from anduril.videomanager.v1.video_manager_api_pub_connect import VideoManagerAPIClientSync

# A name that is unique to this asset and never changes, such as a serial number read from
# hardware or configuration. Replace before running.
ASSET_NAME = "<ASSET-NAME>"
# The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
# so it's the same after every restart.
INGRESS_ID = f"{ASSET_NAME}.cam"
# The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
# and in every language.
ENTITY_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:my-integration:{ASSET_NAME}"))
# RTSP source that Lattice pulls video from. Replace before running.
RTSP_URL = "rtsp://<rtsp-host>:<port>/cam"
# Local file that stores the IDs of tasks this agent is executing.
STATE_FILE = "agent_state.json"

TERMINAL_STATUSES = {Status.DONE_OK, Status.DONE_NOT_OK}


def load_task_ids():
    try:
        with open(STATE_FILE) as f:
            return set(json.load(f)["task_ids"])
    except FileNotFoundError:
        return set()


def save_task_ids(task_ids):
    # Write to a temporary file, then rename it over the original. A power loss during the
    # write leaves the previous file intact instead of a truncated one.
    directory = os.path.dirname(os.path.abspath(STATE_FILE))
    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f:
        json.dump({"task_ids": sorted(task_ids)}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(f.name, STATE_FILE)


def track_task(task_ids, task_id):
    # Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.add(task_id)
    save_task_ids(task_ids)


def untrack_task(task_ids, task_id):
    # Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.discard(task_id)
    save_task_ids(task_ids)


def reconnect_video(client):
    try:
        response = client.get_ingress_stream(GetIngressStreamRequest(ingress_id=INGRESS_ID), timeout_ms=10000)
        # The stream survived the restart. Reuse it instead of creating a duplicate.
        print(f"Reusing stream {INGRESS_ID} with status STREAM_STATUS_{response.ingress_stream.status.name}")
        return
    except ConnectError as error:
        if error.code != Code.NOT_FOUND:
            raise

    # Lattice returns not found both for a stream that never existed and for one that was deleted.
    client.create_ingress_stream(
        CreateIngressStreamRequest(
            ingress_id=INGRESS_ID,
            title=ASSET_NAME,
            ingress=Oneof("rtsp", RtspSettings(url=RTSP_URL)),
        ),
        timeout_ms=30000,
    )
    print(f"Created stream {INGRESS_ID}")


def publish_entity(client):
    now = datetime.now(timezone.utc)
    entity = Entity(
        entity_id=ENTITY_ID,
        is_live=True,
        expiry_time=Timestamp.from_datetime(now + timedelta(minutes=5)),
        aliases=Aliases(name=ASSET_NAME),
        mil_view=MilView(disposition=Disposition.FRIENDLY, environment=Environment.LAND),
        ontology=Ontology(template=Template.ASSET, platform_type="CAMERA"),
        location=Location(position=Position(latitude_degrees=33.6411, longitude_degrees=-117.9187)),
        # Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media=Media(media=[MediaItem(item_identifier=INGRESS_ID, type=MediaType.VIDEO)]),
        # Include every other component your integration publishes, such as its TaskCatalog.
        provenance=Provenance(
            integration_name="my-integration",
            data_type="asset",
            source_update_time=Timestamp.from_datetime(now),
        ),
    )
    client.publish_entity(PublishEntityRequest(entity=entity), timeout_ms=10000)
    print(f"Republished entity {ENTITY_ID}")


def resolve_tracked_tasks(client, task_ids):
    author = Principal(agent=Oneof("system", System(entity_id=ENTITY_ID)))
    for task_id in sorted(task_ids):
        try:
            task = client.get_task(GetTaskRequest(task_id=task_id), timeout_ms=10000).task
        except ConnectError as error:
            if error.code != Code.NOT_FOUND:
                raise
            # The task no longer exists in Lattice, so there's nothing to resolve.
            untrack_task(task_ids, task_id)
            continue
        if not task or not task.status or not task.version:
            print(f"Task {task_id} is missing its status or version. Skipping.")
            continue

        if task.status.status in TERMINAL_STATUSES:
            # An operator or another system closed the task while the agent was offline.
            untrack_task(task_ids, task_id)
            continue

        pending_cancel = task.delivery_state and task.delivery_state.status == DeliveryStatus.PENDING_CANCEL
        if task.status.status == Status.CANCEL_REQUESTED or pending_cancel:
            # An operator cancelled the task while the agent was offline. Lattice records the cancel
            # in delivery_state, not in the task status. Accept the cancellation.
            error = TaskError(code=ErrorCode.CANCELLED, message="Cancelled while the agent was offline.")
        else:
            # The agent lost its execution context, so report the task as failed rather than
            # leave it active with nothing working on it.
            error = TaskError(code=ErrorCode.FAILED, message="Agent restarted and could not resume the task.")

        # Read status_version from GetTask, not from local state: the status might have
        # changed while the agent was offline, and Lattice ignores updates with a stale version.
        status_update = StatusUpdate(
            version=TaskVersion(task_id=task_id, status_version=task.version.status_version + 1),
            status=TaskStatus(status=Status.DONE_NOT_OK, task_error=error),
            author=author,
        )
        client.update_status(UpdateStatusRequest(status_update=status_update), timeout_ms=10000)
        print(f"Closed task {task_id} with ERROR_CODE_{error.code.name}")
        untrack_task(task_ids, task_id)


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 clients over Connect gRPC with authentication
    video_client = create_client(VideoManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)
    entity_client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)
    task_client = create_client(TaskManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    task_ids = load_task_ids()
    try:
        reconnect_video(video_client)
        publish_entity(entity_client)
        resolve_tracked_tasks(task_client, task_ids)
    except Exception as error:
        print(f"Failed to recover after restart: {error}", file=sys.stderr)
        sys.exit(1)

    # Recovery is complete. Start your regular publish loop and agent stream here, and call
    # track_task and untrack_task as tasks start and finish.


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={41} maxLines={6}
// 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

// track_task is called from the main loop you add after recovery.
#![allow(dead_code)]

mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    Aliases, Entity, Location, Media, MediaItem, MediaType, MilView, Ontology, Position, Provenance,
    PublishEntityRequest, Template,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{Disposition, Environment};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::taskmanager::v1::{
    principal, DeliveryStatus, ErrorCode, GetTaskRequest, Principal, Status, StatusUpdate, System, TaskError,
    TaskStatus, TaskVersion, UpdateStatusRequest,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::videomanager::v1::{
    create_ingress_stream_request::Ingress, CreateIngressStreamRequest, GetIngressStreamRequest,
    RtspSettings,
};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::taskmanager::v1::tonic::task_manager_api_client::TaskManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::videomanager::v1::tonic::video_manager_api_client::VideoManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use prost_types::Timestamp;
use serde_json::{json, Value};
use tonic::metadata::{Ascii, MetadataValue};
use tonic::service::interceptor::InterceptedService;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::{Code, Request};
use uuid::Uuid;

use std::collections::BTreeSet;
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::sync::LazyLock;
use std::time::{SystemTime, UNIX_EPOCH};

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME: &str = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
static INGRESS_ID: LazyLock<String> = LazyLock::new(|| format!("{}.cam", ASSET_NAME));
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
static ENTITY_ID: LazyLock<String> = LazyLock::new(|| {
    let name = format!("urn:my-integration:{}", ASSET_NAME);
    Uuid::new_v5(&Uuid::NAMESPACE_URL, name.as_bytes()).to_string()
});
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL: &str = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE: &str = "agent_state.json";

type Interceptor = Box<dyn FnMut(Request<()>) -> Result<Request<()>, tonic::Status> + Send + Sync>;
type VideoClient = VideoManagerApiClient<InterceptedService<Channel, Interceptor>>;
type EntityClient = EntityManagerApiClient<InterceptedService<Channel, Interceptor>>;
type TaskClient = TaskManagerApiClient<InterceptedService<Channel, Interceptor>>;

fn now_timestamp() -> Timestamp {
    let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    Timestamp {
        seconds: d.as_secs() as i64,
        nanos: d.subsec_nanos() as i32,
    }
}

fn load_task_ids() -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
    let contents = match fs::read_to_string(STATE_FILE) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(error.into()),
    };
    let state: Value = contents.parse()?;
    let task_ids = state["task_ids"].as_array().ok_or("task_ids is missing")?;
    Ok(task_ids.iter().filter_map(|id| id.as_str().map(String::from)).collect())
}

fn save_task_ids(task_ids: &BTreeSet<String>) -> std::io::Result<()> {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    let temp_path = format!("{}.tmp", STATE_FILE);
    let mut file = File::create(&temp_path)?;
    file.write_all(json!({ "task_ids": task_ids }).to_string().as_bytes())?;
    file.sync_all()?;
    fs::rename(&temp_path, STATE_FILE)
}

fn track_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.insert(task_id.to_string());
    save_task_ids(task_ids)
}

fn untrack_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.remove(task_id);
    save_task_ids(task_ids)
}

async fn reconnect_video(client: &mut VideoClient) -> Result<(), tonic::Status> {
    let request = Request::new(GetIngressStreamRequest {
        ingress_id: INGRESS_ID.clone(),
    });
    match client.get_ingress_stream(request).await {
        Ok(response) => {
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            let status = response
                .into_inner()
                .ingress_stream
                .map(|stream| stream.status().as_str_name())
                .unwrap_or_default();
            println!("Reusing stream {} with status {}", *INGRESS_ID, status);
            return Ok(());
        }
        Err(status) if status.code() == Code::NotFound => {}
        Err(status) => return Err(status),
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    let request = Request::new(CreateIngressStreamRequest {
        ingress_id: Some(INGRESS_ID.clone()),
        title: ASSET_NAME.to_string(),
        ingress: Some(Ingress::Rtsp(RtspSettings {
            url: Some(RTSP_URL.to_string()),
        })),
    });
    client.create_ingress_stream(request).await?;
    println!("Created stream {}", *INGRESS_ID);
    Ok(())
}

async fn publish_entity(client: &mut EntityClient) -> Result<(), tonic::Status> {
    let now = now_timestamp();
    let entity = Entity {
        entity_id: ENTITY_ID.clone(),
        is_live: true,
        expiry_time: Some(Timestamp {
            seconds: now.seconds + 5 * 60,
            nanos: now.nanos,
        }),
        aliases: Some(Aliases {
            name: ASSET_NAME.to_string(),
            ..Default::default()
        }),
        mil_view: Some(MilView {
            disposition: Disposition::Friendly as i32,
            environment: Environment::Land as i32,
            ..Default::default()
        }),
        ontology: Some(Ontology {
            template: Template::Asset as i32,
            platform_type: "CAMERA".to_string(),
            ..Default::default()
        }),
        location: Some(Location {
            position: Some(Position {
                latitude_degrees: 33.6411,
                longitude_degrees: -117.9187,
                ..Default::default()
            }),
            ..Default::default()
        }),
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: Some(Media {
            media: vec![MediaItem {
                item_identifier: INGRESS_ID.clone(),
                r#type: MediaType::Video as i32,
                ..Default::default()
            }],
        }),
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: Some(Provenance {
            integration_name: "my-integration".to_string(),
            data_type: "asset".to_string(),
            source_update_time: Some(now),
            ..Default::default()
        }),
        ..Default::default()
    };
    client
        .publish_entity(Request::new(PublishEntityRequest {
            entity: Some(entity),
        }))
        .await?;
    println!("Republished entity {}", *ENTITY_ID);
    Ok(())
}

async fn resolve_tracked_tasks(
    client: &mut TaskClient,
    task_ids: &mut BTreeSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let author = Principal {
        agent: Some(principal::Agent::System(System {
            entity_id: ENTITY_ID.clone(),
            ..Default::default()
        })),
        ..Default::default()
    };
    for task_id in task_ids.clone() {
        let request = Request::new(GetTaskRequest {
            task_id: task_id.clone(),
            ..Default::default()
        });
        let task = match client.get_task(request).await {
            Ok(response) => response.into_inner().task,
            Err(status) if status.code() == Code::NotFound => {
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            Err(status) => return Err(status.into()),
        };
        let Some((status, version)) = task.as_ref().and_then(|task| task.status.as_ref().zip(task.version.as_ref()))
        else {
            println!("Task {} is missing its status or version. Skipping.", task_id);
            continue;
        };

        let cancelled = status.status() == Status::CancelRequested
            || task.as_ref().and_then(|task| task.delivery_state.as_ref()).map(|state| state.status())
                == Some(DeliveryStatus::PendingCancel);
        let error = match status.status() {
            Status::DoneOk | Status::DoneNotOk => {
                // An operator or another system closed the task while the agent was offline.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in delivery_state, not in the task status. Accept the cancellation.
            _ if cancelled => TaskError {
                code: ErrorCode::Cancelled as i32,
                message: "Cancelled while the agent was offline.".to_string(),
                ..Default::default()
            },
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            _ => TaskError {
                code: ErrorCode::Failed as i32,
                message: "Agent restarted and could not resume the task.".to_string(),
                ..Default::default()
            },
        };
        let code = error.code().as_str_name();

        // Read status_version from GetTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        let status_update = StatusUpdate {
            version: Some(TaskVersion {
                task_id: task_id.clone(),
                status_version: version.status_version + 1,
                ..Default::default()
            }),
            status: Some(TaskStatus {
                status: Status::DoneNotOk as i32,
                task_error: Some(error),
                ..Default::default()
            }),
            author: Some(author.clone()),
            ..Default::default()
        };
        client
            .update_status(Request::new(UpdateStatusRequest {
                status_update: Some(status_update),
            }))
            .await?;
        println!("Closed task {} with {}", task_id, code);
        untrack_task(task_ids, &task_id)?;
    }
    Ok(())
}

fn auth_interceptor(
    auth_header: MetadataValue<Ascii>,
    sandbox_header: MetadataValue<Ascii>,
) -> Interceptor {
    Box::new(move |mut req: Request<()>| {
        req.metadata_mut()
            .insert("authorization", auth_header.clone());
        req.metadata_mut()
            .insert("anduril-sandbox-authorization", sandbox_header.clone());
        Ok(req)
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    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");
    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables");
        std::process::exit(1);
    }

    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

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

    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<Ascii> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<Ascii> = format!("Bearer {}", sandboxes_token).parse()?;

    // All three clients share the same channel and inject the same auth metadata.
    let mut video_client: VideoClient = VideoManagerApiClient::with_interceptor(
        channel.clone(),
        auth_interceptor(auth_header.clone(), sandbox_header.clone()),
    );
    let mut entity_client: EntityClient = EntityManagerApiClient::with_interceptor(
        channel.clone(),
        auth_interceptor(auth_header.clone(), sandbox_header.clone()),
    );
    let mut task_client: TaskClient = TaskManagerApiClient::with_interceptor(
        channel,
        auth_interceptor(auth_header, sandbox_header),
    );

    let mut task_ids = load_task_ids()?;
    let result: Result<(), Box<dyn std::error::Error>> = async {
        reconnect_video(&mut video_client).await?;
        publish_entity(&mut entity_client).await?;
        resolve_tracked_tasks(&mut task_client, &mut task_ids).await?;
        Ok(())
    }
    .await;
    if let Err(error) = result {
        eprintln!("Failed to recover after restart: {}", error);
        std::process::exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // track_task and untrack_task as tasks start and finish.
    Ok(())
}

```

Call `GetIngressStream` with your ingress ID:

* **Found**: Reuse the stream. For SRT and MPEG-TS, resume pushing to the stream's `url`. For RTSP, Lattice pulls from the source URL you gave it, so make sure your source serves video there again.
* **Not found** (`404` in REST, `NOT_FOUND` in gRPC): Create the stream with the same ingress ID.

```go title={"Go (REST)"} startLine={112} maxLines={32}
// This Go example uses the Lattice REST SDK (lattice-sdk-go) to recover an integration's video
// stream, entity, and tasks after the integration restarts.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"maps"
	"net/http"
	"os"
	"path/filepath"
	"slices"
	"time"

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

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"

// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"

// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()

const (
	// RTSP source that Lattice pulls video from. Replace before running.
	rtspURL = "rtsp://<rtsp-host>:<port>/cam"
	// Local file that stores the IDs of tasks this agent is executing.
	stateFile = "agent_state.json"
)

var terminalStatuses = map[Lattice.TaskStatusStatus]bool{
	Lattice.TaskStatusStatusStatusDoneOk:    true,
	Lattice.TaskStatusStatusStatusDoneNotOk: true,
}

type agentState struct {
	TaskIDs []string `json:"task_ids"`
}

func loadTaskIDs() (map[string]bool, error) {
	taskIDs := map[string]bool{}
	data, err := os.ReadFile(stateFile)
	if errors.Is(err, os.ErrNotExist) {
		return taskIDs, nil
	}
	if err != nil {
		return nil, err
	}
	var state agentState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	for _, taskID := range state.TaskIDs {
		taskIDs[taskID] = true
	}
	return taskIDs, nil
}

func saveTaskIDs(taskIDs map[string]bool) error {
	ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
	slices.Sort(ids)
	data, err := json.Marshal(agentState{TaskIDs: ids})
	if err != nil {
		return err
	}
	// Write to a temporary file, then rename it over the original. A power loss during the
	// write leaves the previous file intact instead of a truncated one.
	f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	if _, err := f.Write(data); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), stateFile)
}

// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
	taskIDs[taskID] = true
	return saveTaskIDs(taskIDs)
}

// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
	delete(taskIDs, taskID)
	return saveTaskIDs(taskIDs)
}

func reconnectVideo(ctx context.Context, client *client.Client) error {
	response, err := client.Video.GetIngressStream(ctx, &Lattice.GetIngressStreamRequest{
		IngressID: ingressID,
	})
	var apiErr *core.APIError
	if err == nil {
		// The stream survived the restart. Reuse it instead of creating a duplicate.
		status := ""
		if s := response.GetIngressStream().GetStatus(); s != nil {
			status = string(*s)
		}
		fmt.Printf("Reusing stream %s with status %s\n", ingressID, status)
		return nil
	}
	if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
		return err
	}

	// Lattice returns not found both for a stream that never existed and for one that was deleted.
	_, err = client.Video.CreateIngressStream(ctx, &Lattice.CreateIngressStreamRequest{
		IngressID: Lattice.String(ingressID),
		Title:     Lattice.String(assetName),
		Rtsp: &Lattice.RtspSettings{
			URL: Lattice.String(rtspURL),
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Created stream %s\n", ingressID)
	return nil
}

func publishEntity(ctx context.Context, client *client.Client) error {
	now := time.Now().UTC()
	_, err := client.Entities.PublishEntity(ctx, &Lattice.Entity{
		EntityID:   Lattice.String(entityID),
		IsLive:     Lattice.Bool(true),
		ExpiryTime: Lattice.Time(now.Add(5 * time.Minute)),
		Aliases:    &Lattice.Aliases{Name: Lattice.String(assetName)},
		MilView: &Lattice.MilView{
			Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
			Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
		},
		Ontology: &Lattice.Ontology{
			Template:     Lattice.OntologyTemplateTemplateAsset.Ptr(),
			PlatformType: Lattice.String("CAMERA"),
		},
		Location: &Lattice.Location{
			Position: &Lattice.Position{
				LatitudeDegrees:  Lattice.Float64(33.6411),
				LongitudeDegrees: Lattice.Float64(-117.9187),
			},
		},
		// Because ingressID never changes, the entity can reference the stream on every publish.
		Media: &Lattice.Media{Media: []*Lattice.MediaItem{{
			ItemIdentifier: Lattice.String(ingressID),
			Type:           Lattice.MediaItemTypeMediaTypeVideo.Ptr(),
		}}},
		// Include every other component your integration publishes, such as its TaskCatalog.
		Provenance: &Lattice.Provenance{
			IntegrationName:  Lattice.String("my-integration"),
			DataType:         Lattice.String("asset"),
			SourceUpdateTime: Lattice.Time(now),
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Republished entity %s\n", entityID)
	return nil
}

func resolveTrackedTasks(ctx context.Context, client *client.Client, taskIDs map[string]bool) error {
	author := &Lattice.Principal{System: &Lattice.System{EntityID: Lattice.String(entityID)}}
	for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
		task, err := client.Tasks.GetTask(ctx, &Lattice.GetTaskRequest{TaskID: taskID})
		var apiErr *core.APIError
		if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
			// The task no longer exists in Lattice, so there's nothing to resolve.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
		if task.Status == nil || task.Status.Status == nil || task.Version == nil || task.Version.StatusVersion == nil {
			fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
			continue
		}

		status := *task.Status.Status
		if terminalStatuses[status] {
			// An operator or another system closed the task while the agent was offline.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}

		var taskError *Lattice.TaskError
		cancelled := status == Lattice.TaskStatusStatusStatusCancelRequested ||
			(task.GetDeliveryState().GetStatus() != nil &&
				*task.GetDeliveryState().GetStatus() == Lattice.DeliveryStateStatusDeliveryStatusPendingCancel)
		if cancelled {
			// An operator cancelled the task while the agent was offline. Lattice records the cancel
			// in delivery_state, not in the task status. Accept the cancellation.
			taskError = &Lattice.TaskError{
				Code:    Lattice.TaskErrorCodeErrorCodeCancelled.Ptr(),
				Message: Lattice.String("Cancelled while the agent was offline."),
			}
		} else {
			// The agent lost its execution context, so report the task as failed rather than
			// leave it active with nothing working on it.
			taskError = &Lattice.TaskError{
				Code:    Lattice.TaskErrorCodeErrorCodeFailed.Ptr(),
				Message: Lattice.String("Agent restarted and could not resume the task."),
			}
		}

		// Read the status version from GetTask, not from local state: the status might have
		// changed while the agent was offline, and Lattice ignores updates with a stale version.
		statusVersion := *task.Version.StatusVersion + 1
		_, err = client.Tasks.UpdateTaskStatus(ctx, &Lattice.TaskStatusUpdate{
			TaskID:        taskID,
			StatusVersion: &statusVersion,
			NewStatus: &Lattice.TaskStatus{
				Status:    Lattice.TaskStatusStatusStatusDoneNotOk.Ptr(),
				TaskError: taskError,
			},
			Author: author,
		})
		if err != nil {
			return err
		}
		fmt.Printf("Closed task %s with %s\n", taskID, *taskError.Code)
		if err := untrackTask(taskIDs, taskID); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	// Get environment variables
	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")

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

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

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

	ctx := context.Background()

	taskIDs, err := loadTaskIDs()
	if err != nil {
		fmt.Printf("Failed to load saved task IDs: %v\n", err)
		os.Exit(1)
	}
	if err := reconnectVideo(ctx, LatticeClient); err != nil {
		fmt.Printf("Failed to reconnect video: %v\n", err)
		os.Exit(1)
	}
	if err := publishEntity(ctx, LatticeClient); err != nil {
		fmt.Printf("Failed to republish entity: %v\n", err)
		os.Exit(1)
	}
	if err := resolveTrackedTasks(ctx, LatticeClient, taskIDs); err != nil {
		fmt.Printf("Failed to resolve tracked tasks: %v\n", err)
		os.Exit(1)
	}

	// Recovery is complete. Start your regular publish loop and agent stream here, and call
	// trackTask and untrackTask as tasks start and finish.
}

```

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

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.core.LatticeApiException;
import com.anduril.resources.tasks.requests.TaskStatusUpdate;
import com.anduril.resources.video.requests.CreateIngressStreamRequest;
import com.anduril.types.Aliases;
import com.anduril.types.DeliveryState;
import com.anduril.types.DeliveryStateStatus;
import com.anduril.types.Entity;
import com.anduril.types.Location;
import com.anduril.types.Media;
import com.anduril.types.MediaItem;
import com.anduril.types.MediaItemType;
import com.anduril.types.MilView;
import com.anduril.types.MilViewDisposition;
import com.anduril.types.MilViewEnvironment;
import com.anduril.types.Ontology;
import com.anduril.types.OntologyTemplate;
import com.anduril.types.Position;
import com.anduril.types.Principal;
import com.anduril.types.Provenance;
import com.anduril.types.RtspSettings;
import com.anduril.types.Task;
import com.anduril.types.TaskError;
import com.anduril.types.TaskErrorCode;
import com.anduril.types.TaskStatus;
import com.anduril.types.TaskStatusStatus;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * Recovers an integration's video stream, entity, and tasks with the Lattice SDK after the
 * integration restarts.
 */
public class HandleRestarts {
    // A name that is unique to this asset and never changes, such as a serial number read from
    // hardware or configuration. Replace before running.
    private static final String ASSET_NAME = "<ASSET-NAME>";
    // The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
    // so it's the same after every restart.
    private static final String INGRESS_ID = ASSET_NAME + ".cam";
    // The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
    // and in every language.
    // NAMESPACE_URL is the standard RFC 9562 URL namespace.
    private static final UUID NAMESPACE_URL = UUID.fromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8");
    private static final String ENTITY_ID = uuid5(NAMESPACE_URL, "urn:my-integration:" + ASSET_NAME).toString();
    // RTSP source that Lattice pulls video from. Replace before running.
    private static final String RTSP_URL = "rtsp://<rtsp-host>:<port>/cam";
    // Local file that stores the IDs of tasks this agent is executing.
    private static final Path STATE_FILE = Path.of("agent_state.json");

    private static final List<TaskStatusStatus> TERMINAL_STATUSES =
        List.of(TaskStatusStatus.STATUS_DONE_OK, TaskStatusStatus.STATUS_DONE_NOT_OK);

    private static final ObjectMapper JSON = new ObjectMapper();

    private static Set<String> loadTaskIds() throws IOException {
        Set<String> taskIds = new HashSet<>();
        if (!Files.exists(STATE_FILE)) {
            return taskIds;
        }
        for (JsonNode taskId : JSON.readTree(STATE_FILE.toFile()).path("task_ids")) {
            taskIds.add(taskId.asText());
        }
        return taskIds;
    }

    private static void saveTaskIds(Set<String> taskIds) throws IOException {
        // Write to a temporary file, then rename it over the original. A power loss during the
        // write leaves the previous file intact instead of a truncated one.
        Path target = STATE_FILE.toAbsolutePath();
        Path temp = Files.createTempFile(target.getParent(), "agent_state", ".tmp");
        ObjectNode state = JSON.createObjectNode();
        ArrayNode ids = state.putArray("task_ids");
        for (String taskId : new TreeSet<>(taskIds)) {
            ids.add(taskId);
        }
        try (FileChannel channel = FileChannel.open(temp, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(JSON.writeValueAsBytes(state)));
            channel.force(true);
        }
        Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE);
    }

    private static void trackTask(Set<String> taskIds, String taskId) throws IOException {
        // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
        taskIds.add(taskId);
        saveTaskIds(taskIds);
    }

    private static void untrackTask(Set<String> taskIds, String taskId) throws IOException {
        // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
        taskIds.remove(taskId);
        saveTaskIds(taskIds);
    }

    private static void reconnectVideo(Lattice client) {
        try {
            String status = client.video().getIngressStream(INGRESS_ID).getIngressStream()
                .flatMap(stream -> stream.getStatus()).map(Object::toString).orElse("");
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            System.out.println("Reusing stream " + INGRESS_ID + " with status " + status);
            return;
        } catch (LatticeApiException e) {
            if (e.statusCode() != 404) {
                throw e;
            }
        }

        // Lattice returns not found both for a stream that never existed and for one that was deleted.
        client.video().createIngressStream(CreateIngressStreamRequest.builder()
            .ingressId(INGRESS_ID)
            .title(ASSET_NAME)
            .rtsp(RtspSettings.builder()
                .url(RTSP_URL)
                .build())
            .build());
        System.out.println("Created stream " + INGRESS_ID);
    }

    private static void publishEntity(Lattice client) {
        OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
        client.entities().publishEntity(Entity.builder()
            .entityId(ENTITY_ID)
            .isLive(true)
            .expiryTime(now.plusMinutes(5))
            .aliases(Aliases.builder().name(ASSET_NAME).build())
            .milView(MilView.builder()
                .disposition(MilViewDisposition.DISPOSITION_FRIENDLY)
                .environment(MilViewEnvironment.ENVIRONMENT_LAND)
                .build())
            .ontology(Ontology.builder().template(OntologyTemplate.TEMPLATE_ASSET).platformType("CAMERA").build())
            .location(Location.builder()
                .position(Position.builder().latitudeDegrees(33.6411).longitudeDegrees(-117.9187).build())
                .build())
            // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
            .media(Media.builder()
                .media(List.of(MediaItem.builder().itemIdentifier(INGRESS_ID).type(MediaItemType.MEDIA_TYPE_VIDEO).build()))
                .build())
            // Include every other component your integration publishes, such as its TaskCatalog.
            .provenance(Provenance.builder()
                .integrationName("my-integration")
                .dataType("asset")
                .sourceUpdateTime(now)
                .build())
            .build());
        System.out.println("Republished entity " + ENTITY_ID);
    }

    private static void resolveTrackedTasks(Lattice client, Set<String> taskIds) throws IOException {
        Principal author = Principal.builder()
            .system(com.anduril.types.System.builder().entityId(ENTITY_ID).build())
            .build();
        for (String taskId : new TreeSet<>(taskIds)) {
            Task task;
            try {
                task = client.tasks().getTask(taskId);
            } catch (LatticeApiException e) {
                if (e.statusCode() != 404) {
                    throw e;
                }
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrackTask(taskIds, taskId);
                continue;
            }
            if (task.getStatus().isEmpty() || task.getStatus().get().getStatus().isEmpty()
                    || task.getVersion().isEmpty() || task.getVersion().get().getStatusVersion().isEmpty()) {
                System.out.println("Task " + taskId + " is missing its status or version. Skipping.");
                continue;
            }
            TaskStatusStatus status = task.getStatus().get().getStatus().get();
            int statusVersion = task.getVersion().get().getStatusVersion().get();

            if (TERMINAL_STATUSES.contains(status)) {
                // An operator or another system closed the task while the agent was offline.
                untrackTask(taskIds, taskId);
                continue;
            }

            TaskError error;
            boolean pendingCancel = task.getDeliveryState().flatMap(DeliveryState::getStatus)
                .map(DeliveryStateStatus.DELIVERY_STATUS_PENDING_CANCEL::equals).orElse(false);
            if (status.equals(TaskStatusStatus.STATUS_CANCEL_REQUESTED) || pendingCancel) {
                // An operator cancelled the task while the agent was offline. Lattice records the cancel
                // in deliveryState, not in the task status. Accept the cancellation.
                error = TaskError.builder()
                    .code(TaskErrorCode.ERROR_CODE_CANCELLED)
                    .message("Cancelled while the agent was offline.")
                    .build();
            } else {
                // The agent lost its execution context, so report the task as failed rather than
                // leave it active with nothing working on it.
                error = TaskError.builder()
                    .code(TaskErrorCode.ERROR_CODE_FAILED)
                    .message("Agent restarted and could not resume the task.")
                    .build();
            }

            // Read the status version from GetTask, not from local state: the status might have
            // changed while the agent was offline, and Lattice ignores updates with a stale version.
            client.tasks().updateTaskStatus(taskId, TaskStatusUpdate.builder()
                .statusVersion(statusVersion + 1)
                .newStatus(TaskStatus.builder()
                    .status(TaskStatusStatus.STATUS_DONE_NOT_OK)
                    .taskError(error)
                    .build())
                .author(author)
                .build());
            System.out.println("Closed task " + taskId + " with " + error.getCode().map(Object::toString).orElse(""));
            untrackTask(taskIds, taskId);
        }
    }

    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 and ensure the endpoint has its scheme
        if (isBlank(endpoint) || isBlank(environmentToken) || isBlank(sandboxesToken)) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        // Create Lattice client with Sandbox authentication
        Lattice client = Lattice.builder()
            .url(endpoint)
            .token(environmentToken)
            .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
            .build();

        try {
            Set<String> taskIds = loadTaskIds();
            reconnectVideo(client);
            publishEntity(client);
            resolveTrackedTasks(client, taskIds);
        } catch (Exception e) {
            System.err.println("Failed to recover after restart: " + e.getMessage());
            System.exit(1);
        }

        // Recovery is complete. Start your regular publish loop and agent stream here, and call
        // trackTask and untrackTask as tasks start and finish.
    }

    private static boolean isBlank(String value) {
        return value == null || value.isEmpty();
    }

    /**
     * Returns a name-based version 5 UUID, which is the same every time for the same namespace and name.
     */
    private static UUID uuid5(UUID namespace, String name) {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            sha1.update(ByteBuffer.allocate(16)
                .putLong(namespace.getMostSignificantBits())
                .putLong(namespace.getLeastSignificantBits())
                .array());
            sha1.update(name.getBytes(StandardCharsets.UTF_8));
            byte[] hash = sha1.digest();
            hash[6] = (byte) ((hash[6] & 0x0f) | 0x50); // Version 5
            hash[8] = (byte) ((hash[8] & 0x3f) | 0x80); // RFC 9562 variant
            ByteBuffer bytes = ByteBuffer.wrap(hash, 0, 16);
            return new UUID(bytes.getLong(), bytes.getLong());
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("SHA-1 is unavailable", e);
        }
    }
}

```

```py title={"Python (REST)"} startLine={77} maxLines={17}
# This Python example uses the Lattice REST SDK (anduril-lattice-sdk) to recover an integration's
# video stream, entity, and tasks after the integration restarts.

import json
import os
import sys
import tempfile
import uuid
from datetime import datetime, timedelta, timezone

from anduril import (
    Aliases,
    Lattice,
    Location,
    Media,
    MediaItem,
    MilView,
    Ontology,
    Position,
    Principal,
    Provenance,
    RtspSettings,
    System,
    TaskError,
    TaskStatus,
)
from anduril.core import ApiError

# A name that is unique to this asset and never changes, such as a serial number read from
# hardware or configuration. Replace before running.
ASSET_NAME = "<ASSET-NAME>"
# The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
# so it's the same after every restart.
INGRESS_ID = f"{ASSET_NAME}.cam"
# The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
# and in every language.
ENTITY_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:my-integration:{ASSET_NAME}"))
# RTSP source that Lattice pulls video from. Replace before running.
RTSP_URL = "rtsp://<rtsp-host>:<port>/cam"
# Local file that stores the IDs of tasks this agent is executing.
STATE_FILE = "agent_state.json"

TERMINAL_STATUSES = {"STATUS_DONE_OK", "STATUS_DONE_NOT_OK"}


def load_task_ids():
    try:
        with open(STATE_FILE) as f:
            return set(json.load(f)["task_ids"])
    except FileNotFoundError:
        return set()


def save_task_ids(task_ids):
    # Write to a temporary file, then rename it over the original. A power loss during the
    # write leaves the previous file intact instead of a truncated one.
    directory = os.path.dirname(os.path.abspath(STATE_FILE))
    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f:
        json.dump({"task_ids": sorted(task_ids)}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(f.name, STATE_FILE)


def track_task(task_ids, task_id):
    # Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.add(task_id)
    save_task_ids(task_ids)


def untrack_task(task_ids, task_id):
    # Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.discard(task_id)
    save_task_ids(task_ids)


def reconnect_video(client):
    try:
        stream = client.video.get_ingress_stream(INGRESS_ID).ingress_stream
        # The stream survived the restart. Reuse it instead of creating a duplicate.
        print(f"Reusing stream {INGRESS_ID} with status {stream.status}")
        return
    except ApiError as error:
        if error.status_code != 404:
            raise

    # Lattice returns not found both for a stream that never existed and for one that was deleted.
    client.video.create_ingress_stream(
        ingress_id=INGRESS_ID,
        title=ASSET_NAME,
        rtsp=RtspSettings(url=RTSP_URL),
    )
    print(f"Created stream {INGRESS_ID}")


def publish_entity(client):
    now = datetime.now(timezone.utc)
    client.entities.publish_entity(
        entity_id=ENTITY_ID,
        is_live=True,
        expiry_time=now + timedelta(minutes=5),
        aliases=Aliases(name=ASSET_NAME),
        mil_view=MilView(disposition="DISPOSITION_FRIENDLY", environment="ENVIRONMENT_LAND"),
        ontology=Ontology(template="TEMPLATE_ASSET", platform_type="CAMERA"),
        location=Location(position=Position(latitude_degrees=33.6411, longitude_degrees=-117.9187)),
        # Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media=Media(media=[MediaItem(item_identifier=INGRESS_ID, type="MEDIA_TYPE_VIDEO")]),
        # Include every other component your integration publishes, such as its TaskCatalog.
        provenance=Provenance(
            integration_name="my-integration",
            data_type="asset",
            source_update_time=now,
        ),
    )
    print(f"Republished entity {ENTITY_ID}")


def resolve_tracked_tasks(client, task_ids):
    author = Principal(system=System(entity_id=ENTITY_ID))
    for task_id in sorted(task_ids):
        try:
            task = client.tasks.get_task(task_id)
        except ApiError as error:
            if error.status_code != 404:
                raise
            # The task no longer exists in Lattice, so there's nothing to resolve.
            untrack_task(task_ids, task_id)
            continue
        if not task.status or not task.version or task.version.status_version is None:
            print(f"Task {task_id} is missing its status or version. Skipping.")
            continue

        if task.status.status in TERMINAL_STATUSES:
            # An operator or another system closed the task while the agent was offline.
            untrack_task(task_ids, task_id)
            continue

        pending_cancel = task.delivery_state and task.delivery_state.status == "DELIVERY_STATUS_PENDING_CANCEL"
        if task.status.status == "STATUS_CANCEL_REQUESTED" or pending_cancel:
            # An operator cancelled the task while the agent was offline. Lattice records the cancel
            # in delivery_state, not in the task status. Accept the cancellation.
            error = TaskError(code="ERROR_CODE_CANCELLED", message="Cancelled while the agent was offline.")
        else:
            # The agent lost its execution context, so report the task as failed rather than
            # leave it active with nothing working on it.
            error = TaskError(code="ERROR_CODE_FAILED", message="Agent restarted and could not resume the task.")

        # Read status_version from GetTask, not from local state: the status might have
        # changed while the agent was offline, and Lattice ignores updates with a stale version.
        client.tasks.update_task_status(
            task_id,
            status_version=task.version.status_version + 1,
            new_status=TaskStatus(status="STATUS_DONE_NOT_OK", task_error=error),
            author=author,
        )
        print(f"Closed task {task_id} with {error.code}")
        untrack_task(task_ids, task_id)


def main():
    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)

    client = Lattice(
        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}"},
    )

    task_ids = load_task_ids()
    try:
        reconnect_video(client)
        publish_entity(client)
        resolve_tracked_tasks(client, task_ids)
    except Exception as error:
        print(f"Failed to recover after restart: {error}", file=sys.stderr)
        sys.exit(1)

    # Recovery is complete. Start your regular publish loop and agent stream here, and call
    # track_task and untrack_task as tasks start and finish.


if __name__ == "__main__":
    main()

```

```ts title={"TypeScript (REST)"} startLine={62} maxLines={20}
// This TypeScript example uses the Lattice REST SDK (@anduril-industries/lattice-sdk) to recover an
// integration's video stream, entity, and tasks after the integration restarts.

import * as fs from "node:fs";
import * as path from "node:path";
import { Lattice, LatticeClient, LatticeError } from "@anduril-industries/lattice-sdk";
import { v5 as uuidv5 } from "uuid";

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
const INGRESS_ID = `${ASSET_NAME}.cam`;
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
const ENTITY_ID = uuidv5(`urn:my-integration:${ASSET_NAME}`, uuidv5.URL);
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE = "agent_state.json";

const TERMINAL_STATUSES = new Set<string | undefined>(["STATUS_DONE_OK", "STATUS_DONE_NOT_OK"]);

function loadTaskIds(): Set<string> {
    try {
        return new Set<string>(JSON.parse(fs.readFileSync(STATE_FILE, "utf8")).task_ids);
    } catch (error) {
        if ((error as NodeJS.ErrnoException).code === "ENOENT") {
            return new Set<string>();
        }
        throw error;
    }
}

function saveTaskIds(taskIds: Set<string>) {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    const tempFile = path.join(path.dirname(path.resolve(STATE_FILE)), `.${path.basename(STATE_FILE)}.${process.pid}.tmp`);
    const fd = fs.openSync(tempFile, "w");
    try {
        fs.writeSync(fd, JSON.stringify({ task_ids: [...taskIds].sort() }));
        fs.fsyncSync(fd);
    } finally {
        fs.closeSync(fd);
    }
    fs.renameSync(tempFile, STATE_FILE);
}

export function trackTask(taskIds: Set<string>, taskId: string) {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    taskIds.add(taskId);
    saveTaskIds(taskIds);
}

export function untrackTask(taskIds: Set<string>, taskId: string) {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    taskIds.delete(taskId);
    saveTaskIds(taskIds);
}

async function reconnectVideo(client: LatticeClient) {
    try {
        const { ingressStream } = await client.video.getIngressStream({ ingressId: INGRESS_ID });
        // The stream survived the restart. Reuse it instead of creating a duplicate.
        console.log(`Reusing stream ${INGRESS_ID} with status ${ingressStream?.status}`);
        return;
    } catch (error) {
        if (!(error instanceof LatticeError && error.statusCode === 404)) {
            throw error;
        }
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    await client.video.createIngressStream({
        ingressId: INGRESS_ID,
        title: ASSET_NAME,
        rtsp: { url: RTSP_URL },
    });
    console.log(`Created stream ${INGRESS_ID}`);
}

async function publishEntity(client: LatticeClient) {
    const now = new Date();
    await client.entities.publishEntity({
        entityId: ENTITY_ID,
        isLive: true,
        expiryTime: new Date(now.getTime() + 5 * 60 * 1000).toISOString(),
        aliases: { name: ASSET_NAME },
        milView: { disposition: "DISPOSITION_FRIENDLY", environment: "ENVIRONMENT_LAND" },
        ontology: { template: "TEMPLATE_ASSET", platformType: "CAMERA" },
        location: { position: { latitudeDegrees: 33.6411, longitudeDegrees: -117.9187 } },
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: { media: [{ itemIdentifier: INGRESS_ID, type: "MEDIA_TYPE_VIDEO" }] },
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: {
            integrationName: "my-integration",
            dataType: "asset",
            sourceUpdateTime: now.toISOString(),
        },
    });
    console.log(`Republished entity ${ENTITY_ID}`);
}

async function resolveTrackedTasks(client: LatticeClient, taskIds: Set<string>) {
    const author = { system: { entityId: ENTITY_ID } };
    for (const taskId of [...taskIds].sort()) {
        let task: Lattice.Task;
        try {
            task = await client.tasks.getTask({ taskId });
        } catch (error) {
            if (!(error instanceof LatticeError && error.statusCode === 404)) {
                throw error;
            }
            // The task no longer exists in Lattice, so there's nothing to resolve.
            untrackTask(taskIds, taskId);
            continue;
        }
        const statusVersion = task.version?.statusVersion;
        if (!task.status || statusVersion === undefined) {
            console.log(`Task ${taskId} is missing its status or version. Skipping.`);
            continue;
        }

        if (TERMINAL_STATUSES.has(task.status.status)) {
            // An operator or another system closed the task while the agent was offline.
            untrackTask(taskIds, taskId);
            continue;
        }

        let taskError: Lattice.TaskError;
        const pendingCancel = task.deliveryState?.status === "DELIVERY_STATUS_PENDING_CANCEL";
        if (task.status.status === "STATUS_CANCEL_REQUESTED" || pendingCancel) {
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in deliveryState, not in the task status. Accept the cancellation.
            taskError = { code: "ERROR_CODE_CANCELLED", message: "Cancelled while the agent was offline." };
        } else {
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            taskError = { code: "ERROR_CODE_FAILED", message: "Agent restarted and could not resume the task." };
        }

        // Read statusVersion from getTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        await client.tasks.updateTaskStatus({
            taskId,
            statusVersion: statusVersion + 1,
            newStatus: { status: "STATUS_DONE_NOT_OK", taskError },
            author,
        });
        console.log(`Closed task ${taskId} with ${taskError.code}`);
        untrackTask(taskIds, taskId);
    }
}

async function App() {
    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,
            // Remove the following if you are not developing on Sandboxes.
            headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}`  }
        }
    );

    const taskIds = loadTaskIds();
    try {
        await reconnectVideo(client);
        await publishEntity(client);
        await resolveTrackedTasks(client, taskIds);
    } catch (error) {
        console.error(`Failed to recover after restart: ${error}`);
        process.exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // trackTask and untrackTask as tasks start and finish.
}

App();

```

```rs title={"Rust (REST)"} startLine={66} maxLines={30}
// This Rust example uses the Lattice REST SDK (anduril-lattice-sdk) to recover an integration's
// video stream, entity, and tasks after the integration restarts.

// track_task is called from the main loop you add after recovery.
#![allow(dead_code)]

use anduril_lattice_sdk::prelude::*;

use std::collections::BTreeSet;
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::sync::LazyLock;
use uuid::Uuid;

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME: &str = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
static INGRESS_ID: LazyLock<String> = LazyLock::new(|| format!("{}.cam", ASSET_NAME));
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
static ENTITY_ID: LazyLock<String> = LazyLock::new(|| {
    let name = format!("urn:my-integration:{}", ASSET_NAME);
    Uuid::new_v5(&Uuid::NAMESPACE_URL, name.as_bytes()).to_string()
});
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL: &str = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE: &str = "agent_state.json";

fn load_task_ids() -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
    let contents = match fs::read_to_string(STATE_FILE) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(error.into()),
    };
    let state: Value = contents.parse()?;
    let task_ids = state["task_ids"].as_array().ok_or("task_ids is missing")?;
    Ok(task_ids.iter().filter_map(|id| id.as_str().map(String::from)).collect())
}

fn save_task_ids(task_ids: &BTreeSet<String>) -> std::io::Result<()> {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    let temp_path = format!("{}.tmp", STATE_FILE);
    let mut file = File::create(&temp_path)?;
    file.write_all(json!({ "task_ids": task_ids }).to_string().as_bytes())?;
    file.sync_all()?;
    fs::rename(&temp_path, STATE_FILE)
}

fn track_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.insert(task_id.to_string());
    save_task_ids(task_ids)
}

fn untrack_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.remove(task_id);
    save_task_ids(task_ids)
}

async fn reconnect_video(client: &Lattice) -> Result<(), ApiError> {
    match client.video.get_ingress_stream(&INGRESS_ID, None).await {
        Ok(response) => {
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            let status = response
                .ingress_stream
                .and_then(|stream| stream.status)
                .map(|status| status.to_string())
                .unwrap_or_default();
            println!("Reusing stream {} with status {}", *INGRESS_ID, status);
            return Ok(());
        }
        Err(ApiError::NotFoundError { .. }) => {}
        Err(error) => return Err(error),
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    let request = CreateIngressStreamRequest {
        ingress_id: Some(INGRESS_ID.clone()),
        title: Some(ASSET_NAME.to_string()),
        rtsp: Some(RtspSettings {
            url: Some(RTSP_URL.to_string()),
            ..Default::default()
        }),
        ..Default::default()
    };
    client.video.create_ingress_stream(&request, None).await?;
    println!("Created stream {}", *INGRESS_ID);
    Ok(())
}

async fn publish_entity(client: &Lattice) -> Result<(), ApiError> {
    let now = Utc::now();
    let entity = Entity {
        entity_id: Some(ENTITY_ID.clone()),
        is_live: Some(true),
        expiry_time: Some((now + chrono::Duration::minutes(5)).fixed_offset()),
        aliases: Some(Aliases {
            name: Some(ASSET_NAME.to_string()),
            ..Default::default()
        }),
        mil_view: Some(MilView {
            disposition: Some(MilViewDisposition::DispositionFriendly),
            environment: Some(MilViewEnvironment::EnvironmentLand),
            ..Default::default()
        }),
        ontology: Some(Ontology {
            template: Some(OntologyTemplate::TemplateAsset),
            platform_type: Some("CAMERA".to_string()),
            ..Default::default()
        }),
        location: Some(Location {
            position: Some(Position {
                latitude_degrees: Some(33.6411),
                longitude_degrees: Some(-117.9187),
                ..Default::default()
            }),
            ..Default::default()
        }),
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: Some(Media {
            media: Some(vec![MediaItem {
                item_identifier: Some(INGRESS_ID.clone()),
                r#type: Some(MediaItemType::MediaTypeVideo),
                ..Default::default()
            }]),
            ..Default::default()
        }),
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: Some(Provenance {
            integration_name: Some("my-integration".to_string()),
            data_type: Some("asset".to_string()),
            source_update_time: Some(now.fixed_offset()),
            ..Default::default()
        }),
        ..Default::default()
    };
    client.entities.publish_entity(&entity, None).await?;
    println!("Republished entity {}", *ENTITY_ID);
    Ok(())
}

async fn resolve_tracked_tasks(
    client: &Lattice,
    task_ids: &mut BTreeSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let author = Principal {
        system: Some(System {
            entity_id: Some(ENTITY_ID.clone()),
            ..Default::default()
        }),
        ..Default::default()
    };
    for task_id in task_ids.clone() {
        let task = match client.tasks.get_task(&task_id, None).await {
            Ok(task) => task,
            Err(ApiError::NotFoundError { .. }) => {
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            Err(error) => return Err(error.into()),
        };
        let (Some(status), Some(status_version)) = (
            task.status.as_ref(),
            task.version.as_ref().and_then(|version| version.status_version),
        ) else {
            println!("Task {} is missing its status or version. Skipping.", task_id);
            continue;
        };

        let cancelled = matches!(status.status, Some(TaskStatusStatus::StatusCancelRequested))
            || matches!(
                task.delivery_state.as_ref().and_then(|state| state.status.as_ref()),
                Some(DeliveryStateStatus::DeliveryStatusPendingCancel)
            );
        let error = match status.status {
            Some(TaskStatusStatus::StatusDoneOk | TaskStatusStatus::StatusDoneNotOk) => {
                // An operator or another system closed the task while the agent was offline.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in delivery_state, not in the task status. Accept the cancellation.
            _ if cancelled => TaskError {
                code: Some(TaskErrorCode::ErrorCodeCancelled),
                message: Some("Cancelled while the agent was offline.".to_string()),
                ..Default::default()
            },
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            _ => TaskError {
                code: Some(TaskErrorCode::ErrorCodeFailed),
                message: Some("Agent restarted and could not resume the task.".to_string()),
                ..Default::default()
            },
        };
        let code = error.code.as_ref().map(|code| code.to_string()).unwrap_or_default();

        // Read status_version from GetTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        let request = TaskStatusUpdate {
            status_version: Some(status_version + 1),
            new_status: Some(TaskStatus {
                status: Some(TaskStatusStatus::StatusDoneNotOk),
                task_error: Some(error),
                ..Default::default()
            }),
            author: Some(author.clone()),
        };
        client.tasks.update_task_status(&task_id, &request, None).await?;
        println!("Closed task {} with {}", task_id, code);
        untrack_task(task_ids, &task_id)?;
    }
    Ok(())
}

#[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)?;

    let mut task_ids = load_task_ids()?;
    let result: Result<(), Box<dyn std::error::Error>> = async {
        reconnect_video(&client).await?;
        publish_entity(&client).await?;
        resolve_tracked_tasks(&client, &mut task_ids).await?;
        Ok(())
    }
    .await;
    if let Err(error) = result {
        eprintln!("Failed to recover after restart: {}", error);
        std::process::exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // track_task and untrack_task as tasks start and finish.
    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={124} 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
//
// It recovers an integration's video stream, entity, and tasks after the integration restarts.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"maps"
	"os"
	"path/filepath"
	"slices"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/taskmanager/v1/taskmanagerv1grpc"
	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/videomanager/v1/videomanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	ontologyv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/ontology/v1"
	taskmanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/taskmanager/v1"
	videomanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/videomanager/v1"

	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"

// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"

// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()

const (
	// RTSP source that Lattice pulls video from. Replace before running.
	rtspURL = "rtsp://<rtsp-host>:<port>/cam"
	// Local file that stores the IDs of tasks this agent is executing.
	stateFile = "agent_state.json"
)

var terminalStatuses = map[taskmanagerv1.Status]bool{
	taskmanagerv1.Status_STATUS_DONE_OK:     true,
	taskmanagerv1.Status_STATUS_DONE_NOT_OK: true,
}

type agentState struct {
	TaskIDs []string `json:"task_ids"`
}

func loadTaskIDs() (map[string]bool, error) {
	taskIDs := map[string]bool{}
	data, err := os.ReadFile(stateFile)
	if errors.Is(err, os.ErrNotExist) {
		return taskIDs, nil
	}
	if err != nil {
		return nil, err
	}
	var state agentState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	for _, taskID := range state.TaskIDs {
		taskIDs[taskID] = true
	}
	return taskIDs, nil
}

func saveTaskIDs(taskIDs map[string]bool) error {
	ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
	slices.Sort(ids)
	data, err := json.Marshal(agentState{TaskIDs: ids})
	if err != nil {
		return err
	}
	// Write to a temporary file, then rename it over the original. A power loss during the
	// write leaves the previous file intact instead of a truncated one.
	f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	if _, err := f.Write(data); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), stateFile)
}

// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
	taskIDs[taskID] = true
	return saveTaskIDs(taskIDs)
}

// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
	delete(taskIDs, taskID)
	return saveTaskIDs(taskIDs)
}

func reconnectVideo(ctx context.Context, client videomanagerv1grpc.VideoManagerAPIClient) error {
	response, err := client.GetIngressStream(ctx, &videomanagerv1.GetIngressStreamRequest{
		IngressId: ingressID,
	})
	if err == nil {
		// The stream survived the restart. Reuse it instead of creating a duplicate.
		fmt.Printf("Reusing stream %s with status %s\n", ingressID, response.GetIngressStream().GetStatus())
		return nil
	}
	if status.Code(err) != codes.NotFound {
		return err
	}

	// Lattice returns not found both for a stream that never existed and for one that was deleted.
	_, err = client.CreateIngressStream(ctx, &videomanagerv1.CreateIngressStreamRequest{
		IngressId: proto.String(ingressID),
		Title:     assetName,
		Ingress: &videomanagerv1.CreateIngressStreamRequest_Rtsp{
			Rtsp: &videomanagerv1.RtspSettings{
				Url: proto.String(rtspURL),
			},
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Created stream %s\n", ingressID)
	return nil
}

func publishEntity(ctx context.Context, client entitymanagerv1grpc.EntityManagerAPIClient) error {
	now := time.Now().UTC()
	_, err := client.PublishEntity(ctx, &entitymanagerv1.PublishEntityRequest{Entity: &entitymanagerv1.Entity{
		EntityId:   entityID,
		IsLive:     true,
		ExpiryTime: timestamppb.New(now.Add(5 * time.Minute)),
		Aliases:    &entitymanagerv1.Aliases{Name: assetName},
		MilView: &entitymanagerv1.MilView{
			Disposition: ontologyv1.Disposition_DISPOSITION_FRIENDLY,
			Environment: ontologyv1.Environment_ENVIRONMENT_LAND,
		},
		Ontology: &entitymanagerv1.Ontology{
			Template:     entitymanagerv1.Template_TEMPLATE_ASSET,
			PlatformType: "CAMERA",
		},
		Location: &entitymanagerv1.Location{
			Position: &entitymanagerv1.Position{
				LatitudeDegrees:  33.6411,
				LongitudeDegrees: -117.9187,
			},
		},
		// Because ingressID never changes, the entity can reference the stream on every publish.
		Media: &entitymanagerv1.Media{Media: []*entitymanagerv1.MediaItem{{
			ItemIdentifier: ingressID,
			Type:           entitymanagerv1.MediaType_MEDIA_TYPE_VIDEO,
		}}},
		// Include every other component your integration publishes, such as its TaskCatalog.
		Provenance: &entitymanagerv1.Provenance{
			IntegrationName:  "my-integration",
			DataType:         "asset",
			SourceUpdateTime: timestamppb.New(now),
		},
	}})
	if err != nil {
		return err
	}
	fmt.Printf("Republished entity %s\n", entityID)
	return nil
}

func resolveTrackedTasks(ctx context.Context, client taskmanagerv1grpc.TaskManagerAPIClient, taskIDs map[string]bool) error {
	author := &taskmanagerv1.Principal{
		Agent: &taskmanagerv1.Principal_System{
			System: &taskmanagerv1.System{EntityId: entityID},
		},
	}
	for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
		response, err := client.GetTask(ctx, &taskmanagerv1.GetTaskRequest{TaskId: taskID})
		if status.Code(err) == codes.NotFound {
			// The task no longer exists in Lattice, so there's nothing to resolve.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
		task := response.GetTask()
		if task.GetStatus() == nil || task.GetVersion() == nil {
			fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
			continue
		}

		taskStatus := task.GetStatus().GetStatus()
		if terminalStatuses[taskStatus] {
			// An operator or another system closed the task while the agent was offline.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}

		var taskError *taskmanagerv1.TaskError
		cancelled := taskStatus == taskmanagerv1.Status_STATUS_CANCEL_REQUESTED ||
			task.GetDeliveryState().GetStatus() == taskmanagerv1.DeliveryStatus_DELIVERY_STATUS_PENDING_CANCEL
		if cancelled {
			// An operator cancelled the task while the agent was offline. Lattice records the cancel
			// in delivery_state, not in the task status. Accept the cancellation.
			taskError = &taskmanagerv1.TaskError{
				Code:    taskmanagerv1.ErrorCode_ERROR_CODE_CANCELLED,
				Message: "Cancelled while the agent was offline.",
			}
		} else {
			// The agent lost its execution context, so report the task as failed rather than
			// leave it active with nothing working on it.
			taskError = &taskmanagerv1.TaskError{
				Code:    taskmanagerv1.ErrorCode_ERROR_CODE_FAILED,
				Message: "Agent restarted and could not resume the task.",
			}
		}

		// Read the status version from GetTask, not from local state: the status might have
		// changed while the agent was offline, and Lattice ignores updates with a stale version.
		_, err = client.UpdateStatus(ctx, &taskmanagerv1.UpdateStatusRequest{
			StatusUpdate: &taskmanagerv1.StatusUpdate{
				Version: &taskmanagerv1.TaskVersion{
					TaskId:        taskID,
					StatusVersion: task.GetVersion().GetStatusVersion() + 1,
				},
				Status: &taskmanagerv1.TaskStatus{
					Status:    taskmanagerv1.Status_STATUS_DONE_NOT_OK,
					TaskError: taskError,
				},
				Author: author,
			},
		})
		if err != nil {
			return err
		}
		fmt.Printf("Closed task %s with %s\n", taskID, taskError.GetCode())
		if err := untrackTask(taskIDs, taskID); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	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()

	videoClient := videomanagerv1grpc.NewVideoManagerAPIClient(conn)
	entityClient := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)
	taskClient := taskmanagerv1grpc.NewTaskManagerAPIClient(conn)

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	taskIDs, err := loadTaskIDs()
	if err != nil {
		log.Fatalf("Failed to load saved task IDs: %v", err)
	}
	if err := reconnectVideo(ctx, videoClient); err != nil {
		log.Fatalf("Failed to reconnect video: %v", err)
	}
	if err := publishEntity(ctx, entityClient); err != nil {
		log.Fatalf("Failed to republish entity: %v", err)
	}
	if err := resolveTrackedTasks(ctx, taskClient, taskIDs); err != nil {
		log.Fatalf("Failed to resolve tracked tasks: %v", err)
	}

	// Recovery is complete. Start your regular publish loop and agent stream here, and call
	// trackTask and untrackTask as tasks start and finish.
}

```

```py title={"Python (gRPC)"} startLine={92} maxLines={20}
# 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
# It recovers an integration's video stream, entity, and tasks after the integration restarts.

import json
import os
import sys
import tempfile
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from connectrpc.code import Code
from connectrpc.errors import ConnectError
from protobuf import Oneof
from protobuf.wkt import Timestamp

from anduril.entitymanager.v1.entity_pub_pb import Aliases, Entity, Provenance
from anduril.entitymanager.v1.entity_manager_api_pub_pb import PublishEntityRequest
from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.location_pub_pb import Location, Position
from anduril.entitymanager.v1.media_pub_pb import Media, MediaItem, MediaType
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.ontology.v1.type_pub_pb import Disposition, Environment
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.taskmanager.v1.task_pub_pb import (
    DeliveryStatus,
    ErrorCode,
    Principal,
    Status,
    StatusUpdate,
    System,
    TaskError,
    TaskStatus,
    TaskVersion,
)
from anduril.taskmanager.v1.task_manager_api_pub_pb import GetTaskRequest, UpdateStatusRequest
from anduril.taskmanager.v1.task_manager_api_pub_connect import TaskManagerAPIClientSync
from anduril.videomanager.v1.create_ingress_stream_request_pub_pb import CreateIngressStreamRequest
from anduril.videomanager.v1.get_ingress_stream_request_pub_pb import GetIngressStreamRequest
from anduril.videomanager.v1.rtsp_settings_pub_pb import RtspSettings
from anduril.videomanager.v1.video_manager_api_pub_connect import VideoManagerAPIClientSync

# A name that is unique to this asset and never changes, such as a serial number read from
# hardware or configuration. Replace before running.
ASSET_NAME = "<ASSET-NAME>"
# The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
# so it's the same after every restart.
INGRESS_ID = f"{ASSET_NAME}.cam"
# The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
# and in every language.
ENTITY_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:my-integration:{ASSET_NAME}"))
# RTSP source that Lattice pulls video from. Replace before running.
RTSP_URL = "rtsp://<rtsp-host>:<port>/cam"
# Local file that stores the IDs of tasks this agent is executing.
STATE_FILE = "agent_state.json"

TERMINAL_STATUSES = {Status.DONE_OK, Status.DONE_NOT_OK}


def load_task_ids():
    try:
        with open(STATE_FILE) as f:
            return set(json.load(f)["task_ids"])
    except FileNotFoundError:
        return set()


def save_task_ids(task_ids):
    # Write to a temporary file, then rename it over the original. A power loss during the
    # write leaves the previous file intact instead of a truncated one.
    directory = os.path.dirname(os.path.abspath(STATE_FILE))
    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f:
        json.dump({"task_ids": sorted(task_ids)}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(f.name, STATE_FILE)


def track_task(task_ids, task_id):
    # Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.add(task_id)
    save_task_ids(task_ids)


def untrack_task(task_ids, task_id):
    # Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.discard(task_id)
    save_task_ids(task_ids)


def reconnect_video(client):
    try:
        response = client.get_ingress_stream(GetIngressStreamRequest(ingress_id=INGRESS_ID), timeout_ms=10000)
        # The stream survived the restart. Reuse it instead of creating a duplicate.
        print(f"Reusing stream {INGRESS_ID} with status STREAM_STATUS_{response.ingress_stream.status.name}")
        return
    except ConnectError as error:
        if error.code != Code.NOT_FOUND:
            raise

    # Lattice returns not found both for a stream that never existed and for one that was deleted.
    client.create_ingress_stream(
        CreateIngressStreamRequest(
            ingress_id=INGRESS_ID,
            title=ASSET_NAME,
            ingress=Oneof("rtsp", RtspSettings(url=RTSP_URL)),
        ),
        timeout_ms=30000,
    )
    print(f"Created stream {INGRESS_ID}")


def publish_entity(client):
    now = datetime.now(timezone.utc)
    entity = Entity(
        entity_id=ENTITY_ID,
        is_live=True,
        expiry_time=Timestamp.from_datetime(now + timedelta(minutes=5)),
        aliases=Aliases(name=ASSET_NAME),
        mil_view=MilView(disposition=Disposition.FRIENDLY, environment=Environment.LAND),
        ontology=Ontology(template=Template.ASSET, platform_type="CAMERA"),
        location=Location(position=Position(latitude_degrees=33.6411, longitude_degrees=-117.9187)),
        # Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media=Media(media=[MediaItem(item_identifier=INGRESS_ID, type=MediaType.VIDEO)]),
        # Include every other component your integration publishes, such as its TaskCatalog.
        provenance=Provenance(
            integration_name="my-integration",
            data_type="asset",
            source_update_time=Timestamp.from_datetime(now),
        ),
    )
    client.publish_entity(PublishEntityRequest(entity=entity), timeout_ms=10000)
    print(f"Republished entity {ENTITY_ID}")


def resolve_tracked_tasks(client, task_ids):
    author = Principal(agent=Oneof("system", System(entity_id=ENTITY_ID)))
    for task_id in sorted(task_ids):
        try:
            task = client.get_task(GetTaskRequest(task_id=task_id), timeout_ms=10000).task
        except ConnectError as error:
            if error.code != Code.NOT_FOUND:
                raise
            # The task no longer exists in Lattice, so there's nothing to resolve.
            untrack_task(task_ids, task_id)
            continue
        if not task or not task.status or not task.version:
            print(f"Task {task_id} is missing its status or version. Skipping.")
            continue

        if task.status.status in TERMINAL_STATUSES:
            # An operator or another system closed the task while the agent was offline.
            untrack_task(task_ids, task_id)
            continue

        pending_cancel = task.delivery_state and task.delivery_state.status == DeliveryStatus.PENDING_CANCEL
        if task.status.status == Status.CANCEL_REQUESTED or pending_cancel:
            # An operator cancelled the task while the agent was offline. Lattice records the cancel
            # in delivery_state, not in the task status. Accept the cancellation.
            error = TaskError(code=ErrorCode.CANCELLED, message="Cancelled while the agent was offline.")
        else:
            # The agent lost its execution context, so report the task as failed rather than
            # leave it active with nothing working on it.
            error = TaskError(code=ErrorCode.FAILED, message="Agent restarted and could not resume the task.")

        # Read status_version from GetTask, not from local state: the status might have
        # changed while the agent was offline, and Lattice ignores updates with a stale version.
        status_update = StatusUpdate(
            version=TaskVersion(task_id=task_id, status_version=task.version.status_version + 1),
            status=TaskStatus(status=Status.DONE_NOT_OK, task_error=error),
            author=author,
        )
        client.update_status(UpdateStatusRequest(status_update=status_update), timeout_ms=10000)
        print(f"Closed task {task_id} with ERROR_CODE_{error.code.name}")
        untrack_task(task_ids, task_id)


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 clients over Connect gRPC with authentication
    video_client = create_client(VideoManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)
    entity_client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)
    task_client = create_client(TaskManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    task_ids = load_task_ids()
    try:
        reconnect_video(video_client)
        publish_entity(entity_client)
        resolve_tracked_tasks(task_client, task_ids)
    except Exception as error:
        print(f"Failed to recover after restart: {error}", file=sys.stderr)
        sys.exit(1)

    # Recovery is complete. Start your regular publish loop and agent stream here, and call
    # track_task and untrack_task as tasks start and finish.


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={104} maxLines={31}
// 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

// track_task is called from the main loop you add after recovery.
#![allow(dead_code)]

mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    Aliases, Entity, Location, Media, MediaItem, MediaType, MilView, Ontology, Position, Provenance,
    PublishEntityRequest, Template,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{Disposition, Environment};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::taskmanager::v1::{
    principal, DeliveryStatus, ErrorCode, GetTaskRequest, Principal, Status, StatusUpdate, System, TaskError,
    TaskStatus, TaskVersion, UpdateStatusRequest,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::videomanager::v1::{
    create_ingress_stream_request::Ingress, CreateIngressStreamRequest, GetIngressStreamRequest,
    RtspSettings,
};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::taskmanager::v1::tonic::task_manager_api_client::TaskManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::videomanager::v1::tonic::video_manager_api_client::VideoManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use prost_types::Timestamp;
use serde_json::{json, Value};
use tonic::metadata::{Ascii, MetadataValue};
use tonic::service::interceptor::InterceptedService;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::{Code, Request};
use uuid::Uuid;

use std::collections::BTreeSet;
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::sync::LazyLock;
use std::time::{SystemTime, UNIX_EPOCH};

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME: &str = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
static INGRESS_ID: LazyLock<String> = LazyLock::new(|| format!("{}.cam", ASSET_NAME));
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
static ENTITY_ID: LazyLock<String> = LazyLock::new(|| {
    let name = format!("urn:my-integration:{}", ASSET_NAME);
    Uuid::new_v5(&Uuid::NAMESPACE_URL, name.as_bytes()).to_string()
});
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL: &str = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE: &str = "agent_state.json";

type Interceptor = Box<dyn FnMut(Request<()>) -> Result<Request<()>, tonic::Status> + Send + Sync>;
type VideoClient = VideoManagerApiClient<InterceptedService<Channel, Interceptor>>;
type EntityClient = EntityManagerApiClient<InterceptedService<Channel, Interceptor>>;
type TaskClient = TaskManagerApiClient<InterceptedService<Channel, Interceptor>>;

fn now_timestamp() -> Timestamp {
    let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    Timestamp {
        seconds: d.as_secs() as i64,
        nanos: d.subsec_nanos() as i32,
    }
}

fn load_task_ids() -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
    let contents = match fs::read_to_string(STATE_FILE) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(error.into()),
    };
    let state: Value = contents.parse()?;
    let task_ids = state["task_ids"].as_array().ok_or("task_ids is missing")?;
    Ok(task_ids.iter().filter_map(|id| id.as_str().map(String::from)).collect())
}

fn save_task_ids(task_ids: &BTreeSet<String>) -> std::io::Result<()> {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    let temp_path = format!("{}.tmp", STATE_FILE);
    let mut file = File::create(&temp_path)?;
    file.write_all(json!({ "task_ids": task_ids }).to_string().as_bytes())?;
    file.sync_all()?;
    fs::rename(&temp_path, STATE_FILE)
}

fn track_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.insert(task_id.to_string());
    save_task_ids(task_ids)
}

fn untrack_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.remove(task_id);
    save_task_ids(task_ids)
}

async fn reconnect_video(client: &mut VideoClient) -> Result<(), tonic::Status> {
    let request = Request::new(GetIngressStreamRequest {
        ingress_id: INGRESS_ID.clone(),
    });
    match client.get_ingress_stream(request).await {
        Ok(response) => {
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            let status = response
                .into_inner()
                .ingress_stream
                .map(|stream| stream.status().as_str_name())
                .unwrap_or_default();
            println!("Reusing stream {} with status {}", *INGRESS_ID, status);
            return Ok(());
        }
        Err(status) if status.code() == Code::NotFound => {}
        Err(status) => return Err(status),
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    let request = Request::new(CreateIngressStreamRequest {
        ingress_id: Some(INGRESS_ID.clone()),
        title: ASSET_NAME.to_string(),
        ingress: Some(Ingress::Rtsp(RtspSettings {
            url: Some(RTSP_URL.to_string()),
        })),
    });
    client.create_ingress_stream(request).await?;
    println!("Created stream {}", *INGRESS_ID);
    Ok(())
}

async fn publish_entity(client: &mut EntityClient) -> Result<(), tonic::Status> {
    let now = now_timestamp();
    let entity = Entity {
        entity_id: ENTITY_ID.clone(),
        is_live: true,
        expiry_time: Some(Timestamp {
            seconds: now.seconds + 5 * 60,
            nanos: now.nanos,
        }),
        aliases: Some(Aliases {
            name: ASSET_NAME.to_string(),
            ..Default::default()
        }),
        mil_view: Some(MilView {
            disposition: Disposition::Friendly as i32,
            environment: Environment::Land as i32,
            ..Default::default()
        }),
        ontology: Some(Ontology {
            template: Template::Asset as i32,
            platform_type: "CAMERA".to_string(),
            ..Default::default()
        }),
        location: Some(Location {
            position: Some(Position {
                latitude_degrees: 33.6411,
                longitude_degrees: -117.9187,
                ..Default::default()
            }),
            ..Default::default()
        }),
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: Some(Media {
            media: vec![MediaItem {
                item_identifier: INGRESS_ID.clone(),
                r#type: MediaType::Video as i32,
                ..Default::default()
            }],
        }),
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: Some(Provenance {
            integration_name: "my-integration".to_string(),
            data_type: "asset".to_string(),
            source_update_time: Some(now),
            ..Default::default()
        }),
        ..Default::default()
    };
    client
        .publish_entity(Request::new(PublishEntityRequest {
            entity: Some(entity),
        }))
        .await?;
    println!("Republished entity {}", *ENTITY_ID);
    Ok(())
}

async fn resolve_tracked_tasks(
    client: &mut TaskClient,
    task_ids: &mut BTreeSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let author = Principal {
        agent: Some(principal::Agent::System(System {
            entity_id: ENTITY_ID.clone(),
            ..Default::default()
        })),
        ..Default::default()
    };
    for task_id in task_ids.clone() {
        let request = Request::new(GetTaskRequest {
            task_id: task_id.clone(),
            ..Default::default()
        });
        let task = match client.get_task(request).await {
            Ok(response) => response.into_inner().task,
            Err(status) if status.code() == Code::NotFound => {
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            Err(status) => return Err(status.into()),
        };
        let Some((status, version)) = task.as_ref().and_then(|task| task.status.as_ref().zip(task.version.as_ref()))
        else {
            println!("Task {} is missing its status or version. Skipping.", task_id);
            continue;
        };

        let cancelled = status.status() == Status::CancelRequested
            || task.as_ref().and_then(|task| task.delivery_state.as_ref()).map(|state| state.status())
                == Some(DeliveryStatus::PendingCancel);
        let error = match status.status() {
            Status::DoneOk | Status::DoneNotOk => {
                // An operator or another system closed the task while the agent was offline.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in delivery_state, not in the task status. Accept the cancellation.
            _ if cancelled => TaskError {
                code: ErrorCode::Cancelled as i32,
                message: "Cancelled while the agent was offline.".to_string(),
                ..Default::default()
            },
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            _ => TaskError {
                code: ErrorCode::Failed as i32,
                message: "Agent restarted and could not resume the task.".to_string(),
                ..Default::default()
            },
        };
        let code = error.code().as_str_name();

        // Read status_version from GetTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        let status_update = StatusUpdate {
            version: Some(TaskVersion {
                task_id: task_id.clone(),
                status_version: version.status_version + 1,
                ..Default::default()
            }),
            status: Some(TaskStatus {
                status: Status::DoneNotOk as i32,
                task_error: Some(error),
                ..Default::default()
            }),
            author: Some(author.clone()),
            ..Default::default()
        };
        client
            .update_status(Request::new(UpdateStatusRequest {
                status_update: Some(status_update),
            }))
            .await?;
        println!("Closed task {} with {}", task_id, code);
        untrack_task(task_ids, &task_id)?;
    }
    Ok(())
}

fn auth_interceptor(
    auth_header: MetadataValue<Ascii>,
    sandbox_header: MetadataValue<Ascii>,
) -> Interceptor {
    Box::new(move |mut req: Request<()>| {
        req.metadata_mut()
            .insert("authorization", auth_header.clone());
        req.metadata_mut()
            .insert("anduril-sandbox-authorization", sandbox_header.clone());
        Ok(req)
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    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");
    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables");
        std::process::exit(1);
    }

    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

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

    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<Ascii> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<Ascii> = format!("Bearer {}", sandboxes_token).parse()?;

    // All three clients share the same channel and inject the same auth metadata.
    let mut video_client: VideoClient = VideoManagerApiClient::with_interceptor(
        channel.clone(),
        auth_interceptor(auth_header.clone(), sandbox_header.clone()),
    );
    let mut entity_client: EntityClient = EntityManagerApiClient::with_interceptor(
        channel.clone(),
        auth_interceptor(auth_header.clone(), sandbox_header.clone()),
    );
    let mut task_client: TaskClient = TaskManagerApiClient::with_interceptor(
        channel,
        auth_interceptor(auth_header, sandbox_header),
    );

    let mut task_ids = load_task_ids()?;
    let result: Result<(), Box<dyn std::error::Error>> = async {
        reconnect_video(&mut video_client).await?;
        publish_entity(&mut entity_client).await?;
        resolve_tracked_tasks(&mut task_client, &mut task_ids).await?;
        Ok(())
    }
    .await;
    if let Err(error) = result {
        eprintln!("Failed to recover after restart: {}", error);
        std::process::exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // track_task and untrack_task as tasks start and finish.
    Ok(())
}

```

Reconnect the stream before you republish the entity, so the entity's `media` never points at a missing stream.

> **Keep your stream**
>
> Don't delete your stream when your integration stops or loses its link. Delete it only when you retire the camera.
> `GetIngressStream` returns not found for a deleted stream, so your integration would create it again on the next startup. If operators need to turn a feed off, give them a setting in your integration instead.

#### Republish your entity

Derive the entity ID from the same asset name. A version 5 UUID is a hash of its input, so every language produces the same ID:

```go title={"Go (REST)"} startLine={32} maxLines={3}
// This Go example uses the Lattice REST SDK (lattice-sdk-go) to recover an integration's video
// stream, entity, and tasks after the integration restarts.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"maps"
	"net/http"
	"os"
	"path/filepath"
	"slices"
	"time"

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

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"

// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"

// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()

const (
	// RTSP source that Lattice pulls video from. Replace before running.
	rtspURL = "rtsp://<rtsp-host>:<port>/cam"
	// Local file that stores the IDs of tasks this agent is executing.
	stateFile = "agent_state.json"
)

var terminalStatuses = map[Lattice.TaskStatusStatus]bool{
	Lattice.TaskStatusStatusStatusDoneOk:    true,
	Lattice.TaskStatusStatusStatusDoneNotOk: true,
}

type agentState struct {
	TaskIDs []string `json:"task_ids"`
}

func loadTaskIDs() (map[string]bool, error) {
	taskIDs := map[string]bool{}
	data, err := os.ReadFile(stateFile)
	if errors.Is(err, os.ErrNotExist) {
		return taskIDs, nil
	}
	if err != nil {
		return nil, err
	}
	var state agentState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	for _, taskID := range state.TaskIDs {
		taskIDs[taskID] = true
	}
	return taskIDs, nil
}

func saveTaskIDs(taskIDs map[string]bool) error {
	ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
	slices.Sort(ids)
	data, err := json.Marshal(agentState{TaskIDs: ids})
	if err != nil {
		return err
	}
	// Write to a temporary file, then rename it over the original. A power loss during the
	// write leaves the previous file intact instead of a truncated one.
	f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	if _, err := f.Write(data); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), stateFile)
}

// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
	taskIDs[taskID] = true
	return saveTaskIDs(taskIDs)
}

// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
	delete(taskIDs, taskID)
	return saveTaskIDs(taskIDs)
}

func reconnectVideo(ctx context.Context, client *client.Client) error {
	response, err := client.Video.GetIngressStream(ctx, &Lattice.GetIngressStreamRequest{
		IngressID: ingressID,
	})
	var apiErr *core.APIError
	if err == nil {
		// The stream survived the restart. Reuse it instead of creating a duplicate.
		status := ""
		if s := response.GetIngressStream().GetStatus(); s != nil {
			status = string(*s)
		}
		fmt.Printf("Reusing stream %s with status %s\n", ingressID, status)
		return nil
	}
	if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
		return err
	}

	// Lattice returns not found both for a stream that never existed and for one that was deleted.
	_, err = client.Video.CreateIngressStream(ctx, &Lattice.CreateIngressStreamRequest{
		IngressID: Lattice.String(ingressID),
		Title:     Lattice.String(assetName),
		Rtsp: &Lattice.RtspSettings{
			URL: Lattice.String(rtspURL),
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Created stream %s\n", ingressID)
	return nil
}

func publishEntity(ctx context.Context, client *client.Client) error {
	now := time.Now().UTC()
	_, err := client.Entities.PublishEntity(ctx, &Lattice.Entity{
		EntityID:   Lattice.String(entityID),
		IsLive:     Lattice.Bool(true),
		ExpiryTime: Lattice.Time(now.Add(5 * time.Minute)),
		Aliases:    &Lattice.Aliases{Name: Lattice.String(assetName)},
		MilView: &Lattice.MilView{
			Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
			Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
		},
		Ontology: &Lattice.Ontology{
			Template:     Lattice.OntologyTemplateTemplateAsset.Ptr(),
			PlatformType: Lattice.String("CAMERA"),
		},
		Location: &Lattice.Location{
			Position: &Lattice.Position{
				LatitudeDegrees:  Lattice.Float64(33.6411),
				LongitudeDegrees: Lattice.Float64(-117.9187),
			},
		},
		// Because ingressID never changes, the entity can reference the stream on every publish.
		Media: &Lattice.Media{Media: []*Lattice.MediaItem{{
			ItemIdentifier: Lattice.String(ingressID),
			Type:           Lattice.MediaItemTypeMediaTypeVideo.Ptr(),
		}}},
		// Include every other component your integration publishes, such as its TaskCatalog.
		Provenance: &Lattice.Provenance{
			IntegrationName:  Lattice.String("my-integration"),
			DataType:         Lattice.String("asset"),
			SourceUpdateTime: Lattice.Time(now),
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Republished entity %s\n", entityID)
	return nil
}

func resolveTrackedTasks(ctx context.Context, client *client.Client, taskIDs map[string]bool) error {
	author := &Lattice.Principal{System: &Lattice.System{EntityID: Lattice.String(entityID)}}
	for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
		task, err := client.Tasks.GetTask(ctx, &Lattice.GetTaskRequest{TaskID: taskID})
		var apiErr *core.APIError
		if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
			// The task no longer exists in Lattice, so there's nothing to resolve.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
		if task.Status == nil || task.Status.Status == nil || task.Version == nil || task.Version.StatusVersion == nil {
			fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
			continue
		}

		status := *task.Status.Status
		if terminalStatuses[status] {
			// An operator or another system closed the task while the agent was offline.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}

		var taskError *Lattice.TaskError
		cancelled := status == Lattice.TaskStatusStatusStatusCancelRequested ||
			(task.GetDeliveryState().GetStatus() != nil &&
				*task.GetDeliveryState().GetStatus() == Lattice.DeliveryStateStatusDeliveryStatusPendingCancel)
		if cancelled {
			// An operator cancelled the task while the agent was offline. Lattice records the cancel
			// in delivery_state, not in the task status. Accept the cancellation.
			taskError = &Lattice.TaskError{
				Code:    Lattice.TaskErrorCodeErrorCodeCancelled.Ptr(),
				Message: Lattice.String("Cancelled while the agent was offline."),
			}
		} else {
			// The agent lost its execution context, so report the task as failed rather than
			// leave it active with nothing working on it.
			taskError = &Lattice.TaskError{
				Code:    Lattice.TaskErrorCodeErrorCodeFailed.Ptr(),
				Message: Lattice.String("Agent restarted and could not resume the task."),
			}
		}

		// Read the status version from GetTask, not from local state: the status might have
		// changed while the agent was offline, and Lattice ignores updates with a stale version.
		statusVersion := *task.Version.StatusVersion + 1
		_, err = client.Tasks.UpdateTaskStatus(ctx, &Lattice.TaskStatusUpdate{
			TaskID:        taskID,
			StatusVersion: &statusVersion,
			NewStatus: &Lattice.TaskStatus{
				Status:    Lattice.TaskStatusStatusStatusDoneNotOk.Ptr(),
				TaskError: taskError,
			},
			Author: author,
		})
		if err != nil {
			return err
		}
		fmt.Printf("Closed task %s with %s\n", taskID, *taskError.Code)
		if err := untrackTask(taskIDs, taskID); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	// Get environment variables
	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")

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

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

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

	ctx := context.Background()

	taskIDs, err := loadTaskIDs()
	if err != nil {
		fmt.Printf("Failed to load saved task IDs: %v\n", err)
		os.Exit(1)
	}
	if err := reconnectVideo(ctx, LatticeClient); err != nil {
		fmt.Printf("Failed to reconnect video: %v\n", err)
		os.Exit(1)
	}
	if err := publishEntity(ctx, LatticeClient); err != nil {
		fmt.Printf("Failed to republish entity: %v\n", err)
		os.Exit(1)
	}
	if err := resolveTrackedTasks(ctx, LatticeClient, taskIDs); err != nil {
		fmt.Printf("Failed to resolve tracked tasks: %v\n", err)
		os.Exit(1)
	}

	// Recovery is complete. Start your regular publish loop and agent stream here, and call
	// trackTask and untrackTask as tasks start and finish.
}

```

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

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.core.LatticeApiException;
import com.anduril.resources.tasks.requests.TaskStatusUpdate;
import com.anduril.resources.video.requests.CreateIngressStreamRequest;
import com.anduril.types.Aliases;
import com.anduril.types.DeliveryState;
import com.anduril.types.DeliveryStateStatus;
import com.anduril.types.Entity;
import com.anduril.types.Location;
import com.anduril.types.Media;
import com.anduril.types.MediaItem;
import com.anduril.types.MediaItemType;
import com.anduril.types.MilView;
import com.anduril.types.MilViewDisposition;
import com.anduril.types.MilViewEnvironment;
import com.anduril.types.Ontology;
import com.anduril.types.OntologyTemplate;
import com.anduril.types.Position;
import com.anduril.types.Principal;
import com.anduril.types.Provenance;
import com.anduril.types.RtspSettings;
import com.anduril.types.Task;
import com.anduril.types.TaskError;
import com.anduril.types.TaskErrorCode;
import com.anduril.types.TaskStatus;
import com.anduril.types.TaskStatusStatus;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * Recovers an integration's video stream, entity, and tasks with the Lattice SDK after the
 * integration restarts.
 */
public class HandleRestarts {
    // A name that is unique to this asset and never changes, such as a serial number read from
    // hardware or configuration. Replace before running.
    private static final String ASSET_NAME = "<ASSET-NAME>";
    // The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
    // so it's the same after every restart.
    private static final String INGRESS_ID = ASSET_NAME + ".cam";
    // The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
    // and in every language.
    // NAMESPACE_URL is the standard RFC 9562 URL namespace.
    private static final UUID NAMESPACE_URL = UUID.fromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8");
    private static final String ENTITY_ID = uuid5(NAMESPACE_URL, "urn:my-integration:" + ASSET_NAME).toString();
    // RTSP source that Lattice pulls video from. Replace before running.
    private static final String RTSP_URL = "rtsp://<rtsp-host>:<port>/cam";
    // Local file that stores the IDs of tasks this agent is executing.
    private static final Path STATE_FILE = Path.of("agent_state.json");

    private static final List<TaskStatusStatus> TERMINAL_STATUSES =
        List.of(TaskStatusStatus.STATUS_DONE_OK, TaskStatusStatus.STATUS_DONE_NOT_OK);

    private static final ObjectMapper JSON = new ObjectMapper();

    private static Set<String> loadTaskIds() throws IOException {
        Set<String> taskIds = new HashSet<>();
        if (!Files.exists(STATE_FILE)) {
            return taskIds;
        }
        for (JsonNode taskId : JSON.readTree(STATE_FILE.toFile()).path("task_ids")) {
            taskIds.add(taskId.asText());
        }
        return taskIds;
    }

    private static void saveTaskIds(Set<String> taskIds) throws IOException {
        // Write to a temporary file, then rename it over the original. A power loss during the
        // write leaves the previous file intact instead of a truncated one.
        Path target = STATE_FILE.toAbsolutePath();
        Path temp = Files.createTempFile(target.getParent(), "agent_state", ".tmp");
        ObjectNode state = JSON.createObjectNode();
        ArrayNode ids = state.putArray("task_ids");
        for (String taskId : new TreeSet<>(taskIds)) {
            ids.add(taskId);
        }
        try (FileChannel channel = FileChannel.open(temp, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(JSON.writeValueAsBytes(state)));
            channel.force(true);
        }
        Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE);
    }

    private static void trackTask(Set<String> taskIds, String taskId) throws IOException {
        // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
        taskIds.add(taskId);
        saveTaskIds(taskIds);
    }

    private static void untrackTask(Set<String> taskIds, String taskId) throws IOException {
        // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
        taskIds.remove(taskId);
        saveTaskIds(taskIds);
    }

    private static void reconnectVideo(Lattice client) {
        try {
            String status = client.video().getIngressStream(INGRESS_ID).getIngressStream()
                .flatMap(stream -> stream.getStatus()).map(Object::toString).orElse("");
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            System.out.println("Reusing stream " + INGRESS_ID + " with status " + status);
            return;
        } catch (LatticeApiException e) {
            if (e.statusCode() != 404) {
                throw e;
            }
        }

        // Lattice returns not found both for a stream that never existed and for one that was deleted.
        client.video().createIngressStream(CreateIngressStreamRequest.builder()
            .ingressId(INGRESS_ID)
            .title(ASSET_NAME)
            .rtsp(RtspSettings.builder()
                .url(RTSP_URL)
                .build())
            .build());
        System.out.println("Created stream " + INGRESS_ID);
    }

    private static void publishEntity(Lattice client) {
        OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
        client.entities().publishEntity(Entity.builder()
            .entityId(ENTITY_ID)
            .isLive(true)
            .expiryTime(now.plusMinutes(5))
            .aliases(Aliases.builder().name(ASSET_NAME).build())
            .milView(MilView.builder()
                .disposition(MilViewDisposition.DISPOSITION_FRIENDLY)
                .environment(MilViewEnvironment.ENVIRONMENT_LAND)
                .build())
            .ontology(Ontology.builder().template(OntologyTemplate.TEMPLATE_ASSET).platformType("CAMERA").build())
            .location(Location.builder()
                .position(Position.builder().latitudeDegrees(33.6411).longitudeDegrees(-117.9187).build())
                .build())
            // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
            .media(Media.builder()
                .media(List.of(MediaItem.builder().itemIdentifier(INGRESS_ID).type(MediaItemType.MEDIA_TYPE_VIDEO).build()))
                .build())
            // Include every other component your integration publishes, such as its TaskCatalog.
            .provenance(Provenance.builder()
                .integrationName("my-integration")
                .dataType("asset")
                .sourceUpdateTime(now)
                .build())
            .build());
        System.out.println("Republished entity " + ENTITY_ID);
    }

    private static void resolveTrackedTasks(Lattice client, Set<String> taskIds) throws IOException {
        Principal author = Principal.builder()
            .system(com.anduril.types.System.builder().entityId(ENTITY_ID).build())
            .build();
        for (String taskId : new TreeSet<>(taskIds)) {
            Task task;
            try {
                task = client.tasks().getTask(taskId);
            } catch (LatticeApiException e) {
                if (e.statusCode() != 404) {
                    throw e;
                }
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrackTask(taskIds, taskId);
                continue;
            }
            if (task.getStatus().isEmpty() || task.getStatus().get().getStatus().isEmpty()
                    || task.getVersion().isEmpty() || task.getVersion().get().getStatusVersion().isEmpty()) {
                System.out.println("Task " + taskId + " is missing its status or version. Skipping.");
                continue;
            }
            TaskStatusStatus status = task.getStatus().get().getStatus().get();
            int statusVersion = task.getVersion().get().getStatusVersion().get();

            if (TERMINAL_STATUSES.contains(status)) {
                // An operator or another system closed the task while the agent was offline.
                untrackTask(taskIds, taskId);
                continue;
            }

            TaskError error;
            boolean pendingCancel = task.getDeliveryState().flatMap(DeliveryState::getStatus)
                .map(DeliveryStateStatus.DELIVERY_STATUS_PENDING_CANCEL::equals).orElse(false);
            if (status.equals(TaskStatusStatus.STATUS_CANCEL_REQUESTED) || pendingCancel) {
                // An operator cancelled the task while the agent was offline. Lattice records the cancel
                // in deliveryState, not in the task status. Accept the cancellation.
                error = TaskError.builder()
                    .code(TaskErrorCode.ERROR_CODE_CANCELLED)
                    .message("Cancelled while the agent was offline.")
                    .build();
            } else {
                // The agent lost its execution context, so report the task as failed rather than
                // leave it active with nothing working on it.
                error = TaskError.builder()
                    .code(TaskErrorCode.ERROR_CODE_FAILED)
                    .message("Agent restarted and could not resume the task.")
                    .build();
            }

            // Read the status version from GetTask, not from local state: the status might have
            // changed while the agent was offline, and Lattice ignores updates with a stale version.
            client.tasks().updateTaskStatus(taskId, TaskStatusUpdate.builder()
                .statusVersion(statusVersion + 1)
                .newStatus(TaskStatus.builder()
                    .status(TaskStatusStatus.STATUS_DONE_NOT_OK)
                    .taskError(error)
                    .build())
                .author(author)
                .build());
            System.out.println("Closed task " + taskId + " with " + error.getCode().map(Object::toString).orElse(""));
            untrackTask(taskIds, taskId);
        }
    }

    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 and ensure the endpoint has its scheme
        if (isBlank(endpoint) || isBlank(environmentToken) || isBlank(sandboxesToken)) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        // Create Lattice client with Sandbox authentication
        Lattice client = Lattice.builder()
            .url(endpoint)
            .token(environmentToken)
            .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
            .build();

        try {
            Set<String> taskIds = loadTaskIds();
            reconnectVideo(client);
            publishEntity(client);
            resolveTrackedTasks(client, taskIds);
        } catch (Exception e) {
            System.err.println("Failed to recover after restart: " + e.getMessage());
            System.exit(1);
        }

        // Recovery is complete. Start your regular publish loop and agent stream here, and call
        // trackTask and untrackTask as tasks start and finish.
    }

    private static boolean isBlank(String value) {
        return value == null || value.isEmpty();
    }

    /**
     * Returns a name-based version 5 UUID, which is the same every time for the same namespace and name.
     */
    private static UUID uuid5(UUID namespace, String name) {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            sha1.update(ByteBuffer.allocate(16)
                .putLong(namespace.getMostSignificantBits())
                .putLong(namespace.getLeastSignificantBits())
                .array());
            sha1.update(name.getBytes(StandardCharsets.UTF_8));
            byte[] hash = sha1.digest();
            hash[6] = (byte) ((hash[6] & 0x0f) | 0x50); // Version 5
            hash[8] = (byte) ((hash[8] & 0x3f) | 0x80); // RFC 9562 variant
            ByteBuffer bytes = ByteBuffer.wrap(hash, 0, 16);
            return new UUID(bytes.getLong(), bytes.getLong());
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("SHA-1 is unavailable", e);
        }
    }
}

```

```py title={"Python (REST)"} startLine={35} maxLines={3}
# This Python example uses the Lattice REST SDK (anduril-lattice-sdk) to recover an integration's
# video stream, entity, and tasks after the integration restarts.

import json
import os
import sys
import tempfile
import uuid
from datetime import datetime, timedelta, timezone

from anduril import (
    Aliases,
    Lattice,
    Location,
    Media,
    MediaItem,
    MilView,
    Ontology,
    Position,
    Principal,
    Provenance,
    RtspSettings,
    System,
    TaskError,
    TaskStatus,
)
from anduril.core import ApiError

# A name that is unique to this asset and never changes, such as a serial number read from
# hardware or configuration. Replace before running.
ASSET_NAME = "<ASSET-NAME>"
# The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
# so it's the same after every restart.
INGRESS_ID = f"{ASSET_NAME}.cam"
# The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
# and in every language.
ENTITY_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:my-integration:{ASSET_NAME}"))
# RTSP source that Lattice pulls video from. Replace before running.
RTSP_URL = "rtsp://<rtsp-host>:<port>/cam"
# Local file that stores the IDs of tasks this agent is executing.
STATE_FILE = "agent_state.json"

TERMINAL_STATUSES = {"STATUS_DONE_OK", "STATUS_DONE_NOT_OK"}


def load_task_ids():
    try:
        with open(STATE_FILE) as f:
            return set(json.load(f)["task_ids"])
    except FileNotFoundError:
        return set()


def save_task_ids(task_ids):
    # Write to a temporary file, then rename it over the original. A power loss during the
    # write leaves the previous file intact instead of a truncated one.
    directory = os.path.dirname(os.path.abspath(STATE_FILE))
    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f:
        json.dump({"task_ids": sorted(task_ids)}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(f.name, STATE_FILE)


def track_task(task_ids, task_id):
    # Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.add(task_id)
    save_task_ids(task_ids)


def untrack_task(task_ids, task_id):
    # Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.discard(task_id)
    save_task_ids(task_ids)


def reconnect_video(client):
    try:
        stream = client.video.get_ingress_stream(INGRESS_ID).ingress_stream
        # The stream survived the restart. Reuse it instead of creating a duplicate.
        print(f"Reusing stream {INGRESS_ID} with status {stream.status}")
        return
    except ApiError as error:
        if error.status_code != 404:
            raise

    # Lattice returns not found both for a stream that never existed and for one that was deleted.
    client.video.create_ingress_stream(
        ingress_id=INGRESS_ID,
        title=ASSET_NAME,
        rtsp=RtspSettings(url=RTSP_URL),
    )
    print(f"Created stream {INGRESS_ID}")


def publish_entity(client):
    now = datetime.now(timezone.utc)
    client.entities.publish_entity(
        entity_id=ENTITY_ID,
        is_live=True,
        expiry_time=now + timedelta(minutes=5),
        aliases=Aliases(name=ASSET_NAME),
        mil_view=MilView(disposition="DISPOSITION_FRIENDLY", environment="ENVIRONMENT_LAND"),
        ontology=Ontology(template="TEMPLATE_ASSET", platform_type="CAMERA"),
        location=Location(position=Position(latitude_degrees=33.6411, longitude_degrees=-117.9187)),
        # Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media=Media(media=[MediaItem(item_identifier=INGRESS_ID, type="MEDIA_TYPE_VIDEO")]),
        # Include every other component your integration publishes, such as its TaskCatalog.
        provenance=Provenance(
            integration_name="my-integration",
            data_type="asset",
            source_update_time=now,
        ),
    )
    print(f"Republished entity {ENTITY_ID}")


def resolve_tracked_tasks(client, task_ids):
    author = Principal(system=System(entity_id=ENTITY_ID))
    for task_id in sorted(task_ids):
        try:
            task = client.tasks.get_task(task_id)
        except ApiError as error:
            if error.status_code != 404:
                raise
            # The task no longer exists in Lattice, so there's nothing to resolve.
            untrack_task(task_ids, task_id)
            continue
        if not task.status or not task.version or task.version.status_version is None:
            print(f"Task {task_id} is missing its status or version. Skipping.")
            continue

        if task.status.status in TERMINAL_STATUSES:
            # An operator or another system closed the task while the agent was offline.
            untrack_task(task_ids, task_id)
            continue

        pending_cancel = task.delivery_state and task.delivery_state.status == "DELIVERY_STATUS_PENDING_CANCEL"
        if task.status.status == "STATUS_CANCEL_REQUESTED" or pending_cancel:
            # An operator cancelled the task while the agent was offline. Lattice records the cancel
            # in delivery_state, not in the task status. Accept the cancellation.
            error = TaskError(code="ERROR_CODE_CANCELLED", message="Cancelled while the agent was offline.")
        else:
            # The agent lost its execution context, so report the task as failed rather than
            # leave it active with nothing working on it.
            error = TaskError(code="ERROR_CODE_FAILED", message="Agent restarted and could not resume the task.")

        # Read status_version from GetTask, not from local state: the status might have
        # changed while the agent was offline, and Lattice ignores updates with a stale version.
        client.tasks.update_task_status(
            task_id,
            status_version=task.version.status_version + 1,
            new_status=TaskStatus(status="STATUS_DONE_NOT_OK", task_error=error),
            author=author,
        )
        print(f"Closed task {task_id} with {error.code}")
        untrack_task(task_ids, task_id)


def main():
    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)

    client = Lattice(
        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}"},
    )

    task_ids = load_task_ids()
    try:
        reconnect_video(client)
        publish_entity(client)
        resolve_tracked_tasks(client, task_ids)
    except Exception as error:
        print(f"Failed to recover after restart: {error}", file=sys.stderr)
        sys.exit(1)

    # Recovery is complete. Start your regular publish loop and agent stream here, and call
    # track_task and untrack_task as tasks start and finish.


if __name__ == "__main__":
    main()

```

```ts title={"TypeScript (REST)"} startLine={15} maxLines={3}
// This TypeScript example uses the Lattice REST SDK (@anduril-industries/lattice-sdk) to recover an
// integration's video stream, entity, and tasks after the integration restarts.

import * as fs from "node:fs";
import * as path from "node:path";
import { Lattice, LatticeClient, LatticeError } from "@anduril-industries/lattice-sdk";
import { v5 as uuidv5 } from "uuid";

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
const INGRESS_ID = `${ASSET_NAME}.cam`;
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
const ENTITY_ID = uuidv5(`urn:my-integration:${ASSET_NAME}`, uuidv5.URL);
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE = "agent_state.json";

const TERMINAL_STATUSES = new Set<string | undefined>(["STATUS_DONE_OK", "STATUS_DONE_NOT_OK"]);

function loadTaskIds(): Set<string> {
    try {
        return new Set<string>(JSON.parse(fs.readFileSync(STATE_FILE, "utf8")).task_ids);
    } catch (error) {
        if ((error as NodeJS.ErrnoException).code === "ENOENT") {
            return new Set<string>();
        }
        throw error;
    }
}

function saveTaskIds(taskIds: Set<string>) {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    const tempFile = path.join(path.dirname(path.resolve(STATE_FILE)), `.${path.basename(STATE_FILE)}.${process.pid}.tmp`);
    const fd = fs.openSync(tempFile, "w");
    try {
        fs.writeSync(fd, JSON.stringify({ task_ids: [...taskIds].sort() }));
        fs.fsyncSync(fd);
    } finally {
        fs.closeSync(fd);
    }
    fs.renameSync(tempFile, STATE_FILE);
}

export function trackTask(taskIds: Set<string>, taskId: string) {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    taskIds.add(taskId);
    saveTaskIds(taskIds);
}

export function untrackTask(taskIds: Set<string>, taskId: string) {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    taskIds.delete(taskId);
    saveTaskIds(taskIds);
}

async function reconnectVideo(client: LatticeClient) {
    try {
        const { ingressStream } = await client.video.getIngressStream({ ingressId: INGRESS_ID });
        // The stream survived the restart. Reuse it instead of creating a duplicate.
        console.log(`Reusing stream ${INGRESS_ID} with status ${ingressStream?.status}`);
        return;
    } catch (error) {
        if (!(error instanceof LatticeError && error.statusCode === 404)) {
            throw error;
        }
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    await client.video.createIngressStream({
        ingressId: INGRESS_ID,
        title: ASSET_NAME,
        rtsp: { url: RTSP_URL },
    });
    console.log(`Created stream ${INGRESS_ID}`);
}

async function publishEntity(client: LatticeClient) {
    const now = new Date();
    await client.entities.publishEntity({
        entityId: ENTITY_ID,
        isLive: true,
        expiryTime: new Date(now.getTime() + 5 * 60 * 1000).toISOString(),
        aliases: { name: ASSET_NAME },
        milView: { disposition: "DISPOSITION_FRIENDLY", environment: "ENVIRONMENT_LAND" },
        ontology: { template: "TEMPLATE_ASSET", platformType: "CAMERA" },
        location: { position: { latitudeDegrees: 33.6411, longitudeDegrees: -117.9187 } },
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: { media: [{ itemIdentifier: INGRESS_ID, type: "MEDIA_TYPE_VIDEO" }] },
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: {
            integrationName: "my-integration",
            dataType: "asset",
            sourceUpdateTime: now.toISOString(),
        },
    });
    console.log(`Republished entity ${ENTITY_ID}`);
}

async function resolveTrackedTasks(client: LatticeClient, taskIds: Set<string>) {
    const author = { system: { entityId: ENTITY_ID } };
    for (const taskId of [...taskIds].sort()) {
        let task: Lattice.Task;
        try {
            task = await client.tasks.getTask({ taskId });
        } catch (error) {
            if (!(error instanceof LatticeError && error.statusCode === 404)) {
                throw error;
            }
            // The task no longer exists in Lattice, so there's nothing to resolve.
            untrackTask(taskIds, taskId);
            continue;
        }
        const statusVersion = task.version?.statusVersion;
        if (!task.status || statusVersion === undefined) {
            console.log(`Task ${taskId} is missing its status or version. Skipping.`);
            continue;
        }

        if (TERMINAL_STATUSES.has(task.status.status)) {
            // An operator or another system closed the task while the agent was offline.
            untrackTask(taskIds, taskId);
            continue;
        }

        let taskError: Lattice.TaskError;
        const pendingCancel = task.deliveryState?.status === "DELIVERY_STATUS_PENDING_CANCEL";
        if (task.status.status === "STATUS_CANCEL_REQUESTED" || pendingCancel) {
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in deliveryState, not in the task status. Accept the cancellation.
            taskError = { code: "ERROR_CODE_CANCELLED", message: "Cancelled while the agent was offline." };
        } else {
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            taskError = { code: "ERROR_CODE_FAILED", message: "Agent restarted and could not resume the task." };
        }

        // Read statusVersion from getTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        await client.tasks.updateTaskStatus({
            taskId,
            statusVersion: statusVersion + 1,
            newStatus: { status: "STATUS_DONE_NOT_OK", taskError },
            author,
        });
        console.log(`Closed task ${taskId} with ${taskError.code}`);
        untrackTask(taskIds, taskId);
    }
}

async function App() {
    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,
            // Remove the following if you are not developing on Sandboxes.
            headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}`  }
        }
    );

    const taskIds = loadTaskIds();
    try {
        await reconnectVideo(client);
        await publishEntity(client);
        await resolveTrackedTasks(client, taskIds);
    } catch (error) {
        console.error(`Failed to recover after restart: ${error}`);
        process.exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // trackTask and untrackTask as tasks start and finish.
}

App();

```

```rs title={"Rust (REST)"} startLine={22} maxLines={6}
// This Rust example uses the Lattice REST SDK (anduril-lattice-sdk) to recover an integration's
// video stream, entity, and tasks after the integration restarts.

// track_task is called from the main loop you add after recovery.
#![allow(dead_code)]

use anduril_lattice_sdk::prelude::*;

use std::collections::BTreeSet;
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::sync::LazyLock;
use uuid::Uuid;

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME: &str = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
static INGRESS_ID: LazyLock<String> = LazyLock::new(|| format!("{}.cam", ASSET_NAME));
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
static ENTITY_ID: LazyLock<String> = LazyLock::new(|| {
    let name = format!("urn:my-integration:{}", ASSET_NAME);
    Uuid::new_v5(&Uuid::NAMESPACE_URL, name.as_bytes()).to_string()
});
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL: &str = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE: &str = "agent_state.json";

fn load_task_ids() -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
    let contents = match fs::read_to_string(STATE_FILE) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(error.into()),
    };
    let state: Value = contents.parse()?;
    let task_ids = state["task_ids"].as_array().ok_or("task_ids is missing")?;
    Ok(task_ids.iter().filter_map(|id| id.as_str().map(String::from)).collect())
}

fn save_task_ids(task_ids: &BTreeSet<String>) -> std::io::Result<()> {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    let temp_path = format!("{}.tmp", STATE_FILE);
    let mut file = File::create(&temp_path)?;
    file.write_all(json!({ "task_ids": task_ids }).to_string().as_bytes())?;
    file.sync_all()?;
    fs::rename(&temp_path, STATE_FILE)
}

fn track_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.insert(task_id.to_string());
    save_task_ids(task_ids)
}

fn untrack_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.remove(task_id);
    save_task_ids(task_ids)
}

async fn reconnect_video(client: &Lattice) -> Result<(), ApiError> {
    match client.video.get_ingress_stream(&INGRESS_ID, None).await {
        Ok(response) => {
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            let status = response
                .ingress_stream
                .and_then(|stream| stream.status)
                .map(|status| status.to_string())
                .unwrap_or_default();
            println!("Reusing stream {} with status {}", *INGRESS_ID, status);
            return Ok(());
        }
        Err(ApiError::NotFoundError { .. }) => {}
        Err(error) => return Err(error),
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    let request = CreateIngressStreamRequest {
        ingress_id: Some(INGRESS_ID.clone()),
        title: Some(ASSET_NAME.to_string()),
        rtsp: Some(RtspSettings {
            url: Some(RTSP_URL.to_string()),
            ..Default::default()
        }),
        ..Default::default()
    };
    client.video.create_ingress_stream(&request, None).await?;
    println!("Created stream {}", *INGRESS_ID);
    Ok(())
}

async fn publish_entity(client: &Lattice) -> Result<(), ApiError> {
    let now = Utc::now();
    let entity = Entity {
        entity_id: Some(ENTITY_ID.clone()),
        is_live: Some(true),
        expiry_time: Some((now + chrono::Duration::minutes(5)).fixed_offset()),
        aliases: Some(Aliases {
            name: Some(ASSET_NAME.to_string()),
            ..Default::default()
        }),
        mil_view: Some(MilView {
            disposition: Some(MilViewDisposition::DispositionFriendly),
            environment: Some(MilViewEnvironment::EnvironmentLand),
            ..Default::default()
        }),
        ontology: Some(Ontology {
            template: Some(OntologyTemplate::TemplateAsset),
            platform_type: Some("CAMERA".to_string()),
            ..Default::default()
        }),
        location: Some(Location {
            position: Some(Position {
                latitude_degrees: Some(33.6411),
                longitude_degrees: Some(-117.9187),
                ..Default::default()
            }),
            ..Default::default()
        }),
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: Some(Media {
            media: Some(vec![MediaItem {
                item_identifier: Some(INGRESS_ID.clone()),
                r#type: Some(MediaItemType::MediaTypeVideo),
                ..Default::default()
            }]),
            ..Default::default()
        }),
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: Some(Provenance {
            integration_name: Some("my-integration".to_string()),
            data_type: Some("asset".to_string()),
            source_update_time: Some(now.fixed_offset()),
            ..Default::default()
        }),
        ..Default::default()
    };
    client.entities.publish_entity(&entity, None).await?;
    println!("Republished entity {}", *ENTITY_ID);
    Ok(())
}

async fn resolve_tracked_tasks(
    client: &Lattice,
    task_ids: &mut BTreeSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let author = Principal {
        system: Some(System {
            entity_id: Some(ENTITY_ID.clone()),
            ..Default::default()
        }),
        ..Default::default()
    };
    for task_id in task_ids.clone() {
        let task = match client.tasks.get_task(&task_id, None).await {
            Ok(task) => task,
            Err(ApiError::NotFoundError { .. }) => {
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            Err(error) => return Err(error.into()),
        };
        let (Some(status), Some(status_version)) = (
            task.status.as_ref(),
            task.version.as_ref().and_then(|version| version.status_version),
        ) else {
            println!("Task {} is missing its status or version. Skipping.", task_id);
            continue;
        };

        let cancelled = matches!(status.status, Some(TaskStatusStatus::StatusCancelRequested))
            || matches!(
                task.delivery_state.as_ref().and_then(|state| state.status.as_ref()),
                Some(DeliveryStateStatus::DeliveryStatusPendingCancel)
            );
        let error = match status.status {
            Some(TaskStatusStatus::StatusDoneOk | TaskStatusStatus::StatusDoneNotOk) => {
                // An operator or another system closed the task while the agent was offline.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in delivery_state, not in the task status. Accept the cancellation.
            _ if cancelled => TaskError {
                code: Some(TaskErrorCode::ErrorCodeCancelled),
                message: Some("Cancelled while the agent was offline.".to_string()),
                ..Default::default()
            },
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            _ => TaskError {
                code: Some(TaskErrorCode::ErrorCodeFailed),
                message: Some("Agent restarted and could not resume the task.".to_string()),
                ..Default::default()
            },
        };
        let code = error.code.as_ref().map(|code| code.to_string()).unwrap_or_default();

        // Read status_version from GetTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        let request = TaskStatusUpdate {
            status_version: Some(status_version + 1),
            new_status: Some(TaskStatus {
                status: Some(TaskStatusStatus::StatusDoneNotOk),
                task_error: Some(error),
                ..Default::default()
            }),
            author: Some(author.clone()),
        };
        client.tasks.update_task_status(&task_id, &request, None).await?;
        println!("Closed task {} with {}", task_id, code);
        untrack_task(task_ids, &task_id)?;
    }
    Ok(())
}

#[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)?;

    let mut task_ids = load_task_ids()?;
    let result: Result<(), Box<dyn std::error::Error>> = async {
        reconnect_video(&client).await?;
        publish_entity(&client).await?;
        resolve_tracked_tasks(&client, &mut task_ids).await?;
        Ok(())
    }
    .await;
    if let Err(error) = result {
        eprintln!("Failed to recover after restart: {}", error);
        std::process::exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // track_task and untrack_task as tasks start and finish.
    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={44} maxLines={3}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
//
// It recovers an integration's video stream, entity, and tasks after the integration restarts.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"maps"
	"os"
	"path/filepath"
	"slices"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/taskmanager/v1/taskmanagerv1grpc"
	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/videomanager/v1/videomanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	ontologyv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/ontology/v1"
	taskmanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/taskmanager/v1"
	videomanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/videomanager/v1"

	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"

// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"

// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()

const (
	// RTSP source that Lattice pulls video from. Replace before running.
	rtspURL = "rtsp://<rtsp-host>:<port>/cam"
	// Local file that stores the IDs of tasks this agent is executing.
	stateFile = "agent_state.json"
)

var terminalStatuses = map[taskmanagerv1.Status]bool{
	taskmanagerv1.Status_STATUS_DONE_OK:     true,
	taskmanagerv1.Status_STATUS_DONE_NOT_OK: true,
}

type agentState struct {
	TaskIDs []string `json:"task_ids"`
}

func loadTaskIDs() (map[string]bool, error) {
	taskIDs := map[string]bool{}
	data, err := os.ReadFile(stateFile)
	if errors.Is(err, os.ErrNotExist) {
		return taskIDs, nil
	}
	if err != nil {
		return nil, err
	}
	var state agentState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	for _, taskID := range state.TaskIDs {
		taskIDs[taskID] = true
	}
	return taskIDs, nil
}

func saveTaskIDs(taskIDs map[string]bool) error {
	ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
	slices.Sort(ids)
	data, err := json.Marshal(agentState{TaskIDs: ids})
	if err != nil {
		return err
	}
	// Write to a temporary file, then rename it over the original. A power loss during the
	// write leaves the previous file intact instead of a truncated one.
	f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	if _, err := f.Write(data); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), stateFile)
}

// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
	taskIDs[taskID] = true
	return saveTaskIDs(taskIDs)
}

// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
	delete(taskIDs, taskID)
	return saveTaskIDs(taskIDs)
}

func reconnectVideo(ctx context.Context, client videomanagerv1grpc.VideoManagerAPIClient) error {
	response, err := client.GetIngressStream(ctx, &videomanagerv1.GetIngressStreamRequest{
		IngressId: ingressID,
	})
	if err == nil {
		// The stream survived the restart. Reuse it instead of creating a duplicate.
		fmt.Printf("Reusing stream %s with status %s\n", ingressID, response.GetIngressStream().GetStatus())
		return nil
	}
	if status.Code(err) != codes.NotFound {
		return err
	}

	// Lattice returns not found both for a stream that never existed and for one that was deleted.
	_, err = client.CreateIngressStream(ctx, &videomanagerv1.CreateIngressStreamRequest{
		IngressId: proto.String(ingressID),
		Title:     assetName,
		Ingress: &videomanagerv1.CreateIngressStreamRequest_Rtsp{
			Rtsp: &videomanagerv1.RtspSettings{
				Url: proto.String(rtspURL),
			},
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Created stream %s\n", ingressID)
	return nil
}

func publishEntity(ctx context.Context, client entitymanagerv1grpc.EntityManagerAPIClient) error {
	now := time.Now().UTC()
	_, err := client.PublishEntity(ctx, &entitymanagerv1.PublishEntityRequest{Entity: &entitymanagerv1.Entity{
		EntityId:   entityID,
		IsLive:     true,
		ExpiryTime: timestamppb.New(now.Add(5 * time.Minute)),
		Aliases:    &entitymanagerv1.Aliases{Name: assetName},
		MilView: &entitymanagerv1.MilView{
			Disposition: ontologyv1.Disposition_DISPOSITION_FRIENDLY,
			Environment: ontologyv1.Environment_ENVIRONMENT_LAND,
		},
		Ontology: &entitymanagerv1.Ontology{
			Template:     entitymanagerv1.Template_TEMPLATE_ASSET,
			PlatformType: "CAMERA",
		},
		Location: &entitymanagerv1.Location{
			Position: &entitymanagerv1.Position{
				LatitudeDegrees:  33.6411,
				LongitudeDegrees: -117.9187,
			},
		},
		// Because ingressID never changes, the entity can reference the stream on every publish.
		Media: &entitymanagerv1.Media{Media: []*entitymanagerv1.MediaItem{{
			ItemIdentifier: ingressID,
			Type:           entitymanagerv1.MediaType_MEDIA_TYPE_VIDEO,
		}}},
		// Include every other component your integration publishes, such as its TaskCatalog.
		Provenance: &entitymanagerv1.Provenance{
			IntegrationName:  "my-integration",
			DataType:         "asset",
			SourceUpdateTime: timestamppb.New(now),
		},
	}})
	if err != nil {
		return err
	}
	fmt.Printf("Republished entity %s\n", entityID)
	return nil
}

func resolveTrackedTasks(ctx context.Context, client taskmanagerv1grpc.TaskManagerAPIClient, taskIDs map[string]bool) error {
	author := &taskmanagerv1.Principal{
		Agent: &taskmanagerv1.Principal_System{
			System: &taskmanagerv1.System{EntityId: entityID},
		},
	}
	for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
		response, err := client.GetTask(ctx, &taskmanagerv1.GetTaskRequest{TaskId: taskID})
		if status.Code(err) == codes.NotFound {
			// The task no longer exists in Lattice, so there's nothing to resolve.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
		task := response.GetTask()
		if task.GetStatus() == nil || task.GetVersion() == nil {
			fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
			continue
		}

		taskStatus := task.GetStatus().GetStatus()
		if terminalStatuses[taskStatus] {
			// An operator or another system closed the task while the agent was offline.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}

		var taskError *taskmanagerv1.TaskError
		cancelled := taskStatus == taskmanagerv1.Status_STATUS_CANCEL_REQUESTED ||
			task.GetDeliveryState().GetStatus() == taskmanagerv1.DeliveryStatus_DELIVERY_STATUS_PENDING_CANCEL
		if cancelled {
			// An operator cancelled the task while the agent was offline. Lattice records the cancel
			// in delivery_state, not in the task status. Accept the cancellation.
			taskError = &taskmanagerv1.TaskError{
				Code:    taskmanagerv1.ErrorCode_ERROR_CODE_CANCELLED,
				Message: "Cancelled while the agent was offline.",
			}
		} else {
			// The agent lost its execution context, so report the task as failed rather than
			// leave it active with nothing working on it.
			taskError = &taskmanagerv1.TaskError{
				Code:    taskmanagerv1.ErrorCode_ERROR_CODE_FAILED,
				Message: "Agent restarted and could not resume the task.",
			}
		}

		// Read the status version from GetTask, not from local state: the status might have
		// changed while the agent was offline, and Lattice ignores updates with a stale version.
		_, err = client.UpdateStatus(ctx, &taskmanagerv1.UpdateStatusRequest{
			StatusUpdate: &taskmanagerv1.StatusUpdate{
				Version: &taskmanagerv1.TaskVersion{
					TaskId:        taskID,
					StatusVersion: task.GetVersion().GetStatusVersion() + 1,
				},
				Status: &taskmanagerv1.TaskStatus{
					Status:    taskmanagerv1.Status_STATUS_DONE_NOT_OK,
					TaskError: taskError,
				},
				Author: author,
			},
		})
		if err != nil {
			return err
		}
		fmt.Printf("Closed task %s with %s\n", taskID, taskError.GetCode())
		if err := untrackTask(taskIDs, taskID); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	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()

	videoClient := videomanagerv1grpc.NewVideoManagerAPIClient(conn)
	entityClient := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)
	taskClient := taskmanagerv1grpc.NewTaskManagerAPIClient(conn)

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	taskIDs, err := loadTaskIDs()
	if err != nil {
		log.Fatalf("Failed to load saved task IDs: %v", err)
	}
	if err := reconnectVideo(ctx, videoClient); err != nil {
		log.Fatalf("Failed to reconnect video: %v", err)
	}
	if err := publishEntity(ctx, entityClient); err != nil {
		log.Fatalf("Failed to republish entity: %v", err)
	}
	if err := resolveTrackedTasks(ctx, taskClient, taskIDs); err != nil {
		log.Fatalf("Failed to resolve tracked tasks: %v", err)
	}

	// Recovery is complete. Start your regular publish loop and agent stream here, and call
	// trackTask and untrackTask as tasks start and finish.
}

```

```py title={"Python (gRPC)"} startLine={50} maxLines={3}
# 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
# It recovers an integration's video stream, entity, and tasks after the integration restarts.

import json
import os
import sys
import tempfile
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from connectrpc.code import Code
from connectrpc.errors import ConnectError
from protobuf import Oneof
from protobuf.wkt import Timestamp

from anduril.entitymanager.v1.entity_pub_pb import Aliases, Entity, Provenance
from anduril.entitymanager.v1.entity_manager_api_pub_pb import PublishEntityRequest
from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.location_pub_pb import Location, Position
from anduril.entitymanager.v1.media_pub_pb import Media, MediaItem, MediaType
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.ontology.v1.type_pub_pb import Disposition, Environment
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.taskmanager.v1.task_pub_pb import (
    DeliveryStatus,
    ErrorCode,
    Principal,
    Status,
    StatusUpdate,
    System,
    TaskError,
    TaskStatus,
    TaskVersion,
)
from anduril.taskmanager.v1.task_manager_api_pub_pb import GetTaskRequest, UpdateStatusRequest
from anduril.taskmanager.v1.task_manager_api_pub_connect import TaskManagerAPIClientSync
from anduril.videomanager.v1.create_ingress_stream_request_pub_pb import CreateIngressStreamRequest
from anduril.videomanager.v1.get_ingress_stream_request_pub_pb import GetIngressStreamRequest
from anduril.videomanager.v1.rtsp_settings_pub_pb import RtspSettings
from anduril.videomanager.v1.video_manager_api_pub_connect import VideoManagerAPIClientSync

# A name that is unique to this asset and never changes, such as a serial number read from
# hardware or configuration. Replace before running.
ASSET_NAME = "<ASSET-NAME>"
# The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
# so it's the same after every restart.
INGRESS_ID = f"{ASSET_NAME}.cam"
# The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
# and in every language.
ENTITY_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:my-integration:{ASSET_NAME}"))
# RTSP source that Lattice pulls video from. Replace before running.
RTSP_URL = "rtsp://<rtsp-host>:<port>/cam"
# Local file that stores the IDs of tasks this agent is executing.
STATE_FILE = "agent_state.json"

TERMINAL_STATUSES = {Status.DONE_OK, Status.DONE_NOT_OK}


def load_task_ids():
    try:
        with open(STATE_FILE) as f:
            return set(json.load(f)["task_ids"])
    except FileNotFoundError:
        return set()


def save_task_ids(task_ids):
    # Write to a temporary file, then rename it over the original. A power loss during the
    # write leaves the previous file intact instead of a truncated one.
    directory = os.path.dirname(os.path.abspath(STATE_FILE))
    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f:
        json.dump({"task_ids": sorted(task_ids)}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(f.name, STATE_FILE)


def track_task(task_ids, task_id):
    # Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.add(task_id)
    save_task_ids(task_ids)


def untrack_task(task_ids, task_id):
    # Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.discard(task_id)
    save_task_ids(task_ids)


def reconnect_video(client):
    try:
        response = client.get_ingress_stream(GetIngressStreamRequest(ingress_id=INGRESS_ID), timeout_ms=10000)
        # The stream survived the restart. Reuse it instead of creating a duplicate.
        print(f"Reusing stream {INGRESS_ID} with status STREAM_STATUS_{response.ingress_stream.status.name}")
        return
    except ConnectError as error:
        if error.code != Code.NOT_FOUND:
            raise

    # Lattice returns not found both for a stream that never existed and for one that was deleted.
    client.create_ingress_stream(
        CreateIngressStreamRequest(
            ingress_id=INGRESS_ID,
            title=ASSET_NAME,
            ingress=Oneof("rtsp", RtspSettings(url=RTSP_URL)),
        ),
        timeout_ms=30000,
    )
    print(f"Created stream {INGRESS_ID}")


def publish_entity(client):
    now = datetime.now(timezone.utc)
    entity = Entity(
        entity_id=ENTITY_ID,
        is_live=True,
        expiry_time=Timestamp.from_datetime(now + timedelta(minutes=5)),
        aliases=Aliases(name=ASSET_NAME),
        mil_view=MilView(disposition=Disposition.FRIENDLY, environment=Environment.LAND),
        ontology=Ontology(template=Template.ASSET, platform_type="CAMERA"),
        location=Location(position=Position(latitude_degrees=33.6411, longitude_degrees=-117.9187)),
        # Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media=Media(media=[MediaItem(item_identifier=INGRESS_ID, type=MediaType.VIDEO)]),
        # Include every other component your integration publishes, such as its TaskCatalog.
        provenance=Provenance(
            integration_name="my-integration",
            data_type="asset",
            source_update_time=Timestamp.from_datetime(now),
        ),
    )
    client.publish_entity(PublishEntityRequest(entity=entity), timeout_ms=10000)
    print(f"Republished entity {ENTITY_ID}")


def resolve_tracked_tasks(client, task_ids):
    author = Principal(agent=Oneof("system", System(entity_id=ENTITY_ID)))
    for task_id in sorted(task_ids):
        try:
            task = client.get_task(GetTaskRequest(task_id=task_id), timeout_ms=10000).task
        except ConnectError as error:
            if error.code != Code.NOT_FOUND:
                raise
            # The task no longer exists in Lattice, so there's nothing to resolve.
            untrack_task(task_ids, task_id)
            continue
        if not task or not task.status or not task.version:
            print(f"Task {task_id} is missing its status or version. Skipping.")
            continue

        if task.status.status in TERMINAL_STATUSES:
            # An operator or another system closed the task while the agent was offline.
            untrack_task(task_ids, task_id)
            continue

        pending_cancel = task.delivery_state and task.delivery_state.status == DeliveryStatus.PENDING_CANCEL
        if task.status.status == Status.CANCEL_REQUESTED or pending_cancel:
            # An operator cancelled the task while the agent was offline. Lattice records the cancel
            # in delivery_state, not in the task status. Accept the cancellation.
            error = TaskError(code=ErrorCode.CANCELLED, message="Cancelled while the agent was offline.")
        else:
            # The agent lost its execution context, so report the task as failed rather than
            # leave it active with nothing working on it.
            error = TaskError(code=ErrorCode.FAILED, message="Agent restarted and could not resume the task.")

        # Read status_version from GetTask, not from local state: the status might have
        # changed while the agent was offline, and Lattice ignores updates with a stale version.
        status_update = StatusUpdate(
            version=TaskVersion(task_id=task_id, status_version=task.version.status_version + 1),
            status=TaskStatus(status=Status.DONE_NOT_OK, task_error=error),
            author=author,
        )
        client.update_status(UpdateStatusRequest(status_update=status_update), timeout_ms=10000)
        print(f"Closed task {task_id} with ERROR_CODE_{error.code.name}")
        untrack_task(task_ids, task_id)


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 clients over Connect gRPC with authentication
    video_client = create_client(VideoManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)
    entity_client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)
    task_client = create_client(TaskManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    task_ids = load_task_ids()
    try:
        reconnect_video(video_client)
        publish_entity(entity_client)
        resolve_tracked_tasks(task_client, task_ids)
    except Exception as error:
        print(f"Failed to recover after restart: {error}", file=sys.stderr)
        sys.exit(1)

    # Recovery is complete. Start your regular publish loop and agent stream here, and call
    # track_task and untrack_task as tasks start and finish.


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={47} maxLines={6}
// 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

// track_task is called from the main loop you add after recovery.
#![allow(dead_code)]

mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    Aliases, Entity, Location, Media, MediaItem, MediaType, MilView, Ontology, Position, Provenance,
    PublishEntityRequest, Template,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{Disposition, Environment};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::taskmanager::v1::{
    principal, DeliveryStatus, ErrorCode, GetTaskRequest, Principal, Status, StatusUpdate, System, TaskError,
    TaskStatus, TaskVersion, UpdateStatusRequest,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::videomanager::v1::{
    create_ingress_stream_request::Ingress, CreateIngressStreamRequest, GetIngressStreamRequest,
    RtspSettings,
};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::taskmanager::v1::tonic::task_manager_api_client::TaskManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::videomanager::v1::tonic::video_manager_api_client::VideoManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use prost_types::Timestamp;
use serde_json::{json, Value};
use tonic::metadata::{Ascii, MetadataValue};
use tonic::service::interceptor::InterceptedService;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::{Code, Request};
use uuid::Uuid;

use std::collections::BTreeSet;
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::sync::LazyLock;
use std::time::{SystemTime, UNIX_EPOCH};

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME: &str = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
static INGRESS_ID: LazyLock<String> = LazyLock::new(|| format!("{}.cam", ASSET_NAME));
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
static ENTITY_ID: LazyLock<String> = LazyLock::new(|| {
    let name = format!("urn:my-integration:{}", ASSET_NAME);
    Uuid::new_v5(&Uuid::NAMESPACE_URL, name.as_bytes()).to_string()
});
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL: &str = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE: &str = "agent_state.json";

type Interceptor = Box<dyn FnMut(Request<()>) -> Result<Request<()>, tonic::Status> + Send + Sync>;
type VideoClient = VideoManagerApiClient<InterceptedService<Channel, Interceptor>>;
type EntityClient = EntityManagerApiClient<InterceptedService<Channel, Interceptor>>;
type TaskClient = TaskManagerApiClient<InterceptedService<Channel, Interceptor>>;

fn now_timestamp() -> Timestamp {
    let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    Timestamp {
        seconds: d.as_secs() as i64,
        nanos: d.subsec_nanos() as i32,
    }
}

fn load_task_ids() -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
    let contents = match fs::read_to_string(STATE_FILE) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(error.into()),
    };
    let state: Value = contents.parse()?;
    let task_ids = state["task_ids"].as_array().ok_or("task_ids is missing")?;
    Ok(task_ids.iter().filter_map(|id| id.as_str().map(String::from)).collect())
}

fn save_task_ids(task_ids: &BTreeSet<String>) -> std::io::Result<()> {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    let temp_path = format!("{}.tmp", STATE_FILE);
    let mut file = File::create(&temp_path)?;
    file.write_all(json!({ "task_ids": task_ids }).to_string().as_bytes())?;
    file.sync_all()?;
    fs::rename(&temp_path, STATE_FILE)
}

fn track_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.insert(task_id.to_string());
    save_task_ids(task_ids)
}

fn untrack_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.remove(task_id);
    save_task_ids(task_ids)
}

async fn reconnect_video(client: &mut VideoClient) -> Result<(), tonic::Status> {
    let request = Request::new(GetIngressStreamRequest {
        ingress_id: INGRESS_ID.clone(),
    });
    match client.get_ingress_stream(request).await {
        Ok(response) => {
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            let status = response
                .into_inner()
                .ingress_stream
                .map(|stream| stream.status().as_str_name())
                .unwrap_or_default();
            println!("Reusing stream {} with status {}", *INGRESS_ID, status);
            return Ok(());
        }
        Err(status) if status.code() == Code::NotFound => {}
        Err(status) => return Err(status),
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    let request = Request::new(CreateIngressStreamRequest {
        ingress_id: Some(INGRESS_ID.clone()),
        title: ASSET_NAME.to_string(),
        ingress: Some(Ingress::Rtsp(RtspSettings {
            url: Some(RTSP_URL.to_string()),
        })),
    });
    client.create_ingress_stream(request).await?;
    println!("Created stream {}", *INGRESS_ID);
    Ok(())
}

async fn publish_entity(client: &mut EntityClient) -> Result<(), tonic::Status> {
    let now = now_timestamp();
    let entity = Entity {
        entity_id: ENTITY_ID.clone(),
        is_live: true,
        expiry_time: Some(Timestamp {
            seconds: now.seconds + 5 * 60,
            nanos: now.nanos,
        }),
        aliases: Some(Aliases {
            name: ASSET_NAME.to_string(),
            ..Default::default()
        }),
        mil_view: Some(MilView {
            disposition: Disposition::Friendly as i32,
            environment: Environment::Land as i32,
            ..Default::default()
        }),
        ontology: Some(Ontology {
            template: Template::Asset as i32,
            platform_type: "CAMERA".to_string(),
            ..Default::default()
        }),
        location: Some(Location {
            position: Some(Position {
                latitude_degrees: 33.6411,
                longitude_degrees: -117.9187,
                ..Default::default()
            }),
            ..Default::default()
        }),
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: Some(Media {
            media: vec![MediaItem {
                item_identifier: INGRESS_ID.clone(),
                r#type: MediaType::Video as i32,
                ..Default::default()
            }],
        }),
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: Some(Provenance {
            integration_name: "my-integration".to_string(),
            data_type: "asset".to_string(),
            source_update_time: Some(now),
            ..Default::default()
        }),
        ..Default::default()
    };
    client
        .publish_entity(Request::new(PublishEntityRequest {
            entity: Some(entity),
        }))
        .await?;
    println!("Republished entity {}", *ENTITY_ID);
    Ok(())
}

async fn resolve_tracked_tasks(
    client: &mut TaskClient,
    task_ids: &mut BTreeSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let author = Principal {
        agent: Some(principal::Agent::System(System {
            entity_id: ENTITY_ID.clone(),
            ..Default::default()
        })),
        ..Default::default()
    };
    for task_id in task_ids.clone() {
        let request = Request::new(GetTaskRequest {
            task_id: task_id.clone(),
            ..Default::default()
        });
        let task = match client.get_task(request).await {
            Ok(response) => response.into_inner().task,
            Err(status) if status.code() == Code::NotFound => {
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            Err(status) => return Err(status.into()),
        };
        let Some((status, version)) = task.as_ref().and_then(|task| task.status.as_ref().zip(task.version.as_ref()))
        else {
            println!("Task {} is missing its status or version. Skipping.", task_id);
            continue;
        };

        let cancelled = status.status() == Status::CancelRequested
            || task.as_ref().and_then(|task| task.delivery_state.as_ref()).map(|state| state.status())
                == Some(DeliveryStatus::PendingCancel);
        let error = match status.status() {
            Status::DoneOk | Status::DoneNotOk => {
                // An operator or another system closed the task while the agent was offline.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in delivery_state, not in the task status. Accept the cancellation.
            _ if cancelled => TaskError {
                code: ErrorCode::Cancelled as i32,
                message: "Cancelled while the agent was offline.".to_string(),
                ..Default::default()
            },
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            _ => TaskError {
                code: ErrorCode::Failed as i32,
                message: "Agent restarted and could not resume the task.".to_string(),
                ..Default::default()
            },
        };
        let code = error.code().as_str_name();

        // Read status_version from GetTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        let status_update = StatusUpdate {
            version: Some(TaskVersion {
                task_id: task_id.clone(),
                status_version: version.status_version + 1,
                ..Default::default()
            }),
            status: Some(TaskStatus {
                status: Status::DoneNotOk as i32,
                task_error: Some(error),
                ..Default::default()
            }),
            author: Some(author.clone()),
            ..Default::default()
        };
        client
            .update_status(Request::new(UpdateStatusRequest {
                status_update: Some(status_update),
            }))
            .await?;
        println!("Closed task {} with {}", task_id, code);
        untrack_task(task_ids, &task_id)?;
    }
    Ok(())
}

fn auth_interceptor(
    auth_header: MetadataValue<Ascii>,
    sandbox_header: MetadataValue<Ascii>,
) -> Interceptor {
    Box::new(move |mut req: Request<()>| {
        req.metadata_mut()
            .insert("authorization", auth_header.clone());
        req.metadata_mut()
            .insert("anduril-sandbox-authorization", sandbox_header.clone());
        Ok(req)
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    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");
    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables");
        std::process::exit(1);
    }

    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

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

    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<Ascii> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<Ascii> = format!("Bearer {}", sandboxes_token).parse()?;

    // All three clients share the same channel and inject the same auth metadata.
    let mut video_client: VideoClient = VideoManagerApiClient::with_interceptor(
        channel.clone(),
        auth_interceptor(auth_header.clone(), sandbox_header.clone()),
    );
    let mut entity_client: EntityClient = EntityManagerApiClient::with_interceptor(
        channel.clone(),
        auth_interceptor(auth_header.clone(), sandbox_header.clone()),
    );
    let mut task_client: TaskClient = TaskManagerApiClient::with_interceptor(
        channel,
        auth_interceptor(auth_header, sandbox_header),
    );

    let mut task_ids = load_task_ids()?;
    let result: Result<(), Box<dyn std::error::Error>> = async {
        reconnect_video(&mut video_client).await?;
        publish_entity(&mut entity_client).await?;
        resolve_tracked_tasks(&mut task_client, &mut task_ids).await?;
        Ok(())
    }
    .await;
    if let Err(error) = result {
        eprintln!("Failed to recover after restart: {}", error);
        std::process::exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // track_task and untrack_task as tasks start and finish.
    Ok(())
}

```

Publish your entity with the same `entity_id`. This extends its `expiry_time` and replaces stale components with current data.
Because the ingress ID doesn't change, the entity lists the same stream in `media` every time.

```go title={"Go (REST)"} startLine={145} maxLines={39}
// This Go example uses the Lattice REST SDK (lattice-sdk-go) to recover an integration's video
// stream, entity, and tasks after the integration restarts.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"maps"
	"net/http"
	"os"
	"path/filepath"
	"slices"
	"time"

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

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"

// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"

// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()

const (
	// RTSP source that Lattice pulls video from. Replace before running.
	rtspURL = "rtsp://<rtsp-host>:<port>/cam"
	// Local file that stores the IDs of tasks this agent is executing.
	stateFile = "agent_state.json"
)

var terminalStatuses = map[Lattice.TaskStatusStatus]bool{
	Lattice.TaskStatusStatusStatusDoneOk:    true,
	Lattice.TaskStatusStatusStatusDoneNotOk: true,
}

type agentState struct {
	TaskIDs []string `json:"task_ids"`
}

func loadTaskIDs() (map[string]bool, error) {
	taskIDs := map[string]bool{}
	data, err := os.ReadFile(stateFile)
	if errors.Is(err, os.ErrNotExist) {
		return taskIDs, nil
	}
	if err != nil {
		return nil, err
	}
	var state agentState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	for _, taskID := range state.TaskIDs {
		taskIDs[taskID] = true
	}
	return taskIDs, nil
}

func saveTaskIDs(taskIDs map[string]bool) error {
	ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
	slices.Sort(ids)
	data, err := json.Marshal(agentState{TaskIDs: ids})
	if err != nil {
		return err
	}
	// Write to a temporary file, then rename it over the original. A power loss during the
	// write leaves the previous file intact instead of a truncated one.
	f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	if _, err := f.Write(data); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), stateFile)
}

// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
	taskIDs[taskID] = true
	return saveTaskIDs(taskIDs)
}

// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
	delete(taskIDs, taskID)
	return saveTaskIDs(taskIDs)
}

func reconnectVideo(ctx context.Context, client *client.Client) error {
	response, err := client.Video.GetIngressStream(ctx, &Lattice.GetIngressStreamRequest{
		IngressID: ingressID,
	})
	var apiErr *core.APIError
	if err == nil {
		// The stream survived the restart. Reuse it instead of creating a duplicate.
		status := ""
		if s := response.GetIngressStream().GetStatus(); s != nil {
			status = string(*s)
		}
		fmt.Printf("Reusing stream %s with status %s\n", ingressID, status)
		return nil
	}
	if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
		return err
	}

	// Lattice returns not found both for a stream that never existed and for one that was deleted.
	_, err = client.Video.CreateIngressStream(ctx, &Lattice.CreateIngressStreamRequest{
		IngressID: Lattice.String(ingressID),
		Title:     Lattice.String(assetName),
		Rtsp: &Lattice.RtspSettings{
			URL: Lattice.String(rtspURL),
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Created stream %s\n", ingressID)
	return nil
}

func publishEntity(ctx context.Context, client *client.Client) error {
	now := time.Now().UTC()
	_, err := client.Entities.PublishEntity(ctx, &Lattice.Entity{
		EntityID:   Lattice.String(entityID),
		IsLive:     Lattice.Bool(true),
		ExpiryTime: Lattice.Time(now.Add(5 * time.Minute)),
		Aliases:    &Lattice.Aliases{Name: Lattice.String(assetName)},
		MilView: &Lattice.MilView{
			Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
			Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
		},
		Ontology: &Lattice.Ontology{
			Template:     Lattice.OntologyTemplateTemplateAsset.Ptr(),
			PlatformType: Lattice.String("CAMERA"),
		},
		Location: &Lattice.Location{
			Position: &Lattice.Position{
				LatitudeDegrees:  Lattice.Float64(33.6411),
				LongitudeDegrees: Lattice.Float64(-117.9187),
			},
		},
		// Because ingressID never changes, the entity can reference the stream on every publish.
		Media: &Lattice.Media{Media: []*Lattice.MediaItem{{
			ItemIdentifier: Lattice.String(ingressID),
			Type:           Lattice.MediaItemTypeMediaTypeVideo.Ptr(),
		}}},
		// Include every other component your integration publishes, such as its TaskCatalog.
		Provenance: &Lattice.Provenance{
			IntegrationName:  Lattice.String("my-integration"),
			DataType:         Lattice.String("asset"),
			SourceUpdateTime: Lattice.Time(now),
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Republished entity %s\n", entityID)
	return nil
}

func resolveTrackedTasks(ctx context.Context, client *client.Client, taskIDs map[string]bool) error {
	author := &Lattice.Principal{System: &Lattice.System{EntityID: Lattice.String(entityID)}}
	for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
		task, err := client.Tasks.GetTask(ctx, &Lattice.GetTaskRequest{TaskID: taskID})
		var apiErr *core.APIError
		if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
			// The task no longer exists in Lattice, so there's nothing to resolve.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
		if task.Status == nil || task.Status.Status == nil || task.Version == nil || task.Version.StatusVersion == nil {
			fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
			continue
		}

		status := *task.Status.Status
		if terminalStatuses[status] {
			// An operator or another system closed the task while the agent was offline.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}

		var taskError *Lattice.TaskError
		cancelled := status == Lattice.TaskStatusStatusStatusCancelRequested ||
			(task.GetDeliveryState().GetStatus() != nil &&
				*task.GetDeliveryState().GetStatus() == Lattice.DeliveryStateStatusDeliveryStatusPendingCancel)
		if cancelled {
			// An operator cancelled the task while the agent was offline. Lattice records the cancel
			// in delivery_state, not in the task status. Accept the cancellation.
			taskError = &Lattice.TaskError{
				Code:    Lattice.TaskErrorCodeErrorCodeCancelled.Ptr(),
				Message: Lattice.String("Cancelled while the agent was offline."),
			}
		} else {
			// The agent lost its execution context, so report the task as failed rather than
			// leave it active with nothing working on it.
			taskError = &Lattice.TaskError{
				Code:    Lattice.TaskErrorCodeErrorCodeFailed.Ptr(),
				Message: Lattice.String("Agent restarted and could not resume the task."),
			}
		}

		// Read the status version from GetTask, not from local state: the status might have
		// changed while the agent was offline, and Lattice ignores updates with a stale version.
		statusVersion := *task.Version.StatusVersion + 1
		_, err = client.Tasks.UpdateTaskStatus(ctx, &Lattice.TaskStatusUpdate{
			TaskID:        taskID,
			StatusVersion: &statusVersion,
			NewStatus: &Lattice.TaskStatus{
				Status:    Lattice.TaskStatusStatusStatusDoneNotOk.Ptr(),
				TaskError: taskError,
			},
			Author: author,
		})
		if err != nil {
			return err
		}
		fmt.Printf("Closed task %s with %s\n", taskID, *taskError.Code)
		if err := untrackTask(taskIDs, taskID); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	// Get environment variables
	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")

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

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

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

	ctx := context.Background()

	taskIDs, err := loadTaskIDs()
	if err != nil {
		fmt.Printf("Failed to load saved task IDs: %v\n", err)
		os.Exit(1)
	}
	if err := reconnectVideo(ctx, LatticeClient); err != nil {
		fmt.Printf("Failed to reconnect video: %v\n", err)
		os.Exit(1)
	}
	if err := publishEntity(ctx, LatticeClient); err != nil {
		fmt.Printf("Failed to republish entity: %v\n", err)
		os.Exit(1)
	}
	if err := resolveTrackedTasks(ctx, LatticeClient, taskIDs); err != nil {
		fmt.Printf("Failed to resolve tracked tasks: %v\n", err)
		os.Exit(1)
	}

	// Recovery is complete. Start your regular publish loop and agent stream here, and call
	// trackTask and untrackTask as tasks start and finish.
}

```

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

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.core.LatticeApiException;
import com.anduril.resources.tasks.requests.TaskStatusUpdate;
import com.anduril.resources.video.requests.CreateIngressStreamRequest;
import com.anduril.types.Aliases;
import com.anduril.types.DeliveryState;
import com.anduril.types.DeliveryStateStatus;
import com.anduril.types.Entity;
import com.anduril.types.Location;
import com.anduril.types.Media;
import com.anduril.types.MediaItem;
import com.anduril.types.MediaItemType;
import com.anduril.types.MilView;
import com.anduril.types.MilViewDisposition;
import com.anduril.types.MilViewEnvironment;
import com.anduril.types.Ontology;
import com.anduril.types.OntologyTemplate;
import com.anduril.types.Position;
import com.anduril.types.Principal;
import com.anduril.types.Provenance;
import com.anduril.types.RtspSettings;
import com.anduril.types.Task;
import com.anduril.types.TaskError;
import com.anduril.types.TaskErrorCode;
import com.anduril.types.TaskStatus;
import com.anduril.types.TaskStatusStatus;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * Recovers an integration's video stream, entity, and tasks with the Lattice SDK after the
 * integration restarts.
 */
public class HandleRestarts {
    // A name that is unique to this asset and never changes, such as a serial number read from
    // hardware or configuration. Replace before running.
    private static final String ASSET_NAME = "<ASSET-NAME>";
    // The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
    // so it's the same after every restart.
    private static final String INGRESS_ID = ASSET_NAME + ".cam";
    // The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
    // and in every language.
    // NAMESPACE_URL is the standard RFC 9562 URL namespace.
    private static final UUID NAMESPACE_URL = UUID.fromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8");
    private static final String ENTITY_ID = uuid5(NAMESPACE_URL, "urn:my-integration:" + ASSET_NAME).toString();
    // RTSP source that Lattice pulls video from. Replace before running.
    private static final String RTSP_URL = "rtsp://<rtsp-host>:<port>/cam";
    // Local file that stores the IDs of tasks this agent is executing.
    private static final Path STATE_FILE = Path.of("agent_state.json");

    private static final List<TaskStatusStatus> TERMINAL_STATUSES =
        List.of(TaskStatusStatus.STATUS_DONE_OK, TaskStatusStatus.STATUS_DONE_NOT_OK);

    private static final ObjectMapper JSON = new ObjectMapper();

    private static Set<String> loadTaskIds() throws IOException {
        Set<String> taskIds = new HashSet<>();
        if (!Files.exists(STATE_FILE)) {
            return taskIds;
        }
        for (JsonNode taskId : JSON.readTree(STATE_FILE.toFile()).path("task_ids")) {
            taskIds.add(taskId.asText());
        }
        return taskIds;
    }

    private static void saveTaskIds(Set<String> taskIds) throws IOException {
        // Write to a temporary file, then rename it over the original. A power loss during the
        // write leaves the previous file intact instead of a truncated one.
        Path target = STATE_FILE.toAbsolutePath();
        Path temp = Files.createTempFile(target.getParent(), "agent_state", ".tmp");
        ObjectNode state = JSON.createObjectNode();
        ArrayNode ids = state.putArray("task_ids");
        for (String taskId : new TreeSet<>(taskIds)) {
            ids.add(taskId);
        }
        try (FileChannel channel = FileChannel.open(temp, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(JSON.writeValueAsBytes(state)));
            channel.force(true);
        }
        Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE);
    }

    private static void trackTask(Set<String> taskIds, String taskId) throws IOException {
        // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
        taskIds.add(taskId);
        saveTaskIds(taskIds);
    }

    private static void untrackTask(Set<String> taskIds, String taskId) throws IOException {
        // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
        taskIds.remove(taskId);
        saveTaskIds(taskIds);
    }

    private static void reconnectVideo(Lattice client) {
        try {
            String status = client.video().getIngressStream(INGRESS_ID).getIngressStream()
                .flatMap(stream -> stream.getStatus()).map(Object::toString).orElse("");
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            System.out.println("Reusing stream " + INGRESS_ID + " with status " + status);
            return;
        } catch (LatticeApiException e) {
            if (e.statusCode() != 404) {
                throw e;
            }
        }

        // Lattice returns not found both for a stream that never existed and for one that was deleted.
        client.video().createIngressStream(CreateIngressStreamRequest.builder()
            .ingressId(INGRESS_ID)
            .title(ASSET_NAME)
            .rtsp(RtspSettings.builder()
                .url(RTSP_URL)
                .build())
            .build());
        System.out.println("Created stream " + INGRESS_ID);
    }

    private static void publishEntity(Lattice client) {
        OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
        client.entities().publishEntity(Entity.builder()
            .entityId(ENTITY_ID)
            .isLive(true)
            .expiryTime(now.plusMinutes(5))
            .aliases(Aliases.builder().name(ASSET_NAME).build())
            .milView(MilView.builder()
                .disposition(MilViewDisposition.DISPOSITION_FRIENDLY)
                .environment(MilViewEnvironment.ENVIRONMENT_LAND)
                .build())
            .ontology(Ontology.builder().template(OntologyTemplate.TEMPLATE_ASSET).platformType("CAMERA").build())
            .location(Location.builder()
                .position(Position.builder().latitudeDegrees(33.6411).longitudeDegrees(-117.9187).build())
                .build())
            // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
            .media(Media.builder()
                .media(List.of(MediaItem.builder().itemIdentifier(INGRESS_ID).type(MediaItemType.MEDIA_TYPE_VIDEO).build()))
                .build())
            // Include every other component your integration publishes, such as its TaskCatalog.
            .provenance(Provenance.builder()
                .integrationName("my-integration")
                .dataType("asset")
                .sourceUpdateTime(now)
                .build())
            .build());
        System.out.println("Republished entity " + ENTITY_ID);
    }

    private static void resolveTrackedTasks(Lattice client, Set<String> taskIds) throws IOException {
        Principal author = Principal.builder()
            .system(com.anduril.types.System.builder().entityId(ENTITY_ID).build())
            .build();
        for (String taskId : new TreeSet<>(taskIds)) {
            Task task;
            try {
                task = client.tasks().getTask(taskId);
            } catch (LatticeApiException e) {
                if (e.statusCode() != 404) {
                    throw e;
                }
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrackTask(taskIds, taskId);
                continue;
            }
            if (task.getStatus().isEmpty() || task.getStatus().get().getStatus().isEmpty()
                    || task.getVersion().isEmpty() || task.getVersion().get().getStatusVersion().isEmpty()) {
                System.out.println("Task " + taskId + " is missing its status or version. Skipping.");
                continue;
            }
            TaskStatusStatus status = task.getStatus().get().getStatus().get();
            int statusVersion = task.getVersion().get().getStatusVersion().get();

            if (TERMINAL_STATUSES.contains(status)) {
                // An operator or another system closed the task while the agent was offline.
                untrackTask(taskIds, taskId);
                continue;
            }

            TaskError error;
            boolean pendingCancel = task.getDeliveryState().flatMap(DeliveryState::getStatus)
                .map(DeliveryStateStatus.DELIVERY_STATUS_PENDING_CANCEL::equals).orElse(false);
            if (status.equals(TaskStatusStatus.STATUS_CANCEL_REQUESTED) || pendingCancel) {
                // An operator cancelled the task while the agent was offline. Lattice records the cancel
                // in deliveryState, not in the task status. Accept the cancellation.
                error = TaskError.builder()
                    .code(TaskErrorCode.ERROR_CODE_CANCELLED)
                    .message("Cancelled while the agent was offline.")
                    .build();
            } else {
                // The agent lost its execution context, so report the task as failed rather than
                // leave it active with nothing working on it.
                error = TaskError.builder()
                    .code(TaskErrorCode.ERROR_CODE_FAILED)
                    .message("Agent restarted and could not resume the task.")
                    .build();
            }

            // Read the status version from GetTask, not from local state: the status might have
            // changed while the agent was offline, and Lattice ignores updates with a stale version.
            client.tasks().updateTaskStatus(taskId, TaskStatusUpdate.builder()
                .statusVersion(statusVersion + 1)
                .newStatus(TaskStatus.builder()
                    .status(TaskStatusStatus.STATUS_DONE_NOT_OK)
                    .taskError(error)
                    .build())
                .author(author)
                .build());
            System.out.println("Closed task " + taskId + " with " + error.getCode().map(Object::toString).orElse(""));
            untrackTask(taskIds, taskId);
        }
    }

    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 and ensure the endpoint has its scheme
        if (isBlank(endpoint) || isBlank(environmentToken) || isBlank(sandboxesToken)) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        // Create Lattice client with Sandbox authentication
        Lattice client = Lattice.builder()
            .url(endpoint)
            .token(environmentToken)
            .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
            .build();

        try {
            Set<String> taskIds = loadTaskIds();
            reconnectVideo(client);
            publishEntity(client);
            resolveTrackedTasks(client, taskIds);
        } catch (Exception e) {
            System.err.println("Failed to recover after restart: " + e.getMessage());
            System.exit(1);
        }

        // Recovery is complete. Start your regular publish loop and agent stream here, and call
        // trackTask and untrackTask as tasks start and finish.
    }

    private static boolean isBlank(String value) {
        return value == null || value.isEmpty();
    }

    /**
     * Returns a name-based version 5 UUID, which is the same every time for the same namespace and name.
     */
    private static UUID uuid5(UUID namespace, String name) {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            sha1.update(ByteBuffer.allocate(16)
                .putLong(namespace.getMostSignificantBits())
                .putLong(namespace.getLeastSignificantBits())
                .array());
            sha1.update(name.getBytes(StandardCharsets.UTF_8));
            byte[] hash = sha1.digest();
            hash[6] = (byte) ((hash[6] & 0x0f) | 0x50); // Version 5
            hash[8] = (byte) ((hash[8] & 0x3f) | 0x80); // RFC 9562 variant
            ByteBuffer bytes = ByteBuffer.wrap(hash, 0, 16);
            return new UUID(bytes.getLong(), bytes.getLong());
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("SHA-1 is unavailable", e);
        }
    }
}

```

```py title={"Python (REST)"} startLine={96} maxLines={20}
# This Python example uses the Lattice REST SDK (anduril-lattice-sdk) to recover an integration's
# video stream, entity, and tasks after the integration restarts.

import json
import os
import sys
import tempfile
import uuid
from datetime import datetime, timedelta, timezone

from anduril import (
    Aliases,
    Lattice,
    Location,
    Media,
    MediaItem,
    MilView,
    Ontology,
    Position,
    Principal,
    Provenance,
    RtspSettings,
    System,
    TaskError,
    TaskStatus,
)
from anduril.core import ApiError

# A name that is unique to this asset and never changes, such as a serial number read from
# hardware or configuration. Replace before running.
ASSET_NAME = "<ASSET-NAME>"
# The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
# so it's the same after every restart.
INGRESS_ID = f"{ASSET_NAME}.cam"
# The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
# and in every language.
ENTITY_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:my-integration:{ASSET_NAME}"))
# RTSP source that Lattice pulls video from. Replace before running.
RTSP_URL = "rtsp://<rtsp-host>:<port>/cam"
# Local file that stores the IDs of tasks this agent is executing.
STATE_FILE = "agent_state.json"

TERMINAL_STATUSES = {"STATUS_DONE_OK", "STATUS_DONE_NOT_OK"}


def load_task_ids():
    try:
        with open(STATE_FILE) as f:
            return set(json.load(f)["task_ids"])
    except FileNotFoundError:
        return set()


def save_task_ids(task_ids):
    # Write to a temporary file, then rename it over the original. A power loss during the
    # write leaves the previous file intact instead of a truncated one.
    directory = os.path.dirname(os.path.abspath(STATE_FILE))
    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f:
        json.dump({"task_ids": sorted(task_ids)}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(f.name, STATE_FILE)


def track_task(task_ids, task_id):
    # Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.add(task_id)
    save_task_ids(task_ids)


def untrack_task(task_ids, task_id):
    # Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.discard(task_id)
    save_task_ids(task_ids)


def reconnect_video(client):
    try:
        stream = client.video.get_ingress_stream(INGRESS_ID).ingress_stream
        # The stream survived the restart. Reuse it instead of creating a duplicate.
        print(f"Reusing stream {INGRESS_ID} with status {stream.status}")
        return
    except ApiError as error:
        if error.status_code != 404:
            raise

    # Lattice returns not found both for a stream that never existed and for one that was deleted.
    client.video.create_ingress_stream(
        ingress_id=INGRESS_ID,
        title=ASSET_NAME,
        rtsp=RtspSettings(url=RTSP_URL),
    )
    print(f"Created stream {INGRESS_ID}")


def publish_entity(client):
    now = datetime.now(timezone.utc)
    client.entities.publish_entity(
        entity_id=ENTITY_ID,
        is_live=True,
        expiry_time=now + timedelta(minutes=5),
        aliases=Aliases(name=ASSET_NAME),
        mil_view=MilView(disposition="DISPOSITION_FRIENDLY", environment="ENVIRONMENT_LAND"),
        ontology=Ontology(template="TEMPLATE_ASSET", platform_type="CAMERA"),
        location=Location(position=Position(latitude_degrees=33.6411, longitude_degrees=-117.9187)),
        # Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media=Media(media=[MediaItem(item_identifier=INGRESS_ID, type="MEDIA_TYPE_VIDEO")]),
        # Include every other component your integration publishes, such as its TaskCatalog.
        provenance=Provenance(
            integration_name="my-integration",
            data_type="asset",
            source_update_time=now,
        ),
    )
    print(f"Republished entity {ENTITY_ID}")


def resolve_tracked_tasks(client, task_ids):
    author = Principal(system=System(entity_id=ENTITY_ID))
    for task_id in sorted(task_ids):
        try:
            task = client.tasks.get_task(task_id)
        except ApiError as error:
            if error.status_code != 404:
                raise
            # The task no longer exists in Lattice, so there's nothing to resolve.
            untrack_task(task_ids, task_id)
            continue
        if not task.status or not task.version or task.version.status_version is None:
            print(f"Task {task_id} is missing its status or version. Skipping.")
            continue

        if task.status.status in TERMINAL_STATUSES:
            # An operator or another system closed the task while the agent was offline.
            untrack_task(task_ids, task_id)
            continue

        pending_cancel = task.delivery_state and task.delivery_state.status == "DELIVERY_STATUS_PENDING_CANCEL"
        if task.status.status == "STATUS_CANCEL_REQUESTED" or pending_cancel:
            # An operator cancelled the task while the agent was offline. Lattice records the cancel
            # in delivery_state, not in the task status. Accept the cancellation.
            error = TaskError(code="ERROR_CODE_CANCELLED", message="Cancelled while the agent was offline.")
        else:
            # The agent lost its execution context, so report the task as failed rather than
            # leave it active with nothing working on it.
            error = TaskError(code="ERROR_CODE_FAILED", message="Agent restarted and could not resume the task.")

        # Read status_version from GetTask, not from local state: the status might have
        # changed while the agent was offline, and Lattice ignores updates with a stale version.
        client.tasks.update_task_status(
            task_id,
            status_version=task.version.status_version + 1,
            new_status=TaskStatus(status="STATUS_DONE_NOT_OK", task_error=error),
            author=author,
        )
        print(f"Closed task {task_id} with {error.code}")
        untrack_task(task_ids, task_id)


def main():
    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)

    client = Lattice(
        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}"},
    )

    task_ids = load_task_ids()
    try:
        reconnect_video(client)
        publish_entity(client)
        resolve_tracked_tasks(client, task_ids)
    except Exception as error:
        print(f"Failed to recover after restart: {error}", file=sys.stderr)
        sys.exit(1)

    # Recovery is complete. Start your regular publish loop and agent stream here, and call
    # track_task and untrack_task as tasks start and finish.


if __name__ == "__main__":
    main()

```

```ts title={"TypeScript (REST)"} startLine={83} maxLines={21}
// This TypeScript example uses the Lattice REST SDK (@anduril-industries/lattice-sdk) to recover an
// integration's video stream, entity, and tasks after the integration restarts.

import * as fs from "node:fs";
import * as path from "node:path";
import { Lattice, LatticeClient, LatticeError } from "@anduril-industries/lattice-sdk";
import { v5 as uuidv5 } from "uuid";

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
const INGRESS_ID = `${ASSET_NAME}.cam`;
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
const ENTITY_ID = uuidv5(`urn:my-integration:${ASSET_NAME}`, uuidv5.URL);
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE = "agent_state.json";

const TERMINAL_STATUSES = new Set<string | undefined>(["STATUS_DONE_OK", "STATUS_DONE_NOT_OK"]);

function loadTaskIds(): Set<string> {
    try {
        return new Set<string>(JSON.parse(fs.readFileSync(STATE_FILE, "utf8")).task_ids);
    } catch (error) {
        if ((error as NodeJS.ErrnoException).code === "ENOENT") {
            return new Set<string>();
        }
        throw error;
    }
}

function saveTaskIds(taskIds: Set<string>) {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    const tempFile = path.join(path.dirname(path.resolve(STATE_FILE)), `.${path.basename(STATE_FILE)}.${process.pid}.tmp`);
    const fd = fs.openSync(tempFile, "w");
    try {
        fs.writeSync(fd, JSON.stringify({ task_ids: [...taskIds].sort() }));
        fs.fsyncSync(fd);
    } finally {
        fs.closeSync(fd);
    }
    fs.renameSync(tempFile, STATE_FILE);
}

export function trackTask(taskIds: Set<string>, taskId: string) {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    taskIds.add(taskId);
    saveTaskIds(taskIds);
}

export function untrackTask(taskIds: Set<string>, taskId: string) {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    taskIds.delete(taskId);
    saveTaskIds(taskIds);
}

async function reconnectVideo(client: LatticeClient) {
    try {
        const { ingressStream } = await client.video.getIngressStream({ ingressId: INGRESS_ID });
        // The stream survived the restart. Reuse it instead of creating a duplicate.
        console.log(`Reusing stream ${INGRESS_ID} with status ${ingressStream?.status}`);
        return;
    } catch (error) {
        if (!(error instanceof LatticeError && error.statusCode === 404)) {
            throw error;
        }
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    await client.video.createIngressStream({
        ingressId: INGRESS_ID,
        title: ASSET_NAME,
        rtsp: { url: RTSP_URL },
    });
    console.log(`Created stream ${INGRESS_ID}`);
}

async function publishEntity(client: LatticeClient) {
    const now = new Date();
    await client.entities.publishEntity({
        entityId: ENTITY_ID,
        isLive: true,
        expiryTime: new Date(now.getTime() + 5 * 60 * 1000).toISOString(),
        aliases: { name: ASSET_NAME },
        milView: { disposition: "DISPOSITION_FRIENDLY", environment: "ENVIRONMENT_LAND" },
        ontology: { template: "TEMPLATE_ASSET", platformType: "CAMERA" },
        location: { position: { latitudeDegrees: 33.6411, longitudeDegrees: -117.9187 } },
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: { media: [{ itemIdentifier: INGRESS_ID, type: "MEDIA_TYPE_VIDEO" }] },
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: {
            integrationName: "my-integration",
            dataType: "asset",
            sourceUpdateTime: now.toISOString(),
        },
    });
    console.log(`Republished entity ${ENTITY_ID}`);
}

async function resolveTrackedTasks(client: LatticeClient, taskIds: Set<string>) {
    const author = { system: { entityId: ENTITY_ID } };
    for (const taskId of [...taskIds].sort()) {
        let task: Lattice.Task;
        try {
            task = await client.tasks.getTask({ taskId });
        } catch (error) {
            if (!(error instanceof LatticeError && error.statusCode === 404)) {
                throw error;
            }
            // The task no longer exists in Lattice, so there's nothing to resolve.
            untrackTask(taskIds, taskId);
            continue;
        }
        const statusVersion = task.version?.statusVersion;
        if (!task.status || statusVersion === undefined) {
            console.log(`Task ${taskId} is missing its status or version. Skipping.`);
            continue;
        }

        if (TERMINAL_STATUSES.has(task.status.status)) {
            // An operator or another system closed the task while the agent was offline.
            untrackTask(taskIds, taskId);
            continue;
        }

        let taskError: Lattice.TaskError;
        const pendingCancel = task.deliveryState?.status === "DELIVERY_STATUS_PENDING_CANCEL";
        if (task.status.status === "STATUS_CANCEL_REQUESTED" || pendingCancel) {
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in deliveryState, not in the task status. Accept the cancellation.
            taskError = { code: "ERROR_CODE_CANCELLED", message: "Cancelled while the agent was offline." };
        } else {
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            taskError = { code: "ERROR_CODE_FAILED", message: "Agent restarted and could not resume the task." };
        }

        // Read statusVersion from getTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        await client.tasks.updateTaskStatus({
            taskId,
            statusVersion: statusVersion + 1,
            newStatus: { status: "STATUS_DONE_NOT_OK", taskError },
            author,
        });
        console.log(`Closed task ${taskId} with ${taskError.code}`);
        untrackTask(taskIds, taskId);
    }
}

async function App() {
    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,
            // Remove the following if you are not developing on Sandboxes.
            headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}`  }
        }
    );

    const taskIds = loadTaskIds();
    try {
        await reconnectVideo(client);
        await publishEntity(client);
        await resolveTrackedTasks(client, taskIds);
    } catch (error) {
        console.error(`Failed to recover after restart: ${error}`);
        process.exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // trackTask and untrackTask as tasks start and finish.
}

App();

```

```rs title={"Rust (REST)"} startLine={97} maxLines={50}
// This Rust example uses the Lattice REST SDK (anduril-lattice-sdk) to recover an integration's
// video stream, entity, and tasks after the integration restarts.

// track_task is called from the main loop you add after recovery.
#![allow(dead_code)]

use anduril_lattice_sdk::prelude::*;

use std::collections::BTreeSet;
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::sync::LazyLock;
use uuid::Uuid;

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME: &str = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
static INGRESS_ID: LazyLock<String> = LazyLock::new(|| format!("{}.cam", ASSET_NAME));
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
static ENTITY_ID: LazyLock<String> = LazyLock::new(|| {
    let name = format!("urn:my-integration:{}", ASSET_NAME);
    Uuid::new_v5(&Uuid::NAMESPACE_URL, name.as_bytes()).to_string()
});
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL: &str = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE: &str = "agent_state.json";

fn load_task_ids() -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
    let contents = match fs::read_to_string(STATE_FILE) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(error.into()),
    };
    let state: Value = contents.parse()?;
    let task_ids = state["task_ids"].as_array().ok_or("task_ids is missing")?;
    Ok(task_ids.iter().filter_map(|id| id.as_str().map(String::from)).collect())
}

fn save_task_ids(task_ids: &BTreeSet<String>) -> std::io::Result<()> {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    let temp_path = format!("{}.tmp", STATE_FILE);
    let mut file = File::create(&temp_path)?;
    file.write_all(json!({ "task_ids": task_ids }).to_string().as_bytes())?;
    file.sync_all()?;
    fs::rename(&temp_path, STATE_FILE)
}

fn track_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.insert(task_id.to_string());
    save_task_ids(task_ids)
}

fn untrack_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.remove(task_id);
    save_task_ids(task_ids)
}

async fn reconnect_video(client: &Lattice) -> Result<(), ApiError> {
    match client.video.get_ingress_stream(&INGRESS_ID, None).await {
        Ok(response) => {
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            let status = response
                .ingress_stream
                .and_then(|stream| stream.status)
                .map(|status| status.to_string())
                .unwrap_or_default();
            println!("Reusing stream {} with status {}", *INGRESS_ID, status);
            return Ok(());
        }
        Err(ApiError::NotFoundError { .. }) => {}
        Err(error) => return Err(error),
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    let request = CreateIngressStreamRequest {
        ingress_id: Some(INGRESS_ID.clone()),
        title: Some(ASSET_NAME.to_string()),
        rtsp: Some(RtspSettings {
            url: Some(RTSP_URL.to_string()),
            ..Default::default()
        }),
        ..Default::default()
    };
    client.video.create_ingress_stream(&request, None).await?;
    println!("Created stream {}", *INGRESS_ID);
    Ok(())
}

async fn publish_entity(client: &Lattice) -> Result<(), ApiError> {
    let now = Utc::now();
    let entity = Entity {
        entity_id: Some(ENTITY_ID.clone()),
        is_live: Some(true),
        expiry_time: Some((now + chrono::Duration::minutes(5)).fixed_offset()),
        aliases: Some(Aliases {
            name: Some(ASSET_NAME.to_string()),
            ..Default::default()
        }),
        mil_view: Some(MilView {
            disposition: Some(MilViewDisposition::DispositionFriendly),
            environment: Some(MilViewEnvironment::EnvironmentLand),
            ..Default::default()
        }),
        ontology: Some(Ontology {
            template: Some(OntologyTemplate::TemplateAsset),
            platform_type: Some("CAMERA".to_string()),
            ..Default::default()
        }),
        location: Some(Location {
            position: Some(Position {
                latitude_degrees: Some(33.6411),
                longitude_degrees: Some(-117.9187),
                ..Default::default()
            }),
            ..Default::default()
        }),
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: Some(Media {
            media: Some(vec![MediaItem {
                item_identifier: Some(INGRESS_ID.clone()),
                r#type: Some(MediaItemType::MediaTypeVideo),
                ..Default::default()
            }]),
            ..Default::default()
        }),
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: Some(Provenance {
            integration_name: Some("my-integration".to_string()),
            data_type: Some("asset".to_string()),
            source_update_time: Some(now.fixed_offset()),
            ..Default::default()
        }),
        ..Default::default()
    };
    client.entities.publish_entity(&entity, None).await?;
    println!("Republished entity {}", *ENTITY_ID);
    Ok(())
}

async fn resolve_tracked_tasks(
    client: &Lattice,
    task_ids: &mut BTreeSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let author = Principal {
        system: Some(System {
            entity_id: Some(ENTITY_ID.clone()),
            ..Default::default()
        }),
        ..Default::default()
    };
    for task_id in task_ids.clone() {
        let task = match client.tasks.get_task(&task_id, None).await {
            Ok(task) => task,
            Err(ApiError::NotFoundError { .. }) => {
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            Err(error) => return Err(error.into()),
        };
        let (Some(status), Some(status_version)) = (
            task.status.as_ref(),
            task.version.as_ref().and_then(|version| version.status_version),
        ) else {
            println!("Task {} is missing its status or version. Skipping.", task_id);
            continue;
        };

        let cancelled = matches!(status.status, Some(TaskStatusStatus::StatusCancelRequested))
            || matches!(
                task.delivery_state.as_ref().and_then(|state| state.status.as_ref()),
                Some(DeliveryStateStatus::DeliveryStatusPendingCancel)
            );
        let error = match status.status {
            Some(TaskStatusStatus::StatusDoneOk | TaskStatusStatus::StatusDoneNotOk) => {
                // An operator or another system closed the task while the agent was offline.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in delivery_state, not in the task status. Accept the cancellation.
            _ if cancelled => TaskError {
                code: Some(TaskErrorCode::ErrorCodeCancelled),
                message: Some("Cancelled while the agent was offline.".to_string()),
                ..Default::default()
            },
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            _ => TaskError {
                code: Some(TaskErrorCode::ErrorCodeFailed),
                message: Some("Agent restarted and could not resume the task.".to_string()),
                ..Default::default()
            },
        };
        let code = error.code.as_ref().map(|code| code.to_string()).unwrap_or_default();

        // Read status_version from GetTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        let request = TaskStatusUpdate {
            status_version: Some(status_version + 1),
            new_status: Some(TaskStatus {
                status: Some(TaskStatusStatus::StatusDoneNotOk),
                task_error: Some(error),
                ..Default::default()
            }),
            author: Some(author.clone()),
        };
        client.tasks.update_task_status(&task_id, &request, None).await?;
        println!("Closed task {} with {}", task_id, code);
        untrack_task(task_ids, &task_id)?;
    }
    Ok(())
}

#[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)?;

    let mut task_ids = load_task_ids()?;
    let result: Result<(), Box<dyn std::error::Error>> = async {
        reconnect_video(&client).await?;
        publish_entity(&client).await?;
        resolve_tracked_tasks(&client, &mut task_ids).await?;
        Ok(())
    }
    .await;
    if let Err(error) = result {
        eprintln!("Failed to recover after restart: {}", error);
        std::process::exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // track_task and untrack_task as tasks start and finish.
    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={154} maxLines={39}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
//
// It recovers an integration's video stream, entity, and tasks after the integration restarts.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"maps"
	"os"
	"path/filepath"
	"slices"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/taskmanager/v1/taskmanagerv1grpc"
	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/videomanager/v1/videomanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	ontologyv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/ontology/v1"
	taskmanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/taskmanager/v1"
	videomanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/videomanager/v1"

	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"

// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"

// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()

const (
	// RTSP source that Lattice pulls video from. Replace before running.
	rtspURL = "rtsp://<rtsp-host>:<port>/cam"
	// Local file that stores the IDs of tasks this agent is executing.
	stateFile = "agent_state.json"
)

var terminalStatuses = map[taskmanagerv1.Status]bool{
	taskmanagerv1.Status_STATUS_DONE_OK:     true,
	taskmanagerv1.Status_STATUS_DONE_NOT_OK: true,
}

type agentState struct {
	TaskIDs []string `json:"task_ids"`
}

func loadTaskIDs() (map[string]bool, error) {
	taskIDs := map[string]bool{}
	data, err := os.ReadFile(stateFile)
	if errors.Is(err, os.ErrNotExist) {
		return taskIDs, nil
	}
	if err != nil {
		return nil, err
	}
	var state agentState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	for _, taskID := range state.TaskIDs {
		taskIDs[taskID] = true
	}
	return taskIDs, nil
}

func saveTaskIDs(taskIDs map[string]bool) error {
	ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
	slices.Sort(ids)
	data, err := json.Marshal(agentState{TaskIDs: ids})
	if err != nil {
		return err
	}
	// Write to a temporary file, then rename it over the original. A power loss during the
	// write leaves the previous file intact instead of a truncated one.
	f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	if _, err := f.Write(data); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), stateFile)
}

// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
	taskIDs[taskID] = true
	return saveTaskIDs(taskIDs)
}

// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
	delete(taskIDs, taskID)
	return saveTaskIDs(taskIDs)
}

func reconnectVideo(ctx context.Context, client videomanagerv1grpc.VideoManagerAPIClient) error {
	response, err := client.GetIngressStream(ctx, &videomanagerv1.GetIngressStreamRequest{
		IngressId: ingressID,
	})
	if err == nil {
		// The stream survived the restart. Reuse it instead of creating a duplicate.
		fmt.Printf("Reusing stream %s with status %s\n", ingressID, response.GetIngressStream().GetStatus())
		return nil
	}
	if status.Code(err) != codes.NotFound {
		return err
	}

	// Lattice returns not found both for a stream that never existed and for one that was deleted.
	_, err = client.CreateIngressStream(ctx, &videomanagerv1.CreateIngressStreamRequest{
		IngressId: proto.String(ingressID),
		Title:     assetName,
		Ingress: &videomanagerv1.CreateIngressStreamRequest_Rtsp{
			Rtsp: &videomanagerv1.RtspSettings{
				Url: proto.String(rtspURL),
			},
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Created stream %s\n", ingressID)
	return nil
}

func publishEntity(ctx context.Context, client entitymanagerv1grpc.EntityManagerAPIClient) error {
	now := time.Now().UTC()
	_, err := client.PublishEntity(ctx, &entitymanagerv1.PublishEntityRequest{Entity: &entitymanagerv1.Entity{
		EntityId:   entityID,
		IsLive:     true,
		ExpiryTime: timestamppb.New(now.Add(5 * time.Minute)),
		Aliases:    &entitymanagerv1.Aliases{Name: assetName},
		MilView: &entitymanagerv1.MilView{
			Disposition: ontologyv1.Disposition_DISPOSITION_FRIENDLY,
			Environment: ontologyv1.Environment_ENVIRONMENT_LAND,
		},
		Ontology: &entitymanagerv1.Ontology{
			Template:     entitymanagerv1.Template_TEMPLATE_ASSET,
			PlatformType: "CAMERA",
		},
		Location: &entitymanagerv1.Location{
			Position: &entitymanagerv1.Position{
				LatitudeDegrees:  33.6411,
				LongitudeDegrees: -117.9187,
			},
		},
		// Because ingressID never changes, the entity can reference the stream on every publish.
		Media: &entitymanagerv1.Media{Media: []*entitymanagerv1.MediaItem{{
			ItemIdentifier: ingressID,
			Type:           entitymanagerv1.MediaType_MEDIA_TYPE_VIDEO,
		}}},
		// Include every other component your integration publishes, such as its TaskCatalog.
		Provenance: &entitymanagerv1.Provenance{
			IntegrationName:  "my-integration",
			DataType:         "asset",
			SourceUpdateTime: timestamppb.New(now),
		},
	}})
	if err != nil {
		return err
	}
	fmt.Printf("Republished entity %s\n", entityID)
	return nil
}

func resolveTrackedTasks(ctx context.Context, client taskmanagerv1grpc.TaskManagerAPIClient, taskIDs map[string]bool) error {
	author := &taskmanagerv1.Principal{
		Agent: &taskmanagerv1.Principal_System{
			System: &taskmanagerv1.System{EntityId: entityID},
		},
	}
	for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
		response, err := client.GetTask(ctx, &taskmanagerv1.GetTaskRequest{TaskId: taskID})
		if status.Code(err) == codes.NotFound {
			// The task no longer exists in Lattice, so there's nothing to resolve.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
		task := response.GetTask()
		if task.GetStatus() == nil || task.GetVersion() == nil {
			fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
			continue
		}

		taskStatus := task.GetStatus().GetStatus()
		if terminalStatuses[taskStatus] {
			// An operator or another system closed the task while the agent was offline.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}

		var taskError *taskmanagerv1.TaskError
		cancelled := taskStatus == taskmanagerv1.Status_STATUS_CANCEL_REQUESTED ||
			task.GetDeliveryState().GetStatus() == taskmanagerv1.DeliveryStatus_DELIVERY_STATUS_PENDING_CANCEL
		if cancelled {
			// An operator cancelled the task while the agent was offline. Lattice records the cancel
			// in delivery_state, not in the task status. Accept the cancellation.
			taskError = &taskmanagerv1.TaskError{
				Code:    taskmanagerv1.ErrorCode_ERROR_CODE_CANCELLED,
				Message: "Cancelled while the agent was offline.",
			}
		} else {
			// The agent lost its execution context, so report the task as failed rather than
			// leave it active with nothing working on it.
			taskError = &taskmanagerv1.TaskError{
				Code:    taskmanagerv1.ErrorCode_ERROR_CODE_FAILED,
				Message: "Agent restarted and could not resume the task.",
			}
		}

		// Read the status version from GetTask, not from local state: the status might have
		// changed while the agent was offline, and Lattice ignores updates with a stale version.
		_, err = client.UpdateStatus(ctx, &taskmanagerv1.UpdateStatusRequest{
			StatusUpdate: &taskmanagerv1.StatusUpdate{
				Version: &taskmanagerv1.TaskVersion{
					TaskId:        taskID,
					StatusVersion: task.GetVersion().GetStatusVersion() + 1,
				},
				Status: &taskmanagerv1.TaskStatus{
					Status:    taskmanagerv1.Status_STATUS_DONE_NOT_OK,
					TaskError: taskError,
				},
				Author: author,
			},
		})
		if err != nil {
			return err
		}
		fmt.Printf("Closed task %s with %s\n", taskID, taskError.GetCode())
		if err := untrackTask(taskIDs, taskID); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	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()

	videoClient := videomanagerv1grpc.NewVideoManagerAPIClient(conn)
	entityClient := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)
	taskClient := taskmanagerv1grpc.NewTaskManagerAPIClient(conn)

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	taskIDs, err := loadTaskIDs()
	if err != nil {
		log.Fatalf("Failed to load saved task IDs: %v", err)
	}
	if err := reconnectVideo(ctx, videoClient); err != nil {
		log.Fatalf("Failed to reconnect video: %v", err)
	}
	if err := publishEntity(ctx, entityClient); err != nil {
		log.Fatalf("Failed to republish entity: %v", err)
	}
	if err := resolveTrackedTasks(ctx, taskClient, taskIDs); err != nil {
		log.Fatalf("Failed to resolve tracked tasks: %v", err)
	}

	// Recovery is complete. Start your regular publish loop and agent stream here, and call
	// trackTask and untrackTask as tasks start and finish.
}

```

```py title={"Python (gRPC)"} startLine={114} maxLines={21}
# 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
# It recovers an integration's video stream, entity, and tasks after the integration restarts.

import json
import os
import sys
import tempfile
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from connectrpc.code import Code
from connectrpc.errors import ConnectError
from protobuf import Oneof
from protobuf.wkt import Timestamp

from anduril.entitymanager.v1.entity_pub_pb import Aliases, Entity, Provenance
from anduril.entitymanager.v1.entity_manager_api_pub_pb import PublishEntityRequest
from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.location_pub_pb import Location, Position
from anduril.entitymanager.v1.media_pub_pb import Media, MediaItem, MediaType
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.ontology.v1.type_pub_pb import Disposition, Environment
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.taskmanager.v1.task_pub_pb import (
    DeliveryStatus,
    ErrorCode,
    Principal,
    Status,
    StatusUpdate,
    System,
    TaskError,
    TaskStatus,
    TaskVersion,
)
from anduril.taskmanager.v1.task_manager_api_pub_pb import GetTaskRequest, UpdateStatusRequest
from anduril.taskmanager.v1.task_manager_api_pub_connect import TaskManagerAPIClientSync
from anduril.videomanager.v1.create_ingress_stream_request_pub_pb import CreateIngressStreamRequest
from anduril.videomanager.v1.get_ingress_stream_request_pub_pb import GetIngressStreamRequest
from anduril.videomanager.v1.rtsp_settings_pub_pb import RtspSettings
from anduril.videomanager.v1.video_manager_api_pub_connect import VideoManagerAPIClientSync

# A name that is unique to this asset and never changes, such as a serial number read from
# hardware or configuration. Replace before running.
ASSET_NAME = "<ASSET-NAME>"
# The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
# so it's the same after every restart.
INGRESS_ID = f"{ASSET_NAME}.cam"
# The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
# and in every language.
ENTITY_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:my-integration:{ASSET_NAME}"))
# RTSP source that Lattice pulls video from. Replace before running.
RTSP_URL = "rtsp://<rtsp-host>:<port>/cam"
# Local file that stores the IDs of tasks this agent is executing.
STATE_FILE = "agent_state.json"

TERMINAL_STATUSES = {Status.DONE_OK, Status.DONE_NOT_OK}


def load_task_ids():
    try:
        with open(STATE_FILE) as f:
            return set(json.load(f)["task_ids"])
    except FileNotFoundError:
        return set()


def save_task_ids(task_ids):
    # Write to a temporary file, then rename it over the original. A power loss during the
    # write leaves the previous file intact instead of a truncated one.
    directory = os.path.dirname(os.path.abspath(STATE_FILE))
    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f:
        json.dump({"task_ids": sorted(task_ids)}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(f.name, STATE_FILE)


def track_task(task_ids, task_id):
    # Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.add(task_id)
    save_task_ids(task_ids)


def untrack_task(task_ids, task_id):
    # Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.discard(task_id)
    save_task_ids(task_ids)


def reconnect_video(client):
    try:
        response = client.get_ingress_stream(GetIngressStreamRequest(ingress_id=INGRESS_ID), timeout_ms=10000)
        # The stream survived the restart. Reuse it instead of creating a duplicate.
        print(f"Reusing stream {INGRESS_ID} with status STREAM_STATUS_{response.ingress_stream.status.name}")
        return
    except ConnectError as error:
        if error.code != Code.NOT_FOUND:
            raise

    # Lattice returns not found both for a stream that never existed and for one that was deleted.
    client.create_ingress_stream(
        CreateIngressStreamRequest(
            ingress_id=INGRESS_ID,
            title=ASSET_NAME,
            ingress=Oneof("rtsp", RtspSettings(url=RTSP_URL)),
        ),
        timeout_ms=30000,
    )
    print(f"Created stream {INGRESS_ID}")


def publish_entity(client):
    now = datetime.now(timezone.utc)
    entity = Entity(
        entity_id=ENTITY_ID,
        is_live=True,
        expiry_time=Timestamp.from_datetime(now + timedelta(minutes=5)),
        aliases=Aliases(name=ASSET_NAME),
        mil_view=MilView(disposition=Disposition.FRIENDLY, environment=Environment.LAND),
        ontology=Ontology(template=Template.ASSET, platform_type="CAMERA"),
        location=Location(position=Position(latitude_degrees=33.6411, longitude_degrees=-117.9187)),
        # Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media=Media(media=[MediaItem(item_identifier=INGRESS_ID, type=MediaType.VIDEO)]),
        # Include every other component your integration publishes, such as its TaskCatalog.
        provenance=Provenance(
            integration_name="my-integration",
            data_type="asset",
            source_update_time=Timestamp.from_datetime(now),
        ),
    )
    client.publish_entity(PublishEntityRequest(entity=entity), timeout_ms=10000)
    print(f"Republished entity {ENTITY_ID}")


def resolve_tracked_tasks(client, task_ids):
    author = Principal(agent=Oneof("system", System(entity_id=ENTITY_ID)))
    for task_id in sorted(task_ids):
        try:
            task = client.get_task(GetTaskRequest(task_id=task_id), timeout_ms=10000).task
        except ConnectError as error:
            if error.code != Code.NOT_FOUND:
                raise
            # The task no longer exists in Lattice, so there's nothing to resolve.
            untrack_task(task_ids, task_id)
            continue
        if not task or not task.status or not task.version:
            print(f"Task {task_id} is missing its status or version. Skipping.")
            continue

        if task.status.status in TERMINAL_STATUSES:
            # An operator or another system closed the task while the agent was offline.
            untrack_task(task_ids, task_id)
            continue

        pending_cancel = task.delivery_state and task.delivery_state.status == DeliveryStatus.PENDING_CANCEL
        if task.status.status == Status.CANCEL_REQUESTED or pending_cancel:
            # An operator cancelled the task while the agent was offline. Lattice records the cancel
            # in delivery_state, not in the task status. Accept the cancellation.
            error = TaskError(code=ErrorCode.CANCELLED, message="Cancelled while the agent was offline.")
        else:
            # The agent lost its execution context, so report the task as failed rather than
            # leave it active with nothing working on it.
            error = TaskError(code=ErrorCode.FAILED, message="Agent restarted and could not resume the task.")

        # Read status_version from GetTask, not from local state: the status might have
        # changed while the agent was offline, and Lattice ignores updates with a stale version.
        status_update = StatusUpdate(
            version=TaskVersion(task_id=task_id, status_version=task.version.status_version + 1),
            status=TaskStatus(status=Status.DONE_NOT_OK, task_error=error),
            author=author,
        )
        client.update_status(UpdateStatusRequest(status_update=status_update), timeout_ms=10000)
        print(f"Closed task {task_id} with ERROR_CODE_{error.code.name}")
        untrack_task(task_ids, task_id)


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 clients over Connect gRPC with authentication
    video_client = create_client(VideoManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)
    entity_client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)
    task_client = create_client(TaskManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    task_ids = load_task_ids()
    try:
        reconnect_video(video_client)
        publish_entity(entity_client)
        resolve_tracked_tasks(task_client, task_ids)
    except Exception as error:
        print(f"Failed to recover after restart: {error}", file=sys.stderr)
        sys.exit(1)

    # Recovery is complete. Start your regular publish loop and agent stream here, and call
    # track_task and untrack_task as tasks start and finish.


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={136} maxLines={56}
// 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

// track_task is called from the main loop you add after recovery.
#![allow(dead_code)]

mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    Aliases, Entity, Location, Media, MediaItem, MediaType, MilView, Ontology, Position, Provenance,
    PublishEntityRequest, Template,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{Disposition, Environment};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::taskmanager::v1::{
    principal, DeliveryStatus, ErrorCode, GetTaskRequest, Principal, Status, StatusUpdate, System, TaskError,
    TaskStatus, TaskVersion, UpdateStatusRequest,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::videomanager::v1::{
    create_ingress_stream_request::Ingress, CreateIngressStreamRequest, GetIngressStreamRequest,
    RtspSettings,
};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::taskmanager::v1::tonic::task_manager_api_client::TaskManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::videomanager::v1::tonic::video_manager_api_client::VideoManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use prost_types::Timestamp;
use serde_json::{json, Value};
use tonic::metadata::{Ascii, MetadataValue};
use tonic::service::interceptor::InterceptedService;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::{Code, Request};
use uuid::Uuid;

use std::collections::BTreeSet;
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::sync::LazyLock;
use std::time::{SystemTime, UNIX_EPOCH};

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME: &str = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
static INGRESS_ID: LazyLock<String> = LazyLock::new(|| format!("{}.cam", ASSET_NAME));
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
static ENTITY_ID: LazyLock<String> = LazyLock::new(|| {
    let name = format!("urn:my-integration:{}", ASSET_NAME);
    Uuid::new_v5(&Uuid::NAMESPACE_URL, name.as_bytes()).to_string()
});
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL: &str = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE: &str = "agent_state.json";

type Interceptor = Box<dyn FnMut(Request<()>) -> Result<Request<()>, tonic::Status> + Send + Sync>;
type VideoClient = VideoManagerApiClient<InterceptedService<Channel, Interceptor>>;
type EntityClient = EntityManagerApiClient<InterceptedService<Channel, Interceptor>>;
type TaskClient = TaskManagerApiClient<InterceptedService<Channel, Interceptor>>;

fn now_timestamp() -> Timestamp {
    let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    Timestamp {
        seconds: d.as_secs() as i64,
        nanos: d.subsec_nanos() as i32,
    }
}

fn load_task_ids() -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
    let contents = match fs::read_to_string(STATE_FILE) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(error.into()),
    };
    let state: Value = contents.parse()?;
    let task_ids = state["task_ids"].as_array().ok_or("task_ids is missing")?;
    Ok(task_ids.iter().filter_map(|id| id.as_str().map(String::from)).collect())
}

fn save_task_ids(task_ids: &BTreeSet<String>) -> std::io::Result<()> {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    let temp_path = format!("{}.tmp", STATE_FILE);
    let mut file = File::create(&temp_path)?;
    file.write_all(json!({ "task_ids": task_ids }).to_string().as_bytes())?;
    file.sync_all()?;
    fs::rename(&temp_path, STATE_FILE)
}

fn track_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.insert(task_id.to_string());
    save_task_ids(task_ids)
}

fn untrack_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.remove(task_id);
    save_task_ids(task_ids)
}

async fn reconnect_video(client: &mut VideoClient) -> Result<(), tonic::Status> {
    let request = Request::new(GetIngressStreamRequest {
        ingress_id: INGRESS_ID.clone(),
    });
    match client.get_ingress_stream(request).await {
        Ok(response) => {
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            let status = response
                .into_inner()
                .ingress_stream
                .map(|stream| stream.status().as_str_name())
                .unwrap_or_default();
            println!("Reusing stream {} with status {}", *INGRESS_ID, status);
            return Ok(());
        }
        Err(status) if status.code() == Code::NotFound => {}
        Err(status) => return Err(status),
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    let request = Request::new(CreateIngressStreamRequest {
        ingress_id: Some(INGRESS_ID.clone()),
        title: ASSET_NAME.to_string(),
        ingress: Some(Ingress::Rtsp(RtspSettings {
            url: Some(RTSP_URL.to_string()),
        })),
    });
    client.create_ingress_stream(request).await?;
    println!("Created stream {}", *INGRESS_ID);
    Ok(())
}

async fn publish_entity(client: &mut EntityClient) -> Result<(), tonic::Status> {
    let now = now_timestamp();
    let entity = Entity {
        entity_id: ENTITY_ID.clone(),
        is_live: true,
        expiry_time: Some(Timestamp {
            seconds: now.seconds + 5 * 60,
            nanos: now.nanos,
        }),
        aliases: Some(Aliases {
            name: ASSET_NAME.to_string(),
            ..Default::default()
        }),
        mil_view: Some(MilView {
            disposition: Disposition::Friendly as i32,
            environment: Environment::Land as i32,
            ..Default::default()
        }),
        ontology: Some(Ontology {
            template: Template::Asset as i32,
            platform_type: "CAMERA".to_string(),
            ..Default::default()
        }),
        location: Some(Location {
            position: Some(Position {
                latitude_degrees: 33.6411,
                longitude_degrees: -117.9187,
                ..Default::default()
            }),
            ..Default::default()
        }),
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: Some(Media {
            media: vec![MediaItem {
                item_identifier: INGRESS_ID.clone(),
                r#type: MediaType::Video as i32,
                ..Default::default()
            }],
        }),
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: Some(Provenance {
            integration_name: "my-integration".to_string(),
            data_type: "asset".to_string(),
            source_update_time: Some(now),
            ..Default::default()
        }),
        ..Default::default()
    };
    client
        .publish_entity(Request::new(PublishEntityRequest {
            entity: Some(entity),
        }))
        .await?;
    println!("Republished entity {}", *ENTITY_ID);
    Ok(())
}

async fn resolve_tracked_tasks(
    client: &mut TaskClient,
    task_ids: &mut BTreeSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let author = Principal {
        agent: Some(principal::Agent::System(System {
            entity_id: ENTITY_ID.clone(),
            ..Default::default()
        })),
        ..Default::default()
    };
    for task_id in task_ids.clone() {
        let request = Request::new(GetTaskRequest {
            task_id: task_id.clone(),
            ..Default::default()
        });
        let task = match client.get_task(request).await {
            Ok(response) => response.into_inner().task,
            Err(status) if status.code() == Code::NotFound => {
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            Err(status) => return Err(status.into()),
        };
        let Some((status, version)) = task.as_ref().and_then(|task| task.status.as_ref().zip(task.version.as_ref()))
        else {
            println!("Task {} is missing its status or version. Skipping.", task_id);
            continue;
        };

        let cancelled = status.status() == Status::CancelRequested
            || task.as_ref().and_then(|task| task.delivery_state.as_ref()).map(|state| state.status())
                == Some(DeliveryStatus::PendingCancel);
        let error = match status.status() {
            Status::DoneOk | Status::DoneNotOk => {
                // An operator or another system closed the task while the agent was offline.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in delivery_state, not in the task status. Accept the cancellation.
            _ if cancelled => TaskError {
                code: ErrorCode::Cancelled as i32,
                message: "Cancelled while the agent was offline.".to_string(),
                ..Default::default()
            },
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            _ => TaskError {
                code: ErrorCode::Failed as i32,
                message: "Agent restarted and could not resume the task.".to_string(),
                ..Default::default()
            },
        };
        let code = error.code().as_str_name();

        // Read status_version from GetTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        let status_update = StatusUpdate {
            version: Some(TaskVersion {
                task_id: task_id.clone(),
                status_version: version.status_version + 1,
                ..Default::default()
            }),
            status: Some(TaskStatus {
                status: Status::DoneNotOk as i32,
                task_error: Some(error),
                ..Default::default()
            }),
            author: Some(author.clone()),
            ..Default::default()
        };
        client
            .update_status(Request::new(UpdateStatusRequest {
                status_update: Some(status_update),
            }))
            .await?;
        println!("Closed task {} with {}", task_id, code);
        untrack_task(task_ids, &task_id)?;
    }
    Ok(())
}

fn auth_interceptor(
    auth_header: MetadataValue<Ascii>,
    sandbox_header: MetadataValue<Ascii>,
) -> Interceptor {
    Box::new(move |mut req: Request<()>| {
        req.metadata_mut()
            .insert("authorization", auth_header.clone());
        req.metadata_mut()
            .insert("anduril-sandbox-authorization", sandbox_header.clone());
        Ok(req)
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    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");
    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables");
        std::process::exit(1);
    }

    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

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

    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<Ascii> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<Ascii> = format!("Bearer {}", sandboxes_token).parse()?;

    // All three clients share the same channel and inject the same auth metadata.
    let mut video_client: VideoClient = VideoManagerApiClient::with_interceptor(
        channel.clone(),
        auth_interceptor(auth_header.clone(), sandbox_header.clone()),
    );
    let mut entity_client: EntityClient = EntityManagerApiClient::with_interceptor(
        channel.clone(),
        auth_interceptor(auth_header.clone(), sandbox_header.clone()),
    );
    let mut task_client: TaskClient = TaskManagerApiClient::with_interceptor(
        channel,
        auth_interceptor(auth_header, sandbox_header),
    );

    let mut task_ids = load_task_ids()?;
    let result: Result<(), Box<dyn std::error::Error>> = async {
        reconnect_video(&mut video_client).await?;
        publish_entity(&mut entity_client).await?;
        resolve_tracked_tasks(&mut task_client, &mut task_ids).await?;
        Ok(())
    }
    .await;
    if let Err(error) = result {
        eprintln!("Failed to recover after restart: {}", error);
        std::process::exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // track_task and untrack_task as tasks start and finish.
    Ok(())
}

```

Publish with `is_live` set to `true`; setting it to `false` deletes a live entity.
After recovery, republish at least every 5 minutes. After a Lattice service restart, Lattice restores only the entities published in the previous 5 minutes, even if they set `noExpiry`.

#### Resolve the tasks your agent was executing

For each saved task ID, call `GetTask` and act on the result:

* **`STATUS_DONE_OK` or `STATUS_DONE_NOT_OK`**: Someone closed the task while your agent was offline. Remove the ID.
* **A pending cancellation**: Lattice records an operator's cancel in the task's `delivery_state` as `DELIVERY_STATUS_PENDING_CANCEL`, and leaves the status as your agent last reported it. Your agent may also have reported `STATUS_CANCEL_REQUESTED` itself before it stopped. Either way, accept the cancellation: set `STATUS_DONE_NOT_OK` with `ERROR_CODE_CANCELLED`.
* **Any other status**: Resume the task if your agent can, or set `STATUS_DONE_NOT_OK` with `ERROR_CODE_FAILED`. The example takes the safe path and fails it.
* **Not found** (`404` in REST, `NOT_FOUND` in gRPC): Remove the ID.

Use the `status_version` from `GetTask`, not from local state. The task might have changed while your agent was offline, and Lattice rejects an update with an old version.

```go title={"Go (REST)"} startLine={185} maxLines={71}
// This Go example uses the Lattice REST SDK (lattice-sdk-go) to recover an integration's video
// stream, entity, and tasks after the integration restarts.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"maps"
	"net/http"
	"os"
	"path/filepath"
	"slices"
	"time"

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

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"

// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"

// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()

const (
	// RTSP source that Lattice pulls video from. Replace before running.
	rtspURL = "rtsp://<rtsp-host>:<port>/cam"
	// Local file that stores the IDs of tasks this agent is executing.
	stateFile = "agent_state.json"
)

var terminalStatuses = map[Lattice.TaskStatusStatus]bool{
	Lattice.TaskStatusStatusStatusDoneOk:    true,
	Lattice.TaskStatusStatusStatusDoneNotOk: true,
}

type agentState struct {
	TaskIDs []string `json:"task_ids"`
}

func loadTaskIDs() (map[string]bool, error) {
	taskIDs := map[string]bool{}
	data, err := os.ReadFile(stateFile)
	if errors.Is(err, os.ErrNotExist) {
		return taskIDs, nil
	}
	if err != nil {
		return nil, err
	}
	var state agentState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	for _, taskID := range state.TaskIDs {
		taskIDs[taskID] = true
	}
	return taskIDs, nil
}

func saveTaskIDs(taskIDs map[string]bool) error {
	ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
	slices.Sort(ids)
	data, err := json.Marshal(agentState{TaskIDs: ids})
	if err != nil {
		return err
	}
	// Write to a temporary file, then rename it over the original. A power loss during the
	// write leaves the previous file intact instead of a truncated one.
	f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	if _, err := f.Write(data); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), stateFile)
}

// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
	taskIDs[taskID] = true
	return saveTaskIDs(taskIDs)
}

// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
	delete(taskIDs, taskID)
	return saveTaskIDs(taskIDs)
}

func reconnectVideo(ctx context.Context, client *client.Client) error {
	response, err := client.Video.GetIngressStream(ctx, &Lattice.GetIngressStreamRequest{
		IngressID: ingressID,
	})
	var apiErr *core.APIError
	if err == nil {
		// The stream survived the restart. Reuse it instead of creating a duplicate.
		status := ""
		if s := response.GetIngressStream().GetStatus(); s != nil {
			status = string(*s)
		}
		fmt.Printf("Reusing stream %s with status %s\n", ingressID, status)
		return nil
	}
	if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
		return err
	}

	// Lattice returns not found both for a stream that never existed and for one that was deleted.
	_, err = client.Video.CreateIngressStream(ctx, &Lattice.CreateIngressStreamRequest{
		IngressID: Lattice.String(ingressID),
		Title:     Lattice.String(assetName),
		Rtsp: &Lattice.RtspSettings{
			URL: Lattice.String(rtspURL),
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Created stream %s\n", ingressID)
	return nil
}

func publishEntity(ctx context.Context, client *client.Client) error {
	now := time.Now().UTC()
	_, err := client.Entities.PublishEntity(ctx, &Lattice.Entity{
		EntityID:   Lattice.String(entityID),
		IsLive:     Lattice.Bool(true),
		ExpiryTime: Lattice.Time(now.Add(5 * time.Minute)),
		Aliases:    &Lattice.Aliases{Name: Lattice.String(assetName)},
		MilView: &Lattice.MilView{
			Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
			Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
		},
		Ontology: &Lattice.Ontology{
			Template:     Lattice.OntologyTemplateTemplateAsset.Ptr(),
			PlatformType: Lattice.String("CAMERA"),
		},
		Location: &Lattice.Location{
			Position: &Lattice.Position{
				LatitudeDegrees:  Lattice.Float64(33.6411),
				LongitudeDegrees: Lattice.Float64(-117.9187),
			},
		},
		// Because ingressID never changes, the entity can reference the stream on every publish.
		Media: &Lattice.Media{Media: []*Lattice.MediaItem{{
			ItemIdentifier: Lattice.String(ingressID),
			Type:           Lattice.MediaItemTypeMediaTypeVideo.Ptr(),
		}}},
		// Include every other component your integration publishes, such as its TaskCatalog.
		Provenance: &Lattice.Provenance{
			IntegrationName:  Lattice.String("my-integration"),
			DataType:         Lattice.String("asset"),
			SourceUpdateTime: Lattice.Time(now),
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Republished entity %s\n", entityID)
	return nil
}

func resolveTrackedTasks(ctx context.Context, client *client.Client, taskIDs map[string]bool) error {
	author := &Lattice.Principal{System: &Lattice.System{EntityID: Lattice.String(entityID)}}
	for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
		task, err := client.Tasks.GetTask(ctx, &Lattice.GetTaskRequest{TaskID: taskID})
		var apiErr *core.APIError
		if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
			// The task no longer exists in Lattice, so there's nothing to resolve.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
		if task.Status == nil || task.Status.Status == nil || task.Version == nil || task.Version.StatusVersion == nil {
			fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
			continue
		}

		status := *task.Status.Status
		if terminalStatuses[status] {
			// An operator or another system closed the task while the agent was offline.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}

		var taskError *Lattice.TaskError
		cancelled := status == Lattice.TaskStatusStatusStatusCancelRequested ||
			(task.GetDeliveryState().GetStatus() != nil &&
				*task.GetDeliveryState().GetStatus() == Lattice.DeliveryStateStatusDeliveryStatusPendingCancel)
		if cancelled {
			// An operator cancelled the task while the agent was offline. Lattice records the cancel
			// in delivery_state, not in the task status. Accept the cancellation.
			taskError = &Lattice.TaskError{
				Code:    Lattice.TaskErrorCodeErrorCodeCancelled.Ptr(),
				Message: Lattice.String("Cancelled while the agent was offline."),
			}
		} else {
			// The agent lost its execution context, so report the task as failed rather than
			// leave it active with nothing working on it.
			taskError = &Lattice.TaskError{
				Code:    Lattice.TaskErrorCodeErrorCodeFailed.Ptr(),
				Message: Lattice.String("Agent restarted and could not resume the task."),
			}
		}

		// Read the status version from GetTask, not from local state: the status might have
		// changed while the agent was offline, and Lattice ignores updates with a stale version.
		statusVersion := *task.Version.StatusVersion + 1
		_, err = client.Tasks.UpdateTaskStatus(ctx, &Lattice.TaskStatusUpdate{
			TaskID:        taskID,
			StatusVersion: &statusVersion,
			NewStatus: &Lattice.TaskStatus{
				Status:    Lattice.TaskStatusStatusStatusDoneNotOk.Ptr(),
				TaskError: taskError,
			},
			Author: author,
		})
		if err != nil {
			return err
		}
		fmt.Printf("Closed task %s with %s\n", taskID, *taskError.Code)
		if err := untrackTask(taskIDs, taskID); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	// Get environment variables
	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")

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

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

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

	ctx := context.Background()

	taskIDs, err := loadTaskIDs()
	if err != nil {
		fmt.Printf("Failed to load saved task IDs: %v\n", err)
		os.Exit(1)
	}
	if err := reconnectVideo(ctx, LatticeClient); err != nil {
		fmt.Printf("Failed to reconnect video: %v\n", err)
		os.Exit(1)
	}
	if err := publishEntity(ctx, LatticeClient); err != nil {
		fmt.Printf("Failed to republish entity: %v\n", err)
		os.Exit(1)
	}
	if err := resolveTrackedTasks(ctx, LatticeClient, taskIDs); err != nil {
		fmt.Printf("Failed to resolve tracked tasks: %v\n", err)
		os.Exit(1)
	}

	// Recovery is complete. Start your regular publish loop and agent stream here, and call
	// trackTask and untrackTask as tasks start and finish.
}

```

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

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.core.LatticeApiException;
import com.anduril.resources.tasks.requests.TaskStatusUpdate;
import com.anduril.resources.video.requests.CreateIngressStreamRequest;
import com.anduril.types.Aliases;
import com.anduril.types.DeliveryState;
import com.anduril.types.DeliveryStateStatus;
import com.anduril.types.Entity;
import com.anduril.types.Location;
import com.anduril.types.Media;
import com.anduril.types.MediaItem;
import com.anduril.types.MediaItemType;
import com.anduril.types.MilView;
import com.anduril.types.MilViewDisposition;
import com.anduril.types.MilViewEnvironment;
import com.anduril.types.Ontology;
import com.anduril.types.OntologyTemplate;
import com.anduril.types.Position;
import com.anduril.types.Principal;
import com.anduril.types.Provenance;
import com.anduril.types.RtspSettings;
import com.anduril.types.Task;
import com.anduril.types.TaskError;
import com.anduril.types.TaskErrorCode;
import com.anduril.types.TaskStatus;
import com.anduril.types.TaskStatusStatus;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * Recovers an integration's video stream, entity, and tasks with the Lattice SDK after the
 * integration restarts.
 */
public class HandleRestarts {
    // A name that is unique to this asset and never changes, such as a serial number read from
    // hardware or configuration. Replace before running.
    private static final String ASSET_NAME = "<ASSET-NAME>";
    // The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
    // so it's the same after every restart.
    private static final String INGRESS_ID = ASSET_NAME + ".cam";
    // The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
    // and in every language.
    // NAMESPACE_URL is the standard RFC 9562 URL namespace.
    private static final UUID NAMESPACE_URL = UUID.fromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8");
    private static final String ENTITY_ID = uuid5(NAMESPACE_URL, "urn:my-integration:" + ASSET_NAME).toString();
    // RTSP source that Lattice pulls video from. Replace before running.
    private static final String RTSP_URL = "rtsp://<rtsp-host>:<port>/cam";
    // Local file that stores the IDs of tasks this agent is executing.
    private static final Path STATE_FILE = Path.of("agent_state.json");

    private static final List<TaskStatusStatus> TERMINAL_STATUSES =
        List.of(TaskStatusStatus.STATUS_DONE_OK, TaskStatusStatus.STATUS_DONE_NOT_OK);

    private static final ObjectMapper JSON = new ObjectMapper();

    private static Set<String> loadTaskIds() throws IOException {
        Set<String> taskIds = new HashSet<>();
        if (!Files.exists(STATE_FILE)) {
            return taskIds;
        }
        for (JsonNode taskId : JSON.readTree(STATE_FILE.toFile()).path("task_ids")) {
            taskIds.add(taskId.asText());
        }
        return taskIds;
    }

    private static void saveTaskIds(Set<String> taskIds) throws IOException {
        // Write to a temporary file, then rename it over the original. A power loss during the
        // write leaves the previous file intact instead of a truncated one.
        Path target = STATE_FILE.toAbsolutePath();
        Path temp = Files.createTempFile(target.getParent(), "agent_state", ".tmp");
        ObjectNode state = JSON.createObjectNode();
        ArrayNode ids = state.putArray("task_ids");
        for (String taskId : new TreeSet<>(taskIds)) {
            ids.add(taskId);
        }
        try (FileChannel channel = FileChannel.open(temp, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(JSON.writeValueAsBytes(state)));
            channel.force(true);
        }
        Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE);
    }

    private static void trackTask(Set<String> taskIds, String taskId) throws IOException {
        // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
        taskIds.add(taskId);
        saveTaskIds(taskIds);
    }

    private static void untrackTask(Set<String> taskIds, String taskId) throws IOException {
        // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
        taskIds.remove(taskId);
        saveTaskIds(taskIds);
    }

    private static void reconnectVideo(Lattice client) {
        try {
            String status = client.video().getIngressStream(INGRESS_ID).getIngressStream()
                .flatMap(stream -> stream.getStatus()).map(Object::toString).orElse("");
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            System.out.println("Reusing stream " + INGRESS_ID + " with status " + status);
            return;
        } catch (LatticeApiException e) {
            if (e.statusCode() != 404) {
                throw e;
            }
        }

        // Lattice returns not found both for a stream that never existed and for one that was deleted.
        client.video().createIngressStream(CreateIngressStreamRequest.builder()
            .ingressId(INGRESS_ID)
            .title(ASSET_NAME)
            .rtsp(RtspSettings.builder()
                .url(RTSP_URL)
                .build())
            .build());
        System.out.println("Created stream " + INGRESS_ID);
    }

    private static void publishEntity(Lattice client) {
        OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
        client.entities().publishEntity(Entity.builder()
            .entityId(ENTITY_ID)
            .isLive(true)
            .expiryTime(now.plusMinutes(5))
            .aliases(Aliases.builder().name(ASSET_NAME).build())
            .milView(MilView.builder()
                .disposition(MilViewDisposition.DISPOSITION_FRIENDLY)
                .environment(MilViewEnvironment.ENVIRONMENT_LAND)
                .build())
            .ontology(Ontology.builder().template(OntologyTemplate.TEMPLATE_ASSET).platformType("CAMERA").build())
            .location(Location.builder()
                .position(Position.builder().latitudeDegrees(33.6411).longitudeDegrees(-117.9187).build())
                .build())
            // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
            .media(Media.builder()
                .media(List.of(MediaItem.builder().itemIdentifier(INGRESS_ID).type(MediaItemType.MEDIA_TYPE_VIDEO).build()))
                .build())
            // Include every other component your integration publishes, such as its TaskCatalog.
            .provenance(Provenance.builder()
                .integrationName("my-integration")
                .dataType("asset")
                .sourceUpdateTime(now)
                .build())
            .build());
        System.out.println("Republished entity " + ENTITY_ID);
    }

    private static void resolveTrackedTasks(Lattice client, Set<String> taskIds) throws IOException {
        Principal author = Principal.builder()
            .system(com.anduril.types.System.builder().entityId(ENTITY_ID).build())
            .build();
        for (String taskId : new TreeSet<>(taskIds)) {
            Task task;
            try {
                task = client.tasks().getTask(taskId);
            } catch (LatticeApiException e) {
                if (e.statusCode() != 404) {
                    throw e;
                }
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrackTask(taskIds, taskId);
                continue;
            }
            if (task.getStatus().isEmpty() || task.getStatus().get().getStatus().isEmpty()
                    || task.getVersion().isEmpty() || task.getVersion().get().getStatusVersion().isEmpty()) {
                System.out.println("Task " + taskId + " is missing its status or version. Skipping.");
                continue;
            }
            TaskStatusStatus status = task.getStatus().get().getStatus().get();
            int statusVersion = task.getVersion().get().getStatusVersion().get();

            if (TERMINAL_STATUSES.contains(status)) {
                // An operator or another system closed the task while the agent was offline.
                untrackTask(taskIds, taskId);
                continue;
            }

            TaskError error;
            boolean pendingCancel = task.getDeliveryState().flatMap(DeliveryState::getStatus)
                .map(DeliveryStateStatus.DELIVERY_STATUS_PENDING_CANCEL::equals).orElse(false);
            if (status.equals(TaskStatusStatus.STATUS_CANCEL_REQUESTED) || pendingCancel) {
                // An operator cancelled the task while the agent was offline. Lattice records the cancel
                // in deliveryState, not in the task status. Accept the cancellation.
                error = TaskError.builder()
                    .code(TaskErrorCode.ERROR_CODE_CANCELLED)
                    .message("Cancelled while the agent was offline.")
                    .build();
            } else {
                // The agent lost its execution context, so report the task as failed rather than
                // leave it active with nothing working on it.
                error = TaskError.builder()
                    .code(TaskErrorCode.ERROR_CODE_FAILED)
                    .message("Agent restarted and could not resume the task.")
                    .build();
            }

            // Read the status version from GetTask, not from local state: the status might have
            // changed while the agent was offline, and Lattice ignores updates with a stale version.
            client.tasks().updateTaskStatus(taskId, TaskStatusUpdate.builder()
                .statusVersion(statusVersion + 1)
                .newStatus(TaskStatus.builder()
                    .status(TaskStatusStatus.STATUS_DONE_NOT_OK)
                    .taskError(error)
                    .build())
                .author(author)
                .build());
            System.out.println("Closed task " + taskId + " with " + error.getCode().map(Object::toString).orElse(""));
            untrackTask(taskIds, taskId);
        }
    }

    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 and ensure the endpoint has its scheme
        if (isBlank(endpoint) || isBlank(environmentToken) || isBlank(sandboxesToken)) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        // Create Lattice client with Sandbox authentication
        Lattice client = Lattice.builder()
            .url(endpoint)
            .token(environmentToken)
            .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
            .build();

        try {
            Set<String> taskIds = loadTaskIds();
            reconnectVideo(client);
            publishEntity(client);
            resolveTrackedTasks(client, taskIds);
        } catch (Exception e) {
            System.err.println("Failed to recover after restart: " + e.getMessage());
            System.exit(1);
        }

        // Recovery is complete. Start your regular publish loop and agent stream here, and call
        // trackTask and untrackTask as tasks start and finish.
    }

    private static boolean isBlank(String value) {
        return value == null || value.isEmpty();
    }

    /**
     * Returns a name-based version 5 UUID, which is the same every time for the same namespace and name.
     */
    private static UUID uuid5(UUID namespace, String name) {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            sha1.update(ByteBuffer.allocate(16)
                .putLong(namespace.getMostSignificantBits())
                .putLong(namespace.getLeastSignificantBits())
                .array());
            sha1.update(name.getBytes(StandardCharsets.UTF_8));
            byte[] hash = sha1.digest();
            hash[6] = (byte) ((hash[6] & 0x0f) | 0x50); // Version 5
            hash[8] = (byte) ((hash[8] & 0x3f) | 0x80); // RFC 9562 variant
            ByteBuffer bytes = ByteBuffer.wrap(hash, 0, 16);
            return new UUID(bytes.getLong(), bytes.getLong());
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("SHA-1 is unavailable", e);
        }
    }
}

```

```py title={"Python (REST)"} startLine={118} maxLines={40}
# This Python example uses the Lattice REST SDK (anduril-lattice-sdk) to recover an integration's
# video stream, entity, and tasks after the integration restarts.

import json
import os
import sys
import tempfile
import uuid
from datetime import datetime, timedelta, timezone

from anduril import (
    Aliases,
    Lattice,
    Location,
    Media,
    MediaItem,
    MilView,
    Ontology,
    Position,
    Principal,
    Provenance,
    RtspSettings,
    System,
    TaskError,
    TaskStatus,
)
from anduril.core import ApiError

# A name that is unique to this asset and never changes, such as a serial number read from
# hardware or configuration. Replace before running.
ASSET_NAME = "<ASSET-NAME>"
# The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
# so it's the same after every restart.
INGRESS_ID = f"{ASSET_NAME}.cam"
# The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
# and in every language.
ENTITY_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:my-integration:{ASSET_NAME}"))
# RTSP source that Lattice pulls video from. Replace before running.
RTSP_URL = "rtsp://<rtsp-host>:<port>/cam"
# Local file that stores the IDs of tasks this agent is executing.
STATE_FILE = "agent_state.json"

TERMINAL_STATUSES = {"STATUS_DONE_OK", "STATUS_DONE_NOT_OK"}


def load_task_ids():
    try:
        with open(STATE_FILE) as f:
            return set(json.load(f)["task_ids"])
    except FileNotFoundError:
        return set()


def save_task_ids(task_ids):
    # Write to a temporary file, then rename it over the original. A power loss during the
    # write leaves the previous file intact instead of a truncated one.
    directory = os.path.dirname(os.path.abspath(STATE_FILE))
    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f:
        json.dump({"task_ids": sorted(task_ids)}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(f.name, STATE_FILE)


def track_task(task_ids, task_id):
    # Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.add(task_id)
    save_task_ids(task_ids)


def untrack_task(task_ids, task_id):
    # Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.discard(task_id)
    save_task_ids(task_ids)


def reconnect_video(client):
    try:
        stream = client.video.get_ingress_stream(INGRESS_ID).ingress_stream
        # The stream survived the restart. Reuse it instead of creating a duplicate.
        print(f"Reusing stream {INGRESS_ID} with status {stream.status}")
        return
    except ApiError as error:
        if error.status_code != 404:
            raise

    # Lattice returns not found both for a stream that never existed and for one that was deleted.
    client.video.create_ingress_stream(
        ingress_id=INGRESS_ID,
        title=ASSET_NAME,
        rtsp=RtspSettings(url=RTSP_URL),
    )
    print(f"Created stream {INGRESS_ID}")


def publish_entity(client):
    now = datetime.now(timezone.utc)
    client.entities.publish_entity(
        entity_id=ENTITY_ID,
        is_live=True,
        expiry_time=now + timedelta(minutes=5),
        aliases=Aliases(name=ASSET_NAME),
        mil_view=MilView(disposition="DISPOSITION_FRIENDLY", environment="ENVIRONMENT_LAND"),
        ontology=Ontology(template="TEMPLATE_ASSET", platform_type="CAMERA"),
        location=Location(position=Position(latitude_degrees=33.6411, longitude_degrees=-117.9187)),
        # Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media=Media(media=[MediaItem(item_identifier=INGRESS_ID, type="MEDIA_TYPE_VIDEO")]),
        # Include every other component your integration publishes, such as its TaskCatalog.
        provenance=Provenance(
            integration_name="my-integration",
            data_type="asset",
            source_update_time=now,
        ),
    )
    print(f"Republished entity {ENTITY_ID}")


def resolve_tracked_tasks(client, task_ids):
    author = Principal(system=System(entity_id=ENTITY_ID))
    for task_id in sorted(task_ids):
        try:
            task = client.tasks.get_task(task_id)
        except ApiError as error:
            if error.status_code != 404:
                raise
            # The task no longer exists in Lattice, so there's nothing to resolve.
            untrack_task(task_ids, task_id)
            continue
        if not task.status or not task.version or task.version.status_version is None:
            print(f"Task {task_id} is missing its status or version. Skipping.")
            continue

        if task.status.status in TERMINAL_STATUSES:
            # An operator or another system closed the task while the agent was offline.
            untrack_task(task_ids, task_id)
            continue

        pending_cancel = task.delivery_state and task.delivery_state.status == "DELIVERY_STATUS_PENDING_CANCEL"
        if task.status.status == "STATUS_CANCEL_REQUESTED" or pending_cancel:
            # An operator cancelled the task while the agent was offline. Lattice records the cancel
            # in delivery_state, not in the task status. Accept the cancellation.
            error = TaskError(code="ERROR_CODE_CANCELLED", message="Cancelled while the agent was offline.")
        else:
            # The agent lost its execution context, so report the task as failed rather than
            # leave it active with nothing working on it.
            error = TaskError(code="ERROR_CODE_FAILED", message="Agent restarted and could not resume the task.")

        # Read status_version from GetTask, not from local state: the status might have
        # changed while the agent was offline, and Lattice ignores updates with a stale version.
        client.tasks.update_task_status(
            task_id,
            status_version=task.version.status_version + 1,
            new_status=TaskStatus(status="STATUS_DONE_NOT_OK", task_error=error),
            author=author,
        )
        print(f"Closed task {task_id} with {error.code}")
        untrack_task(task_ids, task_id)


def main():
    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)

    client = Lattice(
        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}"},
    )

    task_ids = load_task_ids()
    try:
        reconnect_video(client)
        publish_entity(client)
        resolve_tracked_tasks(client, task_ids)
    except Exception as error:
        print(f"Failed to recover after restart: {error}", file=sys.stderr)
        sys.exit(1)

    # Recovery is complete. Start your regular publish loop and agent stream here, and call
    # track_task and untrack_task as tasks start and finish.


if __name__ == "__main__":
    main()

```

```ts title={"TypeScript (REST)"} startLine={105} maxLines={50}
// This TypeScript example uses the Lattice REST SDK (@anduril-industries/lattice-sdk) to recover an
// integration's video stream, entity, and tasks after the integration restarts.

import * as fs from "node:fs";
import * as path from "node:path";
import { Lattice, LatticeClient, LatticeError } from "@anduril-industries/lattice-sdk";
import { v5 as uuidv5 } from "uuid";

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
const INGRESS_ID = `${ASSET_NAME}.cam`;
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
const ENTITY_ID = uuidv5(`urn:my-integration:${ASSET_NAME}`, uuidv5.URL);
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE = "agent_state.json";

const TERMINAL_STATUSES = new Set<string | undefined>(["STATUS_DONE_OK", "STATUS_DONE_NOT_OK"]);

function loadTaskIds(): Set<string> {
    try {
        return new Set<string>(JSON.parse(fs.readFileSync(STATE_FILE, "utf8")).task_ids);
    } catch (error) {
        if ((error as NodeJS.ErrnoException).code === "ENOENT") {
            return new Set<string>();
        }
        throw error;
    }
}

function saveTaskIds(taskIds: Set<string>) {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    const tempFile = path.join(path.dirname(path.resolve(STATE_FILE)), `.${path.basename(STATE_FILE)}.${process.pid}.tmp`);
    const fd = fs.openSync(tempFile, "w");
    try {
        fs.writeSync(fd, JSON.stringify({ task_ids: [...taskIds].sort() }));
        fs.fsyncSync(fd);
    } finally {
        fs.closeSync(fd);
    }
    fs.renameSync(tempFile, STATE_FILE);
}

export function trackTask(taskIds: Set<string>, taskId: string) {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    taskIds.add(taskId);
    saveTaskIds(taskIds);
}

export function untrackTask(taskIds: Set<string>, taskId: string) {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    taskIds.delete(taskId);
    saveTaskIds(taskIds);
}

async function reconnectVideo(client: LatticeClient) {
    try {
        const { ingressStream } = await client.video.getIngressStream({ ingressId: INGRESS_ID });
        // The stream survived the restart. Reuse it instead of creating a duplicate.
        console.log(`Reusing stream ${INGRESS_ID} with status ${ingressStream?.status}`);
        return;
    } catch (error) {
        if (!(error instanceof LatticeError && error.statusCode === 404)) {
            throw error;
        }
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    await client.video.createIngressStream({
        ingressId: INGRESS_ID,
        title: ASSET_NAME,
        rtsp: { url: RTSP_URL },
    });
    console.log(`Created stream ${INGRESS_ID}`);
}

async function publishEntity(client: LatticeClient) {
    const now = new Date();
    await client.entities.publishEntity({
        entityId: ENTITY_ID,
        isLive: true,
        expiryTime: new Date(now.getTime() + 5 * 60 * 1000).toISOString(),
        aliases: { name: ASSET_NAME },
        milView: { disposition: "DISPOSITION_FRIENDLY", environment: "ENVIRONMENT_LAND" },
        ontology: { template: "TEMPLATE_ASSET", platformType: "CAMERA" },
        location: { position: { latitudeDegrees: 33.6411, longitudeDegrees: -117.9187 } },
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: { media: [{ itemIdentifier: INGRESS_ID, type: "MEDIA_TYPE_VIDEO" }] },
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: {
            integrationName: "my-integration",
            dataType: "asset",
            sourceUpdateTime: now.toISOString(),
        },
    });
    console.log(`Republished entity ${ENTITY_ID}`);
}

async function resolveTrackedTasks(client: LatticeClient, taskIds: Set<string>) {
    const author = { system: { entityId: ENTITY_ID } };
    for (const taskId of [...taskIds].sort()) {
        let task: Lattice.Task;
        try {
            task = await client.tasks.getTask({ taskId });
        } catch (error) {
            if (!(error instanceof LatticeError && error.statusCode === 404)) {
                throw error;
            }
            // The task no longer exists in Lattice, so there's nothing to resolve.
            untrackTask(taskIds, taskId);
            continue;
        }
        const statusVersion = task.version?.statusVersion;
        if (!task.status || statusVersion === undefined) {
            console.log(`Task ${taskId} is missing its status or version. Skipping.`);
            continue;
        }

        if (TERMINAL_STATUSES.has(task.status.status)) {
            // An operator or another system closed the task while the agent was offline.
            untrackTask(taskIds, taskId);
            continue;
        }

        let taskError: Lattice.TaskError;
        const pendingCancel = task.deliveryState?.status === "DELIVERY_STATUS_PENDING_CANCEL";
        if (task.status.status === "STATUS_CANCEL_REQUESTED" || pendingCancel) {
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in deliveryState, not in the task status. Accept the cancellation.
            taskError = { code: "ERROR_CODE_CANCELLED", message: "Cancelled while the agent was offline." };
        } else {
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            taskError = { code: "ERROR_CODE_FAILED", message: "Agent restarted and could not resume the task." };
        }

        // Read statusVersion from getTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        await client.tasks.updateTaskStatus({
            taskId,
            statusVersion: statusVersion + 1,
            newStatus: { status: "STATUS_DONE_NOT_OK", taskError },
            author,
        });
        console.log(`Closed task ${taskId} with ${taskError.code}`);
        untrackTask(taskIds, taskId);
    }
}

async function App() {
    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,
            // Remove the following if you are not developing on Sandboxes.
            headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}`  }
        }
    );

    const taskIds = loadTaskIds();
    try {
        await reconnectVideo(client);
        await publishEntity(client);
        await resolveTrackedTasks(client, taskIds);
    } catch (error) {
        console.error(`Failed to recover after restart: ${error}`);
        process.exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // trackTask and untrackTask as tasks start and finish.
}

App();

```

```rs title={"Rust (REST)"} startLine={148} maxLines={74}
// This Rust example uses the Lattice REST SDK (anduril-lattice-sdk) to recover an integration's
// video stream, entity, and tasks after the integration restarts.

// track_task is called from the main loop you add after recovery.
#![allow(dead_code)]

use anduril_lattice_sdk::prelude::*;

use std::collections::BTreeSet;
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::sync::LazyLock;
use uuid::Uuid;

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME: &str = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
static INGRESS_ID: LazyLock<String> = LazyLock::new(|| format!("{}.cam", ASSET_NAME));
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
static ENTITY_ID: LazyLock<String> = LazyLock::new(|| {
    let name = format!("urn:my-integration:{}", ASSET_NAME);
    Uuid::new_v5(&Uuid::NAMESPACE_URL, name.as_bytes()).to_string()
});
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL: &str = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE: &str = "agent_state.json";

fn load_task_ids() -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
    let contents = match fs::read_to_string(STATE_FILE) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(error.into()),
    };
    let state: Value = contents.parse()?;
    let task_ids = state["task_ids"].as_array().ok_or("task_ids is missing")?;
    Ok(task_ids.iter().filter_map(|id| id.as_str().map(String::from)).collect())
}

fn save_task_ids(task_ids: &BTreeSet<String>) -> std::io::Result<()> {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    let temp_path = format!("{}.tmp", STATE_FILE);
    let mut file = File::create(&temp_path)?;
    file.write_all(json!({ "task_ids": task_ids }).to_string().as_bytes())?;
    file.sync_all()?;
    fs::rename(&temp_path, STATE_FILE)
}

fn track_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.insert(task_id.to_string());
    save_task_ids(task_ids)
}

fn untrack_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.remove(task_id);
    save_task_ids(task_ids)
}

async fn reconnect_video(client: &Lattice) -> Result<(), ApiError> {
    match client.video.get_ingress_stream(&INGRESS_ID, None).await {
        Ok(response) => {
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            let status = response
                .ingress_stream
                .and_then(|stream| stream.status)
                .map(|status| status.to_string())
                .unwrap_or_default();
            println!("Reusing stream {} with status {}", *INGRESS_ID, status);
            return Ok(());
        }
        Err(ApiError::NotFoundError { .. }) => {}
        Err(error) => return Err(error),
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    let request = CreateIngressStreamRequest {
        ingress_id: Some(INGRESS_ID.clone()),
        title: Some(ASSET_NAME.to_string()),
        rtsp: Some(RtspSettings {
            url: Some(RTSP_URL.to_string()),
            ..Default::default()
        }),
        ..Default::default()
    };
    client.video.create_ingress_stream(&request, None).await?;
    println!("Created stream {}", *INGRESS_ID);
    Ok(())
}

async fn publish_entity(client: &Lattice) -> Result<(), ApiError> {
    let now = Utc::now();
    let entity = Entity {
        entity_id: Some(ENTITY_ID.clone()),
        is_live: Some(true),
        expiry_time: Some((now + chrono::Duration::minutes(5)).fixed_offset()),
        aliases: Some(Aliases {
            name: Some(ASSET_NAME.to_string()),
            ..Default::default()
        }),
        mil_view: Some(MilView {
            disposition: Some(MilViewDisposition::DispositionFriendly),
            environment: Some(MilViewEnvironment::EnvironmentLand),
            ..Default::default()
        }),
        ontology: Some(Ontology {
            template: Some(OntologyTemplate::TemplateAsset),
            platform_type: Some("CAMERA".to_string()),
            ..Default::default()
        }),
        location: Some(Location {
            position: Some(Position {
                latitude_degrees: Some(33.6411),
                longitude_degrees: Some(-117.9187),
                ..Default::default()
            }),
            ..Default::default()
        }),
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: Some(Media {
            media: Some(vec![MediaItem {
                item_identifier: Some(INGRESS_ID.clone()),
                r#type: Some(MediaItemType::MediaTypeVideo),
                ..Default::default()
            }]),
            ..Default::default()
        }),
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: Some(Provenance {
            integration_name: Some("my-integration".to_string()),
            data_type: Some("asset".to_string()),
            source_update_time: Some(now.fixed_offset()),
            ..Default::default()
        }),
        ..Default::default()
    };
    client.entities.publish_entity(&entity, None).await?;
    println!("Republished entity {}", *ENTITY_ID);
    Ok(())
}

async fn resolve_tracked_tasks(
    client: &Lattice,
    task_ids: &mut BTreeSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let author = Principal {
        system: Some(System {
            entity_id: Some(ENTITY_ID.clone()),
            ..Default::default()
        }),
        ..Default::default()
    };
    for task_id in task_ids.clone() {
        let task = match client.tasks.get_task(&task_id, None).await {
            Ok(task) => task,
            Err(ApiError::NotFoundError { .. }) => {
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            Err(error) => return Err(error.into()),
        };
        let (Some(status), Some(status_version)) = (
            task.status.as_ref(),
            task.version.as_ref().and_then(|version| version.status_version),
        ) else {
            println!("Task {} is missing its status or version. Skipping.", task_id);
            continue;
        };

        let cancelled = matches!(status.status, Some(TaskStatusStatus::StatusCancelRequested))
            || matches!(
                task.delivery_state.as_ref().and_then(|state| state.status.as_ref()),
                Some(DeliveryStateStatus::DeliveryStatusPendingCancel)
            );
        let error = match status.status {
            Some(TaskStatusStatus::StatusDoneOk | TaskStatusStatus::StatusDoneNotOk) => {
                // An operator or another system closed the task while the agent was offline.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in delivery_state, not in the task status. Accept the cancellation.
            _ if cancelled => TaskError {
                code: Some(TaskErrorCode::ErrorCodeCancelled),
                message: Some("Cancelled while the agent was offline.".to_string()),
                ..Default::default()
            },
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            _ => TaskError {
                code: Some(TaskErrorCode::ErrorCodeFailed),
                message: Some("Agent restarted and could not resume the task.".to_string()),
                ..Default::default()
            },
        };
        let code = error.code.as_ref().map(|code| code.to_string()).unwrap_or_default();

        // Read status_version from GetTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        let request = TaskStatusUpdate {
            status_version: Some(status_version + 1),
            new_status: Some(TaskStatus {
                status: Some(TaskStatusStatus::StatusDoneNotOk),
                task_error: Some(error),
                ..Default::default()
            }),
            author: Some(author.clone()),
        };
        client.tasks.update_task_status(&task_id, &request, None).await?;
        println!("Closed task {} with {}", task_id, code);
        untrack_task(task_ids, &task_id)?;
    }
    Ok(())
}

#[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)?;

    let mut task_ids = load_task_ids()?;
    let result: Result<(), Box<dyn std::error::Error>> = async {
        reconnect_video(&client).await?;
        publish_entity(&client).await?;
        resolve_tracked_tasks(&client, &mut task_ids).await?;
        Ok(())
    }
    .await;
    if let Err(error) = result {
        eprintln!("Failed to recover after restart: {}", error);
        std::process::exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // track_task and untrack_task as tasks start and finish.
    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={194} maxLines={77}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
//
// It recovers an integration's video stream, entity, and tasks after the integration restarts.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"maps"
	"os"
	"path/filepath"
	"slices"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/taskmanager/v1/taskmanagerv1grpc"
	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/videomanager/v1/videomanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	ontologyv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/ontology/v1"
	taskmanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/taskmanager/v1"
	videomanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/videomanager/v1"

	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"

// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"

// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()

const (
	// RTSP source that Lattice pulls video from. Replace before running.
	rtspURL = "rtsp://<rtsp-host>:<port>/cam"
	// Local file that stores the IDs of tasks this agent is executing.
	stateFile = "agent_state.json"
)

var terminalStatuses = map[taskmanagerv1.Status]bool{
	taskmanagerv1.Status_STATUS_DONE_OK:     true,
	taskmanagerv1.Status_STATUS_DONE_NOT_OK: true,
}

type agentState struct {
	TaskIDs []string `json:"task_ids"`
}

func loadTaskIDs() (map[string]bool, error) {
	taskIDs := map[string]bool{}
	data, err := os.ReadFile(stateFile)
	if errors.Is(err, os.ErrNotExist) {
		return taskIDs, nil
	}
	if err != nil {
		return nil, err
	}
	var state agentState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	for _, taskID := range state.TaskIDs {
		taskIDs[taskID] = true
	}
	return taskIDs, nil
}

func saveTaskIDs(taskIDs map[string]bool) error {
	ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
	slices.Sort(ids)
	data, err := json.Marshal(agentState{TaskIDs: ids})
	if err != nil {
		return err
	}
	// Write to a temporary file, then rename it over the original. A power loss during the
	// write leaves the previous file intact instead of a truncated one.
	f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	if _, err := f.Write(data); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), stateFile)
}

// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
	taskIDs[taskID] = true
	return saveTaskIDs(taskIDs)
}

// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
	delete(taskIDs, taskID)
	return saveTaskIDs(taskIDs)
}

func reconnectVideo(ctx context.Context, client videomanagerv1grpc.VideoManagerAPIClient) error {
	response, err := client.GetIngressStream(ctx, &videomanagerv1.GetIngressStreamRequest{
		IngressId: ingressID,
	})
	if err == nil {
		// The stream survived the restart. Reuse it instead of creating a duplicate.
		fmt.Printf("Reusing stream %s with status %s\n", ingressID, response.GetIngressStream().GetStatus())
		return nil
	}
	if status.Code(err) != codes.NotFound {
		return err
	}

	// Lattice returns not found both for a stream that never existed and for one that was deleted.
	_, err = client.CreateIngressStream(ctx, &videomanagerv1.CreateIngressStreamRequest{
		IngressId: proto.String(ingressID),
		Title:     assetName,
		Ingress: &videomanagerv1.CreateIngressStreamRequest_Rtsp{
			Rtsp: &videomanagerv1.RtspSettings{
				Url: proto.String(rtspURL),
			},
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Created stream %s\n", ingressID)
	return nil
}

func publishEntity(ctx context.Context, client entitymanagerv1grpc.EntityManagerAPIClient) error {
	now := time.Now().UTC()
	_, err := client.PublishEntity(ctx, &entitymanagerv1.PublishEntityRequest{Entity: &entitymanagerv1.Entity{
		EntityId:   entityID,
		IsLive:     true,
		ExpiryTime: timestamppb.New(now.Add(5 * time.Minute)),
		Aliases:    &entitymanagerv1.Aliases{Name: assetName},
		MilView: &entitymanagerv1.MilView{
			Disposition: ontologyv1.Disposition_DISPOSITION_FRIENDLY,
			Environment: ontologyv1.Environment_ENVIRONMENT_LAND,
		},
		Ontology: &entitymanagerv1.Ontology{
			Template:     entitymanagerv1.Template_TEMPLATE_ASSET,
			PlatformType: "CAMERA",
		},
		Location: &entitymanagerv1.Location{
			Position: &entitymanagerv1.Position{
				LatitudeDegrees:  33.6411,
				LongitudeDegrees: -117.9187,
			},
		},
		// Because ingressID never changes, the entity can reference the stream on every publish.
		Media: &entitymanagerv1.Media{Media: []*entitymanagerv1.MediaItem{{
			ItemIdentifier: ingressID,
			Type:           entitymanagerv1.MediaType_MEDIA_TYPE_VIDEO,
		}}},
		// Include every other component your integration publishes, such as its TaskCatalog.
		Provenance: &entitymanagerv1.Provenance{
			IntegrationName:  "my-integration",
			DataType:         "asset",
			SourceUpdateTime: timestamppb.New(now),
		},
	}})
	if err != nil {
		return err
	}
	fmt.Printf("Republished entity %s\n", entityID)
	return nil
}

func resolveTrackedTasks(ctx context.Context, client taskmanagerv1grpc.TaskManagerAPIClient, taskIDs map[string]bool) error {
	author := &taskmanagerv1.Principal{
		Agent: &taskmanagerv1.Principal_System{
			System: &taskmanagerv1.System{EntityId: entityID},
		},
	}
	for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
		response, err := client.GetTask(ctx, &taskmanagerv1.GetTaskRequest{TaskId: taskID})
		if status.Code(err) == codes.NotFound {
			// The task no longer exists in Lattice, so there's nothing to resolve.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
		task := response.GetTask()
		if task.GetStatus() == nil || task.GetVersion() == nil {
			fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
			continue
		}

		taskStatus := task.GetStatus().GetStatus()
		if terminalStatuses[taskStatus] {
			// An operator or another system closed the task while the agent was offline.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}

		var taskError *taskmanagerv1.TaskError
		cancelled := taskStatus == taskmanagerv1.Status_STATUS_CANCEL_REQUESTED ||
			task.GetDeliveryState().GetStatus() == taskmanagerv1.DeliveryStatus_DELIVERY_STATUS_PENDING_CANCEL
		if cancelled {
			// An operator cancelled the task while the agent was offline. Lattice records the cancel
			// in delivery_state, not in the task status. Accept the cancellation.
			taskError = &taskmanagerv1.TaskError{
				Code:    taskmanagerv1.ErrorCode_ERROR_CODE_CANCELLED,
				Message: "Cancelled while the agent was offline.",
			}
		} else {
			// The agent lost its execution context, so report the task as failed rather than
			// leave it active with nothing working on it.
			taskError = &taskmanagerv1.TaskError{
				Code:    taskmanagerv1.ErrorCode_ERROR_CODE_FAILED,
				Message: "Agent restarted and could not resume the task.",
			}
		}

		// Read the status version from GetTask, not from local state: the status might have
		// changed while the agent was offline, and Lattice ignores updates with a stale version.
		_, err = client.UpdateStatus(ctx, &taskmanagerv1.UpdateStatusRequest{
			StatusUpdate: &taskmanagerv1.StatusUpdate{
				Version: &taskmanagerv1.TaskVersion{
					TaskId:        taskID,
					StatusVersion: task.GetVersion().GetStatusVersion() + 1,
				},
				Status: &taskmanagerv1.TaskStatus{
					Status:    taskmanagerv1.Status_STATUS_DONE_NOT_OK,
					TaskError: taskError,
				},
				Author: author,
			},
		})
		if err != nil {
			return err
		}
		fmt.Printf("Closed task %s with %s\n", taskID, taskError.GetCode())
		if err := untrackTask(taskIDs, taskID); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	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()

	videoClient := videomanagerv1grpc.NewVideoManagerAPIClient(conn)
	entityClient := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)
	taskClient := taskmanagerv1grpc.NewTaskManagerAPIClient(conn)

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	taskIDs, err := loadTaskIDs()
	if err != nil {
		log.Fatalf("Failed to load saved task IDs: %v", err)
	}
	if err := reconnectVideo(ctx, videoClient); err != nil {
		log.Fatalf("Failed to reconnect video: %v", err)
	}
	if err := publishEntity(ctx, entityClient); err != nil {
		log.Fatalf("Failed to republish entity: %v", err)
	}
	if err := resolveTrackedTasks(ctx, taskClient, taskIDs); err != nil {
		log.Fatalf("Failed to resolve tracked tasks: %v", err)
	}

	// Recovery is complete. Start your regular publish loop and agent stream here, and call
	// trackTask and untrackTask as tasks start and finish.
}

```

```py title={"Python (gRPC)"} startLine={137} 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
# It recovers an integration's video stream, entity, and tasks after the integration restarts.

import json
import os
import sys
import tempfile
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from connectrpc.code import Code
from connectrpc.errors import ConnectError
from protobuf import Oneof
from protobuf.wkt import Timestamp

from anduril.entitymanager.v1.entity_pub_pb import Aliases, Entity, Provenance
from anduril.entitymanager.v1.entity_manager_api_pub_pb import PublishEntityRequest
from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.location_pub_pb import Location, Position
from anduril.entitymanager.v1.media_pub_pb import Media, MediaItem, MediaType
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.ontology.v1.type_pub_pb import Disposition, Environment
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.taskmanager.v1.task_pub_pb import (
    DeliveryStatus,
    ErrorCode,
    Principal,
    Status,
    StatusUpdate,
    System,
    TaskError,
    TaskStatus,
    TaskVersion,
)
from anduril.taskmanager.v1.task_manager_api_pub_pb import GetTaskRequest, UpdateStatusRequest
from anduril.taskmanager.v1.task_manager_api_pub_connect import TaskManagerAPIClientSync
from anduril.videomanager.v1.create_ingress_stream_request_pub_pb import CreateIngressStreamRequest
from anduril.videomanager.v1.get_ingress_stream_request_pub_pb import GetIngressStreamRequest
from anduril.videomanager.v1.rtsp_settings_pub_pb import RtspSettings
from anduril.videomanager.v1.video_manager_api_pub_connect import VideoManagerAPIClientSync

# A name that is unique to this asset and never changes, such as a serial number read from
# hardware or configuration. Replace before running.
ASSET_NAME = "<ASSET-NAME>"
# The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
# so it's the same after every restart.
INGRESS_ID = f"{ASSET_NAME}.cam"
# The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
# and in every language.
ENTITY_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:my-integration:{ASSET_NAME}"))
# RTSP source that Lattice pulls video from. Replace before running.
RTSP_URL = "rtsp://<rtsp-host>:<port>/cam"
# Local file that stores the IDs of tasks this agent is executing.
STATE_FILE = "agent_state.json"

TERMINAL_STATUSES = {Status.DONE_OK, Status.DONE_NOT_OK}


def load_task_ids():
    try:
        with open(STATE_FILE) as f:
            return set(json.load(f)["task_ids"])
    except FileNotFoundError:
        return set()


def save_task_ids(task_ids):
    # Write to a temporary file, then rename it over the original. A power loss during the
    # write leaves the previous file intact instead of a truncated one.
    directory = os.path.dirname(os.path.abspath(STATE_FILE))
    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f:
        json.dump({"task_ids": sorted(task_ids)}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(f.name, STATE_FILE)


def track_task(task_ids, task_id):
    # Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.add(task_id)
    save_task_ids(task_ids)


def untrack_task(task_ids, task_id):
    # Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.discard(task_id)
    save_task_ids(task_ids)


def reconnect_video(client):
    try:
        response = client.get_ingress_stream(GetIngressStreamRequest(ingress_id=INGRESS_ID), timeout_ms=10000)
        # The stream survived the restart. Reuse it instead of creating a duplicate.
        print(f"Reusing stream {INGRESS_ID} with status STREAM_STATUS_{response.ingress_stream.status.name}")
        return
    except ConnectError as error:
        if error.code != Code.NOT_FOUND:
            raise

    # Lattice returns not found both for a stream that never existed and for one that was deleted.
    client.create_ingress_stream(
        CreateIngressStreamRequest(
            ingress_id=INGRESS_ID,
            title=ASSET_NAME,
            ingress=Oneof("rtsp", RtspSettings(url=RTSP_URL)),
        ),
        timeout_ms=30000,
    )
    print(f"Created stream {INGRESS_ID}")


def publish_entity(client):
    now = datetime.now(timezone.utc)
    entity = Entity(
        entity_id=ENTITY_ID,
        is_live=True,
        expiry_time=Timestamp.from_datetime(now + timedelta(minutes=5)),
        aliases=Aliases(name=ASSET_NAME),
        mil_view=MilView(disposition=Disposition.FRIENDLY, environment=Environment.LAND),
        ontology=Ontology(template=Template.ASSET, platform_type="CAMERA"),
        location=Location(position=Position(latitude_degrees=33.6411, longitude_degrees=-117.9187)),
        # Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media=Media(media=[MediaItem(item_identifier=INGRESS_ID, type=MediaType.VIDEO)]),
        # Include every other component your integration publishes, such as its TaskCatalog.
        provenance=Provenance(
            integration_name="my-integration",
            data_type="asset",
            source_update_time=Timestamp.from_datetime(now),
        ),
    )
    client.publish_entity(PublishEntityRequest(entity=entity), timeout_ms=10000)
    print(f"Republished entity {ENTITY_ID}")


def resolve_tracked_tasks(client, task_ids):
    author = Principal(agent=Oneof("system", System(entity_id=ENTITY_ID)))
    for task_id in sorted(task_ids):
        try:
            task = client.get_task(GetTaskRequest(task_id=task_id), timeout_ms=10000).task
        except ConnectError as error:
            if error.code != Code.NOT_FOUND:
                raise
            # The task no longer exists in Lattice, so there's nothing to resolve.
            untrack_task(task_ids, task_id)
            continue
        if not task or not task.status or not task.version:
            print(f"Task {task_id} is missing its status or version. Skipping.")
            continue

        if task.status.status in TERMINAL_STATUSES:
            # An operator or another system closed the task while the agent was offline.
            untrack_task(task_ids, task_id)
            continue

        pending_cancel = task.delivery_state and task.delivery_state.status == DeliveryStatus.PENDING_CANCEL
        if task.status.status == Status.CANCEL_REQUESTED or pending_cancel:
            # An operator cancelled the task while the agent was offline. Lattice records the cancel
            # in delivery_state, not in the task status. Accept the cancellation.
            error = TaskError(code=ErrorCode.CANCELLED, message="Cancelled while the agent was offline.")
        else:
            # The agent lost its execution context, so report the task as failed rather than
            # leave it active with nothing working on it.
            error = TaskError(code=ErrorCode.FAILED, message="Agent restarted and could not resume the task.")

        # Read status_version from GetTask, not from local state: the status might have
        # changed while the agent was offline, and Lattice ignores updates with a stale version.
        status_update = StatusUpdate(
            version=TaskVersion(task_id=task_id, status_version=task.version.status_version + 1),
            status=TaskStatus(status=Status.DONE_NOT_OK, task_error=error),
            author=author,
        )
        client.update_status(UpdateStatusRequest(status_update=status_update), timeout_ms=10000)
        print(f"Closed task {task_id} with ERROR_CODE_{error.code.name}")
        untrack_task(task_ids, task_id)


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 clients over Connect gRPC with authentication
    video_client = create_client(VideoManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)
    entity_client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)
    task_client = create_client(TaskManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    task_ids = load_task_ids()
    try:
        reconnect_video(video_client)
        publish_entity(entity_client)
        resolve_tracked_tasks(task_client, task_ids)
    except Exception as error:
        print(f"Failed to recover after restart: {error}", file=sys.stderr)
        sys.exit(1)

    # Recovery is complete. Start your regular publish loop and agent stream here, and call
    # track_task and untrack_task as tasks start and finish.


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={193} maxLines={83}
// 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

// track_task is called from the main loop you add after recovery.
#![allow(dead_code)]

mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    Aliases, Entity, Location, Media, MediaItem, MediaType, MilView, Ontology, Position, Provenance,
    PublishEntityRequest, Template,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{Disposition, Environment};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::taskmanager::v1::{
    principal, DeliveryStatus, ErrorCode, GetTaskRequest, Principal, Status, StatusUpdate, System, TaskError,
    TaskStatus, TaskVersion, UpdateStatusRequest,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::videomanager::v1::{
    create_ingress_stream_request::Ingress, CreateIngressStreamRequest, GetIngressStreamRequest,
    RtspSettings,
};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::taskmanager::v1::tonic::task_manager_api_client::TaskManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::videomanager::v1::tonic::video_manager_api_client::VideoManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use prost_types::Timestamp;
use serde_json::{json, Value};
use tonic::metadata::{Ascii, MetadataValue};
use tonic::service::interceptor::InterceptedService;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::{Code, Request};
use uuid::Uuid;

use std::collections::BTreeSet;
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::sync::LazyLock;
use std::time::{SystemTime, UNIX_EPOCH};

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME: &str = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
static INGRESS_ID: LazyLock<String> = LazyLock::new(|| format!("{}.cam", ASSET_NAME));
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
static ENTITY_ID: LazyLock<String> = LazyLock::new(|| {
    let name = format!("urn:my-integration:{}", ASSET_NAME);
    Uuid::new_v5(&Uuid::NAMESPACE_URL, name.as_bytes()).to_string()
});
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL: &str = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE: &str = "agent_state.json";

type Interceptor = Box<dyn FnMut(Request<()>) -> Result<Request<()>, tonic::Status> + Send + Sync>;
type VideoClient = VideoManagerApiClient<InterceptedService<Channel, Interceptor>>;
type EntityClient = EntityManagerApiClient<InterceptedService<Channel, Interceptor>>;
type TaskClient = TaskManagerApiClient<InterceptedService<Channel, Interceptor>>;

fn now_timestamp() -> Timestamp {
    let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    Timestamp {
        seconds: d.as_secs() as i64,
        nanos: d.subsec_nanos() as i32,
    }
}

fn load_task_ids() -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
    let contents = match fs::read_to_string(STATE_FILE) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(error.into()),
    };
    let state: Value = contents.parse()?;
    let task_ids = state["task_ids"].as_array().ok_or("task_ids is missing")?;
    Ok(task_ids.iter().filter_map(|id| id.as_str().map(String::from)).collect())
}

fn save_task_ids(task_ids: &BTreeSet<String>) -> std::io::Result<()> {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    let temp_path = format!("{}.tmp", STATE_FILE);
    let mut file = File::create(&temp_path)?;
    file.write_all(json!({ "task_ids": task_ids }).to_string().as_bytes())?;
    file.sync_all()?;
    fs::rename(&temp_path, STATE_FILE)
}

fn track_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.insert(task_id.to_string());
    save_task_ids(task_ids)
}

fn untrack_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.remove(task_id);
    save_task_ids(task_ids)
}

async fn reconnect_video(client: &mut VideoClient) -> Result<(), tonic::Status> {
    let request = Request::new(GetIngressStreamRequest {
        ingress_id: INGRESS_ID.clone(),
    });
    match client.get_ingress_stream(request).await {
        Ok(response) => {
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            let status = response
                .into_inner()
                .ingress_stream
                .map(|stream| stream.status().as_str_name())
                .unwrap_or_default();
            println!("Reusing stream {} with status {}", *INGRESS_ID, status);
            return Ok(());
        }
        Err(status) if status.code() == Code::NotFound => {}
        Err(status) => return Err(status),
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    let request = Request::new(CreateIngressStreamRequest {
        ingress_id: Some(INGRESS_ID.clone()),
        title: ASSET_NAME.to_string(),
        ingress: Some(Ingress::Rtsp(RtspSettings {
            url: Some(RTSP_URL.to_string()),
        })),
    });
    client.create_ingress_stream(request).await?;
    println!("Created stream {}", *INGRESS_ID);
    Ok(())
}

async fn publish_entity(client: &mut EntityClient) -> Result<(), tonic::Status> {
    let now = now_timestamp();
    let entity = Entity {
        entity_id: ENTITY_ID.clone(),
        is_live: true,
        expiry_time: Some(Timestamp {
            seconds: now.seconds + 5 * 60,
            nanos: now.nanos,
        }),
        aliases: Some(Aliases {
            name: ASSET_NAME.to_string(),
            ..Default::default()
        }),
        mil_view: Some(MilView {
            disposition: Disposition::Friendly as i32,
            environment: Environment::Land as i32,
            ..Default::default()
        }),
        ontology: Some(Ontology {
            template: Template::Asset as i32,
            platform_type: "CAMERA".to_string(),
            ..Default::default()
        }),
        location: Some(Location {
            position: Some(Position {
                latitude_degrees: 33.6411,
                longitude_degrees: -117.9187,
                ..Default::default()
            }),
            ..Default::default()
        }),
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: Some(Media {
            media: vec![MediaItem {
                item_identifier: INGRESS_ID.clone(),
                r#type: MediaType::Video as i32,
                ..Default::default()
            }],
        }),
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: Some(Provenance {
            integration_name: "my-integration".to_string(),
            data_type: "asset".to_string(),
            source_update_time: Some(now),
            ..Default::default()
        }),
        ..Default::default()
    };
    client
        .publish_entity(Request::new(PublishEntityRequest {
            entity: Some(entity),
        }))
        .await?;
    println!("Republished entity {}", *ENTITY_ID);
    Ok(())
}

async fn resolve_tracked_tasks(
    client: &mut TaskClient,
    task_ids: &mut BTreeSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let author = Principal {
        agent: Some(principal::Agent::System(System {
            entity_id: ENTITY_ID.clone(),
            ..Default::default()
        })),
        ..Default::default()
    };
    for task_id in task_ids.clone() {
        let request = Request::new(GetTaskRequest {
            task_id: task_id.clone(),
            ..Default::default()
        });
        let task = match client.get_task(request).await {
            Ok(response) => response.into_inner().task,
            Err(status) if status.code() == Code::NotFound => {
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            Err(status) => return Err(status.into()),
        };
        let Some((status, version)) = task.as_ref().and_then(|task| task.status.as_ref().zip(task.version.as_ref()))
        else {
            println!("Task {} is missing its status or version. Skipping.", task_id);
            continue;
        };

        let cancelled = status.status() == Status::CancelRequested
            || task.as_ref().and_then(|task| task.delivery_state.as_ref()).map(|state| state.status())
                == Some(DeliveryStatus::PendingCancel);
        let error = match status.status() {
            Status::DoneOk | Status::DoneNotOk => {
                // An operator or another system closed the task while the agent was offline.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in delivery_state, not in the task status. Accept the cancellation.
            _ if cancelled => TaskError {
                code: ErrorCode::Cancelled as i32,
                message: "Cancelled while the agent was offline.".to_string(),
                ..Default::default()
            },
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            _ => TaskError {
                code: ErrorCode::Failed as i32,
                message: "Agent restarted and could not resume the task.".to_string(),
                ..Default::default()
            },
        };
        let code = error.code().as_str_name();

        // Read status_version from GetTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        let status_update = StatusUpdate {
            version: Some(TaskVersion {
                task_id: task_id.clone(),
                status_version: version.status_version + 1,
                ..Default::default()
            }),
            status: Some(TaskStatus {
                status: Status::DoneNotOk as i32,
                task_error: Some(error),
                ..Default::default()
            }),
            author: Some(author.clone()),
            ..Default::default()
        };
        client
            .update_status(Request::new(UpdateStatusRequest {
                status_update: Some(status_update),
            }))
            .await?;
        println!("Closed task {} with {}", task_id, code);
        untrack_task(task_ids, &task_id)?;
    }
    Ok(())
}

fn auth_interceptor(
    auth_header: MetadataValue<Ascii>,
    sandbox_header: MetadataValue<Ascii>,
) -> Interceptor {
    Box::new(move |mut req: Request<()>| {
        req.metadata_mut()
            .insert("authorization", auth_header.clone());
        req.metadata_mut()
            .insert("anduril-sandbox-authorization", sandbox_header.clone());
        Ok(req)
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    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");
    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables");
        std::process::exit(1);
    }

    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

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

    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<Ascii> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<Ascii> = format!("Bearer {}", sandboxes_token).parse()?;

    // All three clients share the same channel and inject the same auth metadata.
    let mut video_client: VideoClient = VideoManagerApiClient::with_interceptor(
        channel.clone(),
        auth_interceptor(auth_header.clone(), sandbox_header.clone()),
    );
    let mut entity_client: EntityClient = EntityManagerApiClient::with_interceptor(
        channel.clone(),
        auth_interceptor(auth_header.clone(), sandbox_header.clone()),
    );
    let mut task_client: TaskClient = TaskManagerApiClient::with_interceptor(
        channel,
        auth_interceptor(auth_header, sandbox_header),
    );

    let mut task_ids = load_task_ids()?;
    let result: Result<(), Box<dyn std::error::Error>> = async {
        reconnect_video(&mut video_client).await?;
        publish_entity(&mut entity_client).await?;
        resolve_tracked_tasks(&mut task_client, &mut task_ids).await?;
        Ok(())
    }
    .await;
    if let Err(error) = result {
        eprintln!("Failed to recover after restart: {}", error);
        std::process::exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // track_task and untrack_task as tasks start and finish.
    Ok(())
}

```

> **Resume only when it's safe**
>
> Resume a task only if your agent can confirm its conditions still hold, for example that the target is still there.
> If you're unsure, fail it. An operator can reassign it.

#### Resume normal operation

Start your publish loop and agent stream as described in [Integrate an agent](/guides/tasks/integrate-an-agent).
From now on, save each task ID before you report `STATUS_EXECUTING`, and remove it after you report `STATUS_DONE_OK` or `STATUS_DONE_NOT_OK`.
That way a crash can't leave a task executing in Lattice with no record of it in your integration:

```go title={"Go (REST)"} startLine={99} maxLines={12}
// This Go example uses the Lattice REST SDK (lattice-sdk-go) to recover an integration's video
// stream, entity, and tasks after the integration restarts.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"maps"
	"net/http"
	"os"
	"path/filepath"
	"slices"
	"time"

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

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"

// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"

// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()

const (
	// RTSP source that Lattice pulls video from. Replace before running.
	rtspURL = "rtsp://<rtsp-host>:<port>/cam"
	// Local file that stores the IDs of tasks this agent is executing.
	stateFile = "agent_state.json"
)

var terminalStatuses = map[Lattice.TaskStatusStatus]bool{
	Lattice.TaskStatusStatusStatusDoneOk:    true,
	Lattice.TaskStatusStatusStatusDoneNotOk: true,
}

type agentState struct {
	TaskIDs []string `json:"task_ids"`
}

func loadTaskIDs() (map[string]bool, error) {
	taskIDs := map[string]bool{}
	data, err := os.ReadFile(stateFile)
	if errors.Is(err, os.ErrNotExist) {
		return taskIDs, nil
	}
	if err != nil {
		return nil, err
	}
	var state agentState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	for _, taskID := range state.TaskIDs {
		taskIDs[taskID] = true
	}
	return taskIDs, nil
}

func saveTaskIDs(taskIDs map[string]bool) error {
	ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
	slices.Sort(ids)
	data, err := json.Marshal(agentState{TaskIDs: ids})
	if err != nil {
		return err
	}
	// Write to a temporary file, then rename it over the original. A power loss during the
	// write leaves the previous file intact instead of a truncated one.
	f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	if _, err := f.Write(data); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), stateFile)
}

// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
	taskIDs[taskID] = true
	return saveTaskIDs(taskIDs)
}

// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
	delete(taskIDs, taskID)
	return saveTaskIDs(taskIDs)
}

func reconnectVideo(ctx context.Context, client *client.Client) error {
	response, err := client.Video.GetIngressStream(ctx, &Lattice.GetIngressStreamRequest{
		IngressID: ingressID,
	})
	var apiErr *core.APIError
	if err == nil {
		// The stream survived the restart. Reuse it instead of creating a duplicate.
		status := ""
		if s := response.GetIngressStream().GetStatus(); s != nil {
			status = string(*s)
		}
		fmt.Printf("Reusing stream %s with status %s\n", ingressID, status)
		return nil
	}
	if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
		return err
	}

	// Lattice returns not found both for a stream that never existed and for one that was deleted.
	_, err = client.Video.CreateIngressStream(ctx, &Lattice.CreateIngressStreamRequest{
		IngressID: Lattice.String(ingressID),
		Title:     Lattice.String(assetName),
		Rtsp: &Lattice.RtspSettings{
			URL: Lattice.String(rtspURL),
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Created stream %s\n", ingressID)
	return nil
}

func publishEntity(ctx context.Context, client *client.Client) error {
	now := time.Now().UTC()
	_, err := client.Entities.PublishEntity(ctx, &Lattice.Entity{
		EntityID:   Lattice.String(entityID),
		IsLive:     Lattice.Bool(true),
		ExpiryTime: Lattice.Time(now.Add(5 * time.Minute)),
		Aliases:    &Lattice.Aliases{Name: Lattice.String(assetName)},
		MilView: &Lattice.MilView{
			Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
			Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
		},
		Ontology: &Lattice.Ontology{
			Template:     Lattice.OntologyTemplateTemplateAsset.Ptr(),
			PlatformType: Lattice.String("CAMERA"),
		},
		Location: &Lattice.Location{
			Position: &Lattice.Position{
				LatitudeDegrees:  Lattice.Float64(33.6411),
				LongitudeDegrees: Lattice.Float64(-117.9187),
			},
		},
		// Because ingressID never changes, the entity can reference the stream on every publish.
		Media: &Lattice.Media{Media: []*Lattice.MediaItem{{
			ItemIdentifier: Lattice.String(ingressID),
			Type:           Lattice.MediaItemTypeMediaTypeVideo.Ptr(),
		}}},
		// Include every other component your integration publishes, such as its TaskCatalog.
		Provenance: &Lattice.Provenance{
			IntegrationName:  Lattice.String("my-integration"),
			DataType:         Lattice.String("asset"),
			SourceUpdateTime: Lattice.Time(now),
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Republished entity %s\n", entityID)
	return nil
}

func resolveTrackedTasks(ctx context.Context, client *client.Client, taskIDs map[string]bool) error {
	author := &Lattice.Principal{System: &Lattice.System{EntityID: Lattice.String(entityID)}}
	for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
		task, err := client.Tasks.GetTask(ctx, &Lattice.GetTaskRequest{TaskID: taskID})
		var apiErr *core.APIError
		if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
			// The task no longer exists in Lattice, so there's nothing to resolve.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
		if task.Status == nil || task.Status.Status == nil || task.Version == nil || task.Version.StatusVersion == nil {
			fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
			continue
		}

		status := *task.Status.Status
		if terminalStatuses[status] {
			// An operator or another system closed the task while the agent was offline.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}

		var taskError *Lattice.TaskError
		cancelled := status == Lattice.TaskStatusStatusStatusCancelRequested ||
			(task.GetDeliveryState().GetStatus() != nil &&
				*task.GetDeliveryState().GetStatus() == Lattice.DeliveryStateStatusDeliveryStatusPendingCancel)
		if cancelled {
			// An operator cancelled the task while the agent was offline. Lattice records the cancel
			// in delivery_state, not in the task status. Accept the cancellation.
			taskError = &Lattice.TaskError{
				Code:    Lattice.TaskErrorCodeErrorCodeCancelled.Ptr(),
				Message: Lattice.String("Cancelled while the agent was offline."),
			}
		} else {
			// The agent lost its execution context, so report the task as failed rather than
			// leave it active with nothing working on it.
			taskError = &Lattice.TaskError{
				Code:    Lattice.TaskErrorCodeErrorCodeFailed.Ptr(),
				Message: Lattice.String("Agent restarted and could not resume the task."),
			}
		}

		// Read the status version from GetTask, not from local state: the status might have
		// changed while the agent was offline, and Lattice ignores updates with a stale version.
		statusVersion := *task.Version.StatusVersion + 1
		_, err = client.Tasks.UpdateTaskStatus(ctx, &Lattice.TaskStatusUpdate{
			TaskID:        taskID,
			StatusVersion: &statusVersion,
			NewStatus: &Lattice.TaskStatus{
				Status:    Lattice.TaskStatusStatusStatusDoneNotOk.Ptr(),
				TaskError: taskError,
			},
			Author: author,
		})
		if err != nil {
			return err
		}
		fmt.Printf("Closed task %s with %s\n", taskID, *taskError.Code)
		if err := untrackTask(taskIDs, taskID); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	// Get environment variables
	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")

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

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

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

	ctx := context.Background()

	taskIDs, err := loadTaskIDs()
	if err != nil {
		fmt.Printf("Failed to load saved task IDs: %v\n", err)
		os.Exit(1)
	}
	if err := reconnectVideo(ctx, LatticeClient); err != nil {
		fmt.Printf("Failed to reconnect video: %v\n", err)
		os.Exit(1)
	}
	if err := publishEntity(ctx, LatticeClient); err != nil {
		fmt.Printf("Failed to republish entity: %v\n", err)
		os.Exit(1)
	}
	if err := resolveTrackedTasks(ctx, LatticeClient, taskIDs); err != nil {
		fmt.Printf("Failed to resolve tracked tasks: %v\n", err)
		os.Exit(1)
	}

	// Recovery is complete. Start your regular publish loop and agent stream here, and call
	// trackTask and untrackTask as tasks start and finish.
}

```

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

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.core.LatticeApiException;
import com.anduril.resources.tasks.requests.TaskStatusUpdate;
import com.anduril.resources.video.requests.CreateIngressStreamRequest;
import com.anduril.types.Aliases;
import com.anduril.types.DeliveryState;
import com.anduril.types.DeliveryStateStatus;
import com.anduril.types.Entity;
import com.anduril.types.Location;
import com.anduril.types.Media;
import com.anduril.types.MediaItem;
import com.anduril.types.MediaItemType;
import com.anduril.types.MilView;
import com.anduril.types.MilViewDisposition;
import com.anduril.types.MilViewEnvironment;
import com.anduril.types.Ontology;
import com.anduril.types.OntologyTemplate;
import com.anduril.types.Position;
import com.anduril.types.Principal;
import com.anduril.types.Provenance;
import com.anduril.types.RtspSettings;
import com.anduril.types.Task;
import com.anduril.types.TaskError;
import com.anduril.types.TaskErrorCode;
import com.anduril.types.TaskStatus;
import com.anduril.types.TaskStatusStatus;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * Recovers an integration's video stream, entity, and tasks with the Lattice SDK after the
 * integration restarts.
 */
public class HandleRestarts {
    // A name that is unique to this asset and never changes, such as a serial number read from
    // hardware or configuration. Replace before running.
    private static final String ASSET_NAME = "<ASSET-NAME>";
    // The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
    // so it's the same after every restart.
    private static final String INGRESS_ID = ASSET_NAME + ".cam";
    // The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
    // and in every language.
    // NAMESPACE_URL is the standard RFC 9562 URL namespace.
    private static final UUID NAMESPACE_URL = UUID.fromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8");
    private static final String ENTITY_ID = uuid5(NAMESPACE_URL, "urn:my-integration:" + ASSET_NAME).toString();
    // RTSP source that Lattice pulls video from. Replace before running.
    private static final String RTSP_URL = "rtsp://<rtsp-host>:<port>/cam";
    // Local file that stores the IDs of tasks this agent is executing.
    private static final Path STATE_FILE = Path.of("agent_state.json");

    private static final List<TaskStatusStatus> TERMINAL_STATUSES =
        List.of(TaskStatusStatus.STATUS_DONE_OK, TaskStatusStatus.STATUS_DONE_NOT_OK);

    private static final ObjectMapper JSON = new ObjectMapper();

    private static Set<String> loadTaskIds() throws IOException {
        Set<String> taskIds = new HashSet<>();
        if (!Files.exists(STATE_FILE)) {
            return taskIds;
        }
        for (JsonNode taskId : JSON.readTree(STATE_FILE.toFile()).path("task_ids")) {
            taskIds.add(taskId.asText());
        }
        return taskIds;
    }

    private static void saveTaskIds(Set<String> taskIds) throws IOException {
        // Write to a temporary file, then rename it over the original. A power loss during the
        // write leaves the previous file intact instead of a truncated one.
        Path target = STATE_FILE.toAbsolutePath();
        Path temp = Files.createTempFile(target.getParent(), "agent_state", ".tmp");
        ObjectNode state = JSON.createObjectNode();
        ArrayNode ids = state.putArray("task_ids");
        for (String taskId : new TreeSet<>(taskIds)) {
            ids.add(taskId);
        }
        try (FileChannel channel = FileChannel.open(temp, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(JSON.writeValueAsBytes(state)));
            channel.force(true);
        }
        Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE);
    }

    private static void trackTask(Set<String> taskIds, String taskId) throws IOException {
        // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
        taskIds.add(taskId);
        saveTaskIds(taskIds);
    }

    private static void untrackTask(Set<String> taskIds, String taskId) throws IOException {
        // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
        taskIds.remove(taskId);
        saveTaskIds(taskIds);
    }

    private static void reconnectVideo(Lattice client) {
        try {
            String status = client.video().getIngressStream(INGRESS_ID).getIngressStream()
                .flatMap(stream -> stream.getStatus()).map(Object::toString).orElse("");
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            System.out.println("Reusing stream " + INGRESS_ID + " with status " + status);
            return;
        } catch (LatticeApiException e) {
            if (e.statusCode() != 404) {
                throw e;
            }
        }

        // Lattice returns not found both for a stream that never existed and for one that was deleted.
        client.video().createIngressStream(CreateIngressStreamRequest.builder()
            .ingressId(INGRESS_ID)
            .title(ASSET_NAME)
            .rtsp(RtspSettings.builder()
                .url(RTSP_URL)
                .build())
            .build());
        System.out.println("Created stream " + INGRESS_ID);
    }

    private static void publishEntity(Lattice client) {
        OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
        client.entities().publishEntity(Entity.builder()
            .entityId(ENTITY_ID)
            .isLive(true)
            .expiryTime(now.plusMinutes(5))
            .aliases(Aliases.builder().name(ASSET_NAME).build())
            .milView(MilView.builder()
                .disposition(MilViewDisposition.DISPOSITION_FRIENDLY)
                .environment(MilViewEnvironment.ENVIRONMENT_LAND)
                .build())
            .ontology(Ontology.builder().template(OntologyTemplate.TEMPLATE_ASSET).platformType("CAMERA").build())
            .location(Location.builder()
                .position(Position.builder().latitudeDegrees(33.6411).longitudeDegrees(-117.9187).build())
                .build())
            // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
            .media(Media.builder()
                .media(List.of(MediaItem.builder().itemIdentifier(INGRESS_ID).type(MediaItemType.MEDIA_TYPE_VIDEO).build()))
                .build())
            // Include every other component your integration publishes, such as its TaskCatalog.
            .provenance(Provenance.builder()
                .integrationName("my-integration")
                .dataType("asset")
                .sourceUpdateTime(now)
                .build())
            .build());
        System.out.println("Republished entity " + ENTITY_ID);
    }

    private static void resolveTrackedTasks(Lattice client, Set<String> taskIds) throws IOException {
        Principal author = Principal.builder()
            .system(com.anduril.types.System.builder().entityId(ENTITY_ID).build())
            .build();
        for (String taskId : new TreeSet<>(taskIds)) {
            Task task;
            try {
                task = client.tasks().getTask(taskId);
            } catch (LatticeApiException e) {
                if (e.statusCode() != 404) {
                    throw e;
                }
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrackTask(taskIds, taskId);
                continue;
            }
            if (task.getStatus().isEmpty() || task.getStatus().get().getStatus().isEmpty()
                    || task.getVersion().isEmpty() || task.getVersion().get().getStatusVersion().isEmpty()) {
                System.out.println("Task " + taskId + " is missing its status or version. Skipping.");
                continue;
            }
            TaskStatusStatus status = task.getStatus().get().getStatus().get();
            int statusVersion = task.getVersion().get().getStatusVersion().get();

            if (TERMINAL_STATUSES.contains(status)) {
                // An operator or another system closed the task while the agent was offline.
                untrackTask(taskIds, taskId);
                continue;
            }

            TaskError error;
            boolean pendingCancel = task.getDeliveryState().flatMap(DeliveryState::getStatus)
                .map(DeliveryStateStatus.DELIVERY_STATUS_PENDING_CANCEL::equals).orElse(false);
            if (status.equals(TaskStatusStatus.STATUS_CANCEL_REQUESTED) || pendingCancel) {
                // An operator cancelled the task while the agent was offline. Lattice records the cancel
                // in deliveryState, not in the task status. Accept the cancellation.
                error = TaskError.builder()
                    .code(TaskErrorCode.ERROR_CODE_CANCELLED)
                    .message("Cancelled while the agent was offline.")
                    .build();
            } else {
                // The agent lost its execution context, so report the task as failed rather than
                // leave it active with nothing working on it.
                error = TaskError.builder()
                    .code(TaskErrorCode.ERROR_CODE_FAILED)
                    .message("Agent restarted and could not resume the task.")
                    .build();
            }

            // Read the status version from GetTask, not from local state: the status might have
            // changed while the agent was offline, and Lattice ignores updates with a stale version.
            client.tasks().updateTaskStatus(taskId, TaskStatusUpdate.builder()
                .statusVersion(statusVersion + 1)
                .newStatus(TaskStatus.builder()
                    .status(TaskStatusStatus.STATUS_DONE_NOT_OK)
                    .taskError(error)
                    .build())
                .author(author)
                .build());
            System.out.println("Closed task " + taskId + " with " + error.getCode().map(Object::toString).orElse(""));
            untrackTask(taskIds, taskId);
        }
    }

    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 and ensure the endpoint has its scheme
        if (isBlank(endpoint) || isBlank(environmentToken) || isBlank(sandboxesToken)) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        // Create Lattice client with Sandbox authentication
        Lattice client = Lattice.builder()
            .url(endpoint)
            .token(environmentToken)
            .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
            .build();

        try {
            Set<String> taskIds = loadTaskIds();
            reconnectVideo(client);
            publishEntity(client);
            resolveTrackedTasks(client, taskIds);
        } catch (Exception e) {
            System.err.println("Failed to recover after restart: " + e.getMessage());
            System.exit(1);
        }

        // Recovery is complete. Start your regular publish loop and agent stream here, and call
        // trackTask and untrackTask as tasks start and finish.
    }

    private static boolean isBlank(String value) {
        return value == null || value.isEmpty();
    }

    /**
     * Returns a name-based version 5 UUID, which is the same every time for the same namespace and name.
     */
    private static UUID uuid5(UUID namespace, String name) {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            sha1.update(ByteBuffer.allocate(16)
                .putLong(namespace.getMostSignificantBits())
                .putLong(namespace.getLeastSignificantBits())
                .array());
            sha1.update(name.getBytes(StandardCharsets.UTF_8));
            byte[] hash = sha1.digest();
            hash[6] = (byte) ((hash[6] & 0x0f) | 0x50); // Version 5
            hash[8] = (byte) ((hash[8] & 0x3f) | 0x80); // RFC 9562 variant
            ByteBuffer bytes = ByteBuffer.wrap(hash, 0, 16);
            return new UUID(bytes.getLong(), bytes.getLong());
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("SHA-1 is unavailable", e);
        }
    }
}

```

```py title={"Python (REST)"} startLine={65} maxLines={10}
# This Python example uses the Lattice REST SDK (anduril-lattice-sdk) to recover an integration's
# video stream, entity, and tasks after the integration restarts.

import json
import os
import sys
import tempfile
import uuid
from datetime import datetime, timedelta, timezone

from anduril import (
    Aliases,
    Lattice,
    Location,
    Media,
    MediaItem,
    MilView,
    Ontology,
    Position,
    Principal,
    Provenance,
    RtspSettings,
    System,
    TaskError,
    TaskStatus,
)
from anduril.core import ApiError

# A name that is unique to this asset and never changes, such as a serial number read from
# hardware or configuration. Replace before running.
ASSET_NAME = "<ASSET-NAME>"
# The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
# so it's the same after every restart.
INGRESS_ID = f"{ASSET_NAME}.cam"
# The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
# and in every language.
ENTITY_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:my-integration:{ASSET_NAME}"))
# RTSP source that Lattice pulls video from. Replace before running.
RTSP_URL = "rtsp://<rtsp-host>:<port>/cam"
# Local file that stores the IDs of tasks this agent is executing.
STATE_FILE = "agent_state.json"

TERMINAL_STATUSES = {"STATUS_DONE_OK", "STATUS_DONE_NOT_OK"}


def load_task_ids():
    try:
        with open(STATE_FILE) as f:
            return set(json.load(f)["task_ids"])
    except FileNotFoundError:
        return set()


def save_task_ids(task_ids):
    # Write to a temporary file, then rename it over the original. A power loss during the
    # write leaves the previous file intact instead of a truncated one.
    directory = os.path.dirname(os.path.abspath(STATE_FILE))
    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f:
        json.dump({"task_ids": sorted(task_ids)}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(f.name, STATE_FILE)


def track_task(task_ids, task_id):
    # Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.add(task_id)
    save_task_ids(task_ids)


def untrack_task(task_ids, task_id):
    # Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.discard(task_id)
    save_task_ids(task_ids)


def reconnect_video(client):
    try:
        stream = client.video.get_ingress_stream(INGRESS_ID).ingress_stream
        # The stream survived the restart. Reuse it instead of creating a duplicate.
        print(f"Reusing stream {INGRESS_ID} with status {stream.status}")
        return
    except ApiError as error:
        if error.status_code != 404:
            raise

    # Lattice returns not found both for a stream that never existed and for one that was deleted.
    client.video.create_ingress_stream(
        ingress_id=INGRESS_ID,
        title=ASSET_NAME,
        rtsp=RtspSettings(url=RTSP_URL),
    )
    print(f"Created stream {INGRESS_ID}")


def publish_entity(client):
    now = datetime.now(timezone.utc)
    client.entities.publish_entity(
        entity_id=ENTITY_ID,
        is_live=True,
        expiry_time=now + timedelta(minutes=5),
        aliases=Aliases(name=ASSET_NAME),
        mil_view=MilView(disposition="DISPOSITION_FRIENDLY", environment="ENVIRONMENT_LAND"),
        ontology=Ontology(template="TEMPLATE_ASSET", platform_type="CAMERA"),
        location=Location(position=Position(latitude_degrees=33.6411, longitude_degrees=-117.9187)),
        # Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media=Media(media=[MediaItem(item_identifier=INGRESS_ID, type="MEDIA_TYPE_VIDEO")]),
        # Include every other component your integration publishes, such as its TaskCatalog.
        provenance=Provenance(
            integration_name="my-integration",
            data_type="asset",
            source_update_time=now,
        ),
    )
    print(f"Republished entity {ENTITY_ID}")


def resolve_tracked_tasks(client, task_ids):
    author = Principal(system=System(entity_id=ENTITY_ID))
    for task_id in sorted(task_ids):
        try:
            task = client.tasks.get_task(task_id)
        except ApiError as error:
            if error.status_code != 404:
                raise
            # The task no longer exists in Lattice, so there's nothing to resolve.
            untrack_task(task_ids, task_id)
            continue
        if not task.status or not task.version or task.version.status_version is None:
            print(f"Task {task_id} is missing its status or version. Skipping.")
            continue

        if task.status.status in TERMINAL_STATUSES:
            # An operator or another system closed the task while the agent was offline.
            untrack_task(task_ids, task_id)
            continue

        pending_cancel = task.delivery_state and task.delivery_state.status == "DELIVERY_STATUS_PENDING_CANCEL"
        if task.status.status == "STATUS_CANCEL_REQUESTED" or pending_cancel:
            # An operator cancelled the task while the agent was offline. Lattice records the cancel
            # in delivery_state, not in the task status. Accept the cancellation.
            error = TaskError(code="ERROR_CODE_CANCELLED", message="Cancelled while the agent was offline.")
        else:
            # The agent lost its execution context, so report the task as failed rather than
            # leave it active with nothing working on it.
            error = TaskError(code="ERROR_CODE_FAILED", message="Agent restarted and could not resume the task.")

        # Read status_version from GetTask, not from local state: the status might have
        # changed while the agent was offline, and Lattice ignores updates with a stale version.
        client.tasks.update_task_status(
            task_id,
            status_version=task.version.status_version + 1,
            new_status=TaskStatus(status="STATUS_DONE_NOT_OK", task_error=error),
            author=author,
        )
        print(f"Closed task {task_id} with {error.code}")
        untrack_task(task_ids, task_id)


def main():
    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)

    client = Lattice(
        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}"},
    )

    task_ids = load_task_ids()
    try:
        reconnect_video(client)
        publish_entity(client)
        resolve_tracked_tasks(client, task_ids)
    except Exception as error:
        print(f"Failed to recover after restart: {error}", file=sys.stderr)
        sys.exit(1)

    # Recovery is complete. Start your regular publish loop and agent stream here, and call
    # track_task and untrack_task as tasks start and finish.


if __name__ == "__main__":
    main()

```

```ts title={"TypeScript (REST)"} startLine={50} maxLines={11}
// This TypeScript example uses the Lattice REST SDK (@anduril-industries/lattice-sdk) to recover an
// integration's video stream, entity, and tasks after the integration restarts.

import * as fs from "node:fs";
import * as path from "node:path";
import { Lattice, LatticeClient, LatticeError } from "@anduril-industries/lattice-sdk";
import { v5 as uuidv5 } from "uuid";

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
const INGRESS_ID = `${ASSET_NAME}.cam`;
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
const ENTITY_ID = uuidv5(`urn:my-integration:${ASSET_NAME}`, uuidv5.URL);
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE = "agent_state.json";

const TERMINAL_STATUSES = new Set<string | undefined>(["STATUS_DONE_OK", "STATUS_DONE_NOT_OK"]);

function loadTaskIds(): Set<string> {
    try {
        return new Set<string>(JSON.parse(fs.readFileSync(STATE_FILE, "utf8")).task_ids);
    } catch (error) {
        if ((error as NodeJS.ErrnoException).code === "ENOENT") {
            return new Set<string>();
        }
        throw error;
    }
}

function saveTaskIds(taskIds: Set<string>) {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    const tempFile = path.join(path.dirname(path.resolve(STATE_FILE)), `.${path.basename(STATE_FILE)}.${process.pid}.tmp`);
    const fd = fs.openSync(tempFile, "w");
    try {
        fs.writeSync(fd, JSON.stringify({ task_ids: [...taskIds].sort() }));
        fs.fsyncSync(fd);
    } finally {
        fs.closeSync(fd);
    }
    fs.renameSync(tempFile, STATE_FILE);
}

export function trackTask(taskIds: Set<string>, taskId: string) {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    taskIds.add(taskId);
    saveTaskIds(taskIds);
}

export function untrackTask(taskIds: Set<string>, taskId: string) {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    taskIds.delete(taskId);
    saveTaskIds(taskIds);
}

async function reconnectVideo(client: LatticeClient) {
    try {
        const { ingressStream } = await client.video.getIngressStream({ ingressId: INGRESS_ID });
        // The stream survived the restart. Reuse it instead of creating a duplicate.
        console.log(`Reusing stream ${INGRESS_ID} with status ${ingressStream?.status}`);
        return;
    } catch (error) {
        if (!(error instanceof LatticeError && error.statusCode === 404)) {
            throw error;
        }
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    await client.video.createIngressStream({
        ingressId: INGRESS_ID,
        title: ASSET_NAME,
        rtsp: { url: RTSP_URL },
    });
    console.log(`Created stream ${INGRESS_ID}`);
}

async function publishEntity(client: LatticeClient) {
    const now = new Date();
    await client.entities.publishEntity({
        entityId: ENTITY_ID,
        isLive: true,
        expiryTime: new Date(now.getTime() + 5 * 60 * 1000).toISOString(),
        aliases: { name: ASSET_NAME },
        milView: { disposition: "DISPOSITION_FRIENDLY", environment: "ENVIRONMENT_LAND" },
        ontology: { template: "TEMPLATE_ASSET", platformType: "CAMERA" },
        location: { position: { latitudeDegrees: 33.6411, longitudeDegrees: -117.9187 } },
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: { media: [{ itemIdentifier: INGRESS_ID, type: "MEDIA_TYPE_VIDEO" }] },
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: {
            integrationName: "my-integration",
            dataType: "asset",
            sourceUpdateTime: now.toISOString(),
        },
    });
    console.log(`Republished entity ${ENTITY_ID}`);
}

async function resolveTrackedTasks(client: LatticeClient, taskIds: Set<string>) {
    const author = { system: { entityId: ENTITY_ID } };
    for (const taskId of [...taskIds].sort()) {
        let task: Lattice.Task;
        try {
            task = await client.tasks.getTask({ taskId });
        } catch (error) {
            if (!(error instanceof LatticeError && error.statusCode === 404)) {
                throw error;
            }
            // The task no longer exists in Lattice, so there's nothing to resolve.
            untrackTask(taskIds, taskId);
            continue;
        }
        const statusVersion = task.version?.statusVersion;
        if (!task.status || statusVersion === undefined) {
            console.log(`Task ${taskId} is missing its status or version. Skipping.`);
            continue;
        }

        if (TERMINAL_STATUSES.has(task.status.status)) {
            // An operator or another system closed the task while the agent was offline.
            untrackTask(taskIds, taskId);
            continue;
        }

        let taskError: Lattice.TaskError;
        const pendingCancel = task.deliveryState?.status === "DELIVERY_STATUS_PENDING_CANCEL";
        if (task.status.status === "STATUS_CANCEL_REQUESTED" || pendingCancel) {
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in deliveryState, not in the task status. Accept the cancellation.
            taskError = { code: "ERROR_CODE_CANCELLED", message: "Cancelled while the agent was offline." };
        } else {
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            taskError = { code: "ERROR_CODE_FAILED", message: "Agent restarted and could not resume the task." };
        }

        // Read statusVersion from getTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        await client.tasks.updateTaskStatus({
            taskId,
            statusVersion: statusVersion + 1,
            newStatus: { status: "STATUS_DONE_NOT_OK", taskError },
            author,
        });
        console.log(`Closed task ${taskId} with ${taskError.code}`);
        untrackTask(taskIds, taskId);
    }
}

async function App() {
    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,
            // Remove the following if you are not developing on Sandboxes.
            headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}`  }
        }
    );

    const taskIds = loadTaskIds();
    try {
        await reconnectVideo(client);
        await publishEntity(client);
        await resolveTrackedTasks(client, taskIds);
    } catch (error) {
        console.error(`Failed to recover after restart: ${error}`);
        process.exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // trackTask and untrackTask as tasks start and finish.
}

App();

```

```rs title={"Rust (REST)"} startLine={54} maxLines={11}
// This Rust example uses the Lattice REST SDK (anduril-lattice-sdk) to recover an integration's
// video stream, entity, and tasks after the integration restarts.

// track_task is called from the main loop you add after recovery.
#![allow(dead_code)]

use anduril_lattice_sdk::prelude::*;

use std::collections::BTreeSet;
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::sync::LazyLock;
use uuid::Uuid;

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME: &str = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
static INGRESS_ID: LazyLock<String> = LazyLock::new(|| format!("{}.cam", ASSET_NAME));
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
static ENTITY_ID: LazyLock<String> = LazyLock::new(|| {
    let name = format!("urn:my-integration:{}", ASSET_NAME);
    Uuid::new_v5(&Uuid::NAMESPACE_URL, name.as_bytes()).to_string()
});
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL: &str = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE: &str = "agent_state.json";

fn load_task_ids() -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
    let contents = match fs::read_to_string(STATE_FILE) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(error.into()),
    };
    let state: Value = contents.parse()?;
    let task_ids = state["task_ids"].as_array().ok_or("task_ids is missing")?;
    Ok(task_ids.iter().filter_map(|id| id.as_str().map(String::from)).collect())
}

fn save_task_ids(task_ids: &BTreeSet<String>) -> std::io::Result<()> {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    let temp_path = format!("{}.tmp", STATE_FILE);
    let mut file = File::create(&temp_path)?;
    file.write_all(json!({ "task_ids": task_ids }).to_string().as_bytes())?;
    file.sync_all()?;
    fs::rename(&temp_path, STATE_FILE)
}

fn track_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.insert(task_id.to_string());
    save_task_ids(task_ids)
}

fn untrack_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.remove(task_id);
    save_task_ids(task_ids)
}

async fn reconnect_video(client: &Lattice) -> Result<(), ApiError> {
    match client.video.get_ingress_stream(&INGRESS_ID, None).await {
        Ok(response) => {
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            let status = response
                .ingress_stream
                .and_then(|stream| stream.status)
                .map(|status| status.to_string())
                .unwrap_or_default();
            println!("Reusing stream {} with status {}", *INGRESS_ID, status);
            return Ok(());
        }
        Err(ApiError::NotFoundError { .. }) => {}
        Err(error) => return Err(error),
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    let request = CreateIngressStreamRequest {
        ingress_id: Some(INGRESS_ID.clone()),
        title: Some(ASSET_NAME.to_string()),
        rtsp: Some(RtspSettings {
            url: Some(RTSP_URL.to_string()),
            ..Default::default()
        }),
        ..Default::default()
    };
    client.video.create_ingress_stream(&request, None).await?;
    println!("Created stream {}", *INGRESS_ID);
    Ok(())
}

async fn publish_entity(client: &Lattice) -> Result<(), ApiError> {
    let now = Utc::now();
    let entity = Entity {
        entity_id: Some(ENTITY_ID.clone()),
        is_live: Some(true),
        expiry_time: Some((now + chrono::Duration::minutes(5)).fixed_offset()),
        aliases: Some(Aliases {
            name: Some(ASSET_NAME.to_string()),
            ..Default::default()
        }),
        mil_view: Some(MilView {
            disposition: Some(MilViewDisposition::DispositionFriendly),
            environment: Some(MilViewEnvironment::EnvironmentLand),
            ..Default::default()
        }),
        ontology: Some(Ontology {
            template: Some(OntologyTemplate::TemplateAsset),
            platform_type: Some("CAMERA".to_string()),
            ..Default::default()
        }),
        location: Some(Location {
            position: Some(Position {
                latitude_degrees: Some(33.6411),
                longitude_degrees: Some(-117.9187),
                ..Default::default()
            }),
            ..Default::default()
        }),
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: Some(Media {
            media: Some(vec![MediaItem {
                item_identifier: Some(INGRESS_ID.clone()),
                r#type: Some(MediaItemType::MediaTypeVideo),
                ..Default::default()
            }]),
            ..Default::default()
        }),
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: Some(Provenance {
            integration_name: Some("my-integration".to_string()),
            data_type: Some("asset".to_string()),
            source_update_time: Some(now.fixed_offset()),
            ..Default::default()
        }),
        ..Default::default()
    };
    client.entities.publish_entity(&entity, None).await?;
    println!("Republished entity {}", *ENTITY_ID);
    Ok(())
}

async fn resolve_tracked_tasks(
    client: &Lattice,
    task_ids: &mut BTreeSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let author = Principal {
        system: Some(System {
            entity_id: Some(ENTITY_ID.clone()),
            ..Default::default()
        }),
        ..Default::default()
    };
    for task_id in task_ids.clone() {
        let task = match client.tasks.get_task(&task_id, None).await {
            Ok(task) => task,
            Err(ApiError::NotFoundError { .. }) => {
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            Err(error) => return Err(error.into()),
        };
        let (Some(status), Some(status_version)) = (
            task.status.as_ref(),
            task.version.as_ref().and_then(|version| version.status_version),
        ) else {
            println!("Task {} is missing its status or version. Skipping.", task_id);
            continue;
        };

        let cancelled = matches!(status.status, Some(TaskStatusStatus::StatusCancelRequested))
            || matches!(
                task.delivery_state.as_ref().and_then(|state| state.status.as_ref()),
                Some(DeliveryStateStatus::DeliveryStatusPendingCancel)
            );
        let error = match status.status {
            Some(TaskStatusStatus::StatusDoneOk | TaskStatusStatus::StatusDoneNotOk) => {
                // An operator or another system closed the task while the agent was offline.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in delivery_state, not in the task status. Accept the cancellation.
            _ if cancelled => TaskError {
                code: Some(TaskErrorCode::ErrorCodeCancelled),
                message: Some("Cancelled while the agent was offline.".to_string()),
                ..Default::default()
            },
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            _ => TaskError {
                code: Some(TaskErrorCode::ErrorCodeFailed),
                message: Some("Agent restarted and could not resume the task.".to_string()),
                ..Default::default()
            },
        };
        let code = error.code.as_ref().map(|code| code.to_string()).unwrap_or_default();

        // Read status_version from GetTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        let request = TaskStatusUpdate {
            status_version: Some(status_version + 1),
            new_status: Some(TaskStatus {
                status: Some(TaskStatusStatus::StatusDoneNotOk),
                task_error: Some(error),
                ..Default::default()
            }),
            author: Some(author.clone()),
        };
        client.tasks.update_task_status(&task_id, &request, None).await?;
        println!("Closed task {} with {}", task_id, code);
        untrack_task(task_ids, &task_id)?;
    }
    Ok(())
}

#[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)?;

    let mut task_ids = load_task_ids()?;
    let result: Result<(), Box<dyn std::error::Error>> = async {
        reconnect_video(&client).await?;
        publish_entity(&client).await?;
        resolve_tracked_tasks(&client, &mut task_ids).await?;
        Ok(())
    }
    .await;
    if let Err(error) = result {
        eprintln!("Failed to recover after restart: {}", error);
        std::process::exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // track_task and untrack_task as tasks start and finish.
    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={111} maxLines={12}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
//
// It recovers an integration's video stream, entity, and tasks after the integration restarts.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"maps"
	"os"
	"path/filepath"
	"slices"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/taskmanager/v1/taskmanagerv1grpc"
	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/videomanager/v1/videomanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	ontologyv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/ontology/v1"
	taskmanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/taskmanager/v1"
	videomanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/videomanager/v1"

	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"

// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"

// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()

const (
	// RTSP source that Lattice pulls video from. Replace before running.
	rtspURL = "rtsp://<rtsp-host>:<port>/cam"
	// Local file that stores the IDs of tasks this agent is executing.
	stateFile = "agent_state.json"
)

var terminalStatuses = map[taskmanagerv1.Status]bool{
	taskmanagerv1.Status_STATUS_DONE_OK:     true,
	taskmanagerv1.Status_STATUS_DONE_NOT_OK: true,
}

type agentState struct {
	TaskIDs []string `json:"task_ids"`
}

func loadTaskIDs() (map[string]bool, error) {
	taskIDs := map[string]bool{}
	data, err := os.ReadFile(stateFile)
	if errors.Is(err, os.ErrNotExist) {
		return taskIDs, nil
	}
	if err != nil {
		return nil, err
	}
	var state agentState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	for _, taskID := range state.TaskIDs {
		taskIDs[taskID] = true
	}
	return taskIDs, nil
}

func saveTaskIDs(taskIDs map[string]bool) error {
	ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
	slices.Sort(ids)
	data, err := json.Marshal(agentState{TaskIDs: ids})
	if err != nil {
		return err
	}
	// Write to a temporary file, then rename it over the original. A power loss during the
	// write leaves the previous file intact instead of a truncated one.
	f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	if _, err := f.Write(data); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), stateFile)
}

// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
	taskIDs[taskID] = true
	return saveTaskIDs(taskIDs)
}

// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
	delete(taskIDs, taskID)
	return saveTaskIDs(taskIDs)
}

func reconnectVideo(ctx context.Context, client videomanagerv1grpc.VideoManagerAPIClient) error {
	response, err := client.GetIngressStream(ctx, &videomanagerv1.GetIngressStreamRequest{
		IngressId: ingressID,
	})
	if err == nil {
		// The stream survived the restart. Reuse it instead of creating a duplicate.
		fmt.Printf("Reusing stream %s with status %s\n", ingressID, response.GetIngressStream().GetStatus())
		return nil
	}
	if status.Code(err) != codes.NotFound {
		return err
	}

	// Lattice returns not found both for a stream that never existed and for one that was deleted.
	_, err = client.CreateIngressStream(ctx, &videomanagerv1.CreateIngressStreamRequest{
		IngressId: proto.String(ingressID),
		Title:     assetName,
		Ingress: &videomanagerv1.CreateIngressStreamRequest_Rtsp{
			Rtsp: &videomanagerv1.RtspSettings{
				Url: proto.String(rtspURL),
			},
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Created stream %s\n", ingressID)
	return nil
}

func publishEntity(ctx context.Context, client entitymanagerv1grpc.EntityManagerAPIClient) error {
	now := time.Now().UTC()
	_, err := client.PublishEntity(ctx, &entitymanagerv1.PublishEntityRequest{Entity: &entitymanagerv1.Entity{
		EntityId:   entityID,
		IsLive:     true,
		ExpiryTime: timestamppb.New(now.Add(5 * time.Minute)),
		Aliases:    &entitymanagerv1.Aliases{Name: assetName},
		MilView: &entitymanagerv1.MilView{
			Disposition: ontologyv1.Disposition_DISPOSITION_FRIENDLY,
			Environment: ontologyv1.Environment_ENVIRONMENT_LAND,
		},
		Ontology: &entitymanagerv1.Ontology{
			Template:     entitymanagerv1.Template_TEMPLATE_ASSET,
			PlatformType: "CAMERA",
		},
		Location: &entitymanagerv1.Location{
			Position: &entitymanagerv1.Position{
				LatitudeDegrees:  33.6411,
				LongitudeDegrees: -117.9187,
			},
		},
		// Because ingressID never changes, the entity can reference the stream on every publish.
		Media: &entitymanagerv1.Media{Media: []*entitymanagerv1.MediaItem{{
			ItemIdentifier: ingressID,
			Type:           entitymanagerv1.MediaType_MEDIA_TYPE_VIDEO,
		}}},
		// Include every other component your integration publishes, such as its TaskCatalog.
		Provenance: &entitymanagerv1.Provenance{
			IntegrationName:  "my-integration",
			DataType:         "asset",
			SourceUpdateTime: timestamppb.New(now),
		},
	}})
	if err != nil {
		return err
	}
	fmt.Printf("Republished entity %s\n", entityID)
	return nil
}

func resolveTrackedTasks(ctx context.Context, client taskmanagerv1grpc.TaskManagerAPIClient, taskIDs map[string]bool) error {
	author := &taskmanagerv1.Principal{
		Agent: &taskmanagerv1.Principal_System{
			System: &taskmanagerv1.System{EntityId: entityID},
		},
	}
	for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
		response, err := client.GetTask(ctx, &taskmanagerv1.GetTaskRequest{TaskId: taskID})
		if status.Code(err) == codes.NotFound {
			// The task no longer exists in Lattice, so there's nothing to resolve.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
		task := response.GetTask()
		if task.GetStatus() == nil || task.GetVersion() == nil {
			fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
			continue
		}

		taskStatus := task.GetStatus().GetStatus()
		if terminalStatuses[taskStatus] {
			// An operator or another system closed the task while the agent was offline.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}

		var taskError *taskmanagerv1.TaskError
		cancelled := taskStatus == taskmanagerv1.Status_STATUS_CANCEL_REQUESTED ||
			task.GetDeliveryState().GetStatus() == taskmanagerv1.DeliveryStatus_DELIVERY_STATUS_PENDING_CANCEL
		if cancelled {
			// An operator cancelled the task while the agent was offline. Lattice records the cancel
			// in delivery_state, not in the task status. Accept the cancellation.
			taskError = &taskmanagerv1.TaskError{
				Code:    taskmanagerv1.ErrorCode_ERROR_CODE_CANCELLED,
				Message: "Cancelled while the agent was offline.",
			}
		} else {
			// The agent lost its execution context, so report the task as failed rather than
			// leave it active with nothing working on it.
			taskError = &taskmanagerv1.TaskError{
				Code:    taskmanagerv1.ErrorCode_ERROR_CODE_FAILED,
				Message: "Agent restarted and could not resume the task.",
			}
		}

		// Read the status version from GetTask, not from local state: the status might have
		// changed while the agent was offline, and Lattice ignores updates with a stale version.
		_, err = client.UpdateStatus(ctx, &taskmanagerv1.UpdateStatusRequest{
			StatusUpdate: &taskmanagerv1.StatusUpdate{
				Version: &taskmanagerv1.TaskVersion{
					TaskId:        taskID,
					StatusVersion: task.GetVersion().GetStatusVersion() + 1,
				},
				Status: &taskmanagerv1.TaskStatus{
					Status:    taskmanagerv1.Status_STATUS_DONE_NOT_OK,
					TaskError: taskError,
				},
				Author: author,
			},
		})
		if err != nil {
			return err
		}
		fmt.Printf("Closed task %s with %s\n", taskID, taskError.GetCode())
		if err := untrackTask(taskIDs, taskID); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	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()

	videoClient := videomanagerv1grpc.NewVideoManagerAPIClient(conn)
	entityClient := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)
	taskClient := taskmanagerv1grpc.NewTaskManagerAPIClient(conn)

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	taskIDs, err := loadTaskIDs()
	if err != nil {
		log.Fatalf("Failed to load saved task IDs: %v", err)
	}
	if err := reconnectVideo(ctx, videoClient); err != nil {
		log.Fatalf("Failed to reconnect video: %v", err)
	}
	if err := publishEntity(ctx, entityClient); err != nil {
		log.Fatalf("Failed to republish entity: %v", err)
	}
	if err := resolveTrackedTasks(ctx, taskClient, taskIDs); err != nil {
		log.Fatalf("Failed to resolve tracked tasks: %v", err)
	}

	// Recovery is complete. Start your regular publish loop and agent stream here, and call
	// trackTask and untrackTask as tasks start and finish.
}

```

```py title={"Python (gRPC)"} startLine={80} maxLines={10}
# 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
# It recovers an integration's video stream, entity, and tasks after the integration restarts.

import json
import os
import sys
import tempfile
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from connectrpc.code import Code
from connectrpc.errors import ConnectError
from protobuf import Oneof
from protobuf.wkt import Timestamp

from anduril.entitymanager.v1.entity_pub_pb import Aliases, Entity, Provenance
from anduril.entitymanager.v1.entity_manager_api_pub_pb import PublishEntityRequest
from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.location_pub_pb import Location, Position
from anduril.entitymanager.v1.media_pub_pb import Media, MediaItem, MediaType
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.ontology.v1.type_pub_pb import Disposition, Environment
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.taskmanager.v1.task_pub_pb import (
    DeliveryStatus,
    ErrorCode,
    Principal,
    Status,
    StatusUpdate,
    System,
    TaskError,
    TaskStatus,
    TaskVersion,
)
from anduril.taskmanager.v1.task_manager_api_pub_pb import GetTaskRequest, UpdateStatusRequest
from anduril.taskmanager.v1.task_manager_api_pub_connect import TaskManagerAPIClientSync
from anduril.videomanager.v1.create_ingress_stream_request_pub_pb import CreateIngressStreamRequest
from anduril.videomanager.v1.get_ingress_stream_request_pub_pb import GetIngressStreamRequest
from anduril.videomanager.v1.rtsp_settings_pub_pb import RtspSettings
from anduril.videomanager.v1.video_manager_api_pub_connect import VideoManagerAPIClientSync

# A name that is unique to this asset and never changes, such as a serial number read from
# hardware or configuration. Replace before running.
ASSET_NAME = "<ASSET-NAME>"
# The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
# so it's the same after every restart.
INGRESS_ID = f"{ASSET_NAME}.cam"
# The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
# and in every language.
ENTITY_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:my-integration:{ASSET_NAME}"))
# RTSP source that Lattice pulls video from. Replace before running.
RTSP_URL = "rtsp://<rtsp-host>:<port>/cam"
# Local file that stores the IDs of tasks this agent is executing.
STATE_FILE = "agent_state.json"

TERMINAL_STATUSES = {Status.DONE_OK, Status.DONE_NOT_OK}


def load_task_ids():
    try:
        with open(STATE_FILE) as f:
            return set(json.load(f)["task_ids"])
    except FileNotFoundError:
        return set()


def save_task_ids(task_ids):
    # Write to a temporary file, then rename it over the original. A power loss during the
    # write leaves the previous file intact instead of a truncated one.
    directory = os.path.dirname(os.path.abspath(STATE_FILE))
    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f:
        json.dump({"task_ids": sorted(task_ids)}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(f.name, STATE_FILE)


def track_task(task_ids, task_id):
    # Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.add(task_id)
    save_task_ids(task_ids)


def untrack_task(task_ids, task_id):
    # Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.discard(task_id)
    save_task_ids(task_ids)


def reconnect_video(client):
    try:
        response = client.get_ingress_stream(GetIngressStreamRequest(ingress_id=INGRESS_ID), timeout_ms=10000)
        # The stream survived the restart. Reuse it instead of creating a duplicate.
        print(f"Reusing stream {INGRESS_ID} with status STREAM_STATUS_{response.ingress_stream.status.name}")
        return
    except ConnectError as error:
        if error.code != Code.NOT_FOUND:
            raise

    # Lattice returns not found both for a stream that never existed and for one that was deleted.
    client.create_ingress_stream(
        CreateIngressStreamRequest(
            ingress_id=INGRESS_ID,
            title=ASSET_NAME,
            ingress=Oneof("rtsp", RtspSettings(url=RTSP_URL)),
        ),
        timeout_ms=30000,
    )
    print(f"Created stream {INGRESS_ID}")


def publish_entity(client):
    now = datetime.now(timezone.utc)
    entity = Entity(
        entity_id=ENTITY_ID,
        is_live=True,
        expiry_time=Timestamp.from_datetime(now + timedelta(minutes=5)),
        aliases=Aliases(name=ASSET_NAME),
        mil_view=MilView(disposition=Disposition.FRIENDLY, environment=Environment.LAND),
        ontology=Ontology(template=Template.ASSET, platform_type="CAMERA"),
        location=Location(position=Position(latitude_degrees=33.6411, longitude_degrees=-117.9187)),
        # Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media=Media(media=[MediaItem(item_identifier=INGRESS_ID, type=MediaType.VIDEO)]),
        # Include every other component your integration publishes, such as its TaskCatalog.
        provenance=Provenance(
            integration_name="my-integration",
            data_type="asset",
            source_update_time=Timestamp.from_datetime(now),
        ),
    )
    client.publish_entity(PublishEntityRequest(entity=entity), timeout_ms=10000)
    print(f"Republished entity {ENTITY_ID}")


def resolve_tracked_tasks(client, task_ids):
    author = Principal(agent=Oneof("system", System(entity_id=ENTITY_ID)))
    for task_id in sorted(task_ids):
        try:
            task = client.get_task(GetTaskRequest(task_id=task_id), timeout_ms=10000).task
        except ConnectError as error:
            if error.code != Code.NOT_FOUND:
                raise
            # The task no longer exists in Lattice, so there's nothing to resolve.
            untrack_task(task_ids, task_id)
            continue
        if not task or not task.status or not task.version:
            print(f"Task {task_id} is missing its status or version. Skipping.")
            continue

        if task.status.status in TERMINAL_STATUSES:
            # An operator or another system closed the task while the agent was offline.
            untrack_task(task_ids, task_id)
            continue

        pending_cancel = task.delivery_state and task.delivery_state.status == DeliveryStatus.PENDING_CANCEL
        if task.status.status == Status.CANCEL_REQUESTED or pending_cancel:
            # An operator cancelled the task while the agent was offline. Lattice records the cancel
            # in delivery_state, not in the task status. Accept the cancellation.
            error = TaskError(code=ErrorCode.CANCELLED, message="Cancelled while the agent was offline.")
        else:
            # The agent lost its execution context, so report the task as failed rather than
            # leave it active with nothing working on it.
            error = TaskError(code=ErrorCode.FAILED, message="Agent restarted and could not resume the task.")

        # Read status_version from GetTask, not from local state: the status might have
        # changed while the agent was offline, and Lattice ignores updates with a stale version.
        status_update = StatusUpdate(
            version=TaskVersion(task_id=task_id, status_version=task.version.status_version + 1),
            status=TaskStatus(status=Status.DONE_NOT_OK, task_error=error),
            author=author,
        )
        client.update_status(UpdateStatusRequest(status_update=status_update), timeout_ms=10000)
        print(f"Closed task {task_id} with ERROR_CODE_{error.code.name}")
        untrack_task(task_ids, task_id)


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 clients over Connect gRPC with authentication
    video_client = create_client(VideoManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)
    entity_client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)
    task_client = create_client(TaskManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    task_ids = load_task_ids()
    try:
        reconnect_video(video_client)
        publish_entity(entity_client)
        resolve_tracked_tasks(task_client, task_ids)
    except Exception as error:
        print(f"Failed to recover after restart: {error}", file=sys.stderr)
        sys.exit(1)

    # Recovery is complete. Start your regular publish loop and agent stream here, and call
    # track_task and untrack_task as tasks start and finish.


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={92} maxLines={11}
// 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

// track_task is called from the main loop you add after recovery.
#![allow(dead_code)]

mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    Aliases, Entity, Location, Media, MediaItem, MediaType, MilView, Ontology, Position, Provenance,
    PublishEntityRequest, Template,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{Disposition, Environment};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::taskmanager::v1::{
    principal, DeliveryStatus, ErrorCode, GetTaskRequest, Principal, Status, StatusUpdate, System, TaskError,
    TaskStatus, TaskVersion, UpdateStatusRequest,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::videomanager::v1::{
    create_ingress_stream_request::Ingress, CreateIngressStreamRequest, GetIngressStreamRequest,
    RtspSettings,
};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::taskmanager::v1::tonic::task_manager_api_client::TaskManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::videomanager::v1::tonic::video_manager_api_client::VideoManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use prost_types::Timestamp;
use serde_json::{json, Value};
use tonic::metadata::{Ascii, MetadataValue};
use tonic::service::interceptor::InterceptedService;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::{Code, Request};
use uuid::Uuid;

use std::collections::BTreeSet;
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::sync::LazyLock;
use std::time::{SystemTime, UNIX_EPOCH};

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME: &str = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
static INGRESS_ID: LazyLock<String> = LazyLock::new(|| format!("{}.cam", ASSET_NAME));
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
static ENTITY_ID: LazyLock<String> = LazyLock::new(|| {
    let name = format!("urn:my-integration:{}", ASSET_NAME);
    Uuid::new_v5(&Uuid::NAMESPACE_URL, name.as_bytes()).to_string()
});
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL: &str = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE: &str = "agent_state.json";

type Interceptor = Box<dyn FnMut(Request<()>) -> Result<Request<()>, tonic::Status> + Send + Sync>;
type VideoClient = VideoManagerApiClient<InterceptedService<Channel, Interceptor>>;
type EntityClient = EntityManagerApiClient<InterceptedService<Channel, Interceptor>>;
type TaskClient = TaskManagerApiClient<InterceptedService<Channel, Interceptor>>;

fn now_timestamp() -> Timestamp {
    let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    Timestamp {
        seconds: d.as_secs() as i64,
        nanos: d.subsec_nanos() as i32,
    }
}

fn load_task_ids() -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
    let contents = match fs::read_to_string(STATE_FILE) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(error.into()),
    };
    let state: Value = contents.parse()?;
    let task_ids = state["task_ids"].as_array().ok_or("task_ids is missing")?;
    Ok(task_ids.iter().filter_map(|id| id.as_str().map(String::from)).collect())
}

fn save_task_ids(task_ids: &BTreeSet<String>) -> std::io::Result<()> {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    let temp_path = format!("{}.tmp", STATE_FILE);
    let mut file = File::create(&temp_path)?;
    file.write_all(json!({ "task_ids": task_ids }).to_string().as_bytes())?;
    file.sync_all()?;
    fs::rename(&temp_path, STATE_FILE)
}

fn track_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.insert(task_id.to_string());
    save_task_ids(task_ids)
}

fn untrack_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.remove(task_id);
    save_task_ids(task_ids)
}

async fn reconnect_video(client: &mut VideoClient) -> Result<(), tonic::Status> {
    let request = Request::new(GetIngressStreamRequest {
        ingress_id: INGRESS_ID.clone(),
    });
    match client.get_ingress_stream(request).await {
        Ok(response) => {
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            let status = response
                .into_inner()
                .ingress_stream
                .map(|stream| stream.status().as_str_name())
                .unwrap_or_default();
            println!("Reusing stream {} with status {}", *INGRESS_ID, status);
            return Ok(());
        }
        Err(status) if status.code() == Code::NotFound => {}
        Err(status) => return Err(status),
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    let request = Request::new(CreateIngressStreamRequest {
        ingress_id: Some(INGRESS_ID.clone()),
        title: ASSET_NAME.to_string(),
        ingress: Some(Ingress::Rtsp(RtspSettings {
            url: Some(RTSP_URL.to_string()),
        })),
    });
    client.create_ingress_stream(request).await?;
    println!("Created stream {}", *INGRESS_ID);
    Ok(())
}

async fn publish_entity(client: &mut EntityClient) -> Result<(), tonic::Status> {
    let now = now_timestamp();
    let entity = Entity {
        entity_id: ENTITY_ID.clone(),
        is_live: true,
        expiry_time: Some(Timestamp {
            seconds: now.seconds + 5 * 60,
            nanos: now.nanos,
        }),
        aliases: Some(Aliases {
            name: ASSET_NAME.to_string(),
            ..Default::default()
        }),
        mil_view: Some(MilView {
            disposition: Disposition::Friendly as i32,
            environment: Environment::Land as i32,
            ..Default::default()
        }),
        ontology: Some(Ontology {
            template: Template::Asset as i32,
            platform_type: "CAMERA".to_string(),
            ..Default::default()
        }),
        location: Some(Location {
            position: Some(Position {
                latitude_degrees: 33.6411,
                longitude_degrees: -117.9187,
                ..Default::default()
            }),
            ..Default::default()
        }),
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: Some(Media {
            media: vec![MediaItem {
                item_identifier: INGRESS_ID.clone(),
                r#type: MediaType::Video as i32,
                ..Default::default()
            }],
        }),
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: Some(Provenance {
            integration_name: "my-integration".to_string(),
            data_type: "asset".to_string(),
            source_update_time: Some(now),
            ..Default::default()
        }),
        ..Default::default()
    };
    client
        .publish_entity(Request::new(PublishEntityRequest {
            entity: Some(entity),
        }))
        .await?;
    println!("Republished entity {}", *ENTITY_ID);
    Ok(())
}

async fn resolve_tracked_tasks(
    client: &mut TaskClient,
    task_ids: &mut BTreeSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let author = Principal {
        agent: Some(principal::Agent::System(System {
            entity_id: ENTITY_ID.clone(),
            ..Default::default()
        })),
        ..Default::default()
    };
    for task_id in task_ids.clone() {
        let request = Request::new(GetTaskRequest {
            task_id: task_id.clone(),
            ..Default::default()
        });
        let task = match client.get_task(request).await {
            Ok(response) => response.into_inner().task,
            Err(status) if status.code() == Code::NotFound => {
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            Err(status) => return Err(status.into()),
        };
        let Some((status, version)) = task.as_ref().and_then(|task| task.status.as_ref().zip(task.version.as_ref()))
        else {
            println!("Task {} is missing its status or version. Skipping.", task_id);
            continue;
        };

        let cancelled = status.status() == Status::CancelRequested
            || task.as_ref().and_then(|task| task.delivery_state.as_ref()).map(|state| state.status())
                == Some(DeliveryStatus::PendingCancel);
        let error = match status.status() {
            Status::DoneOk | Status::DoneNotOk => {
                // An operator or another system closed the task while the agent was offline.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in delivery_state, not in the task status. Accept the cancellation.
            _ if cancelled => TaskError {
                code: ErrorCode::Cancelled as i32,
                message: "Cancelled while the agent was offline.".to_string(),
                ..Default::default()
            },
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            _ => TaskError {
                code: ErrorCode::Failed as i32,
                message: "Agent restarted and could not resume the task.".to_string(),
                ..Default::default()
            },
        };
        let code = error.code().as_str_name();

        // Read status_version from GetTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        let status_update = StatusUpdate {
            version: Some(TaskVersion {
                task_id: task_id.clone(),
                status_version: version.status_version + 1,
                ..Default::default()
            }),
            status: Some(TaskStatus {
                status: Status::DoneNotOk as i32,
                task_error: Some(error),
                ..Default::default()
            }),
            author: Some(author.clone()),
            ..Default::default()
        };
        client
            .update_status(Request::new(UpdateStatusRequest {
                status_update: Some(status_update),
            }))
            .await?;
        println!("Closed task {} with {}", task_id, code);
        untrack_task(task_ids, &task_id)?;
    }
    Ok(())
}

fn auth_interceptor(
    auth_header: MetadataValue<Ascii>,
    sandbox_header: MetadataValue<Ascii>,
) -> Interceptor {
    Box::new(move |mut req: Request<()>| {
        req.metadata_mut()
            .insert("authorization", auth_header.clone());
        req.metadata_mut()
            .insert("anduril-sandbox-authorization", sandbox_header.clone());
        Ok(req)
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    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");
    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables");
        std::process::exit(1);
    }

    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

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

    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<Ascii> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<Ascii> = format!("Bearer {}", sandboxes_token).parse()?;

    // All three clients share the same channel and inject the same auth metadata.
    let mut video_client: VideoClient = VideoManagerApiClient::with_interceptor(
        channel.clone(),
        auth_interceptor(auth_header.clone(), sandbox_header.clone()),
    );
    let mut entity_client: EntityClient = EntityManagerApiClient::with_interceptor(
        channel.clone(),
        auth_interceptor(auth_header.clone(), sandbox_header.clone()),
    );
    let mut task_client: TaskClient = TaskManagerApiClient::with_interceptor(
        channel,
        auth_interceptor(auth_header, sandbox_header),
    );

    let mut task_ids = load_task_ids()?;
    let result: Result<(), Box<dyn std::error::Error>> = async {
        reconnect_video(&mut video_client).await?;
        publish_entity(&mut entity_client).await?;
        resolve_tracked_tasks(&mut task_client, &mut task_ids).await?;
        Ok(())
    }
    .await;
    if let Err(error) = result {
        eprintln!("Failed to recover after restart: {}", error);
        std::process::exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // track_task and untrack_task as tasks start and finish.
    Ok(())
}

```

Save the file safely. A power loss in the middle of a write can leave a truncated file, so write to a temporary file in the same directory, flush it to disk, then rename it over the original.
A rename on the same file system is atomic, so the file on disk is always complete:

```go title={"Go (REST)"} startLine={71} maxLines={27}
// This Go example uses the Lattice REST SDK (lattice-sdk-go) to recover an integration's video
// stream, entity, and tasks after the integration restarts.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"maps"
	"net/http"
	"os"
	"path/filepath"
	"slices"
	"time"

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

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"

// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"

// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()

const (
	// RTSP source that Lattice pulls video from. Replace before running.
	rtspURL = "rtsp://<rtsp-host>:<port>/cam"
	// Local file that stores the IDs of tasks this agent is executing.
	stateFile = "agent_state.json"
)

var terminalStatuses = map[Lattice.TaskStatusStatus]bool{
	Lattice.TaskStatusStatusStatusDoneOk:    true,
	Lattice.TaskStatusStatusStatusDoneNotOk: true,
}

type agentState struct {
	TaskIDs []string `json:"task_ids"`
}

func loadTaskIDs() (map[string]bool, error) {
	taskIDs := map[string]bool{}
	data, err := os.ReadFile(stateFile)
	if errors.Is(err, os.ErrNotExist) {
		return taskIDs, nil
	}
	if err != nil {
		return nil, err
	}
	var state agentState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	for _, taskID := range state.TaskIDs {
		taskIDs[taskID] = true
	}
	return taskIDs, nil
}

func saveTaskIDs(taskIDs map[string]bool) error {
	ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
	slices.Sort(ids)
	data, err := json.Marshal(agentState{TaskIDs: ids})
	if err != nil {
		return err
	}
	// Write to a temporary file, then rename it over the original. A power loss during the
	// write leaves the previous file intact instead of a truncated one.
	f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	if _, err := f.Write(data); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), stateFile)
}

// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
	taskIDs[taskID] = true
	return saveTaskIDs(taskIDs)
}

// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
	delete(taskIDs, taskID)
	return saveTaskIDs(taskIDs)
}

func reconnectVideo(ctx context.Context, client *client.Client) error {
	response, err := client.Video.GetIngressStream(ctx, &Lattice.GetIngressStreamRequest{
		IngressID: ingressID,
	})
	var apiErr *core.APIError
	if err == nil {
		// The stream survived the restart. Reuse it instead of creating a duplicate.
		status := ""
		if s := response.GetIngressStream().GetStatus(); s != nil {
			status = string(*s)
		}
		fmt.Printf("Reusing stream %s with status %s\n", ingressID, status)
		return nil
	}
	if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
		return err
	}

	// Lattice returns not found both for a stream that never existed and for one that was deleted.
	_, err = client.Video.CreateIngressStream(ctx, &Lattice.CreateIngressStreamRequest{
		IngressID: Lattice.String(ingressID),
		Title:     Lattice.String(assetName),
		Rtsp: &Lattice.RtspSettings{
			URL: Lattice.String(rtspURL),
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Created stream %s\n", ingressID)
	return nil
}

func publishEntity(ctx context.Context, client *client.Client) error {
	now := time.Now().UTC()
	_, err := client.Entities.PublishEntity(ctx, &Lattice.Entity{
		EntityID:   Lattice.String(entityID),
		IsLive:     Lattice.Bool(true),
		ExpiryTime: Lattice.Time(now.Add(5 * time.Minute)),
		Aliases:    &Lattice.Aliases{Name: Lattice.String(assetName)},
		MilView: &Lattice.MilView{
			Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
			Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
		},
		Ontology: &Lattice.Ontology{
			Template:     Lattice.OntologyTemplateTemplateAsset.Ptr(),
			PlatformType: Lattice.String("CAMERA"),
		},
		Location: &Lattice.Location{
			Position: &Lattice.Position{
				LatitudeDegrees:  Lattice.Float64(33.6411),
				LongitudeDegrees: Lattice.Float64(-117.9187),
			},
		},
		// Because ingressID never changes, the entity can reference the stream on every publish.
		Media: &Lattice.Media{Media: []*Lattice.MediaItem{{
			ItemIdentifier: Lattice.String(ingressID),
			Type:           Lattice.MediaItemTypeMediaTypeVideo.Ptr(),
		}}},
		// Include every other component your integration publishes, such as its TaskCatalog.
		Provenance: &Lattice.Provenance{
			IntegrationName:  Lattice.String("my-integration"),
			DataType:         Lattice.String("asset"),
			SourceUpdateTime: Lattice.Time(now),
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Republished entity %s\n", entityID)
	return nil
}

func resolveTrackedTasks(ctx context.Context, client *client.Client, taskIDs map[string]bool) error {
	author := &Lattice.Principal{System: &Lattice.System{EntityID: Lattice.String(entityID)}}
	for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
		task, err := client.Tasks.GetTask(ctx, &Lattice.GetTaskRequest{TaskID: taskID})
		var apiErr *core.APIError
		if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
			// The task no longer exists in Lattice, so there's nothing to resolve.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
		if task.Status == nil || task.Status.Status == nil || task.Version == nil || task.Version.StatusVersion == nil {
			fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
			continue
		}

		status := *task.Status.Status
		if terminalStatuses[status] {
			// An operator or another system closed the task while the agent was offline.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}

		var taskError *Lattice.TaskError
		cancelled := status == Lattice.TaskStatusStatusStatusCancelRequested ||
			(task.GetDeliveryState().GetStatus() != nil &&
				*task.GetDeliveryState().GetStatus() == Lattice.DeliveryStateStatusDeliveryStatusPendingCancel)
		if cancelled {
			// An operator cancelled the task while the agent was offline. Lattice records the cancel
			// in delivery_state, not in the task status. Accept the cancellation.
			taskError = &Lattice.TaskError{
				Code:    Lattice.TaskErrorCodeErrorCodeCancelled.Ptr(),
				Message: Lattice.String("Cancelled while the agent was offline."),
			}
		} else {
			// The agent lost its execution context, so report the task as failed rather than
			// leave it active with nothing working on it.
			taskError = &Lattice.TaskError{
				Code:    Lattice.TaskErrorCodeErrorCodeFailed.Ptr(),
				Message: Lattice.String("Agent restarted and could not resume the task."),
			}
		}

		// Read the status version from GetTask, not from local state: the status might have
		// changed while the agent was offline, and Lattice ignores updates with a stale version.
		statusVersion := *task.Version.StatusVersion + 1
		_, err = client.Tasks.UpdateTaskStatus(ctx, &Lattice.TaskStatusUpdate{
			TaskID:        taskID,
			StatusVersion: &statusVersion,
			NewStatus: &Lattice.TaskStatus{
				Status:    Lattice.TaskStatusStatusStatusDoneNotOk.Ptr(),
				TaskError: taskError,
			},
			Author: author,
		})
		if err != nil {
			return err
		}
		fmt.Printf("Closed task %s with %s\n", taskID, *taskError.Code)
		if err := untrackTask(taskIDs, taskID); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	// Get environment variables
	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")

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

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

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

	ctx := context.Background()

	taskIDs, err := loadTaskIDs()
	if err != nil {
		fmt.Printf("Failed to load saved task IDs: %v\n", err)
		os.Exit(1)
	}
	if err := reconnectVideo(ctx, LatticeClient); err != nil {
		fmt.Printf("Failed to reconnect video: %v\n", err)
		os.Exit(1)
	}
	if err := publishEntity(ctx, LatticeClient); err != nil {
		fmt.Printf("Failed to republish entity: %v\n", err)
		os.Exit(1)
	}
	if err := resolveTrackedTasks(ctx, LatticeClient, taskIDs); err != nil {
		fmt.Printf("Failed to resolve tracked tasks: %v\n", err)
		os.Exit(1)
	}

	// Recovery is complete. Start your regular publish loop and agent stream here, and call
	// trackTask and untrackTask as tasks start and finish.
}

```

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

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.core.LatticeApiException;
import com.anduril.resources.tasks.requests.TaskStatusUpdate;
import com.anduril.resources.video.requests.CreateIngressStreamRequest;
import com.anduril.types.Aliases;
import com.anduril.types.DeliveryState;
import com.anduril.types.DeliveryStateStatus;
import com.anduril.types.Entity;
import com.anduril.types.Location;
import com.anduril.types.Media;
import com.anduril.types.MediaItem;
import com.anduril.types.MediaItemType;
import com.anduril.types.MilView;
import com.anduril.types.MilViewDisposition;
import com.anduril.types.MilViewEnvironment;
import com.anduril.types.Ontology;
import com.anduril.types.OntologyTemplate;
import com.anduril.types.Position;
import com.anduril.types.Principal;
import com.anduril.types.Provenance;
import com.anduril.types.RtspSettings;
import com.anduril.types.Task;
import com.anduril.types.TaskError;
import com.anduril.types.TaskErrorCode;
import com.anduril.types.TaskStatus;
import com.anduril.types.TaskStatusStatus;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * Recovers an integration's video stream, entity, and tasks with the Lattice SDK after the
 * integration restarts.
 */
public class HandleRestarts {
    // A name that is unique to this asset and never changes, such as a serial number read from
    // hardware or configuration. Replace before running.
    private static final String ASSET_NAME = "<ASSET-NAME>";
    // The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
    // so it's the same after every restart.
    private static final String INGRESS_ID = ASSET_NAME + ".cam";
    // The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
    // and in every language.
    // NAMESPACE_URL is the standard RFC 9562 URL namespace.
    private static final UUID NAMESPACE_URL = UUID.fromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8");
    private static final String ENTITY_ID = uuid5(NAMESPACE_URL, "urn:my-integration:" + ASSET_NAME).toString();
    // RTSP source that Lattice pulls video from. Replace before running.
    private static final String RTSP_URL = "rtsp://<rtsp-host>:<port>/cam";
    // Local file that stores the IDs of tasks this agent is executing.
    private static final Path STATE_FILE = Path.of("agent_state.json");

    private static final List<TaskStatusStatus> TERMINAL_STATUSES =
        List.of(TaskStatusStatus.STATUS_DONE_OK, TaskStatusStatus.STATUS_DONE_NOT_OK);

    private static final ObjectMapper JSON = new ObjectMapper();

    private static Set<String> loadTaskIds() throws IOException {
        Set<String> taskIds = new HashSet<>();
        if (!Files.exists(STATE_FILE)) {
            return taskIds;
        }
        for (JsonNode taskId : JSON.readTree(STATE_FILE.toFile()).path("task_ids")) {
            taskIds.add(taskId.asText());
        }
        return taskIds;
    }

    private static void saveTaskIds(Set<String> taskIds) throws IOException {
        // Write to a temporary file, then rename it over the original. A power loss during the
        // write leaves the previous file intact instead of a truncated one.
        Path target = STATE_FILE.toAbsolutePath();
        Path temp = Files.createTempFile(target.getParent(), "agent_state", ".tmp");
        ObjectNode state = JSON.createObjectNode();
        ArrayNode ids = state.putArray("task_ids");
        for (String taskId : new TreeSet<>(taskIds)) {
            ids.add(taskId);
        }
        try (FileChannel channel = FileChannel.open(temp, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(JSON.writeValueAsBytes(state)));
            channel.force(true);
        }
        Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE);
    }

    private static void trackTask(Set<String> taskIds, String taskId) throws IOException {
        // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
        taskIds.add(taskId);
        saveTaskIds(taskIds);
    }

    private static void untrackTask(Set<String> taskIds, String taskId) throws IOException {
        // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
        taskIds.remove(taskId);
        saveTaskIds(taskIds);
    }

    private static void reconnectVideo(Lattice client) {
        try {
            String status = client.video().getIngressStream(INGRESS_ID).getIngressStream()
                .flatMap(stream -> stream.getStatus()).map(Object::toString).orElse("");
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            System.out.println("Reusing stream " + INGRESS_ID + " with status " + status);
            return;
        } catch (LatticeApiException e) {
            if (e.statusCode() != 404) {
                throw e;
            }
        }

        // Lattice returns not found both for a stream that never existed and for one that was deleted.
        client.video().createIngressStream(CreateIngressStreamRequest.builder()
            .ingressId(INGRESS_ID)
            .title(ASSET_NAME)
            .rtsp(RtspSettings.builder()
                .url(RTSP_URL)
                .build())
            .build());
        System.out.println("Created stream " + INGRESS_ID);
    }

    private static void publishEntity(Lattice client) {
        OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
        client.entities().publishEntity(Entity.builder()
            .entityId(ENTITY_ID)
            .isLive(true)
            .expiryTime(now.plusMinutes(5))
            .aliases(Aliases.builder().name(ASSET_NAME).build())
            .milView(MilView.builder()
                .disposition(MilViewDisposition.DISPOSITION_FRIENDLY)
                .environment(MilViewEnvironment.ENVIRONMENT_LAND)
                .build())
            .ontology(Ontology.builder().template(OntologyTemplate.TEMPLATE_ASSET).platformType("CAMERA").build())
            .location(Location.builder()
                .position(Position.builder().latitudeDegrees(33.6411).longitudeDegrees(-117.9187).build())
                .build())
            // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
            .media(Media.builder()
                .media(List.of(MediaItem.builder().itemIdentifier(INGRESS_ID).type(MediaItemType.MEDIA_TYPE_VIDEO).build()))
                .build())
            // Include every other component your integration publishes, such as its TaskCatalog.
            .provenance(Provenance.builder()
                .integrationName("my-integration")
                .dataType("asset")
                .sourceUpdateTime(now)
                .build())
            .build());
        System.out.println("Republished entity " + ENTITY_ID);
    }

    private static void resolveTrackedTasks(Lattice client, Set<String> taskIds) throws IOException {
        Principal author = Principal.builder()
            .system(com.anduril.types.System.builder().entityId(ENTITY_ID).build())
            .build();
        for (String taskId : new TreeSet<>(taskIds)) {
            Task task;
            try {
                task = client.tasks().getTask(taskId);
            } catch (LatticeApiException e) {
                if (e.statusCode() != 404) {
                    throw e;
                }
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrackTask(taskIds, taskId);
                continue;
            }
            if (task.getStatus().isEmpty() || task.getStatus().get().getStatus().isEmpty()
                    || task.getVersion().isEmpty() || task.getVersion().get().getStatusVersion().isEmpty()) {
                System.out.println("Task " + taskId + " is missing its status or version. Skipping.");
                continue;
            }
            TaskStatusStatus status = task.getStatus().get().getStatus().get();
            int statusVersion = task.getVersion().get().getStatusVersion().get();

            if (TERMINAL_STATUSES.contains(status)) {
                // An operator or another system closed the task while the agent was offline.
                untrackTask(taskIds, taskId);
                continue;
            }

            TaskError error;
            boolean pendingCancel = task.getDeliveryState().flatMap(DeliveryState::getStatus)
                .map(DeliveryStateStatus.DELIVERY_STATUS_PENDING_CANCEL::equals).orElse(false);
            if (status.equals(TaskStatusStatus.STATUS_CANCEL_REQUESTED) || pendingCancel) {
                // An operator cancelled the task while the agent was offline. Lattice records the cancel
                // in deliveryState, not in the task status. Accept the cancellation.
                error = TaskError.builder()
                    .code(TaskErrorCode.ERROR_CODE_CANCELLED)
                    .message("Cancelled while the agent was offline.")
                    .build();
            } else {
                // The agent lost its execution context, so report the task as failed rather than
                // leave it active with nothing working on it.
                error = TaskError.builder()
                    .code(TaskErrorCode.ERROR_CODE_FAILED)
                    .message("Agent restarted and could not resume the task.")
                    .build();
            }

            // Read the status version from GetTask, not from local state: the status might have
            // changed while the agent was offline, and Lattice ignores updates with a stale version.
            client.tasks().updateTaskStatus(taskId, TaskStatusUpdate.builder()
                .statusVersion(statusVersion + 1)
                .newStatus(TaskStatus.builder()
                    .status(TaskStatusStatus.STATUS_DONE_NOT_OK)
                    .taskError(error)
                    .build())
                .author(author)
                .build());
            System.out.println("Closed task " + taskId + " with " + error.getCode().map(Object::toString).orElse(""));
            untrackTask(taskIds, taskId);
        }
    }

    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 and ensure the endpoint has its scheme
        if (isBlank(endpoint) || isBlank(environmentToken) || isBlank(sandboxesToken)) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        // Create Lattice client with Sandbox authentication
        Lattice client = Lattice.builder()
            .url(endpoint)
            .token(environmentToken)
            .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
            .build();

        try {
            Set<String> taskIds = loadTaskIds();
            reconnectVideo(client);
            publishEntity(client);
            resolveTrackedTasks(client, taskIds);
        } catch (Exception e) {
            System.err.println("Failed to recover after restart: " + e.getMessage());
            System.exit(1);
        }

        // Recovery is complete. Start your regular publish loop and agent stream here, and call
        // trackTask and untrackTask as tasks start and finish.
    }

    private static boolean isBlank(String value) {
        return value == null || value.isEmpty();
    }

    /**
     * Returns a name-based version 5 UUID, which is the same every time for the same namespace and name.
     */
    private static UUID uuid5(UUID namespace, String name) {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            sha1.update(ByteBuffer.allocate(16)
                .putLong(namespace.getMostSignificantBits())
                .putLong(namespace.getLeastSignificantBits())
                .array());
            sha1.update(name.getBytes(StandardCharsets.UTF_8));
            byte[] hash = sha1.digest();
            hash[6] = (byte) ((hash[6] & 0x0f) | 0x50); // Version 5
            hash[8] = (byte) ((hash[8] & 0x3f) | 0x80); // RFC 9562 variant
            ByteBuffer bytes = ByteBuffer.wrap(hash, 0, 16);
            return new UUID(bytes.getLong(), bytes.getLong());
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("SHA-1 is unavailable", e);
        }
    }
}

```

```py title={"Python (REST)"} startLine={54} maxLines={9}
# This Python example uses the Lattice REST SDK (anduril-lattice-sdk) to recover an integration's
# video stream, entity, and tasks after the integration restarts.

import json
import os
import sys
import tempfile
import uuid
from datetime import datetime, timedelta, timezone

from anduril import (
    Aliases,
    Lattice,
    Location,
    Media,
    MediaItem,
    MilView,
    Ontology,
    Position,
    Principal,
    Provenance,
    RtspSettings,
    System,
    TaskError,
    TaskStatus,
)
from anduril.core import ApiError

# A name that is unique to this asset and never changes, such as a serial number read from
# hardware or configuration. Replace before running.
ASSET_NAME = "<ASSET-NAME>"
# The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
# so it's the same after every restart.
INGRESS_ID = f"{ASSET_NAME}.cam"
# The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
# and in every language.
ENTITY_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:my-integration:{ASSET_NAME}"))
# RTSP source that Lattice pulls video from. Replace before running.
RTSP_URL = "rtsp://<rtsp-host>:<port>/cam"
# Local file that stores the IDs of tasks this agent is executing.
STATE_FILE = "agent_state.json"

TERMINAL_STATUSES = {"STATUS_DONE_OK", "STATUS_DONE_NOT_OK"}


def load_task_ids():
    try:
        with open(STATE_FILE) as f:
            return set(json.load(f)["task_ids"])
    except FileNotFoundError:
        return set()


def save_task_ids(task_ids):
    # Write to a temporary file, then rename it over the original. A power loss during the
    # write leaves the previous file intact instead of a truncated one.
    directory = os.path.dirname(os.path.abspath(STATE_FILE))
    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f:
        json.dump({"task_ids": sorted(task_ids)}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(f.name, STATE_FILE)


def track_task(task_ids, task_id):
    # Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.add(task_id)
    save_task_ids(task_ids)


def untrack_task(task_ids, task_id):
    # Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.discard(task_id)
    save_task_ids(task_ids)


def reconnect_video(client):
    try:
        stream = client.video.get_ingress_stream(INGRESS_ID).ingress_stream
        # The stream survived the restart. Reuse it instead of creating a duplicate.
        print(f"Reusing stream {INGRESS_ID} with status {stream.status}")
        return
    except ApiError as error:
        if error.status_code != 404:
            raise

    # Lattice returns not found both for a stream that never existed and for one that was deleted.
    client.video.create_ingress_stream(
        ingress_id=INGRESS_ID,
        title=ASSET_NAME,
        rtsp=RtspSettings(url=RTSP_URL),
    )
    print(f"Created stream {INGRESS_ID}")


def publish_entity(client):
    now = datetime.now(timezone.utc)
    client.entities.publish_entity(
        entity_id=ENTITY_ID,
        is_live=True,
        expiry_time=now + timedelta(minutes=5),
        aliases=Aliases(name=ASSET_NAME),
        mil_view=MilView(disposition="DISPOSITION_FRIENDLY", environment="ENVIRONMENT_LAND"),
        ontology=Ontology(template="TEMPLATE_ASSET", platform_type="CAMERA"),
        location=Location(position=Position(latitude_degrees=33.6411, longitude_degrees=-117.9187)),
        # Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media=Media(media=[MediaItem(item_identifier=INGRESS_ID, type="MEDIA_TYPE_VIDEO")]),
        # Include every other component your integration publishes, such as its TaskCatalog.
        provenance=Provenance(
            integration_name="my-integration",
            data_type="asset",
            source_update_time=now,
        ),
    )
    print(f"Republished entity {ENTITY_ID}")


def resolve_tracked_tasks(client, task_ids):
    author = Principal(system=System(entity_id=ENTITY_ID))
    for task_id in sorted(task_ids):
        try:
            task = client.tasks.get_task(task_id)
        except ApiError as error:
            if error.status_code != 404:
                raise
            # The task no longer exists in Lattice, so there's nothing to resolve.
            untrack_task(task_ids, task_id)
            continue
        if not task.status or not task.version or task.version.status_version is None:
            print(f"Task {task_id} is missing its status or version. Skipping.")
            continue

        if task.status.status in TERMINAL_STATUSES:
            # An operator or another system closed the task while the agent was offline.
            untrack_task(task_ids, task_id)
            continue

        pending_cancel = task.delivery_state and task.delivery_state.status == "DELIVERY_STATUS_PENDING_CANCEL"
        if task.status.status == "STATUS_CANCEL_REQUESTED" or pending_cancel:
            # An operator cancelled the task while the agent was offline. Lattice records the cancel
            # in delivery_state, not in the task status. Accept the cancellation.
            error = TaskError(code="ERROR_CODE_CANCELLED", message="Cancelled while the agent was offline.")
        else:
            # The agent lost its execution context, so report the task as failed rather than
            # leave it active with nothing working on it.
            error = TaskError(code="ERROR_CODE_FAILED", message="Agent restarted and could not resume the task.")

        # Read status_version from GetTask, not from local state: the status might have
        # changed while the agent was offline, and Lattice ignores updates with a stale version.
        client.tasks.update_task_status(
            task_id,
            status_version=task.version.status_version + 1,
            new_status=TaskStatus(status="STATUS_DONE_NOT_OK", task_error=error),
            author=author,
        )
        print(f"Closed task {task_id} with {error.code}")
        untrack_task(task_ids, task_id)


def main():
    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)

    client = Lattice(
        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}"},
    )

    task_ids = load_task_ids()
    try:
        reconnect_video(client)
        publish_entity(client)
        resolve_tracked_tasks(client, task_ids)
    except Exception as error:
        print(f"Failed to recover after restart: {error}", file=sys.stderr)
        sys.exit(1)

    # Recovery is complete. Start your regular publish loop and agent stream here, and call
    # track_task and untrack_task as tasks start and finish.


if __name__ == "__main__":
    main()

```

```ts title={"TypeScript (REST)"} startLine={36} maxLines={13}
// This TypeScript example uses the Lattice REST SDK (@anduril-industries/lattice-sdk) to recover an
// integration's video stream, entity, and tasks after the integration restarts.

import * as fs from "node:fs";
import * as path from "node:path";
import { Lattice, LatticeClient, LatticeError } from "@anduril-industries/lattice-sdk";
import { v5 as uuidv5 } from "uuid";

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
const INGRESS_ID = `${ASSET_NAME}.cam`;
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
const ENTITY_ID = uuidv5(`urn:my-integration:${ASSET_NAME}`, uuidv5.URL);
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE = "agent_state.json";

const TERMINAL_STATUSES = new Set<string | undefined>(["STATUS_DONE_OK", "STATUS_DONE_NOT_OK"]);

function loadTaskIds(): Set<string> {
    try {
        return new Set<string>(JSON.parse(fs.readFileSync(STATE_FILE, "utf8")).task_ids);
    } catch (error) {
        if ((error as NodeJS.ErrnoException).code === "ENOENT") {
            return new Set<string>();
        }
        throw error;
    }
}

function saveTaskIds(taskIds: Set<string>) {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    const tempFile = path.join(path.dirname(path.resolve(STATE_FILE)), `.${path.basename(STATE_FILE)}.${process.pid}.tmp`);
    const fd = fs.openSync(tempFile, "w");
    try {
        fs.writeSync(fd, JSON.stringify({ task_ids: [...taskIds].sort() }));
        fs.fsyncSync(fd);
    } finally {
        fs.closeSync(fd);
    }
    fs.renameSync(tempFile, STATE_FILE);
}

export function trackTask(taskIds: Set<string>, taskId: string) {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    taskIds.add(taskId);
    saveTaskIds(taskIds);
}

export function untrackTask(taskIds: Set<string>, taskId: string) {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    taskIds.delete(taskId);
    saveTaskIds(taskIds);
}

async function reconnectVideo(client: LatticeClient) {
    try {
        const { ingressStream } = await client.video.getIngressStream({ ingressId: INGRESS_ID });
        // The stream survived the restart. Reuse it instead of creating a duplicate.
        console.log(`Reusing stream ${INGRESS_ID} with status ${ingressStream?.status}`);
        return;
    } catch (error) {
        if (!(error instanceof LatticeError && error.statusCode === 404)) {
            throw error;
        }
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    await client.video.createIngressStream({
        ingressId: INGRESS_ID,
        title: ASSET_NAME,
        rtsp: { url: RTSP_URL },
    });
    console.log(`Created stream ${INGRESS_ID}`);
}

async function publishEntity(client: LatticeClient) {
    const now = new Date();
    await client.entities.publishEntity({
        entityId: ENTITY_ID,
        isLive: true,
        expiryTime: new Date(now.getTime() + 5 * 60 * 1000).toISOString(),
        aliases: { name: ASSET_NAME },
        milView: { disposition: "DISPOSITION_FRIENDLY", environment: "ENVIRONMENT_LAND" },
        ontology: { template: "TEMPLATE_ASSET", platformType: "CAMERA" },
        location: { position: { latitudeDegrees: 33.6411, longitudeDegrees: -117.9187 } },
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: { media: [{ itemIdentifier: INGRESS_ID, type: "MEDIA_TYPE_VIDEO" }] },
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: {
            integrationName: "my-integration",
            dataType: "asset",
            sourceUpdateTime: now.toISOString(),
        },
    });
    console.log(`Republished entity ${ENTITY_ID}`);
}

async function resolveTrackedTasks(client: LatticeClient, taskIds: Set<string>) {
    const author = { system: { entityId: ENTITY_ID } };
    for (const taskId of [...taskIds].sort()) {
        let task: Lattice.Task;
        try {
            task = await client.tasks.getTask({ taskId });
        } catch (error) {
            if (!(error instanceof LatticeError && error.statusCode === 404)) {
                throw error;
            }
            // The task no longer exists in Lattice, so there's nothing to resolve.
            untrackTask(taskIds, taskId);
            continue;
        }
        const statusVersion = task.version?.statusVersion;
        if (!task.status || statusVersion === undefined) {
            console.log(`Task ${taskId} is missing its status or version. Skipping.`);
            continue;
        }

        if (TERMINAL_STATUSES.has(task.status.status)) {
            // An operator or another system closed the task while the agent was offline.
            untrackTask(taskIds, taskId);
            continue;
        }

        let taskError: Lattice.TaskError;
        const pendingCancel = task.deliveryState?.status === "DELIVERY_STATUS_PENDING_CANCEL";
        if (task.status.status === "STATUS_CANCEL_REQUESTED" || pendingCancel) {
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in deliveryState, not in the task status. Accept the cancellation.
            taskError = { code: "ERROR_CODE_CANCELLED", message: "Cancelled while the agent was offline." };
        } else {
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            taskError = { code: "ERROR_CODE_FAILED", message: "Agent restarted and could not resume the task." };
        }

        // Read statusVersion from getTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        await client.tasks.updateTaskStatus({
            taskId,
            statusVersion: statusVersion + 1,
            newStatus: { status: "STATUS_DONE_NOT_OK", taskError },
            author,
        });
        console.log(`Closed task ${taskId} with ${taskError.code}`);
        untrackTask(taskIds, taskId);
    }
}

async function App() {
    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,
            // Remove the following if you are not developing on Sandboxes.
            headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}`  }
        }
    );

    const taskIds = loadTaskIds();
    try {
        await reconnectVideo(client);
        await publishEntity(client);
        await resolveTrackedTasks(client, taskIds);
    } catch (error) {
        console.error(`Failed to recover after restart: ${error}`);
        process.exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // trackTask and untrackTask as tasks start and finish.
}

App();

```

```rs title={"Rust (REST)"} startLine={44} maxLines={9}
// This Rust example uses the Lattice REST SDK (anduril-lattice-sdk) to recover an integration's
// video stream, entity, and tasks after the integration restarts.

// track_task is called from the main loop you add after recovery.
#![allow(dead_code)]

use anduril_lattice_sdk::prelude::*;

use std::collections::BTreeSet;
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::sync::LazyLock;
use uuid::Uuid;

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME: &str = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
static INGRESS_ID: LazyLock<String> = LazyLock::new(|| format!("{}.cam", ASSET_NAME));
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
static ENTITY_ID: LazyLock<String> = LazyLock::new(|| {
    let name = format!("urn:my-integration:{}", ASSET_NAME);
    Uuid::new_v5(&Uuid::NAMESPACE_URL, name.as_bytes()).to_string()
});
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL: &str = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE: &str = "agent_state.json";

fn load_task_ids() -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
    let contents = match fs::read_to_string(STATE_FILE) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(error.into()),
    };
    let state: Value = contents.parse()?;
    let task_ids = state["task_ids"].as_array().ok_or("task_ids is missing")?;
    Ok(task_ids.iter().filter_map(|id| id.as_str().map(String::from)).collect())
}

fn save_task_ids(task_ids: &BTreeSet<String>) -> std::io::Result<()> {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    let temp_path = format!("{}.tmp", STATE_FILE);
    let mut file = File::create(&temp_path)?;
    file.write_all(json!({ "task_ids": task_ids }).to_string().as_bytes())?;
    file.sync_all()?;
    fs::rename(&temp_path, STATE_FILE)
}

fn track_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.insert(task_id.to_string());
    save_task_ids(task_ids)
}

fn untrack_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.remove(task_id);
    save_task_ids(task_ids)
}

async fn reconnect_video(client: &Lattice) -> Result<(), ApiError> {
    match client.video.get_ingress_stream(&INGRESS_ID, None).await {
        Ok(response) => {
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            let status = response
                .ingress_stream
                .and_then(|stream| stream.status)
                .map(|status| status.to_string())
                .unwrap_or_default();
            println!("Reusing stream {} with status {}", *INGRESS_ID, status);
            return Ok(());
        }
        Err(ApiError::NotFoundError { .. }) => {}
        Err(error) => return Err(error),
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    let request = CreateIngressStreamRequest {
        ingress_id: Some(INGRESS_ID.clone()),
        title: Some(ASSET_NAME.to_string()),
        rtsp: Some(RtspSettings {
            url: Some(RTSP_URL.to_string()),
            ..Default::default()
        }),
        ..Default::default()
    };
    client.video.create_ingress_stream(&request, None).await?;
    println!("Created stream {}", *INGRESS_ID);
    Ok(())
}

async fn publish_entity(client: &Lattice) -> Result<(), ApiError> {
    let now = Utc::now();
    let entity = Entity {
        entity_id: Some(ENTITY_ID.clone()),
        is_live: Some(true),
        expiry_time: Some((now + chrono::Duration::minutes(5)).fixed_offset()),
        aliases: Some(Aliases {
            name: Some(ASSET_NAME.to_string()),
            ..Default::default()
        }),
        mil_view: Some(MilView {
            disposition: Some(MilViewDisposition::DispositionFriendly),
            environment: Some(MilViewEnvironment::EnvironmentLand),
            ..Default::default()
        }),
        ontology: Some(Ontology {
            template: Some(OntologyTemplate::TemplateAsset),
            platform_type: Some("CAMERA".to_string()),
            ..Default::default()
        }),
        location: Some(Location {
            position: Some(Position {
                latitude_degrees: Some(33.6411),
                longitude_degrees: Some(-117.9187),
                ..Default::default()
            }),
            ..Default::default()
        }),
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: Some(Media {
            media: Some(vec![MediaItem {
                item_identifier: Some(INGRESS_ID.clone()),
                r#type: Some(MediaItemType::MediaTypeVideo),
                ..Default::default()
            }]),
            ..Default::default()
        }),
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: Some(Provenance {
            integration_name: Some("my-integration".to_string()),
            data_type: Some("asset".to_string()),
            source_update_time: Some(now.fixed_offset()),
            ..Default::default()
        }),
        ..Default::default()
    };
    client.entities.publish_entity(&entity, None).await?;
    println!("Republished entity {}", *ENTITY_ID);
    Ok(())
}

async fn resolve_tracked_tasks(
    client: &Lattice,
    task_ids: &mut BTreeSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let author = Principal {
        system: Some(System {
            entity_id: Some(ENTITY_ID.clone()),
            ..Default::default()
        }),
        ..Default::default()
    };
    for task_id in task_ids.clone() {
        let task = match client.tasks.get_task(&task_id, None).await {
            Ok(task) => task,
            Err(ApiError::NotFoundError { .. }) => {
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            Err(error) => return Err(error.into()),
        };
        let (Some(status), Some(status_version)) = (
            task.status.as_ref(),
            task.version.as_ref().and_then(|version| version.status_version),
        ) else {
            println!("Task {} is missing its status or version. Skipping.", task_id);
            continue;
        };

        let cancelled = matches!(status.status, Some(TaskStatusStatus::StatusCancelRequested))
            || matches!(
                task.delivery_state.as_ref().and_then(|state| state.status.as_ref()),
                Some(DeliveryStateStatus::DeliveryStatusPendingCancel)
            );
        let error = match status.status {
            Some(TaskStatusStatus::StatusDoneOk | TaskStatusStatus::StatusDoneNotOk) => {
                // An operator or another system closed the task while the agent was offline.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in delivery_state, not in the task status. Accept the cancellation.
            _ if cancelled => TaskError {
                code: Some(TaskErrorCode::ErrorCodeCancelled),
                message: Some("Cancelled while the agent was offline.".to_string()),
                ..Default::default()
            },
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            _ => TaskError {
                code: Some(TaskErrorCode::ErrorCodeFailed),
                message: Some("Agent restarted and could not resume the task.".to_string()),
                ..Default::default()
            },
        };
        let code = error.code.as_ref().map(|code| code.to_string()).unwrap_or_default();

        // Read status_version from GetTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        let request = TaskStatusUpdate {
            status_version: Some(status_version + 1),
            new_status: Some(TaskStatus {
                status: Some(TaskStatusStatus::StatusDoneNotOk),
                task_error: Some(error),
                ..Default::default()
            }),
            author: Some(author.clone()),
        };
        client.tasks.update_task_status(&task_id, &request, None).await?;
        println!("Closed task {} with {}", task_id, code);
        untrack_task(task_ids, &task_id)?;
    }
    Ok(())
}

#[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)?;

    let mut task_ids = load_task_ids()?;
    let result: Result<(), Box<dyn std::error::Error>> = async {
        reconnect_video(&client).await?;
        publish_entity(&client).await?;
        resolve_tracked_tasks(&client, &mut task_ids).await?;
        Ok(())
    }
    .await;
    if let Err(error) = result {
        eprintln!("Failed to recover after restart: {}", error);
        std::process::exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // track_task and untrack_task as tasks start and finish.
    Ok(())
}

```

```go title={"Go (gRPC)"} startLine={83} 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
//
// It recovers an integration's video stream, entity, and tasks after the integration restarts.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"maps"
	"os"
	"path/filepath"
	"slices"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/taskmanager/v1/taskmanagerv1grpc"
	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/videomanager/v1/videomanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	ontologyv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/ontology/v1"
	taskmanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/taskmanager/v1"
	videomanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/videomanager/v1"

	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"

// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"

// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()

const (
	// RTSP source that Lattice pulls video from. Replace before running.
	rtspURL = "rtsp://<rtsp-host>:<port>/cam"
	// Local file that stores the IDs of tasks this agent is executing.
	stateFile = "agent_state.json"
)

var terminalStatuses = map[taskmanagerv1.Status]bool{
	taskmanagerv1.Status_STATUS_DONE_OK:     true,
	taskmanagerv1.Status_STATUS_DONE_NOT_OK: true,
}

type agentState struct {
	TaskIDs []string `json:"task_ids"`
}

func loadTaskIDs() (map[string]bool, error) {
	taskIDs := map[string]bool{}
	data, err := os.ReadFile(stateFile)
	if errors.Is(err, os.ErrNotExist) {
		return taskIDs, nil
	}
	if err != nil {
		return nil, err
	}
	var state agentState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	for _, taskID := range state.TaskIDs {
		taskIDs[taskID] = true
	}
	return taskIDs, nil
}

func saveTaskIDs(taskIDs map[string]bool) error {
	ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
	slices.Sort(ids)
	data, err := json.Marshal(agentState{TaskIDs: ids})
	if err != nil {
		return err
	}
	// Write to a temporary file, then rename it over the original. A power loss during the
	// write leaves the previous file intact instead of a truncated one.
	f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	if _, err := f.Write(data); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), stateFile)
}

// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
	taskIDs[taskID] = true
	return saveTaskIDs(taskIDs)
}

// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
	delete(taskIDs, taskID)
	return saveTaskIDs(taskIDs)
}

func reconnectVideo(ctx context.Context, client videomanagerv1grpc.VideoManagerAPIClient) error {
	response, err := client.GetIngressStream(ctx, &videomanagerv1.GetIngressStreamRequest{
		IngressId: ingressID,
	})
	if err == nil {
		// The stream survived the restart. Reuse it instead of creating a duplicate.
		fmt.Printf("Reusing stream %s with status %s\n", ingressID, response.GetIngressStream().GetStatus())
		return nil
	}
	if status.Code(err) != codes.NotFound {
		return err
	}

	// Lattice returns not found both for a stream that never existed and for one that was deleted.
	_, err = client.CreateIngressStream(ctx, &videomanagerv1.CreateIngressStreamRequest{
		IngressId: proto.String(ingressID),
		Title:     assetName,
		Ingress: &videomanagerv1.CreateIngressStreamRequest_Rtsp{
			Rtsp: &videomanagerv1.RtspSettings{
				Url: proto.String(rtspURL),
			},
		},
	})
	if err != nil {
		return err
	}
	fmt.Printf("Created stream %s\n", ingressID)
	return nil
}

func publishEntity(ctx context.Context, client entitymanagerv1grpc.EntityManagerAPIClient) error {
	now := time.Now().UTC()
	_, err := client.PublishEntity(ctx, &entitymanagerv1.PublishEntityRequest{Entity: &entitymanagerv1.Entity{
		EntityId:   entityID,
		IsLive:     true,
		ExpiryTime: timestamppb.New(now.Add(5 * time.Minute)),
		Aliases:    &entitymanagerv1.Aliases{Name: assetName},
		MilView: &entitymanagerv1.MilView{
			Disposition: ontologyv1.Disposition_DISPOSITION_FRIENDLY,
			Environment: ontologyv1.Environment_ENVIRONMENT_LAND,
		},
		Ontology: &entitymanagerv1.Ontology{
			Template:     entitymanagerv1.Template_TEMPLATE_ASSET,
			PlatformType: "CAMERA",
		},
		Location: &entitymanagerv1.Location{
			Position: &entitymanagerv1.Position{
				LatitudeDegrees:  33.6411,
				LongitudeDegrees: -117.9187,
			},
		},
		// Because ingressID never changes, the entity can reference the stream on every publish.
		Media: &entitymanagerv1.Media{Media: []*entitymanagerv1.MediaItem{{
			ItemIdentifier: ingressID,
			Type:           entitymanagerv1.MediaType_MEDIA_TYPE_VIDEO,
		}}},
		// Include every other component your integration publishes, such as its TaskCatalog.
		Provenance: &entitymanagerv1.Provenance{
			IntegrationName:  "my-integration",
			DataType:         "asset",
			SourceUpdateTime: timestamppb.New(now),
		},
	}})
	if err != nil {
		return err
	}
	fmt.Printf("Republished entity %s\n", entityID)
	return nil
}

func resolveTrackedTasks(ctx context.Context, client taskmanagerv1grpc.TaskManagerAPIClient, taskIDs map[string]bool) error {
	author := &taskmanagerv1.Principal{
		Agent: &taskmanagerv1.Principal_System{
			System: &taskmanagerv1.System{EntityId: entityID},
		},
	}
	for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
		response, err := client.GetTask(ctx, &taskmanagerv1.GetTaskRequest{TaskId: taskID})
		if status.Code(err) == codes.NotFound {
			// The task no longer exists in Lattice, so there's nothing to resolve.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
		task := response.GetTask()
		if task.GetStatus() == nil || task.GetVersion() == nil {
			fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
			continue
		}

		taskStatus := task.GetStatus().GetStatus()
		if terminalStatuses[taskStatus] {
			// An operator or another system closed the task while the agent was offline.
			if err := untrackTask(taskIDs, taskID); err != nil {
				return err
			}
			continue
		}

		var taskError *taskmanagerv1.TaskError
		cancelled := taskStatus == taskmanagerv1.Status_STATUS_CANCEL_REQUESTED ||
			task.GetDeliveryState().GetStatus() == taskmanagerv1.DeliveryStatus_DELIVERY_STATUS_PENDING_CANCEL
		if cancelled {
			// An operator cancelled the task while the agent was offline. Lattice records the cancel
			// in delivery_state, not in the task status. Accept the cancellation.
			taskError = &taskmanagerv1.TaskError{
				Code:    taskmanagerv1.ErrorCode_ERROR_CODE_CANCELLED,
				Message: "Cancelled while the agent was offline.",
			}
		} else {
			// The agent lost its execution context, so report the task as failed rather than
			// leave it active with nothing working on it.
			taskError = &taskmanagerv1.TaskError{
				Code:    taskmanagerv1.ErrorCode_ERROR_CODE_FAILED,
				Message: "Agent restarted and could not resume the task.",
			}
		}

		// Read the status version from GetTask, not from local state: the status might have
		// changed while the agent was offline, and Lattice ignores updates with a stale version.
		_, err = client.UpdateStatus(ctx, &taskmanagerv1.UpdateStatusRequest{
			StatusUpdate: &taskmanagerv1.StatusUpdate{
				Version: &taskmanagerv1.TaskVersion{
					TaskId:        taskID,
					StatusVersion: task.GetVersion().GetStatusVersion() + 1,
				},
				Status: &taskmanagerv1.TaskStatus{
					Status:    taskmanagerv1.Status_STATUS_DONE_NOT_OK,
					TaskError: taskError,
				},
				Author: author,
			},
		})
		if err != nil {
			return err
		}
		fmt.Printf("Closed task %s with %s\n", taskID, taskError.GetCode())
		if err := untrackTask(taskIDs, taskID); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	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()

	videoClient := videomanagerv1grpc.NewVideoManagerAPIClient(conn)
	entityClient := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)
	taskClient := taskmanagerv1grpc.NewTaskManagerAPIClient(conn)

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	taskIDs, err := loadTaskIDs()
	if err != nil {
		log.Fatalf("Failed to load saved task IDs: %v", err)
	}
	if err := reconnectVideo(ctx, videoClient); err != nil {
		log.Fatalf("Failed to reconnect video: %v", err)
	}
	if err := publishEntity(ctx, entityClient); err != nil {
		log.Fatalf("Failed to republish entity: %v", err)
	}
	if err := resolveTrackedTasks(ctx, taskClient, taskIDs); err != nil {
		log.Fatalf("Failed to resolve tracked tasks: %v", err)
	}

	// Recovery is complete. Start your regular publish loop and agent stream here, and call
	// trackTask and untrackTask as tasks start and finish.
}

```

```py title={"Python (gRPC)"} startLine={69} maxLines={9}
# 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
# It recovers an integration's video stream, entity, and tasks after the integration restarts.

import json
import os
import sys
import tempfile
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from connectrpc.code import Code
from connectrpc.errors import ConnectError
from protobuf import Oneof
from protobuf.wkt import Timestamp

from anduril.entitymanager.v1.entity_pub_pb import Aliases, Entity, Provenance
from anduril.entitymanager.v1.entity_manager_api_pub_pb import PublishEntityRequest
from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.location_pub_pb import Location, Position
from anduril.entitymanager.v1.media_pub_pb import Media, MediaItem, MediaType
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.ontology.v1.type_pub_pb import Disposition, Environment
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.taskmanager.v1.task_pub_pb import (
    DeliveryStatus,
    ErrorCode,
    Principal,
    Status,
    StatusUpdate,
    System,
    TaskError,
    TaskStatus,
    TaskVersion,
)
from anduril.taskmanager.v1.task_manager_api_pub_pb import GetTaskRequest, UpdateStatusRequest
from anduril.taskmanager.v1.task_manager_api_pub_connect import TaskManagerAPIClientSync
from anduril.videomanager.v1.create_ingress_stream_request_pub_pb import CreateIngressStreamRequest
from anduril.videomanager.v1.get_ingress_stream_request_pub_pb import GetIngressStreamRequest
from anduril.videomanager.v1.rtsp_settings_pub_pb import RtspSettings
from anduril.videomanager.v1.video_manager_api_pub_connect import VideoManagerAPIClientSync

# A name that is unique to this asset and never changes, such as a serial number read from
# hardware or configuration. Replace before running.
ASSET_NAME = "<ASSET-NAME>"
# The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
# so it's the same after every restart.
INGRESS_ID = f"{ASSET_NAME}.cam"
# The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
# and in every language.
ENTITY_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:my-integration:{ASSET_NAME}"))
# RTSP source that Lattice pulls video from. Replace before running.
RTSP_URL = "rtsp://<rtsp-host>:<port>/cam"
# Local file that stores the IDs of tasks this agent is executing.
STATE_FILE = "agent_state.json"

TERMINAL_STATUSES = {Status.DONE_OK, Status.DONE_NOT_OK}


def load_task_ids():
    try:
        with open(STATE_FILE) as f:
            return set(json.load(f)["task_ids"])
    except FileNotFoundError:
        return set()


def save_task_ids(task_ids):
    # Write to a temporary file, then rename it over the original. A power loss during the
    # write leaves the previous file intact instead of a truncated one.
    directory = os.path.dirname(os.path.abspath(STATE_FILE))
    with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f:
        json.dump({"task_ids": sorted(task_ids)}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(f.name, STATE_FILE)


def track_task(task_ids, task_id):
    # Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.add(task_id)
    save_task_ids(task_ids)


def untrack_task(task_ids, task_id):
    # Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.discard(task_id)
    save_task_ids(task_ids)


def reconnect_video(client):
    try:
        response = client.get_ingress_stream(GetIngressStreamRequest(ingress_id=INGRESS_ID), timeout_ms=10000)
        # The stream survived the restart. Reuse it instead of creating a duplicate.
        print(f"Reusing stream {INGRESS_ID} with status STREAM_STATUS_{response.ingress_stream.status.name}")
        return
    except ConnectError as error:
        if error.code != Code.NOT_FOUND:
            raise

    # Lattice returns not found both for a stream that never existed and for one that was deleted.
    client.create_ingress_stream(
        CreateIngressStreamRequest(
            ingress_id=INGRESS_ID,
            title=ASSET_NAME,
            ingress=Oneof("rtsp", RtspSettings(url=RTSP_URL)),
        ),
        timeout_ms=30000,
    )
    print(f"Created stream {INGRESS_ID}")


def publish_entity(client):
    now = datetime.now(timezone.utc)
    entity = Entity(
        entity_id=ENTITY_ID,
        is_live=True,
        expiry_time=Timestamp.from_datetime(now + timedelta(minutes=5)),
        aliases=Aliases(name=ASSET_NAME),
        mil_view=MilView(disposition=Disposition.FRIENDLY, environment=Environment.LAND),
        ontology=Ontology(template=Template.ASSET, platform_type="CAMERA"),
        location=Location(position=Position(latitude_degrees=33.6411, longitude_degrees=-117.9187)),
        # Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media=Media(media=[MediaItem(item_identifier=INGRESS_ID, type=MediaType.VIDEO)]),
        # Include every other component your integration publishes, such as its TaskCatalog.
        provenance=Provenance(
            integration_name="my-integration",
            data_type="asset",
            source_update_time=Timestamp.from_datetime(now),
        ),
    )
    client.publish_entity(PublishEntityRequest(entity=entity), timeout_ms=10000)
    print(f"Republished entity {ENTITY_ID}")


def resolve_tracked_tasks(client, task_ids):
    author = Principal(agent=Oneof("system", System(entity_id=ENTITY_ID)))
    for task_id in sorted(task_ids):
        try:
            task = client.get_task(GetTaskRequest(task_id=task_id), timeout_ms=10000).task
        except ConnectError as error:
            if error.code != Code.NOT_FOUND:
                raise
            # The task no longer exists in Lattice, so there's nothing to resolve.
            untrack_task(task_ids, task_id)
            continue
        if not task or not task.status or not task.version:
            print(f"Task {task_id} is missing its status or version. Skipping.")
            continue

        if task.status.status in TERMINAL_STATUSES:
            # An operator or another system closed the task while the agent was offline.
            untrack_task(task_ids, task_id)
            continue

        pending_cancel = task.delivery_state and task.delivery_state.status == DeliveryStatus.PENDING_CANCEL
        if task.status.status == Status.CANCEL_REQUESTED or pending_cancel:
            # An operator cancelled the task while the agent was offline. Lattice records the cancel
            # in delivery_state, not in the task status. Accept the cancellation.
            error = TaskError(code=ErrorCode.CANCELLED, message="Cancelled while the agent was offline.")
        else:
            # The agent lost its execution context, so report the task as failed rather than
            # leave it active with nothing working on it.
            error = TaskError(code=ErrorCode.FAILED, message="Agent restarted and could not resume the task.")

        # Read status_version from GetTask, not from local state: the status might have
        # changed while the agent was offline, and Lattice ignores updates with a stale version.
        status_update = StatusUpdate(
            version=TaskVersion(task_id=task_id, status_version=task.version.status_version + 1),
            status=TaskStatus(status=Status.DONE_NOT_OK, task_error=error),
            author=author,
        )
        client.update_status(UpdateStatusRequest(status_update=status_update), timeout_ms=10000)
        print(f"Closed task {task_id} with ERROR_CODE_{error.code.name}")
        untrack_task(task_ids, task_id)


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 clients over Connect gRPC with authentication
    video_client = create_client(VideoManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)
    entity_client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)
    task_client = create_client(TaskManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    task_ids = load_task_ids()
    try:
        reconnect_video(video_client)
        publish_entity(entity_client)
        resolve_tracked_tasks(task_client, task_ids)
    except Exception as error:
        print(f"Failed to recover after restart: {error}", file=sys.stderr)
        sys.exit(1)

    # Recovery is complete. Start your regular publish loop and agent stream here, and call
    # track_task and untrack_task as tasks start and finish.


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={82} maxLines={9}
// 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

// track_task is called from the main loop you add after recovery.
#![allow(dead_code)]

mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    Aliases, Entity, Location, Media, MediaItem, MediaType, MilView, Ontology, Position, Provenance,
    PublishEntityRequest, Template,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{Disposition, Environment};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::taskmanager::v1::{
    principal, DeliveryStatus, ErrorCode, GetTaskRequest, Principal, Status, StatusUpdate, System, TaskError,
    TaskStatus, TaskVersion, UpdateStatusRequest,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::videomanager::v1::{
    create_ingress_stream_request::Ingress, CreateIngressStreamRequest, GetIngressStreamRequest,
    RtspSettings,
};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::taskmanager::v1::tonic::task_manager_api_client::TaskManagerApiClient;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::videomanager::v1::tonic::video_manager_api_client::VideoManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use prost_types::Timestamp;
use serde_json::{json, Value};
use tonic::metadata::{Ascii, MetadataValue};
use tonic::service::interceptor::InterceptedService;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::{Code, Request};
use uuid::Uuid;

use std::collections::BTreeSet;
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::sync::LazyLock;
use std::time::{SystemTime, UNIX_EPOCH};

// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const ASSET_NAME: &str = "<ASSET-NAME>";
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
static INGRESS_ID: LazyLock<String> = LazyLock::new(|| format!("{}.cam", ASSET_NAME));
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
static ENTITY_ID: LazyLock<String> = LazyLock::new(|| {
    let name = format!("urn:my-integration:{}", ASSET_NAME);
    Uuid::new_v5(&Uuid::NAMESPACE_URL, name.as_bytes()).to_string()
});
// RTSP source that Lattice pulls video from. Replace before running.
const RTSP_URL: &str = "rtsp://<rtsp-host>:<port>/cam";
// Local file that stores the IDs of tasks this agent is executing.
const STATE_FILE: &str = "agent_state.json";

type Interceptor = Box<dyn FnMut(Request<()>) -> Result<Request<()>, tonic::Status> + Send + Sync>;
type VideoClient = VideoManagerApiClient<InterceptedService<Channel, Interceptor>>;
type EntityClient = EntityManagerApiClient<InterceptedService<Channel, Interceptor>>;
type TaskClient = TaskManagerApiClient<InterceptedService<Channel, Interceptor>>;

fn now_timestamp() -> Timestamp {
    let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    Timestamp {
        seconds: d.as_secs() as i64,
        nanos: d.subsec_nanos() as i32,
    }
}

fn load_task_ids() -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
    let contents = match fs::read_to_string(STATE_FILE) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(error.into()),
    };
    let state: Value = contents.parse()?;
    let task_ids = state["task_ids"].as_array().ok_or("task_ids is missing")?;
    Ok(task_ids.iter().filter_map(|id| id.as_str().map(String::from)).collect())
}

fn save_task_ids(task_ids: &BTreeSet<String>) -> std::io::Result<()> {
    // Write to a temporary file, then rename it over the original. A power loss during the
    // write leaves the previous file intact instead of a truncated one.
    let temp_path = format!("{}.tmp", STATE_FILE);
    let mut file = File::create(&temp_path)?;
    file.write_all(json!({ "task_ids": task_ids }).to_string().as_bytes())?;
    file.sync_all()?;
    fs::rename(&temp_path, STATE_FILE)
}

fn track_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call before reporting STATUS_EXECUTING, so the ID is on disk before work starts.
    task_ids.insert(task_id.to_string());
    save_task_ids(task_ids)
}

fn untrack_task(task_ids: &mut BTreeSet<String>, task_id: &str) -> std::io::Result<()> {
    // Call after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
    task_ids.remove(task_id);
    save_task_ids(task_ids)
}

async fn reconnect_video(client: &mut VideoClient) -> Result<(), tonic::Status> {
    let request = Request::new(GetIngressStreamRequest {
        ingress_id: INGRESS_ID.clone(),
    });
    match client.get_ingress_stream(request).await {
        Ok(response) => {
            // The stream survived the restart. Reuse it instead of creating a duplicate.
            let status = response
                .into_inner()
                .ingress_stream
                .map(|stream| stream.status().as_str_name())
                .unwrap_or_default();
            println!("Reusing stream {} with status {}", *INGRESS_ID, status);
            return Ok(());
        }
        Err(status) if status.code() == Code::NotFound => {}
        Err(status) => return Err(status),
    }

    // Lattice returns not found both for a stream that never existed and for one that was deleted.
    let request = Request::new(CreateIngressStreamRequest {
        ingress_id: Some(INGRESS_ID.clone()),
        title: ASSET_NAME.to_string(),
        ingress: Some(Ingress::Rtsp(RtspSettings {
            url: Some(RTSP_URL.to_string()),
        })),
    });
    client.create_ingress_stream(request).await?;
    println!("Created stream {}", *INGRESS_ID);
    Ok(())
}

async fn publish_entity(client: &mut EntityClient) -> Result<(), tonic::Status> {
    let now = now_timestamp();
    let entity = Entity {
        entity_id: ENTITY_ID.clone(),
        is_live: true,
        expiry_time: Some(Timestamp {
            seconds: now.seconds + 5 * 60,
            nanos: now.nanos,
        }),
        aliases: Some(Aliases {
            name: ASSET_NAME.to_string(),
            ..Default::default()
        }),
        mil_view: Some(MilView {
            disposition: Disposition::Friendly as i32,
            environment: Environment::Land as i32,
            ..Default::default()
        }),
        ontology: Some(Ontology {
            template: Template::Asset as i32,
            platform_type: "CAMERA".to_string(),
            ..Default::default()
        }),
        location: Some(Location {
            position: Some(Position {
                latitude_degrees: 33.6411,
                longitude_degrees: -117.9187,
                ..Default::default()
            }),
            ..Default::default()
        }),
        // Because INGRESS_ID never changes, the entity can reference the stream on every publish.
        media: Some(Media {
            media: vec![MediaItem {
                item_identifier: INGRESS_ID.clone(),
                r#type: MediaType::Video as i32,
                ..Default::default()
            }],
        }),
        // Include every other component your integration publishes, such as its TaskCatalog.
        provenance: Some(Provenance {
            integration_name: "my-integration".to_string(),
            data_type: "asset".to_string(),
            source_update_time: Some(now),
            ..Default::default()
        }),
        ..Default::default()
    };
    client
        .publish_entity(Request::new(PublishEntityRequest {
            entity: Some(entity),
        }))
        .await?;
    println!("Republished entity {}", *ENTITY_ID);
    Ok(())
}

async fn resolve_tracked_tasks(
    client: &mut TaskClient,
    task_ids: &mut BTreeSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let author = Principal {
        agent: Some(principal::Agent::System(System {
            entity_id: ENTITY_ID.clone(),
            ..Default::default()
        })),
        ..Default::default()
    };
    for task_id in task_ids.clone() {
        let request = Request::new(GetTaskRequest {
            task_id: task_id.clone(),
            ..Default::default()
        });
        let task = match client.get_task(request).await {
            Ok(response) => response.into_inner().task,
            Err(status) if status.code() == Code::NotFound => {
                // The task no longer exists in Lattice, so there's nothing to resolve.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            Err(status) => return Err(status.into()),
        };
        let Some((status, version)) = task.as_ref().and_then(|task| task.status.as_ref().zip(task.version.as_ref()))
        else {
            println!("Task {} is missing its status or version. Skipping.", task_id);
            continue;
        };

        let cancelled = status.status() == Status::CancelRequested
            || task.as_ref().and_then(|task| task.delivery_state.as_ref()).map(|state| state.status())
                == Some(DeliveryStatus::PendingCancel);
        let error = match status.status() {
            Status::DoneOk | Status::DoneNotOk => {
                // An operator or another system closed the task while the agent was offline.
                untrack_task(task_ids, &task_id)?;
                continue;
            }
            // An operator cancelled the task while the agent was offline. Lattice records the cancel
            // in delivery_state, not in the task status. Accept the cancellation.
            _ if cancelled => TaskError {
                code: ErrorCode::Cancelled as i32,
                message: "Cancelled while the agent was offline.".to_string(),
                ..Default::default()
            },
            // The agent lost its execution context, so report the task as failed rather than
            // leave it active with nothing working on it.
            _ => TaskError {
                code: ErrorCode::Failed as i32,
                message: "Agent restarted and could not resume the task.".to_string(),
                ..Default::default()
            },
        };
        let code = error.code().as_str_name();

        // Read status_version from GetTask, not from local state: the status might have
        // changed while the agent was offline, and Lattice ignores updates with a stale version.
        let status_update = StatusUpdate {
            version: Some(TaskVersion {
                task_id: task_id.clone(),
                status_version: version.status_version + 1,
                ..Default::default()
            }),
            status: Some(TaskStatus {
                status: Status::DoneNotOk as i32,
                task_error: Some(error),
                ..Default::default()
            }),
            author: Some(author.clone()),
            ..Default::default()
        };
        client
            .update_status(Request::new(UpdateStatusRequest {
                status_update: Some(status_update),
            }))
            .await?;
        println!("Closed task {} with {}", task_id, code);
        untrack_task(task_ids, &task_id)?;
    }
    Ok(())
}

fn auth_interceptor(
    auth_header: MetadataValue<Ascii>,
    sandbox_header: MetadataValue<Ascii>,
) -> Interceptor {
    Box::new(move |mut req: Request<()>| {
        req.metadata_mut()
            .insert("authorization", auth_header.clone());
        req.metadata_mut()
            .insert("anduril-sandbox-authorization", sandbox_header.clone());
        Ok(req)
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    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");
    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables");
        std::process::exit(1);
    }

    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

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

    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<Ascii> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<Ascii> = format!("Bearer {}", sandboxes_token).parse()?;

    // All three clients share the same channel and inject the same auth metadata.
    let mut video_client: VideoClient = VideoManagerApiClient::with_interceptor(
        channel.clone(),
        auth_interceptor(auth_header.clone(), sandbox_header.clone()),
    );
    let mut entity_client: EntityClient = EntityManagerApiClient::with_interceptor(
        channel.clone(),
        auth_interceptor(auth_header.clone(), sandbox_header.clone()),
    );
    let mut task_client: TaskClient = TaskManagerApiClient::with_interceptor(
        channel,
        auth_interceptor(auth_header, sandbox_header),
    );

    let mut task_ids = load_task_ids()?;
    let result: Result<(), Box<dyn std::error::Error>> = async {
        reconnect_video(&mut video_client).await?;
        publish_entity(&mut entity_client).await?;
        resolve_tracked_tasks(&mut task_client, &mut task_ids).await?;
        Ok(())
    }
    .await;
    if let Err(error) = result {
        eprintln!("Failed to recover after restart: {}", error);
        std::process::exit(1);
    }

    // Recovery is complete. Start your regular publish loop and agent stream here, and call
    // track_task and untrack_task as tasks start and finish.
    Ok(())
}

```

## Find tasks your agent never received

Lattice counts a task as delivered as soon as it sends the task over your agent's stream, before your agent confirms it.
If your integration crashes at that moment, your agent has no record of the task.

After you reconnect, look up the open tasks assigned to your agent, and treat any you don't recognize as new:

* **gRPC**: Call `QueryTasks` with `assignee` set to your agent's entity and a `status_filter` that excludes `STATUS_DONE_OK` and `STATUS_DONE_NOT_OK`.
* **REST**: The REST `QueryTasks` can't filter by assignee, so call `StreamTasks` with `assignee` set to your agent's entity. When it connects, it first replays matching tasks, including ones that finished in the last hour, then sends live updates. Skip the finished ones.

If you create tasks for agents that restart often, set `delivery_constraints.require_acknowledgement` when you call `CreateTask`.
Lattice then re-sends the task until the agent confirms receipt, up to the `deliver_before` deadline that this option requires.

## Recover after a lost connection

A network outage affects tasks the same way a restart does, even though your integration keeps running.
While your agent is disconnected, operators can cancel or close its tasks and Lattice can send it new ones, and Lattice doesn't re-send what your agent missed.

Each time your agent stream reconnects:

1. Call `GetTask` for each task your agent is working on. Stop work on any task that's closed, not found, or has a pending cancellation, and handle it as in [Recover on startup](#recover-on-startup). Keep working on the rest. If one finished while you were disconnected, report it with the `status_version` from `GetTask`.
2. [Find tasks your agent never received](#find-tasks-your-agent-never-received).

Keep your publish loop running through the outage, with retries. If the outage outlasts your entity's `expiry_time`, the entity disappears until your next successful publish.
For SRT and MPEG-TS video, resume pushing to the stream's `url` when the link returns.

## Recover tasks you created

If your integration assigns tasks to other agents, save the ID of each one.
On startup, call `GetTask` for each saved ID to catch up and remove the finished ones, then call `StreamTasks` to follow the rest.
Cancel any task whose result your integration can no longer use, so it doesn't run unmonitored.

## What's next

* Review [Retry connections](/guides/best-practices/retry-connections) to handle transient errors during recovery.
* See [Integrate an agent](/guides/tasks/integrate-an-agent) for the full agent workflow, including cancellation.
* Read [Manage streams](/guides/video/manage-streams) to list and re-egress video streams.
* Learn how [entity expiry and republishing](/guides/entities/overview#entity-lifecycle) work.