# PlayDrop server SDK declarations

Generated from `@playdrop/server` (`packages/game-server/src`) and the types it references; do not edit by hand. Guides: https://www.playdrop.ai/create/learn/server-sdk. Types from `@playdrop/types` that these declarations use are in the shared types (get_documentation topic `shared-types`, https://www.playdrop.ai/docs-markdown/en/shared-types.md).

## @playdrop/server

```ts
/** The `playdrop` export of @playdrop/server. */
declare const playdrop: {
  readonly ai: Readonly<{
      text: Readonly<{
          createTask: (taskRequest: PlayDropAiTaskRequest<"TEXT">, options?: PlayDropCreateAiTaskOptions) => Promise<AgentTaskResponseBase & {
              kind: "TEXT";
              provider: AgentTaskProvider;
              request: {
                  kind: "TEXT";
                  input: string;
                  system?: string;
                  size?: AiTextSize;
              };
              result: AgentTaskGenerationResult | null;
          }>;
      }>;
      json: Readonly<{
          createTask: (taskRequest: PlayDropAiTaskRequest<"JSON">, options?: PlayDropCreateAiTaskOptions) => Promise<AgentTaskResponseBase & {
              kind: "JSON";
              provider: AgentTaskProvider;
              request: {
                  kind: "JSON";
                  input: string;
                  system?: string;
                  size?: AiTextSize;
                  responseSchema: Record<string, unknown>;
              };
              result: AgentTaskGenerationResult | null;
          }>;
      }>;
      image: Readonly<{
          createTask: (taskRequest: PlayDropAiTaskRequest<"IMAGE">, options?: PlayDropCreateAiTaskOptions) => Promise<AgentTaskResponseBase & {
              kind: "IMAGE";
              provider: AgentTaskProvider;
              request: AiGenerationAssetFields & {
                  kind: "IMAGE";
                  input: string;
                  image1?: AiGenerationInputReference;
                  image2?: AiGenerationInputReference;
                  aspectRatio?: "1:1" | "3:4" | "9:16" | "4:3" | "16:9";
                  imageSize?: "1K" | "4K";
                  assetJob?: AssetJobRequest;
              };
              result: AgentTaskGenerationResult | null;
          }>;
      }>;
      model3d: Readonly<{
          createTask: (taskRequest: PlayDropAiTaskRequest<"MODEL_3D">, options?: PlayDropCreateAiTaskOptions) => Promise<AgentTaskResponseBase & {
              kind: "MODEL_3D";
              provider: AgentTaskProvider;
              request: AiGenerationAssetFields & AiGenerationFalOrderFields & {
                  kind: "MODEL_3D";
                  input: string;
                  image1?: AiGenerationInputReference;
                  image2?: AiGenerationInputReference;
                  targetPolycount?: number;
                  shouldTexture?: boolean;
                  outputFormat?: "GLB";
                  assetJob?: AssetJobRequest;
              };
              result: AgentTaskGenerationResult | null;
          }>;
      }>;
      video: Readonly<{
          createTask: (taskRequest: PlayDropAiTaskRequest<"VIDEO">, options?: PlayDropCreateAiTaskOptions) => Promise<AgentTaskResponseBase & {
              kind: "VIDEO";
              provider: AgentTaskProvider;
              request: AiGenerationAssetFields & AiGenerationFalOrderFields & {
                  kind: "VIDEO";
                  input: string;
                  image1?: AiGenerationInputReference;
                  image2?: AiGenerationInputReference;
                  durationSeconds?: 5 | 10;
                  aspectRatio?: "16:9" | "9:16" | "1:1";
              };
              result: AgentTaskGenerationResult | null;
          }>;
      }>;
      sfx: Readonly<{
          createTask: (taskRequest: PlayDropAiTaskRequest<"SFX">, options?: PlayDropCreateAiTaskOptions) => Promise<AgentTaskResponseBase & {
              kind: "SFX";
              provider: AgentTaskProvider;
              request: AiGenerationAssetFields & AiGenerationFalOrderFields & {
                  kind: "SFX";
                  input: string;
                  durationSeconds?: number;
                  loop?: boolean;
                  coverPrompt?: string;
              };
              result: AgentTaskGenerationResult | null;
          }>;
      }>;
      speech: Readonly<{
          createTask: (taskRequest: PlayDropAiTaskRequest<"SPEECH">, options?: PlayDropCreateAiTaskOptions) => Promise<AgentTaskResponseBase & {
              kind: "SPEECH";
              provider: AgentTaskProvider;
              request: AiGenerationAssetFields & AiGenerationFalOrderFields & {
                  kind: "SPEECH";
                  input: string;
                  speechVoice?: string;
                  speechProviderVoiceId?: string;
              };
              result: AgentTaskGenerationResult | null;
          }>;
      }>;
      music: Readonly<{
          createTask: (taskRequest: PlayDropAiTaskRequest<"MUSIC">, options?: PlayDropCreateAiTaskOptions) => Promise<AgentTaskResponseBase & {
              kind: "MUSIC";
              provider: AgentTaskProvider;
              request: AiGenerationAssetFields & AiGenerationFalOrderFields & {
                  kind: "MUSIC";
                  input: string;
                  durationMs?: number;
                  forceInstrumental?: boolean;
                  coverPrompt?: string;
              };
              result: AgentTaskGenerationResult | null;
          }>;
      }>;
      inputs: Readonly<{
          prepare(input: PrepareAiTaskInputUploadRequest, options?: PlayDropCreateAiTaskOptions): Promise<PrepareAiTaskInputUploadResponse>;
          finalize(uploadId: string, options?: PlayDropCreateAiTaskOptions): Promise<FinalizeAiTaskInputUploadResponse>;
          upload(bytes: Uint8Array, options: PlayDropUploadAiTaskInputOptions): Promise<{
              type: "TASK_UPLOAD";
              uploadId: string;
          }>;
      }>;
      tasks: Readonly<{
          downloadFile(id: number, options?: {
              role?: string;
          }): Promise<Blob>;
          get(id: number): Promise<GenerationAgentTaskResponse>;
          list(options?: {
              kind?: AgentTaskGenerationKind;
              status?: AgentTaskStatus;
              limit?: number;
              offset?: number;
          }): Promise<GenerationAgentTaskResponse[]>;
          events(id: number): Promise<AgentTaskEventResponse[]>;
          cancel(id: number): Promise<GenerationAgentTaskResponse>;
          clear(id: number): Promise<void>;
      }>;
  }>;
  readonly shop: Readonly<PlayDropShopAPI>;
  readonly social: Readonly<PlayDropSocialAPI>;
  readonly multiplayer: Readonly<{
      forRoom(room: Room): {
          voice: {
              setPolicy(value: RoomVoiceAudience, options?: {
                  range?: number;
              }): void;
              setTeam(player: PlayDropPlayer, team: string | null): void;
              setAudience(player: PlayDropPlayer, value: RoomVoiceAudience | null): void;
              updatePositions(values: Array<{
                  player: PlayDropPlayer;
                  position: Position;
              }>): void;
          };
      };
  }>;
};
```

## packages/game-server/src/player.ts

```ts
/** Opaque platform credential for asset ownership. Never construct or send it to a client. */
export type PlayDropAssetOwnerGrant = string & {
  readonly [assetOwnerGrantBrand]: true;
};

/** Opaque social credential scoped to this player, app, version, deployment, and session. */
export type PlayDropSocialGrant = string & {
  readonly [socialGrantBrand]: true;
};

/** App-scoped delayed turn/result delivery, valid for fourteen days. Never expose to clients. */
export type PlayDropDeliveryGrant = string & { readonly [deliveryGrantBrand]: true };

/** Opaque IAP credential scoped to this player, app, version, deployment, and session. */
export type PlayDropIapGrant = string & {
  readonly [iapGrantBrand]: true;
};

/** App ownership, not a game-defined team, moderator, or match role. */
export type PlayDropAppRole = "OWNER" | "PLAYER";

/**
 * Platform-verified identity supplied through Colyseus `client.auth`.
 * PlayDrop installs authentication on exported rooms; game code must not define
 * `onAuth` or accept identity or grants from game messages. Pass this exact object
 * to server social methods and to AI generation's optional `owner` argument.
 *
 * Import `Room`, `Client`, and `defineRoom` from `colyseus` for this example.
 * Export the room map from the entry declared in the game's catalogue.
 *
 * @example
 * ```ts
 * class GameRoom extends Room {
 *   override onJoin(client: Client<{ auth: PlayDropPlayer }>): void {
 *     console.log(client.auth.userId, client.auth.appRole, client.auth.testSlot);
 *   }
 * }
 * export const rooms = { game: defineRoom(GameRoom) };
 * ```
 */
export interface PlayDropPlayer {
  /** Retained catalogue capability, supplied only by the trusted platform. */
  readonly roomVoice?: boolean;
  /**
   * In an iMessage conversation (`sdk.host.conversation === "imessage"`): the key of that conversation's turn match,
   * verified by the platform. Scope the player to that one match and keep it out of ordinary lists. Absent otherwise.
   */
  readonly conversationMatch?: string;
  /** Current coordinated launch, verified by the platform; absent for ordinary games. */
  readonly partyPlay?: boolean;
  readonly partyCapable?: boolean;
  /** Stable PlayDrop user ID. Use this, not a supplied username, for game membership. */
  userId: number;
  username: string;
  selectedProfileAssetRef: string | null;
  /**
   * The player's picture URL as PlayDrop shows it everywhere (`sdk.me.avatarUrl`, `SocialFriend.avatarUrl`): the
   * sign-in provider photo first, the avatar's preview only without one. Null when the platform has none; then draw
   * `selectedProfileAssetRef`. Send it to the room's clients so opponents see the same picture.
   */
  readonly avatarUrl?: string | null;
  /** Platform play session ID; distinct from a Colyseus room session ID. */
  sessionId: string;
  appId: number;
  /** Published app-version ID, or 0 for an authenticated unpublished draft. */
  appVersionId: number;
  /** OWNER only when this identity owns the app. Test players have PLAYER role. */
  appRole: PlayDropAppRole;
  isTestPlayer: boolean;
  /** Creator test-player slot 1 through 4, or null for other identities. */
  testSlot: number | null;
  /** Null when player-owned AI output is unavailable, including test identities. */
  readonly assetOwnerGrant: PlayDropAssetOwnerGrant | null;
  readonly socialGrant: PlayDropSocialGrant;
  readonly deliveryGrant?: PlayDropDeliveryGrant;
  /** Opaque grant for server-side shop receipt verification and settlement (`playdrop.shop`). */
  readonly iapGrant?: PlayDropIapGrant;
}
```

## packages/game-server/src/ai-assets.ts

```ts
export type PlayDropCreateAiTaskOptions = { owner?: PlayDropPlayer };

export type PlayDropUploadAiTaskInputOptions = PlayDropCreateAiTaskOptions & {
  fileName: string;
  contentType: PrepareAiTaskInputUploadRequest["contentType"];
};

export type PlayDropAiTaskRequest<K extends AgentTaskGenerationKind> = Omit<
  Extract<CreateAiGenerationTaskRequest, { kind: K }>,
  "kind"
>;

function modality<K extends AgentTaskGenerationKind>(kind: K) {
  return Object.freeze({
    createTask: async (taskRequest: PlayDropAiTaskRequest<K>, options?: PlayDropCreateAiTaskOptions) =>
      await createTask(kind, taskRequest, options),
  });
}

export const ai = Object.freeze({
  text: modality("TEXT"),
  json: modality("JSON"),
  image: modality("IMAGE"),
  model3d: modality("MODEL_3D"),
  video: modality("VIDEO"),
  sfx: modality("SFX"),
  speech: modality("SPEECH"),
  music: modality("MUSIC"),
  inputs: Object.freeze({
    async prepare(
      input: PrepareAiTaskInputUploadRequest,
      options: PlayDropCreateAiTaskOptions = {},
    ): Promise<PrepareAiTaskInputUploadResponse> {
      return assertPreparedInputUpload(
        await request(
          "/internal/game-server/ai/input-uploads",
          { method: "POST", body: JSON.stringify(input) },
          options.owner,
        ),
      );
    },
    async finalize(
      uploadId: string,
      options: PlayDropCreateAiTaskOptions = {},
    ): Promise<FinalizeAiTaskInputUploadResponse> {
      const normalized = uploadId.trim();
      if (!normalized) throw new Error("server_ai_invalid_upload_id");
      const payload = await request(
        `/internal/game-server/ai/input-uploads/${encodeURIComponent(normalized)}/finalize`,
        { method: "POST" },
        options.owner,
      );
      if (!payload || typeof payload !== "object" || Array.isArray(payload)) throw new Error("server_ai_invalid_response");
      const result = payload as Partial<FinalizeAiTaskInputUploadResponse>;
      if (result.uploadId !== normalized || typeof result.uploadedAt !== "string") {
        throw new Error("server_ai_invalid_response");
      }
      return result as FinalizeAiTaskInputUploadResponse;
    },
    async upload(
      bytes: Uint8Array,
      options: PlayDropUploadAiTaskInputOptions,
    ): Promise<{ type: "TASK_UPLOAD"; uploadId: string }> {
      if (!(bytes instanceof Uint8Array) || bytes.byteLength <= 0) throw new Error("server_ai_invalid_upload_bytes");
      const buffer = Buffer.from(bytes);
      const prepared = await this.prepare(
        {
          fileName: options.fileName,
          contentType: options.contentType,
          sizeBytes: buffer.byteLength,
          sha256: createHash("sha256").update(buffer).digest("hex"),
          md5Base64: createHash("md5").update(buffer).digest("base64"),
        },
        options,
      );
      const uploadRequest = inputUploadRequest(prepared);
      const uploaded = await globalThis.fetch(uploadRequest.url, {
        method: prepared.uploadMethod,
        headers: uploadRequest.headers,
        body: buffer as unknown as BodyInit,
        signal: AbortSignal.timeout(60_000),
      });
      if (!uploaded.ok) throw new Error(`server_ai_input_upload_failed:${uploaded.status}`);
      await this.finalize(prepared.uploadId, options);
      return { type: "TASK_UPLOAD", uploadId: prepared.uploadId };
    },
  }),
  tasks: Object.freeze({
    /**
     * Download a completed media task created by this app's game server.
     * Private result asset refs are not browser catalogue download URLs.
     * Send the returned bytes and MIME type through the room to the intended
     * player; never send the service token or owner grant to the browser.
     */
    async downloadFile(id: number, options: { role?: string } = {}): Promise<Blob> {
      if (!Number.isInteger(id) || id <= 0) throw new Error("server_ai_invalid_task_id");
      const params = new URLSearchParams();
      if (options.role !== undefined) params.set("role", options.role);
      const query = params.toString();
      const response = await requestResponse(
        `/internal/game-server/ai/tasks/${id}/file${query ? `?${query}` : ""}`,
        { method: "GET" },
      );
      return await response.blob();
    },
    async get(id: number): Promise<GenerationAgentTaskResponse> {
      if (!Number.isInteger(id) || id <= 0) throw new Error("server_ai_invalid_task_id");
      return assertTask(await request(`/internal/game-server/ai/tasks/${id}`, { method: "GET" }));
    },
    async list(options: { kind?: AgentTaskGenerationKind; status?: AgentTaskStatus; limit?: number; offset?: number } = {}): Promise<GenerationAgentTaskResponse[]> {
      const params = new URLSearchParams();
      if (options.kind) params.set("kind", options.kind);
      if (options.status) params.set("status", options.status);
      if (options.limit !== undefined) params.set("limit", String(options.limit));
      if (options.offset !== undefined) params.set("offset", String(options.offset));
      const query = params.toString();
      const payload = await request(`/internal/game-server/ai/tasks${query ? `?${query}` : ""}`, { method: "GET" });
      const tasks = payload && typeof payload === "object" && !Array.isArray(payload)
        ? (payload as { tasks?: unknown }).tasks
        : null;
      if (!Array.isArray(tasks)) throw new Error("server_ai_invalid_response");
      return tasks.map((task) => assertTask({ task }));
    },
    async events(id: number): Promise<AgentTaskEventResponse[]> {
      if (!Number.isInteger(id) || id <= 0) throw new Error("server_ai_invalid_task_id");
      const payload = await request(`/internal/game-server/ai/tasks/${id}/events`, { method: "GET" });
      const events = payload && typeof payload === "object" && !Array.isArray(payload)
        ? (payload as { events?: unknown }).events
        : null;
      if (!Array.isArray(events)) throw new Error("server_ai_invalid_response");
      return events as AgentTaskEventResponse[];
    },
    async cancel(id: number): Promise<GenerationAgentTaskResponse> {
      if (!Number.isInteger(id) || id <= 0) throw new Error("server_ai_invalid_task_id");
      return assertTask(await request(`/internal/game-server/ai/tasks/${id}/cancel`, { method: "POST" }));
    },
    async clear(id: number): Promise<void> {
      if (!Number.isInteger(id) || id <= 0) throw new Error("server_ai_invalid_task_id");
      await request(`/internal/game-server/ai/tasks/${id}`, { method: "DELETE" });
    },
  }),
});
```

## packages/game-server/src/shop.ts

```ts
/**
 * Authoritative server-side shop receipt verification and atomic settlement on behalf of
 * a verified `client.auth` player (`PlayDropPlayer`).
 *
 * Never trust a browser receipt object, client-supplied `userId`, or client-supplied `appId`
 * to authorize paid work. Pass only the platform-verified `client.auth` and `receiptId` to
 * these methods.
 *
 * Important settlement contract:
 * - `verifyReceipt` reads the authoritative receipt for `(client.auth.userId, appId)` and
 *   validates optional expected `sku`, `amount`, `kind`, and `status`, including already
 *   `CONSUMED` receipts when retrying a previously bound entitlement.
 * - Mere verification does **not** reserve funds or prevent concurrent cancellation.
 * - Game servers must durably bind each `receiptId` to a single logical entitlement or
 *   generation record (with a unique index on `receiptId`) and call `consumeReceipt`
 *   atomically **before** starting paid AI or irreversible fulfillment so a cancel race
 *   cannot obtain unpaid work.
 * - If paid fulfillment fails after `verifyReceipt` but before `consumeReceipt`, call
 *   `cancelReceipt` to release an `AUTHORIZED` hold back to the buyer.
 * - If paid work fails for good after `consumeReceipt`, call `refund` to give the credits back.
 */
export interface PlayDropShopAPI {
  /**
   * Read and verify a receipt owned by `player` (`client.auth`) for this app.
   * Does not mutate receipt status or reserve funds.
   *
   * @example
   * ```ts
   * const receipt = await playdrop.shop.verifyReceipt(client.auth, receiptId, {
   *   sku: "doodle_illustration_100",
   *   amount: 100,
   *   kind: "consumable",
   *   status: ["AUTHORIZED", "CONSUMED"],
   * });
   * ```
   */
  verifyReceipt(
    player: PlayDropPlayer,
    receiptId: number,
    expected?: VerifyShopReceiptOptions,
  ): Promise<ShopReceipt>;

  /**
   * Atomically consume an `AUTHORIZED` consumable receipt owned by `player` (`client.auth`)
   * for this app and settle the credit ledger before paid execution.
   *
   * @example
   * ```ts
   * const consumed = await playdrop.shop.consumeReceipt(client.auth, receiptId, {
   *   sku: "doodle_illustration_100",
   *   amount: 100,
   *   kind: "consumable",
   * });
   * ```
   */
  consumeReceipt(
    player: PlayDropPlayer,
    receiptId: number,
    expected?: SettleShopReceiptOptions,
  ): Promise<ShopReceipt>;

  /**
   * Atomically cancel an `AUTHORIZED` receipt owned by `player` (`client.auth`) for this app,
   * releasing the held credits back to the buyer when fulfillment is aborted before consumption.
   *
   * @example
   * ```ts
   * const cancelled = await playdrop.shop.cancelReceipt(client.auth, receiptId, {
   *   sku: "doodle_illustration_100",
   *   amount: 100,
   *   kind: "consumable",
   * });
   * ```
   */
  cancelReceipt(
    player: PlayDropPlayer,
    receiptId: number,
    expected?: SettleShopReceiptOptions,
  ): Promise<ShopReceipt>;

  /**
   * Refund a `CONSUMED` receipt of this app when the paid work failed for good (a retry
   * cannot deliver it). The buyer's credits go back to the balances they were paid from, the
   * creator's share is removed, and the receipt becomes `CANCELLED`. The buyer does not need to
   * be connected. Calling it again for the same receipt returns it unchanged, so retry freely.
   *
   * Allowed within 7 days of the purchase (`refund_window_expired` after), and refused with
   * `refund_payout_settled` once the creator's share was paid out. Pass the buyer's
   * `client.auth` as `player` when you have it; test players' receipts require it.
   *
   * @example
   * ```ts
   * await playdrop.shop.refund(receiptId, { reason: "illustration_failed" });
   * ```
   */
  refund(receiptId: number, options: RefundShopReceiptOptions): Promise<ShopReceipt>;
}

/** Options of `playdrop.shop.refund`. */
export interface RefundShopReceiptOptions {
  /** Why the paid work could not be delivered, kept on the receipt (1 to 200 characters). */
  reason: string;
  /** The buyer's verified `client.auth`, when connected. Required for test players' receipts. */
  player?: PlayDropPlayer;
}
```

## packages/game-server/src/social.ts

```ts
/**
 * Game messages in PlayDrop Chat on behalf of a verified `client.auth` player.
 * Keep authoritative match state in the game server and MongoDB. Handle a failed
 * notification separately from a move that has already been committed.
 */
export interface PlayDropSocialAPI {
  /** Current authorized party of this original client.auth identity. Read-only. */
  getParty(player: PlayDropPlayer): Promise<GameParty | null>;
  /**
   * Friends with a fresh play session in this app. This is not the complete friend
   * list, presence, or stranger matchmaking, and an unpublished draft may return [].
   * There is no server friend picker; friend selection belongs to the host UI.
   */
  listGameFriends(player: PlayDropPlayer): Promise<SocialFriend[]>;
  /**
   * Send a typed game card as this player. The platform enforces friendship and
   * recipient authorization from host selection, fresh same-game play, or an
   * existing game-message relationship. An opponent ID alone does not authorize
   * messaging. Pass the original `client.auth`.
   * Reuse a stable clientMessageId for retries of the same logical notification.
   * In async 1v1 games send `turn` when the recipient must move and `result` when the match ends; PlayDrop keeps whose
   * turn it is from them. Pass `silent: true` while the recipient is in the match: the card is still posted and visible
   * in the chat, only without a push or unread badge, so the conversation stays right after live play. Always pass the
   * `mediaRef` the player's client got from `sdk.social.uploadMedia` to show the move as a picture, and a
   * `matchRevision` that grows with each committed move or result so a late card never moves whose turn it is backwards.
   *
   * @example
   * ```ts
   * await playdrop.social.sendMessage(client.auth, {
   *   recipientUserId: opponentId,
   *   type: "turn",
   *   title: "Your turn",
   *   payload: matchId,
   *   clientMessageId: `${matchId}-${turnNumber}-${opponentId}`,
   * });
   * ```
   */
  sendMessage(player: PlayDropPlayer, input: SendSocialMessageInput): Promise<SendSocialMessageResponse>;
  /**
   * Read this player's unconsumed, unexpired messages for this app, oldest first.
   * The limit defaults to 20 and accepts 1 through 50. Continue with nextCursor;
   * an empty messages array does not imply there is no next page.
   * Incoming messages use `id` and `from.id`, not `messageId` or `senderUserId`.
   *
   * @example
   * ```ts
   * const page = await playdrop.social.getMessages(client.auth, { limit: 20 });
   * for (const message of page.messages) {
   *   await handleGameMessage(message.from.id, message.payload);
   *   await playdrop.social.consumeMessage(client.auth, message.id);
   * }
   * ```
   */
  getMessages(
    player: PlayDropPlayer,
    options?: { cursor?: string; limit?: number },
  ): Promise<SocialMessagePage>;
  /** Mark a received message consumed after handling it. Pass the incoming message's `id`. */
  consumeMessage(player: PlayDropPlayer, messageId: string): Promise<void>;
}
```

## packages/game-server/src/multiplayer.ts

```ts
type Position = { x: number; y: number; z: number };

function createHandle(room: Room) {
  let audience: RoomVoiceAudience = "all";
  let range = 20;
  let inFlight = false;
  const teams = new Map<number, string | null>();
  const overrides = new Map<number, RoomVoiceAudience | null>();
  const positions = new Map<number, { position: Position; updatedAt: number }>();
  let lastPayload = "";
  let lastSent = 0;
  function member(player: PlayDropPlayer) {
    if (!room.clients.some(client => client.auth === player)) throw new Error("voice_player_not_in_room");
  }
  const voice = {
    setPolicy(value: RoomVoiceAudience, options?: { range?: number }) {
      if (!["all", "team", "proximity", "off"].includes(value)) throw new Error("voice_invalid_audience");
      if (options?.range !== undefined && (!Number.isFinite(options.range) || options.range <= 0 || options.range > 100_000)) throw new Error("voice_invalid_range");
      audience = value; range = options?.range ?? range;
    },
    setTeam(player: PlayDropPlayer, team: string | null) {
      member(player); if (team !== null && (typeof team !== "string" || team.length > 128)) throw new Error("voice_invalid_team"); teams.set(player.userId, team);
    },
    setAudience(player: PlayDropPlayer, value: RoomVoiceAudience | null) {
      member(player); if (value !== null && !["all", "team", "proximity", "off"].includes(value)) throw new Error("voice_invalid_audience"); overrides.set(player.userId, value);
    },
    updatePositions(values: Array<{ player: PlayDropPlayer; position: Position }>) {
      if (!Array.isArray(values) || values.length > 8) throw new Error("voice_invalid_positions");
      for (const entry of values) {
        member(entry.player);
        if (![entry.position.x, entry.position.y, entry.position.z].every(value => Number.isFinite(value) && Math.abs(value) <= 1e8)) throw new Error("voice_invalid_position");
        positions.set(entry.player.userId, { position: { ...entry.position }, updatedAt: Date.now() });
      }
    },
  };
  async function flush() {
    // Existing games never send these updates unless their retained catalogue opts into room voice.
    if (inFlight || !room.clients.some(client => (client.auth as PlayDropPlayer | undefined)?.roomVoice === true)) return;
    inFlight = true;
    try {
      const base = process.env.PLAYDROP_PLATFORM_API_URL;
      const token = process.env.PLAYDROP_SERVICE_TOKEN;
      if (!base || !token) return;
      const players = room.clients.map(client => client.auth as PlayDropPlayer);
      const hearingPairs: Array<[number, number]> = [];
      for (const listener of players) for (const speaker of players) {
        if (listener.userId === speaker.userId) continue;
        const permitted = [listener, speaker].every(player => {
          const policy = overrides.get(player.userId) ?? audience;
          if (policy === "off") return false;
          if (policy === "team") return !!teams.get(listener.userId) && teams.get(listener.userId) === teams.get(speaker.userId);
          if (policy !== "proximity") return true;
          const left = positions.get(listener.userId), right = positions.get(speaker.userId);
          return !!left && !!right && Date.now() - left.updatedAt <= 2000 && Date.now() - right.updatedAt <= 2000 &&
            Math.hypot(left.position.x - right.position.x, left.position.y - right.position.y, left.position.z - right.position.z) <= range;
        });
        if (permitted) hearingPairs.push([listener.userId, speaker.userId]);
      }
      const payload = JSON.stringify({ roomId: room.roomId, audience, range, hearingPairs,
        players: players.map(player => ({ socialGrant: player.socialGrant, audience: overrides.get(player.userId) ?? null })) });
      if (payload === lastPayload && Date.now() - lastSent < 3000) return;
      const response = await fetch(`${base.replace(/\/$/, "")}/internal/game-server/voice/room`, {
        method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
        body: payload, signal: AbortSignal.timeout(1500),
      });
      if (response.ok) { lastPayload = payload; lastSent = Date.now(); }
      const present = new Set(players.map(player => player.userId));
      for (const map of [teams, overrides, positions]) for (const id of map.keys()) if (!present.has(id)) map.delete(id);
    } catch { /* Voice recovery must not fail the room's game loop. Stale policy expires at the API. */ }
    finally { inFlight = false; }
  }
  return { voice, flush };
}
```
