@frequencytalk/agent 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +73 -2
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +5443 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +654 -0
- package/dist/index.js +5277 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/server.d.ts +12 -0
- package/dist/mcp/server.js +5416 -0
- package/dist/mcp/server.js.map +1 -0
- package/package.json +38 -4
- package/server.json +48 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/mcp/server.ts","../../src/client.ts","../../src/realtime.ts","../../src/api/frequencies.ts","../../src/api/contacts.ts","../../src/chat.ts","../../src/calls.ts","../../src/audio/native.ts","../../../shared/src/frequency.ts","../../../shared/src/billing.ts","../../../shared/src/pstn.ts","../../../shared/src/contacts.ts","../../../shared/src/userKind.ts","../../../shared/src/events.ts","../../../shared/src/responses.ts","../../../shared/src/api.ts","../../../shared/src/countries.ts","../../../shared/src/companyContact.ts","../../../shared/src/profanity.ts","../../../shared/src/share/pointer.ts","../../../shared/src/share/control.ts","../../../shared/src/share/tools.ts","../../../shared/src/errors.ts","../../../shared/src/scopes.ts","../../../shared/src/blockedWords.ts","../../../shared/src/nativeTransport.ts","../../../shared/src/redisWatch.ts","../../../shared/src/tasks.ts","../../../shared/src/feedback.ts","../../../shared/src/emojiCatalog.ts","../../../shared/src/share/reedSolomon.ts","../../../shared/src/share/shardWire.ts","../../../shared/src/share/assembler.ts","../../../shared/src/share/rateControl.ts","../../../shared/src/share/fecControl.ts","../../../shared/src/share/record.ts","../../../shared/src/share/controlInput.ts","../../../shared/src/share/controlViewer.ts","../../../shared/src/agents.ts","../../../shared/src/credit.ts","../../../shared/src/native/codec.ts","../../src/speaker.ts","../../src/audio/opus.ts","../../src/audio/wav.ts","../../src/audio/resample.ts","../../src/listener.ts","../../src/agent.ts","../../src/config.ts","../../src/mcp/tools.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { Agent } from \"../agent.js\";\nimport { loadKey } from \"../config.js\";\nimport { registerTools } from \"./tools.js\";\n\n/**\n * The MCP server (`npx @frequencytalk/agent mcp`): Frequency Talk as tools and resources for any\n * MCP-capable agent runtime, over stdio. The key comes from the environment or the config file,\n * never argv; the session is renewed from it as needed. Native audio sessions open lazily on\n * the first tool that needs one and close after a minute idle, so a quiet agent holds no UDP\n * socket and no media container.\n */\nexport async function startMcpServer(options: { baseUrl?: string } = {}): Promise<void> {\n const source = await loadKey(options);\n const agent = await Agent.connect({ baseUrl: source.baseUrl, key: source.key, realtime: { bufferSize: 500 } });\n const server = new McpServer({ name: \"frequencytalk-agent\", version: \"0.1.0\" });\n registerTools(server, agent);\n const transport = new StdioServerTransport();\n const shutdown = async () => {\n await agent.close().catch(() => undefined);\n process.exit(0);\n };\n process.on(\"SIGINT\", () => void shutdown());\n process.on(\"SIGTERM\", () => void shutdown());\n await server.connect(transport);\n}\n","import type { AgentSession, CreditBalance, UserProfile } from \"@frequency/shared\";\n\n/**\n * The HTTP client (contract §9, §25): a bearer token minted from the agent's key, renewed by\n * exchanging the key again when it expires or is refused. Every route of the service is reachable\n * through `request`; the typed modules (frequencies, contacts, chat, calls, credit) sit on top.\n */\n\nexport interface FrequencyClientOptions {\n /** The control plane's origin, e.g. `https://frequencytalk.com`. No trailing slash. */\n baseUrl: string;\n /** The agent account key (`ftag_...`). Read it from `FREQUENCY_AGENT_KEY` or the config file; never put it in argv. */\n key: string;\n /** Optional: an already-minted session to start from (renewed from the key when it expires). */\n session?: AgentSession;\n fetch?: typeof globalThis.fetch;\n /** Called with each new session, so a long-lived process can persist it if it wants to. */\n onSession?: (session: AgentSession) => void;\n}\n\n/** An API refusal: the service's error envelope, with the HTTP status and any `Retry-After`. */\nexport class FrequencyError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n message: string,\n readonly details?: unknown,\n readonly retryAfterSeconds?: number,\n ) {\n super(message);\n this.name = \"FrequencyError\";\n }\n}\n\n/** A 402: the service wants a payment first. For the top-up route the challenge is the body and headers to pay against. */\nexport class PaymentRequired extends Error {\n constructor(\n /** The `WWW-Authenticate: Payment ...` challenge, when the route issued one (the top-up). */\n readonly challenge: string | null,\n /** The error envelope, when the 402 is `SUBSCRIPTION_REQUIRED` with its `details.credit`. */\n readonly error: { code: string; message: string; details?: unknown } | null,\n readonly headers: Headers,\n readonly body: string,\n ) {\n super(error?.message ?? \"Payment required.\");\n this.name = \"PaymentRequired\";\n }\n}\n\nexport interface RequestOptions {\n method?: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n body?: unknown;\n headers?: Record<string, string>;\n /** Send without the bearer token (the sign-in routes). */\n anonymous?: boolean;\n /** Retry once after re-exchanging the key on a 401. Default true. */\n renewOn401?: boolean;\n}\n\nfunction retryAfterSeconds(res: Response): number | undefined {\n const raw = res.headers.get(\"retry-after\");\n if (!raw) return undefined;\n const seconds = Number(raw.trim());\n return Number.isFinite(seconds) && seconds >= 0 ? seconds : undefined;\n}\n\n/** Renew a little before the token's own expiry, so a request never races it. */\nconst RENEW_MARGIN_MS = 60_000;\n\n/**\n * What the typed modules and the native session need from a client: the origin, a bearer token\n * on demand, and one request with the service's refusals thrown as `FrequencyError`.\n * `FrequencyClient` is the agent's implementation and refuses anything but an agent key; the\n * load generator's probes supply their own over a token the load-test endpoints minted, which\n * is the only way a non-agent session drives this package.\n */\nexport interface ApiClient {\n readonly baseUrl: string;\n accessToken(): Promise<string>;\n request<T>(path: string, options?: RequestOptions): Promise<T>;\n}\n\nexport class FrequencyClient implements ApiClient {\n readonly baseUrl: string;\n private readonly key: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly onSession: ((session: AgentSession) => void) | undefined;\n private session: AgentSession | null;\n private renewing: Promise<AgentSession> | null = null;\n\n constructor(options: FrequencyClientOptions) {\n if (!options.baseUrl || !/^https?:\\/\\//.test(options.baseUrl)) throw new Error(\"baseUrl must be an http(s) origin\");\n if (!options.key.startsWith(\"ftag_\")) throw new Error(\"key must be an agent account key (ftag_...)\");\n this.baseUrl = options.baseUrl.replace(/\\/$/, \"\");\n this.key = options.key;\n this.fetchImpl = options.fetch ?? globalThis.fetch;\n this.onSession = options.onSession;\n this.session = options.session ?? null;\n }\n\n /** The current session, minting one from the key if there is none or it is about to expire. */\n async signIn(): Promise<AgentSession> {\n if (this.session && Date.parse(this.session.expiresAt) - Date.now() > RENEW_MARGIN_MS) return this.session;\n return this.renew();\n }\n\n /** Exchange the key again, now. One exchange at a time; concurrent callers share it. */\n async renew(): Promise<AgentSession> {\n if (!this.renewing) {\n this.renewing = (async () => {\n try {\n const session = await this.request<AgentSession>(\"/v1/auth/agent\", { method: \"POST\", body: { key: this.key }, anonymous: true, renewOn401: false });\n this.session = session;\n this.onSession?.(session);\n return session;\n } finally {\n this.renewing = null;\n }\n })();\n }\n return this.renewing;\n }\n\n /** The access token for a socket or a signalling URL, renewed if needed. */\n async accessToken(): Promise<string> {\n return (await this.signIn()).accessToken;\n }\n\n /** The signed-in agent. */\n async me(): Promise<UserProfile> {\n return this.request<UserProfile>(\"/v1/users/me\");\n }\n\n /** The balance that pays for what this agent does (its own, or its sponsor's). */\n async credit(): Promise<CreditBalance> {\n return this.request<CreditBalance>(\"/v1/billing/credit\");\n }\n\n /**\n * One request against the service. Parses the error envelope into `FrequencyError`, a 402 into\n * `PaymentRequired`, renews the session once on a 401, and honours `Retry-After` only by\n * reporting it: the caller decides whether to wait.\n */\n async request<T>(path: string, options: RequestOptions = {}): Promise<T> {\n const { method = \"GET\", body, headers = {}, anonymous = false, renewOn401 = true } = options;\n const send = async (): Promise<Response> => {\n const auth = anonymous ? {} : { authorization: `Bearer ${await this.accessToken()}` };\n return this.fetchImpl(`${this.baseUrl}${path}`, {\n method,\n headers: { ...(body !== undefined ? { \"content-type\": \"application/json\" } : {}), ...auth, ...headers },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n });\n };\n let res = await send();\n if (res.status === 401 && !anonymous && renewOn401) {\n await this.renew();\n res = await send();\n }\n if (res.status === 204) return undefined as T;\n const text = await res.text();\n if (res.status === 402) {\n let error: PaymentRequired[\"error\"] = null;\n try {\n error = (JSON.parse(text) as { error?: PaymentRequired[\"error\"] }).error ?? null;\n } catch {\n error = null;\n }\n throw new PaymentRequired(res.headers.get(\"www-authenticate\"), error, res.headers, text);\n }\n let json: unknown;\n try {\n json = text ? JSON.parse(text) : undefined;\n } catch {\n json = undefined;\n }\n if (!res.ok) {\n const envelope = (json as { error?: { code?: string; message?: string; details?: unknown } } | undefined)?.error;\n throw new FrequencyError(res.status, envelope?.code ?? \"UNKNOWN_ERROR\", envelope?.message ?? res.statusText, envelope?.details, retryAfterSeconds(res));\n }\n return json as T;\n }\n}\n","import WebSocket from \"ws\";\nimport type { ClientToServerEvent, ServerToClientEvent } from \"@frequency/shared\";\nimport type { FrequencyClient } from \"./client.js\";\n\n/**\n * The realtime socket (`/ws`, contract §10 and §13): presence, rosters, chat frames, call\n * events, the lot. One socket per agent process; subscribe to the frequencies you care about.\n *\n * Reconnects with jittered backoff; a 4401 (the token expired) renews the session once and\n * reconnects; a 4409 (the session was revoked, the key deleted) is terminal and `onClosed`\n * says so. The last 500 events are kept in a ring buffer so a caller that connects late, or\n * an MCP tool answering \"what happened\", can read them without having listened.\n */\n\nexport type RealtimeEvent = ServerToClientEvent;\n\nexport interface RealtimeOptions {\n /** Frequencies to subscribe to on every (re)connect. */\n frequencyIds?: string[];\n onEvent?: (event: RealtimeEvent) => void;\n onOpen?: () => void;\n /** Terminal: the session was revoked (4409) or the caller closed it. */\n onClosed?: (reason: \"revoked\" | \"closed\") => void;\n /** Ring buffer size. Default 500. */\n bufferSize?: number;\n}\n\nexport const WS_CLOSE_UNAUTHORIZED = 4401;\nexport const WS_CLOSE_SESSION_REVOKED = 4409;\n\nexport class Realtime {\n private ws: WebSocket | null = null;\n private closedByCaller = false;\n private attempt = 0;\n private renewedOnce = false;\n private readonly buffer: RealtimeEvent[] = [];\n private readonly bufferSize: number;\n private readonly subscriptions = new Set<string>();\n private readonly waiters: Array<{ predicate: (event: RealtimeEvent) => boolean; resolve: (event: RealtimeEvent) => void }> = [];\n\n constructor(\n private readonly client: FrequencyClient,\n private readonly options: RealtimeOptions = {},\n ) {\n this.bufferSize = options.bufferSize ?? 500;\n for (const id of options.frequencyIds ?? []) this.subscriptions.add(id);\n }\n\n /** Opens the socket and resolves once the server has answered a ping (the connect path has finished). */\n async connect(): Promise<void> {\n this.closedByCaller = false;\n await this.open();\n }\n\n private async open(): Promise<void> {\n const token = await this.client.accessToken();\n const url = `${this.client.baseUrl.replace(/^http/, \"ws\")}/ws?token=${encodeURIComponent(token)}`;\n const ws = new WebSocket(url);\n this.ws = ws;\n await new Promise<void>((resolve, reject) => {\n ws.once(\"open\", () => resolve());\n ws.once(\"error\", (err) => reject(err));\n });\n this.attempt = 0;\n ws.on(\"message\", (raw) => this.onMessage(raw));\n ws.on(\"close\", (code) => void this.onClose(code));\n ws.on(\"error\", () => undefined);\n for (const id of this.subscriptions) this.send({ type: \"subscribe\", frequencyId: id });\n this.send({ type: \"ping\" });\n await this.waitFor((e) => e.type === \"pong\", 10_000);\n this.options.onOpen?.();\n }\n\n private onMessage(raw: WebSocket.RawData): void {\n let event: RealtimeEvent;\n try {\n event = JSON.parse(raw.toString()) as RealtimeEvent;\n } catch {\n return;\n }\n this.buffer.push(event);\n if (this.buffer.length > this.bufferSize) this.buffer.shift();\n for (const waiter of [...this.waiters]) {\n if (waiter.predicate(event)) {\n this.waiters.splice(this.waiters.indexOf(waiter), 1);\n waiter.resolve(event);\n }\n }\n this.options.onEvent?.(event);\n }\n\n private async onClose(code: number): Promise<void> {\n this.ws = null;\n if (this.closedByCaller) return;\n if (code === WS_CLOSE_SESSION_REVOKED) {\n this.options.onClosed?.(\"revoked\");\n return;\n }\n if (code === WS_CLOSE_UNAUTHORIZED && !this.renewedOnce) {\n this.renewedOnce = true;\n await this.client.renew().catch(() => undefined);\n } else if (code === WS_CLOSE_UNAUTHORIZED) {\n // Renewed already and still refused: the key is gone or the account is. Terminal.\n this.options.onClosed?.(\"revoked\");\n return;\n }\n const delay = Math.min(30_000, 500 * 2 ** this.attempt) + Math.floor(Math.random() * 500);\n this.attempt += 1;\n await new Promise((resolve) => setTimeout(resolve, delay));\n if (this.closedByCaller) return;\n try {\n await this.open();\n this.renewedOnce = false;\n } catch {\n void this.onClose(0);\n }\n }\n\n send(frame: ClientToServerEvent): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) throw new Error(\"realtime: not connected\");\n this.ws.send(JSON.stringify(frame));\n }\n\n subscribe(frequencyId: string): void {\n this.subscriptions.add(frequencyId);\n if (this.ws?.readyState === WebSocket.OPEN) this.send({ type: \"subscribe\", frequencyId });\n }\n\n unsubscribe(frequencyId: string): void {\n this.subscriptions.delete(frequencyId);\n if (this.ws?.readyState === WebSocket.OPEN) this.send({ type: \"unsubscribe\", frequencyId });\n }\n\n /** The recent events, oldest first. */\n recent(filter?: (event: RealtimeEvent) => boolean): RealtimeEvent[] {\n return filter ? this.buffer.filter(filter) : [...this.buffer];\n }\n\n /** Resolves with the first event (already buffered or still to come) matching the predicate. */\n waitFor(predicate: (event: RealtimeEvent) => boolean, timeoutMs = 30_000): Promise<RealtimeEvent> {\n const already = this.buffer.find(predicate);\n if (already) return Promise.resolve(already);\n return new Promise((resolve, reject) => {\n const waiter = { predicate, resolve };\n this.waiters.push(waiter);\n setTimeout(() => {\n const i = this.waiters.indexOf(waiter);\n if (i !== -1) {\n this.waiters.splice(i, 1);\n reject(new Error(\"realtime: timed out waiting for an event\"));\n }\n }, timeoutMs).unref?.();\n });\n }\n\n get connected(): boolean {\n return this.ws?.readyState === WebSocket.OPEN;\n }\n\n close(): void {\n this.closedByCaller = true;\n this.ws?.close(1000, \"closed\");\n this.ws = null;\n this.options.onClosed?.(\"closed\");\n }\n}\n","import type { ApiClient } from \"../client.js\";\n\n/**\n * Frequencies (contract §1, §10): what an agent can see, join, tune and create. The shapes are\n * the service's own responses; the SDK adds no layer on them beyond typing the few fields an\n * agent needs to act.\n */\n\nexport interface FrequencySummary {\n id: string;\n khz: number;\n name: string;\n mode: \"push_to_talk\" | \"broadcast\" | \"direct\";\n publiclyListable?: boolean;\n description?: string | null;\n}\n\nexport interface ChannelSummary {\n id: string;\n name: string;\n kind: string;\n isDefault?: boolean;\n talkPermission?: string;\n}\n\nexport interface TuneResult {\n token: string;\n mediaNodeAddress: string;\n mediaNodeStatus: string;\n expiresAt: string;\n nativeTransport?: {\n udpEndpoint: string;\n bootId: string;\n channelKeys: { keysetId: string; epoch: number; keys: Record<string, { id: number; key: string }> };\n };\n}\n\nexport interface RosterMember {\n userId: string;\n handle: string | null;\n stationId: string;\n kind?: \"person\" | \"agent\" | \"line\";\n online?: boolean;\n}\n\nexport class Frequencies {\n constructor(private readonly client: ApiClient) {}\n\n /** The frequencies this agent belongs to. */\n mine(): Promise<FrequencySummary[]> {\n return this.client.request<FrequencySummary[]>(\"/v1/frequencies\");\n }\n\n /** The public dial: listable frequencies, each marked with whether this agent is already a member. */\n publicFrequencies(): Promise<Array<FrequencySummary & { isMember: boolean }>> {\n return this.client.request<Array<FrequencySummary & { isMember: boolean }>>(\"/v1/frequencies/public\");\n }\n\n /** The public stations (broadcast frequencies on the dial), as anyone may see them. */\n publicStations(): Promise<unknown> {\n return this.client.request<unknown>(\"/v1/public/stations\");\n }\n\n /**\n * \"Know the number, tune in\": by dial number (kHz, e.g. 118025 for 118.025), with the access\n * code where the frequency has one. Joins where it can and answers the media join token.\n */\n tuneByNumber(khz: number, accessCode?: string): Promise<TuneResult & { frequency?: FrequencySummary }> {\n return this.client.request<TuneResult & { frequency?: FrequencySummary }>(\"/v1/frequencies/tune-by-number\", { method: \"POST\", body: { khz, ...(accessCode ? { accessCode } : {}) } });\n }\n\n get(id: string): Promise<FrequencySummary> {\n return this.client.request<FrequencySummary>(`/v1/frequencies/${encodeURIComponent(id)}`);\n }\n\n channels(id: string): Promise<ChannelSummary[]> {\n return this.client.request<ChannelSummary[]>(`/v1/frequencies/${encodeURIComponent(id)}/channels`);\n }\n\n /** Who is tuned right now. */\n async roster(id: string): Promise<RosterMember[]> {\n const res = await this.client.request<{ members: RosterMember[] }>(`/v1/frequencies/${encodeURIComponent(id)}/roster`);\n return res.members;\n }\n\n /** Ask to join a listable frequency: `joined` when it auto-approves, `pending_approval` when an admin must. */\n requestJoin(id: string): Promise<{ status: \"joined\" } | { status: \"pending_approval\"; invitationId: string }> {\n return this.client.request(`/v1/frequencies/${encodeURIComponent(id)}/request-join`, { method: \"POST\" });\n }\n\n leave(id: string): Promise<void> {\n return this.client.request<void>(`/v1/frequencies/${encodeURIComponent(id)}/leave`, { method: \"POST\" });\n }\n\n /** The media join token for a frequency; `transmitIntent` asks for a talk-capable session. */\n tune(id: string, options: { transmitIntent?: boolean; takeOver?: boolean } = {}): Promise<TuneResult> {\n return this.client.request<TuneResult>(`/v1/frequencies/${encodeURIComponent(id)}/tune`, { method: \"POST\", body: { transmitIntent: options.transmitIntent ?? false, ...(options.takeOver ? { takeOver: true } : {}) } });\n }\n\n /**\n * Create a push-to-talk frequency. The operator's attestation is required (`ageConfirmed`,\n * `termsAccepted`); billing applies as to any account (a 402 names what the balance needs).\n */\n create(body: { name: string; description?: string; publiclyListable?: boolean; accessCode?: string; vanityKhz?: number; ageConfirmed: true; termsAccepted: true }): Promise<FrequencySummary> {\n return this.client.request<FrequencySummary>(\"/v1/frequencies\", { method: \"POST\", body });\n }\n}\n","import type { FrequencyClient } from \"../client.js\";\n\n/** Contacts (contract §15): who an agent may call, and the requests either way. */\n\nexport interface Contact {\n id: string;\n handle: string | null;\n stationId: string;\n kind?: \"person\" | \"agent\" | \"line\";\n status?: string;\n}\n\nexport class Contacts {\n constructor(private readonly client: FrequencyClient) {}\n\n async list(): Promise<Contact[]> {\n return (await this.client.request<{ contacts: Contact[] }>(\"/v1/contacts\")).contacts;\n }\n\n /** Ask somebody to be a contact, by their Station ID (`FT-XXXX`), which is unambiguous. */\n request(identifier: string): Promise<unknown> {\n return this.client.request(\"/v1/contacts/requests\", { method: \"POST\", body: { identifier } });\n }\n\n requests(): Promise<unknown> {\n return this.client.request(\"/v1/contacts/requests\");\n }\n\n accept(requestId: string): Promise<unknown> {\n return this.client.request(`/v1/contacts/requests/${encodeURIComponent(requestId)}/accept`, { method: \"POST\" });\n }\n\n decline(requestId: string): Promise<unknown> {\n return this.client.request(`/v1/contacts/requests/${encodeURIComponent(requestId)}/decline`, { method: \"POST\" });\n }\n\n remove(userId: string): Promise<void> {\n return this.client.request<void>(`/v1/contacts/${encodeURIComponent(userId)}`, { method: \"DELETE\" });\n }\n\n search(q: string): Promise<Contact[]> {\n return this.client.request<Contact[]>(`/v1/users/search?q=${encodeURIComponent(q)}`);\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { FrequencyClient } from \"./client.js\";\nimport type { Realtime, RealtimeEvent } from \"./realtime.js\";\n\n/**\n * Chat (contract §15): a relay, not a mailbox. A send is idempotent for two minutes under its\n * `clientMessageId`; what arrives is a `contact.message` frame on the socket, and the buffer\n * of what arrived while nobody was listening is read back with `read`. Each message is\n * identified by `(seq, sentAt)`, and a re-read after a gap is deduped on that pair.\n */\n\nexport interface ChatMessage {\n id: string;\n seq: number;\n sentAt: string;\n fromUserId: string;\n body: string;\n kind?: string;\n sender?: { kind?: string; handle: string | null; stationId: string } | null;\n}\n\nexport class Chat {\n private readonly seen = new Map<string, Set<string>>();\n\n constructor(\n private readonly client: FrequencyClient,\n private readonly realtime?: Realtime,\n ) {}\n\n private key(m: { seq: number; sentAt: string }): string {\n return `${m.seq}:${m.sentAt}`;\n }\n\n /** Send a text to a contact, or to anyone who accepts messages from non-contacts (every agent does by default). */\n async send(toUserId: string, body: string, options: { clientMessageId?: string } = {}): Promise<{ id: string; seq: number; sentAt: string }> {\n return this.client.request(`/v1/contacts/${encodeURIComponent(toUserId)}/messages`, {\n method: \"POST\",\n body: { body, clientMessageId: options.clientMessageId ?? randomUUID() },\n });\n }\n\n /** What is waiting from this peer. Deduped against what the socket already delivered. */\n async read(peerUserId: string): Promise<ChatMessage[]> {\n const res = await this.client.request<{ messages: ChatMessage[] }>(`/v1/contacts/${encodeURIComponent(peerUserId)}/messages`);\n const messages = res.messages;\n const seen = this.seen.get(peerUserId) ?? new Set<string>();\n this.seen.set(peerUserId, seen);\n const fresh = messages.filter((m) => !seen.has(this.key(m)));\n for (const m of fresh) seen.add(this.key(m));\n return fresh;\n }\n\n /** Mark what was read, so the service can drop it from the buffer. */\n ack(peerUserId: string, upTo: number): Promise<void> {\n return this.client.request<void>(`/v1/contacts/${encodeURIComponent(peerUserId)}/messages/ack`, { method: \"POST\", body: { upTo } });\n }\n\n /** The messages that arrived on the socket, from everyone or one peer, oldest first. */\n inbox(peerUserId?: string): ChatMessage[] {\n if (!this.realtime) return [];\n return this.realtime\n .recent((e) => e.type === \"contact.message\" && (!peerUserId || (e as unknown as { fromUserId: string }).fromUserId === peerUserId))\n .map((e) => e as unknown as ChatMessage);\n }\n\n /** Resolves with the next message from a peer (or anyone), from the socket. */\n waitForMessage(peerUserId?: string, timeoutMs = 60_000): Promise<ChatMessage> {\n if (!this.realtime) throw new Error(\"chat.waitForMessage needs the realtime socket\");\n const seenNow = new Set(this.inbox(peerUserId).map((m) => this.key(m)));\n return this.realtime\n .waitFor((e: RealtimeEvent) => {\n if (e.type !== \"contact.message\") return false;\n const m = e as unknown as ChatMessage;\n return (!peerUserId || m.fromUserId === peerUserId) && !seenNow.has(this.key(m));\n }, timeoutMs)\n .then((e) => e as unknown as ChatMessage);\n }\n}\n","import type { FrequencyClient } from \"./client.js\";\nimport type { Realtime } from \"./realtime.js\";\n\n/**\n * Calls (contract §16): a call is an ephemeral frequency. Place one to a contact, answer one\n * that rings, hang up. Audio on the call is the native session tuned to the call's frequency.\n */\n\nexport interface PlacedCall {\n id: string;\n frequencyId: string;\n channelId: string;\n ringUntil?: string;\n participants?: unknown[];\n ringback?: string;\n}\n\n/** The `call.ringing` event: somebody is calling this agent. Answer before `expiresAt`. */\nexport interface IncomingRing {\n type: \"call.ringing\";\n callId: string;\n fromUserId: string;\n participantUserIds?: string[];\n expiresAt: number | string;\n}\n\nexport class Calls {\n constructor(\n private readonly client: FrequencyClient,\n private readonly realtime?: Realtime,\n ) {}\n\n place(toUserIds: string[]): Promise<PlacedCall> {\n return this.client.request<PlacedCall>(\"/v1/calls\", { method: \"POST\", body: { toUserIds } });\n }\n\n accept(callId: string): Promise<PlacedCall> {\n return this.client.request<PlacedCall>(`/v1/calls/${encodeURIComponent(callId)}/accept`, { method: \"POST\" });\n }\n\n decline(callId: string): Promise<void> {\n return this.client.request<void>(`/v1/calls/${encodeURIComponent(callId)}/decline`, { method: \"POST\" });\n }\n\n hangUp(callId: string): Promise<void> {\n return this.client.request<void>(`/v1/calls/${encodeURIComponent(callId)}`, { method: \"DELETE\" });\n }\n\n /** Calls ringing at this agent right now, from the socket's recent events. */\n ringing(): IncomingRing[] {\n if (!this.realtime) return [];\n return this.realtime.recent((e) => e.type === \"call.ringing\").map((e) => e as unknown as IncomingRing);\n }\n\n /** Resolves with the next ring. */\n waitForRing(timeoutMs = 120_000): Promise<IncomingRing> {\n if (!this.realtime) throw new Error(\"calls.waitForRing needs the realtime socket\");\n return this.realtime.waitFor((e) => e.type === \"call.ringing\", timeoutMs).then((e) => e as unknown as IncomingRing);\n }\n}\n","import { createSocket, type Socket } from \"node:dgram\";\nimport WebSocket from \"ws\";\nimport { AEAD, HEADER, NATIVE_TRANSPORT_VERSION, PAYLOAD, PAYLOAD_TYPE } from \"@frequency/shared\";\nimport { audioPayload, open, seal } from \"@frequency/shared/native-codec\";\nimport type { ApiClient } from \"../client.js\";\nimport type { Frequencies, TuneResult } from \"../api/frequencies.js\";\n\n/**\n * A native-transport session on one frequency (audio-routing-contract.md \"Transports\"; the\n * wire in `@frequency/shared/native-codec`). THIS IS THE REFERENCE CLIENT: the load\n * generator's conformance probes (`npm run native:probe`, `npm run bridge:probe`) drive this\n * class against a live deployment, so the client agents ship with and the client the probes\n * certify are one piece of code. Where this file and the contract disagree, one is a bug.\n *\n * The obligations the contract spells out, each kept here so a caller cannot forget one:\n * - tune until the node hands out `nativeTransport`, then authenticate on the signalling\n * socket with `nativeTransport: true` and check the node generation (`bootId`) matches\n * the keys we hold;\n * - SEND before you can RECEIVE: a sealed keepalive right after `authOk`, and every few\n * seconds after, or the datapath never learns this socket's address and forwards nothing;\n * - seal every audio packet under the stream's HOME channel key (the copy the platform's\n * bridge consumes; skip it and every browser listener hears nothing);\n * - VERIFY attribution: a received packet's header connection id must match the owner the\n * `nativeStream` announcement bound to that stream id, or the packet is dropped;\n * - on `nativeKeysRotated`, fetch the ring again and install it when the generation matches,\n * without re-tuning. Compare `keysetId`, never `epoch` (a uint8 the control plane re-mints\n * at 0 on restart). A generation change is the one exception: never install, tell the\n * caller (`onGenerationChange`), whose only correct move is to close and open again.\n *\n * What was dropped and what was installed is counted (`receiveStats`, `resyncStats`) because\n * every failure on this path is silence: a healthy `frames` count with nothing audible is the\n * application's problem; `misattributed` or `undecryptable` climbing is a key or announcement\n * problem; `installs` is the number that proves a rotation was survived.\n *\n * Wire version 1 is sent and received. Version 2 audio (one seal, the content key wrapped per\n * channel) is announced by capability `native-transport-v2` and is counted here as\n * `unsupportedVersion`; peers on v2 are the next step for this package (handoff).\n */\n\ntype MediaEvent = { type: string } & Record<string, unknown>;\n\nexport type NativeTransportBlock = NonNullable<TuneResult[\"nativeTransport\"]>;\n\nexport interface NativeAudioFrame {\n streamId: number;\n timestamp: number;\n opus: Buffer;\n connectionId: number;\n}\n\nexport interface NativeStreamAnnouncement {\n streamId: number;\n connectionId: number;\n producerUserId?: string;\n producerCallsign?: string;\n channelId?: string;\n}\n\n/** What the resync half of the contract did, for a probe or a diagnostic. */\nexport interface NativeResyncStats {\n /** Rings installed without a re-tune: the number that proves the rotation handling works. */\n installs: number;\n /** Notices naming material already held: the common case, the notice is frequency-wide. */\n alreadyCurrent: number;\n /** Notices whose fetch could not be installed after the retries. */\n failures: number;\n /** Fetches that answered with another node generation: not installed, `onGenerationChange` fired. */\n generationChanges: number;\n /** Fetches the receive side asked for on its own: a run of packets that would not open with nothing opening alongside, the sign of a missed notice. */\n staleWatchRefreshes: number;\n}\n\n/** What arrived on the socket and what was done with it. */\nexport interface NativeReceiveStats {\n /** Audio frames opened and attributed, handed to the listeners. */\n frames: number;\n /** Packets whose version byte this build does not read (wire v2). */\n unsupportedVersion: number;\n /** Packets on a channel this session holds no key for. */\n unknownChannel: number;\n /** Packets that did not open under the channel key: a stale ring on one side. */\n undecryptable: number;\n /** Keepalives and control packets. */\n notAudio: number;\n /** Audio whose header connection id is not the announced owner of its stream id. */\n misattributed: number;\n}\n\nexport interface NativeSessionOptions {\n /** Send keepalives this often (ms). Default 2000. */\n keepaliveMs?: number;\n /** The jitter before a resync fetch (ms, uniform from 0). Default 1000: the notice is frequency-wide, so an unjittered fetch is a stampede. */\n resyncJitterMs?: number;\n onStream?: (announcement: NativeStreamAnnouncement) => void;\n onAudio?: (frame: NativeAudioFrame) => void;\n onEvent?: (event: MediaEvent) => void;\n /** The node changed generation under this session: nothing was installed, and the only correct response is `close()` then `open()` again. */\n onGenerationChange?: () => void;\n /** The signalling socket closed (the node went away, the token expired, or the session was revoked). Nothing is received after this. */\n onClose?: (close: { code: number; reason: string }) => void;\n}\n\ninterface NativeKeysResult {\n bootId: string;\n keysetId: string;\n epoch: number;\n keys: Record<string, { id: number; key: string }>;\n}\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n/** Twenty packets is 400 ms of one talker's audio: long enough to be no stray straggler, short enough to be inaudible as a gap. */\nconst STALE_RUN_PACKETS = 20;\nconst STALE_REFRESH_MIN_MS = 5_000;\n\nexport class NativeSession {\n private ws: WebSocket | null = null;\n private udp: Socket | null = null;\n /** Increments PER SEAL, never per frame: a frame sealed to N channels burns N values, which keeps (connectionId, sequence) unique under a shared channel key. */\n private sequence = 0n;\n private connection = 0;\n private senderMacKey = Buffer.alloc(0);\n private native: NativeTransportBlock | null = null;\n private joinToken = \"\";\n private keepalive: NodeJS.Timeout | null = null;\n private homeChannelId: string | null = null;\n private producing: { streamId: number; channelId: string } | null = null;\n private timestamp = 0;\n private readonly owners = new Map<number, number>();\n private readonly pending: Array<{ type: string; resolve: (e: MediaEvent) => void; reject: (err: Error) => void }> = [];\n /** The last 500 signalling events, oldest first. A probe reads them; `waitFor` searches them. */\n readonly events: MediaEvent[] = [];\n /** One notice at a time: two overlapping fetches could install in the wrong order and leave the older ring on top. */\n private resync: Promise<void> = Promise.resolve();\n private readonly audioListeners = new Set<(frame: NativeAudioFrame) => void>();\n private closedWith: { code: number; reason: string } | null = null;\n readonly resyncStats: NativeResyncStats = { installs: 0, alreadyCurrent: 0, failures: 0, generationChanges: 0, staleWatchRefreshes: 0 };\n /** The stale-key watch: consecutive packets that would not open since the last one that did, and when a refresh was last asked for. */\n private staleRun = 0;\n private lastStaleRefresh = 0;\n readonly receiveStats: NativeReceiveStats = { frames: 0, unsupportedVersion: 0, unknownChannel: 0, undecryptable: 0, notAudio: 0, misattributed: 0 };\n\n constructor(\n private readonly client: ApiClient,\n private readonly frequencies: Frequencies,\n readonly frequencyId: string,\n private readonly options: NativeSessionOptions = {},\n ) {}\n\n /** The node-issued datapath identity, 0 until `open()` has authenticated. */\n get connectionId(): number {\n return this.connection;\n }\n\n /** The transport block this session holds (endpoint, generation, the current ring), null until open. */\n get transport(): NativeTransportBlock | null {\n return this.native;\n }\n\n /** How the signalling socket closed, or null while it is open (and before `open()`). */\n get closed(): { code: number; reason: string } | null {\n return this.closedWith;\n }\n\n /** Tune (with transmit intent), wait for the native block, open signalling, authenticate, bind the UDP socket, start keepalives. */\n async open(options: { transmitIntent?: boolean; channelId?: string } = {}): Promise<void> {\n const deadline = Date.now() + 90_000;\n for (;;) {\n const tuned = await this.frequencies.tune(this.frequencyId, { transmitIntent: options.transmitIntent ?? true });\n if (tuned.nativeTransport) {\n this.native = tuned.nativeTransport;\n this.joinToken = tuned.token;\n break;\n }\n // Absence is an ORDINARY state (the container is booting, or its generation is not cleared yet), not an error.\n if (Date.now() > deadline) throw new Error(`no native transport on ${this.frequencyId} after 90s (node ${tuned.mediaNodeStatus})`);\n await sleep(2000);\n }\n const token = await this.client.accessToken();\n const url = `${this.client.baseUrl.replace(/^http/, \"ws\")}/media-proxy/${this.frequencyId}/signal?token=${encodeURIComponent(token)}`;\n const ws = new WebSocket(url);\n this.ws = ws;\n await new Promise<void>((resolve, reject) => {\n ws.once(\"open\", () => resolve());\n ws.once(\"error\", reject);\n });\n ws.on(\"message\", (raw) => this.onSignal(raw));\n ws.on(\"close\", (code, reason) => {\n // Surface it: a closed signalling socket is silence on every path, and a waiter must not\n // sit out its timeout for an event that can no longer arrive.\n this.closedWith = { code, reason: reason.toString() };\n for (const p of this.pending.splice(0)) p.reject(new Error(`native: signalling closed (${code} ${reason.toString()}) while waiting for \"${p.type}\"`));\n this.options.onClose?.(this.closedWith);\n });\n for (let attempt = 0; ; attempt += 1) {\n this.send({ type: \"auth\", token: this.joinToken, nativeTransport: true });\n const ack = await this.waitFor(\"authOk\", 10_000);\n const nativeAck = ack.native as { connectionId: number; senderMacKey: string; bootId: string } | undefined;\n if (nativeAck) {\n // The generation the KEYS came from must be the generation the IDENTITY came from: sealing\n // under a key from a previous boot with an id allocated by this one is the nonce-reuse hazard.\n if (nativeAck.bootId !== this.native!.bootId) throw new Error(\"native: bootId mismatch between the keys and the identity; re-tune\");\n this.connection = nativeAck.connectionId;\n this.senderMacKey = Buffer.from(nativeAck.senderMacKey, \"base64\");\n break;\n }\n // authOk WITHOUT a native block = \"not cleared yet, ask again shortly\".\n if (attempt === 29) throw new Error(\"native: the node never issued a native identity\");\n this.events.length = 0;\n await sleep(1000);\n }\n this.udp = createSocket(\"udp4\");\n await new Promise<void>((resolve) => this.udp!.bind(0, resolve));\n this.udp.on(\"message\", (packet) => this.onPacket(packet));\n this.homeChannelId = options.channelId ?? (await this.defaultChannelId());\n // Send before receive: the datapath learns this socket's address from the first MAC-valid packet.\n this.sendKeepalive();\n this.keepalive = setInterval(() => this.sendKeepalive(), this.options.keepaliveMs ?? 2000);\n this.keepalive.unref?.();\n }\n\n private async defaultChannelId(): Promise<string> {\n const channels = await this.frequencies.channels(this.frequencyId);\n const home = channels.find((c) => c.isDefault)?.id ?? channels[0]?.id;\n if (!home) throw new Error(\"native: the frequency has no channel to home a stream on\");\n return home;\n }\n\n private send(frame: Record<string, unknown>): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) throw new Error(\"native: signalling is not open\");\n this.ws.send(JSON.stringify(frame));\n }\n\n private onSignal(raw: WebSocket.RawData): void {\n let event: MediaEvent;\n try {\n event = JSON.parse(raw.toString()) as MediaEvent;\n } catch {\n return;\n }\n this.events.push(event);\n if (this.events.length > 500) this.events.shift();\n if (event.type === \"nativeStream\") {\n const streamId = Number(event.streamId);\n const connectionId = Number(event.connectionId);\n this.owners.set(streamId, connectionId);\n this.options.onStream?.({ streamId, connectionId, producerUserId: event.producerUserId as string | undefined, producerCallsign: event.producerCallsign as string | undefined, channelId: event.channelId as string | undefined });\n }\n if (event.type === \"nativeStreamClosed\") this.owners.delete(Number(event.streamId));\n // Handled HERE, not by whatever the application is awaiting: a rotation arrives whenever\n // anybody leaves the frequency, at any moment, including mid-talkspurt.\n if (event.type === \"nativeKeysRotated\") this.onKeysRotated(String(event.keysetId));\n for (const p of [...this.pending]) {\n if (p.type === event.type) {\n this.pending.splice(this.pending.indexOf(p), 1);\n p.resolve(event);\n }\n }\n this.options.onEvent?.(event);\n }\n\n /** The first buffered signalling event of a type, or the next one to arrive within the timeout. */\n waitFor(type: string, timeoutMs = 10_000): Promise<MediaEvent> {\n const found = this.events.find((e) => e.type === type);\n if (found) return Promise.resolve(found);\n if (this.closedWith) return Promise.reject(new Error(`native: signalling closed (${this.closedWith.code} ${this.closedWith.reason}); \"${type}\" cannot arrive`));\n return new Promise((resolve, reject) => {\n const p = { type, resolve, reject };\n this.pending.push(p);\n setTimeout(() => {\n const i = this.pending.indexOf(p);\n if (i !== -1) {\n this.pending.splice(i, 1);\n reject(new Error(`native: timed out waiting for \"${type}\" (saw: ${this.events.map((e) => e.type).join(\", \") || \"nothing\"})`));\n }\n }, timeoutMs).unref?.();\n });\n }\n\n /**\n * Fetch the ring now and install it when it is newer and from this node generation. `current`\n * when the service holds what we hold; `no-node` when there is no running node to bind keys to\n * (the old ring stays and still seals). Throws on a generation change, after counting it and\n * calling `onGenerationChange`: nothing is installed, close and open again.\n */\n async refreshKeys(): Promise<\"installed\" | \"current\" | \"no-node\"> {\n const outcome = await this.fetchAndInstall();\n if (outcome === \"generation-changed\") throw new Error(\"native: the node changed generation; close and open the session again\");\n return outcome;\n }\n\n private async fetchAndInstall(): Promise<\"installed\" | \"current\" | \"no-node\" | \"generation-changed\"> {\n if (!this.native) throw new Error(\"native: not open\");\n let fetched: NativeKeysResult;\n try {\n fetched = await this.client.request<NativeKeysResult>(`/v1/frequencies/${encodeURIComponent(this.frequencyId)}/native-keys`);\n } catch (err) {\n if (err instanceof Error && (err as { status?: unknown }).status === 409) return \"no-node\";\n throw err;\n }\n if (fetched.bootId !== this.native.bootId) {\n this.resyncStats.generationChanges += 1;\n this.options.onGenerationChange?.();\n return \"generation-changed\";\n }\n if (fetched.keysetId === this.native.channelKeys.keysetId) return \"current\";\n // One assignment, after the fetch resolved: the old ring keeps sealing until the new one is in.\n this.native = { ...this.native, channelKeys: { keysetId: fetched.keysetId, epoch: fetched.epoch, keys: fetched.keys } };\n this.resyncStats.installs += 1;\n return \"installed\";\n }\n\n private onKeysRotated(keysetId: string): void {\n this.resync = this.resync.then(async () => {\n if (!this.native) return;\n if (keysetId === this.native.channelKeys.keysetId) {\n this.resyncStats.alreadyCurrent += 1;\n return;\n }\n const jitter = this.options.resyncJitterMs ?? 1000;\n for (let attempt = 0; attempt < 3; attempt += 1) {\n await sleep(Math.floor(Math.random() * jitter) + attempt * jitter);\n let outcome: Awaited<ReturnType<NativeSession[\"fetchAndInstall\"]>>;\n try {\n outcome = await this.fetchAndInstall();\n } catch {\n continue; // one flaky fetch is not a failure; the bounded retry is\n }\n if (outcome !== \"current\") return; // installed, no node, or a generation change: each is final\n // `current` after a notice naming other material is a stale read: ask again.\n }\n this.resyncStats.failures += 1;\n });\n }\n\n /** Resolves once every queued rotation notice has been acted on. Probes only; a client never blocks on it. */\n async keysSettled(): Promise<void> {\n for (;;) {\n const chain = this.resync;\n await chain;\n if (chain === this.resync) return;\n }\n }\n\n private channelKey(channelId: string): { id: number; key: Buffer } {\n const entry = this.native?.channelKeys.keys[channelId];\n if (!entry) throw new Error(`native: no key for channel ${channelId}`);\n return { id: entry.id, key: Buffer.from(entry.key, \"base64\") };\n }\n\n private transmitSealed(channelId: string, payload: Buffer): void {\n if (!this.native || !this.udp) throw new Error(\"native: not open\");\n // Read the ring ONCE: a resync can swap it between any two statements.\n const ring = this.native.channelKeys;\n const entry = ring.keys[channelId];\n if (!entry) throw new Error(`native: no key for channel ${channelId}`);\n const [host, port] = this.native.udpEndpoint.split(\":\");\n this.sequence += 1n;\n const packet = seal({\n connectionId: this.connection,\n channelNativeId: entry.id,\n keyEpoch: ring.epoch,\n sequence: this.sequence,\n voiceLevel: 128,\n channelKey: Buffer.from(entry.key, \"base64\"),\n senderMacKey: this.senderMacKey,\n payload,\n });\n this.udp.send(packet, Number(port), host);\n }\n\n private sendKeepalive(): void {\n if (!this.homeChannelId) return;\n const payload = Buffer.alloc(PAYLOAD.OPUS_OFFSET);\n payload[PAYLOAD.TYPE_OFFSET] = PAYLOAD_TYPE.keepalive;\n try {\n this.transmitSealed(this.homeChannelId, payload);\n } catch {\n // The ring may be mid-resync; the next tick sends again.\n }\n }\n\n /** Subscribe to a channel's streams (listening). */\n listen(channelId: string): void {\n this.send({ type: \"subscribeChannel\", channelId });\n }\n\n /** Announce a voice stream on the home channel (plus relays), and return its stream id. */\n async startTalking(options: { relayChannelIds?: string[]; sourceKey?: string } = {}): Promise<number> {\n if (!this.homeChannelId) throw new Error(\"native: not open\");\n this.send({ type: \"nativeProduce\", channelId: this.homeChannelId, relayChannelIds: options.relayChannelIds ?? [], sourceKey: options.sourceKey ?? \"agent\", profile: \"voice\" });\n const produced = await this.waitFor(\"nativeProduced\", 10_000);\n this.producing = { streamId: Number(produced.streamId), channelId: this.homeChannelId };\n this.events.splice(this.events.indexOf(produced), 1);\n return this.producing.streamId;\n }\n\n /** One 20 ms Opus frame onto the stream: sealed under the home channel, and each relay, as the contract requires. */\n sendOpusFrame(opus: Buffer, relayChannelIds: string[] = []): void {\n if (!this.producing) throw new Error(\"native: not talking; call startTalking first\");\n const payload = audioPayload(this.producing.streamId, this.timestamp, opus);\n this.timestamp = (this.timestamp + 960) >>> 0;\n for (const channelId of [this.producing.channelId, ...relayChannelIds]) this.transmitSealed(channelId, payload);\n }\n\n stopTalking(): void {\n if (!this.producing) return;\n this.send({ type: \"closeNativeStream\", streamId: this.producing.streamId });\n this.producing = null;\n }\n\n private onPacket(packet: Buffer): void {\n if (!this.native || packet.length < HEADER.LENGTH + AEAD.TAG_BYTES) return;\n if ((packet[HEADER.VERSION_FLAGS_OFFSET]! & 0x0f) !== NATIVE_TRANSPORT_VERSION) {\n this.receiveStats.unsupportedVersion += 1;\n return;\n }\n const connectionId = packet.readUInt32BE(HEADER.CONNECTION_ID_OFFSET);\n const channelNativeId = packet.readUInt32BE(HEADER.CHANNEL_ID_OFFSET);\n const entry = Object.values(this.native.channelKeys.keys).find((k) => k.id === channelNativeId);\n if (!entry) {\n this.receiveStats.unknownChannel += 1;\n return;\n }\n let body: ReturnType<typeof open>;\n try {\n body = open(packet, Buffer.from(entry.key, \"base64\"));\n } catch {\n this.receiveStats.undecryptable += 1;\n this.staleKeyWatch();\n return;\n }\n this.staleRun = 0;\n if (body.type !== PAYLOAD_TYPE.audio) {\n this.receiveStats.notAudio += 1;\n return;\n }\n // Attribution: the AEAD proves a channel member sealed it, never which one; the owner the\n // announcement bound to the stream id is the only check, and a mismatch is dropped.\n const owner = this.owners.get(body.streamId);\n if (owner === undefined || owner !== connectionId) {\n this.receiveStats.misattributed += 1;\n return;\n }\n this.receiveStats.frames += 1;\n const frame: NativeAudioFrame = { streamId: body.streamId, timestamp: body.timestamp, opus: body.opus, connectionId };\n this.options.onAudio?.(frame);\n for (const listener of this.audioListeners) listener(frame);\n }\n\n /**\n * The backstop for a missed `nativeKeysRotated` (the node announces a rotation only once it\n * has a baseline to compare against, so a rotation inside its first poll window is never\n * announced): a run of packets that will not open, with nothing opening since, means the ring\n * is stale on one side, and the cheap cure is to ask for it again. Bounded to one fetch per\n * five seconds; a generation change or a down node is handled as every fetch is.\n */\n private staleKeyWatch(): void {\n this.staleRun += 1;\n if (this.staleRun < STALE_RUN_PACKETS) return;\n const now = Date.now();\n if (now - this.lastStaleRefresh < STALE_REFRESH_MIN_MS) return;\n this.lastStaleRefresh = now;\n this.staleRun = 0;\n this.resyncStats.staleWatchRefreshes += 1;\n this.resync = this.resync.then(() => this.fetchAndInstall().then(() => undefined, () => undefined));\n }\n\n /** Receive every attributed audio frame; returns the detach function. */\n attachAudio(listener: (frame: NativeAudioFrame) => void): () => void {\n this.audioListeners.add(listener);\n return () => this.audioListeners.delete(listener);\n }\n\n /** The owner bound to a stream id, from the announcements. */\n ownerOf(streamId: number): number | undefined {\n return this.owners.get(streamId);\n }\n\n async close(): Promise<void> {\n if (this.keepalive) clearInterval(this.keepalive);\n this.keepalive = null;\n try {\n this.stopTalking();\n } catch {\n // closing anyway\n }\n this.ws?.close();\n this.ws = null;\n this.udp?.close();\n this.udp = null;\n // Closing the signalling socket untunes; membership of the frequency is untouched.\n }\n}\n","/**\n * Frequency numbering.\n *\n * Two tiers share ONE canonical representation — integer kHz — and one uniqueness\n * domain (`Frequency.khz` is DB-unique regardless of mode):\n *\n * - push_to_talk: aviation-style HAM band. Real-world VHF aviation band is\n * 118.000-136.975 MHz in 25kHz steps (760 channels). When the primary band is\n * exhausted we extend into additional simulated bands by continuing the same\n * arithmetic progression (137.000-155.975 is \"Band 2\", etc). These upper bands\n * don't correspond to real spectrum allocations — they exist purely so the system\n * never runs out of numbers.\n * - broadcast: the OPEN dial space (2026-07-20). Stations may take ANY number of the\n * form XXXX.XXX (\"97.9\", \"101.15\", \"1234.567\") — we present the look and feel of\n * radio without its constraints. Auto-allocation walks classic US FM dial numbers\n * (88.1, 88.3, … odd tenths) for authenticity.\n *\n * Storing integer kHz (never floats, never the label string) is what makes duplicate\n * prevention airtight: \"94.5\", \"94.50\" and \"94.500\" all canonicalize to 94500 before\n * they reach the API, so the unique constraint sees one number.\n */\n\nimport { z } from \"zod\";\n\nimport type { DialMode } from \"./domain.js\";\n\nexport const FREQ_STEP_KHZ = 25;\nexport const FREQ_BAND_START_KHZ = 118_000;\nexport const FREQ_BAND_END_KHZ = 136_975;\nexport const FREQ_CHANNELS_PER_BAND =\n (FREQ_BAND_END_KHZ - FREQ_BAND_START_KHZ) / FREQ_STEP_KHZ + 1; // 760\nexport const FREQ_BAND_SPAN_KHZ = FREQ_CHANNELS_PER_BAND * FREQ_STEP_KHZ; // 19,000\n\n// ---- Open dial space (broadcast) ----------------------------------------------------\n\n/** Lowest representable dial number: \"0.100\". */\nexport const DIAL_MIN_KHZ = 100;\n/** Highest representable dial number: \"9999.999\" (4 integer digits, 3 decimals). */\nexport const DIAL_MAX_KHZ = 9_999_999;\nexport function isValidFrequencyKhz(khz: number): boolean {\n if (!Number.isInteger(khz)) return false;\n if (khz < FREQ_BAND_START_KHZ) return false;\n return (khz - FREQ_BAND_START_KHZ) % FREQ_STEP_KHZ === 0;\n}\n\n/** HAM-band rule (push_to_talk frequencies) — alias of isValidFrequencyKhz. */\nexport const isValidHamKhz = isValidFrequencyKhz;\n\n/** Open-dial rule (broadcast frequencies): any on-resolution number in the space. */\nexport function isValidDialKhz(khz: number): boolean {\n return Number.isInteger(khz) && khz >= DIAL_MIN_KHZ && khz <= DIAL_MAX_KHZ;\n}\n\n// ---- Broadcast auto-allocation ------------------------------------------------------\n\n/**\n * The simulated dial that broadcast numbers are auto-allocated across, as an EXCLUSIVE\n * open interval — neither bound is ever handed out.\n *\n * Deliberately unconstrained by real FM regulation (2026-07-22 product decision). The\n * dial only has to *look* like FM; it is not bound by it, so stations may sit at 97.1,\n * 97.11, 97.01 or 97.111 alike, and the range is free to run up into the numbers the\n * push-to-talk band also uses. That overlap is cosmetic, not a collision: `khz` is unique\n * across both modes, so whoever asks first gets the number.\n */\nexport const BROADCAST_ALLOC_MIN_KHZ = 0;\nexport const BROADCAST_ALLOC_MAX_KHZ = 122_000;\n\n/**\n * The order broadcast numbers are handed out in: repeated halving of the open interval.\n *\n * Sequential allocation from one end put the first stations shoulder to shoulder —\n * 88.1, 88.3, 88.5 — which reads as a broken dial when a handful of stations exist, and\n * it is exactly the situation the platform is in today. Halving spreads them instead:\n * over (0, 122.000) the first is 61.000, then 30.500 and 91.500, then 15.250, 45.750,\n * 76.250 and 106.750, each level splitting every gap the previous one left.\n *\n * Yields ASCENDING within a level. The order across a level is arbitrary for spacing\n * purposes — every point at a given level is equidistant from its neighbours — so the\n * simplest predictable order wins.\n *\n * Ends when a level's spacing would fall below the 1 kHz dial resolution; by then the\n * interval is saturated and the caller backfills (see nextBroadcastKhz).\n */\nexport function* bisectingDialSequence(minKhz: number, maxKhz: number): Generator<number> {\n const span = maxKhz - minKhz;\n if (span < 2) return;\n for (let denominator = 2; denominator <= span; denominator *= 2) {\n for (let numerator = 1; numerator < denominator; numerator += 2) {\n const khz = minKhz + Math.round((span * numerator) / denominator);\n // Rounding at fine levels can land on the same integer twice, or below the lowest\n // representable dial number when the interval starts at 0. Both are the caller's\n // problem to skip, but filtering the invalid ones here keeps that caller simple.\n if (isValidDialKhz(khz)) yield khz;\n }\n }\n}\n\n/**\n * The next free broadcast number: the halving sequence first, then a linear backfill of\n * whatever it skipped, then upward past the interval once nothing is left inside it.\n *\n * `used` is every number already taken IN EITHER MODE — one uniqueness domain.\n */\nexport function nextBroadcastKhz(\n used: ReadonlySet<number>,\n minKhz: number = BROADCAST_ALLOC_MIN_KHZ,\n maxKhz: number = BROADCAST_ALLOC_MAX_KHZ,\n): number {\n for (const khz of bisectingDialSequence(minKhz, maxKhz)) {\n if (!used.has(khz)) return khz;\n }\n // Backfill: the sequence visits every integer in a saturated interval, but rounding\n // collisions mean a few can be missed. Sweep for them before leaving the dial.\n for (let khz = Math.max(minKhz + 1, DIAL_MIN_KHZ); khz < maxKhz; khz++) {\n if (!used.has(khz)) return khz;\n }\n // The simulated dial is full. Keep climbing — the space runs to DIAL_MAX_KHZ, which is\n // where \"expand into the push-to-talk range\" actually happens.\n for (let khz = maxKhz; khz <= DIAL_MAX_KHZ; khz++) {\n if (!used.has(khz)) return khz;\n }\n throw new Error(\"No broadcast dial number is free.\");\n}\n\n// ---- Published band plans -----------------------------------------------------------\n\n/**\n * Everything a client needs to render and traverse a dial, without hardcoding any of it.\n *\n * These rules previously lived only in this file and were never served, so every consumer\n * had to guess: the Tuner assumed the aviation band applied to all frequencies and\n * rendered an 88.1 FM station as 126.1. Served over `GET /platform/config`.\n */\nexport interface BandPlan {\n mode: \"push_to_talk\" | \"broadcast\";\n /** Lowest tunable kHz. */\n minKhz: number;\n /** Highest tunable kHz, inclusive. */\n maxKhz: number;\n /**\n * Channel grid. `null` means a continuous dial with no snap grid (broadcast stations may\n * take any integer kHz), in which case a UI should use `dialResolutionKhz` as its finest\n * step.\n */\n gridStepKhz: number | null;\n /** Finest addressable increment — always 1 kHz, since kHz is the canonical unit. */\n dialResolutionKhz: number;\n /**\n * How the server picks the next free number.\n *\n * `sequential` walks `allocationStartKhz` upward in `allocationStepKhz` increments.\n * `bisecting` repeatedly halves the open interval\n * (`allocationWindowMinKhz`, `allocationWindowMaxKhz`), so a sparsely-populated dial\n * stays spread out instead of clustering at one end.\n *\n * Informational: a client cannot predict its own number, because allocation resolves\n * against every number in use across BOTH modes at the moment of the request.\n */\n allocationStrategy: \"sequential\" | \"bisecting\";\n /** `sequential` only — null when bisecting. */\n allocationStartKhz: number | null;\n allocationStepKhz: number | null;\n /** `bisecting` only, exclusive at both ends — null when sequential. */\n allocationWindowMinKhz: number | null;\n allocationWindowMaxKhz: number | null;\n /**\n * Width of the primary band. push_to_talk numbering continues past `maxKhz` into\n * further simulated bands in multiples of this (Band 2 = 137.000-155.975, etc), so\n * `maxKhz` is the end of Band 1, not a hard ceiling. `null` for a continuous dial.\n */\n bandSpanKhz: number | null;\n /** Channels in the primary band; `null` for a continuous dial. */\n channelsPerBand: number | null;\n /** Decimal places in the canonical label. */\n labelDecimals: number;\n /** Whether the label trims trailing zeros (\"97.9\") or keeps them (\"118.000\"). */\n labelTrimsTrailingZeros: boolean;\n /** True when a dial UI should wrap around from `maxKhz` back to `minKhz`. */\n circular: boolean;\n}\n\n/**\n * The runtime description of BandPlan, used to document and serialise `/platform/config`.\n *\n * The interface above stays the thing code is written against; this exists because a\n * TypeScript interface cannot be turned into an OpenAPI schema or checked at a service\n * boundary. The two are pinned together by the assertions below, so adding a field to one\n * and forgetting the other is a compile error rather than a field that silently vanishes\n * from the served config — which is precisely the class of bug that had the Tuner guessing\n * at the band plan in the first place.\n */\nexport const BandPlanSchema = z.object({\n mode: z.enum([\"push_to_talk\", \"broadcast\"]),\n minKhz: z.number().int().describe(\"Lowest tunable kHz.\"),\n maxKhz: z.number().int().describe(\"Highest tunable kHz, inclusive.\"),\n gridStepKhz: z.number().int().nullable().describe(\"Channel grid; null means a continuous dial with no snap grid.\"),\n dialResolutionKhz: z.number().int().describe(\"Finest addressable increment — always 1, since kHz is the canonical unit.\"),\n allocationStrategy: z\n .enum([\"sequential\", \"bisecting\"])\n .describe(\n \"How the server picks the next free number. `sequential` walks allocationStartKhz upward in allocationStepKhz increments. \" +\n \"`bisecting` repeatedly halves the open interval (allocationWindowMinKhz, allocationWindowMaxKhz), keeping a sparse dial spread out. \" +\n \"Informational only: a number cannot be predicted client-side, since allocation resolves against everything in use across both modes.\",\n ),\n allocationStartKhz: z.number().int().nullable().describe(\"Sequential only; null when bisecting.\"),\n allocationStepKhz: z.number().int().nullable().describe(\"Sequential only; null when bisecting.\"),\n allocationWindowMinKhz: z.number().int().nullable().describe(\"Bisecting only, exclusive; null when sequential.\"),\n allocationWindowMaxKhz: z.number().int().nullable().describe(\"Bisecting only, exclusive; null when sequential.\"),\n bandSpanKhz: z.number().int().nullable().describe(\"Width of the primary band; numbering continues past maxKhz in multiples of this. Null for a continuous dial.\"),\n channelsPerBand: z.number().int().nullable().describe(\"Channels in the primary band; null for a continuous dial.\"),\n labelDecimals: z.number().int().describe(\"Decimal places in the canonical label.\"),\n labelTrimsTrailingZeros: z.boolean().describe('Whether the label trims trailing zeros (\"97.9\") or keeps them (\"118.000\").'),\n circular: z.boolean().describe(\"True when a dial UI should wrap from maxKhz back to minKhz.\"),\n});\n\n// Bidirectional: neither type may gain a field the other lacks. Assigning in both\n// directions is what makes it bidirectional — a one-way check would still permit the\n// schema to quietly drop a field.\ntype _SchemaMatchesInterface = z.infer<typeof BandPlanSchema> extends BandPlan ? true : never;\ntype _InterfaceMatchesSchema = BandPlan extends z.infer<typeof BandPlanSchema> ? true : never;\nconst _bandPlanShapesAgree: [_SchemaMatchesInterface, _InterfaceMatchesSchema] = [true, true];\nvoid _bandPlanShapesAgree;\n\nexport const BandPlansSchema = z.object({\n push_to_talk: BandPlanSchema,\n broadcast: BandPlanSchema,\n});\n\nexport const BAND_PLANS: Record<DialMode, BandPlan> = {\n push_to_talk: {\n mode: \"push_to_talk\",\n minKhz: FREQ_BAND_START_KHZ,\n maxKhz: FREQ_BAND_END_KHZ,\n gridStepKhz: FREQ_STEP_KHZ,\n dialResolutionKhz: 1,\n allocationStrategy: \"sequential\",\n allocationStartKhz: FREQ_BAND_START_KHZ,\n allocationStepKhz: FREQ_STEP_KHZ,\n allocationWindowMinKhz: null,\n allocationWindowMaxKhz: null,\n bandSpanKhz: FREQ_BAND_SPAN_KHZ,\n channelsPerBand: FREQ_CHANNELS_PER_BAND,\n labelDecimals: 3,\n labelTrimsTrailingZeros: false,\n circular: true,\n },\n broadcast: {\n mode: \"broadcast\",\n minKhz: DIAL_MIN_KHZ,\n maxKhz: DIAL_MAX_KHZ,\n gridStepKhz: null, // open dial: any integer kHz is a valid station number\n dialResolutionKhz: 1,\n allocationStrategy: \"bisecting\",\n allocationStartKhz: null,\n allocationStepKhz: null,\n allocationWindowMinKhz: BROADCAST_ALLOC_MIN_KHZ,\n allocationWindowMaxKhz: BROADCAST_ALLOC_MAX_KHZ,\n bandSpanKhz: null,\n channelsPerBand: null,\n labelDecimals: 3,\n labelTrimsTrailingZeros: true,\n circular: false,\n },\n};\n\nexport function bandNumberForKhz(khz: number): number {\n return Math.floor((khz - FREQ_BAND_START_KHZ) / FREQ_BAND_SPAN_KHZ) + 1;\n}\n\n/** Converts an allocation index (0-based, across all bands) to a kHz value. */\nexport function indexToKhz(index: number): number {\n return FREQ_BAND_START_KHZ + index * FREQ_STEP_KHZ;\n}\n\n/** Inverse of indexToKhz; throws on invalid (non-grid-aligned) input. */\nexport function khzToIndex(khz: number): number {\n if (!isValidFrequencyKhz(khz)) {\n throw new Error(`${khz} is not a valid frequency (must be on the 25kHz grid from ${FREQ_BAND_START_KHZ})`);\n }\n return (khz - FREQ_BAND_START_KHZ) / FREQ_STEP_KHZ;\n}\n\n/** Formats a kHz integer as \"121.500\" (aviation MHz notation, 3 decimals). */\nexport function formatFrequencyKhz(khz: number): string {\n const mhz = khz / 1000;\n return mhz.toFixed(3);\n}\n\n/** Parses a \"121.500\" (or \"121.5\") style string back into integer kHz. Returns null if invalid/off-grid. */\nexport function parseFrequencyLabel(label: string): number | null {\n const khz = parseDialLabel(label);\n if (khz === null || !isValidFrequencyKhz(khz)) return null;\n return khz;\n}\n\n/**\n * Shorthand-tolerant open-dial parse: \"97.9\" → 97900, \"118\" → 118000, \"0094.500\" →\n * 94500. Always MHz notation — \"979\" means 979.000 MHz, NOT 97.9. Equivalent spellings\n * canonicalize to the same integer (\"94.5\" ≡ \"94.50\" ≡ \"94.500\"), which is what makes\n * the DB unique constraint reject look-alike duplicates. Returns null on invalid input.\n */\nexport function parseDialLabel(label: string): number | null {\n const trimmed = label.trim();\n if (!/^\\d{1,4}(\\.\\d{1,3})?$/.test(trimmed)) return null;\n const mhz = Number.parseFloat(trimmed);\n if (Number.isNaN(mhz)) return null;\n const khz = Math.round(mhz * 1000);\n if (!isValidDialKhz(khz)) return null;\n return khz;\n}\n\n/**\n * Mode-aware canonical display. push_to_talk keeps the aviation 3-decimal look\n * (\"118.000\"); broadcast trims trailing zeros but keeps at least one decimal so it\n * reads like a dial position (\"97.9\", \"101.15\", \"100.0\").\n */\nexport function formatDialKhz(khz: number, mode: DialMode): string {\n if (mode === \"push_to_talk\") return formatFrequencyKhz(khz);\n const fixed = formatFrequencyKhz(khz); // \"97.900\"\n const trimmed = fixed.replace(/0+$/, \"\");\n return trimmed.endsWith(\".\") ? `${trimmed}0` : trimmed;\n}\n\n/**\n * Is a frequency listed to people who are not members of it?\n *\n * BROADCAST — DERIVED, never stored. A broadcast station is a station: being on the\n * broadcast dial IS the listing. It is listed unless its owner gated it with an access\n * code, which is already the one privacy lever a user actually sets (\"Presence of a code\n * makes the frequency private\" — CreateFrequencyBodySchema).\n *\n * That replaced the stored `publiclyListable` flag for broadcast (2026-07-27). The flag\n * had no UI anywhere and defaults to false, so in practice EVERY station was invisible to\n * the anonymous directory while every signed-in user already saw the whole broadcast dial\n * through `/frequencies/public` — which had long since stopped consulting the flag for\n * exactly this reason. Two overlapping notions of \"private\", one of them dead, and the\n * two dial endpoints disagreeing about the same station.\n *\n * PUSH-TO-TALK — the stored flag, unchanged. A personal frequency without a code is NOT\n * thereby public: the number itself is the invite, and strangers must not be able to\n * browse or request to join it just because its owner set no code.\n *\n * Lives here rather than in the control plane because the admin plane reports the same\n * answer from its own Prisma client, and a duplicated one-liner would drift.\n */\nexport function isPubliclyListed(frequency: {\n mode: DialMode;\n publiclyListable: boolean;\n hasAccessCode: boolean;\n}): boolean {\n if (frequency.mode === \"broadcast\") return !frequency.hasAccessCode;\n return frequency.publiclyListable;\n}\n","/**\n * Merchant/billing contracts (2026-07-19; Stripe wired 2026-07-20): plan constants and\n * entitlement keys shared by the control plane's entitlement seam (server\n * billing/entitlements.ts) and client copy. Stripe is the payment provider — checkout is\n * embedded in the client, enforcement is server-side behind BILLING_ENFORCED.\n */\n\nimport type { FrequencyMode } from \"./domain.js\";\n\n// The company. The service is \"Frequency Talk\"; \"Frequency\" is the flagship client app.\nexport const COMPANY_NAME = \"Frequency Talk Technologies LLC\";\n\nexport type PlanKey = \"operator\" | \"broadcast\";\n\nexport const PLANS = {\n // Personal push-to-talk frequency.\n operator: { key: \"operator\", name: \"Operator\", priceUsdCents: 999, per: \"frequency\" },\n // Organization-owned broadcast (program audio) frequency.\n broadcast: { key: \"broadcast\", name: \"Broadcast\", priceUsdCents: 3999, per: \"frequency\" },\n} as const satisfies Record<PlanKey, { key: PlanKey; name: string; priceUsdCents: number; per: \"frequency\" }>;\n\nexport function formatPlanPrice(plan: PlanKey): string {\n const cents = PLANS[plan].priceUsdCents;\n return `$${(cents / 100).toFixed(2)}`;\n}\n\n/**\n * What a customer is told they will pay, as opposed to what the plan costs us to state.\n *\n * Sales tax is charged ON TOP of the listed price (owner decision 2026-08-28: $9.99 is the\n * base the company must net, so tax must not be carved out of it — the Stripe Prices carry\n * `tax_behavior: \"exclusive\"` to match, permanently, since Stripe lets that move only once).\n * Every surface that quotes a price therefore has to say so: quoting a flat $9.99 and then\n * charging $10.56 is a bait-and-switch, and on a subscription with a free trial it is exactly\n * what card networks and consumer-protection rules examine.\n *\n * ONE function rather than the suffix typed at each of the eight call sites, because the eight\n * are what drift: five in the client's BillingTab, ModeSwitchSection, the server's 402\n * SUBSCRIPTION_REQUIRED message and the marketing pricing page. The exact figure is deliberately\n * NOT computed here — it depends on the buyer's address and only Stripe knows it. It appears on\n * the invoice and the receipt, which is honest and needs no tax calculation at quote time.\n */\nexport const TAX_SUFFIX = \"+ tax\";\n\nexport function formatPlanPriceWithTax(plan: PlanKey): string {\n return `${formatPlanPrice(plan)} ${TAX_SUFFIX}`;\n}\n\n// Entitlement keys as checked by the server's requireEntitlement seam.\nexport const ENTITLEMENTS = {\n operatorFrequency: \"frequency.operator\",\n broadcastFrequency: \"frequency.broadcast\",\n} as const;\nexport type EntitlementKey = (typeof ENTITLEMENTS)[keyof typeof ENTITLEMENTS];\n\n// A frequency mode that somebody pays for. `direct` (a 1:1 call) is excluded BY TYPE\n// rather than by a runtime check, so there is no \"skip billing for calls\" branch anywhere\n// to forget or to get wrong — a call has no plan, and PLAN_FOR_MODE cannot be asked for\n// one. The public create route reinforces it independently: CreateFrequencyBodySchema.mode\n// cannot express `direct`, so requireEntitlement is unreachable, not skipped.\nexport type BillableFrequencyMode = Exclude<FrequencyMode, \"direct\">;\n\n// Which plan pays for a frequency of a given mode — the 402 SUBSCRIPTION_REQUIRED\n// response and the client's upgrade view both key off this.\nexport const PLAN_FOR_MODE = {\n push_to_talk: \"operator\",\n broadcast: \"broadcast\",\n} as const satisfies Record<BillableFrequencyMode, PlanKey>;\n\nexport const ENTITLEMENT_FOR_PLAN = {\n operator: ENTITLEMENTS.operatorFrequency,\n broadcast: ENTITLEMENTS.broadcastFrequency,\n} as const satisfies Record<PlanKey, EntitlementKey>;\n\n// Stripe price lookup_keys — the idempotency handle scripts/stripe-setup.ts finds or\n// creates Prices by. Env vars (STRIPE_PRICE_*) carry the resolved price IDs at runtime;\n// these keys are how those IDs get minted per sandbox/live environment.\nexport const STRIPE_LOOKUP_KEYS = {\n operator: \"operator_monthly\",\n broadcast: \"broadcast_monthly\",\n} as const satisfies Record<PlanKey, string>;\n\n// One-time coupon applied to the first Broadcast invoice on an operator→broadcast\n// upgrade: the already-paid operator month is credited in full (owner rule 2026-08-01 —\n// the flat monthly total, not a time proration). Fixed id so every Stripe environment\n// can find-or-create it idempotently (scripts/stripe-setup.ts, plus a lazy ensure at\n// upgrade time in billing/planChange.ts).\nexport const STRIPE_UPGRADE_CREDIT_COUPON_ID = \"operator-upgrade-credit\";\n\n// Card is collected at checkout; first charge lands after the trial.\nexport const TRIAL_DAYS = 14;\n\n// Stripe subscription statuses, recorded verbatim in Subscription.status.\nexport type SubscriptionStatus =\n | \"incomplete\"\n | \"incomplete_expired\"\n | \"trialing\"\n | \"active\"\n | \"past_due\"\n | \"canceled\"\n | \"unpaid\"\n | \"paused\";\n\n// Statuses eligible to CLAIM a new frequency slot. `past_due` still keeps an\n// already-claimed frequency working and cannot claim a fresh one — but note that is now a\n// GRACE WINDOW, not the end of the story: since 0.36.0, a subscription reaching `canceled`\n// suspends every frequency it paid for (billing/sync.ts\n// suspendFrequenciesForEndedSubscription), which SUPERSEDES the record-only lapse policy of\n// 2026-07-20. Under that policy a lapsed subscription was recorded and never enforced, so an\n// unpaid station stayed on the air indefinitely and nobody found out.\n//\n// So the sequence is: payment fails -> past_due, station keeps working while Stripe retries\n// (8 attempts over 2 weeks) -> canceled, station suspended, owner can re-enable it whenever\n// they pay again.\nexport const ENTITLING_STATUSES = [\"active\", \"trialing\"] as const;\n","/**\n * Phone numbers (the PSTN service, 2026-10-21; design: docs/work-orders/phone-numbers.md).\n *\n * A customer buys a US number from us and it becomes a `phone` channel on one of their\n * frequencies. Whoever dials it is heard on that channel; whoever is armed on the channel\n * talks back. The line itself is a synthetic user (`<e164>@pstn.invalid`, `users.kind =\n * line`), so the caller appears in rosters and in \"Users Transmitting\" as the line and every\n * routing rule applies unchanged.\n *\n * Phase 1 (this file's first version) is numbers and channels with no audio; the call\n * surface lands in phase 2 and billing in phase 3. The plan constants below are the agreed\n * price list (owner, 2026-09-19) and are not seeded into Stripe until phase 3.\n */\n\nimport { z } from \"zod\";\n\n/** Only US numbers are sold (owner, 2026-09-19). NANP: +1, then an area code and an exchange\n * that both start 2-9. */\nexport const US_E164_PATTERN = /^\\+1[2-9]\\d{2}[2-9]\\d{6}$/;\n\nexport function isUsE164(value: string): boolean {\n return US_E164_PATTERN.test(value);\n}\n\n/** `+18035550100` -> `(803) 555-0100`. Anything that is not a US E.164 number is returned as is. */\nexport function formatUsNumber(e164: string): string {\n if (!isUsE164(e164)) return e164;\n return `(${e164.slice(2, 5)}) ${e164.slice(5, 8)}-${e164.slice(8)}`;\n}\n\n/** Three digits, first 2-9: the NANP area-code shape, which is what a search is keyed by.\n * A pattern rather than a schema on purpose: a shared `*Schema` export becomes an OpenAPI\n * component, and a `$ref` inside a QUERY parameter crashes the spec generator. */\nexport const AREA_CODE_PATTERN = /^[2-9]\\d{2}$/;\n\nexport const PhoneCarrierSchema = z.enum([\"telnyx\", \"fake\"]);\nexport type PhoneCarrier = z.infer<typeof PhoneCarrierSchema>;\n\n// pending: ordered at the carrier, not yet confirmed active (an alert fires past 10 minutes).\n// active: ours, routed to its channel.\n// releasing: release requested; the carrier has not confirmed. The row survives the\n// frequency's deletion in this state so a failed release is never forgotten.\n// released: gone from the carrier; the row is history.\nexport const PhoneNumberStatusSchema = z.enum([\"pending\", \"active\", \"releasing\", \"released\"]);\nexport type PhoneNumberStatus = z.infer<typeof PhoneNumberStatusSchema>;\n\nexport const PhoneNumberSchema = z.object({\n id: z.string(),\n e164: z.string().describe(\"The number in E.164 form, e.g. +18035550100.\"),\n display: z.string().describe(\"The number formatted for a person: (803) 555-0100.\"),\n frequencyId: z.string().nullable().describe(\"Null once the frequency it lived on is gone.\"),\n channelId: z.string().nullable().describe(\"The `phone` channel carrying this line; null after release.\"),\n lineUserId: z.string().nullable().describe(\"The synthetic user the line appears as in rosters; null once released.\"),\n status: PhoneNumberStatusSchema,\n carrier: PhoneCarrierSchema,\n purchasedByUserId: z.string().nullable(),\n createdAt: z.string(),\n activatedAt: z.string().nullable(),\n releasedAt: z.string().nullable(),\n});\nexport type PhoneNumber = z.infer<typeof PhoneNumberSchema>;\n\n/** What a channel row carries about its line, so a board draws the lamp without a second read. */\nexport const ChannelPhoneSummarySchema = z.object({\n phoneNumberId: z.string(),\n e164: z.string(),\n display: z.string(),\n status: PhoneNumberStatusSchema,\n});\nexport type ChannelPhoneSummary = z.infer<typeof ChannelPhoneSummarySchema>;\n\nexport const AvailablePhoneNumberSchema = z.object({\n e164: z.string(),\n display: z.string(),\n locality: z.string().nullable().describe(\"City, when the carrier reports one.\"),\n region: z.string().nullable().describe(\"State, two letters, when the carrier reports one.\"),\n});\nexport type AvailablePhoneNumber = z.infer<typeof AvailablePhoneNumberSchema>;\n\nexport const BuyPhoneNumberBodySchema = z.object({\n e164: z.string().regex(US_E164_PATTERN, \"Only US numbers in E.164 form (+1 and ten digits) can be bought.\"),\n /** The channel's name on the board. Defaults to the formatted number. */\n name: z.string().trim().min(1).max(64).optional(),\n});\nexport type BuyPhoneNumberBody = z.infer<typeof BuyPhoneNumberBodySchema>;\n\n/** Checked by the control plane's phone entitlement seam; a plan key in `PHONE_PLANS`. */\nexport const PHONE_LINE_ENTITLEMENT = \"phone.line\" as const;\n\nexport type PhonePlanKey = \"phone_basic\" | \"phone_plus\" | \"phone_pro\";\n\n/** Per number, per month. Minutes cover inbound and outbound alike, rounded up per call. */\nexport const PHONE_PLANS = {\n phone_basic: { key: \"phone_basic\", name: \"Phone Line Basic\", priceUsdCents: 999, minutes: 300 },\n phone_plus: { key: \"phone_plus\", name: \"Phone Line Plus\", priceUsdCents: 1999, minutes: 1000 },\n phone_pro: { key: \"phone_pro\", name: \"Phone Line Pro\", priceUsdCents: 3999, minutes: 3000 },\n} as const satisfies Record<PhonePlanKey, { key: PhonePlanKey; name: string; priceUsdCents: number; minutes: number }>;\n\nexport const PHONE_PLAN_KEYS = Object.keys(PHONE_PLANS) as PhonePlanKey[];\n\n/** One-time, non-expiring minute packs added to a line's bucket. */\nexport const PHONE_MINUTE_PACKS = [\n { key: \"phone_pack_250\", name: \"250 minutes\", priceUsdCents: 499, minutes: 250 },\n { key: \"phone_pack_1000\", name: \"1,000 minutes\", priceUsdCents: 1499, minutes: 1000 },\n { key: \"phone_pack_3000\", name: \"3,000 minutes\", priceUsdCents: 3499, minutes: 3000 },\n] as const;\n\n/** Stripe price lookup_keys for phase 3's seeder; listed now so the contract can name them. */\nexport const PHONE_STRIPE_LOOKUP_KEYS = {\n phone_basic: \"phone_basic_monthly\",\n phone_plus: \"phone_plus_monthly\",\n phone_pro: \"phone_pro_monthly\",\n} as const satisfies Record<PhonePlanKey, string>;\n","import { z } from \"zod\";\nimport { UserKindSchema } from \"./userKind.js\";\n\n/* ------------------------------------------------------------------------ *\n * Contacts, presence status, the chat relay, waves, and direct calls.\n *\n * The one social layer that is NOT mediated by a frequency. Everything else in\n * this platform reaches a person through a Membership; this reaches them\n * directly, which is why every capability here is gated on a MUTUAL contact\n * edge and nothing at all is exposed on a one-way one.\n * ------------------------------------------------------------------------ */\n\n/**\n * The ceiling on one account's contact list.\n *\n * Not a product limit borrowed from Steam (250) for the sake of it — it is the\n * bound on the presence fan-out. A connect edge publishes one user-lane envelope\n * per reachable contact, and that is the platform's first fan-out proportional to\n * a social graph rather than to an edge (docs/realtime-scale.md §2). Enforced on\n * BOTH sides at accept, because the pair is written as two rows and a cap checked\n * on one side only would let the requester's list grow past it.\n */\nexport const MAX_CONTACTS = 250;\n\n/** How long a pending request stays actionable before the sweeper retires it. */\nexport const CONTACT_REQUEST_TTL_DAYS = 30;\n\n/* ---------------------------------- chat --------------------------------- */\n\n/**\n * The chat relay holds messages ONLY long enough to deliver them, and never in\n * Postgres. A recipient who is offline or backgrounded gets their buffer drained\n * on the next connect; after this it is gone.\n *\n * This is a relay, not a mailbox: the server keeps no row and there is no history\n * endpoint to add later without reopening that decision. A transcript exists only\n * where a CLIENT keeps one on the user's own machine (the Service Manager does, opt-out,\n * in IndexedDB), and moves between apps only as an exported archive (contract §15).\n */\nexport const CHAT_BUFFER_TTL_SECONDS = 600;\n\n/** Messages retained per conversation per recipient. Oldest dropped (LTRIM). */\nexport const CHAT_BUFFER_MAX = 50;\n\n/** Longest a single message may be, in bytes of UTF-8. */\nexport const MAX_MESSAGE_BYTES = 2000;\n\n/**\n * How long a send stays idempotent under its clientMessageId. A client that\n * retries after a timeout must not double-post: with no history, a duplicate can\n * never be corrected after the fact.\n */\nexport const CHAT_IDEMPOTENCY_TTL_SECONDS = 120;\n\n/* ---------------------------------- wave --------------------------------- */\n\n/**\n * Per-PAIR cooldown on waves. The per-account rate limit\n * (RealtimeLimits.waveSendsPerMinute) stops a broadcast spray; this stops one\n * person being poked repeatedly, which is where the harm actually is.\n */\nexport const WAVE_COOLDOWN_SECONDS = 3600;\n\n/* ---------------------------------- calls -------------------------------- */\n\n/**\n * How long a call rings before it times out.\n *\n * This is the ONLY latency a caller ever observes on an unanswered call, because\n * there is no ring acknowledgement: telling the caller \"it's ringing\" would\n * reveal that the callee has a live socket, which is precisely what `invisible`\n * exists to hide. Busy and blocked are masked the same way — refused visibly only\n * when the callee is already visible to the caller, and otherwise left to ring out.\n */\nexport const CALL_RING_SECONDS = 45;\n\n/**\n * How long a call rings at a recipient before their ANSWERING MACHINE picks it up.\n *\n * The owner asked for *\"the 4 or 5 rings\"* a telephone gives you, and this number is\n * DERIVED from that rather than chosen to sound about right: every ring clip in the\n * library is exactly 2.6 s long, because for a looping category the file length IS the\n * cadence (`tools/make-sounds.py`, CATEGORIES). Five rings is 13.0 s.\n *\n * ⚠️ **It is a deadline on the ring, not a second timer, and the difference matters after\n * a socket gap.** The recipient's client measures it from the ring's own `expiresAt` minus\n * `CALL_RING_SECONDS`, so a client that reconnects mid-ring picks up at the moment the\n * caller has actually been waiting that long, rather than 13 s after it happened to find\n * out. A client that started a fresh timer would answer a call that had been ringing for\n * 40 s as though it had just arrived.\n *\n * ⚠️ **Well under `CALL_RING_SECONDS`, and that gap is not slack — it is the whole\n * behaviour for anyone with the machine switched OFF.** Those calls ring the full 45 s and\n * are then simply over, which is what the owner asked for: *\"if they don't have answer\n * machine on it just rings till the person hangs up just like a phone would.\"*\n */\nexport const CALL_AUTOANSWER_SECONDS = 13;\n\n/**\n * The longest message the answering machine will take, after which it hangs up — the\n * SHIPPED DEFAULT, not the live value. The account carries `voicemailMaxSeconds`.\n *\n * A cap rather than a silence detector alone, because silence is not a reliable end of\n * message: a caller thinking mid-sentence and a caller who has walked away sound\n * identical for several seconds, and the recording lives in the recipient's own browser\n * storage where an unbounded one is a real cost to a real person's disk.\n *\n * ⚠️ **It is also the machine's HANGUP DEADLINE, which is a different job from bounding a\n * file and is why it may never be unlimited.** The machine holds a real call open: a media\n * container, a slot on a media host, and the caller's own line. Owner, 2026-09-23, after a\n * machine that could not speak also never hung up: *\"we need to set a max length, and let\n * them set it in the settings.\"*\n */\nexport const VOICEMAIL_MAX_SECONDS = 120;\n\n/** The shortest and longest a person may set their own message cap to. */\nexport const VOICEMAIL_MIN_SETTABLE_SECONDS = 15;\nexport const VOICEMAIL_MAX_SETTABLE_SECONDS = 300;\n\n/**\n * How long the caller may say nothing before the machine decides they are finished.\n *\n * Generous on purpose. Cutting somebody off mid-thought is the failure everyone has\n * experienced from an answering machine, and the length cap above is what bounds the\n * pathological case.\n */\nexport const VOICEMAIL_SILENCE_SECONDS = 6;\n\n/**\n * The most people one call may hold, counting the host — the BOOT DEFAULT, not the live\n * value. An operator moves it from the admin console (Settings → Realtime limits →\n * `callMaxParticipants`); the control plane reads `getCallLimits()`, never this constant.\n *\n * ⚠️ **This is a CAPACITY decision wearing a constant, not a UI preference.** A call is a\n * Frequency, a Frequency takes a 20-port RTC slot on a media host, and multiplexing several\n * calls into one container is forbidden by the one-container-per-frequency model — so the\n * standing ceiling is ~50 concurrent calls per media host. Group calling *improves* that\n * ratio (eight people in one call is one slot where four pairs would be four), but it raises\n * per-container CPU, and call waiting doubles a user's container footprint for as long as\n * they hold one call and talk on another.\n *\n * Raising it is no longer an untracked capacity risk: the media container is SIZED from\n * this number (`provisioner/resources.ts`), so a bigger room asks for a bigger container\n * rather than quietly getting a two-person one. What raising it can still do is ask for\n * more CPU than the media host physically has, which is clamped and logged rather than\n * failing the provision. The bound on the lever is `REALTIME_LIMIT_FIELDS`' range.\n */\nexport const CALL_MAX_PARTICIPANTS = 8;\n\n/**\n * The highest `callMaxParticipants` an operator may set, and therefore the widest roster\n * the wire schema accepts.\n *\n * The REQUEST schema is validated against this ceiling rather than against the live\n * setting, because a zod schema is built once at boot and a lever that only takes effect\n * on restart is not a lever. The live number is enforced a layer down, in `placeCall` /\n * `inviteToCall`, where it is read once per call — so over-capacity is a `CallFullError`\n * naming the real number, and only an absurd roster is a schema rejection.\n */\nexport const CALL_MAX_PARTICIPANTS_CEILING = 16;\n\n/**\n * How many calls may be ringing at one person at once — again the boot default; the live\n * value is `getCallLimits().maxPendingRings`.\n *\n * Call waiting is exactly the relaxation of \"the one call ringing at me\" to \"the calls\n * ringing at me\", so this number is what stops that becoming a way to fill somebody's\n * screen with rings. One held call plus one arriving is the phone semantics being emulated;\n * the third is the margin that keeps a race from refusing a legitimate second call.\n */\nexport const CALL_MAX_PENDING_RINGS = 3;\n\n/**\n * The highest `callMaxPendingRings` an operator may set — and therefore the most rings a\n * CLIENT must be prepared to show at once.\n *\n * ⚠️ **A client bounding its own ring list by `CALL_MAX_PENDING_RINGS` would re-create the\n * bug that made the list necessary.** That constant is the boot DEFAULT; an operator who\n * raises the live lever gets rings the server considers legitimate and the client silently\n * drops — a missed call, with nothing on screen and nothing in a log. So the client bounds\n * by this ceiling, which no live setting can exceed, and the server's own limit is what\n * decides how many actually arrive.\n *\n * Ten rather than a round hundred because the bound is a defence against a runaway, not a\n * product number: past a handful, a screen of rings is unanswerable anyway.\n */\nexport const CALL_MAX_PENDING_RINGS_CEILING = 10;\n\n/* ---------------------------------- types -------------------------------- */\n\n/**\n * The status a user CHOSE. `offline` is deliberately not a member: it is the\n * absence of a socket, not a choice. \"Appear offline while connected\" IS\n * `invisible`, and two names for one state is drift. (A client picker may still\n * offer an \"Offline\" entry — it maps to `invisible` plus refuse-incoming.)\n *\n * `busy` is the only member with TEETH: it is not a label, it is a refusal, and\n * incoming calls, chats and waves are rejected at SEND time rather than held\n * (owner rule, 2026-09-01 — \"we don't hold it, because we don't accept it\"). It\n * is also the only one the platform can set on your behalf, from a live broadcast\n * stream; see `presence/status.ts`. `away` refuses waves only — a greeting wants\n * somebody there to receive it, while a message can sit unread.\n */\nexport const UserStatusSchema = z.enum([\"online\", \"away\", \"busy\", \"invisible\"]);\nexport type UserStatus = z.infer<typeof UserStatusSchema>;\n\n/**\n * The status a THIRD PARTY is allowed to observe. An invisible user always reads\n * `offline` here, and `presence/visibility.ts` is the only thing on the server\n * permitted to produce one of these — no route may call `isUserOnline` for a\n * third-party-facing answer.\n *\n * `busy` is observable because a refusal has to be explainable: a Wave button that\n * greys out, or a 409 that arrives, is unreadable unless the sender can see WHY.\n * It is not a privacy leak for the same reason `away` is not — an invisible user\n * still reads `offline` here whatever they are doing, which is checked FIRST.\n */\nexport const VisibleStatusSchema = z.enum([\"online\", \"away\", \"busy\", \"offline\"]);\nexport type VisibleStatus = z.infer<typeof VisibleStatusSchema>;\n\nexport const ContactRequestStatusSchema = z.enum([\"pending\", \"accepted\", \"declined\", \"cancelled\"]);\nexport type ContactRequestStatus = z.infer<typeof ContactRequestStatusSchema>;\n\n/**\n * Why a call ended. Every participant receives the same reason.\n *\n * `merged` is the one that does NOT mean \"you are no longer on a call\": the call was\n * absorbed into another one and everybody who had answered is now in that room instead.\n * A client rendering it as an ordinary hangup tells the operator the conversation is over\n * while they are still in it.\n *\n * ⚠️ **`removed` is the one that is NOT sent to every participant**, and it is the only\n * exception to the line above. The host dropping somebody from a conference does not end\n * the call — everybody else carries on and sees an ordinary `call.participant` saying that\n * person left — so this reason reaches exactly one client, the one being removed. It exists\n * rather than being folded into `hangup` because a call that vanishes with no explanation is\n * the failure this platform keeps paying for: the operator cannot tell being dropped from a\n * bug, and \"they hung up\" would be a lie about somebody else's action. A host may only\n * remove somebody while THREE are present, so this reason can never be the one that ends a\n * call for the people left behind.\n */\nexport const CallEndReasonSchema = z.enum([\n \"hangup\",\n \"declined\",\n \"cancelled\",\n \"timeout\",\n \"failed\",\n \"blocked\",\n \"moved\",\n \"merged\",\n \"removed\",\n]);\nexport type CallEndReason = z.infer<typeof CallEndReasonSchema>;\n\n/**\n * What one participant is doing in a call.\n *\n * ⚠️ **A 1:1 call is the two-participant case of this, not a separate path.** The whole\n * point of the participant set is that there is one state machine: the moment \"the callee\"\n * and \"the caller\" are scalar fields again, group calling grows a second implementation of\n * ringing, hanging up and sweeping, and the two drift.\n *\n * - `ringing` — invited and being rung; their client is showing an incoming call.\n * - `active` — answered, in the room, audible.\n * - `held` — answered, still a member, deliberately not exchanging audio. Hold is not a new\n * audio concept: the client pauses its producer and drops its listen set on that\n * frequency, both of which it already does. The state exists so the OTHER participants\n * can be shown why somebody went quiet.\n * - `left` — declined, hung up, or rang out. Terminal; a participant never comes back, a\n * re-invite is a new participant entry.\n */\nexport const CallParticipantStateSchema = z.enum([\"ringing\", \"active\", \"held\", \"left\"]);\nexport type CallParticipantState = z.infer<typeof CallParticipantStateSchema>;\n\n/**\n * What KIND of thing is on the call.\n *\n * Only `user` exists today. `external` is reserved, deliberately and in the wire contract\n * rather than in a comment, so that a DID/VOIP gateway can be added later without reshaping\n * the call session — the owner's instruction was to design for it and build nothing. A\n * client must therefore tolerate a participant whose `userId` resolves to no contact.\n */\nexport const CallParticipantKindSchema = z.enum([\"user\", \"external\"]);\nexport type CallParticipantKind = z.infer<typeof CallParticipantKindSchema>;\n\n/** The state of one outbound message, as the sender's client renders it. */\n/**\n * What a relayed message IS (contract §15, \"Message kinds\"). Everything rides the one relay,\n * so idempotency, the shared `seq` order, the reconnect re-read, the mute, blocks and the\n * busy refusal all apply unchanged; the kind only says how a client folds it in.\n *\n * - `text`: an ordinary message (optionally a `replyTo` quote of an earlier one).\n * - `reaction`: a tapback on message `refId`: `reaction` is the emoji, `reactionRemove`\n * takes theirs back. One per person per message, newest wins.\n * - `edit`: `body` replaces message `refId`'s text. Author only, within 15 minutes.\n * - `unsend`: message `refId` is withdrawn. Author only, within 2 minutes.\n *\n * ⚠️ **The server keeps no history, so it CANNOT enforce author or window for edit and\n * unsend; every receiving client must** (compare the edit's `fromUserId` with the target's,\n * and both `sentAt`s, which are server-assigned). `body` always carries a human-readable\n * fallback, so a client that does not understand a kind still shows something true.\n */\nexport const ChatMessageKindSchema = z.enum([\"text\", \"reaction\", \"edit\", \"unsend\", \"offer\"]);\nexport type ChatMessageKind = z.infer<typeof ChatMessageKindSchema>;\n\nexport const CHAT_EDIT_WINDOW_SECONDS = 15 * 60;\nexport const CHAT_UNSEND_WINDOW_SECONDS = 2 * 60;\n/** An emoji is at most a handful of code points; the cap only stops text posing as one. */\nexport const CHAT_REACTION_MAX_CHARS = 16;\nexport const CHAT_REPLY_EXCERPT_MAX = 200;\n\n/* ----------------------------------- group chats ---------------------------------- */\n\n/**\n * A group chat (contract §15, \"Group chats\"): a conversation among three or more people, or\n * between two people who are not contacts but met in a group.\n *\n * ⚠️ **A group's identity IS its member set.** The id is derived from the sorted member ids,\n * so re-forming the same people always yields the same id, and a client's history for that\n * id simply continues. Adding or removing somebody is therefore not an edit of a group, it\n * is a MOVE to a different one, and every member's window follows. Never mint a random id\n * here: it would give one grouping two histories.\n *\n * The server stores who is in each ACTIVE group and nothing else. No message is ever written\n * to the database; the relay rules are the 1:1 relay's, per recipient.\n */\nexport const CHAT_GROUP_MAX_MEMBERS = 10;\n\n/* ------------------------- device-to-device file transfer ------------------------- */\n\n/**\n * A file (or voice message) offered in a chat: contract §20. The offer rides the relay as a\n * message of kind `offer`; the BYTES never touch the platform, they go device to device over a\n * WebRTC data channel that the server forces through the TURN relay, so neither person learns\n * the other's address. Nothing moves until the recipient accepts.\n */\nexport const CHAT_FILE_NAME_MAX = 180;\nexport const CHAT_VOICE_PEAKS_MAX = 48;\n\nexport const ChatVoiceMetaSchema = z.object({\n durationMs: z.int().min(0).max(60 * 60 * 1000),\n /** A small waveform to draw before the audio arrives: 0-255 per bar. */\n peaks: z.array(z.int().min(0).max(255)).max(CHAT_VOICE_PEAKS_MAX),\n});\nexport type ChatVoiceMeta = z.infer<typeof ChatVoiceMetaSchema>;\n\n/**\n * An IMAGE offer's preview, shown before the recipient accepts (owner, 2026-09-27: a clear\n * thumbnail, so you can see what you are being sent). The sender's app makes it; the control\n * plane DECODES AND RE-ENCODES it with `sharp` before relaying, so what reaches the recipient is\n * a fresh WebP of known size and never the sender's bytes (the link-preview rule). It is the one\n * part of a file that passes through the platform, by the owner's choice; the full image never\n * does.\n */\nexport const CHAT_THUMBNAIL_EDGE = 320;\nexport const CHAT_THUMBNAIL_MAX_CHARS = 60_000;\nexport const ChatThumbnailSchema = z\n .string()\n .max(CHAT_THUMBNAIL_MAX_CHARS)\n .regex(/^data:image\\/(webp|jpeg|png);base64,[A-Za-z0-9+/]+={0,2}$/, \"Not an image thumbnail.\");\n\nexport const ChatFileOfferSchema = z.object({\n offerId: z.string().min(1).max(64),\n name: z.string().min(1).max(CHAT_FILE_NAME_MAX),\n size: z.int().min(1),\n mime: z.string().max(127),\n /** Present when this is a VOICE message: pressing Play accepts it. */\n voice: ChatVoiceMetaSchema.nullable(),\n /** An image's preview (re-encoded by the server), or null. Optional on older offers. */\n thumbnail: ChatThumbnailSchema.nullable().default(null),\n /** The ORIGINAL image's size in pixels, so the panel can reserve the right shape. */\n width: z.int().min(1).max(100_000).nullable().default(null),\n height: z.int().min(1).max(100_000).nullable().default(null),\n /**\n * Offered to a GROUP chat (0.99.0, capability `group-chat-files`). A transfer is device to\n * device between two people, so a group offer is one transfer PER RECIPIENT: `offerId` names\n * the offer, and each recipient's own transfer is `groupOfferLegId(offerId, theirUserId)`.\n * False (the default) on every 1:1 offer, where `offerId` IS the transfer.\n */\n group: z.boolean().default(false),\n});\nexport type ChatFileOffer = z.infer<typeof ChatFileOfferSchema>;\n\n/**\n * One recipient's transfer of a GROUP file offer (contract §20, \"In a group chat\"). Derived\n * rather than listed in the message, on purpose: a list of transfers in a message every member\n * reads would tell each of them who the sender could not reach (a Busy member gets none), which\n * is a status they are not entitled to see. Knowing somebody else's derived id grants nothing:\n * every transfer route answers only the two people it is between.\n */\nexport function groupOfferLegId(groupOfferId: string, userId: string): string {\n return `${groupOfferId}.${userId}`;\n}\n\n/** The group offer a transfer belongs to, or null for a 1:1 transfer. */\nexport function groupOfferIdOfLeg(offerId: string): string | null {\n const dot = offerId.indexOf(\".\");\n return dot > 0 ? offerId.slice(0, dot) : null;\n}\n\nexport const TransferStateSchema = z.enum([\"offered\", \"accepted\", \"declined\", \"cancelled\", \"complete\", \"failed\", \"expired\"]);\nexport type TransferState = z.infer<typeof TransferStateSchema>;\n/**\n * How many times a recipient may retry one failed transfer (capability `transfer-retry`). A\n * retry makes ANOTHER person's device open a relay connection without that person doing\n * anything, so it is a few and then \"send it again\", not a loop.\n */\nexport const TRANSFER_MAX_RETRIES = 3;\n\n/** Admin-set limits (`chat_transfer_limits` platform setting). */\nexport const CHAT_TRANSFER_LIMITS_KEY = \"chat_transfer_limits\";\nexport const ChatTransferLimitsSchema = z.object({\n maxFileBytes: z.int().min(1024).max(100 * 1024 ** 3),\n offerTtlHours: z.int().min(1).max(24 * 30),\n voiceMaxSeconds: z.int().min(5).max(3600),\n maxActivePerUser: z.int().min(1).max(50),\n /**\n * Largest file offered to a GROUP chat (0.99.0). Lower than `maxFileBytes` on purpose: the\n * sender's computer uploads a separate copy through the relay to every member who accepts, so a\n * group of ten costs nine times the 1:1 transfer. The effective cap is the smaller of the two.\n */\n maxGroupFileBytes: z.int().min(1024).max(100 * 1024 ** 3),\n});\nexport type ChatTransferLimits = z.infer<typeof ChatTransferLimitsSchema>;\nexport const DEFAULT_CHAT_TRANSFER_LIMITS: ChatTransferLimits = {\n maxFileBytes: 2 * 1024 ** 3,\n offerTtlHours: 168,\n voiceMaxSeconds: 300,\n maxActivePerUser: 3,\n // 25 MiB: a song as a 320 kbps MP3 is about 2.4 MB a minute, so this covers ten minutes of\n // it, and about two and a half minutes of CD-quality WAV (10 MB a minute); voice messages\n // and phone photos sit far below it. Nine copies of it is still a bounded upload.\n maxGroupFileBytes: 25 * 1024 ** 2,\n};\n\n/** What a group offer may be at most: the group cap, never above the 1:1 one. */\nexport function groupFileLimit(limits: ChatTransferLimits): number {\n return Math.min(limits.maxGroupFileBytes, limits.maxFileBytes);\n}\n\n/** A malformed or partial row keeps each valid field and defaults the rest. */\nexport function parseChatTransferLimits(value: unknown): ChatTransferLimits {\n const out = { ...DEFAULT_CHAT_TRANSFER_LIMITS };\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n for (const key of Object.keys(out) as (keyof ChatTransferLimits)[]) {\n const field = ChatTransferLimitsSchema.shape[key].safeParse((value as Record<string, unknown>)[key]);\n if (field.success) out[key] = field.data;\n }\n }\n return out;\n}\n\n/**\n * The sender's IANA time zone on a TEXT message, when they share it (a per-machine choice, on\n * by default). It lets a reader see \"3pm\" in their own zone (clarity assist). Shape-checked\n * only; a reader must still treat an unknown zone as absent.\n */\nexport const ChatTimeZoneSchema = z\n .string()\n .max(64)\n .regex(/^[A-Za-z][A-Za-z0-9_+\\-]*(?:\\/[A-Za-z0-9_+\\-]+){0,2}$/, \"Not a time zone name.\");\n\n/** The quoted message a reply shows above its own text, carried whole so it renders even when the reader no longer holds the original. */\nexport const ChatReplyToSchema = z.object({\n id: z.string().min(1).max(64),\n fromUserId: z.string().min(1).max(64),\n excerpt: z.string().max(CHAT_REPLY_EXCERPT_MAX),\n});\nexport type ChatReplyTo = z.infer<typeof ChatReplyToSchema>;\n\n/**\n * The live \"typing…\" and \"Read\" signals (contract §15). Published and never buffered or\n * stored: a missed one costs nothing, and the next one or the re-read corrects the view.\n */\nexport const CHAT_TYPING_EXPIRES_SECONDS = 6;\nexport const CHAT_TYPING_MIN_INTERVAL_SECONDS = 3;\n\nexport const ChatDeliveryStateSchema = z.enum([\"sending\", \"sent\", \"delivered\", \"failed\"]);\nexport type ChatDeliveryState = z.infer<typeof ChatDeliveryStateSchema>;\n\n/* --------------------------- per-contact settings -------------------------- */\n\n/**\n * The reserved sound id meaning CHOSEN SILENCE, distinct from an absent choice.\n *\n * ⚠️ `null` and `\"none\"` are genuinely different and collapsing them breaks a real\n * setting. For a ring, `null` means \"never chose\" — the default ring — so if null\n * meant silence there would be no way to express \"turn this person's ring off\".\n * For footsteps, `null` already means off, so `\"none\"` is merely the explicit\n * spelling of the same thing. Two meanings on one column type; keep both.\n */\nexport const SOUND_CHOICE_NONE = \"none\";\n\n/**\n * Which setting a sound belongs to, and therefore which pickers it appears in.\n *\n * ⚠️ **A sound is not usable across categories, and that is the reason this is an enum\n * rather than a free tag.** A ring loops and a footstep does not; a call-waiting pip is\n * built to sit UNDER a live conversation and would be inaudible as a ring; the busy tone\n * is a cadence with no melody at all. Offering one list everywhere would put sounds in\n * front of people that cannot do the job they are picking them for.\n *\n * The ten members are the owner's own taxonomy (2026-09-20), and the three headings are\n * how they are grouped on screen:\n *\n * Phone `ring` an incoming call. LOOPS.\n * `callwaiting` a second call arriving while you are on one. LOOPS.\n * `busy` they refused, or they are Busy. LOOPS.\n * `voicemail` your answering machine took a message.\n * Chat `message` a message arrived.\n * `sent` yours went out.\n * Footsteps `logon` a contact signed in.\n * `logoff` a contact signed out.\n * `join` somebody stepped onto a frequency you are tuned to.\n * `leave` somebody stepped off one.\n * (no picker) `startup` the app opened. THE SONIC MARK — see below.\n * `greeting` what a CALLER hears when the machine picks up. See below.\n *\n * ⚠️ **`startup` is a category with no setting behind it, and that is deliberate** (owner,\n * 2026-09-20: *\"this is our sonic mark, we don't want them to change it. We need to pick\n * one.\"*). It stays a category because that is how a sound is served — `GET /sounds` plus\n * `/sounds/:id/audio` — but it has exactly ONE member, it is flagged `isDefault`, there is\n * no `startupTone` on the account block for anybody to set, and no picker renders it. A\n * signature that each user can swap is not a signature.\n *\n * ⚠️ **`greeting` is the second category with no setting behind it, and it is not the same\n * KIND of thing as everything else here — it is the only member of this enum that plays to\n * somebody ELSE.** Every other sound is the app talking to its own user; the default\n * greeting is what a caller hears when an answering machine with no recorded greeting picks\n * up. It is in the library rather than baked into the client for one reason worth more than\n * the oddity: the library is served anonymously and version-keyed, so what the platform\n * says on somebody's behalf can be changed without a client release. It has exactly one\n * member and no picker, exactly like `startup`, and `default-sounds-exist.test.ts` asserts\n * that the single-member set is those TWO and nothing else.\n *\n * ⚠️ **`voicemail` is account-level only — there is no per-contact voicemail tone**, which\n * puts it with `busy` and `sent` rather than with `ring`. The rule those three share is\n * that the event is about YOU: a call you placed failing, your own message going out, and\n * your own machine having taken something are all facts about your side, and a per-person\n * copy of one could not mean anything.\n *\n * ⚠️ **`steps` and `alert` were members until 2026-09-20 and are gone.** `steps` was ONE\n * choice carrying two clips (arriving and leaving) and `alert` was a single fixed sound for\n * a contact coming online, with no counterpart for going offline. The owner's ruling —\n * *\"footsteps is four different sounds\"*, then *\"log in and log out are not the same\n * sound\"* and *\"join and left are not the same sound\"* — retires both: four events, four\n * independent choices, four categories. Rows in the old categories are RETIRED rather than\n * deleted, so anybody who had chosen one keeps hearing it, and `listCatalog` withholds\n * them because this enum can no longer name what they are.\n */\nexport const SoundCategorySchema = z.enum([\n \"ring\", \"callwaiting\", \"busy\", \"voicemail\",\n \"message\", \"sent\", \"wave\",\n \"logon\", \"logoff\", \"join\", \"leave\",\n \"startup\", \"greeting\",\n]);\nexport type SoundCategory = z.infer<typeof SoundCategorySchema>;\n\n/**\n * The one sound per category that plays for somebody who has chosen nothing.\n *\n * ⚠️ **A client must never hard-code any of these.** `GET /sounds` serves `isDefault` per\n * category precisely so that changing what the product sounds like needs no client\n * release, and this record is what the server flags FROM — it is not a list for a client\n * to copy. A client that offers its own extra \"Standard\" entry beside the flagged one puts\n * the same sound on screen twice; a client that assumes a name is simply wrong the day the\n * set moves, which has now happened twice.\n *\n * **They are one family and that is the point.** Every sound in the library is built on G\n * major's G-B-D, and each role owns a gesture within it: the ring rises a perfect fifth\n * (G4 -> D5) and a received message falls the same fifth (D5 -> G4) — the ring asks, the\n * message answers. `docs/sound-design.md` carries the whole map, the research the shapes\n * come from, and the measurements.\n *\n * ⚠️ `ring-beacon` and the `-soft`/`-bloom` stems kept their ids through the 2026-09-20\n * rebuild even though every byte behind them changed, because an id is a PERMANENT handle\n * on somebody's choice. Replacing an asset's audio is the supported move; replacing its id\n * silently takes their sound away.\n */\nexport const DEFAULT_SOUND_IDS: Record<SoundCategory, string> = {\n ring: \"ring-beacon\",\n callwaiting: \"callwaiting-pip\",\n busy: \"busy-tone\",\n // ⚠️ Not a fifth and not a rise: a falling minor third, D5 -> B4, which is the \"somebody\n // left something for you\" gesture rather than the ring's demand. It must not be mistaken\n // for a call arriving, because the one thing it never means is that anybody is waiting.\n voicemail: \"voicemail-drop\",\n message: \"message-drop\",\n sent: \"sent-tick\",\n // ⚠️ The library had no wave sound AT ALL until 0.71.0, which made the one event whose\n // entire purpose is to get somebody's attention the only silent one in the product. Its\n // gesture is D5 -> B4 -> D5: out and back, ending UP, because every other contour in the\n // family is spoken for and a wave is neither the ring's demand nor the message's answer.\n wave: \"wave-hello\",\n logon: \"logon-bloom\",\n logoff: \"logoff-bloom\",\n join: \"join-soft\",\n leave: \"leave-soft\",\n // ⚠️ The sonic mark, and the one entry here nobody can override — there is no\n // `startupTone` field. Renamed from `startup-signal` on 2026-09-20 because the sound\n // behind it is a different design, not a re-voicing: unlike every other id in this\n // table, no user's stored choice can be pointing at the old one, because choosing a\n // startup sound was never possible for more than a day and is now impossible by\n // construction. `tools/sonic_mark.py` holds it, the four candidates it was chosen over,\n // and the research behind the choice.\n startup: \"startup-ovation\",\n // ⚠️ The only entry here that is not played to this app's own user. It is what a CALLER\n // hears when a machine with no recorded greeting answers, so unlike every other row it\n // carries words: a tone cannot tell somebody they have reached an answering machine, and\n // a caller who does not know that says \"hello?\" into a recording. `tools/make-greeting.sh`\n // holds the script and the voice.\n greeting: \"greeting-default\",\n};\n\n\n/** Labels one contact may carry, and how long one may be. Owner-private free text. */\nexport const MAX_CONTACT_LABELS = 12;\nexport const MAX_CONTACT_LABEL_LENGTH = 32;\n/** The owner-private nickname's ceiling. */\nexport const MAX_CONTACT_ALIAS_LENGTH = 40;\n\n/**\n * A sound choice as stored: a library id, `\"none\"`, or null.\n *\n * ⚠️ **A `file:` choice is refused here on purpose.** Switchboard lets a user point a\n * setting at a .wav on their own disk, which is a good feature and a machine-local one: the\n * moment it synced, a Windows path would arrive on a Mac, resolve to nothing, and fall back\n * to the wrong sound with no error anywhere. A local file choice therefore lives in\n * client-persisted state and SHADOWS the synced value, and the UI says so. The server\n * stores library ids and `\"none\"`, and rejecting the prefix at the edge is what keeps that\n * true.\n */\nexport const SoundChoiceSchema = z\n .string()\n .trim()\n .min(1)\n .max(64)\n .regex(/^[a-z0-9][a-z0-9-]*$/, \"A sound is a library id from GET /sounds, or \\\"none\\\".\")\n .nullable();\n\n/**\n * How loud one notification role plays, 0-100, as a percentage of the app's own headroom.\n *\n * ⚠️ **This can only ever ATTENUATE what the operating system is already doing, and saying\n * so is part of shipping it.** macOS (CoreAudio) scales every application's output by the\n * system volume and there is no entitlement, API or private path that lets an app exceed or\n * bypass it — iOS has critical alerts, macOS has no equivalent for application audio. So 100\n * here is \"as loud as this app is allowed to be\", never \"loud regardless\". A UI that implied\n * otherwise would be promising something the platform refuses to do.\n *\n * Linear in AMPLITUDE (gain = pct/100), deliberately not in dB: the library is already\n * loudness-normalised role by role (`tools/make-sounds.py` targets a maximum-momentary LUFS\n * per category), so these sliders exist to move one role relative to the others, not to\n * repair a balance that is wrong in the files.\n */\nexport const SoundVolumeSchema = z.number().int().min(0).max(100);\n\n/**\n * The shipped level for every role — the gain notification playback used as a hard-coded\n * constant before these sliders existed, so nobody's sounds change loudness on upgrade.\n */\nexport const DEFAULT_SOUND_VOLUME = 60;\n\n/**\n * Everything one account has chosen about one other person. Owner-private in full —\n * **not one field here is ever returned to the person it describes.**\n *\n * ⚠️ **Sent WHOLE, never patched** (`PUT`, not `PATCH`). One request carries the entire\n * block for one contact, which makes every edit idempotent and means two clients at\n * different versions cannot merge two halves of a preference set — Switchboard's\n * board↔engine contract makes the same call for the same reason, and a partial-body PATCH\n * would reintroduce exactly what it avoids. An absent field is therefore a RESET to its\n * default, not \"leave it alone\".\n */\n/**\n * A per-contact volume: 0-100, or null to inherit the account level.\n *\n * ⚠️ Null is INHERIT and not \"silent\". Silence is the sound field saying `\"none\"`, which is\n * a separate axis on purpose — a volume of 0 would mute the row while still claiming a sound\n * is selected, so the two states would disagree about what is happening.\n */\nexport const ContactVolumeSchema = SoundVolumeSchema.nullable();\n\nexport const ContactPreferencesSchema = z.object({\n alias: z\n .string()\n .trim()\n .max(MAX_CONTACT_ALIAS_LENGTH)\n .nullable()\n .describe(\n \"Owner-private nickname, drawn AFTER the callsign and never instead of it — the callsign is how everybody \" +\n \"else refers to them, so a row that swapped one for the other leaves the user unable to quote the name that works.\",\n ),\n favorite: z.boolean().describe(\"Owner-private pin. The other side is never told.\"),\n labels: z\n // Deliberately NOT `.min(1)` on a member: a whole-object PUT carries every label the\n // user has, and a stray blank from a text field they opened and closed would otherwise\n // 400 the entire block — losing eight unrelated settings to punish an empty string. The\n // server normalises instead (trims, drops empties, de-duplicates case-insensitively)\n // and returns what it stored, so the client can see what happened.\n .array(z.string().trim().max(MAX_CONTACT_LABEL_LENGTH))\n .max(MAX_CONTACT_LABELS)\n .describe(\n \"Owner-private grouping. A label is a string several contacts SHARE, not an object anybody owns: no create \" +\n \"step, no delete step — typing the same word on two people groups them, and taking it off the last person removes it.\",\n ),\n logonSound: SoundChoiceSchema.describe(\n \"Sound when THIS contact signs in. A `logon` library id, \\\"none\\\" to mute just them, or null to inherit the \" +\n \"account default. Replaced the old `onlineSound` boolean, which was an opt-IN gate: the account setting is \" +\n \"the switch now, and this is the per-contact override that beats it.\",\n ),\n logoffSound: SoundChoiceSchema.describe(\n \"Sound when they sign out. Chosen SEPARATELY from logonSound — arriving and leaving are two events (owner, 2026-09-20).\",\n ),\n onlinePopup: z\n .boolean()\n .nullable()\n .describe(\n \"Show a desktop notification when they sign in or out. null INHERITS the account default; true/false override \" +\n \"it for this one person. Nullable for the same reason every sound here is: a plain boolean cannot say \" +\n \"\\\"whatever I chose for everybody\\\", so an account-wide switch could never reach a contact row already written.\",\n ),\n allowMessages: z\n .boolean()\n .describe(\n \"May they reach you with a chat or a wave. Enforced server-side and SILENTLY: a refused send answers exactly \" +\n \"as a delivered one does, because an \\\"undeliverable\\\" answer would be a presence oracle.\",\n ),\n allowCalls: z\n .boolean()\n .describe(\n \"May they ring you. A refused call is placed and simply never delivered, so it rings out at \" +\n \"CALL_RING_SECONDS — byte- and latency-identical to nobody answering.\",\n ),\n // ⚠️ `.default(true)` and not required, unlike every other field here, and that is the\n // point: the PUT is whole-object and an absent field is a RESET, so an older client that\n // re-sends the block it read before this field existed resets the switch to ON (what the\n // person had before they could choose) instead of being refused with a 400 for an edit\n // that had nothing to do with voicemail. Capability `contact-allow-voicemail`.\n allowVoicemail: z\n .boolean()\n .default(true)\n .describe(\n \"May they reach your answering machine (0.77.0). With it off they never do: while you are Busy they get \" +\n \"CALL_BUSY exactly as if your machine were switched off, and otherwise the call rings the full time and \" +\n \"ends. Declining their call hangs up rather than sending them to the machine. Absent on a PUT = true.\",\n ),\n ringTone: SoundChoiceSchema.describe(\"Library id from the `ring` category, \\\"none\\\" for silence, or null to inherit.\"),\n joinSound: SoundChoiceSchema.describe(\n \"Sound when THIS contact steps onto a frequency you are tuned to. A `join` library id, \\\"none\\\", or null to inherit.\",\n ),\n leaveSound: SoundChoiceSchema.describe(\n \"Sound when they step off one. A `leave` library id, \\\"none\\\", or null to inherit. Chosen SEPARATELY from \" +\n \"joinSound: arriving and leaving are two events, not one event with a direction.\",\n ),\n callWaitingSound: SoundChoiceSchema.describe(\n \"The pip when THIS contact reaches you while you are already on another call. A `callwaiting` library id, \" +\n \"\\\"none\\\", or null to inherit the account default.\",\n ),\n messageSound: SoundChoiceSchema.describe(\n \"Sound when a chat message arrives from THIS contact. A `message` library id, \\\"none\\\" to mute just them, or \" +\n \"null to inherit. Silent either way while you are already looking at that conversation.\",\n ),\n waveSound: SoundChoiceSchema.describe(\n \"Sound when THIS contact waves. A `wave` library id, \\\"none\\\" to mute just them, or null to inherit. \" +\n \"⚠️ Unlike a message this one is never suppressed by having their window open: a wave is not addressed to \" +\n \"a conversation, it is somebody asking whether you are there.\",\n ),\n\n // ⚠️ Per-contact VOLUME, and nullable for exactly the reason every sound here is: a plain\n // number cannot say \"whatever I chose for everybody\", so an account-wide level could never\n // reach a contact row that had already been written. null INHERITS.\n //\n // ⚠️ There is deliberately no per-contact `busy` or `messageSent`. Those two are about\n // YOU — a call you placed failing, your own message going out — so a per-person copy of\n // them would be a control that cannot mean anything. The account page keeps all nine; a\n // contact carries the seven that are about that contact.\n ringVolume: ContactVolumeSchema.describe(\"How loud their ring is, 0-100, or null to inherit the account level.\"),\n callWaitingVolume: ContactVolumeSchema.describe(\"How loud their call-waiting pip is, or null to inherit.\"),\n messageVolume: ContactVolumeSchema.describe(\"How loud their message tone is, or null to inherit.\"),\n waveVolume: ContactVolumeSchema.describe(\"How loud their wave is, or null to inherit.\"),\n logonVolume: ContactVolumeSchema.describe(\"How loud their sign-in sound is, or null to inherit.\"),\n logoffVolume: ContactVolumeSchema.describe(\"How loud their sign-out sound is, or null to inherit.\"),\n joinVolume: ContactVolumeSchema.describe(\"How loud their arriving footstep is, or null to inherit.\"),\n leaveVolume: ContactVolumeSchema.describe(\"How loud their leaving footstep is, or null to inherit.\"),\n});\nexport type ContactPreferences = z.infer<typeof ContactPreferencesSchema>;\n\n/**\n * What an untouched contact carries. Served, not assumed, so a client never has to decide\n * what an absent block means — and so this set can change without a client release.\n *\n * Note there is no \"all defaults means unset\" tombstone on the server, deliberately: the\n * row IS the contact edge, so it always exists. \"Have I customised this person\" is a\n * comparison against these values, which is a client concern.\n */\n/**\n * Every field of `ContactPreferences` that names a SOUND, as a list rather than as\n * knowledge.\n *\n * ⚠️ This exists so the control plane's field→category map can be typed\n * `Record<ContactSoundField, SoundCategory>` and a missing entry becomes a COMPILE error.\n * `logonSound` and `logoffSound` were added to this schema in 0.61.0 and not to that map,\n * so for one release those two fields were stored with no validation at all — any string,\n * including an id belonging to another category, which is the exact thing the map exists to\n * refuse. Nothing failed, because a validator that is never asked cannot complain.\n */\nexport const CONTACT_SOUND_FIELDS = [\n \"ringTone\",\n \"callWaitingSound\",\n \"messageSound\",\n \"waveSound\",\n \"logonSound\",\n \"logoffSound\",\n \"joinSound\",\n \"leaveSound\",\n] as const;\nexport type ContactSoundField = (typeof CONTACT_SOUND_FIELDS)[number];\n\n/** Every field of `ContactPreferences` that holds a per-contact LEVEL. Same rule as above. */\nexport const CONTACT_VOLUME_FIELDS = [\n \"ringVolume\",\n \"callWaitingVolume\",\n \"messageVolume\",\n \"waveVolume\",\n \"logonVolume\",\n \"logoffVolume\",\n \"joinVolume\",\n \"leaveVolume\",\n] as const;\nexport type ContactVolumeField = (typeof CONTACT_VOLUME_FIELDS)[number];\n\nconst _contactVolumeFieldsAreRealFields: readonly (keyof ContactPreferences)[] = CONTACT_VOLUME_FIELDS;\nvoid _contactVolumeFieldsAreRealFields;\n\n// Compile-time proof that every name above is really a field of the block, so the list\n// cannot drift into naming something that no longer exists.\nconst _contactSoundFieldsAreRealFields: readonly (keyof ContactPreferences)[] = CONTACT_SOUND_FIELDS;\nvoid _contactSoundFieldsAreRealFields;\n\nexport const DEFAULT_CONTACT_PREFERENCES: ContactPreferences = {\n alias: null,\n favorite: false,\n labels: [],\n onlinePopup: null,\n allowMessages: true,\n allowCalls: true,\n allowVoicemail: true,\n ringTone: null,\n callWaitingSound: null,\n messageSound: null,\n waveSound: null,\n // Inherit, at every level. See the account block below for why \"off\" is now spelled\n // `\"none\"` on the ACCOUNT rather than as a false boolean here.\n logonSound: null,\n logoffSound: null,\n // Inherit the account level. Never a number here: a contact nobody has touched must\n // FOLLOW the account slider, and shipping 60 would silently pin every existing contact to\n // today's value the moment per-contact volume existed.\n ringVolume: null,\n callWaitingVolume: null,\n messageVolume: null,\n waveVolume: null,\n logonVolume: null,\n logoffVolume: null,\n joinVolume: null,\n leaveVolume: null,\n // Null is INHERIT at every level since 0.58.0, so these resolve through the account\n // default to the catalog's `isDefault` member rather than to silence. \"Off for this one\n // person\" is `\"none\"`; \"off for everybody\" is `\"none\"` on the account default.\n joinSound: null,\n leaveSound: null,\n};\n\n/* ----------------------- account-level notification defaults ---------------------- */\n\n/**\n * What a contact's own settings fall back to — one set per ACCOUNT, overridden per contact.\n *\n * ⚠️ **This is what removes the `null` asymmetry, rather than deepening it.**\n * `SoundChoiceSchema` documents that `null` means \"never chose → the default\" for a ring but\n * OFF for footsteps, and says to keep both meanings. That asymmetry existed only because\n * footsteps had nothing to fall back TO: with no account level, \"inherit\" and \"off\" were the\n * same state. Now they are not, so BOTH fields read the same way and the special case is gone:\n *\n * - `null` → inherit. Per-contact null falls back to here; here, null falls back to the\n * catalog's `isDefault` member for that category.\n * - `\"none\"` → chosen silence, at whichever level it is set.\n *\n * So \"turn footsteps off for one person\" is `\"none\"` on that contact, and \"turn them off for\n * everybody\" is `\"none\"` here — two different wishes that were previously one value.\n *\n * ⚠️ **Footsteps become ON by default for every account (owner, 2026-09-20), and that ships\n * with NO data migration.** Existing contacts already store `null`, which used to mean off and\n * now means inherit; the flip is delivered by the `steps` category gaining an `isDefault`\n * member. The cost of that is real and is stated rather than hidden: a user who had\n * deliberately turned footsteps off is indistinguishable from one who never touched them,\n * because both stored `null`, so both are turned on. There is no column that could tell them\n * apart, and inventing one to guess would be worse than the flip the owner asked for.\n */\nexport const AccountNotificationDefaultsSchema = z.object({\n ringTone: SoundChoiceSchema.describe(\n \"Default ring for a contact who has not chosen one. null inherits the catalog default, \\\"none\\\" is silence.\",\n ),\n ringVolume: SoundVolumeSchema,\n callWaitingTone: SoundChoiceSchema.describe(\n \"The pip that plays when a second call arrives while you are on one. Account-level only: it belongs to the \" +\n \"call you are ALREADY on, not to whoever is calling.\",\n ),\n callWaitingVolume: SoundVolumeSchema,\n busyTone: SoundChoiceSchema.describe(\"What plays when a call you placed is refused, or the other person is Busy.\"),\n busyVolume: SoundVolumeSchema,\n voicemailEnabled: z\n .boolean()\n .describe(\n \"Whether the answering machine picks up. ON by default. With it on, a call this account does not answer \" +\n \"within CALL_AUTOANSWER_SECONDS is answered by the machine, which plays the greeting, beeps and records; \" +\n \"and a call arriving while this account reads `busy` goes straight there with no ring delay. With it OFF \" +\n \"the call rings the full CALL_RING_SECONDS and is then over, and a caller who can already see this \" +\n \"account as `busy` gets 409 CALL_BUSY exactly as they always have. ⚠️ The machine lives in the CLIENT, so \" +\n \"it can only answer while an app is running: with every app closed the caller still gets CALL_UNAVAILABLE \" +\n \"and no message can be left. That bound is accepted (owner, 2026-09-22) and is the price of the platform \" +\n \"storing no message audio at any point.\",\n ),\n chatReadReceipts: z\n .boolean()\n .default(true)\n .describe(\n \"Whether your contacts see \\\"Read\\\" under what they sent you once you have looked at it. ON by default. \" +\n \"Off means `contact.read` is never published for you; it changes nothing about what YOU see of theirs. \" +\n \"Never sent while you are invisible either way. Optional on the way in (defaults to on) so an app that \" +\n \"predates it can still save the rest of this record.\",\n ),\n chatTypingIndicators: z\n .boolean()\n .default(true)\n .describe(\"Whether your contacts see \\\"typing…\\\" while you write to them. ON by default; same rules as chatReadReceipts.\"),\n acceptMessagesFromNonContacts: z\n .boolean()\n .default(false)\n .describe(\n \"Whether somebody who is NOT a contact may send this account a direct message (capability `chat-non-contacts`). \" +\n \"OFF by default. On, any account may write to you through POST /contacts/:userId/messages; blocks, Busy, \" +\n \"invisibility, the per-account rate limit and the mute all still apply. Off, a non-contact's send is the \" +\n \"same 404 a stranger always got, so the setting cannot be probed. Writing to a non-contact yourself lets \" +\n \"THAT person reply for a day whatever this says, or a conversation you started could not be answered. \" +\n \"Carried to everybody tuned with you as `acceptsMessages` on the roster row, so a client offers the option \" +\n \"only where it would be accepted. Optional on the way in (defaults to off).\",\n ),\n voicemailMaxSeconds: z\n .int()\n .min(VOICEMAIL_MIN_SETTABLE_SECONDS)\n .max(VOICEMAIL_MAX_SETTABLE_SECONDS)\n .describe(\n \"The longest message the answering machine will take before it hangs up, in seconds. It is also the \" +\n \"machine's hangup deadline, so it is bounded at both ends rather than allowing 'unlimited': the machine \" +\n \"holds a real call open, with a media container and the caller's own line, and a message that never ends \" +\n \"is a call that never ends. A caller who stops talking is cut off well before this by the silence window.\",\n ),\n voicemailTone: SoundChoiceSchema.describe(\n \"What plays when your own machine has taken a message. Account-level only, like busyTone beside it: it is a \" +\n \"fact about your side rather than about whoever called.\",\n ),\n voicemailVolume: SoundVolumeSchema,\n messageTone: SoundChoiceSchema.describe(\"A chat message arriving.\"),\n messageVolume: SoundVolumeSchema,\n messageSentTone: SoundChoiceSchema.describe(\"Your own message going out. \\\"none\\\" is a common and sane choice here.\"),\n messageSentVolume: SoundVolumeSchema,\n waveTone: SoundChoiceSchema.describe(\"A contact waving at you.\"),\n waveVolume: SoundVolumeSchema,\n wavePopup: z\n .boolean()\n .describe(\n \"Show a desktop notification when a contact waves, and keep it up until it is dismissed. Account-wide. \" +\n \"⚠️ Ships ON, unlike `onlinePopup` beside it, and the difference is who asked for the interruption: a \" +\n \"contact signing in is something that merely happened, while a wave is a person pressing a button whose \" +\n \"only purpose is to reach you. It is also the one notification here with nothing to come back to — a \" +\n \"wave is never buffered, so an unseen one is simply lost.\",\n ),\n logonTone: SoundChoiceSchema.describe(\n \"A contact signing in. ⚠️ Ships as \\\"none\\\" — see DEFAULT_ACCOUNT_NOTIFICATION_DEFAULTS for why this is the one \" +\n \"pair that may, and why that is not the silent-role trap the other eight guard against.\",\n ),\n logonVolume: SoundVolumeSchema,\n logoffTone: SoundChoiceSchema.describe(\"A contact signing out. Ships as \\\"none\\\" for the same reason as logonTone.\"),\n logoffVolume: SoundVolumeSchema,\n joinTone: SoundChoiceSchema.describe(\n \"Default for a contact stepping onto a frequency you are tuned to, when they have not chosen one.\",\n ),\n joinVolume: SoundVolumeSchema,\n leaveTone: SoundChoiceSchema.describe(\"Default for a contact stepping off one.\"),\n leaveVolume: SoundVolumeSchema,\n onlinePopup: z\n .boolean()\n .describe(\n \"Show a desktop notification when a contact signs in or out. The account-wide switch; a contact's own \" +\n \"`onlinePopup` overrides it, and null there means inherit this.\",\n ),\n});\nexport type AccountNotificationDefaults = z.infer<typeof AccountNotificationDefaultsSchema>;\n\n/**\n * What an account that has never touched this carries.\n *\n * ⚠️ **Eight roles ship as `null` and two ship as `\"none\"`, and the difference is the whole\n * policy.** `null` is INHERIT, so the audible default is whatever the catalog flags\n * `isDefault` and what the product sounds like can be changed with no client release and no\n * row rewritten — which is why there are no sound ids in this file's runtime path at all.\n * `\"none\"` is chosen silence, and `logonTone`/`logoffTone` take it because the owner's rule\n * still holds: with a long contact list, every sign-in making a noise is a setting nobody\n * asked for.\n *\n * ⚠️ **Shipping `\"none\"` is normally the silent-role trap, and the ONLY thing that makes it\n * safe here is that the page shows an unticked box.** Until 2026-09-20 these two were gated\n * by a per-contact `onlineSound` boolean that defaulted false, so the account control looked\n * live and did nothing until you opened a contact — the owner's *\"put a use checkbox next to\n * each notification type\"* is what retired it. The checkbox IS this value (`\"none\"` or not),\n * so an off role is visibly off rather than mysteriously mute. `soundResolution.test.ts`\n * asserts the split by name; do not widen the exemption without a control that shows it.\n */\nexport const DEFAULT_ACCOUNT_NOTIFICATION_DEFAULTS: AccountNotificationDefaults = {\n ringTone: null,\n ringVolume: DEFAULT_SOUND_VOLUME,\n callWaitingTone: null,\n callWaitingVolume: DEFAULT_SOUND_VOLUME,\n busyTone: null,\n busyVolume: DEFAULT_SOUND_VOLUME,\n // ⚠️ **ON, and it is the one switch here whose default changes what a CALLER experiences**\n // — every other value in this record only decides what this account hears. Shipping it off\n // would mean the feature exists for nobody until they find the setting, and an answering\n // machine nobody has switched on is indistinguishable from no answering machine. The\n // owner's shape is a telephone's, and a telephone's machine is on.\n voicemailEnabled: true,\n voicemailMaxSeconds: VOICEMAIL_MAX_SECONDS,\n chatReadReceipts: true,\n chatTypingIndicators: true,\n // OFF, by the owner's ask (2026-09-25): a direct message from a stranger is opt-in.\n acceptMessagesFromNonContacts: false,\n voicemailTone: null,\n voicemailVolume: DEFAULT_SOUND_VOLUME,\n messageTone: null,\n messageVolume: DEFAULT_SOUND_VOLUME,\n messageSentTone: null,\n messageSentVolume: DEFAULT_SOUND_VOLUME,\n waveTone: null,\n waveVolume: DEFAULT_SOUND_VOLUME,\n // ⚠️ ON by default, and the one popup here that is. See the field's own note: a wave is\n // somebody deliberately reaching for you and it is never buffered, so the alternative to\n // interrupting is losing it. Turning it off is one click on the same page.\n wavePopup: true,\n // The two the owner asked to start off. See the block comment above.\n logonTone: SOUND_CHOICE_NONE,\n logonVolume: DEFAULT_SOUND_VOLUME,\n logoffTone: SOUND_CHOICE_NONE,\n logoffVolume: DEFAULT_SOUND_VOLUME,\n joinTone: null,\n joinVolume: DEFAULT_SOUND_VOLUME,\n leaveTone: null,\n leaveVolume: DEFAULT_SOUND_VOLUME,\n // A desktop popup interrupts whatever the user is doing in another application, so it is\n // opt-in even though the sound beside it is not.\n onlinePopup: false,\n};\n\n/**\n * Resolve one sound choice down the chain: contact → account → catalog default.\n *\n * ⚠️ **`\"none\"` STOPS the chain at whatever level set it** — that is the whole point of\n * keeping it distinct from `null`, and a resolver that treated them alike would make\n * \"off for this one person\" unexpressible again. Returns `null` for silence, which is\n * what every caller already checks for.\n *\n * `catalogDefault` is passed in rather than read from a constant on purpose: the catalog\n * SERVES `isDefault` precisely so a client never hard-codes a sound id (`SoundAssetSchema`\n * says so at length), and a helper with its own copy would be the hard-coding it forbids.\n */\n/**\n * A role's VOLUME: the contact's level, else the account's, else the shipped default.\n *\n * ⚠️ Deliberately much simpler than `resolveSoundChoice`, because volume has no equivalent\n * of `\"none\"` — there is no \"chosen zero that stops the chain\", since silence is the sound\n * field's job. Two nullable levels and a constant floor is the whole rule, and keeping it\n * separate is what stops somebody adding a sentinel here to mirror the other function.\n */\nexport function resolveSoundVolume(\n contactVolume: number | null | undefined,\n accountVolume: number | null | undefined,\n): number {\n if (typeof contactVolume === \"number\") return contactVolume;\n if (typeof accountVolume === \"number\") return accountVolume;\n return DEFAULT_SOUND_VOLUME;\n}\n\nexport function resolveSoundChoice(\n contactChoice: string | null | undefined,\n accountDefault: string | null | undefined,\n catalogDefault: string | null | undefined,\n): string | null {\n for (const level of [contactChoice, accountDefault]) {\n if (level === SOUND_CHOICE_NONE) return null;\n if (level !== null && level !== undefined) return level;\n }\n return catalogDefault === SOUND_CHOICE_NONE ? null : (catalogDefault ?? null);\n}\n\n\n\n/**\n * Who sent a 1:1 message, carried ONLY when sender and recipient are not contacts\n * (capability `chat-non-contacts`). A thread's label is otherwise resolved from the contact\n * graph, which by definition holds nothing for this person. The same public identity a\n * UserSummary carries and nothing more: never a name or an email.\n */\nexport const ChatSenderSchema = z.object({\n kind: UserKindSchema.describe(\"person or agent (contract §25): draw the agent badge on the thread. Defaulted for an older server.\"),\n handle: z.string().nullable().describe(\"Callsign; null for a listener-only account, so render stationId instead.\"),\n stationId: z.string().describe(\"FT-XXXX. Stable, and what POST /contacts/requests or a block takes.\"),\n avatar: z.string().nullable(),\n avatarColor: z.string(),\n});\nexport type ChatSender = z.infer<typeof ChatSenderSchema>;\n","import { z } from \"zod\";\n\n/**\n * What kind of account a UserSummary describes (contract §25, capability `agents`). A leaf\n * module on purpose: responses.ts, contacts.ts and events.ts all carry it and import each\n * other in one direction only.\n */\nexport const UserKindSchema = z.enum([\"person\", \"line\", \"agent\"]);\nexport type UserKind = z.infer<typeof UserKindSchema>;\n\nexport const USER_KIND_DESCRIPTION =\n \"person: a human. agent: an automated account acting under an operator (capability `agents`); draw a badge beside its \" +\n \"callsign and never hide it. line: the synthetic user behind a phone number.\";\n","import { z } from \"zod\";\nimport { UserKindSchema } from \"./userKind.js\";\n\nimport { CallEndReasonSchema, ChatFileOfferSchema, ChatSenderSchema, ChatMessageKindSchema, ChatReplyToSchema, ChatTimeZoneSchema, TransferStateSchema, UserStatusSchema, VisibleStatusSchema } from \"./contacts.js\";\nimport { BoardChannelSharedSchema, ChatConversationRefSchema, ChatGroupSchema, FrequencyMemberSchema } from \"./responses.js\";\nimport { TuningDeltaSchema } from \"./api.js\";\nimport { MAX_SEALED_POINTER_CHARS } from \"./share/pointer.js\";\nimport { MAX_SEALED_CONTROL_CHARS } from \"./share/control.js\";\nimport { ShareToolsWireSchema } from \"./share/tools.js\";\n\n/* ------------------------------------------------------------------------ *\n * Control-plane realtime WebSocket contract (wss://control-plane/ws)\n * One connection per authenticated client. Server pushes presence/roster/\n * speaking/membership events for every frequency the client subscribes to.\n * ------------------------------------------------------------------------ */\n\n/**\n * WHY an install lost a stream it was carrying. ONE vocabulary across all three transports,\n * deliberately: the realtime lane's `stream.displaced` (HLS) and the media lane's\n * `streamDisplaced` (WebRTC and native UDP) share it, so a client maps both to one UI state\n * and the no-auto-retry rule written for the first already covers the second unchanged.\n *\n * Before this there were two spellings of one event and a free-text `error` message on the\n * third path, which is how Switchboard came to read our docs as promising a rule that was\n * only ever built for HLS.\n *\n * - `takeover` — another install of this account deliberately took the frequency's one\n * audio stream (a `takeover: true` listen-ticket mint, contract §6). A human pressed play\n * somewhere else.\n * - `transmit-elsewhere` — another install of this account started transmitting on this\n * frequency (transmit exclusivity, newest wins). Nobody pressed anything here.\n *\n * In BOTH cases the session that receives it is STILL SIGNED IN. Stop, say so, and require a\n * user action to resume: never auto-retry, which is how two machines trade a stream forever.\n */\nexport const StreamDisplacedReasonSchema = z.enum([\"takeover\", \"transmit-elsewhere\"]);\nexport type StreamDisplacedReason = z.infer<typeof StreamDisplacedReasonSchema>;\n\nexport const ClientToServerEventSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"subscribe\"), frequencyId: z.string() }),\n z.object({ type: z.literal(\"unsubscribe\"), frequencyId: z.string() }),\n z.object({ type: z.literal(\"ping\") }),\n // Full-state declaration of this device's tuned presence on a frequency: \"I am\n // connected to F, listening on these channels, armed to talk on those.\" Idempotent\n // upsert — one message type serves as the connect edge, every coalesced change, and\n // the ~30s keepalive refresh alike (an unchanged refresh is absorbed server-side and\n // fans nothing out). Distinct from `subscribe`, which only routes events and is sent\n // for every member frequency; declaring tuned does not subscribe, and vice versa.\n // The channel lists follow the routing contract's roster rule: talking = could talk\n // right now (armed), never speech activity.\n z.object({\n type: z.literal(\"tuned\"),\n frequencyId: z.string(),\n listeningChannelIds: z.array(z.string()).max(512),\n talkingChannelIds: z.array(z.string()).max(512),\n }),\n z.object({ type: z.literal(\"untuned\"), frequencyId: z.string() }),\n // This device's human has (or has not) gone idle. Auto-away is CLIENT-DECLARED and\n // server-clamped: the server cannot infer human idleness, because the socket pings on a\n // timer regardless of what the person is doing, so socket silence is not idleness. Only\n // the client can see input activity — do not build a server-side idle timer.\n //\n // Idempotent and reference-counted per connection, the same shape as `tuned`: an\n // unchanged declaration is absorbed server-side and fans nothing out, and a status edge\n // fires only on the 0<->N transition of an account's non-idle connections. A five-device\n // account flapping idle therefore publishes nothing.\n z.object({ type: z.literal(\"presence\"), idle: z.boolean() }),\n]);\nexport type ClientToServerEvent = z.infer<typeof ClientToServerEventSchema>;\n\nexport const ServerToClientEventSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"pong\") }),\n z.object({\n type: z.literal(\"presence.update\"),\n frequencyId: z.string(),\n userId: z.string(),\n online: z.boolean(),\n }),\n z.object({\n type: z.literal(\"roster.update\"),\n frequencyId: z.string(),\n channelId: z.string(),\n listenerCount: z.number(),\n talkerCallsigns: z.array(z.string()),\n }),\n z.object({\n type: z.literal(\"speaking.start\"),\n frequencyId: z.string(),\n channelId: z.string(),\n userId: z.string(),\n callsign: z.string(),\n }),\n z.object({\n type: z.literal(\"speaking.stop\"),\n frequencyId: z.string(),\n channelId: z.string(),\n userId: z.string(),\n }),\n // Frequency lane for existing members' rosters — and, since user-directory-events\n // (2026-08-08), ALSO published on the joiner's own user lane by announceJoin whenever a\n // user GAINS a frequency (accept/approve/create/join-by-number/invite-link/staff sync):\n // none of the joiner's devices can be subscribed to a frequency they just gained, and\n // the lane an event arrived on is invisible to a client, so the same nudge serves both.\n // `member` and `personalChannel` (capability frequency-board) make this a DELTA for a board:\n // the joiner's row and the personal channel a board draws them under, so nobody re-reads\n // the member list or the channel list to learn about one person. `member` deliberately has\n // no `online`: presence is resolved per viewer and an invisible member must not be announced\n // by a broadcast. Absent on the user-lane copy to the joiner's own devices, whose answer to\n // gaining a frequency is to read it whole.\n z.object({\n type: z.literal(\"membership.updated\"),\n frequencyId: z.string(),\n userId: z.string(),\n role: z.enum([\"owner\", \"admin\", \"user\"]),\n member: FrequencyMemberSchema.omit({ online: true }).optional(),\n personalChannel: BoardChannelSharedSchema.nullable().optional(),\n }),\n z.object({\n type: z.literal(\"membership.removed\"),\n frequencyId: z.string(),\n userId: z.string(),\n }),\n // Frequency-level properties changed (e.g. mode) — clients refetch the frequency\n // DETAIL on this (not refreshFrequencyData, which only refetches channels/members/groups).\n z.object({ type: z.literal(\"frequency.updated\"), frequencyId: z.string() }),\n // Live program metadata (2026-07-22). Carries the payload inline rather than acting as a\n // refetch nudge like frequency.updated: a now-playing ticker can change every few\n // minutes per station, and making every listener re-GET the frequency for a one-line\n // text change is exactly the round-trip a radio client should not be making.\n z.object({\n type: z.literal(\"station.nowPlaying\"),\n frequencyId: z.string(),\n organizationId: z.string(),\n nowPlaying: z\n .object({\n text: z.string().nullable(),\n trackTitle: z.string().nullable(),\n trackArtist: z.string().nullable(),\n updatedAt: z.string().nullable(),\n since: z.string().nullable(),\n })\n .nullable(),\n }),\n // The live Cheer and Hush tally (capability `cheer-hush`, 0.118.0). Sent ONLY to the\n // station's staff, dj and up, never to listeners: a tally is a floor on the audience\n // size, which the platform does not print. At most one a second per station, carrying\n // the whole tally, so a missed frame is repaired by the next one.\n z.object({\n type: z.literal(\"station.reactions\"),\n frequencyId: z.string(),\n since: z.string(),\n cheers: z.int(),\n hushes: z.int(),\n at: z.string(),\n }),\n // `board` and `affectedUserIds` (capability frequency-board) make these a DELTA for a board.\n // `board` is the channel as every recipient sees it. `affectedUserIds` names whose OWN\n // standing on the channel (member, may talk) changed: those clients read their one board\n // channel, everybody else applies `board` and makes no request. null means \"everyone\n // re-read your standing\" (the channel's type or a group link changed). A recipient of an\n // event WITHOUT `board` falls back to reading the list, which is the pre-0.113 behaviour.\n z.object({\n type: z.literal(\"channel.created\"),\n frequencyId: z.string(),\n channelId: z.string(),\n board: BoardChannelSharedSchema.optional(),\n affectedUserIds: z.array(z.string()).nullable().optional(),\n }),\n z.object({\n type: z.literal(\"channel.updated\"),\n frequencyId: z.string(),\n channelId: z.string(),\n board: BoardChannelSharedSchema.optional(),\n affectedUserIds: z.array(z.string()).nullable().optional(),\n }),\n z.object({ type: z.literal(\"channel.deleted\"), frequencyId: z.string(), channelId: z.string() }),\n // The admin mute (capability member-force-mute, contract §10c): an owner or admin muted or\n // unmuted `userId` on this channel, or the member lifted it themselves (then byUserId ===\n // userId). Delivered to the channel's audience and always to the muted person, who must be\n // told who did it (owner, 2026-10-11: \"the user should be notified they were muted and by\n // whom\"). A mute is NOT a tuning change: the member's talk plugs stay as they were, and the\n // media node refuses their audio on the channel until it is lifted.\n z.object({\n type: z.literal(\"channel.forceMute\"),\n frequencyId: z.string(),\n channelId: z.string(),\n userId: z.string(),\n muted: z.boolean(),\n byUserId: z.string(),\n }),\n // Covers group create/rename/delete/membership changes and channel<->group link\n // changes — clients just refetch groups + channels for the frequency on any of these,\n // same as the channel.* events above, rather than diffing individual fields over the wire.\n z.object({ type: z.literal(\"group.created\"), frequencyId: z.string(), groupId: z.string() }),\n z.object({ type: z.literal(\"group.updated\"), frequencyId: z.string(), groupId: z.string() }),\n z.object({ type: z.literal(\"group.deleted\"), frequencyId: z.string(), groupId: z.string() }),\n // User-targeted at the invitee (capability: user-directory-events) — the one event a\n // client can never get from a frequency lane, because an invitee is not a member and\n // cannot subscribe. Nudge-style like favorites.updated: refetch GET /users/me/invitations.\n z.object({ type: z.literal(\"invitation.created\"), invitationId: z.string(), frequencyId: z.string() }),\n // User-targeted at the invitee: their invitation was answered (usually on another of\n // their own devices) — clear the pinned invite without a poll.\n z.object({\n type: z.literal(\"invitation.updated\"),\n invitationId: z.string(),\n frequencyId: z.string(),\n status: z.enum([\"accepted\", \"declined\"]),\n }),\n // Frequency lane: the frequency is gone. \"Drop it locally\" — do NOT refetch its detail\n // (the row no longer exists; a refetch just manufactures a 404).\n z.object({ type: z.literal(\"frequency.deleted\"), frequencyId: z.string() }),\n // Frequency lane: taken off the air (capability: frequency-suspension). Carries the\n // class INLINE rather than acting as a refetch nudge, and that is load-bearing: a\n // suspended frequency's detail may now answer 403, so a client that reacted by\n // refetching would turn an ordinary event into an unhandled rejection — the exact shape\n // of the membership.removed-about-self bug. Treat it like frequency.deleted (deactivate\n // locally, persistTuningState=false) except that the station still exists and should\n // still be shown, with a banner, and re-enabled from the app when `reinstatable`.\n z.object({\n type: z.literal(\"frequency.suspended\"),\n frequencyId: z.string(),\n suspensionClass: z.enum([\"non_payment\", \"voluntary\", \"conduct\", \"legal\"]),\n reinstatable: z.boolean(),\n }),\n // Frequency lane: back on the air. Safe as a plain refetch nudge, unlike its sibling —\n // by the time this arrives the frequency reads normally again.\n z.object({ type: z.literal(\"frequency.reinstated\"), frequencyId: z.string() }),\n z.object({\n type: z.literal(\"mediaNode.status\"),\n frequencyId: z.string(),\n status: z.enum([\"starting\", \"running\", \"stopping\", \"stopped\", \"error\"]),\n }),\n // The frequency's SHARE container changed state (capability `share-container`). A separate\n // event from mediaNode.status on purpose: clients read that one as \"the frequency's audio\",\n // and a share container stopping must never drop a call's voice to static. `running` is sent\n // only once the container's generation is cleared, i.e. once a re-tune would carry\n // `share.connect`; re-tune on it. `stopped` means the share lane is gone.\n z.object({\n type: z.literal(\"shareNode.status\"),\n frequencyId: z.string(),\n status: z.enum([\"starting\", \"running\", \"stopping\", \"stopped\", \"error\"]),\n }),\n // One member's tuned-presence row changed or appeared (capability: frequency-roster).\n // Full row with upsert semantics — receivers replace their (userId, deviceId) entry\n // wholesale. Two devices of one account are two rows. Not replayed on subscribe:\n // seed from GET /frequencies/:id/roster and re-seed there after a reconnect.\n z.object({\n type: z.literal(\"frequency.rosterMember\"),\n frequencyId: z.string(),\n userId: z.string(),\n /** Server-issued installationId; identifies which of the user's devices this row is. */\n deviceId: z.string(),\n callsign: z.string(),\n /** Same identity fields as the REST row (TunedRosterMemberSchema), read fresh at publish. */\n /** person or agent (contract §25). Defaulted for an older server. */\n kind: UserKindSchema.default(\"person\"),\n stationId: z.string(),\n avatar: z.string().nullable(),\n avatarColor: z.string(),\n /** Accepts direct messages from non-contacts (capability chat-non-contacts). Defaulted for an older server. */\n acceptsMessages: z.boolean().default(false),\n listeningChannelIds: z.array(z.string()),\n /** Intent, not activity — channels this device could talk on right now. */\n talkingChannelIds: z.array(z.string()),\n }),\n z.object({\n type: z.literal(\"frequency.rosterLeave\"),\n frequencyId: z.string(),\n userId: z.string(),\n deviceId: z.string(),\n }),\n // Coalesced directory numbers for clients not rendering the member list — the two\n // figures the frequency list draws (\"N connected · M talking\"). Throttled server-side\n // and, like every event on this lane, not replayed on subscribe: seed and re-seed from\n // GET /frequencies (tunedCounts) rather than waiting for the next edge.\n z.object({\n type: z.literal(\"frequency.tunedCounts\"),\n frequencyId: z.string(),\n connectedCount: z.number(),\n talkingCount: z.number(),\n }),\n // The deployed client-bundle version (operator-bumped after a web deploy; also sent\n // once on every WS connect). GLOBAL — delivered to every connection regardless of\n // frequency subscriptions. A client that sees a DIFFERENT value than the first one it\n // received this page load has a newer bundle waiting.\n //\n // ⚠️ The two fields answer DIFFERENT questions and are not interchangeable.\n //\n // `version` is the built bundle's content-hash FILENAME (`index-Bn3RNcNV.js`), which the\n // deploy reads off disk. It is exact for \"has the deployed bundle changed?\" and it can\n // NEVER be ordered — there is no sense in which one content hash is below another.\n //\n // `minVersion` is a real MAJOR.MINOR.PATCH floor, compared against the semver the running\n // bundle was stamped with at build time. This is the force-reload lever: it exists so a\n // breaking server change can require clients onto the new bundle rather than merely\n // offering it. Null means no floor, which is the ordinary state — and it is null rather\n // than \"0.0.0\" so \"no floor set\" is distinguishable from \"a floor everything satisfies\".\n //\n // Since 2026-08-29 an ordinary new bundle no longer reloads the client behind its back: it\n // lights the UPDATE control and the user picks the moment (owner decision — this should feel\n // like an application, not a web page). Only a floor forces it, and even then never while\n // the client is on the air.\n z.object({\n type: z.literal(\"system.clientVersion\"),\n version: z.string(),\n minVersion: z.string().nullable(),\n }),\n /**\n * An operator message from Frequency Talk — maintenance windows, outages, account notices.\n * Global (see publishGlobal), and re-sent on the WS hello so it reaches clients that connect\n * AFTER it was posted; a notice that only reached whoever happened to be online at the\n * instant it was sent could not warn about anything upcoming, which is most of the point.\n *\n * ⚠️ **A notice is presentation and nothing else.** It must never reload the client, touch the\n * audio graph or interrupt a broadcast (owner constraint, 2026-08-29) — the forced-update\n * lever is `system.clientVersion` above, and keeping the two apart is what stops \"we should\n * tell people about Tuesday's maintenance\" from ever taking a station off the air.\n *\n * `expiresAt` is an ISO instant and is advisory on the client (the server stops sending an\n * expired notice; a client already holding one hides it at the same moment without needing a\n * push). Dismissal is client-side and per-id — see the client store.\n */\n z.object({\n type: z.literal(\"system.notice\"),\n id: z.string(),\n severity: z.enum([\"info\", \"warning\", \"critical\"]),\n title: z.string(),\n body: z.string(),\n expiresAt: z.string(),\n /**\n * When the operator posted this, as an ISO instant — the client's ORDERING key, and the\n * reason it is on the wire at all (0.40.0).\n *\n * The client pages unread notices oldest-first so they read as a catch-up queue. It cannot\n * take that order from array position: the server sorts NEWEST-first for the console's\n * list, and a notice arriving later on the live lane is appended, so hello order and push\n * order would combine into something neither end agreed on. An explicit key means both\n * consumers sort for themselves and neither depends on the other's choice.\n *\n * ⚠️ The notice's `createdBy` is deliberately NOT here and must never be — it is a platform\n * user id, and which staff member wrote a notice is not a customer's business.\n */\n postedAt: z.string(),\n }),\n /**\n * A notice withdrawn before its expiry — an outage that turned out to be nothing, a window\n * that moved. Carries only the id: the client removes it, and a client that never saw it\n * ignores it harmlessly.\n */\n z.object({\n type: z.literal(\"system.noticeCleared\"),\n id: z.string(),\n }),\n // This session has been signed out server-side and every token it holds is already\n // dead. USER-TARGETED: delivered only to connections belonging to the affected user\n // (see publishToUser), unlike everything above, which is addressed to a frequency.\n // The client's job is to tear down and show the reason — its access token would\n // otherwise keep working until it expires, and the WS would keep reconnecting.\n z.object({\n type: z.literal(\"session.revoked\"),\n // WHICH session was revoked. The user lane reaches every socket the account has open,\n // including apps in other families that are legitimately still signed in, so the\n // server matches this against each socket's own session before delivering — a Tuner\n // being signed out must not take the console down with it.\n sessionId: z.string(),\n // WHY it was revoked, because the causes want opposite endings from the client:\n // \"signed-in-elsewhere\" and \"revoked-by-user\" mean show a sign-in screen that says\n // so; \"account-deleted\" means the user's own erasure request is being honoured and a\n // deletion flow elsewhere in the client owns the ending — do NOT render it as a\n // displacement. That distinction cannot be inferred client-side by timing: this push\n // is emitted inside the delete handler, so it consistently beats the DELETE's own\n // 202 to the client (measured 1–3 ms on live runs, Tuner 2026-08-09).\n reason: z.enum([\"signed-in-elsewhere\", \"revoked-by-user\", \"account-deleted\"]),\n /** Free-text detail for the sign-in screen, e.g. the app that took over. */\n detail: z.string().optional(),\n }),\n // Another install of this account deliberately took over a frequency's one audio\n // stream (a `takeover: true` ticket mint — contract §6). USER-TARGETED like\n // session.revoked, and further narrowed server-side to the socket whose install lost\n // the lease. The session it lands on is STILL SIGNED IN — the client stops playback,\n // shows \"playing elsewhere\", and must NOT auto-re-mint with takeover (that is what\n // would make two machines steal the stream from each other forever). A later\n // deliberate play press may take it back.\n z.object({\n type: z.literal(\"stream.displaced\"),\n frequencyId: z.string(),\n /** The server-issued installationId whose stream was taken — the loser, not the winner. */\n installationId: z.string(),\n // Always \"takeover\" on this lane (the HLS route is the only thing that publishes it),\n // and present anyway so a client can switch on one field across both lanes rather than\n // inferring the cause from which socket the message arrived on.\n reason: StreamDisplacedReasonSchema,\n }),\n // ONE LOCATION PER FREQUENCY (capability `one-location-per-frequency`, owner decision\n // 2026-09-26). Another install of this account tuned in to this frequency — to listen, to\n // talk, or to pick up a call — so this install must drop it. USER-TARGETED like\n // session.revoked, and narrowed server-side to the sockets that take part in the rule: an\n // app registered with `oneLocationPerFrequency` (the consoles: Service Manager,\n // Switchboard, Broadcast, Walkie), never the install that tuned, and never a Tuner, which\n // keeps its own HLS stream-lease rule in both directions.\n //\n // What a receiver MUST do: deactivate that frequency LOCALLY (tear down its media\n // connection, stop playing and transmitting), keep the app open and signed in, tell the\n // user, and NOT persist the untune to the account's saved tuning state, which is per USER\n // and now describes the location that took over. Never re-tune by itself: a later\n // deliberate tune takes it back. For a call's ephemeral frequency, leave the call locally\n // WITHOUT `DELETE /calls/:id`; the call carries on at the other install.\n z.object({\n type: z.literal(\"frequency.displaced\"),\n frequencyId: z.string(),\n /** The install that took the frequency (the winner). A receiver whose own installationId\n * matches must ignore the frame; the server already never sends it there. */\n byInstallationId: z.string(),\n reason: z.literal(\"tuned-elsewhere\"),\n }),\n // An owner or admin changed THIS user's listen and talk channels on a frequency\n // (capability member-tuning, `PUT /frequencies/:id/members/:userId/tuning-state`).\n // USER-TARGETED: only the member it is about receives it, on every connection of theirs.\n // It carries the same DELTA the admin sent, never a whole state, so applying it cannot\n // disturb anything the admin did not name (other channels, \"Users Transmitting\" picks).\n // The server has ALREADY stored the result in the member's tuning state and committed any\n // access it had to grant, so a client that is tuned applies the delta live, in any mic\n // mode, and re-declares `tuned`; one that is not tuned re-reads its saved tuning states so\n // the next tune restores it, and must NOT tune by itself. Ids the client cannot act on (a\n // channel it does not carry, a talk add it may not transmit on) are skipped. Never lifts\n // the receiver's own board mute. Show the member who did it: `byUserId` is a member of the\n // same frequency, resolvable to a callsign from the member list.\n z.object({\n type: z.literal(\"frequency.tuningSet\"),\n frequencyId: z.string(),\n byUserId: z.string(),\n listen: TuningDeltaSchema,\n talk: TuningDeltaSchema,\n }),\n // The caller's preset slots changed — one set, cleared, or a favorited frequency\n // deleted out from under them. USER-TARGETED like session.revoked, but delivered to\n // EVERY connection of the account with no per-session narrowing: the point of account\n // favorites is that the desktop hears about the phone's edit. A bare nudge on purpose —\n // refetch GET /favorites; it is at most MAX_FAVORITE_SLOT rows.\n z.object({ type: z.literal(\"favorites.updated\") }),\n // This account's own profile changed — a callsign rename (POST /users/me/callsign) or any\n // successful PATCH /users/me. USER-TARGETED like favorites.updated, delivered to EVERY\n // connection of the account with no per-session narrowing: the point is that the session\n // which did NOT make the change finds out.\n //\n // Why it carries the new callsign rather than being a bare nudge: the access token has a\n // `handle` claim and the realtime socket labels its connection from the TOKEN, so a\n // renamed user keeps announcing the old callsign into presence and rosters until its\n // token is replaced. A client that receives this must refresh its access token and let\n // the socket reconnect — that, not this payload, is what makes the rename visible to\n // everybody else. The payload is here so the client can repaint its own chrome\n // immediately instead of waiting for the round trip.\n //\n // ⚠️ **`avatar` and `avatarColor` are here because a suite has more than one place to\n // change them, and without this event the others never find out.** Switchboard carries\n // the same avatar picker this app does; a picture chosen there landed in the database and\n // reached a Service Manager session only if that session happened to re-read\n // `GET /users/me` — which only the Account page does. Every OTHER surface draws the face\n // from the cached `UserSummary`, so the app showed two different avatars at once, and it\n // survived a relaunch because that summary is on disk. Any app holding a user summary of\n // its OWN account must repaint from these fields.\n z.object({\n type: z.literal(\"profile.updated\"),\n handle: z.string().nullable(),\n displayName: z.string(),\n avatar: z.string().nullable(),\n avatarColor: z.string(),\n }),\n // This account's own presence status changed. USER-TARGETED and delivered to EVERY\n // connection of the account, on the favorites.updated precedent: the session that did\n // NOT make the change has to find out, and one of the two ways this fires has no session\n // behind it at all.\n //\n // It carries BOTH halves because they answer different questions and the client shows\n // both: `chosen` is what the picker's radio group should tick, `effective` is what the\n // lamp should paint. They differ whenever the platform has inferred something — a live\n // broadcast makes `effective` \"busy\" over a `chosen` of \"online\", exactly as auto-away\n // has always made it \"away\". `auto` says which, so the UI can explain a status the user\n // did not pick, which the standing \"a lamp must explain itself\" rule requires.\n //\n // The auto-busy edge is why this event exists rather than the client simply knowing: the\n // fact is derived server-side from the media node's heartbeat, so no client can compute\n // it, and a DJ's phone must show Busy for a show going out from their desktop.\n z.object({\n type: z.literal(\"user.status\"),\n chosen: UserStatusSchema,\n effective: UserStatusSchema,\n auto: z.boolean(),\n }),\n // Whether this account may send feedback changed (capability `feedback`). USER-TARGETED,\n // every connection of the account: a block raised by one app's submissions hides the\n // entry point in all of them, and an operator lifting it brings it back without a\n // relaunch. A boolean, so a duplicate delivery is inert. A client that missed the frame\n // converges on its next `GET /users/me`, which carries the same fact as `maySendFeedback`.\n z.object({\n type: z.literal(\"user.feedback\"),\n allowed: z.boolean(),\n }),\n /* -------------------------------------------------------------------- *\n * Contacts, chat, waves and calls (capability `contacts` / `group-calls`)\n *\n * ALL of these ride the USER lane (publishToUser). They have to: at ring\n * time a callee has no membership on the call frequency, and a contact\n * request comes from somebody who is not yet a contact — in both cases the\n * frequency lane would refuse a subscribe from exactly the party who needs\n * the event.\n *\n * Nothing here is ever published for a user whose effective status is\n * `invisible`, and there is deliberately no ring acknowledgement to a\n * caller: \"it's ringing\" would reveal that the callee holds a live socket,\n * which is the whole thing `invisible` exists to hide.\n * -------------------------------------------------------------------- */\n // Someone's status changed, or they connected/disconnected. Published only to\n // contacts who currently hold a socket (the reachability filter in\n // publishPresenceEdge) — an unreachable contact reseeds from GET /contacts on\n // connect, which is the contract's standing reseed rule, so the filter is lossless.\n z.object({\n type: z.literal(\"contact.presence\"),\n userId: z.string(),\n // The canonical schema, not a hand-copied enum: this literal read\n // `[\"online\",\"away\",\"offline\"]` and had to be found and widened by hand when `busy`\n // was added, which is exactly the drift a shared package exists to prevent.\n status: VisibleStatusSchema,\n /**\n * When this status was true, in ms since the epoch.\n *\n * ⚠️ **Hold the newest `at` you have seen per contact and IGNORE anything not newer —\n * including a `GET /contacts` response, which carries the same field.** Presence has two\n * sources and they must converge: an edge arriving while a reseed is in flight used to lose\n * to the older REST response, permanently, because the next correction only comes at the\n * contact's next genuine transition. That is not theoretical — it is the half of the 0.69.2\n * failure the server-side fix did not close, and a client that plays a sound on the\n * online/offline transition renders it as a logoff chime for somebody who is online.\n *\n * A wall clock rather than a counter, deliberately. `keysetId` exists because a restart\n * re-mints `epoch` at 0, and the chat relay's `seq` is an `INCR` with a TTL that restarts at\n * 1 — a presence counter would expire, reset, and then be ignored forever by any client\n * holding a higher value.\n */\n at: z.number().int(),\n }),\n // The contact GRAPH changed — a request accepted, a contact removed, someone\n // blocked. A bare nudge on purpose: refetch GET /contacts, which is at most\n // MAX_CONTACTS rows. The favorites.updated argument verbatim.\n z.object({ type: z.literal(\"contacts.updated\") }),\n // A new incoming contact request. Carries the sender because this is the one\n // event a client can get no other way — the requester is not yet a contact, so\n // there is no list the client could already be holding them in. The\n // invitation.created argument verbatim.\n z.object({ type: z.literal(\"contact.request\"), requestId: z.string(), fromUserId: z.string() }),\n // A relayed 1:1 message. Delivered to the recipient's lane AND echoed to the\n // sender's own lane, unnarrowed, so the sender's other sessions see what they\n // sent from the desktop.\n //\n // No history exists behind this: GET /contacts/:id/messages re-reads only what is\n // still in the relay buffer (CHAT_BUFFER_TTL_SECONDS), so a dropped frame is\n // recoverable for minutes, not forever. That is why it is classified critical.\n z.object({\n type: z.literal(\"contact.message\"),\n id: z.string(),\n seq: z.number().int(),\n fromUserId: z.string(),\n toUserId: z.string(),\n body: z.string(),\n sentAt: z.string(),\n clientMessageId: z.string().nullable(),\n // Message kinds (contract §15). DEFAULTED rather than required on the way in, so a frame\n // from a server that predates them still parses as plain text instead of being dropped.\n kind: ChatMessageKindSchema.default(\"text\"),\n refId: z.string().nullable().default(null),\n reaction: z.string().nullable().default(null),\n reactionRemove: z.boolean().default(false),\n replyTo: ChatReplyToSchema.nullable().default(null),\n tz: ChatTimeZoneSchema.nullable().default(null),\n offer: ChatFileOfferSchema.nullable().default(null),\n // Who sent it, when the two are NOT contacts (capability chat-non-contacts); null\n // between contacts. Defaulted for a server that predates it.\n sender: ChatSenderSchema.nullable().default(null),\n }),\n // The recipient drained their buffer up to `seq` — the delivery receipt, and the\n // same call that does the draining. Suppressed for an invisible recipient, whose\n // messages simply read as still buffered.\n z.object({ type: z.literal(\"contact.messageAck\"), peerUserId: z.string(), seq: z.number().int() }),\n // They are typing to you (or stopped). Live only: never buffered, expires on its own after\n // CHAT_TYPING_EXPIRES_SECONDS without a refresh, and never sent while the typist is\n // invisible or has switched typing indicators off.\n z.object({ type: z.literal(\"contact.typing\"), fromUserId: z.string(), typing: z.boolean() }),\n // A file transfer changed state (accepted, declined, cancelled, complete, failed). Sent to BOTH\n // parties. Critical: a missed \"accepted\" would leave the sender waiting with the recipient\n // ready, and GET /contacts/:id/files is the reconcile after a gap.\n // `attempt` is the record's connection attempt: `accepted` with a HIGHER attempt than the one\n // a client holds is a retry, and the sender's device holding the file starts again on it.\n z.object({ type: z.literal(\"contact.transfer\"), offerId: z.string(), fromUserId: z.string(), toUserId: z.string(), state: TransferStateSchema, attempt: z.int(), by: z.string() }),\n // WebRTC signalling for a transfer, relayed with every non-relay ICE candidate REMOVED by the\n // server (the IP mask, contract §20).\n z.object({\n type: z.literal(\"contact.transferSignal\"),\n offerId: z.string(),\n fromUserId: z.string(),\n // The attempt it belongs to. A client drops a signal for any attempt but its current one.\n attempt: z.int(),\n description: z.object({ type: z.enum([\"offer\", \"answer\"]), sdp: z.string() }).nullable(),\n candidate: z.object({ candidate: z.string(), sdpMid: z.string().nullable(), sdpMLineIndex: z.number().int().nullable() }).nullable(),\n }),\n // They have READ your messages up to this position (the ack is only \"their app has it\").\n // Live only, never stored (owner rule: no server-side read state); suppressed while the\n // reader is invisible or has switched read receipts off.\n z.object({ type: z.literal(\"contact.read\"), fromUserId: z.string(), upTo: z.object({ sentAt: z.string(), seq: z.number().int() }), at: z.string() }),\n // --- group chats (contract §15, \"Group chats\") ---------------------------------------\n // NEW event types rather than a `groupId` on contact.message, on purpose: a client that\n // predates groups ignores an unknown type, where an old one reading contact.message would\n // file a group's message under a single sender as if it were a 1:1.\n //\n // A message in a group. To every member it reached (and echoed to the sender's own lane).\n // Same relay rules and the same critical classification as contact.message.\n z.object({\n type: z.literal(\"chat.groupMessage\"),\n groupId: z.string(),\n id: z.string(),\n seq: z.number().int(),\n fromUserId: z.string(),\n body: z.string(),\n sentAt: z.string(),\n clientMessageId: z.string().nullable(),\n kind: ChatMessageKindSchema.default(\"text\"),\n refId: z.string().nullable().default(null),\n reaction: z.string().nullable().default(null),\n reactionRemove: z.boolean().default(false),\n replyTo: ChatReplyToSchema.nullable().default(null),\n tz: ChatTimeZoneSchema.nullable().default(null),\n offer: ChatFileOfferSchema.nullable().default(null),\n }),\n // A member drained their buffer up to `seq`: to every other member.\n z.object({ type: z.literal(\"chat.groupAck\"), groupId: z.string(), fromUserId: z.string(), seq: z.number().int() }),\n z.object({ type: z.literal(\"chat.groupTyping\"), groupId: z.string(), fromUserId: z.string(), typing: z.boolean() }),\n z.object({ type: z.literal(\"chat.groupRead\"), groupId: z.string(), fromUserId: z.string(), upTo: z.object({ sentAt: z.string(), seq: z.number().int() }), at: z.string() }),\n // The members changed, so the chat MOVED: `from` no longer exists for anybody and `to` is\n // where it went (null when fewer than two remain, or for the person who left). Sent to\n // everybody in either set, so the person leaving learns their window has closed. Nobody can\n // remove anybody else (owner rule), so a chat changes only by an add or by somebody leaving. `from` is\n // null for the person just ADDED: they were not in the old chat, and naming it relative to\n // them would point at a 1:1 of their own that has nothing to do with this one. `group`\n // carries the new set's labels, because members of a group need not be each other's contacts.\n z.object({\n type: z.literal(\"chat.membership\"),\n from: ChatConversationRefSchema.nullable(),\n to: ChatConversationRefSchema.nullable(),\n group: ChatGroupSchema.nullable(),\n change: z.enum([\"added\", \"left\"]),\n byUserId: z.string(),\n userId: z.string().describe(\"Who was added, or who left.\"),\n }),\n // A wave. Never buffered — a greeting delivered nine minutes late is worse than\n // none — and the send is always 204 whether or not this could be delivered,\n // because a \"recipient offline\" response would be a presence oracle.\n z.object({ type: z.literal(\"contact.wave\"), fromUserId: z.string(), at: z.string() }),\n // An incoming call. Invitee lane ONLY; there is no host-side twin (see above).\n //\n // `fromUserId` is whoever RANG THIS PERSON — the host on a call placed to several people\n // at once, but the inviter on somebody added to a call already in progress, which is not\n // the same party. `participantUserIds` is everybody already in or invited to the room, so\n // an invitee can see what they are being asked to join before they answer; it excludes\n // nobody, because a room you are about to enter is a room whose occupants you are\n // entitled to know. It does NOT reveal presence: being invited is not being online.\n z.object({\n type: z.literal(\"call.ringing\"),\n callId: z.string(),\n fromUserId: z.string(),\n participantUserIds: z.array(z.string()),\n expiresAt: z.string(),\n }),\n // Answered. Both lanes — the callee's other devices need it to stop ringing, and it\n // tells the caller their call was picked up.\n //\n // The frequencyId here is NOT news to the caller any more: they were given it at\n // ring by `POST /calls` and have been tuned and producing into the empty room ever\n // since, so that the container is up and their first word is carried. It is still\n // carried because the callee's other devices and any client reseeding across this\n // frame need it, and because a frame that means \"you are now connected\" should say\n // what to. What this event uniquely marks is the transition — dialing to connected,\n // and the moment an elapsed timer may start.\n z.object({\n type: z.literal(\"call.accepted\"),\n callId: z.string(),\n // Who answered (0.105.0, capability `call-accepted-answerer`). Only a frame naming THIS\n // user means \"stop ringing here\"; another user's answer leaves a group invitee ringing.\n userId: z.string(),\n frequencyId: z.string(),\n channelId: z.string(),\n audioMode: z.literal(\"open_mic\"),\n }),\n // Over, for any reason, to both lanes. Handling MUST be idempotent: the party who\n // hung up has already torn down locally when this arrives.\n //\n // `frequency.deleted` for the call frequency may arrive alongside this, and may\n // arrive first; this event is authoritative. So is the media proxy closing 4403\n // (\"membership revoked\") within its 30s revalidation window — that is the cascade\n // removing both memberships, and it is expected after a normal hangup rather than\n // a sign anything went wrong.\n z.object({\n type: z.literal(\"call.ended\"),\n callId: z.string(),\n // ⚠️ **The schema, never a second copy of its members.** This was a hand-written\n // duplicate of `CallEndReasonSchema` and the two were one edit away from disagreeing:\n // adding `removed` to the source left this one refusing the very frame the server had\n // just started sending, and the only thing that caught it was the compiler happening to\n // be asked. A rule spelled out in two places is a rule that gets half-updated.\n reason: CallEndReasonSchema,\n }),\n // One participant's state changed — somebody answered, went on hold, came back, or left.\n //\n // ⚠️ **Delivered to the participants of THIS call and nobody else.** It says a named\n // person is on a call right now, which is a presence fact of the strongest kind; it is\n // only ever sent to people who are in the room with them and can hear that for themselves.\n //\n // This is the frame that makes a group call legible, and it is why `left` is a state\n // rather than a removal: a client that is told somebody left can say so, where a client\n // handed a shorter list has to diff two rosters to work out what happened.\n z.object({\n type: z.literal(\"call.participant\"),\n callId: z.string(),\n userId: z.string(),\n state: z.enum([\"ringing\", \"active\", \"held\", \"left\"]),\n }),\n // The host is moving everybody off this ad-hoc call and onto a real frequency.\n //\n // ⚠️ **Ordering is load-bearing: this is published BEFORE the call is torn down.** A\n // `call.ended`, the call frequency's `frequency.deleted` and the media proxy's 4403 all\n // follow within moments, and a client that learned where to go only after them would have\n // torn its call state down and landed nowhere.\n //\n // ⚠️ **It MAY have granted access** (0.75.0, capability `call-move-grant`): a move sent\n // with `grantAccess: true` makes participants who could not reach the target permanent\n // members of it, and every one of those grants has committed and published its own\n // `membership.updated` BEFORE this frame goes out. So a client receiving this already has\n // the membership it needs, and must not treat the frame as proof it had access before.\n //\n // Who is TOLD is still wider than who was granted: everybody in the call who can reach the\n // target gets this, including somebody whose phone is still ringing, while only\n // participants who answered and are not masked could have been granted. A participant who\n // still cannot reach it is simply not sent this frame, as before.\n z.object({\n type: z.literal(\"call.movedToFrequency\"),\n callId: z.string(),\n frequencyId: z.string(),\n channelId: z.string(),\n }),\n // Two calls became one — the phone's Merge. `callId` is the call that was ABSORBED and no\n // longer exists; `intoCallId` and its frequency are where everybody went.\n //\n // ⚠️ **Ordering is load-bearing, exactly as it is for `call.movedToFrequency`: this is\n // published BEFORE the absorbed call is torn down.** The `call.ended` (reason `merged`),\n // the absorbed frequency's `frequency.deleted` and the media proxy's 4403 all follow\n // within moments, and a client told where to go only after them has already dropped its\n // call state and landed nowhere.\n //\n // It reaches everybody who was in the absorbed call, INCLUDING whoever pressed Merge —\n // who is in both rooms and therefore already where this frame is pointing. Handling must\n // be idempotent about that: the surviving call may already be on screen and connected.\n z.object({\n type: z.literal(\"call.merged\"),\n callId: z.string(),\n intoCallId: z.string(),\n frequencyId: z.string(),\n channelId: z.string(),\n audioMode: z.literal(\"open_mic\"),\n }),\n z.object({ type: z.literal(\"error\"), message: z.string() }),\n]);\nexport type ServerToClientEvent = z.infer<typeof ServerToClientEventSchema>;\n\n/* ------------------------------------------------------------------------ *\n * Media-node signaling contract (wss://media-node/signal?token=...)\n * mediasoup-flavored: one transport for send, one for receive, per client.\n * ------------------------------------------------------------------------ */\n\nexport const MediaClientToServerSchema = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"auth\"),\n token: z.string(),\n // M1 native transport: the client asks for a native datapath identity with its auth.\n // The node answers with authOk.native ONLY when its generation is cleared to serve\n // (the §3.2 handshake in docs/m1-threat-model.md, mirrored from ../switchboard) — an\n // authOk WITHOUT the block means \"not cleared yet, retry auth shortly\", never an\n // error. Browser/mediasoup clients omit this and are untouched.\n nativeTransport: z.literal(true).optional(),\n // SHARE container only (capability `share-camera`): this connection is the install's CAMERA\n // lane, a second connection beside its ordinary one. It is replaced only by the same install's\n // next camera connection, never by its ordinary one, and it may start only `camera` shares.\n // Its own connection, so its own datapath identity: the node forwards per SENDER, so viewers\n // of the camera and viewers of the screen are separate sets and neither carries the other.\n shareLane: z.literal(\"camera\").optional(),\n }),\n z.object({ type: z.literal(\"getRouterRtpCapabilities\") }),\n z.object({\n type: z.literal(\"createTransport\"),\n direction: z.enum([\"send\", \"recv\"]),\n }),\n z.object({\n type: z.literal(\"connectTransport\"),\n transportId: z.string(),\n dtlsParameters: z.unknown(),\n }),\n z.object({\n type: z.literal(\"produce\"),\n transportId: z.string(),\n channelId: z.string(),\n kind: z.literal(\"audio\"),\n rtpParameters: z.unknown(),\n // Group channels this one stream should also be pickup-able on, beyond its home\n // channelId — see setProducerRelays.\n relayChannelIds: z.array(z.string()).optional().default([]),\n // Opaque, stable identifier for the CAPTURE SOURCE feeding this producer (client-side\n // hash of the input device; \"default\" for the system default). Two producers from the\n // same client with different sourceKeys carry genuinely different audio (Stage C\n // per-channel mics) and must BOTH be heard by listeners; equal\n // (user, device, sourceKey) across frequencies means identical audio to de-dup once.\n // Required — a defaulted sourceKey collapses distinct mics into one de-dup bucket\n // and silences one of them, which is worse than refusing the produce.\n sourceKey: z.string().min(1),\n // Capture profile of this producer. The media node uses it ONLY to pick the\n // producer's on-air label: a \"broadcast\" (program audio) producer is labeled with\n // the join token's org stationCallsign when present, while \"voice\" producers keep\n // the personal callsign — the DJ streams as the station but talks as themselves.\n // Encoding stays producer-driven; the media node remains otherwise profile-blind.\n // Required for the same reason as pauseProducer.reason below: pre-release, the\n // client version floor moves instead of a legacy branch being kept.\n profile: z.enum([\"voice\", \"broadcast\"]),\n // Ask to be told (`listenerReady`) each time a listener of this producer can actually HEAR\n // it: their consumer resumed AND their receive transport connected. Opt-in so no other app\n // ever receives a message type it does not know. The answering machine sets it, so its\n // greeting waits for the caller instead of starting into a line nobody is on yet.\n notifyListenerReady: z.boolean().optional(),\n }),\n z.object({ type: z.literal(\"closeProducer\"), producerId: z.string() }),\n // `reason` distinguishes two gestures that arrive as the same pause frame but carry\n // opposite station-stage policy: HARD MUTE (\"mute\") holds a broadcast station in\n // dead_air indefinitely while connected; TRANSMIT OFF (\"transmit_off\") ends arming\n // immediately (off_air, container idle-reaps). Required — pre-release, no legacy\n // reason-less branch; the client version floor moves instead.\n z.object({ type: z.literal(\"pauseProducer\"), producerId: z.string(), reason: z.enum([\"mute\", \"transmit_off\"]) }),\n z.object({ type: z.literal(\"resumeProducer\"), producerId: z.string() }),\n // Every user has exactly one producer (their personal channel). Which OTHER channels\n // can currently pick it up is a live, self-controlled choice, not a separate stream per\n // channel — this updates that set on the existing producer without renegotiating it.\n z.object({ type: z.literal(\"setProducerRelays\"), producerId: z.string(), relayChannelIds: z.array(z.string()) }),\n // ---- M1 native transport: stream announcement -------------------------------------\n // A native sender has no mediasoup producer to announce it (that is the entire point —\n // no WebRTC stack in the engine), yet the node's forward sets and the listener's\n // attribution binding both need to know a stream exists, whose it is, and which channels\n // it may be picked up on. These three messages are the native mirror of\n // produce/closeProducer/setProducerRelays, carrying the same routing facts with none of\n // the RTP negotiation. Everything downstream (permission gate, relay reconciliation\n // against the 5s snapshot, matched-channel relevance) is the SAME code path as mediasoup\n // producers — deliberately, so the two transports cannot drift on \"heard exactly once\".\n z.object({\n type: z.literal(\"nativeProduce\"),\n channelId: z.string(),\n relayChannelIds: z.array(z.string()).optional().default([]),\n // Required, exactly as on produce above — the two transports must not drift on the\n // facts that drive de-dup and on-air labelling.\n sourceKey: z.string().min(1),\n profile: z.enum([\"voice\", \"broadcast\"]),\n // What this sender is encoding (2026-08-03). OPTIONAL and purely descriptive: nothing\n // routes on it, an engine that omits it works exactly as before, and the server reports\n // \"not stated\" rather than inventing a value.\n //\n // It has to be DECLARED because the wire protocol is deliberately codec-opaque — the\n // datapath forwards sealed bytes it could not inspect if it wanted to — so unlike the\n // mediasoup path, where the same facts are read off the negotiated rtpParameters, there\n // is nothing here to measure. Send it once per stream, matching what the encoder is\n // configured with; a station's listeners are told this is what was put on the air.\n encoding: z\n .object({\n codec: z.string(),\n bitrateKbps: z.number().nullable(),\n sampleRate: z.number(),\n channels: z.number(),\n fec: z.boolean(),\n dtx: z.boolean(),\n frameMs: z.number().nullable(),\n })\n .optional(),\n }),\n z.object({ type: z.literal(\"closeNativeStream\"), streamId: z.number().int().positive() }),\n // HARD MUTE for a native sender (0.74.0). The stream stays REGISTERED and stops counting\n // as unpaused, so a broadcast station falls through to `broadcastAudio: \"silent\"` and\n // holds `dead_air` indefinitely while the signaling session is up — exactly what\n // pauseProducer's `reason: \"mute\"` does on the mediasoup path. Before this there was no\n // way to express it: the only frame a native sender had was closeNativeStream, which IS\n // transmit-off, so a muted station read `off_air`, dropped off the public dial mid-show,\n // answered listeners 503 OFF_AIR, and had nothing but the container's idle TTL standing\n // between it and being reaped.\n //\n // Deliberately NO `reason` field, and this is the one place the native pair departs from\n // the mediasoup one. `pauseProducer.reason` exists because ONE gesture there carries two\n // opposite station-stage policies; here those two gestures are already two different\n // frames, and closeNativeStream IS transmit-off. A `reason` would be a second spelling of\n // a fact the frame name already carries, and the first thing that goes wrong is the two\n // spellings disagreeing. A hard-muted native operator who then flips TRANSMIT OFF sends\n // closeNativeStream, which works unchanged from the paused state — no re-send, no\n // reclassification.\n z.object({ type: z.literal(\"pauseNativeStream\"), streamId: z.number().int().positive() }),\n z.object({ type: z.literal(\"resumeNativeStream\"), streamId: z.number().int().positive() }),\n z.object({\n type: z.literal(\"setNativeStreamRelays\"),\n streamId: z.number().int().positive(),\n relayChannelIds: z.array(z.string()),\n }),\n // ---- Screen share on the native transport (capability `screen-share`, 0.81.0) --------\n // A share is the first non-voice media the platform carries, and it is deliberately NOT a\n // voice stream: its audience is everybody tuned to the frequency who ASKS for it, not a\n // channel's listeners, so it lives in its own registry on the node and never touches the\n // voice relevance model, the browser bridge or the HLS mix. Native connections only.\n //\n // Its own frame rather than a `profile` on nativeProduce: that frame REQUIRES a home channel\n // and a sourceKey (a defaulted sourceKey silences a mic, which is why it is required), and a\n // share has neither. Folding the two together would make both fields optional for voice too.\n //\n // Sealed ONCE, under the frequency's share key (header channelId = SHARE_CHANNEL_ID): no\n // carrying set, no home copy. Ended by the existing closeNativeStream { streamId }. Requires\n // talk permission on at least one channel of the frequency. Does NOT supersede, retire or\n // pause the sender's voice, on this install or any other. One `screen` and one\n // `screen-audio` per connection; a second of the same profile replaces the first. `camera`\n // (capability `share-camera`) is a webcam, H.264 like `screen`, started only on a camera-lane\n // connection (`auth.shareLane`), never leased (the one-share-per-person rule is the SCREEN's).\n z.object({\n type: z.literal(\"nativeShare\"),\n profile: z.enum([\"screen\", \"screen-audio\", \"camera\"]),\n // Bounded free text, not an enum: the node routes nothing on it and only matches it\n // against a viewer's declared decoders, so a new codec needs no node release.\n codec: z.string().min(1).max(32),\n // Video only. Descriptive: announced to viewers, enforced by nothing.\n width: z.number().int().positive().max(16_384).optional(),\n height: z.number().int().positive().max(16_384).optional(),\n fps: z.number().positive().max(240).optional(),\n // Video only, descriptive too: what a viewer's Point, Draw, Control and sound can do on this\n // share, as the sharer's app knows it (share/tools.ts). Relayed on shareStarted unchanged.\n tools: ShareToolsWireSchema.optional(),\n }),\n // OPT-IN forwarding. A share reaches exactly the connections that subscribed and are still\n // tuned, which is what keeps an older client that would feed video bytes to its Opus decoder\n // from ever receiving one. `decoders` must include the share's codec or the subscription is\n // refused. One subscription carries BOTH of that sharer's streams (see SHARE_CHANNEL_ID).\n z.object({\n type: z.literal(\"subscribeShare\"),\n streamId: z.number().int().positive(),\n decoders: z.array(z.string().min(1).max(32)).min(1).max(16),\n }),\n z.object({ type: z.literal(\"unsubscribeShare\"), streamId: z.number().int().positive() }),\n // SHARE CONTAINER only (capability `share-webtransport`): ask for a WebTransport ticket, the\n // browser's way onto the native datapath. Answered with `shareTransport` or with\n // permissionDenied {action: \"shareTransport\"}. Ask again whenever a session must be (re)opened:\n // a ticket expires in a minute, and the certificate hashes rotate.\n z.object({ type: z.literal(\"shareTransport\") }),\n // Viewer -> node -> sharer. Keyframe requests are aggregated to at most one per second per\n // share however many viewers ask; rfi and stats are relayed as they arrive, rate-limited\n // per viewer so one client cannot flood the sharer's signaling lane.\n z.object({\n type: z.literal(\"shareFeedback\"),\n streamId: z.number().int().positive(),\n kind: z.enum([\"keyframe\", \"rfi\", \"stats\"]),\n frameId: z.number().int().nonnegative().max(0xffff_ffff).optional(),\n loss: z.number().min(0).max(1).optional(),\n residualLoss: z.number().min(0).max(1).optional(),\n rttMs: z.number().nonnegative().max(60_000).optional(),\n kbps: z.number().nonnegative().max(1_000_000).optional(),\n // `stats` only (Service Manager, 2026-09-30): the box this viewer shows the share in, in\n // DEVICE pixels (CSS size x devicePixelRatio). The sharer encodes no larger than the biggest\n // viewer needs (packages/shared/src/share/viewerSize.ts); absent reads as \"full size\", so an\n // older viewer, or one whose window is hidden, never shrinks anybody's picture.\n viewWidth: z.number().int().positive().max(16_384).optional(),\n viewHeight: z.number().int().positive().max(16_384).optional(),\n }),\n // Viewer -> node -> the sharer and every other viewer (capability `share-pointer`): a pointer\n // move or a piece of ink on a share this connection is WATCHING. `sealed` is opaque to the node\n // (packages/shared/src/share/pointer.ts: a key derived from the share key, the sender's datapath\n // id bound in the AAD), which checks only that the sender subscribes and caps the rate.\n z.object({ type: z.literal(\"sharePointer\"), streamId: z.number().int().positive(), sealed: z.string().min(1).max(MAX_SEALED_POINTER_CHARS) }),\n // The sharer changes their share's `tools` mid-share (2026-10-05): the streamer's Allow\n // drawing / Allow control switches. Owner only; the node relays it as `shareToolsChanged`\n // and enforces the two allow fields from then on.\n z.object({ type: z.literal(\"shareTools\"), streamId: z.number().int().positive(), tools: ShareToolsWireSchema }),\n // Viewer <-> sharer (capability `share-control`): one step of a remote-control exchange, or a\n // batch of input, addressed to ONE datapath id (`to`). From a viewer it may go only to the\n // share's owner; from the owner, only to a current viewer. `sealed` is opaque to the node\n // (packages/shared/src/share/control.ts: sender and recipient bound in the AAD, and the input\n // sealed again under a key only the two installs hold).\n z.object({\n type: z.literal(\"shareControl\"),\n streamId: z.number().int().positive(),\n to: z.number().int().nonnegative().max(0xffff_ffff),\n sealed: z.string().min(1).max(MAX_SEALED_CONTROL_CHARS),\n }),\n z.object({ type: z.literal(\"subscribeChannel\"), channelId: z.string() }),\n z.object({ type: z.literal(\"unsubscribeChannel\"), channelId: z.string() }),\n z.object({\n type: z.literal(\"consume\"),\n transportId: z.string(),\n producerId: z.string(),\n // Which of the producer's (home or relay) channels this listener is consuming it\n // under — needed so unsubscribing from that specific channel later closes the right\n // consumers even though the same producer may be relevant under several channels.\n channelId: z.string(),\n rtpCapabilities: z.unknown(),\n }),\n z.object({ type: z.literal(\"resumeConsumer\"), consumerId: z.string() }),\n z.object({ type: z.literal(\"ping\") }),\n]);\nexport type MediaClientToServer = z.infer<typeof MediaClientToServerSchema>;\n\nexport const MediaServerToClientSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"pong\") }),\n z.object({\n type: z.literal(\"authOk\"),\n userId: z.string(),\n // Null for listener-only accounts (email-only signup — no callsign yet). Such a\n // connection can subscribe and consume but every produce path is refused.\n callsign: z.string().nullable(),\n // M1 native transport (requested via auth.nativeTransport, granted only when the node's\n // generation is cleared — §3.2). connectionId is uint32, NODE-allocated, generation-\n // scoped, fresh on every auth, never reused within a generation: it is the nonce input\n // whose uniqueness the whole record layer rests on, which is exactly why it is issued\n // here and not in TuneResult (the control plane restarts on every deploy while node\n // generations live on). senderMacKey is 32 bytes base64 — the per-connection\n // AES-256-GMAC key (SENDER_MAC in nativeTransport.ts); it shares this connection's\n // lifetime, which is what makes reusing the (connectionId, sequence) nonce under it\n // sound. bootId names the generation so the engine can correlate against TuneResult's\n // channel-key set.\n native: z\n .object({\n connectionId: z.number().int().nonnegative(),\n senderMacKey: z.string(),\n bootId: z.string(),\n // The native wire versions THIS container's datapath accepts (nativeTransport.ts,\n // NATIVE_TRANSPORT_WIRE_V2). The container answers for itself because a deploy is not a\n // fleet upgrade: a running container keeps its image until it is recycled. A sender\n // uses wire v2 only when 2 is listed. ABSENT means [1] (a container from before 0.107.0),\n // which is why the field is optional: its absence is the signal, not a missing value.\n wireVersions: z.array(z.number().int().positive()).optional(),\n })\n .optional(),\n }),\n z.object({ type: z.literal(\"authError\"), message: z.string() }),\n z.object({ type: z.literal(\"routerRtpCapabilities\"), rtpCapabilities: z.unknown() }),\n z.object({\n type: z.literal(\"transportCreated\"),\n transportId: z.string(),\n direction: z.enum([\"send\", \"recv\"]),\n iceParameters: z.unknown(),\n iceCandidates: z.unknown(),\n dtlsParameters: z.unknown(),\n }),\n z.object({ type: z.literal(\"transportConnected\"), transportId: z.string() }),\n z.object({ type: z.literal(\"produced\"), producerId: z.string(), channelId: z.string() }),\n z.object({\n type: z.literal(\"newProducer\"),\n producerId: z.string(),\n channelId: z.string(),\n producerUserId: z.string(),\n producerCallsign: z.string(),\n // Identifies which of the producer's devices this stream comes from, so\n // cross-frequency de-dup can key on (user, device) — two devices of one user are\n // BOTH audible, while the same device heard via two frequencies is still mixed once.\n producerDeviceId: z.string().min(1),\n producerSourceKey: z.string().min(1), // capture source within the device — see produce.sourceKey\n // Capture profile of the producer (see produce.profile). Listeners key cross-frequency\n // de-dup decisions on it — broadcast program streams are never collapsed across\n // frequencies, even from one device (one operator running several stations off one\n // capture rig is supported), while the same voice heard via two frequencies still\n // mixes once.\n producerProfile: z.enum([\"voice\", \"broadcast\"]),\n }),\n z.object({ type: z.literal(\"producerClosed\"), producerId: z.string(), channelId: z.string() }),\n // ---- M1 native transport: stream announcement (server side) ------------------------\n // Ack for the sender's own nativeProduce: the uint32 that goes in the sealed payload's\n // streamId field (PAYLOAD.STREAM_ID_OFFSET). Room-scoped, monotonic, never rebound — a\n // producer takeover is closeNativeStream + a FRESH id, never the same id pointed at\n // something new (threat model §3.4).\n z.object({ type: z.literal(\"nativeProduced\"), streamId: z.number().int().positive(), channelId: z.string() }),\n // Pushed to every listener for whom this stream is (now) relevant, under the channel it\n // is relevant VIA — the native mirror of newProducer, and the binding §3.4 requires: a\n // listener MUST check that a packet's payload streamId belongs to the header's\n // connectionId before trusting attribution, because streamId rides INSIDE the\n // channel-keyed envelope and is therefore forgeable by any other holder of that channel\n // key. Without this announcement that check has nothing to check against.\n z.object({\n type: z.literal(\"nativeStream\"),\n streamId: z.number().int().positive(),\n // The sender's uint32 datapath connectionId — the header field this streamId must\n // agree with. This is the whole point of the message.\n connectionId: z.number().int().nonnegative(),\n channelId: z.string(),\n producerUserId: z.string(),\n producerCallsign: z.string(),\n producerDeviceId: z.string().optional(),\n producerSourceKey: z.string().optional(),\n }),\n z.object({ type: z.literal(\"nativeStreamClosed\"), streamId: z.number().int().positive(), channelId: z.string() }),\n // ---- Screen share (capability `screen-share`, 0.81.0) ----------------------------------\n // Ack for the sharer's own nativeShare: the streamId its sealed share payloads carry.\n // Allocated from the same never-rebound counter as voice streams.\n z.object({ type: z.literal(\"nativeShareProduced\"), streamId: z.number().int().positive(), profile: z.enum([\"screen\", \"screen-audio\", \"camera\"]) }),\n // The answer to `shareTransport`. Open `new WebTransport(url, {serverCertificateHashes})` with\n // each `value` decoded from hex, before `expiresAt` (unix seconds), then send and receive the\n // same sealed datagrams a native client sends over UDP. Both hashes are needed: the door may\n // rotate its certificate between this frame and the handshake. `tunnel` is the same ticket for\n // the TCP fallback (capability `share-tcp-fallback`): where UDP is blocked, open a WebSocket on\n // the signaling URL with its final `/signal` replaced by `/tunnel` and `ticket=<tunnel>` added to\n // its query, and carry each datagram as one binary message.\n z.object({\n type: z.literal(\"shareTransport\"),\n url: z.string(),\n certificateHashes: z.array(z.object({ algorithm: z.literal(\"sha-256\"), value: z.string().regex(/^[0-9a-f]{64}$/) })).min(1),\n expiresAt: z.number().int().positive(),\n tunnel: z.string().regex(/^[0-9a-f]{56}$/),\n }),\n // To every NATIVE connection tuned to the frequency, and replayed to one that tunes in\n // mid-share. New types rather than fields on nativeStream, so an older client ignores them.\n // `connectionId` is the owner binding STREAM_ATTRIBUTION_REQUIRES_OWNER_CHECK asks for, as\n // on nativeStream: the share key is held by every member, so any member could forge one.\n z.object({\n type: z.literal(\"shareStarted\"),\n streamId: z.number().int().positive(),\n connectionId: z.number().int().nonnegative(),\n userId: z.string(),\n callsign: z.string(),\n deviceId: z.string(),\n kind: z.enum([\"video\", \"audio\"]),\n codec: z.string(),\n width: z.number().int().positive().optional(),\n height: z.number().int().positive().optional(),\n fps: z.number().positive().optional(),\n // The sharer's `nativeShare.tools`, as sent (video only). Read it with readShareTools.\n tools: ShareToolsWireSchema.optional(),\n // \"camera\": a webcam (capability `share-camera`), shown in a face window of its own rather\n // than as a screen. Absent: a screen share or its sound. A client that does not know the\n // field reads a camera as one more screen share, which is a picture it can still show.\n source: z.literal(\"camera\").optional(),\n }),\n // The share is over: closed, replaced, the sharer left, or they no longer hold talk on any\n // channel. Any subscription to it is gone with it.\n z.object({ type: z.literal(\"shareEnded\"), streamId: z.number().int().positive() }),\n // To the SHARER only: who is watching this share right now, sent whenever it changes (and\n // once, empty, when the share starts). `count` is how many installs are watching, on any\n // frequency (2026-10-05, owner: \"count only\" off a call). `viewers` NAMES them, on a CALL\n // only: one entry per viewing install, so the sharer's own second device appears under their\n // own name; the sharer's self-view is in neither. Off a call `viewers` is always empty, because\n // naming a viewer could reveal an `invisible` member (the join token's `watchingVisible` claim\n // is the switch); a count reveals nothing the tuned roster does not.\n z.object({\n type: z.literal(\"shareViewers\"),\n streamId: z.number().int().positive(),\n viewers: z.array(z.object({ userId: z.string(), callsign: z.string().nullable(), deviceId: z.string() })),\n count: z.number().int().min(0).optional(),\n }),\n // To every native member: the sharer changed what viewers may do mid-share (`shareTools`).\n // Replaces the `tools` the share was announced with.\n z.object({ type: z.literal(\"shareToolsChanged\"), streamId: z.number().int().positive(), tools: ShareToolsWireSchema }),\n // To the SHARER only: a viewer's feedback, relayed. `fromConnectionId` is the viewer's\n // datapath id, absent on an aggregated keyframe request (which stands for all of them).\n z.object({\n type: z.literal(\"shareFeedback\"),\n streamId: z.number().int().positive(),\n kind: z.enum([\"keyframe\", \"rfi\", \"stats\"]),\n fromConnectionId: z.number().int().nonnegative().optional(),\n frameId: z.number().int().nonnegative().optional(),\n loss: z.number().optional(),\n residualLoss: z.number().optional(),\n rttMs: z.number().optional(),\n kbps: z.number().optional(),\n viewWidth: z.number().optional(),\n viewHeight: z.number().optional(),\n }),\n // A viewer's pointer or ink, relayed to the sharer and the share's other viewers. The node\n // stamps who sent it (`fromConnectionId`, their datapath id, which the seal's AAD also binds, and\n // their callsign for the label) and cannot read it.\n z.object({\n type: z.literal(\"sharePointer\"),\n streamId: z.number().int().positive(),\n fromConnectionId: z.number().int().nonnegative(),\n callsign: z.string().nullable(),\n sealed: z.string().min(1).max(MAX_SEALED_POINTER_CHARS),\n }),\n // A remote-control message for us, from `fromConnectionId` (the sender's datapath id, stamped by\n // the node, which the seal's AAD also binds). The node cannot read it.\n z.object({\n type: z.literal(\"shareControl\"),\n streamId: z.number().int().positive(),\n fromConnectionId: z.number().int().nonnegative(),\n callsign: z.string().nullable(),\n sealed: z.string().min(1).max(MAX_SEALED_CONTROL_CHARS),\n }),\n /**\n * The frequency's native channel keys have moved; the ones you hold are stale (issue #75).\n *\n * Carries NO key material — deliberately. The media node holds channel keys only for the\n * channels it actively bridges (audio-routing-contract.md, \"the node reads only what it must\")\n * and an all-native channel stays node-blind; shipping keys through this lane to save the\n * client a request would quietly end that property. Fetch them from the control plane instead:\n * `GET /frequencies/:id/native-keys`, and JITTER it (contract §10) — the triggering event is\n * frequency-wide, so every native client is told at the same instant.\n *\n * Then INSTALL, do not re-tune. Re-tune mints a new connectionId, senderMac key and stream\n * ids, so it interrupts audio and rebuilds session state on an event that fires whenever\n * anyone leaves the frequency, is removed, is banned, or the generation changes. Keep sealing\n * under the previous epoch until the new ring is in, so nothing is clipped across the swap.\n *\n * Compare `keysetId`, not `epoch`: a control-plane restart re-mints at epoch 0 with different\n * bytes, so the epoch alone cannot tell you the material changed.\n *\n * Why this exists at all: before it, a client's epoch was frozen at tune time while the server\n * rotated, so a talker that had been on air a while went silently inaudible to everyone who\n * tuned after it — and because the STALE party is the sender, a listener that noticed could\n * only re-tune itself, which never helped and looped.\n */\n z.object({\n type: z.literal(\"nativeKeysRotated\"),\n keysetId: z.string(),\n epoch: z.number().int().min(0).max(255),\n }),\n z.object({\n type: z.literal(\"consumed\"),\n consumerId: z.string(),\n producerId: z.string(),\n channelId: z.string(),\n kind: z.literal(\"audio\"),\n rtpParameters: z.unknown(),\n producerUserId: z.string(),\n producerCallsign: z.string(),\n producerDeviceId: z.string().optional(), // see newProducer\n producerSourceKey: z.string().optional(), // see produce.sourceKey\n producerProfile: z.enum([\"voice\", \"broadcast\"]), // see newProducer — required there too\n }),\n z.object({ type: z.literal(\"consumerClosed\"), consumerId: z.string() }),\n /**\n * A listener of this connection's producer can now hear it: their consumer is resumed and\n * their receive transport's DTLS is connected. Sent only for a producer produced with\n * `notifyListenerReady: true`, once per consumer, to the producer's own connection.\n */\n z.object({ type: z.literal(\"listenerReady\"), producerId: z.string(), listenerUserId: z.string() }),\n z.object({\n type: z.literal(\"permissionDenied\"),\n action: z.string(),\n channelId: z.string().optional(),\n reason: z.string(),\n }),\n /**\n * Another install of THIS account took over transmit on this frequency, and this\n * connection's producers and native streams have been retired (transmit exclusivity —\n * one transmitting install per (user, frequency), newest wins; audio-routing-contract.md).\n *\n * Sent to every connection of the LOSING install, before nothing else changes: the socket\n * is deliberately NOT closed. A 4409 means \"this session was signed out and will never be\n * accepted again\", and none of that is true here — the displaced session is valid, it\n * simply is not the one on the air. Closing it would also make the client reconnect and\n * re-arm, i.e. steal the stream straight back, which is the exact loop the HLS lane's\n * no-auto-retry rule exists to prevent.\n *\n * A NEW message type rather than a `reason` on `producerClosed`/`nativeStreamClosed`,\n * because those two are LISTENER-facing (an announcement being withdrawn). Overloading\n * them would make one message mean two different things depending on who read it — and\n * the displaced sender does receive those too, for its own streams.\n *\n * Client contract: disarm TX, surface it (\"Transmitting somewhere else\"), and do NOT\n * re-arm by itself. A later deliberate press may take it back.\n */\n z.object({\n type: z.literal(\"streamDisplaced\"),\n frequencyId: z.string(),\n reason: StreamDisplacedReasonSchema,\n /** The install that TOOK it — the winner. The loser is whoever received this. */\n displacedBy: z.object({ installationId: z.string() }),\n }),\n z.object({ type: z.literal(\"error\"), message: z.string() }),\n]);\nexport type MediaServerToClient = z.infer<typeof MediaServerToClientSchema>;\n","import { z } from \"zod\";\nimport { USER_KIND_DESCRIPTION, UserKindSchema } from \"./userKind.js\";\nimport type {\n Channel,\n Frequency,\n FrequencyStation,\n FrequencySuspension,\n MediaNodeStatus,\n NowPlaying,\n Organization,\n OrganizationMember,\n StationDetail,\n StationLiveState,\n StreamInfo,\n UserSummary,\n} from \"./domain.js\";\nimport type { OrgRole } from \"./orgPermissions.js\";\nimport { BandPlansSchema } from \"./frequency.js\";\nimport { ChannelPhoneSummarySchema } from \"./pstn.js\";\nimport {\n CallEndReasonSchema,\n CallParticipantKindSchema,\n CallParticipantStateSchema,\n AccountNotificationDefaultsSchema,\n ChatMessageKindSchema,\n ChatReplyToSchema,\n ChatTimeZoneSchema,\n ChatFileOfferSchema,\n ChatSenderSchema,\n ChatTransferLimitsSchema,\n TransferStateSchema,\n ContactPreferencesSchema,\n ContactRequestStatusSchema,\n SoundCategorySchema,\n UserStatusSchema,\n VisibleStatusSchema,\n} from \"./contacts.js\";\nimport type {\n BillingInvoicesDto,\n BillingPaymentMethodDto,\n BillingStatusDto,\n BillingSubscriptionDto,\n PlanChangePreviewDto,\n PlanChangeResultDto,\n PlanChangeStartDto,\n SubscribeResultDto,\n SubscriptionMutationDto,\n} from \"./api.js\";\n\n/**\n * Response schemas — the shape of what the control plane SENDS.\n *\n * Request bodies have been described in api.ts for a while; responses never were. They\n * were hand-built object literals inside each handler, which meant the only way to learn\n * what a call returns was to make one and look, and nothing stopped a field from being\n * renamed or dropped between releases. These are attached to the routes, so they both\n * generate the OpenAPI spec and are enforced on the way out.\n *\n * Enforcement cuts both ways and is worth stating plainly: a key not described here is\n * STRIPPED from the response. That is deliberate — it is what stops an internal field\n * from leaking by accident — but it means adding a field to a handler without adding it\n * here silently does nothing.\n */\n\n/** Mutual assignability: fails if either side gains or loses a field. */\ntype Same<A, B> = A extends B ? (B extends A ? true : never) : never;\n\n// ---- Common ---------------------------------------------------------------------------\n\nexport const OkSchema = z.object({ ok: z.literal(true) });\n\n// ---- Users ----------------------------------------------------------------------------\n\n/**\n * A user as OTHER people see them. Deliberately carries no email — see UserSearch below —\n * and, since 2026-08-29, NO REAL NAME.\n *\n * `handle` + `stationId` are the whole identity surface a third party ever gets (owner\n * rule). A person's name is a BILLING field: it is collected once at signup for the\n * invoice, the receipt and the card statement, it lives on UserProfile, and it is\n * returned only to the account holder themselves. It used to ride on this DTO, which put\n * a real name in front of every member list, ban list, company roster, listener ledger\n * and — via `GET /users/search` — any authenticated stranger who could guess an email.\n */\nexport const UserSummarySchema = z.object({\n id: z.string(),\n kind: UserKindSchema.describe(USER_KIND_DESCRIPTION),\n handle: z.string().nullable().describe(\"Callsign. NOT unique — stationId is the stable identifier. Null for listener-only accounts (email-only signup); render stationId instead.\"),\n stationId: z.string().describe(\"Globally unique, human-quotable id (FT-XXXX). The fallback label wherever handle is null.\"),\n avatarColor: z.string().describe(\"Hex colour, #rrggbb.\"),\n avatar: z\n .string()\n .nullable()\n .describe(\n \"Chosen avatar id from GET /avatars, or null for \\\"not set\\\" — a normal state, not an error. \" +\n \"Resolve it against the catalog for the image URL; draw the avatarColor placeholder for null \" +\n \"OR for an id you do not recognise. Capability `user-avatar`.\",\n ),\n});\nconst _userSummaryMatches: Same<z.infer<typeof UserSummarySchema>, UserSummary> = true;\nvoid _userSummaryMatches;\n\n/**\n * The signed-in user's own profile. Includes `email` and `displayName`, which\n * UserSummarySchema must not: this is only ever returned for `request.authUser`, never\n * for a third party. It is the ONLY response in the API that carries a user's name.\n */\nexport const UserProfileSchema = UserSummarySchema.extend({\n email: z.email().describe(\"Only ever returned for the authenticated user themselves.\"),\n displayName: z\n .string()\n .describe(\n \"The account holder's name, used for BILLING RECORDS ONLY — it is what Stripe puts on the invoice, the receipt and the card statement. Never shown to other users, who see handle + stationId. Only ever returned for the authenticated user themselves.\",\n ),\n createdAt: z.iso.datetime(),\n /**\n * Account-level notification defaults — what a contact's own settings fall back to.\n *\n * Served HERE rather than from a route of its own because this object is already read\n * once at sign-in and the client needs these before the first roster event can make a\n * noise. A separate GET would be one more request in the login burst, which is a shape\n * this client has been bitten by three times (0.52.0's effect loop, the pre-markAccepted\n * reconnect spin, and the per-frame onReconnected guard) — each time the per-account\n * rate limiter turned a client bug into what read as an outage.\n *\n * WRITTEN through `PUT /users/me/notification-defaults`, not through `PATCH /users/me`:\n * a whole-object PUT is what makes an edit idempotent and stops two clients at different\n * versions merging two halves of a preference set, exactly as ContactPreferences does.\n */\n notificationDefaults: AccountNotificationDefaultsSchema,\n /**\n * Whether this account may send feedback (capability `feedback`). False once the account\n * is blocked for abusive submissions or by an operator; a client then HIDES its feedback\n * entry point rather than showing a control that can only refuse.\n *\n * On the profile for the reason `notificationDefaults` is: the control sits in the\n * persistent chrome, so its gate has to be loaded at sign-in, and this read already is.\n */\n maySendFeedback: z.boolean(),\n /**\n * For an agent account, the person who created it from their own account (contract §25,\n * \"Sponsored agents\"), whose billing it rides on and who holds its keys. Null for a\n * self-serve agent and for every person.\n */\n sponsorUserId: z.string().nullable(),\n});\nexport type UserProfile = z.infer<typeof UserProfileSchema>;\n\n/**\n * A search hit.\n *\n * Identical to UserSummary, and that is the point. Search used to return the full profile\n * DTO — email and account-creation time included — to any authenticated caller, which made\n * `GET /users/search?q=` an address book of every user on the platform. Nothing consumed\n * those fields; the invite flow takes an email directly rather than looking one up.\n *\n * Search still MATCHES on email so you can find a colleague by theirs, which leaves a\n * narrow \"is this address registered\" oracle. That is a product call, not a leak, and it\n * is a much weaker one than handing back the address.\n */\nexport const UserSearchResultSchema = UserSummarySchema;\n\n/**\n * One avatar in the platform's curated library (capability `user-avatar`).\n *\n * Carries no bytes: the image is a separate, anonymous, immutable URL\n * (`GET /avatars/{id}/image?v={version}&size=sm|lg`). `version` is the cache key — it\n * changes only when an operator replaces the artwork, so a client may treat the versioned\n * URL as permanent and never revalidate it. THAT is how an app avoids downloading the same\n * picture twice; there is nothing else to implement.\n *\n * Retired assets are absent from this list and still SERVE, so somebody who chose one keeps\n * their picture while nobody new can pick it. An id you cannot find here is therefore not\n * necessarily invalid — draw the placeholder and move on.\n */\nexport const AvatarAssetSchema = z.object({\n id: z.string().describe(\"The opaque token stored on a user's `avatar`.\"),\n label: z.string().describe(\"Human name for the picker, e.g. \\\"Microphone\\\".\"),\n category: z.string().describe(\"Grouping for the picker, e.g. \\\"Equipment\\\".\"),\n sortOrder: z.number().int().describe(\"Ascending within a category.\"),\n version: z.number().int().describe(\"Image cache key. Pass as ?v= for an immutable response.\"),\n});\n\nexport const AvatarCatalogSchema = z.object({\n avatars: z.array(AvatarAssetSchema),\n});\n\n/**\n * One notification sound in the platform library.\n *\n * Every entry is ONE CLIP. ⚠️ Until 2026-09-20 a `steps` entry was one choice carrying two —\n * arriving and leaving, fetched as `?part=in` and `?part=out` — and the owner's split of\n * footsteps into four independent roles retired that shape. Rows in the old categories are\n * retired, withheld from this catalog and still served by the audio route, which is why\n * `?part=out` remains on the route and appears nowhere in a live catalog entry.\n */\nexport const SoundAssetSchema = z.object({\n id: z.string().describe(\"What a contact's `ringTone` / `joinSound` / `leaveSound`, or an account default, stores.\"),\n label: z.string().describe(\"What the picker says, e.g. \\\"Marimba\\\".\"),\n category: SoundCategorySchema,\n sortOrder: z.number().int().describe(\"Ascending within a category.\"),\n version: z.number().int().describe(\"Audio cache key. Pass as ?v= for an immutable response.\"),\n isDefault: z\n .boolean()\n .describe(\n \"True for the one sound that plays when a ring has never been chosen. **Served rather than \" +\n \"hard-coded**: a client that assumed a name is wrong the day the set changes, and a client that offers its \" +\n \"own extra \\\"Standard\\\" entry beside the named one puts the same sound on screen twice under two names. \" +\n \"⚠️ Exactly one member of EACH of the ten categories carries it, so an unfiltered `find(s => s.isDefault)` \" +\n \"returns whichever category sorts first - a footstep where a ring belongs. Filter by category. It was true \" +\n \"for exactly one row in the whole catalog until 2026-09-20 and was therefore right by accident.\",\n ),\n});\n\nexport const SoundCatalogSchema = z.object({\n sounds: z.array(SoundAssetSchema),\n});\n\nexport const TuningStateSchema = z.object({\n frequencyId: z.string(),\n active: z.boolean().describe(\"Whether the user currently has this frequency tuned in.\"),\n selectedChannelIds: z.array(z.string()).describe(\"Channels the user is listening to.\"),\n selectedTransmitChannelIds: z.array(z.string()).describe(\"Channels the user's transmit toggle addresses.\"),\n});\n\nexport const MemberTuningStatesSchema = z.object({\n states: z\n .array(\n z.object({\n userId: z.string(),\n selectedChannelIds: z.array(z.string()).describe(\"Channels this member has saved as listening.\"),\n selectedTransmitChannelIds: z.array(z.string()).describe(\"Channels this member has saved as talking, their own personal channel included.\"),\n }),\n )\n .describe(\"One row per member who has a saved selection. A member with none is absent, which reads as nothing selected.\"),\n forceMuted: z\n .array(\n z.object({\n userId: z.string(),\n channelIds: z.array(z.string()).describe(\"The channels of this frequency this member is under the admin mute on.\"),\n }),\n )\n .describe(\n \"Who is under the admin mute, and where (capability `member-force-mute`). Independent of the saved selections: a member with nothing saved can still appear here. Draw Unmute for a member listed here.\",\n ),\n});\n\n/** The answer to the frequency-wide admin mute: which channels now carry the requested state. */\nexport const MemberForceMuteResultSchema = z.object({\n ok: z.literal(true),\n channelIds: z.array(z.string()).describe(\"Every channel of the frequency the member could talk on, all now in the requested state (muted or not).\"),\n});\n\nexport const MemberTuningResultSchema = TuningStateSchema.extend({\n applied: z\n .enum([\"live\", \"stored\"])\n .describe(\n \"live: the member is tuned to this frequency right now and their client was sent the change. stored: they are not (or are appearing offline), so it applies when they next tune.\",\n ),\n});\n\n// ---- Auth -----------------------------------------------------------------------------\n\nexport const TokenPairSchema = z.object({\n accessToken: z.string().describe(\"Short-lived bearer token. Send as `Authorization: Bearer <token>`.\"),\n refreshToken: z\n .string()\n .describe(\n \"Single-use. Rotated on every refresh: the old value stops working as soon as a new pair is issued, so persist the new one before using it.\",\n ),\n});\n\nexport const AuthSessionSchema = TokenPairSchema.extend({\n user: UserSummarySchema,\n /**\n * Present (true) only when this sign-in cancelled a pending account deletion — the\n * grace-window escape hatch (capability `account-deletion`). Clients should tell the\n * user plainly: \"Your scheduled account deletion has been cancelled.\" Absent otherwise.\n */\n deletionCancelled: z.boolean().optional(),\n});\n\n/**\n * 202 from DELETE /users/me: the deletion is scheduled, every session is being revoked,\n * and the account will be erased after `purgeAfter` unless the user signs in again before\n * then (any successful sign-in cancels it). See docs/user-data-deletion.md.\n */\nexport const AccountDeletionScheduleSchema = z.object({\n requestedAt: z.string().describe(\"When the deletion was accepted (ISO 8601).\"),\n purgeAfter: z.string().describe(\"Erasure happens at the first sweep after this instant (ISO 8601).\"),\n graceDays: z.number().int().describe(\"The grace window in days; signing in before it ends cancels the deletion.\"),\n});\nexport type AccountDeletionSchedule = z.infer<typeof AccountDeletionScheduleSchema>;\n\n// ---- OAuth 2.1 (Phase 2) --------------------------------------------------------------\n\n/**\n * Token response from POST /oauth/token, RFC 6749 §5.1 — snake_case on purpose, unlike the\n * rest of the API, so off-the-shelf OAuth client libraries work against it unmodified.\n */\nexport const OAuthTokenResponseSchema = z.object({\n access_token: z.string(),\n token_type: z.literal(\"Bearer\"),\n expires_in: z.number().int().describe(\"Access-token lifetime in seconds.\"),\n refresh_token: z\n .string()\n .optional()\n .describe(\"Absent on client_credentials grants. Single-use and rotating, same semantics as /auth/refresh.\"),\n scope: z.string().describe(\"Space-delimited scopes actually granted (may be narrower than requested).\"),\n installation_id: z\n .string()\n .optional()\n .describe(\n \"Server-issued identity for this app install, minted on the authorization_code grant. Persist it: it names this session in GET /auth/sessions and keys media-node device slots.\",\n ),\n});\n\n/**\n * Error response from POST /oauth/token, RFC 6749 §5.2 — NOT the platform ApiError\n * envelope, again so standard OAuth libraries can parse failures.\n */\nexport const OAuthTokenErrorSchema = z.object({\n error: z.enum([\"invalid_request\", \"invalid_client\", \"invalid_grant\", \"unauthorized_client\", \"unsupported_grant_type\", \"invalid_scope\"]),\n error_description: z.string().optional(),\n});\n\n/** RFC 8414 authorization-server metadata, served at /.well-known/oauth-authorization-server. */\nexport const AuthServerMetadataSchema = z.object({\n issuer: z.string(),\n authorization_endpoint: z.string(),\n token_endpoint: z.string(),\n jwks_uri: z.string(),\n response_types_supported: z.array(z.string()),\n grant_types_supported: z.array(z.string()),\n code_challenge_methods_supported: z.array(z.string()).describe('Always [\"S256\"] - plain is not supported.'),\n scopes_supported: z.array(z.string()),\n token_endpoint_auth_methods_supported: z.array(z.string()),\n});\n\nexport const JwkSchema = z\n .object({\n kty: z.string(),\n crv: z.string().optional(),\n x: z.string().optional(),\n kid: z.string(),\n alg: z.string(),\n use: z.string(),\n })\n .describe(\"Public JSON Web Key. Ed25519 (OKP/EdDSA) today; treat the set as the contract, not the algorithm.\");\n\nexport const JwksSchema = z.object({ keys: z.array(JwkSchema) });\n\n/** One signed-in app install, as listed by GET /auth/sessions. */\nexport const UserSessionSchema = z.object({\n id: z.string().describe(\"Refresh-token family id. Pass to DELETE /auth/sessions/{id} to revoke.\"),\n clientId: z.string().describe('OAuth client, e.g. \"frequency-web\", \"tuner-windows\".'),\n clientName: z.string().describe(\"Human-readable app name for display.\"),\n scope: z.string().describe(\"Space-delimited scopes this session's tokens carry.\"),\n createdAt: z.string().describe(\"When this install first signed in.\"),\n lastRefreshedAt: z.string().nullable().describe(\"Last successful token rotation; null if never rotated.\"),\n current: z.boolean().describe(\"True for the session that made this request.\"),\n});\n\n/**\n * One session standing in the way of a new sign-in, as carried in a 409 SESSION_CONFLICT's\n * `details.sessions`. Everything here exists to answer one question for a broadcaster\n * about to displace themselves: *is that other me, and is it live?*\n *\n * We report only what we honestly know. There is no geolocation — `ip` is the raw address\n * the sign-in came from, which a person can usually recognise as home vs. studio, and\n * inventing a city from it would be a guess dressed as a fact.\n */\nexport const ConflictingSessionSchema = z.object({\n id: z.string().describe(\"Refresh-token family id of the session that would be closed.\"),\n clientName: z.string().describe('App this session belongs to, e.g. \"Frequency Talk Service Manager\".'),\n platform: z.string().nullable().describe('Coarse OS read off the user agent, e.g. \"macOS\". Null when unknown.'),\n ip: z.string().nullable().describe(\"Address the session signed in from. Null for sessions predating this field.\"),\n signedInAt: z.string().describe(\"When this session signed in.\"),\n lastActiveAt: z.string().nullable().describe(\"Last token rotation; null if it has never refreshed.\"),\n transmitting: z\n .object({\n broadcast: z.boolean().describe(\"True when the live producer is program audio on a broadcast station, not voice.\"),\n stationCallsign: z.string().nullable(),\n frequencyLabel: z.string().nullable(),\n })\n .nullable()\n .describe(\"Non-null when this session is ON AIR right now — signing it out interrupts the transmission.\"),\n});\nexport type ConflictingSession = z.infer<typeof ConflictingSessionSchema>;\n\n/**\n * What the hosted sign-in page's `/oauth/authorize/*` routes may answer — RFC 6749's token\n * vocabulary PLUS the three refusals that belong to a sign-in a human is standing in front\n * of, and which `OAuthTokenErrorSchema` cannot express.\n *\n * ⚠️ **It could not express them, and that was not a documentation gap — it was a 500.**\n * `/oauth/authorize/complete` declared `OAuthTokenErrorSchema` on its 409 and 422 while\n * sending `signup_required`, `callsign_required` and `session_conflict`, none of which are\n * in that closed enum, so a serialization failure turned every one of them into\n * `500 INTERNAL_ERROR`. **A first-ever sign-in through the hosted page — the only login\n * screen a native app has — could therefore never reach its callsign prompt**, and the\n * page's `error === 'signup_required'` branch was unreachable code from the day it was\n * written. The `sessions` array had a second, quieter version of the same problem: a\n * response schema STRIPS unknown keys, so even a 409 that serialized would have arrived\n * with nothing in it to render.\n *\n * Found 2026-09-19 by a test asserting the response of a new sibling route, which is the\n * lesson worth keeping: the existing suite only ever provoked `invalid_request` here, and\n * `invalid_request` is in the enum, so every test passed over a route that was broken for\n * every real first-time user. Assert the refusals, not just the rejections.\n */\nexport const OAuthAuthorizeErrorSchema = z.object({\n error: z.enum([\n \"invalid_request\",\n \"invalid_client\",\n \"invalid_grant\",\n \"unauthorized_client\",\n \"unsupported_grant_type\",\n \"invalid_scope\",\n \"signup_required\",\n \"callsign_required\",\n \"session_conflict\",\n ]),\n error_description: z.string().optional(),\n sessions: z\n .array(ConflictingSessionSchema)\n .optional()\n .describe(\"Present on `session_conflict`: the sessions that would be closed. Resubmit with `signOutOtherSessions: true` to proceed.\"),\n});\n\nexport const DevMailboxEntrySchema = z\n .object({\n email: z.string(),\n code: z.string(),\n sentAt: z.string(),\n })\n .describe(\"Development only: the login code that would have been emailed. Never enabled in production.\");\n\nexport const WebAuthnVerifiedSchema = z.object({ verified: z.boolean() });\n\n/**\n * WebAuthn ceremony options are produced by @simplewebauthn/server and passed to the\n * browser API verbatim. Described as an opaque object on purpose: restating the WebAuthn\n * spec here would add a second definition to keep in sync with the library, and — because\n * an undescribed key is stripped — any field this got wrong would be quietly removed from\n * the response and break the ceremony in the client.\n */\nexport const OpaquePassthroughSchema = z.record(z.string(), z.unknown());\n\n/**\n * Widen a library-defined object to the passthrough schema's type.\n *\n * `PublicKeyCredentialCreationOptionsJSON` and friends are declared as interfaces, and a\n * TypeScript interface has no index signature, so it is not assignable to\n * `Record<string, unknown>` even though the value is a plain JSON object at runtime. This\n * is purely a typing accommodation — kept as one named helper so the cast is explained\n * once instead of repeated inline at every WebAuthn route.\n */\nexport function asJsonObject(value: object): Record<string, unknown> {\n return value as Record<string, unknown>;\n}\n\nexport const WebAuthnLoginOptionsSchema = z.object({\n userId: z.string(),\n options: OpaquePassthroughSchema,\n});\n\n/**\n * A DISCOVERABLE passkey ceremony, keyed to itself rather than to an account.\n *\n * ⚠️ **It carries NO user-identifying field, and that absence is the contract.** The\n * email-keyed sibling answers a `userId` — a real one, or a decoy derived from the address,\n * so the two are indistinguishable. This ceremony never saw an address, so there is nothing\n * to identify and nothing to conceal: adding a `userId` here later would invent an oracle on\n * a route that structurally has none.\n *\n * `options.allowCredentials` is `[]`, which is what makes it discoverable: the authenticator\n * offers whatever passkeys it holds for this relying party. Spend `ceremonyId` on\n * `POST /oauth/token` with the webauthn grant, in place of `user_id`.\n */\nexport const WebAuthnDiscoverableOptionsSchema = z.object({\n ceremonyId: z.string(),\n options: OpaquePassthroughSchema,\n});\n\n/**\n * A user-facing view of one enrolled passkey. Deliberately excludes `credentialId`,\n * `publicKey` and `counter`: none are needed to recognise \"my laptop from March\", and the\n * serializer stripping them here is what keeps key material off the wire.\n */\nexport const WebAuthnCredentialSummarySchema = z.object({\n id: z.string(),\n nickname: z.string().nullable(),\n deviceType: z.string().describe('`\"singleDevice\"` or `\"multiDevice\"`, as reported at enrollment.'),\n backedUp: z.boolean().describe(\"Whether the authenticator reported the credential as synced/backed up.\"),\n createdAt: z.string(),\n lastUsedAt: z.string().nullable().describe(\"Last successful passkey login with this credential; null if never used.\"),\n});\nexport type WebAuthnCredentialSummary = z.infer<typeof WebAuthnCredentialSummarySchema>;\n\nexport const WebAuthnCredentialListSchema = z.object({\n credentials: z.array(WebAuthnCredentialSummarySchema),\n});\n\n// ---- Platform -------------------------------------------------------------------------\n\nexport const PlatformConfigSchema = z.object({\n supportedCountries: z\n .array(z.string().length(2))\n .describe(\"ISO 3166-1 alpha-2 codes this deployment operates in. Company contacts outside this list are rejected.\"),\n bands: BandPlansSchema.describe(\"The authoritative dial description, keyed by frequency mode.\"),\n});\n\n// ---- Stations and frequencies ---------------------------------------------------------\n\nexport const NowPlayingSchema = z.object({\n text: z.string().nullable().describe(\"Free-text programme line, e.g. \\\"The Morning Show\\\".\"),\n trackTitle: z.string().nullable(),\n trackArtist: z.string().nullable(),\n updatedAt: z.string().nullable().describe(\"ISO timestamp of the last update, so a client can age out stale metadata.\"),\n since: z\n .string()\n .nullable()\n .describe(\n \"When the thing now playing began (ISO 8601): the airing a Cheer or Hush is counted against (capability `cheer-hush`). It moves only when the song or show itself changes. Null when there is nothing to cheer or hush right now.\",\n ),\n});\nconst _nowPlayingMatches: Same<z.infer<typeof NowPlayingSchema>, NowPlaying> = true;\nvoid _nowPlayingMatches;\n\nexport const StationFormatSchema = z.enum([\"talk\", \"music\", \"mixed\"]);\n\n/**\n * The station identity carried inline on a frequency.\n *\n * Content and now-playing ride the embed rather than being fetched separately so a\n * directory row renders from one response — otherwise a radio client makes an extra fetch\n * per station on the dial just to show what is playing.\n *\n * Since 2026-08-02 a broadcast frequency IS the station and carries these fields itself, so\n * `id` is the frequency's id (it was the owning organization's) and the logo moved to\n * GET /frequencies/{id}/logo. Same fields, same values — only the source changed.\n */\nexport const FrequencyStationSchema = z.object({\n id: z.string().describe(\"The broadcast frequency's id. Was the organization's id before 2026-08-02.\"),\n name: z.string().describe(\"Station name — the frequency's name. Globally unique across stations.\"),\n stationCallsign: z.string().describe(\"On-air callsign. Globally unique.\"),\n brandColor: z.string().nullable().describe(\"Hex, #rrggbb. May be illegible on a dark UI — clients should adjust luminance rather than use it raw.\"),\n tagline: z.string().nullable(),\n logoVersion: z.number().int().describe(\"Increments on every logo change; use it to bust caches of GET /frequencies/{id}/logo.\"),\n hasLogo: z.boolean().describe(\"Whether GET /frequencies/{id}/logo will return an image.\"),\n format: StationFormatSchema.nullable(),\n genre: z.string().nullable(),\n nowPlaying: NowPlayingSchema.nullable().describe(\"Null when the station has published nothing — branch on presence, not on four nulls.\"),\n});\nconst _stationMatches: Same<z.infer<typeof FrequencyStationSchema>, FrequencyStation> = true;\nvoid _stationMatches;\n\nexport const StationLinkSchema = z.object({ label: z.string(), url: z.string() });\n\n/**\n * A station as its own staff see it — GET/PATCH /frequencies/{id}/station. The embed above\n * plus the settings-only fields, so a dial row never carries what only a manager needs.\n */\nexport const StationDetailSchema = FrequencyStationSchema.extend({\n websiteUrl: z.string().nullable(),\n links: z.array(StationLinkSchema).nullable(),\n organizationId: z.string().describe(\"The company that owns this station.\"),\n myRole: z.enum([\"owner\", \"manager\", \"dj\", \"screener\"]).describe(\"The caller's role at that company. Editing needs manager or above.\"),\n});\nconst _stationDetailMatches: Same<z.infer<typeof StationDetailSchema>, StationDetail> = true;\nvoid _stationDetailMatches;\n\nexport const SuspensionClassSchema = z\n .enum([\"non_payment\", \"voluntary\", \"conduct\", \"legal\"])\n .describe(\n \"Why the frequency is off the air. Ours, not Stripe's, so unlike Subscription.status this is a closed set. The class is what decides who may lift the suspension — read `reinstatable` rather than encoding that policy client-side. `voluntary` means the customer cancelled; if they cancelled during the free trial the station is also deleted when that trial would have ended, which is the one class that is not indefinite.\",\n );\n\nexport const FrequencySuspensionSchema = z.object({\n class: SuspensionClassSchema,\n since: z.string().describe(\"When it went off the air.\"),\n reinstatable: z\n .boolean()\n .describe(\n \"Whether the OWNER can lift this themselves (POST /frequencies/{id}/reinstate). Computed server-side; do NOT re-derive it from `class`. True for non_payment and voluntary. The route additionally requires a live subscription, so true here is necessary but not sufficient.\",\n ),\n deletionScheduledAt: z\n .string()\n .nullable()\n .describe(\n \"When the frequency will be DELETED rather than merely left off the air, or null. Non-null only for a `voluntary` suspension raised by cancelling during the free trial, where the station is reclaimed at the end of the trial the customer already had; every other suspension is indefinite. Reinstating at any point before this clears it. Surface the date — a deadline the customer cannot see is one they will miss.\",\n ),\n});\nconst _frequencySuspensionMatches: Same<z.infer<typeof FrequencySuspensionSchema>, FrequencySuspension> = true;\nvoid _frequencySuspensionMatches;\n\n/**\n * The frequency modes that cross the wire — the two DIAL modes, and deliberately not\n * `direct`.\n *\n * `FrequencyMode` (domain.ts) has a third member for 1:1 calls. It is absent here on\n * purpose: a call is an off-dial frequency that appears on no dial surface, so no client\n * ever receives one in a Frequency DTO, and this schema is the last line that would let\n * one through. `toFrequencyDto` throws on `mode === \"direct\"` for the same reason — a\n * leak becomes a loud 500 rather than a station on somebody's dial. Widening this enum\n * to match the domain union would silently remove both guards at once.\n */\nexport const FrequencyModeSchema = z.enum([\"push_to_talk\", \"broadcast\"]);\n\nexport const FrequencySchema = z.object({\n id: z.string(),\n khz: z.number().int().describe(\"The canonical number. Integer kHz, globally unique across both modes.\"),\n label: z\n .string()\n .describe(\n 'Mode-aware display label — broadcast reads as a dial position (\"97.9\"), push-to-talk keeps aviation notation (\"118.000\"). Render verbatim; do not re-derive it from khz.',\n ),\n name: z.string(),\n description: z.string().nullable(),\n ownerId: z.string(),\n publiclyListable: z\n .boolean()\n .describe(\n \"Whether non-members can discover this frequency. EFFECTIVE, not a raw setting: for broadcast it is derived (listed unless it has an access code — being on the dial IS the listing); for push-to-talk it is the owner's stored flag.\",\n ),\n autoApprovePublicJoin: z.boolean(),\n mode: FrequencyModeSchema,\n hasAccessCode: z.boolean().describe(\"Whether a first-time joiner must supply a code. The code itself is never exposed here.\"),\n organizationId: z.string().nullable().describe(\"Always set for broadcast (org-only); null for personal push-to-talk.\"),\n station: FrequencyStationSchema.nullable().describe(\"Embedded station identity when org-owned.\"),\n suspension: FrequencySuspensionSchema.nullable().describe(\n \"Set when the frequency is off the air by platform or billing action; null (the normal case) when it is live. Nothing is deleted by a suspension — keep rendering the station's identity, but refuse to tune it. Capability: frequency-suspension.\",\n ),\n createdAt: z.string(),\n});\n// Frequency declares `station?: FrequencyStation | null` (optional) because a few internal\n// call sites build DTOs without the org include; every ROUTE response includes it, so the\n// schema requires the key and only its value is nullable. That difference is deliberate,\n// which is why this is a one-way check rather than the usual mutual one.\ntype _FrequencyResponseIsAFrequency = z.infer<typeof FrequencySchema> extends Frequency ? true : never;\nconst _frequencyMatches: _FrequencyResponseIsAFrequency = true;\nvoid _frequencyMatches;\n\nexport const FrequencyRoleSchema = z.enum([\"owner\", \"admin\", \"user\"]);\n\nexport const MediaNodeStatusSchema = z\n .enum([\"starting\", \"running\", \"stopping\", \"stopped\", \"error\"])\n .describe('\"stopped\" is an ordinary state, not a failure — provisioning is transmit-gated, so a frequency nobody is transmitting on has no container.');\nconst _mediaNodeStatusMatches: Same<z.infer<typeof MediaNodeStatusSchema>, MediaNodeStatus> = true;\nvoid _mediaNodeStatusMatches;\n\n/** Live tuned-presence counts for a frequency (capability: frequency-roster). */\nexport const TunedCountsSchema = z.object({\n connected: z.number().int().describe(\"Devices currently declaring themselves tuned to this frequency. Soft state with a ~90s horizon.\"),\n talking: z.number().int().describe(\"Of those, devices with a non-empty talking set — could talk right now, not necessarily making sound.\"),\n});\n\nconst MayBroadcastSchema = z\n .boolean()\n .describe(\n \"Whether the caller may send the station's PROGRAM (the broadcast capture profile) on this frequency: its owner or an admin, or staff of the company that owns it with the on-air capability. \" +\n \"Everybody else given talk on Public transmits an ordinary VOICE there, which the listen stream mixes with the program; a broadcast-profile produce from them is refused. \" +\n \"Only meaningful on a broadcast frequency, since only a station has a program; it is decided without reading the mode so that switching a frequency to broadcast does not strand its owner.\",\n );\n\nconst MayManageChannelsSchema = z\n .boolean()\n .describe(\n \"Whether the caller may use the channel controls here: create, rename and delete group channels, and manage who is on them, which includes turning a member's talk on or off (on Public, that puts them on the air). \" +\n \"True for the frequency's owner and admins, and, on a frequency a company owns, for its staff at screener or above (company capability `station.manageChannels`, 0.79.0). \" +\n \"It does NOT widen what the caller can see: a managed channel stays invisible to staff who are not on its roster. Group links, a channel's own talk permission and force-mute stay admin-only.\",\n );\n\n/** A frequency the caller is a member of; `myRole` is their role on it. */\nexport const MyFrequencySchema = FrequencySchema.extend({\n myRole: FrequencyRoleSchema,\n mayBroadcast: MayBroadcastSchema,\n mayManageChannels: MayManageChannelsSchema,\n mediaNodeStatus: MediaNodeStatusSchema.describe(\n \"Current media-node status for this frequency. One list call seeds every band's status at directory build and after a realtime reconnect — \" +\n \"a lost `mediaNode.status` edge is unrecoverable by waiting, so re-seed from here rather than polling per frequency.\",\n ),\n tunedCounts: TunedCountsSchema.optional().describe(\n \"Live tuned-presence counts (capability: frequency-roster). Absent when unknown (Redis unavailable). Like mediaNodeStatus, this list is the bulk seed: \" +\n \"`frequency.tunedCounts` edges that fire while a client is disconnected are lost, not replayed — re-seed from here after a reconnect.\",\n ),\n});\n\n/** One device's row in a frequency's tuned roster (capability: frequency-roster). */\nexport const TunedRosterMemberSchema = z.object({\n userId: z.string(),\n kind: UserKindSchema.describe(USER_KIND_DESCRIPTION),\n deviceId: z.string().describe(\"Server-issued installation id. Two devices of one account are two rows; a client finds its own row by its access token's installation_id claim.\"),\n callsign: z.string().describe(\"The person's own callsign, always — station-callsign substitution is a per-producer media-socket fact and never appears here.\"),\n stationId: z\n .string()\n .describe(\n \"The person's Station ID (FT-XXXX), the stable identifier a callsign is not. Send THIS to `POST /contacts/requests` \" +\n \"to add somebody from a roster row: a callsign can be ambiguous, a Station ID never is. Same value UserSummary carries.\",\n ),\n avatar: z.string().nullable().describe(\"Chosen avatar id, exactly as UserSummary carries it (null = not set). Capability `user-avatar`.\"),\n avatarColor: z.string().describe(\"Hex colour, #rrggbb: the placeholder behind a null or unrecognised avatar.\"),\n acceptsMessages: z\n .boolean()\n .describe(\n \"Whether this person accepts direct messages from non-contacts (their `acceptMessagesFromNonContacts`, capability \" +\n \"`chat-non-contacts`). Offer a Message action on this row only when it is true or they are already a contact. \" +\n \"Discloses a preference, never presence.\",\n ),\n listeningChannelIds: z.array(z.string()),\n talkingChannelIds: z.array(z.string()).describe('Intent, not activity — channels this device could talk on right now (routing contract\\'s roster rule), as declared by the client.'),\n});\n\n/** Snapshot of everyone tuned to a frequency. Works with no media node — the roster lives on the control plane. */\nexport const FrequencyRosterSchema = z.object({\n frequencyId: z.string(),\n connectedCount: z.number().int(),\n talkingCount: z.number().int().describe(\"Members with a non-empty talkingChannelIds set.\"),\n members: z\n .array(TunedRosterMemberSchema)\n .describe(\"Everyone tuned, including members subscribed to zero channels and including the caller's own row(s). Maintain with frequency.rosterMember / frequency.rosterLeave deltas; re-fetch after a realtime reconnect.\"),\n});\n\n/** A publicly-listable frequency, decorated with whether the caller has already joined. */\nexport const PublicFrequencySchema = FrequencySchema.extend({ isMember: z.boolean() });\n\nexport const FrequencyDetailSchema = FrequencySchema.extend({\n myRole: FrequencyRoleSchema.nullable().describe(\"Null when the caller is not a member (only possible for publicly-listable frequencies).\"),\n mayBroadcast: MayBroadcastSchema,\n mayManageChannels: MayManageChannelsSchema,\n mediaNodeStatus: MediaNodeStatusSchema,\n});\n\n/**\n * Live dial state for one broadcast station.\n *\n * `liveState` is the four-stage signal (capability \"station-live-stages\") — see the note\n * on the `StationLiveStage` domain type. Filter a dial on `liveState !== \"off_air\"`;\n * render live/dead-air indicators from the stage directly.\n */\nexport const StationLiveStageSchema = z\n .enum([\"live\", \"dead_air\", \"interrupted\", \"off_air\"])\n .describe(\n '\"live\" = armed and audible; \"dead_air\" = armed but silent (hard mute or genuine silence) — holds indefinitely, keep the station on the dial; ' +\n '\"interrupted\" = involuntary drop while armed, listed for a short grace with the stream down; \"off_air\" = not armed.',\n );\n\nexport const StationLiveStateSchema = z.object({\n frequencyId: z.string(),\n khz: z.number().int(),\n liveState: StationLiveStageSchema,\n listenerCount: z\n .number()\n .int()\n .nonnegative()\n .describe(\"WebRTC room listeners only — HLS listeners never join the room and are not counted.\"),\n});\nconst _stationLiveStateMatches: Same<z.infer<typeof StationLiveStateSchema>, StationLiveState> = true;\nvoid _stationLiveStateMatches;\n\nexport const PublicStationStatsSchema = z.object({\n stations: z\n .array(StationLiveStateSchema)\n .describe(\n \"Publicly-listed broadcast frequencies, ordered by dial number — the same listing rule /public/stations applies, \" +\n \"without its extra not-off_air filter. Code-gated stations are NOT here at any stage (0.24.0); a member reads \" +\n \"their own from /stations/stats/mine.\",\n ),\n});\n\n/**\n * The authed companion to PublicStationStatsSchema: live state for the caller's OWN\n * broadcast frequencies, which is the only way to watch a code-gated station's stage now\n * that the anonymous route withholds them (0.24.0).\n *\n * Same row shape on purpose — a client folds both responses into one dial through the same\n * code path, and the only difference is which stations each may speak about.\n */\nexport const MyStationStatsSchema = z.object({\n stations: z\n .array(StationLiveStateSchema)\n .describe(\"Live state for every broadcast frequency the caller is a member of, listed or code-gated, ordered by dial number.\"),\n});\n\n/** A directory row: the frequency, its branding, and its live dial state. */\nexport const PublicStationSchema = FrequencySchema.extend({\n liveState: StationLiveStateSchema.shape.liveState,\n listenerCount: StationLiveStateSchema.shape.listenerCount,\n});\n\nexport const PublicStationDirectorySchema = z.object({\n stations: z\n .array(PublicStationSchema)\n .describe(\n \"Publicly-listable broadcast frequencies not off_air (live, dead_air, and interrupted stations all hold the dial), ordered by dial number. Pass ?includeOffline=true for the rest.\",\n ),\n});\n\n// ---- Stream quality: the chain from studio to listener -------------------------------\n\nexport const StreamEncodingSchema = z.object({\n codec: z.string().describe('Lowercase encoder codec name, e.g. \"opus\".'),\n bitrateKbps: z.number().nullable().describe(\"Target/ceiling bitrate the sender encoded at; null when it declared none.\"),\n sampleRate: z.number(),\n channels: z.number().describe(\"1 = mono (voice), 2 = stereo (program audio).\"),\n fec: z.boolean().describe(\"In-band forward error correction.\"),\n dtx: z.boolean().describe(\"Discontinuous transmission. Off for program audio — it punches holes in music.\"),\n frameMs: z.number().nullable().describe(\"Encoder frame size where the sender states it; null on the WebRTC path, which does not negotiate it.\"),\n});\n\nexport const StreamContributionSchema = z.object({\n transport: z.enum([\"webrtc\", \"native\"]).describe(\"Which datapath the program audio arrived over.\"),\n encoding: StreamEncodingSchema.nullable().describe(\n \"Null when a native sender declared nothing — that transport is codec-opaque by design, so the server says \" +\n '\"not stated\" rather than guessing. WebRTC senders always negotiate, so this is always present for them.',\n ),\n});\n\nexport const StreamDeliverySchema = z.object({\n codec: z.string(),\n bitrateKbps: z.number().describe(\n \"The ENCODER setting. A player reading BANDWIDTH off the master playlist sees ~10-15% more, because that is \" +\n \"measured on the muxed segments and includes MPEG-TS overhead. Different quantities, not a disagreement.\",\n ),\n sampleRate: z.number(),\n channels: z.number(),\n segmentSeconds: z.number(),\n windowSeconds: z.number().describe(\"Audio held in the rolling playlist — segment length x window size.\"),\n});\n\nexport const StreamInfoSchema = z.object({\n live: z\n .boolean()\n .describe(\n 'Program audio is flowing right now — the same question as the directory\\'s `liveState === \"live\"`. Independent of `contribution`: ' +\n \"a station can be live while the platform cannot describe its encoding. Never infer one from the other.\",\n ),\n contribution: StreamContributionSchema.nullable().describe(\n \"What reached the platform. Null when nothing is on the air, or when the media node is too old to report it.\",\n ),\n delivery: StreamDeliverySchema.describe(\"What the HLS listen tier serves. Deployment config — the same for every station here.\"),\n bottleneck: z\n .enum([\"contribution\", \"delivery\"])\n .nullable()\n .describe(\n \"Which leg constrains the result, or null when nothing is on the air. Deliberately not a percentage: \" +\n \"lossy-to-lossy chains do not compose linearly, so any single fidelity score would be fiction.\",\n ),\n streamHealth: z\n .enum([\"live\", \"stalled\"])\n .optional()\n .describe(\n \"Capability `air-monitor`. The same fact the listen-ticket mint carries, readable here without minting a ticket: \" +\n \"`live` = on air and servable; `stalled` = transmitting but the encoder cannot serve, so every listener is getting \" +\n \"OFF_AIR while the broadcaster's own meters are green. ABSENT means no signal (off the air, an old node): never read \" +\n \"absence as healthy. This one field changes while a station is on the air, so a TRANSMITTING client may poll the \" +\n \"route for it, no faster than once every 15 seconds.\",\n ),\n});\nconst _streamInfoMatches: Same<z.infer<typeof StreamInfoSchema>, StreamInfo> = true;\nvoid _streamInfoMatches;\n\n/**\n * Response from POST /listen/:frequencyId/ticket — the HLS connect ticket that\n * authenticates playback in place of the access token (contract §6).\n */\nexport const ListenTicketResponseSchema = z.object({\n ticket: z\n .string()\n .describe(\n \"Opaque, bound to this frequency/account/install/session. Active playback keeps it alive; a stopped player's ticket \" +\n \"expires on its own. Treat it as a credential — never log it.\",\n ),\n playlistUrl: z\n .string()\n // NORMATIVE, not prose (0.24.1, Tuner origin-pinning Q2). A leading \"/\" and no \"//\" is\n // the machine-checkable form of \"same origin\": a native client pins the playlist host\n // and refuses any other, so \"this is a path\" is a security property its guard rests on,\n // and a description cannot be validated. \"//host/x\" is a protocol-relative URL — a path\n // by eye, a different authority in a URL parser — so it is excluded explicitly.\n // If a listen CDN ever makes this absolute, this constraint is what forces that to be a\n // deliberate, coordinated contract change rather than a silent one.\n .regex(/^\\/(?!\\/)/, \"playlistUrl must be a same-origin path\")\n .describe(\n \"A PATH on this control plane's origin, ticket included — guaranteed to start with a single `/`. \" +\n \"Hand it to the player verbatim; do not append anything, and resolve it against the origin you already trust.\",\n ),\n expiresInSeconds: z\n .number()\n .int()\n .describe(\n \"Idle lifetime. Every playlist poll slides the expiry, so this only runs out once playback stops. On 401 TICKET_EXPIRED, \" +\n \"mint a new ticket rather than refreshing the access token first — only mint failures concern the token.\",\n ),\n streamHealth: z\n .enum([\"live\", \"stalled\"])\n .optional()\n .describe(\n \"Capability `stream-health`. Whether the station's egress pipeline can serve what its producer is sending: `live` = on \" +\n \"air and servable; `stalled` = transmitting but the encoder cannot serve, so playback will answer OFF_AIR despite the \" +\n \"station being on the air — show a technical-difficulties state rather than plain static. ABSENT means no signal: \" +\n \"station off air, or a deployment/node predating the capability — behave exactly as before this field existed.\",\n ),\n liveState: StationLiveStageSchema.optional().describe(\n 'Capability `hls-mint-offair`. The station stage the mint preflight read — never \"off_air\" (that answers 503 OFF_AIR ' +\n \"with no ticket minted). ABSENT on push-to-talk frequencies and deployments predating the capability. dead_air and \" +\n \"interrupted still mint: the stream is expected back, so hold the ticket and poll.\",\n ),\n});\n\nexport const IceServerSchema = z.object({\n urls: z.string(),\n username: z.string().optional(),\n credential: z.string().optional(),\n});\n\n/**\n * The frequency's SHARE KEY (screen share, capability `screen-share`, 0.81.0). A screen share's\n * audience is the whole frequency, and no channel key reaches all of it (managed channels are\n * private), so every member the tune admits gets this one more key. It lives in the SAME keyset\n * as the channel keys (same keysetId, epoch and bootId) and rotates with them, so the existing\n * nativeKeysRotated + GET /native-keys path covers it. The media node never holds it.\n */\nconst ShareKeySchema = z\n .object({\n id: z.number().int().positive().describe(\"The share key's uint32 wire id: the packet header's channelId on every share packet. Take it from here rather than hard-coding it.\"),\n key: z.string().describe(\"32-byte base64 AES-256-GCM share key, CURRENT epoch only.\"),\n })\n .describe(\"The frequency-wide screen-share key, held by every member. Seal a share ONCE under it: no carrying set, no home copy.\");\n\n/**\n * How to reach the frequency's SHARE container (capability `share-container`, 2026-09-28): the\n * container screen shares run in once a frequency has one, separate from the voice container,\n * with its own signaling path, its own UDP endpoint, its own join token and its own share key.\n * Present on a tune result whenever the frequency HAS a share container; `connect` is present\n * only once that container is running with a cleared generation (its share key cannot be handed\n * out before then). Until `connect` appears, wait for a `shareNode.status` of `running` and\n * re-tune.\n */\nexport const TuneShareSchema = z\n .object({\n status: MediaNodeStatusSchema,\n connect: z\n .object({\n signalPath: z.string().describe(\"A PATH on this control plane's origin, as mediaNodeAddress is: the share container's proxied signaling socket. Send `auth` with `token` below and `nativeTransport: true`.\"),\n token: z.string().describe(\"A media-join token for the SHARE container. It opens only that container: the voice container refuses it, and the share container refuses the voice token.\"),\n udpEndpoint: z.string().describe(\"host:port the native datapath dials for shares, on the share container's host. Not the voice udpEndpoint.\"),\n bootId: z.string().describe(\"The share container's generation. Must match that container's authOk.native.bootId, or re-tune.\"),\n keysetId: z.string().describe(\"Identity of the share key below; compare it, not the epoch, against a `nativeKeysRotated` notice from the share container.\"),\n epoch: z.number().int().min(0).max(255).describe(\"The share key's epoch (uint8, wraps mod 256).\"),\n shareKey: ShareKeySchema,\n })\n .optional(),\n })\n .describe(\"The frequency's share container. Absent when it has none, in which case shares (if any) run in the voice container under nativeTransport.channelKeys.shareKey.\");\n\n/** The share key again, without re-tuning: the answer to `nativeKeysRotated` from a share container. */\nexport const ShareKeyResultSchema = z.object({\n keysetId: z.string().describe(\"Identity of this key material; matches the keysetId in the notice that prompted the fetch.\"),\n bootId: z.string().describe(\"The share container's generation these keys are bound to. A mismatch against your share session's generation means re-tune, not install.\"),\n epoch: z.number().int().min(0).max(255).describe(\"Current share key epoch (uint8, wraps mod 256).\"),\n shareKey: ShareKeySchema,\n});\n\nexport const TuneResultSchema = z.object({\n token: z.string().describe(\"Short-lived media-join token. Present it to the signaling endpoint below.\"),\n mediaNodeAddress: z\n .string()\n .describe(\n \"A PATH, not a URL. The media node is not directly reachable; join it against this control plane's own origin, which proxies the signaling traffic.\",\n ),\n mediaNodeStatus: MediaNodeStatusSchema,\n iceServers: z.array(IceServerSchema),\n expiresAt: z.string().describe(\"ISO timestamp after which `token` is refused.\"),\n // M1 native transport (docs/m1-threat-model.md §3.1a/§4.1, mirrored from ../switchboard).\n // Present only when NATIVE_TRANSPORT_ENABLED and this frequency's node has a CLEARED\n // generation (media_nodes.bootId — stored strictly after any generation rekey completed,\n // see the §3.2 handshake). Absence is ordinary: flag off, node stopped, or clearance\n // still in flight — re-tune to refetch, the one resync primitive (§4.4). Deliberately\n // NOT here: connectionId and the senderMac key, which are node-issued in the control-WS\n // auth ack — a TuneResult-carried connectionId is exactly the deploy-reset allocator\n // hazard the crypto review killed.\n nativeTransport: z\n .object({\n udpEndpoint: z.string().describe(\"host:port the native datapath dials directly (rtcMinPort+1 — not proxied, unlike signaling).\"),\n bootId: z.string().describe(\"The node generation these keys are bound to; must match authOk.native.bootId or re-tune.\"),\n channelKeys: z.object({\n keysetId: z\n .string()\n .describe(\n \"Identity of THIS key material, new on every rotation and every mint. Compare this — not the epoch — to decide whether a `nativeKeysRotated` notice concerns keys you already hold: a control-plane restart re-mints at epoch 0 with different bytes, so the epoch number can collide while the material differs.\",\n ),\n epoch: z.number().int().min(0).max(255).describe(\"Current key epoch (uint8, wraps mod 256). Receivers keep their own previous epoch for the tolerance window.\"),\n // Channel UUID -> { the channel's uint32 WIRE id, its 32-byte base64 key }. The id\n // travels WITH the key on purpose: the packet header carries a uint32 routing key\n // (a UUID per packet is unaffordable in a 35-byte header), and shipping the mapping\n // in the same authenticated payload as the key means it can never drift from the\n // key it belongs to, and needs no extra message or announcement race. `id` is\n // stable for the channel's lifetime — it survives rotations, re-tunes and node\n // restarts — and is never 0 (control packets use channelId 0).\n keys: z\n .record(\n z.string(),\n z.object({\n id: z.number().int().positive().describe(\"The channel's uint32 id as it appears in the packet header's channelId field.\"),\n key: z.string().describe(\"32-byte base64 AES-256-GCM channel key, CURRENT epoch only.\"),\n }),\n )\n .describe(\"Channel UUID -> { id, key }.\"),\n shareKey: ShareKeySchema,\n }),\n })\n .optional(),\n share: TuneShareSchema.optional(),\n});\n\n/**\n * Fresh native channel keys WITHOUT re-tuning — the response to a `nativeKeysRotated` notice.\n *\n * Same material `TuneResult.nativeTransport.channelKeys` carries, and the same authorization,\n * but none of tune's side effects: no new connectionId, no new senderMac key, no new stream\n * ids, no provisioning. That is the whole point — a talker installs new keys and keeps talking,\n * where a re-tune would interrupt its audio and rebuild its session on an event that fires\n * whenever anybody leaves the frequency.\n */\nexport const NativeKeysResultSchema = z.object({\n keysetId: z.string().describe(\"Identity of this key material; matches the keysetId in the notice that prompted the fetch.\"),\n bootId: z.string().describe(\"The node generation these keys are bound to. A mismatch against your session's generation means re-tune, not install.\"),\n epoch: z.number().int().min(0).max(255).describe(\"Current key epoch (uint8, wraps mod 256).\"),\n keys: z\n .record(\n z.string(),\n z.object({\n id: z.number().int().positive().describe(\"The channel's uint32 id as it appears in the packet header's channelId field.\"),\n key: z.string().describe(\"32-byte base64 AES-256-GCM channel key, CURRENT epoch only.\"),\n }),\n )\n .describe(\"Channel UUID -> { id, key }.\"),\n shareKey: ShareKeySchema,\n});\n\nexport const AccessCodeSchema = z.object({\n accessCode: z.string().nullable().describe(\"Null when the frequency is open. Owner/admin only.\"),\n});\n\nexport const AccessCodeUpdatedSchema = z.object({\n ok: z.literal(true),\n hasAccessCode: z.boolean(),\n});\n\nexport const JoinRequestResultSchema = z.discriminatedUnion(\"status\", [\n z.object({ status: z.literal(\"joined\") }).describe(\"Auto-approve was on; the caller is now a member.\"),\n z.object({ status: z.literal(\"pending_approval\"), invitationId: z.string() }).describe(\"An admin must approve; poll or await the realtime event.\"),\n]);\n\n// ---- Companies (organizations) ---------------------------------------------------------\n\nexport const OrgRoleSchema = z\n .enum([\"owner\", \"manager\", \"dj\", \"screener\"])\n .describe(\"A company role, highest first. screener (0.79.0) is station staff who is not on the air: it may use the channel controls on the company's stations but is not a broadcaster.\");\nconst _orgRoleMatches: Same<z.infer<typeof OrgRoleSchema>, OrgRole> = true;\nvoid _orgRoleMatches;\n\n\n/**\n * A company as its own staff see it.\n *\n * `name` is the legal entity's name — the station's name, callsign and branding moved to\n * the broadcast frequency on 2026-08-02, because one company owns many stations. Nothing\n * resolves a company by name; the only handle on an existing one is the id.\n *\n * The contact fields are PII and are only populated for manager+ callers; a dj gets the\n * same KEYS with `null` values rather than a different shape, so a client does not have to\n * branch on role to parse the response. Do not infer \"this company has no address\" from\n * nulls — infer \"you cannot see it\". `name` is visible to a dj: it is what identifies the\n * company they work for.\n */\nexport const OrganizationSchema = z.object({\n id: z.string(),\n name: z.string().describe(\"The company's name. Not unique, and never a lookup key.\"),\n stationCount: z\n .number()\n .int()\n .optional()\n .describe(\"Broadcast frequencies this company owns. Present on GET /orgs/mine, which is the only supported way to reach an existing company.\"),\n addressLine1: z.string().nullable(),\n addressLine2: z.string().nullable(),\n city: z.string().nullable(),\n region: z.string().nullable(),\n postalCode: z.string().nullable(),\n country: z.string().nullable().describe(\"ISO 3166-1 alpha-2.\"),\n phone: z.string().nullable(),\n contactEmail: z.string().nullable(),\n createdAt: z.string(),\n myRole: OrgRoleSchema.optional().describe(\"The caller's role. Present on listings and on reads by a member.\"),\n});\ntype _OrganizationResponseIsAnOrganization = z.infer<typeof OrganizationSchema> extends Organization ? true : never;\nconst _organizationMatches: _OrganizationResponseIsAnOrganization = true;\nvoid _organizationMatches;\n\nexport const OrganizationMemberSchema = z.object({\n userId: z.string(),\n handle: z.string().nullable().describe(\"Null for listener-only accounts; render stationId.\"),\n stationId: z.string(),\n avatarColor: z.string(),\n avatar: z.string().nullable().describe(\"Chosen avatar id, or null. See UserSummarySchema.\"),\n role: OrgRoleSchema,\n createdAt: z.string(),\n});\nconst _orgMemberMatches: Same<z.infer<typeof OrganizationMemberSchema>, OrganizationMember> = true;\nvoid _orgMemberMatches;\n\n/** One of the company's stations, for the company-settings roster. */\nexport const CompanyStationSchema = z.object({\n frequencyId: z.string(),\n name: z.string(),\n stationCallsign: z.string(),\n khz: z.number().int(),\n label: z.string().describe(\"Mode-aware display label. Render verbatim.\"),\n});\n\nexport const OrganizationDetailSchema = OrganizationSchema.extend({\n members: z.array(OrganizationMemberSchema).describe(\"On-air staff. Present on a single-company read, absent from listings.\"),\n stations: z\n .array(CompanyStationSchema)\n .describe(\"Broadcast frequencies this company owns. Staff are hired once at the company and reach every one of them.\"),\n});\n\n// ---- Frequency membership and invitations ---------------------------------------------\n\n/** A member of a frequency, flattened — the user fields are inlined rather than nested. */\nexport const FrequencyMemberSchema = z.object({\n userId: z.string(),\n kind: UserKindSchema.describe(USER_KIND_DESCRIPTION),\n handle: z.string().nullable().describe(\"Null for listener-only accounts; render stationId.\"),\n stationId: z.string(),\n avatarColor: z.string(),\n avatar: z.string().nullable().describe(\"Chosen avatar id, or null. See UserSummarySchema.\"),\n role: FrequencyRoleSchema,\n staffRole: OrgRoleSchema.nullable().describe(\n \"The member's role at the company that owns this station (owner, manager, dj, screener), or null when they are not its staff or the frequency has no company. Display this in place of `role` when present: company staff are synced onto a station as ordinary `user` members, so `role` alone reads `user` for a hired DJ. `role` still decides frequency-admin actions.\",\n ),\n joinedAt: z.string(),\n online: z.boolean().describe(\"Live presence at the time of the request. Not a stored field — do not cache it.\"),\n});\n\nexport const InvitationStatusSchema = z.enum([\"pending\", \"accepted\", \"declined\", \"revoked\"]);\n\nexport const InvitationSchema = z.object({\n id: z.string(),\n frequencyId: z.string(),\n invitedUserId: z.string(),\n invitedByUserId: z.string(),\n status: InvitationStatusSchema,\n createdAt: z.string(),\n respondedAt: z.string().nullable(),\n});\n\n/** An invitation as the invitee sees it, denormalised so the list renders without lookups. */\nexport const ReceivedInvitationSchema = z.object({\n id: z.string(),\n frequencyId: z.string(),\n frequencyName: z.string(),\n frequencyKhz: z.number().int(),\n frequencyLabel: z.string().describe(\"Mode-aware display label. Render verbatim.\"),\n invitedBy: z\n .object({ handle: z.string().nullable(), stationId: z.string() })\n .describe(\"The inviter's on-air identity. No real name — see UserSummarySchema.\"),\n createdAt: z.string(),\n});\n\nexport const InvitationAcceptedSchema = z.object({\n ok: z.literal(true),\n frequencyId: z.string().describe(\"The frequency just joined, so the caller can tune straight in.\"),\n});\n\n// ---- Favorites (numbered preset slots, account state) ---------------------------------\n\n/** One preset slot. The full frequency DTO rides along so a preset button — label,\n * branding, mode — renders without a second call; membership still gates the AUDIO,\n * so a favorite kept after leaving a private station renders but re-asks its code. */\nexport const FavoriteSchema = z.object({\n slot: z.number().int(),\n frequency: FrequencySchema,\n updatedAt: z.string(),\n});\n\n// ---- Frequency bans -------------------------------------------------------------------\n\nexport const BanOriginSchema = z.enum([\"admin\", \"code_attempts\"]);\n\n/** A ban-list row, flattened like FrequencyMemberSchema. */\nexport const FrequencyBanSchema = z.object({\n userId: z.string(),\n handle: z.string().nullable().describe(\"Null for listener-only accounts; render stationId.\"),\n stationId: z.string(),\n avatarColor: z.string(),\n avatar: z.string().nullable().describe(\"Chosen avatar id, or null. See UserSummarySchema.\"),\n origin: BanOriginSchema.describe(\"`admin` = banned by a person; `code_attempts` = automatic, after repeated wrong access codes.\"),\n reason: z.string().nullable(),\n bannedBy: z\n .object({ handle: z.string().nullable(), stationId: z.string() })\n .nullable()\n .describe(\"Null for automatic (code_attempts) bans. On-air identity only — see UserSummarySchema.\"),\n expiresAt: z.string().nullable().describe(\"Null = until lifted. code_attempts bans expire on their own.\"),\n createdAt: z.string(),\n});\n\n// ---- Channels and groups --------------------------------------------------------------\n\nexport const ChannelKindSchema = z.enum([\"personal\", \"group\", \"phone\"]);\nexport const TalkPermissionSchema = z.enum([\"open\", \"managed\", \"broadcast_open\"]);\n\nexport const ChannelSchema = z.object({\n id: z.string(),\n frequencyId: z.string(),\n kind: ChannelKindSchema,\n name: z.string(),\n ownerUserId: z.string().nullable().describe(\"Set for personal channels.\"),\n talkPermission: TalkPermissionSchema,\n colorIndex: z.number().int().describe(\"Index into the fixed channel-colour palette.\"),\n isDefault: z.boolean().describe('The auto-created \"Public\" channel; its roster follows frequency membership and cannot be edited directly.'),\n memberUserIds: z.array(z.string()).describe(\"Directly-added roster. Does NOT include members who are only in via a linked group.\"),\n memberTalkPermissions: z.record(z.string(), z.boolean()).describe(\"userId -> canTalk, for direct members only.\"),\n groupIds: z.array(z.string()),\n groupTalkPermissions: z.record(z.string(), z.boolean()).describe(\"groupId -> canTalk, applying to every member of that group.\"),\n effectiveMemberUserIds: z.array(z.string()).describe(\"Direct members unioned with every linked group's membership. Recomputed on each read.\"),\n talkEligibleUserIds: z.array(z.string()).describe(\"The subset of effective members who may transmit here.\"),\n forceMutedUserIds: z\n .array(z.string())\n .describe(\n \"Members under the admin mute on this channel (capability `member-force-mute`): the media node refuses their audio here until an owner or admin lifts it, or they lift it themselves. Draw Unmute in place of Mute for these.\",\n ),\n nowPlayingTag: z.string().nullable().describe(\"DJ-set now-playing tag on a broadcast channel; null when unset.\"),\n phone: ChannelPhoneSummarySchema.optional().describe(\"The line behind a `phone` channel (capability `phone-numbers`). Absent on every other kind.\"),\n createdAt: z.string(),\n listenerCount: z.number().int().describe(\"Live, from the media node's roster snapshot. Zero when nothing is running.\"),\n talkerCallsigns: z.array(z.string()).describe(\"Currently transmitting, for roster display.\"),\n});\nconst _channelMatches: Same<z.infer<typeof ChannelSchema>, Channel> = true;\nvoid _channelMatches;\n\n/**\n * A channel as a BOARD needs it (capability `frequency-board`): everything in ChannelSchema\n * except the six id lists and maps, which are replaced by a count and by the CALLER's own\n * standing on the channel.\n *\n * The lists are what a management screen edits. A board only ever asked them three\n * questions, all about itself: am I on this channel, did I join it directly, may I talk\n * here. On a frequency of 2000 people the lists were most of a megabyte, re-read by every\n * tuned client whenever anybody's access changed.\n */\nexport const BoardChannelSharedSchema = z.object({\n id: z.string(),\n frequencyId: z.string(),\n kind: ChannelKindSchema,\n name: z.string(),\n ownerUserId: z.string().nullable().describe(\"Set for personal channels.\"),\n talkPermission: TalkPermissionSchema,\n colorIndex: z.number().int(),\n isDefault: z.boolean(),\n nowPlayingTag: z.string().nullable(),\n phone: ChannelPhoneSummarySchema.optional().describe(\"The line behind a `phone` channel (capability `phone-numbers`). Absent on every other kind.\"),\n createdAt: z.string(),\n memberCount: z.number().int().describe(\"Effective members: the direct roster unioned with every linked group. 1 for a personal channel.\"),\n});\nexport type BoardChannelShared = z.infer<typeof BoardChannelSharedSchema>;\n\nexport const BoardChannelViewerSchema = z.object({\n member: z.boolean().describe(\"The caller is an effective member (directly or through a linked group). For a personal channel: the caller owns it.\"),\n directMember: z.boolean().describe(\"The caller holds a direct roster row, i.e. what a self-leave would remove.\"),\n mayTalk: z.boolean().describe(\"The caller may transmit here: the shared `canTransmit` rule, evaluated server-side, role override included.\"),\n forceMuted: z\n .boolean()\n .describe(\n \"The caller is under the admin mute on this channel (capability `member-force-mute`): their talk switch may stay on, but the media node refuses their audio here until it is lifted. The caller may lift it themselves.\",\n ),\n});\n\nexport const BoardChannelSchema = BoardChannelSharedSchema.extend({\n listenerCount: z.number().int().describe(\"Live, from the media node's roster snapshot. Zero when nothing is running.\"),\n talkerCallsigns: z.array(z.string()).describe(\"Currently transmitting, for roster display.\"),\n viewer: BoardChannelViewerSchema,\n});\nexport type BoardChannel = z.infer<typeof BoardChannelSchema>;\n\nexport const FrequencyBoardSchema = z.object({\n channels: z.array(BoardChannelSchema).describe(\"Every channel the caller may see, oldest first. Managed channels they are not on are omitted, exactly as GET /frequencies/:id/channels omits them.\"),\n});\n\n/** One member, with the personal channel a board draws them under. */\nexport const BoardMemberSchema = z.object({\n member: FrequencyMemberSchema,\n personalChannel: BoardChannelSchema.nullable(),\n});\n\nexport const BulkMembersAddedSchema = z.object({\n ok: z.literal(true),\n added: z.number().int().describe(\"How many of the requested users were actually added — non-members of the frequency are skipped, not rejected.\"),\n});\n\nexport const GroupSchema = z.object({\n id: z.string(),\n frequencyId: z.string(),\n name: z.string(),\n memberUserIds: z.array(z.string()),\n organizationId: z.string().nullable().describe(\"Set when the group is derived from an organization's staff; its membership is then read-only.\"),\n createdAt: z.string(),\n});\n\n// ---- Invite links ---------------------------------------------------------------------\n\n/**\n * A standing, shareable invite. Exactly one of frequencyId / organizationId is set, and\n * which one decides whether `role` or `orgRole` is meaningful.\n */\nexport const InviteLinkSchema = z.object({\n id: z.string(),\n code: z.string().describe(\"The shareable code. Case-insensitive on redeem.\"),\n frequencyId: z.string().nullable(),\n organizationId: z.string().nullable(),\n role: FrequencyRoleSchema.describe(\"Granted on redeem of a FREQUENCY link. Present but meaningless on an organization link.\"),\n orgRole: OrgRoleSchema.nullable().describe(\"Granted on redeem of an ORGANIZATION link; null on a frequency link.\"),\n expiresAt: z.string().nullable(),\n maxUses: z.number().int().nullable().describe(\"Null = unlimited.\"),\n useCount: z.number().int(),\n revoked: z.boolean(),\n createdAt: z.string(),\n channelId: z.string().nullable().describe(\"Channel-targeted links: redeem places the redeemer on this channel. Null = plain membership (default Public via ordinary join).\"),\n channelName: z.string().nullable().describe(\"The target channel's CURRENT name — renames track live; the id is the identity.\"),\n canTalk: z.boolean().describe(\"Whether redeem grants transmit on the target channel. Always false on untargeted and organization links.\"),\n});\n\n/** What an anonymous invitee is shown before signing up — deliberately minimal. */\nexport const InviteLinkPreviewSchema = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"frequency\"),\n name: z.string(),\n khz: z.number().int(),\n label: z.string().describe(\"Mode-aware display label. Render verbatim.\"),\n // The id, not just the name, because the name is free text and not unique: a client\n // wiring a listen cable to the target channel must match on identity or it will patch\n // onto a channel the link never named (Switchboard, 2026-08-19).\n channelId: z.string().nullable().describe(\"Channel-targeted links: the target channel's id — the identity to match on. Null = plain membership (default Public via ordinary join).\"),\n channelName: z.string().nullable().describe(\"Channel-targeted links: where the redeemer lands. Null = plain membership. Display only — never match on this.\"),\n canTalk: z.boolean().describe(\"Whether redeeming grants transmit on that channel.\"),\n }),\n z.object({\n kind: z.literal(\"organization\"),\n // The company's name only. It carried a stationCallsign until 2026-08-02, when station\n // identity moved to the frequency — a staff invite is to the company, not to one of its\n // stations, so there is no single callsign to name here.\n name: z.string(),\n }),\n]);\n\nexport const InviteRedeemResultSchema = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"frequency\"),\n frequencyId: z.string(),\n // Where the redeem actually put them. A redeemer may never have previewed (a code\n // pasted after sign-in), so redeem has to be able to answer this on its own.\n channelId: z.string().nullable().describe(\"Channel-targeted links: the channel this redeem placed the redeemer on. Null = plain membership, no channel grant.\"),\n }),\n z.object({ kind: z.literal(\"organization\"), organizationId: z.string() }),\n]);\n\n// ---- Billing --------------------------------------------------------------------------\n\n/**\n * Anonymous billing bootstrap (2026-07-24) — what a checkout surface needs BEFORE\n * sign-in: whether this deployment takes payments at all, the Stripe publishable key\n * (public by design; the secret key never leaves the server), authoritative plan pricing,\n * and the trial length. Added for the frequencytalk.com subscribe page, which serves\n * users of client apps that never open the Frequency console.\n */\nexport const BillingPublicConfigSchema = z.object({\n configured: z.boolean().describe(\"Whether this deployment has billing configured (Stripe keys + prices present).\"),\n publishableKey: z\n .string()\n .nullable()\n .describe(\"Stripe publishable key for Payment Element surfaces, or null when not set server-side.\"),\n plans: z.array(\n z.object({\n key: z.enum([\"operator\", \"broadcast\"]),\n name: z.string(),\n priceUsdCents: z.number().int(),\n per: z.literal(\"frequency\"),\n }),\n ),\n trialDays: z.number().int().describe(\"Free-trial length for first-time customers; returning customers are charged immediately.\"),\n});\nexport type BillingPublicConfigDto = z.infer<typeof BillingPublicConfigSchema>;\n\n/**\n * The CALLER's own free-trial answer (0.100.0, capability `trial-eligibility`). Computed by\n * the same function `POST /billing/subscribe` applies (`billing/trial.ts`), so the label an app\n * shows and the price the card is charged cannot disagree. Never cached: it changes the moment\n * the caller first buys or creates a frequency.\n */\nexport const BillingTrialEligibilitySchema = z.object({\n trialEligible: z\n .boolean()\n .describe(\n \"Whether this caller's next subscription would start with the free trial. False once they own any frequency, or have ever \" +\n \"had a subscription (any status, canceled included) on a billing account they can bill against: their own, or a company \" +\n \"they hold owner or manager on.\",\n ),\n trialDays: z\n .number()\n .int()\n .describe(\"Trial length this caller's next subscription would get: the deployment's trial length when eligible, 0 when not.\"),\n});\nexport type BillingTrialEligibilityDto = z.infer<typeof BillingTrialEligibilitySchema>;\n\nexport const SetupIntentCreatedSchema = z.object({\n clientSecret: z\n .string()\n .nullable()\n .describe(\"Confirm this with the Stripe Payment Element, then call /billing/subscribe.\"),\n customerSessionClientSecret: z\n .string()\n .nullable()\n .describe(\"Stripe CustomerSession secret so the Payment Element can offer this customer's saved cards.\"),\n});\n\n/**\n * Stripe subscription status. A plain string, not an enum: the value is Stripe's, arrives\n * via webhooks as well as this API, and Stripe may add statuses — the same reasoning as\n * error codes staying open. `subscriptionActive` is the field to branch on.\n */\nexport const SubscribeResultSchema = z.object({\n status: z.string().describe(\"Stripe's subscription status, verbatim.\"),\n subscriptionActive: z.boolean().describe(\"Whether the subscription entitles frequency creation right now. Branch on this, not on status.\"),\n});\nconst _subscribeResultMatches: Same<z.infer<typeof SubscribeResultSchema>, SubscribeResultDto> = true;\nvoid _subscribeResultMatches;\n\nexport const BillingSubscriptionSchema = z.object({\n id: z.string(),\n planKey: z.enum([\"operator\", \"broadcast\"]),\n status: z.string(),\n frequencyId: z.string().nullable().describe(\"The frequency occupying this slot, or null for an unclaimed (paid but unused) slot.\"),\n currentPeriodEnd: z.string().nullable(),\n cancelAtPeriodEnd: z.boolean(),\n lastPaymentFailureAt: z\n .string()\n .nullable()\n .describe(\"When the most recent payment attempt failed, or null while the card is healthy. Cleared on recovery.\"),\n nextPaymentAttemptAt: z\n .string()\n .nullable()\n .describe(\n \"When Stripe will next attempt the card. NULL while `lastPaymentFailureAt` is set means no retry is coming — the card must be replaced. Branch on that pair, not on status alone.\",\n ),\n fundedBy: z.enum([\"stripe\", \"credit\"]).describe(\"What pays for this row: a card subscription at Stripe, or the account's prepaid credit (0.123.3). A credit-funded row has no Stripe subscription, so the card routes answer 409 CREDIT_FUNDED_SUBSCRIPTION.\"),\n owner: z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"user\") }),\n z.object({ type: z.literal(\"organization\"), organizationId: z.string(), name: z.string() }),\n ]),\n});\nconst _billingSubscriptionMatches: Same<z.infer<typeof BillingSubscriptionSchema>, BillingSubscriptionDto> = true;\nvoid _billingSubscriptionMatches;\n\nexport const BillingStatusSchema = z.object({\n configured: z.boolean().describe(\"Whether this deployment has billing configured at all.\"),\n enforced: z.boolean().describe(\"Whether frequency creation is actually gated on a subscription.\"),\n subscriptions: z.array(BillingSubscriptionSchema),\n});\nconst _billingStatusMatches: Same<z.infer<typeof BillingStatusSchema>, BillingStatusDto> = true;\nvoid _billingStatusMatches;\n\nexport const PortalSessionSchema = z.object({\n url: z.string().describe(\"Stripe-hosted Customer Portal URL. Open in the system browser, not in-app.\"),\n});\n\n/** A non-reserving pick from the number allocator — see GET /frequencies/suggest-number. */\nexport const SuggestedNumberSchema = z.object({\n khz: z.number().int().describe(\"Suggested integer kHz — valid for the requested mode and unused at suggestion time. NOT reserved.\"),\n label: z.string().describe('Display form of the number, e.g. \"121.500\".'),\n});\nexport type SuggestedNumberDto = z.infer<typeof SuggestedNumberSchema>;\n\n// In-house subscription management (2026-07-22) — see the note in api.ts.\n\nexport const BillingPaymentMethodSchema = z.object({\n paymentMethod: z\n .object({\n kind: z.string().describe('Stripe PaymentMethod type, e.g. \"card\". Card fields are null for other kinds.'),\n brand: z.string().nullable().describe('Card network, e.g. \"visa\".'),\n last4: z.string().nullable(),\n expMonth: z.number().nullable(),\n expYear: z.number().nullable(),\n })\n .nullable()\n .describe(\"The payment method charged for this subscription, or null if none is on file yet.\"),\n});\nconst _billingPaymentMethodMatches: Same<z.infer<typeof BillingPaymentMethodSchema>, BillingPaymentMethodDto> = true;\nvoid _billingPaymentMethodMatches;\n\nexport const BillingInvoiceSchema = z.object({\n id: z.string(),\n number: z.string().nullable().describe(\"Stripe's human invoice number, once finalised.\"),\n status: z.string().describe('Stripe invoice status: \"draft\", \"open\", \"paid\", \"void\", \"uncollectible\".'),\n amountDue: z.number().describe(\"In the smallest currency unit (cents).\"),\n amountPaid: z.number().describe(\"In the smallest currency unit (cents).\"),\n currency: z.string().describe('Lowercase ISO code, e.g. \"usd\".'),\n created: z.string().describe(\"ISO 8601.\"),\n hostedInvoiceUrl: z.string().nullable().describe(\"Stripe-hosted invoice page. Open in the system browser.\"),\n invoicePdf: z.string().nullable().describe(\"Direct PDF download link.\"),\n});\nexport const BillingInvoicesSchema = z.object({ invoices: z.array(BillingInvoiceSchema) });\nconst _billingInvoicesMatches: Same<z.infer<typeof BillingInvoicesSchema>, BillingInvoicesDto> = true;\nvoid _billingInvoicesMatches;\n\nexport const SubscriptionMutationSchema = z.object({\n id: z.string(),\n status: z.string().describe(\"Stripe's subscription status, verbatim.\"),\n cancelAtPeriodEnd: z.boolean(),\n currentPeriodEnd: z.string().nullable(),\n});\nconst _subscriptionMutationMatches: Same<z.infer<typeof SubscriptionMutationSchema>, SubscriptionMutationDto> = true;\nvoid _subscriptionMutationMatches;\n\n// Plan changes (2026-08-01) — see the note in api.ts.\n\nexport const PlanChangePreviewSchema = z.object({\n targetPlanKey: z.enum([\"operator\", \"broadcast\"]),\n dueNowCents: z.number().int().describe(\"First charge after credits, in cents (0 while a carried trial runs).\"),\n creditCents: z.number().int().describe(\"Credit applied: the fixed operator month (upgrade) or unused broadcast time (downgrade).\"),\n trialCarried: z.boolean().describe(\"Whether the old subscription's remaining trial days carry to the new one.\"),\n trialEnd: z.string().nullable().describe(\"ISO 8601 end of the carried trial, when trialCarried.\"),\n khzRequired: z.boolean().optional().describe(\"Downgrade only: the frequency must move to a HAM-band number in the same change.\"),\n});\nconst _planChangePreviewMatches: Same<z.infer<typeof PlanChangePreviewSchema>, PlanChangePreviewDto> = true;\nvoid _planChangePreviewMatches;\n\nexport const PlanChangeStartSchema = z.object({\n clientSecret: z.string().describe(\"Confirm this with the Stripe Payment Element, then call the matching /complete.\"),\n customerSessionClientSecret: z.string().optional().describe(\"CustomerSession secret so the Payment Element can offer saved cards.\"),\n organizationId: z.string().optional().describe(\"Upgrade only: the station minted (or adopted) for the broadcast side.\"),\n organizationMinted: z.boolean().optional().describe(\"True when /start created the org — delete it via DELETE /orgs/:id on abandon.\"),\n preview: PlanChangePreviewSchema,\n});\nconst _planChangeStartMatches: Same<z.infer<typeof PlanChangeStartSchema>, PlanChangeStartDto> = true;\nvoid _planChangeStartMatches;\n\nexport const PlanChangeResultSchema = z.object({\n newSubscriptionId: z.string().describe(\"Our id for the replacement subscription (as in /billing/status).\"),\n status: z.string().describe(\"Stripe's status of the new subscription, verbatim.\"),\n oldSubscriptionStatus: z.string().describe(\"Stripe's status of the replaced subscription after cancellation.\"),\n});\nconst _planChangeResultMatches: Same<z.infer<typeof PlanChangeResultSchema>, PlanChangeResultDto> = true;\nvoid _planChangeResultMatches;\n\n// ---- Listener ledger (2026-08-13) -----------------------------------------------------\n\n/**\n * One row of the listener ledger: a continuous listen on a frequency, over one audio\n * transport, from `startedAt` to `endedAt` (null = live right now). This is the station\n * operator's licensed-music audience evidence — rows are written by the audio paths\n * themselves (HLS ticket lifecycle; media-node heartbeat for WebRTC/native), never by a\n * client's say-so, and they survive account erasure with identity detached.\n */\nexport const ListenerSessionSchema = z.object({\n id: z.string(),\n frequencyId: z.string(),\n userId: z.string().nullable().describe(\"Null for anonymous listeners and for erased accounts (identity detached, row retained).\"),\n handle: z.string().nullable().describe(\"The listener's callsign at read time, when the account still exists. Also null for a listener-only account, which has none — fall back to stationId.\"),\n stationId: z\n .string()\n .nullable()\n .describe(\n \"The listener's Station ID at read time, when the account still exists. Replaced `displayName` on 2026-08-29: most rows here come from listen-only apps whose accounts carry NO callsign, so without it a signed-in listener would be unidentifiable — and this is licensing evidence. On-air identity only; no real name.\",\n ),\n transport: z.enum([\"hls\", \"webrtc\", \"native\"]).describe(\"Which audio path carried the listen — hls covers the Tuner and any player; webrtc the Service Manager; native a Switchboard engine.\"),\n clientId: z\n .string()\n .nullable()\n .describe(\n \"Which APP the listen came from — an OAuth client_id (\\\"tuner-windows\\\", \\\"tuner-apple\\\", \\\"frequency-web\\\", …); §2 maps id to name, and the id is sent because renaming a shipped client moves only its display name. NOT A DEVICE CLASS and must not be rendered as one: `tuner-apple` is deliberately one client_id for macOS AND iOS (§4), so a phone and a laptop are indistinguishable here by design, and no smart-speaker or car client exists. Null on rows predating 2026-09-08 (no backfill is possible) and whenever the listening install has no surviving session to resolve.\",\n ),\n startedAt: z.string(),\n lastSeenAt: z.string().describe(\"Last proven moment of listening — the liveness clock.\"),\n endedAt: z.string().nullable().describe(\"Null while the listen is live.\"),\n endReason: z.string().nullable().describe('How it ended: \"disconnected\", \"stopped\", \"expired\", \"timeout\", \"revoked\", \"replaced\".'),\n});\n\nexport const ListenerSessionListSchema = z.object({\n sessions: z.array(ListenerSessionSchema).describe(\"Newest first.\"),\n liveCount: z.number().int().describe(\"Open sessions (endedAt null) on the frequency right now.\"),\n});\n\n/**\n * Where a frequency's audience was over a period, as totals (capability `listener-places`,\n * 0.115.0). Counts are DISTINCT LISTENERS, not listens. A place with fewer listeners than\n * `floor` is never named: its listeners stay inside the level above.\n */\nexport const ListenerPlacesSchema = z.object({\n from: z.string().describe(\"First UTC day of the period, YYYY-MM-DD (inclusive).\"),\n to: z.string().describe(\"The UTC day the period ends BEFORE, YYYY-MM-DD (exclusive).\"),\n floor: z.number().int().describe(\"A place with fewer distinct listeners than this in the period is not named. Its listeners are still counted in the level above: a small state in its country, a small country in `elsewhere`.\"),\n listeners: z.number().int().describe(\"Distinct listeners in the period, placed or not. The denominator for a percentage.\"),\n unknown: z\n .number()\n .int()\n .describe(\"Listeners with at least one listen that carries no place: listens before 0.115.0, a private or unlisted address, or a listen opened with no location database loaded. A listener can count here and in a country.\"),\n elsewhere: z.number().int().describe(\"Listeners in countries too small to name, added together.\"),\n countries: z\n .array(\n z.object({\n country: z.string().describe(\"ISO 3166-1 alpha-2 country code, upper case. The app supplies the name.\"),\n listeners: z.number().int(),\n areas: z\n .array(\n z.object({\n id: z.string().describe('A stable id, for example \"us-west-coast\".'),\n name: z.string().describe('English display name, for example \"West Coast\".'),\n listeners: z.number().int(),\n }),\n )\n .describe(\"Broad areas of the country, largest first. United States only today; empty for every other country. An area is a group of states, so it can be named where none of its states is large enough to be.\"),\n regions: z\n .array(z.object({ region: z.string().describe(\"State or province, by its English name.\"), listeners: z.number().int() }))\n .describe(\"States or provinces at or above the floor, largest first. Somebody who listened from two counts in both, so these can sum to more than the country.\"),\n }),\n )\n .describe(\"Countries at or above the floor, largest first.\"),\n attribution: z\n .object({ text: z.string(), url: z.string() })\n .nullable()\n .describe(\"The credit the location database's licence requires. SHOW IT, as a link, wherever these totals are drawn. Null when the deployment has no database loaded.\"),\n});\n\n/**\n * Where a station is told that it dropped off the air (capability `off-air-notice`,\n * 0.116.0). The two numbers are served so a settings pane can say what will happen without\n * carrying its own copy of them.\n */\nexport const OffAirNoticeSchema = z.object({\n email: z.string().nullable().describe(\"The address notices go to. Null means none is set and nothing is sent.\"),\n updatedAt: z.string().nullable().describe(\"When the address was last set (ISO 8601). Null when none is set.\"),\n holdSeconds: z.number().int().describe(\"How long a station must have been off the air unexpectedly before the message is sent. A drop that recovers sooner sends nothing.\"),\n minGapSeconds: z.number().int().describe(\"The least time between two off-the-air messages for one station. A station that keeps dropping gets one message, which says how many times.\"),\n});\nexport type OffAirNotice = z.infer<typeof OffAirNoticeSchema>;\n\n// ---- Cheer and Hush (capability `cheer-hush`, 0.118.0) ----------------------------------\n\nexport const StationReactionSchema = z.enum([\"cheer\", \"hush\"]);\n\n/** A listener's own Cheer or Hush on what is playing. Never anybody else's, never a count. */\nexport const MyStationReactionSchema = z.object({\n since: z.string().nullable().describe(\"The airing this answer is about: `nowPlaying.since`. Null when nothing can be cheered or hushed right now.\"),\n reaction: StationReactionSchema.nullable().describe(\"The caller's own Cheer or Hush on that airing. Null when they have sent neither, or took it back.\"),\n});\nexport type MyStationReaction = z.infer<typeof MyStationReactionSchema>;\n\n/** What an airing is: a song (it has a title) or a show (it has only its line of text). */\nexport const AiringKindSchema = z.enum([\"track\", \"show\"]);\n\n/** The live tally for a station's staff. `airing` null means nothing is playing that can be cheered. */\nexport const StationReactionTallySchema = z.object({\n airing: z\n .object({\n since: z.string().describe(\"When this airing began: `nowPlaying.since`.\"),\n kind: AiringKindSchema,\n title: z.string().describe(\"The song's title, or the show's line of text.\"),\n artist: z.string().nullable().describe(\"The song's artist. Null for a show, and for a song published without one.\"),\n })\n .nullable(),\n cheers: z.int().describe(\"How many listeners are cheering this airing. People, not presses: one listener counts once.\"),\n hushes: z.int().describe(\"How many listeners are hushing this airing.\"),\n});\nexport type StationReactionTally = z.infer<typeof StationReactionTallySchema>;\n\n/** What the audience made of each song and show over a period, most liked first. */\nexport const StationPopularSchema = z.object({\n from: z.string().describe(\"Start of the period (ISO 8601, inclusive).\"),\n to: z.string().describe(\"End of the period (ISO 8601, exclusive).\"),\n items: z.array(\n z.object({\n key: z.string().describe(\"The service's own identity for this song or show. Opaque: compare it, never build it.\"),\n kind: AiringKindSchema,\n title: z.string().describe(\"As most recently published.\"),\n artist: z.string().nullable(),\n plays: z.int().describe(\"How many airings it had in the period. Two cheers in forty plays and two in two are opposite facts.\"),\n cheers: z.int().describe(\"Cheers across those airings. One listener counts once per airing.\"),\n hushes: z.int(),\n lastPlayedAt: z.string(),\n }),\n ),\n});\nexport type StationPopular = z.infer<typeof StationPopularSchema>;\n\n/* ------------------------------------------------------------------------ *\n * Contacts (capability `contacts`)\n *\n * Every DTO here carries on-air identity only — handle, stationId, avatarColor —\n * exactly as UserSummarySchema does, and for the same reason. A contact is a\n * person you talk to, not a person whose billing name you are entitled to.\n * ------------------------------------------------------------------------ */\n\n/**\n * One contact, as the list holder sees them.\n *\n * ⚠️ **Every field spread in from `ContactPreferencesSchema` is OWNER-PRIVATE and must\n * never be returned to the person it describes.** They are flattened onto this DTO rather\n * than nested under a `preferences` key because `alias` and `favorite` were already here\n * and a nested copy beside them would be two spellings of one fact — the shape that\n * drifts. The WRITE route still takes the whole block at once (see the schema's note on\n * why it is a PUT); flat on the read side and whole on the write side are not in tension.\n */\nexport const ContactSchema = UserSummarySchema.extend({\n status: VisibleStatusSchema.describe(\n \"What THIS caller may observe. An invisible contact always reads `offline` — never infer liveness from anything else in this DTO.\",\n ),\n since: z.iso.datetime().describe(\"When the request was accepted.\"),\n statusAt: z\n .number()\n .int()\n .describe(\n \"When `status` was true, in ms since the epoch — the same clock as the `at` on a `contact.presence` event. Hold the newest value per contact and ignore anything not newer, in EITHER direction: this read and the event stream are two sources of one truth, and an edge arriving while this request is in flight would otherwise lose to the older answer permanently. Sampled BEFORE the statuses are read, so an edge published mid-read is always newer and therefore always wins.\",\n ),\n waveCooldownSeconds: z\n .number()\n .int()\n .nullable()\n .describe(\n \"Seconds until YOU may wave at this contact again, or null when you may wave now. Render the Wave control as \" +\n \"unavailable with the time remaining rather than letting the press bounce: the refusal is otherwise a 429 the \" +\n \"operator has to be looking elsewhere on screen to read. A DURATION and not a deadline, so a client with a \" +\n \"skewed clock still counts down correctly — convert it to a local deadline on receipt and re-derive from the \" +\n \"`Retry-After` on a 429, which is the same number measured later. This is YOUR spend against them and says \" +\n \"nothing whatever about them: a muted, hidden, offline and delivered wave all leave it identical, which is \" +\n \"deliberate and is what makes serving it safe.\",\n ),\n}).extend(ContactPreferencesSchema.shape);\nexport type Contact = z.infer<typeof ContactSchema>;\n\nexport const ContactListSchema = z.object({\n contacts: z.array(ContactSchema),\n maxContacts: z.number().int().describe(\"The server's ceiling, served rather than hardcoded so a client renders the real limit.\"),\n});\n\n/**\n * A pending request, in either direction.\n *\n * `user` is the OTHER party — the sender on an incoming request, the recipient on\n * an outgoing one — because that is the only person a client needs to render, and\n * carrying both would put the caller's own summary in every row for nothing.\n *\n * There is no message field, deliberately: free text attached to a request from a\n * stranger is an unmoderated channel to someone who has not consented to hear from\n * them, and it would need its own screening, reporting and retention story.\n */\nexport const ContactRequestSchema = z.object({\n id: z.string(),\n direction: z.enum([\"incoming\", \"outgoing\"]),\n user: UserSummarySchema.describe(\"The other party.\"),\n status: ContactRequestStatusSchema,\n createdAt: z.iso.datetime(),\n});\nexport type ContactRequestDto = z.infer<typeof ContactRequestSchema>;\n\nexport const ContactRequestListSchema = z.object({\n incoming: z.array(ContactRequestSchema),\n outgoing: z.array(ContactRequestSchema),\n});\n\nexport const BlockedUserSchema = UserSummarySchema.extend({\n blockedAt: z.iso.datetime(),\n});\n\nexport const BlockedUserListSchema = z.object({ blocked: z.array(BlockedUserSchema) });\n\n/** The caller's own status. `effective` differs from `chosen` only via auto-away. */\nexport const MyStatusSchema = z.object({\n chosen: UserStatusSchema,\n effective: UserStatusSchema,\n});\n\n/* ---------------------------------- chat --------------------------------- */\n\n/**\n * One relayed message.\n *\n * `seq` is server-assigned and SHARED by both directions of a conversation, which\n * is what totally-orders an interleaved exchange without either clock being\n * trusted. It is also the cursor for the reconnect re-read and the ack.\n */\nexport const ChatMessageSchema = z.object({\n id: z.string(),\n seq: z.number().int().describe(\"Monotonic within the conversation, across both directions. The ack cursor.\"),\n fromUserId: z.string(),\n body: z.string(),\n sentAt: z.iso.datetime(),\n clientMessageId: z.string().nullable().describe(\"Echoed back so a sender can match this to its optimistic row; null on messages from the other party.\"),\n kind: ChatMessageKindSchema.describe(\"How to fold this in (contract §15). `text` for anything relayed before kinds existed.\"),\n refId: z.string().nullable().describe(\"The message a reaction, edit or unsend points at; null for text.\"),\n reaction: z.string().nullable().describe(\"The emoji of a reaction; null otherwise.\"),\n reactionRemove: z.boolean().describe(\"A reaction taking the sender's earlier one back.\"),\n replyTo: ChatReplyToSchema.nullable().describe(\"The message a text replies to, quoted whole; null when not a reply.\"),\n tz: ChatTimeZoneSchema.nullable().describe(\"The sender's IANA time zone, when they share it; null otherwise. Lets a reader show a written time in their own zone.\"),\n offer: ChatFileOfferSchema.nullable().describe(\"For kind `offer`: the file or voice message offered (contract §20); null otherwise.\"),\n sender: ChatSenderSchema.nullable().describe(\n \"Who sent it, when the two of you are NOT contacts (capability `chat-non-contacts`), so the thread can be named; \" +\n \"null between contacts, whose label comes from the contact list.\",\n ),\n});\nexport type ChatMessage = z.infer<typeof ChatMessageSchema>;\n\nexport const ChatMessageListSchema = z.object({\n messages: z.array(ChatMessageSchema).describe(\"Ascending by seq. Only what is still buffered — this is a relay, not a history.\"),\n});\n\nexport const ChatSendResultSchema = z.object({\n id: z.string(),\n seq: z.number().int(),\n sentAt: z.iso.datetime(),\n});\n\n/* ------------------------------- group chats ------------------------------- */\n\n/**\n * Where a conversation lives: a 1:1 with a contact (`peerUserId`), or a group (`groupId`).\n *\n * A two-person conversation between CONTACTS is always the 1:1, even when a group shrank to\n * it, so that their one history continues. A two-person conversation between people who are\n * NOT contacts (they met in a group) is a group of two.\n */\nexport const ChatConversationRefSchema = z.union([\n z.object({ peerUserId: z.string() }).strict(),\n z.object({ groupId: z.string() }).strict(),\n]);\nexport type ChatConversationRef = z.infer<typeof ChatConversationRefSchema>;\n\nexport const ChatGroupSchema = z.object({\n groupId: z.string().describe(\"Derived from the member set: the same people always make the same id, so a client's history for it continues.\"),\n members: z.array(UserSummarySchema).describe(\"Everybody in the group, the caller included. Labels only (handle, stationId), never a name.\"),\n});\nexport type ChatGroup = z.infer<typeof ChatGroupSchema>;\n\nexport const ChatGroupListSchema = z.object({\n groups: z.array(ChatGroupSchema).describe(\"Every active group the caller is in. The reconcile after a socket gap, since a missed `chat.membership` has no next edge.\"),\n});\n\nexport const ChatGroupChangeResultSchema = z.object({\n conversation: ChatConversationRefSchema.nullable().describe(\"Where the chat went: a group, the 1:1 the remaining two already share, or null when fewer than two remain.\"),\n group: ChatGroupSchema.nullable().describe(\"The group it went to, when `conversation` is a group.\"),\n});\n\nexport const ChatGroupSendResultSchema = ChatSendResultSchema.extend({\n skipped: z.array(z.string()).describe(\"Members this message did NOT reach because their status is Busy. Nothing is held for them.\"),\n});\n\nexport const ChatGroupFileOfferResultSchema = ChatGroupSendResultSchema.extend({\n offerId: z.string().describe(\"The group offer. Each recipient's transfer is `groupOfferLegId(offerId, theirUserId)`.\"),\n expiresAt: z.iso.datetime(),\n transfers: z\n .array(z.object({ offerId: z.string(), toUserId: z.string() }))\n .describe(\"One transfer per member the offer was made to: everybody but you and the members in `skipped`.\"),\n});\n\n/**\n * A link preview: the page's own Open Graph card, read by the control plane (never a\n * screenshot, and the page's scripts never run). `image` is a re-encoded WebP inside a data\n * URL, so a client renders it without contacting the linked site or sending a token anywhere.\n * Every text field is display text, already stripped of control and bidi characters, and\n * must still be rendered as TEXT, never as markup.\n */\nexport const LinkPreviewSchema = z.object({\n url: z.string().describe(\"The URL previewed, fragment removed.\"),\n host: z.string().describe(\"The host the page was finally served from, after redirects.\"),\n title: z.string().nullable(),\n description: z.string().nullable(),\n siteName: z.string().nullable(),\n image: z.string().nullable().describe(\"data:image/webp;base64,... re-encoded server-side, or null.\"),\n});\nexport type LinkPreview = z.infer<typeof LinkPreviewSchema>;\n\nexport const LinkPreviewResponseSchema = z.object({\n preview: LinkPreviewSchema.nullable().describe(\"Null when the page has no card, cannot be fetched safely, or previews are switched off.\"),\n enabled: z.boolean().describe(\"False when an operator has switched link previews off platform-wide.\"),\n});\n\n/** One transfer as the server records it (metadata only; the bytes never reach the platform). */\nexport const TransferRecordSchema = z.object({\n offerId: z.string(),\n fromUserId: z.string(),\n toUserId: z.string(),\n name: z.string(),\n size: z.int(),\n mime: z.string(),\n voice: z.boolean(),\n state: TransferStateSchema,\n attempt: z\n .int()\n .describe(\"Which connection attempt this is: 1 from the offer, one more after each `retry`. Signalling and `fail` name it, and anything naming an older attempt is dropped.\"),\n groupId: z.string().nullable().describe(\"The group chat this transfer was offered in (one per recipient of a group offer), or null for a 1:1.\"),\n createdAt: z.iso.datetime(),\n expiresAt: z.iso.datetime(),\n});\nexport type TransferRecord = z.infer<typeof TransferRecordSchema>;\n\nexport const TransferConfigSchema = z.object({\n limits: ChatTransferLimitsSchema,\n maxRetries: z.int().describe(\"How many times a recipient may retry one failed transfer before `RETRY_LIMIT` (capability `transfer-retry`).\"),\n iceServers: z\n .array(z.object({ urls: z.string(), username: z.string().optional(), credential: z.string().optional() }))\n .describe(\"TURN relay for the data channel. Use iceTransportPolicy \\\"relay\\\": the server strips every non-relay candidate anyway.\"),\n});\nexport type TransferConfig = z.infer<typeof TransferConfigSchema>;\n\n/* ---------------------------------- calls -------------------------------- */\n\n/**\n * The result of answering a call.\n *\n * `audioMode` is on the CALL, not the channel: there is no latching field on a\n * Channel, and a call's frequency mode never crosses the wire. The client keeps\n * its producer unpaused and the server never needs to know.\n */\nexport const CallAcceptedSchema = z.object({\n callId: z.string(),\n frequencyId: z.string().describe(\"The ephemeral call frequency. It appears on no dial surface and is destroyed when the call ends.\"),\n channelId: z.string().describe(\"The single call channel. Every participant TX and RX exactly this.\"),\n audioMode: z.literal(\"open_mic\").describe(\"Full duplex. Not push-to-talk, and not gated by the console's talk mode.\"),\n});\n\n/**\n * One participant in a call.\n *\n * ⚠️ **`user` is a `UserSummary`, so it carries no display name** — the owner rule that a\n * name is a billing field applies here exactly as it does to a frequency roster. Render\n * `handle`, falling back to `stationId`.\n *\n * `kind: \"external\"` is reserved for a future DID/VOIP gateway and cannot occur today. A\n * client must still tolerate it rather than assuming every participant resolves to one of\n * its own contacts: in a group call, somebody else's contact can be in the room with you.\n */\nexport const CallParticipantSchema = z.object({\n user: UserSummarySchema,\n kind: CallParticipantKindSchema,\n state: CallParticipantStateSchema,\n isHost: z.boolean().describe(\"The participant who placed the call. Only the host may move the call to a frequency.\"),\n});\n\n/**\n * The result of PLACING a call — the caller's half of `CallAcceptedSchema`, and\n * deliberately the same shape.\n *\n * The caller is handed the frequency at ring and is expected to tune it\n * immediately, so the container is up and their producer is live before anybody\n * answers. It used to be withheld until `call.accepted`, to avoid provisioning a\n * container for a call that might never be answered — that cost is now paid on\n * purpose, because it was otherwise paid on the ANSWER, where the user is\n * waiting.\n *\n * ⚠️ **This is not a ring acknowledgement and must not be rendered as one.** The\n * frequency is minted before the callee is consulted at all — a call that is\n * being masked (blocked, or busy-and-invisible) returns exactly this, ring and\n * all, and simply never reaches them. A caller still sees \"calling…\" until\n * `call.accepted`, `call.ended`, or `expiresAt`, and nothing else is coming.\n */\nexport const CallPlacedSchema = z.object({\n callId: z.string(),\n frequencyId: z.string().describe(\"The ephemeral call frequency. Tune it now — do not wait for an answer.\"),\n channelId: z.string().describe(\"The single call channel. Every participant TX and RX exactly this.\"),\n audioMode: z.literal(\"open_mic\").describe(\"Full duplex. Not push-to-talk, and not gated by the console's talk mode.\"),\n expiresAt: z.iso.datetime().describe(\"When an unanswered ring times out. The only latency an unanswered call ever shows.\"),\n /**\n * ⚠️ Everyone named here reads `ringing`, INCLUDING anybody whose ring is being masked.\n * That is not a cosmetic choice — a participant who showed any other state would rebuild\n * the oracle the mask exists to close, in a field rather than in a timing difference.\n */\n participants: CallParticipantSchema.array().describe(\"Everybody invited, the caller included. All invitees read `ringing` whether or not their ring was actually delivered.\"),\n /**\n * What the CALLER should hear while they wait, and nothing more.\n *\n * ⚠️ **Derived over UNMASKED invitees only, and `normal` when there are none.** A masked\n * invitee must not move this by a hair: somebody who has muted this caller is online and\n * may well be mid-conversation, and a `waiting` tone would announce both facts to the one\n * person they chose not to hear from. With every invitee masked the call rings out in\n * silence and this reads `normal`, which is exactly what an idle, un-muted callee gives.\n *\n * ⚠️ **`waiting` needs EVERY unmasked invitee to be on another call.** In a group, one\n * free person means the call can be answered right now, so the ordinary ringback is the\n * honest sound.\n *\n * This is a deliberate, owner-ruled disclosure (2026-09-21) and the contract's\n * \"accepted, by design\" list carries it: a caller learns that a visible contact is\n * mid-call, which their contact list does not show. The platform already said as much in\n * the over-limit `CALL_BUSY` message; this makes it the normal case rather than an edge.\n */\n ringback: z\n .enum([\"normal\", \"waiting\"])\n .describe(\"The tone to play while dialling. `waiting` means every invitee who was actually rung is already on another call. Never a statement about a masked invitee.\"),\n});\n\n/**\n * What a call WAS, from one person's side — the phone's Recents.\n *\n * ⚠️ **`outcome` describes the READER, not the call**, and the two genuinely differ: the\n * same conversation is `no_answer` to the person who placed it and `missed` to the person\n * who never picked up. A client rendering a single \"call outcome\" for everybody will be\n * wrong for somebody in every group call.\n *\n * - `answered` — they were in it. `answeredAt` is set, and with `endedAt` gives the\n * duration, which is per person: somebody rung into a conference half way through was not\n * on it for the whole thing.\n * - `missed` — they were rung and never picked up.\n * - `declined` — they refused it.\n * - `no_answer` — they placed it and nobody picked up. The caller's spelling of `missed`;\n * nobody rang THEM, so `missed` would be a different claim.\n *\n * ⚠️ **A call the reader was never told about has no entry**, because there is nothing to\n * tell them. Somebody who blocked you, muted you, or was invisible when you rang gets no\n * row for that call and is not named as a peer in anybody else's — the same rule that\n * removes the ring acknowledgement, applied after the fact.\n *\n * `peers` is everybody else who was on it. It may be SHORTER than it once was: an erased\n * account leaves nothing to resolve, which is erasure by reference and is deliberate.\n */\nexport const CallLogEntrySchema = z.object({\n id: z.string(),\n callId: z.string().describe(\"The call it describes. The room itself is long gone — a call frequency is destroyed when the call ends.\"),\n direction: z.enum([\"outgoing\", \"incoming\"]),\n outcome: z.enum([\"answered\", \"missed\", \"declined\", \"no_answer\"]).describe(\"From the READER's side. See the schema note.\"),\n peers: UserSummarySchema.array().describe(\"Everybody else who was on it, as far as they still exist.\"),\n startedAt: z.iso.datetime().describe(\"When the call was placed. The same instant for everybody on it.\"),\n answeredAt: z.iso.datetime().nullable().describe(\"When the READER joined, or null if they never did.\"),\n endedAt: z.iso.datetime().describe(\"When the reader's own involvement ended.\"),\n});\n\n/**\n * The state of a call, as one participant sees it.\n *\n * ⚠️ **`participants` replaced a scalar `peer`, and that is the whole shape of Phase 3.**\n * A 1:1 call is the two-entry case; there is no separate two-party representation to keep\n * in step. The reader is always IN this list — match on your own user id rather than\n * assuming a position, because the host is not necessarily first and `left` participants\n * are retained for the life of the call so a client can say who dropped out.\n */\nexport const CallStateSchema = z.object({\n callId: z.string(),\n state: z.enum([\"ringing\", \"active\", \"ended\"]),\n participants: CallParticipantSchema.array().describe(\"Everybody who has been invited, including the reader and anybody who has since left.\"),\n role: z.enum([\"host\", \"guest\"]).describe(\"The reader's own role. `caller`/`callee` are gone: in a call of five they name nothing.\"),\n frequencyId: z.string().nullable().describe(\"The ephemeral call frequency, carried in every state to every participant. Null only on a call that has ended.\"),\n channelId: z.string().nullable(),\n expiresAt: z.iso.datetime().nullable().describe(\"When the reader's own unanswered ring times out. Null once they have answered.\"),\n endReason: CallEndReasonSchema.nullable(),\n});\n\n/**\n * Somewhere a call can be handed off to — one CHANNEL, named with its frequency.\n *\n * ⚠️ **A flat list of channels, not frequencies, because the operator is choosing a\n * channel.** The owner's rule for what appears here: *\"a list of channels they all have in\n * common among all their frequencies\"*, or somewhere the mover can grant everybody into.\n * Anything else is simply ABSENT rather than returned with a reason — a destination that\n * would strand somebody is not offered.\n *\n * ⚠️ **This is a picker's data, never an authorization.** `POST /calls/:callId/move`\n * re-derives every one of these decisions from the same function, because a client can\n * post whatever it likes and because this answer can be seconds stale by the time somebody\n * presses the button.\n */\nexport const CallMoveDestinationSchema = z.object({\n frequencyId: z.string(),\n frequencyName: z.string(),\n frequencyLabel: z.string().describe(\"Mode-aware display label. Render verbatim, same rule as FrequencySchema.label.\"),\n channelId: z.string(),\n channelName: z.string(),\n talkPermission: TalkPermissionSchema,\n isDefault: z\n .boolean()\n .describe(\n 'The auto-created \"Public\" channel. Worth surfacing: arrivals granted access land there able to LISTEN and not to talk, because its roster follows frequency membership and cannot be edited directly.',\n ),\n access: z\n .enum([\"all_present\", \"grant_required\"])\n .describe(\n \"`all_present` — everybody on the call can already reach this channel, and the move grants nothing. `grant_required` — some cannot, and moving here will make them permanent members of the frequency. Say which, before the button is pressed.\",\n ),\n grantUserIds: z\n .array(z.string())\n .describe(\"Who a move here would grant access to. Empty when `access` is `all_present`.\"),\n skippedUserIds: z\n .array(z.string())\n .describe(\n \"Participants who cannot be brought and will stay behind. A banned participant lands here rather than refusing the whole move, because refusing on their behalf would leak their ban to the host by elimination.\",\n ),\n});\n\nexport const CallMoveDestinationsSchema = z.object({\n participantUserIds: z\n .array(z.string())\n .describe(\n \"The participants eligibility was computed over: everybody who has JOINED and is not masked. Somebody still ringing is excluded, because they never answered.\",\n ),\n destinations: CallMoveDestinationSchema.array(),\n});\n","import { z } from \"zod\";\nimport { validateCompanyContact, type CompanyContactLike } from \"./companyContact.js\";\nimport { isCleanText, PROFANITY_MESSAGE } from \"./profanity.js\";\n\n// A public-facing free-text name (frequency/station/org/channel/group name, display name,\n// tagline): length-bounded AND profanity-screened. Screening is enforced here so it applies\n// on every write path server-side; the client re-uses containsProfanity for inline feedback.\nconst publicName = (min: number, max: number) =>\n z.string().min(min).max(max).refine(isCleanText, PROFANITY_MESSAGE);\n\n/* Request body schemas shared between the control-plane route handlers\n * (server-side validation) and the client's typed API wrapper. */\n\n// Adds the shared field validation (control-char rejection, per-country postal, E.164 phone,\n// email, length) as zod issues so the SERVER enforces exactly what the client checks — the\n// route handler's ZodError→400 mapping turns any violation into a rejected request.\nfunction refineCompanyContact(value: CompanyContactLike, ctx: z.RefinementCtx, partial: boolean): void {\n for (const [field, message] of Object.entries(validateCompanyContact(value, { partial }))) {\n ctx.addIssue({ code: \"custom\", path: [field], message });\n }\n}\n\n/**\n * The one definition of what a callsign may look like.\n *\n * A user's `handle`, a station's `stationCallsign` and every rename path all compose these\n * — a callsign refused at signup must be refused on rename, and \"two checks that agree\n * today\" is how they stop agreeing. Case-insensitive by design (`/i`): a callsign is\n * self-expression and its case belongs to the user (owner ruling 2026-08-21), so it is\n * stored verbatim and no surface may re-case one for display.\n *\n * The pattern admits 2-16 characters, not 3-16 — the message said 3 for a long time and\n * the message was the typo. `A1` has always been accepted.\n */\nexport const CALLSIGN_PATTERN = /^[A-Z0-9][A-Z0-9-]{1,15}$/i;\nexport const CALLSIGN_GRAMMAR_MESSAGE = \"2-16 chars, letters/numbers/hyphen\";\n\n/** Charset and length only. Kept separate from HandleSchema so a route that wants to\n * answer \"that is not allowed language\" with its OWN error code can run the profanity\n * predicate itself instead of having it collapse into VALIDATION_ERROR. */\nexport const CallsignGrammarSchema = z.string().regex(CALLSIGN_PATTERN, CALLSIGN_GRAMMAR_MESSAGE);\n\n/** Grammar + the profanity screen — the full predicate for a user callsign. */\nexport const HandleSchema = CallsignGrammarSchema.refine(isCleanText, PROFANITY_MESSAGE);\n\n/** A user's display name — the same length-bounded, profanity-screened rule every\n * public-facing free-text name gets. Exported so routes that declare their body inline\n * (the hosted OAuth signup) can compose it instead of settling for a bare `z.string()`. */\nexport const PublicDisplayNameSchema = publicName(1, 64);\n\n// Station callsign reuses the handle charset rules. Unlike handle, globally unique\n// (2026-07-20). Lives on the STATION, i.e. the broadcast frequency itself since 2026-08-02\n// — see Frequency.stationCallsign in schema.prisma, not the owning company.\n//\n// Spelled out rather than aliased to HandleSchema even though the rules are identical: the\n// OpenAPI component registry is keyed by schema INSTANCE and resolves an alias to a single\n// shortest name, so `= HandleSchema` silently renamed the published `StationCallsignInput`\n// component to `HandleInput` — and the Tuner generates its C# DTOs from that artifact, so a\n// renamed component renames a type in someone else's codebase. Two names for one rule is\n// the point; they share the pattern and the predicate, not the identity.\nexport const StationCallsignSchema = CallsignGrammarSchema.refine(isCleanText, PROFANITY_MESSAGE);\n\nexport const RequestCodeBodySchema = z.object({\n email: z.email(),\n});\nexport type RequestCodeBody = z.infer<typeof RequestCodeBodySchema>;\n\nexport const VerifyCodeBodySchema = z.object({\n email: z.email(),\n code: z.string().length(6),\n deviceId: z.string().min(1),\n // Which registered app is signing in (Phase 2). Optional for compatibility - omitted\n // means \"frequency-web\". Determines the scopes minted into the access token and which\n // app the session is listed under in GET /auth/sessions.\n clientId: z.string().min(1).max(64).optional(),\n // Provided on first-ever login for this email (SIGNUP_REQUIRED, talk apps only —\n // listen-only apps create the account from the email alone), and on the\n // CALLSIGN_REQUIRED retry when a talk app signs in to an account that has no callsign\n // yet. Ignored whenever the account already has one.\n handle: HandleSchema.optional(),\n displayName: publicName(1, 64).optional(),\n // Answer to a 409 SESSION_CONFLICT: \"yes, close the session I already have in this app\n // and sign me in here.\" Only broadcast operators ever see that rejection — everyone\n // else's older session is closed silently — so this flag is the operator's explicit\n // consent to interrupt whatever the other install is doing, possibly a live show.\n signOutOtherSessions: z.boolean().optional(),\n});\nexport type VerifyCodeBody = z.infer<typeof VerifyCodeBodySchema>;\n\nexport const UpdateWebAuthnCredentialBodySchema = z.object({\n // null clears the nickname; the field is required so an empty body can't silently no-op.\n nickname: z.string().trim().min(1).max(64).nullable(),\n});\nexport type UpdateWebAuthnCredentialBody = z.infer<typeof UpdateWebAuthnCredentialBodySchema>;\n\nexport const RefreshTokenBodySchema = z.object({\n refreshToken: z.string().min(1),\n deviceId: z.string().min(1),\n});\nexport type RefreshTokenBody = z.infer<typeof RefreshTokenBodySchema>;\n\n// Confirms DELETE /users/me (capability `account-deletion`). `code` is the six-digit\n// deletion code from POST /users/me/deletion-code — a login code is NOT accepted (codes\n// carry a purpose server-side). Deliberately carries NO billing field: the deletion flow\n// never cancels a subscription as a side effect (owner policy 2026-08-07) — a live\n// subscription answers 409 ACTIVE_SUBSCRIPTION and the user cancels through the normal\n// billing path first. See docs/user-data-deletion.md for the whole flow.\n/**\n * Body of DELETE /users/me. **Exactly one** confirmation factor, never both and never\n * neither — a caller that sends both is confused about which one it is relying on, and\n * silently preferring one would hide that.\n *\n * Two factors rather than one because the emailed code is proof of MAILBOX control while a\n * passkey is proof of AUTHENTICATOR possession plus user verification, and an account can\n * legitimately be in a state where only one is available: a listener who never enrolled a\n * passkey has only the code, and someone who has lost access to the mailbox they signed up\n * with has only the passkey. Both prove what this route actually needs, which is freshness —\n * that the human at the keyboard right now authorised this, not that a session persisted.\n *\n * Modelled as two optional fields rather than a discriminated union deliberately: it\n * generates ONE class in the peers' typed clients instead of two plus a wrapper, and the\n * Tuner's C# DTOs come off this artifact.\n */\nexport const DeleteAccountBodySchema = z\n .object({\n code: z\n .string()\n .length(6)\n .optional()\n .describe(\"The six-digit code emailed by POST /users/me/deletion-code. Mutually exclusive with `assertion`.\"),\n // Opaque on purpose: this is the browser's AuthenticationResponseJSON, whose shape is\n // owned by the WebAuthn spec and @simplewebauthn, not by us. Re-modelling it in zod\n // would mean tracking a spec we do not control, and every field is passed straight to\n // the verifier anyway.\n assertion: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n \"The WebAuthn `AuthenticationResponseJSON` for the challenge from POST /users/me/deletion-challenge \" +\n \"(capability `account-deletion-passkey`). Mutually exclusive with `code`. Survives a 409 blocker for \" +\n \"resubmission, like `code`, for the 5-minute life of the challenge.\",\n ),\n })\n .refine((body) => Boolean(body.code) !== Boolean(body.assertion), {\n message: \"Send exactly one of `code` or `assertion`.\",\n });\nexport type DeleteAccountBody = z.infer<typeof DeleteAccountBodySchema>;\n\n/**\n * An avatar id: the short, opaque token a user carries to name their chosen picture.\n *\n * The grammar is Switchboard's proposal, adopted unchanged, and it is deliberately NOT an\n * enum in the schema — the vocabulary is DATA (the `avatar_assets` table, curated from the\n * admin console), so a new emblem is an operator action rather than a platform deploy. What\n * the schema cannot do, the route does: `PATCH /users/me` looks the id up in the live\n * catalog and refuses one that is unknown or retired (400 UNKNOWN_AVATAR). A typed id that\n * silently persists as a placeholder forever is the failure that check exists to stop.\n *\n * Opaque so the shape survives a later user-upload phase without a migration — an uploaded\n * avatar would be `up-<hash>`, which fits this grammar (note `img:<version>`, sketched in\n * Switchboard's design note, does NOT: `:` is not in the character class).\n */\nexport const AVATAR_ID_REGEX = /^[a-z0-9][a-z0-9-]{0,31}$/;\nexport const AvatarIdSchema = z\n .string()\n .regex(AVATAR_ID_REGEX)\n .describe(\"Avatar id from GET /avatars. Opaque — draw the placeholder for one you do not recognise.\");\n\nexport const UpdateProfileBodySchema = z.object({\n displayName: publicName(1, 64).optional(),\n avatarColor: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),\n /**\n * The chosen avatar, or `null` to clear it back to the `avatarColor` placeholder.\n * Absent = leave unchanged; `null` is an explicit clear and is never refused, even when\n * the catalog is empty. Capability `user-avatar`.\n */\n avatar: AvatarIdSchema.nullish(),\n});\nexport type UpdateProfileBody = z.infer<typeof UpdateProfileBodySchema>;\n\n/**\n * Operator upload of one library avatar (admin console → control plane `/internal/avatars`).\n *\n * Base64 JSON on the `UploadStationLogoBodySchema` precedent below: every route in this API\n * is JSON. The SOURCE budget is generous on purpose: there is no client-side resize, because\n * the control plane owns `sharp` and the admin SPA does not, so an operator drops a master\n * and the server derives both renditions.\n *\n * ⚠️ A budget in bytes is only real if the TRANSPORT lets it through, and this one did not.\n * Base64 inflates by 4/3, so an upload near this budget is a ~2.7 MB request body — and\n * Fastify's default `bodyLimit` is 1 MiB, which rejects it with a bare 413 before any\n * handler, schema or size check runs. This comment used to assert that the internal write\n * path raised that default; no code anywhere did, in either plane, so the effective limit\n * was ~750 KB from the feature shipping (0.48.0) until it was measured and fixed. Both write\n * routes in both planes now set `bodyLimit: AVATAR_UPLOAD_BODY_LIMIT_BYTES` below.\n *\n * The reason no test caught it is worth keeping: every avatar test built its artwork from a\n * flat colour, which PNG compresses to a few hundred bytes, so the suite passed at ANY body\n * limit. A byte budget can only be tested with incompressible bytes.\n */\nexport const AVATAR_SOURCE_MAX_BYTES = 2 * 1024 * 1024;\n\n/**\n * Fastify `bodyLimit` for the four avatar write routes (POST + PATCH, control plane and\n * admin plane).\n *\n * DERIVED, never written as a number: the two constants have to move together, and the\n * failure mode when they drift is silent — the transport rejects a legal upload and the\n * budget above quietly means something smaller than it says.\n *\n * Set clear of the encoded maximum rather than flush against it, on purpose. The rule is\n * `AVATAR_SOURCE_MAX_BYTES`, enforced in the handlers, where the refusal names the limit and\n * tells the operator to resize. A body limit sized exactly to the budget would hand every\n * over-budget upload to the transport instead, which answers 413 \"Request body is too large\"\n * — true, but it names neither the limit nor the remedy. So the headroom exists to keep the\n * GOOD message reachable; this limit is a backstop against buffering something absurd, not\n * the rule.\n */\nexport const AVATAR_UPLOAD_BODY_LIMIT_BYTES = 2 * (Math.ceil(AVATAR_SOURCE_MAX_BYTES / 3) * 4 + 4 * 1024);\n/** Edge of the canonical (`lg`) PNG rendition the server derives. */\nexport const AVATAR_RENDITION_PX = 512;\n/** Edge of the small (`sm`) rendition — picker tiles and roster rows. */\nexport const AVATAR_RENDITION_SMALL_PX = 96;\n/** Edge of the medium (`md`) rendition: a picker tile that is sharp at 150% scaling, at a\n * quarter of `lg`'s bytes (card 0a6cb1b3). */\nexport const AVATAR_RENDITION_MEDIUM_PX = 192;\n\n/**\n * Body of POST /users/me/callsign (capability `callsign-rename`).\n *\n * `handle` deliberately carries GRAMMAR ONLY here. The profanity screen still runs — the\n * route calls the same `isCleanText` predicate `HandleSchema` does — but it runs in the\n * handler so that \"we don't allow that language\" arrives as its own error code rather than\n * as one more VALIDATION_ERROR a client cannot tell from \"too long\". Clients branch on\n * `code`, so three refusals that mean different things need three codes: VALIDATION_ERROR,\n * PROFANE_CALLSIGN, CALLSIGN_RENAME_COOLDOWN.\n *\n * A separate route rather than a widened PATCH /users/me: a rename needs a cooldown check,\n * a realtime announcement and a token-staleness story, and the profile PATCH handler passes\n * its validated body straight to Prisma with no seam for any of them.\n */\nexport const RenameCallsignBodySchema = z.object({\n handle: CallsignGrammarSchema,\n});\nexport type RenameCallsignBody = z.infer<typeof RenameCallsignBodySchema>;\n\n// The owning COMPANY's details, captured when a new company is created (see Organization\n// in prisma/schema.prisma). `companyName` lands on Organization.name — the company IS its\n// name, and a station's own name/callsign live on the broadcast frequency. Kept under the\n// `companyName` wire key so the client form and subscribe.html don't churn.\n// country is ISO 3166-1 alpha-2 (Stripe's format). Optional on the wire where a caller may\n// instead attach to an existing company by id (see resolveCompany.ts); reused across\n// frequency-create, org-create, and the billing upgrade.\nexport const CompanyContactSchema = z\n .object({\n companyName: z.string().min(1).max(128),\n addressLine1: z.string().min(1).max(200),\n addressLine2: z.string().max(200).optional(),\n city: z.string().min(1).max(120),\n // region/postalCode are optional on the wire — not every country uses them (see\n // COUNTRY_METADATA in countries.ts). The superRefine below enforces per-country\n // requiredness + postal FORMAT; the server also enforces country ALLOWLIST membership\n // (assertCountrySupported), which z can't express.\n region: z.string().max(120).optional(),\n postalCode: z.string().max(32).optional(),\n country: z.string().length(2),\n phone: z.string().min(1).max(40),\n contactEmail: z.email().max(200),\n })\n // Full field validation (control chars, per-country postal, E.164 phone, region option,\n // required-ness) — the server's real gate against malformed/injection-y PII.\n .superRefine((value, ctx) => refineCompanyContact(value, ctx, false));\nexport type CompanyContact = z.infer<typeof CompanyContactSchema>;\n\nexport const CreateFrequencyBodySchema = z.object({\n name: publicName(1, 64),\n description: z.string().max(500).optional(),\n vanityKhz: z.number().int().positive().optional(),\n // PUSH-TO-TALK ONLY. A broadcast station's listing is derived from whether it has an\n // access code (being on the broadcast dial IS the listing), so sending this with\n // mode \"broadcast\" is a 422 rather than a silently ignored field.\n publiclyListable: z.boolean().optional(),\n autoApprovePublicJoin: z.boolean().optional(),\n mode: z.enum([\"push_to_talk\", \"broadcast\"]).optional(),\n // The COMPANY that will own this station: one of the caller's own companies, by id.\n // Membership is verified against the caller (manager+) — there is deliberately no\n // attach-by-company-name path anywhere, since a typed name would let anyone probe for,\n // or graft a station onto, someone else's company (2026-08-02). Mutually exclusive with\n // companyContact; exactly one is required for mode \"broadcast\". See resolveCompany.ts.\n organizationId: z.uuid().optional(),\n // On-air callsign for this station. Required for mode \"broadcast\" — it is a column on\n // the frequency itself (2026-08-02), so every broadcast frequency carries its own.\n // The station's NAME is this frequency's `name` above (2026-07-21).\n stationCallsign: StationCallsignSchema.optional(),\n // Details of a NEW company to create and own this station. Mutually exclusive with\n // organizationId (enforced in resolveCompany.ts). If the name+contactEmail match a\n // company the caller already manages (case-insensitive), that company is REUSED instead\n // of a duplicate being minted (2026-08-10) — still membership-scoped, not attach-by-name.\n companyContact: CompanyContactSchema.optional(),\n // Presence of a code makes the frequency private — see Frequency.hasAccessCode.\n accessCode: z.string().min(4).max(64).optional(),\n // Attestation that the account holder is 18+ / the age of majority (Terms §1). Must be\n // true — enforced in the handler (422 AGE_ATTESTATION_REQUIRED, not a schema literal, so\n // pre-attestation clients get a catalogued, branchable error instead of an opaque 400).\n // Servers advertising the \"age-attestation\" capability enforce and durably record it.\n ageConfirmed: z.boolean().optional(),\n // Acceptance of the Terms of Service as a whole. **Must be true** since 0.35.0 — enforced in\n // the handler (422 TERMS_ACCEPTANCE_REQUIRED), not as a schema literal, for exactly the reason\n // ageConfirmed is: a client that omits it gets a catalogued, branchable error rather than an\n // opaque 400. Recorded as its own acceptance row. The in-app and site clickwraps are ONE\n // combined checkbox covering age + Terms, so both fields always arrive together.\n termsAccepted: z.boolean().optional(),\n});\nexport type CreateFrequencyBody = z.infer<typeof CreateFrequencyBodySchema>;\n\nexport const TuneByNumberBodySchema = z.object({\n khz: z.number().int().positive(),\n accessCode: z.string().optional(),\n});\nexport type TuneByNumberBody = z.infer<typeof TuneByNumberBodySchema>;\n\n// transmitIntent is what actually provisions a media-node container (see\n// POST /frequencies/:id/tune) — plain listening never does. Optional/defaulted false so\n// listen-only tuning is the ordinary, unmarked case.\n//\n// It means \"this caller is about to produce audio\", NOT \"keep my session alive\". Sending it\n// unconditionally on a repeating poll is expensive: containers are reaped on TRANSMIT\n// idleness, so each poll rebuilds a container the sweeper then reaps, forever. A Switchboard\n// seat doing exactly this drove 43 container recreations in 85 minutes on alpha (2026-08-03).\nexport const TuneBodySchema = z.object({\n transmitIntent: z.boolean().optional().default(false),\n // ONE LOCATION PER FREQUENCY (capability `one-location-per-frequency`). Both flags matter\n // only to apps covered by the rule (the consoles); a Tuner's tune ignores them.\n //\n // `resume: true` says \"this is an automatic reconnect of a connection this install already\n // had, not a new tune-in\". A resume never takes the frequency from another install: if the\n // account has since tuned in somewhere else, it answers 409 FREQUENCY_OPENED_ELSEWHERE and\n // the client drops the frequency locally. Without it, a laptop waking from sleep would\n // re-tune on its reconnect ladder and take the frequency back from the desk the user moved\n // to. Absent = a deliberate tune-in, which takes the frequency and displaces the others.\n resume: z.boolean().optional(),\n // `takeOver: true` answers the 409 BROADCAST_ELSEWHERE question with \"yes, take the\n // station off the air on my other device\".\n takeOver: z.boolean().optional(),\n // SCREEN SHARE (capability `share-container`, 2026-09-28): \"this caller is about to share\".\n // Provisions the frequency's SHARE container (a separate container from the voice one,\n // placed on a video host) exactly as transmitIntent provisions the voice one, and with the\n // same warning: it means about to share, never keep-alive, because a share container is\n // reaped once nothing is being shared. Viewers never send it; a running share container is\n // described in every member's tune result regardless.\n shareIntent: z.boolean().optional(),\n});\nexport type TuneBody = z.infer<typeof TuneBodySchema>;\n\nexport const UpdateFrequencyBodySchema = z.object({\n name: publicName(1, 64).optional(),\n description: z.string().max(500).nullable().optional(),\n // Re-number (2026-07-20, open dial space). Integer kHz — the client canonicalizes\n // the typed label via parseDialLabel; the route re-validates against the EFFECTIVE\n // mode (broadcast: isValidDialKhz; push_to_talk: isValidHamKhz). A simultaneous\n // {mode, khz} patch is the supported broadcast→PTT path.\n khz: z.number().int().positive().optional(),\n // PUSH-TO-TALK ONLY — see CreateFrequencyBodySchema. To keep a broadcast station off\n // the public dial, give it an access code (PATCH /frequencies/:id/access-code).\n publiclyListable: z.boolean().optional(),\n autoApprovePublicJoin: z.boolean().optional(),\n mode: z.enum([\"push_to_talk\", \"broadcast\"]).optional(),\n // Setting requires manager+ on the target company; clearing (null) requires manager+ on\n // the current one. The effective mode must never be \"broadcast\" with no company.\n organizationId: z.uuid().nullable().optional(),\n // On switch to \"broadcast\", the frequency BECOMES a station: these supply its on-air\n // callsign and, when no organizationId is given, the new company to own it. Branding and\n // the rest of the station's identity are edited through PATCH /frequencies/:id/station,\n // which sits behind a different authorization bar (company manager+, not frequency admin)\n // and is why it is a separate route. See CreateFrequencyBodySchema and resolveCompany.ts.\n stationCallsign: StationCallsignSchema.optional(),\n companyContact: CompanyContactSchema.optional(),\n});\nexport type UpdateFrequencyBody = z.infer<typeof UpdateFrequencyBodySchema>;\n\n// A frequency's private-join secret is a reusable shared code (like a WiFi password),\n// stored reversibly (AES-256-GCM, lib/secretBox.ts) so owners/admins can reveal/edit it —\n// see GET/PATCH /frequencies/:id/access-code. null clears it (frequency becomes public).\nexport const SetAccessCodeBodySchema = z.object({\n accessCode: z.string().min(4).max(64).nullable(),\n});\nexport type SetAccessCodeBody = z.infer<typeof SetAccessCodeBodySchema>;\n\nexport const InviteMemberBodySchema = z.object({\n handleOrEmail: z.string().min(1),\n});\nexport type InviteMemberBody = z.infer<typeof InviteMemberBodySchema>;\n\nexport const ChangeRoleBodySchema = z.object({\n role: z.enum([\"admin\", \"user\"]),\n});\nexport type ChangeRoleBody = z.infer<typeof ChangeRoleBodySchema>;\n\n// Favorites are numbered radio-preset BUTTONS, sparse by design: slot 3 can be set while\n// 1–2 are empty, and the same frequency may sit on two slots, as on a physical radio.\n// Slots 1..MAX_FAVORITE_SLOT — sized well past Tuner's six physical buttons so a\n// list-shaped client (the phone) has headroom without the row count being unbounded.\nexport const MAX_FAVORITE_SLOT = 24;\nexport const FavoriteSlotSchema = z.number().int().min(1).max(MAX_FAVORITE_SLOT);\n\nexport const SetFavoriteBodySchema = z.object({\n frequencyId: z.string().min(1),\n});\nexport type SetFavoriteBody = z.infer<typeof SetFavoriteBodySchema>;\n\nexport const BanMemberBodySchema = z.object({\n userId: z.string().min(1),\n /** Admin-facing note shown in the ban list; never delivered to the banned user. */\n reason: z.string().max(200).optional(),\n});\nexport type BanMemberBody = z.infer<typeof BanMemberBodySchema>;\n\nexport const CreateChannelBodySchema = z.object({\n name: publicName(1, 64),\n talkPermission: z.enum([\"open\", \"managed\", \"broadcast_open\"]).default(\"open\"),\n // Initial roster; the creating admin/owner is always included regardless of whether\n // they list themselves (see channels/routes.ts).\n memberUserIds: z.array(z.string()).optional().default([]),\n});\nexport type CreateChannelBody = z.infer<typeof CreateChannelBodySchema>;\n\nexport const UpdateChannelBodySchema = z.object({\n name: publicName(1, 64).optional(),\n talkPermission: z.enum([\"open\", \"managed\", \"broadcast_open\"]).optional(),\n});\nexport type UpdateChannelBody = z.infer<typeof UpdateChannelBodySchema>;\n\n// CHANNEL Now-Playing tag: short, OPTIONAL free-text a DJ sets on a broadcast frequency's\n// Public channel. Distinct from the org-level UpdateNowPlayingBodySchema below (station\n// ticker with text/track/artist); this is a single tag on the channel itself. Security\n// validation, enforced server-side (any violation → 400): length-capped, control\n// characters rejected, and profanity-screened like every other public free-text field.\n// Empty string is allowed and clears the tag (the field is not required).\nexport const NOW_PLAYING_TAG_MAX = 120;\nexport const UpdateChannelNowPlayingBodySchema = z.object({\n nowPlayingTag: z\n .string()\n .max(NOW_PLAYING_TAG_MAX)\n // eslint-disable-next-line no-control-regex\n .refine((v) => !/[\\u0000-\\u001F\\u007F]/.test(v), \"Control characters are not allowed.\")\n .refine(isCleanText, PROFANITY_MESSAGE),\n});\nexport type UpdateChannelNowPlayingBody = z.infer<typeof UpdateChannelNowPlayingBodySchema>;\n\nexport const ForceMuteBodySchema = z.object({\n userId: z.string(),\n muted: z.boolean(),\n});\nexport type ForceMuteBody = z.infer<typeof ForceMuteBodySchema>;\n\n/** The frequency-wide admin mute (capability member-force-mute): every channel of the\n * frequency the member could talk on, in one call. */\nexport const MemberForceMuteBodySchema = z.object({\n muted: z.boolean(),\n});\nexport type MemberForceMuteBody = z.infer<typeof MemberForceMuteBodySchema>;\n\n// Bulk roster edit — lets a \"select all\" (or multi-select) action in the UI apply to a\n// channel with hundreds/thousands of members in one round trip instead of one request per user.\nexport const BulkChannelMembersBodySchema = z.object({\n userIds: z.array(z.string()).min(1).max(5000),\n});\nexport type BulkChannelMembersBody = z.infer<typeof BulkChannelMembersBodySchema>;\n\nexport const CreateGroupBodySchema = z.object({\n name: publicName(1, 64),\n memberUserIds: z.array(z.string()).optional().default([]),\n});\nexport type CreateGroupBody = z.infer<typeof CreateGroupBodySchema>;\n\nexport const UpdateGroupBodySchema = z.object({\n name: publicName(1, 64),\n});\nexport type UpdateGroupBody = z.infer<typeof UpdateGroupBodySchema>;\n\n// Same shape as BulkChannelMembersBodySchema, kept separate since it validates a\n// conceptually different roster (group membership vs. a channel's direct roster).\nexport const BulkGroupMembersBodySchema = z.object({\n userIds: z.array(z.string()).min(1).max(5000),\n});\nexport type BulkGroupMembersBody = z.infer<typeof BulkGroupMembersBodySchema>;\n\n// Talk-vs-listen designation for an already-added channel member or linked group — see\n// ChannelMembership.canTalk / ChannelGroup.canTalk in prisma/schema.prisma. Reused for\n// both PATCH .../members/:userId and PATCH .../groups/:groupId (identical shape).\nexport const SetTalkPermissionBodySchema = z.object({\n canTalk: z.boolean(),\n});\nexport type SetTalkPermissionBody = z.infer<typeof SetTalkPermissionBodySchema>;\n\n// Partial update — either field may be omitted so callers can update \"just active\" (on\n// activate/deactivate) or \"just the relay-channel selection\" (on toggling a channel)\n// without clobbering the other. See FrequencyTuningState in prisma/schema.prisma.\nexport const UpdateTuningStateBodySchema = z.object({\n active: z.boolean().optional(),\n selectedChannelIds: z.array(z.string()).optional(),\n selectedTransmitChannelIds: z.array(z.string()).optional(),\n});\nexport type UpdateTuningStateBody = z.infer<typeof UpdateTuningStateBodySchema>;\n\n/**\n * One side (listen or talk) of a change an owner or admin makes to ANOTHER member's tuning\n * state. A DELTA on purpose: the admin flips one cell of a grid, and a whole-state write would\n * clobber whatever the member toggled a moment earlier. Applied in the order removeAll,\n * remove, add, so \"replace everything with B\" and \"move from A to B\" are each one request.\n * `removeAll` exists so \"turn their mic off\" never depends on the caller's roster read being\n * current.\n */\nexport const TuningDeltaSchema = z.object({\n add: z.array(z.string()).max(200),\n remove: z.array(z.string()).max(200),\n removeAll: z.boolean(),\n});\nexport type TuningDelta = z.infer<typeof TuningDeltaSchema>;\n\nexport const SetMemberTuningBodySchema = z.object({\n listen: TuningDeltaSchema.describe(\"Channels the member listens to. Group channels of this frequency only.\"),\n talk: TuningDeltaSchema.describe(\n \"Channels the member talks on. `add` takes group channels only; `remove` may also name the member's own personal channel.\",\n ),\n grantAccess: z\n .boolean()\n .describe(\n \"What happens when the member lacks access to a channel being added. false: the request is refused whole with TUNING_ACCESS_REQUIRED. true: they are given the roster row first (talk for a talk add, listen-only for a listen add).\",\n ),\n});\nexport type SetMemberTuningBody = z.infer<typeof SetMemberTuningBodySchema>;\n\n// --- Stations (the broadcast frequency's own identity) ---\n\n/**\n * PATCH /frequencies/:id/station — everything that makes a broadcast frequency a station\n * apart from its name (which is the frequency's `name`, edited through PATCH\n * /frequencies/:id). Split out of the old UpdateOrgBodySchema on 2026-08-02, when station\n * identity moved off the company: a company owns many stations, and each needs its own\n * callsign, look and program metadata.\n *\n * Separate route from PATCH /frequencies/:id because the two answer to different\n * authorization bars — a frequency admin renames the station, but only a company manager+\n * changes its on-air identity.\n */\nexport const UpdateStationBodySchema = z.object({\n stationCallsign: StationCallsignSchema.optional(),\n brandColor: z.string().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional(),\n // Station branding (2026-07-20): short on-air slogan + outbound links. Profanity-screened.\n tagline: z.string().max(140).refine(isCleanText, PROFANITY_MESSAGE).nullable().optional(),\n websiteUrl: z.url().max(300).nullable().optional(),\n // Content classification (2026-07-22) — what the station plays, as opposed to\n // FrequencyMode, which is how audio is carried. Lets a directory categorise a dial.\n format: z.enum([\"talk\", \"music\", \"mixed\"]).nullable().optional(),\n genre: z.string().max(60).refine(isCleanText, PROFANITY_MESSAGE).nullable().optional(),\n links: z\n .array(z.object({ label: z.string().min(1).max(24), url: z.url().max(300) }))\n .max(5)\n .nullable()\n .optional(),\n});\nexport type UpdateStationBody = z.infer<typeof UpdateStationBodySchema>;\n\n/**\n * PUT /frequencies/:id/off-air-notice (capability `off-air-notice`, 0.116.0). One address,\n * or null to stop the notices. It is whatever the station enters: a person, a shared\n * mailbox, or the inbound address of a paging service, which is how a station gets paged\n * without the service sending anything but email.\n */\nexport const SetOffAirNoticeBodySchema = z.object({\n email: z.email().max(254).nullable(),\n});\nexport type SetOffAirNoticeBody = z.infer<typeof SetOffAirNoticeBodySchema>;\n\n/**\n * A listener's Cheer or Hush on what a station is playing (capability `cheer-hush`,\n * 0.118.0), or null to take it back. It names no song: the service counts it against\n * whatever is playing when it arrives, so a slow client cannot cheer the song that just ended.\n */\nexport const SetStationReactionBodySchema = z.object({\n reaction: z.enum([\"cheer\", \"hush\"]).nullable(),\n});\nexport type SetStationReactionBody = z.infer<typeof SetStationReactionBodySchema>;\n\n// Station logo upload: base64 JSON on a dedicated PUT (all routes are JSON; ≤300KB\n// decoded ≈ 400KB encoded, comfortably under Fastify's 1MiB default bodyLimit).\nexport const UploadStationLogoBodySchema = z.object({\n dataBase64: z.string().min(1),\n mime: z.enum([\"image/png\", \"image/jpeg\", \"image/webp\"]),\n});\nexport type UploadStationLogoBody = z.infer<typeof UploadStationLogoBodySchema>;\nexport const STATION_LOGO_MAX_BYTES = 300 * 1024;\n\n// --- Companies (organizations) ---\n\n// A company is created from its contact details alone — its `name` IS\n// companyContact.companyName (2026-08-02). Stations are created separately, as broadcast\n// frequencies, and attach to a company by id.\nexport const CreateOrgBodySchema = z.object({\n companyContact: CompanyContactSchema,\n});\nexport type CreateOrgBody = z.infer<typeof CreateOrgBodySchema>;\n\n// Company details only — a station's name, callsign, branding and program metadata are\n// edited through the frequency that IS that station (UpdateStationBodySchema above).\n// NOTE for older clients: zod strips unknown keys, so a pre-2026-08-02 client sending\n// branding here gets a silent no-op rather than an error. Called out in the release notes.\nexport const UpdateOrgBodySchema = z.object({\n // Company contact — editable later in company settings (each field nullable so an owner\n // can clear one). Changing any of these re-syncs the Stripe Customer (billing/accounts.ts).\n // `companyName` writes Organization.name: one field, same wire key as CompanyContactSchema,\n // so the shared contact form patches exactly the object it collected. Not nullable — a\n // company always has a name — unlike the rest, which may be cleared.\n companyName: z.string().min(1).max(128).optional(),\n addressLine1: z.string().min(1).max(200).nullable().optional(),\n addressLine2: z.string().max(200).nullable().optional(),\n city: z.string().min(1).max(120).nullable().optional(),\n // region/postalCode: not all countries use them (see COUNTRY_METADATA) — allow empty/null.\n region: z.string().max(120).nullable().optional(),\n postalCode: z.string().max(32).nullable().optional(),\n country: z.string().length(2).nullable().optional(),\n phone: z.string().min(1).max(40).nullable().optional(),\n contactEmail: z.email().max(200).nullable().optional(),\n})\n // Partial validation: any contact field PRESENT in the patch is format-checked (control\n // chars, per-country postal, E.164 phone, region option) — the edit path is held to the\n // same security bar as create, just without the required-ness checks.\n .superRefine((value, ctx) => refineCompanyContact(value, ctx, true));\nexport type UpdateOrgBody = z.infer<typeof UpdateOrgBodySchema>;\n\n/**\n * Now-playing / program metadata (2026-07-22), pushed to ONE station:\n * PATCH /frequencies/:id/now-playing. Separate from UpdateStationBodySchema on purpose:\n * this is high-frequency, low-privilege data a DJ or an automation system pushes every few\n * minutes, whereas station branding is rare and manager+ only. Every field is nullable so\n * a station can clear the ticker when it goes off-air.\n */\nexport const UpdateNowPlayingBodySchema = z.object({\n text: z.string().max(200).refine(isCleanText, PROFANITY_MESSAGE).nullable().optional(),\n trackTitle: z.string().max(200).refine(isCleanText, PROFANITY_MESSAGE).nullable().optional(),\n trackArtist: z.string().max(200).refine(isCleanText, PROFANITY_MESSAGE).nullable().optional(),\n});\nexport type UpdateNowPlayingBody = z.infer<typeof UpdateNowPlayingBodySchema>;\n\n// Same widened semantics as InviteMemberBodySchema: email, Station ID, or unambiguous handle.\nexport const AddOrgMemberBodySchema = z.object({\n handleOrEmail: z.string().min(1),\n role: z.enum([\"manager\", \"dj\", \"screener\"]).default(\"dj\"),\n});\nexport type AddOrgMemberBody = z.infer<typeof AddOrgMemberBodySchema>;\n\n// Owner role is never assignable this way (mirror of frequency ChangeRoleBodySchema).\nexport const ChangeOrgRoleBodySchema = z.object({\n role: z.enum([\"manager\", \"dj\", \"screener\"]),\n});\nexport type ChangeOrgRoleBody = z.infer<typeof ChangeOrgRoleBodySchema>;\n\n// --- Invite links ---\n\n// Frequency-scoped link. \"admin\"-granting links are owner-mintable only (route-enforced).\nexport const CreateInviteLinkBodySchema = z.object({\n role: z.enum([\"admin\", \"user\"]).default(\"user\"),\n // Talk-granting links (canTalk: true) must carry an expiresAt no further out than the\n // server's ceiling (7 days) — route-enforced with VALIDATION_ERROR, capability\n // \"invite-link-channel-targeting\".\n expiresAt: z.iso.datetime().optional(),\n maxUses: z.number().int().positive().max(10000).optional(),\n // Channel targeting (capability \"invite-link-channel-targeting\"): redeem places the\n // redeemer on this channel's roster. Must be a group channel of the same frequency.\n channelId: z.string().optional(),\n // Grants transmit on the target channel. Requires channelId, and turns the link into a\n // forwardable transmit grant — hence the mandatory bounded expiresAt above.\n canTalk: z.boolean().default(false),\n});\nexport type CreateInviteLinkBody = z.infer<typeof CreateInviteLinkBodySchema>;\n\n// Org-scoped link (staff invites). Owner is never grantable.\nexport const CreateOrgInviteLinkBodySchema = z.object({\n orgRole: z.enum([\"manager\", \"dj\", \"screener\"]).default(\"dj\"),\n expiresAt: z.iso.datetime().optional(),\n maxUses: z.number().int().positive().max(10000).optional(),\n});\nexport type CreateOrgInviteLinkBody = z.infer<typeof CreateOrgInviteLinkBodySchema>;\n\nexport const RedeemInviteBodySchema = z.object({\n code: z.string().min(4).max(64),\n});\nexport type RedeemInviteBody = z.infer<typeof RedeemInviteBodySchema>;\n\n// --- Billing (Stripe) ---\n\n// In-app checkout, fully app-styled (2026-07-20 rework — the prebuilt embedded Checkout\n// iframe looked foreign in the console): the server mints a SetupIntent, the client\n// collects the card with a themed Payment Element, then /billing/subscribe creates the\n// trial subscription server-side. broadcast plans bill an organization — organizationId\n// required for planKey \"broadcast\" (route-enforced, manager+).\nexport const CreateSetupIntentBodySchema = z.object({\n planKey: z.enum([\"operator\", \"broadcast\"]),\n organizationId: z.uuid().optional(),\n});\nexport type CreateSetupIntentBody = z.infer<typeof CreateSetupIntentBodySchema>;\n\n// setupIntentId comes back from the client's confirmSetup — the server re-verifies it\n// against Stripe (succeeded + belongs to the caller's customer) before subscribing.\nexport const CompleteSubscriptionBodySchema = z.object({\n planKey: z.enum([\"operator\", \"broadcast\"]),\n organizationId: z.uuid().optional(),\n setupIntentId: z.string().min(1),\n // 18+ attestation — must be true (422 AGE_ATTESTATION_REQUIRED); recorded durably.\n // See CreateFrequencyBodySchema.ageConfirmed and the \"age-attestation\" capability.\n ageConfirmed: z.boolean().optional(),\n // Acceptance of the Terms of Service as a whole — **required** since 0.35.0\n // (422 TERMS_ACCEPTANCE_REQUIRED). One combined clickwrap sends this with ageConfirmed.\n termsAccepted: z.boolean().optional(),\n});\nexport type CompleteSubscriptionBody = z.infer<typeof CompleteSubscriptionBodySchema>;\n\n// POST /billing/subscribe response — subscription state is known synchronously (no\n// webhook round-trip needed to proceed).\nexport type SubscribeResultDto = {\n status: string;\n subscriptionActive: boolean;\n};\n\nexport const CreatePortalSessionBodySchema = z.object({\n organizationId: z.uuid().optional(),\n});\nexport type CreatePortalSessionBody = z.infer<typeof CreatePortalSessionBodySchema>;\n\n// GET /billing/status response shape (server-composed, client-rendered).\nexport type BillingSubscriptionDto = {\n id: string;\n planKey: \"operator\" | \"broadcast\";\n status: string;\n frequencyId: string | null;\n currentPeriodEnd: string | null;\n cancelAtPeriodEnd: boolean;\n // Dunning state (0.36.0). Both null while the card is healthy. `lastPaymentFailureAt` set\n // with `nextPaymentAttemptAt` NULL is the case worth branching on: nobody is going to\n // retry, so the customer's card is the only way forward.\n lastPaymentFailureAt: string | null;\n nextPaymentAttemptAt: string | null;\n // What pays for this row (0.123.3): `stripe` (a card subscription, the historical case) or\n // `credit` (the account's prepaid balance; no Stripe subscription behind it, so the card\n // routes answer 409 CREDIT_FUNDED_SUBSCRIPTION).\n fundedBy: \"stripe\" | \"credit\";\n owner: { type: \"user\" } | { type: \"organization\"; organizationId: string; name: string };\n};\nexport type BillingStatusDto = {\n configured: boolean;\n enforced: boolean;\n subscriptions: BillingSubscriptionDto[];\n};\n\n// --- In-house subscription management (2026-07-22) ---\n// The app manages subscriptions itself (cancel/resume, card on file, invoices) instead of\n// handing off to the Stripe-hosted portal — owner call: in-app control and styling beat a\n// foreign-looking external page. Everything is keyed on OUR subscription id (from\n// /billing/status); the routes authorize against the subscription's billing account, so\n// no organizationId juggling is needed.\n\nexport const CompletePaymentMethodBodySchema = z.object({\n setupIntentId: z.string().min(1),\n});\nexport type CompletePaymentMethodBody = z.infer<typeof CompletePaymentMethodBodySchema>;\n\n// Card summary for display. `kind` is Stripe's PaymentMethod type (\"card\", \"link\", ...);\n// the card fields are null for non-card kinds.\nexport type BillingPaymentMethodDto = {\n paymentMethod: {\n kind: string;\n brand: string | null;\n last4: string | null;\n expMonth: number | null;\n expYear: number | null;\n } | null;\n};\n\nexport type BillingInvoiceDto = {\n id: string;\n number: string | null;\n status: string;\n amountDue: number;\n amountPaid: number;\n currency: string;\n created: string;\n hostedInvoiceUrl: string | null;\n invoicePdf: string | null;\n};\nexport type BillingInvoicesDto = { invoices: BillingInvoiceDto[] };\n\n// Cancel/resume response — the refreshed subscription state. The client should still\n// reload /billing/status afterwards for the full picture.\nexport type SubscriptionMutationDto = {\n id: string;\n status: string;\n cancelAtPeriodEnd: boolean;\n currentPeriodEnd: string | null;\n};\n\n// --- Plan changes (2026-08-01) ---\n// Upgrade (operator→broadcast) and downgrade (broadcast→push_to_talk) are cancel-and-\n// replace across two Stripe customers (operator bills the person, broadcast bills the\n// org — a Stripe subscription cannot move between customers). Two-step flow like\n// checkout: /start mints the destination-side prerequisites + a SetupIntent, the client\n// confirms the card, /complete charges and flips the frequency.\n\nexport const UpgradeSubscriptionStartBodySchema = z\n .object({\n // The station's name, editable at conversion (2026-08-02) and prefilled client-side\n // with the frequency's current name. A broadcast frequency's name IS its station name,\n // so /complete renames the frequency to match — the two never diverge. Omitted (older\n // clients) = keep the frequency's current name. Globally unique across stations, so a\n // taken one is a 409 STATION_NAME_TAKEN; /start checks availability early, advisory\n // only, so nobody reaches the card form on a name that would fail after payment.\n stationName: publicName(1, 64).optional(),\n // The callsign is the station's on-air ID, unique like the name and checked the same way.\n stationCallsign: StationCallsignSchema,\n // Which company this station will belong to: an existing one of the caller's, by id\n // (membership verified, never resolved from a typed name), or a new one to create.\n // Exactly one — the superRefine below is the wire-level half of resolveCompany.ts.\n organizationId: z.uuid().optional(),\n companyContact: CompanyContactSchema.optional(),\n })\n .superRefine((value, ctx) => {\n if (!value.organizationId === !value.companyContact) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"organizationId\"],\n message: \"Give either an existing company (organizationId) or details for a new one, not both.\",\n });\n }\n });\nexport type UpgradeSubscriptionStartBody = z.infer<typeof UpgradeSubscriptionStartBodySchema>;\n\nexport const UpgradeSubscriptionCompleteBodySchema = z.object({\n setupIntentId: z.string().min(1),\n // The company resolved by /start — echoed back so /complete binds card, company and\n // frequency. Its membership is re-verified here; /start's answer is never trusted alone.\n organizationId: z.uuid(),\n // The station's identity, resent so the flip writes it straight onto the frequency\n // (2026-08-02). /start no longer parks these on the company — the station is BORN on the\n // frequency at /complete, which is also the only moment the frequency becomes broadcast.\n // Both are re-checked for uniqueness inside the flip transaction; /start's check was\n // advisory. stationName omitted = keep the frequency's current name.\n stationName: publicName(1, 64).optional(),\n stationCallsign: StationCallsignSchema,\n ageConfirmed: z.boolean().optional(),\n // Required since 0.35.0 — 422 TERMS_ACCEPTANCE_REQUIRED.\n termsAccepted: z.boolean().optional(),\n});\nexport type UpgradeSubscriptionCompleteBody = z.infer<typeof UpgradeSubscriptionCompleteBodySchema>;\n\nexport const DowngradeSubscriptionCompleteBodySchema = z.object({\n setupIntentId: z.string().min(1),\n // Required when the frequency sits on a non-HAM dial number (preview.khzRequired).\n khz: z.number().int().positive().optional(),\n ageConfirmed: z.boolean().optional(),\n // Same combined clickwrap as every other acquisition path, and required like them since\n // 0.35.0 (422 TERMS_ACCEPTANCE_REQUIRED). This path had no field at all until 2026-08-27,\n // so it could not record a `terms` row even when the client had collected the acceptance.\n termsAccepted: z.boolean().optional(),\n // Must be true — the company signs off that all stored company information is\n // released for deletion and will not be retained (422 COMPANY_RELEASE_REQUIRED).\n companyInfoReleaseAccepted: z.boolean().optional(),\n});\nexport type DowngradeSubscriptionCompleteBody = z.infer<typeof DowngradeSubscriptionCompleteBodySchema>;\n\n// What /start quotes: charges are stated up front and recomputed server-side at\n// /complete time — the preview is display-only.\nexport type PlanChangePreviewDto = {\n targetPlanKey: \"operator\" | \"broadcast\";\n /** First charge after credits, in cents (0 while a carried trial runs). */\n dueNowCents: number;\n /** Credit applied: fixed operator month (upgrade) or unused broadcast time (downgrade). */\n creditCents: number;\n trialCarried: boolean;\n trialEnd: string | null;\n /** Downgrade only: the frequency must move to a HAM-band number in the same change. */\n khzRequired?: boolean;\n};\n\nexport type PlanChangeStartDto = {\n clientSecret: string;\n customerSessionClientSecret?: string;\n /** Upgrade only: the company that will own the station — created or attached by /start. */\n organizationId?: string;\n /** True when /start created the company — the client deletes it on abandon. An\n * attached existing company is never deleted, however the flow ends. */\n organizationMinted?: boolean;\n preview: PlanChangePreviewDto;\n};\n\nexport type PlanChangeResultDto = {\n newSubscriptionId: string;\n status: string;\n oldSubscriptionStatus: string;\n};\n\n// ApiErrorSchema / ApiError moved to ./errors.ts, alongside the catalogue of codes that\n// can appear in them. Still exported from the package root, so importers are unaffected.\n","// Country-aware address metadata (2026-07-21) — the minimal libaddressinput-style subset\n// that drives the company-contact form: which fields a country uses, their labels, and\n// (for countries with a fixed set) the administrative-area options. Hand-authored for the\n// launch allowlist; adding a country = one entry here + toggling it into the active\n// supported-countries platform setting. Country codes are ISO 3166-1 alpha-2 (uppercase).\n//\n// `region` / `postal` are null when that country's addresses don't use the field at all\n// (so the form hides it), else { label, required } — with `options` when it's a closed set\n// rendered as a dropdown (US/CA/AU) rather than free text.\n\nexport interface AdminAreaOption {\n code: string;\n name: string;\n}\n\nexport interface AddressFieldMeta {\n label: string;\n required: boolean;\n options?: AdminAreaOption[];\n}\n\nexport interface CountryMeta {\n name: string;\n region: AddressFieldMeta | null;\n postal: AddressFieldMeta | null;\n // International dialing prefix (e.g. \"+1\"), the default calling code the phone field\n // preselects when this country is chosen.\n callingCode: string;\n // Anchored regex SOURCE (case-insensitive) a postal code must match. Omitted when the\n // country has no postal field. Kept as a string (not RegExp) so it stays JSON-portable\n // and is compiled per-check with the `i` flag.\n postalPattern?: string;\n}\n\nconst US_STATES: AdminAreaOption[] = [\n { code: \"AL\", name: \"Alabama\" }, { code: \"AK\", name: \"Alaska\" }, { code: \"AZ\", name: \"Arizona\" },\n { code: \"AR\", name: \"Arkansas\" }, { code: \"CA\", name: \"California\" }, { code: \"CO\", name: \"Colorado\" },\n { code: \"CT\", name: \"Connecticut\" }, { code: \"DE\", name: \"Delaware\" }, { code: \"DC\", name: \"District of Columbia\" },\n { code: \"FL\", name: \"Florida\" }, { code: \"GA\", name: \"Georgia\" }, { code: \"HI\", name: \"Hawaii\" },\n { code: \"ID\", name: \"Idaho\" }, { code: \"IL\", name: \"Illinois\" }, { code: \"IN\", name: \"Indiana\" },\n { code: \"IA\", name: \"Iowa\" }, { code: \"KS\", name: \"Kansas\" }, { code: \"KY\", name: \"Kentucky\" },\n { code: \"LA\", name: \"Louisiana\" }, { code: \"ME\", name: \"Maine\" }, { code: \"MD\", name: \"Maryland\" },\n { code: \"MA\", name: \"Massachusetts\" }, { code: \"MI\", name: \"Michigan\" }, { code: \"MN\", name: \"Minnesota\" },\n { code: \"MS\", name: \"Mississippi\" }, { code: \"MO\", name: \"Missouri\" }, { code: \"MT\", name: \"Montana\" },\n { code: \"NE\", name: \"Nebraska\" }, { code: \"NV\", name: \"Nevada\" }, { code: \"NH\", name: \"New Hampshire\" },\n { code: \"NJ\", name: \"New Jersey\" }, { code: \"NM\", name: \"New Mexico\" }, { code: \"NY\", name: \"New York\" },\n { code: \"NC\", name: \"North Carolina\" }, { code: \"ND\", name: \"North Dakota\" }, { code: \"OH\", name: \"Ohio\" },\n { code: \"OK\", name: \"Oklahoma\" }, { code: \"OR\", name: \"Oregon\" }, { code: \"PA\", name: \"Pennsylvania\" },\n { code: \"RI\", name: \"Rhode Island\" }, { code: \"SC\", name: \"South Carolina\" }, { code: \"SD\", name: \"South Dakota\" },\n { code: \"TN\", name: \"Tennessee\" }, { code: \"TX\", name: \"Texas\" }, { code: \"UT\", name: \"Utah\" },\n { code: \"VT\", name: \"Vermont\" }, { code: \"VA\", name: \"Virginia\" }, { code: \"WA\", name: \"Washington\" },\n { code: \"WV\", name: \"West Virginia\" }, { code: \"WI\", name: \"Wisconsin\" }, { code: \"WY\", name: \"Wyoming\" },\n];\n\nconst CA_PROVINCES: AdminAreaOption[] = [\n { code: \"AB\", name: \"Alberta\" }, { code: \"BC\", name: \"British Columbia\" }, { code: \"MB\", name: \"Manitoba\" },\n { code: \"NB\", name: \"New Brunswick\" }, { code: \"NL\", name: \"Newfoundland and Labrador\" },\n { code: \"NS\", name: \"Nova Scotia\" }, { code: \"NT\", name: \"Northwest Territories\" }, { code: \"NU\", name: \"Nunavut\" },\n { code: \"ON\", name: \"Ontario\" }, { code: \"PE\", name: \"Prince Edward Island\" }, { code: \"QC\", name: \"Quebec\" },\n { code: \"SK\", name: \"Saskatchewan\" }, { code: \"YT\", name: \"Yukon\" },\n];\n\nconst AU_STATES: AdminAreaOption[] = [\n { code: \"NSW\", name: \"New South Wales\" }, { code: \"QLD\", name: \"Queensland\" }, { code: \"SA\", name: \"South Australia\" },\n { code: \"TAS\", name: \"Tasmania\" }, { code: \"VIC\", name: \"Victoria\" }, { code: \"WA\", name: \"Western Australia\" },\n { code: \"ACT\", name: \"Australian Capital Territory\" }, { code: \"NT\", name: \"Northern Territory\" },\n];\n\n// The full set we have address metadata for. The ACTIVE allowlist (which of these we\n// currently do business with) is a runtime platform setting, seeded from\n// DEFAULT_SUPPORTED_COUNTRIES; every code here must appear there or be toggled on later.\nexport const COUNTRY_METADATA: Record<string, CountryMeta> = {\n US: { name: \"United States\", region: { label: \"State\", required: true, options: US_STATES }, postal: { label: \"ZIP code\", required: true }, callingCode: \"+1\", postalPattern: \"^\\\\d{5}(-\\\\d{4})?$\" },\n CA: { name: \"Canada\", region: { label: \"Province\", required: true, options: CA_PROVINCES }, postal: { label: \"Postal code\", required: true }, callingCode: \"+1\", postalPattern: \"^[A-Za-z]\\\\d[A-Za-z] ?\\\\d[A-Za-z]\\\\d$\" },\n GB: { name: \"United Kingdom\", region: null, postal: { label: \"Postcode\", required: true }, callingCode: \"+44\", postalPattern: \"^[A-Za-z]{1,2}\\\\d[A-Za-z\\\\d]? ?\\\\d[A-Za-z]{2}$\" },\n IE: { name: \"Ireland\", region: { label: \"County\", required: false }, postal: { label: \"Eircode\", required: false }, callingCode: \"+353\", postalPattern: \"^[A-Za-z]\\\\d{2} ?[A-Za-z\\\\d]{4}$\" },\n AU: { name: \"Australia\", region: { label: \"State/territory\", required: true, options: AU_STATES }, postal: { label: \"Postcode\", required: true }, callingCode: \"+61\", postalPattern: \"^\\\\d{4}$\" },\n NZ: { name: \"New Zealand\", region: null, postal: { label: \"Postcode\", required: true }, callingCode: \"+64\", postalPattern: \"^\\\\d{4}$\" },\n DE: { name: \"Germany\", region: null, postal: { label: \"Postal code\", required: true }, callingCode: \"+49\", postalPattern: \"^\\\\d{5}$\" },\n FR: { name: \"France\", region: null, postal: { label: \"Postal code\", required: true }, callingCode: \"+33\", postalPattern: \"^\\\\d{5}$\" },\n NL: { name: \"Netherlands\", region: null, postal: { label: \"Postal code\", required: true }, callingCode: \"+31\", postalPattern: \"^\\\\d{4} ?[A-Za-z]{2}$\" },\n ES: { name: \"Spain\", region: { label: \"Province\", required: true }, postal: { label: \"Postal code\", required: true }, callingCode: \"+34\", postalPattern: \"^\\\\d{5}$\" },\n IT: { name: \"Italy\", region: { label: \"Province\", required: true }, postal: { label: \"Postal code\", required: true }, callingCode: \"+39\", postalPattern: \"^\\\\d{5}$\" },\n SE: { name: \"Sweden\", region: null, postal: { label: \"Postal code\", required: true }, callingCode: \"+46\", postalPattern: \"^\\\\d{3} ?\\\\d{2}$\" },\n};\n\n// Distinct international calling codes across the known countries (for the phone field's\n// prefix dropdown), each labeled with the country name(s) that use it, sorted by code.\nexport const CALLING_CODES: { code: string; label: string }[] = (() => {\n const byCode = new Map<string, string[]>();\n for (const meta of Object.values(COUNTRY_METADATA)) {\n const names = byCode.get(meta.callingCode) ?? [];\n names.push(meta.name);\n byCode.set(meta.callingCode, names);\n }\n return [...byCode.entries()]\n .map(([code, names]) => ({ code, label: `${code} (${names.join(\", \")})` }))\n .sort((a, b) => Number(a.code.slice(1)) - Number(b.code.slice(1)));\n})();\n\n// The curated starter allowlist. Seeds the `supported_countries` platform setting on first\n// boot, and is the fallback whenever that row is missing or empty; editable afterward via the\n// admin plane.\n//\n// **UNITED STATES ONLY for the beta launch (owner decision, 2026-08-27.)** It was every code\n// in COUNTRY_METADATA from 2026-07-21 until then. The metadata table deliberately KEEPS all\n// twelve countries — we hold their address/postal/phone rules and can do business there the\n// moment a code is toggled on; what narrows is only who we currently transact with. That is\n// the split the COUNTRY_METADATA comment above describes, and this is the lever it names.\n//\n// ⚠️ EDITING THIS DOES NOT NARROW A RUNNING DEPLOYMENT. `loadPlatformSettings` creates the\n// `supported_countries` row only when it is ABSENT, so an environment that already booted\n// (alpha did, with all twelve) keeps the seeded value forever. Restricting an existing\n// deployment is an admin-console Settings change against that row; this constant governs fresh\n// environments and the empty-row fallback. Both the app and the marketing site read the live\n// row (`/v1/platform/config` → `supportedCountries`, which subscribe.html filters its inlined\n// table by), so the row is the single source of truth for what a customer can actually pick.\nexport const DEFAULT_SUPPORTED_COUNTRIES: string[] = [\"US\"];\n\nexport function isKnownCountry(code: string): boolean {\n return Object.prototype.hasOwnProperty.call(COUNTRY_METADATA, code.toUpperCase());\n}\n","import { COUNTRY_METADATA } from \"./countries.js\";\n\n/**\n * Field-level validation for the company-contact PII block, shared by the client (inline\n * error messages) and the server (zod superRefine — the security boundary). Every rule\n * runs on BOTH sides so nothing bypasses validation by talking to the API directly.\n *\n * Security posture: reject control characters / line separators on every free-text field\n * (defence-in-depth against header/log/terminal injection; SQL is already parameterized by\n * Prisma and React escapes on render), enforce per-country postal formats and an E.164-ish\n * phone, and cap lengths. No field is written to storage or forwarded to Stripe unvalidated.\n */\n\n// A structural shape — avoids importing the CompanyContact type from api.ts (which imports\n// this module) and works for both the full create payload and a partial org-edit patch.\nexport interface CompanyContactLike {\n companyName?: string | null;\n addressLine1?: string | null;\n addressLine2?: string | null;\n city?: string | null;\n region?: string | null;\n postalCode?: string | null;\n country?: string | null;\n phone?: string | null;\n contactEmail?: string | null;\n}\n\nexport type CompanyContactField =\n | \"companyName\" | \"addressLine1\" | \"addressLine2\" | \"city\"\n | \"region\" | \"postalCode\" | \"country\" | \"phone\" | \"contactEmail\";\n\n// The address subset shared by the company-contact block and the card billing-details block\n// (collected app-side and forwarded to Stripe). Same validation rules run on both.\nexport type AddressField = \"addressLine1\" | \"addressLine2\" | \"city\" | \"region\" | \"postalCode\" | \"country\";\n\nexport interface AddressLike {\n addressLine1?: string | null;\n addressLine2?: string | null;\n city?: string | null;\n region?: string | null;\n postalCode?: string | null;\n country?: string | null;\n}\n\n// Card billing details = a person/company name + postal address + billing contact.\n// Phone and email were added 2026-07-22: Stripe's card confirmation requires both under\n// the current payment-method configuration, and the billing email is deliberately its\n// own field — it may differ from the signed-in account's email (invoices often go to\n// accounting, not the person clicking the button).\nexport type BillingDetailsField = \"name\" | \"phone\" | \"contactEmail\" | AddressField;\n\nexport interface BillingDetailsLike extends AddressLike {\n name?: string | null;\n phone?: string | null;\n contactEmail?: string | null;\n}\n\n// True if the string contains a disallowed invisible/control code point. Blocks (a) C0\n// controls + DEL + C1 (newline/null smuggling into logs, headers, terminals), (b) Unicode\n// line/paragraph separators, and (c) bidi-override / zero-width / format characters used for\n// Trojan-Source & homograph display-spoofing of names shown in the UI and on Stripe invoices.\n// Done by code point so no control char sits in source.\nexport function hasControlChars(s: string): boolean {\n for (let i = 0; i < s.length; i++) {\n const code = s.charCodeAt(i);\n if (\n code <= 0x1f || // C0 controls\n (code >= 0x7f && code <= 0x9f) || // DEL + C1\n code === 0x2028 || code === 0x2029 || // line / paragraph separator\n (code >= 0x200b && code <= 0x200f) || // zero-width + LTR/RTL marks\n (code >= 0x202a && code <= 0x202e) || // bidi embeddings / overrides\n (code >= 0x2060 && code <= 0x2064) || // word joiner + invisible operators\n (code >= 0x2066 && code <= 0x2069) || // bidi isolates\n code === 0xfeff // zero-width no-break space / BOM\n ) {\n return true;\n }\n }\n return false;\n}\n\n// Pragmatic email check (server also runs zod .email()); anchored, no spaces, one @.\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n// E.164-ish: a \"+\" then a leading digit and 4-20 more grouping-friendly chars.\nconst PHONE_ALLOWED = /^\\+\\d[\\d\\s\\-().]{4,20}$/;\n\nconst LIMITS = { name: 128, companyName: 128, addressLine1: 200, addressLine2: 200, city: 120, region: 120, postalCode: 32, phone: 40, contactEmail: 200 } as const;\n\nfunction clean(v: string | null | undefined): string {\n return (v ?? \"\").trim();\n}\n\nfunction digitCount(s: string): number {\n return (s.match(/\\d/g) ?? []).length;\n}\n\n/** True when `postal` matches the country's expected format (or the country/pattern is unknown). */\nexport function postalMatches(country: string, postal: string): boolean {\n const pattern = COUNTRY_METADATA[country.toUpperCase()]?.postalPattern;\n if (!pattern) return true;\n return new RegExp(pattern, \"i\").test(postal.trim());\n}\n\n// Free-text field: no control chars, within length. Required (+ non-partial) → must be present.\nfunction textField<F extends string>(\n errors: Partial<Record<F, string>>,\n value: string | null | undefined,\n field: F,\n required: boolean,\n label: string,\n limit: number,\n partial: boolean,\n): void {\n const val = clean(value);\n if (!val) {\n if (required && !partial) errors[field] = `${label} is required.` as Partial<Record<F, string>>[F];\n return;\n }\n if (hasControlChars(val)) errors[field] = `${label} contains invalid characters.` as Partial<Record<F, string>>[F];\n else if (val.length > limit) errors[field] = `${label} is too long (max ${limit}).` as Partial<Record<F, string>>[F];\n}\n\n/**\n * Validates the shared postal-address subset (address lines, city, country, region, postal)\n * into `errors`. Reused by the company-contact block AND the card billing-details block so the\n * two never diverge. Region/postal sanitization runs ALWAYS when a value is present (never gated\n * on country — a partial edit omitting `country` must not skip it); required-ness, \"country\n * doesn't use this field\", and closed-set/format checks are metadata-driven.\n */\nfunction validateAddressInto<F extends AddressField>(\n errors: Partial<Record<F, string>>,\n c: AddressLike,\n partial: boolean,\n): void {\n const country = clean(c.country).toUpperCase();\n const meta = country ? COUNTRY_METADATA[country] : undefined;\n\n textField(errors, c.addressLine1, \"addressLine1\" as F, true, \"Street address\", LIMITS.addressLine1, partial);\n textField(errors, c.addressLine2, \"addressLine2\" as F, false, \"Suite / unit\", LIMITS.addressLine2, partial);\n textField(errors, c.city, \"city\" as F, true, \"City\", LIMITS.city, partial);\n\n const set = (field: AddressField, msg: string) => {\n errors[field as F] = msg as Partial<Record<F, string>>[F];\n };\n\n // Country must be one we have metadata for.\n if (!country) {\n if (!partial) set(\"country\", \"Select a country.\");\n } else if (!meta) {\n set(\"country\", \"Unsupported country.\");\n }\n\n const region = clean(c.region);\n if (region) {\n if (hasControlChars(region) || region.length > LIMITS.region) {\n set(\"region\", \"Region contains invalid characters.\");\n } else if (meta && !meta.region) {\n set(\"region\", `${meta.name} addresses don't use a region — leave it blank.`);\n } else if (meta?.region?.options && !meta.region.options.some((o) => o.code === region)) {\n set(\"region\", `Choose a valid ${meta.region.label.toLowerCase()}.`);\n }\n } else if (meta?.region?.required && !partial) {\n set(\"region\", `${meta.region.label} is required.`);\n }\n\n const postal = clean(c.postalCode);\n if (postal) {\n if (hasControlChars(postal) || postal.length > LIMITS.postalCode) {\n set(\"postalCode\", \"Postal code contains invalid characters.\");\n } else if (meta && !meta.postal) {\n set(\"postalCode\", `${meta.name} addresses don't use a postal code — leave it blank.`);\n } else if (meta?.postalPattern && !new RegExp(meta.postalPattern, \"i\").test(postal)) {\n set(\"postalCode\", `Enter a valid ${meta.postal?.label ?? \"postal code\"} for ${meta.name}.`);\n }\n } else if (meta?.postal?.required && !partial) {\n set(\"postalCode\", `${meta.postal.label} is required.`);\n }\n}\n\n/**\n * Returns a { field: message } map of validation errors — empty means valid. In `partial`\n * mode (an org edit that may omit fields) only FORMAT is checked on the fields that are\n * present; otherwise every required field must also be non-empty (create semantics).\n */\nexport function validateCompanyContact(\n c: CompanyContactLike,\n opts: { partial?: boolean } = {},\n): Partial<Record<CompanyContactField, string>> {\n const partial = opts.partial ?? false;\n const errors: Partial<Record<CompanyContactField, string>> = {};\n\n textField(errors, c.companyName, \"companyName\", true, \"Company name\", LIMITS.companyName, partial);\n validateAddressInto(errors, c, partial);\n validateContactInto(errors, c.phone, c.contactEmail, partial);\n return errors;\n}\n\n/** Phone + email rules shared by the company block and the card billing block. */\nfunction validateContactInto(\n errors: { phone?: string; contactEmail?: string },\n rawPhone: string | null | undefined,\n rawEmail: string | null | undefined,\n partial: boolean,\n): void {\n // Phone: required, E.164-ish (a \"+<country code>\" then digits), 7-15 total digits.\n const phone = clean(rawPhone);\n if (!phone) {\n if (!partial) errors.phone = \"Phone number is required.\";\n } else if (phone.length > LIMITS.phone || !PHONE_ALLOWED.test(phone) || digitCount(phone) < 7 || digitCount(phone) > 15) {\n errors.phone = \"Enter a valid phone number, including country code (e.g. +1 555 0100).\";\n }\n\n // Email: required, well-formed, within length.\n const email = clean(rawEmail);\n if (!email) {\n if (!partial) errors.contactEmail = \"Email is required.\";\n } else if (email.length > LIMITS.contactEmail || !EMAIL_RE.test(email)) {\n errors.contactEmail = \"Enter a valid email address.\";\n }\n}\n\n/**\n * Validates the card billing details (name + postal address + billing phone/email)\n * collected app-side and forwarded to Stripe. Same address and contact rules as the\n * company block. Non-partial: name, the country's required address fields, phone and\n * email must all be present — Stripe's confirm rejects without them (2026-07-22 alpha\n * checkout freeze), so the form must be able to gate on completeness.\n */\nexport function validateBillingDetails(\n b: BillingDetailsLike,\n opts: { partial?: boolean } = {},\n): Partial<Record<BillingDetailsField, string>> {\n const partial = opts.partial ?? false;\n const errors: Partial<Record<BillingDetailsField, string>> = {};\n textField(errors, b.name, \"name\", true, \"Name\", LIMITS.name, partial);\n validateAddressInto(errors, b, partial);\n validateContactInto(errors, b.phone, b.contactEmail, partial);\n return errors;\n}\n","/**\n * Profanity filter for user-visible identity/display fields (frequency & station names,\n * callsigns, handles, display names, taglines, channel/group names). Enforced server-side\n * as a zod `.refine` (the boundary) and re-used client-side for inline feedback.\n *\n * Obfuscation-resistant but false-positive-averse (station names legitimately contain\n * \"Classic\", \"Bass\", \"Sussex\", \"Cocktail\", …):\n * - leetspeak is normalized (sh1t → shit, f@ck → fack→…),\n * - each token is checked in two forms — as typed and with runs of repeats collapsed\n * (fuuuck → fuck) — so exaggeration doesn't evade,\n * - SEVERE words match as a SUBSTRING of a token (catches \"bullshit\", \"fuckface\"); the few\n * innocent words that embed one (Scunthorpe, shiitake, niggardly) are allow-listed,\n * - MODERATE words match only as a WHOLE token, so \"classic\"/\"cocktail\"/\"assassin\" are fine,\n * - a spaced-out \"f u c k\" is caught only when several single-letter tokens run together.\n *\n * The lists are curated and intentionally lean toward blocking. Operators add to them from\n * the admin console (Settings, Blocked words); see setAdminBlockedWords below.\n */\n\n// Homoglyph / leetspeak → letter. Applied before tokenizing so \"sh1t\"/\"b!tch\"/\"n1gg3r\" fold.\nconst LEET: Record<string, string> = {\n \"0\": \"o\", \"1\": \"i\", \"3\": \"e\", \"4\": \"a\", \"5\": \"s\", \"7\": \"t\", \"8\": \"b\", \"9\": \"g\",\n \"@\": \"a\", \"$\": \"s\", \"!\": \"i\", \"|\": \"i\", \"€\": \"e\",\n};\n\n// Matched as a substring of a token (after normalization). Rarely embedded in clean words.\nconst SEVERE = [\n \"fuck\", \"fuk\", \"phuck\", \"phuk\", \"shit\", \"cunt\", \"kunt\", \"bitch\", \"bastard\", \"asshole\",\n \"bullshit\", \"dumbass\", \"jackass\", \"motherfuck\", \"dickhead\", \"cocksuck\", \"whore\", \"slut\",\n \"nigger\", \"nigga\", \"faggot\", \"kike\", \"wetback\", \"chingchong\",\n];\n\n// Matched only as a WHOLE token — these embed in innocent words (class, cocktail, spicy…).\nconst MODERATE = new Set([\n \"ass\", \"asses\", \"cock\", \"dick\", \"cum\", \"tit\", \"tits\", \"piss\", \"crap\", \"prick\", \"arse\",\n \"twat\", \"wank\", \"wanker\", \"bollocks\", \"pussy\", \"chink\", \"spic\", \"coon\", \"gook\", \"dyke\",\n \"fag\", \"fags\", \"tranny\", \"retard\", \"retarded\", \"bugger\", \"bellend\",\n]);\n\n// Innocent words that embed a SEVERE substring (in as-typed or collapsed form). Both forms\n// of a token are checked against this set before flagging.\nconst ALLOWLIST = new Set([\"scunthorpe\", \"shiitake\", \"shitake\", \"niggardly\", \"niggard\"]);\n\nfunction normalize(text: string): string {\n let out = \"\";\n for (const ch of text.toLowerCase()) out += LEET[ch] ?? ch;\n return out;\n}\n\nfunction collapseRuns(token: string): string {\n return token.replace(/(.)\\1+/g, \"$1\");\n}\n\n/**\n * Words an operator added from the admin console (the `blocked_words` platform setting), on\n * top of the curated lists above. Module state on purpose: this filter runs inside zod\n * `.refine`s, which are synchronous and cannot await a settings read, so the control plane\n * pushes the list in here at boot and on every settings reload (platform/settings.ts). A\n * process that never calls setAdminBlockedWords (the clients, which use this only for\n * inline hints) simply checks the curated lists, and the server stays the boundary.\n */\nlet adminWholeWords = new Set<string>();\nlet adminAnywhereWords: string[] = [];\n\n/** The form a blocked word is stored and compared in, or null when it cannot be one. */\nexport function normalizeBlockedWord(word: string): string | null {\n const folded = normalize(word.trim());\n return /^[a-z]{2,40}$/.test(folded) ? folded : null;\n}\n\n/** Replaces the operator-added words. Entries that do not normalize to letters are dropped. */\nexport function setAdminBlockedWords(words: ReadonlyArray<{ word: string; match: \"word\" | \"anywhere\" }>): void {\n const whole = new Set<string>();\n const anywhere = new Set<string>();\n for (const entry of words) {\n const folded = normalizeBlockedWord(entry.word);\n if (!folded) continue;\n (entry.match === \"anywhere\" ? anywhere : whole).add(folded);\n }\n adminWholeWords = whole;\n adminAnywhereWords = [...anywhere];\n}\n\nfunction tokenIsProfane(token: string): boolean {\n const collapsed = collapseRuns(token);\n if (ALLOWLIST.has(token) || ALLOWLIST.has(collapsed)) return false;\n if (MODERATE.has(token) || MODERATE.has(collapsed)) return true;\n if (adminWholeWords.has(token) || adminWholeWords.has(collapsed)) return true;\n for (const word of SEVERE) {\n if (token.includes(word) || collapsed.includes(word)) return true;\n }\n for (const word of adminAnywhereWords) {\n if (token.includes(word) || collapsed.includes(word)) return true;\n }\n return false;\n}\n\n/** True if `text` contains blocked language. Empty / whitespace-only → false. */\nexport function containsProfanity(text: string): boolean {\n if (!text) return false;\n const tokens = normalize(text).split(/[^a-z]+/).filter(Boolean);\n if (tokens.length === 0) return false;\n for (const token of tokens) {\n if (tokenIsProfane(token)) return true;\n }\n // Spaced-out obfuscation (\"f u c k\") — only when the input is mostly single letters, so\n // \"W A B C\" call letters or normal multi-word names aren't smushed into a false match.\n const singles = tokens.filter((t) => t.length === 1);\n if (singles.length >= 3 && singles.length >= tokens.length - 1) {\n const joined = collapseRuns(tokens.join(\"\"));\n for (const word of [...SEVERE, ...adminAnywhereWords]) {\n if (joined.includes(word)) return true;\n }\n }\n return false;\n}\n\nexport const PROFANITY_MESSAGE = \"That contains language we don't allow — please choose different wording.\";\n\n/** zod `.refine` predicate: true when the value is clean. */\nexport const isCleanText = (v: string): boolean => !containsProfanity(v);\n","import { z } from \"zod\";\n\n/**\n * Pointer and ink on a screen share (capability `share-pointer`, contract §19 \"Pointer and ink\"):\n * a viewer points at, or draws on, the screen somebody is showing, and the sharer and every other\n * viewer see it. Isomorphic, like the rest of this directory: runs in a tab, a Worker and Node.\n *\n * It travels on the share container's SIGNALING socket (`sharePointer`), not the datapath: it is a\n * few dozen small messages a second at most, it must not be lost or reordered (a lost ink segment\n * is a gap in somebody's circle), and the signaling socket is already reliable and ordered.\n *\n * The node relays it BLIND. Where somebody points on another person's screen is content, and ink\n * can spell words, so each message is sealed under a key derived from the share key, which the\n * node never holds:\n * - The key is HKDF-SHA256(share key, info {@link POINTER_KEY_INFO}), never the share key itself.\n * The share key's nonces are connectionId || sequence; a pointer message has no sequence of its\n * own to spend, so it gets its own key and a random 96-bit IV, and the two nonce spaces can\n * never meet.\n * - The AAD binds the stream, the key epoch and the SENDER's datapath connectionId. The node\n * stamps `fromConnectionId` on the way out; a stamp that disagrees with the AAD fails to open,\n * so the node cannot relabel one viewer's pointer as another's, nor move it to another share.\n * - `seq` rises per sender. A message at or below the last one seen from that sender is dropped,\n * so a replay changes nothing.\n * Any member holding the share key can still forge a pointer in their OWN name; that is the same\n * trust the share itself runs on.\n */\n\nexport const POINTER_KEY_INFO = \"frequency-talk share pointer v1\";\nconst AAD_TAG = \"ftp1\";\n/** The sealed blob, base64: 4 epoch + 12 IV + JSON + 16 tag. A full ink message fits well inside. */\nexport const MAX_SEALED_POINTER_CHARS = 2048;\n/** Points per ink message; a longer stroke is sent as several. */\nexport const MAX_INK_POINTS_PER_MESSAGE = 48;\n/** How often a pointer move or an ink batch goes out, at most. */\nexport const POINTER_SEND_INTERVAL_MS = 33;\n/** A pointer nobody has moved for this long disappears. */\nexport const POINTER_IDLE_MS = 4_000;\n/** Ink stays at full strength this long after its stroke ends, then fades out over INK_FADE_MS. */\nexport const INK_HOLD_MS = 4_000;\nexport const INK_FADE_MS = 1_000;\n/** A stroke that stops growing without saying it ended (its sender went away) counts as ended. */\nexport const INK_STALL_MS = 2_000;\n/** Per sender: strokes kept at once, and points per stroke. Past either, the oldest goes / the rest are ignored. */\nexport const MAX_STROKES_PER_SENDER = 32;\nexport const MAX_POINTS_PER_STROKE = 1_024;\n/** A click with Point on: rings spread out from the spot over this long, then it is gone. */\nexport const PING_MS = 1_200;\n/** Per sender: pings kept at once. Past it the oldest goes. */\nexport const MAX_PINGS_PER_SENDER = 8;\n\nconst coord = z.number().min(0).max(1);\nconst seq = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);\n\n/** What a viewer sends, inside the seal. Coordinates are fractions of the shared picture (0..1),\n * so they land in the same place whatever size each person views it at. */\nexport const PointerMessageSchema = z.discriminatedUnion(\"t\", [\n z.object({ t: z.literal(\"move\"), seq, x: coord, y: coord }),\n z.object({ t: z.literal(\"hide\"), seq }),\n /** A click with Point on: \"look here\". Drawn as rings spreading out from the spot. */\n z.object({ t: z.literal(\"ping\"), seq, x: coord, y: coord }),\n z.object({\n t: z.literal(\"ink\"),\n seq,\n /** The stroke this extends. A new id is a new stroke. */\n id: z.number().int().nonnegative().max(0xffff),\n /** Flat x,y pairs appended to the stroke. */\n pts: z\n .array(coord)\n .min(2)\n .max(MAX_INK_POINTS_PER_MESSAGE * 2)\n .refine((p) => p.length % 2 === 0, \"points come in x,y pairs\"),\n done: z.boolean(),\n /** On the message that ends the stroke: draw an arrowhead at its last point, aimed the way\n * the stroke was going (Point's click and drag). A receiver that does not know it draws the\n * line without the head. */\n arrow: z.boolean().optional(),\n }),\n]);\nexport type PointerMessage = z.infer<typeof PointerMessageSchema>;\n/** A message before its sequence number is assigned. */\nexport type PointerMessageBody = PointerMessage extends infer M ? (M extends PointerMessage ? Omit<M, \"seq\"> : never) : never;\n\n/** The slice of SubtleCrypto this module uses. The real one is assignable to it. */\nexport interface PointerSubtle {\n importKey(format: \"raw\", keyData: Uint8Array, algorithm: \"HKDF\", extractable: false, keyUsages: [\"deriveKey\"]): Promise<object>;\n deriveKey(\n algorithm: { name: \"HKDF\"; hash: \"SHA-256\"; salt: Uint8Array; info: Uint8Array },\n baseKey: object,\n derivedKeyType: { name: \"AES-GCM\"; length: 256 },\n extractable: false,\n keyUsages: (\"encrypt\" | \"decrypt\")[],\n ): Promise<object>;\n encrypt(algorithm: { name: \"AES-GCM\"; iv: Uint8Array; additionalData: Uint8Array; tagLength: 128 }, key: object, data: Uint8Array): Promise<ArrayBuffer>;\n decrypt(algorithm: { name: \"AES-GCM\"; iv: Uint8Array; additionalData: Uint8Array; tagLength: 128 }, key: object, data: Uint8Array): Promise<ArrayBuffer>;\n}\n\ninterface CryptoLike {\n subtle?: PointerSubtle;\n getRandomValues<T extends Uint8Array>(array: T): T;\n}\n\nfunction webCrypto(): CryptoLike & { subtle: PointerSubtle } {\n const c = (globalThis as { crypto?: CryptoLike }).crypto;\n if (!c?.subtle) throw new Error(\"WebCrypto is not available here (crypto.subtle needs a secure context)\");\n return c as CryptoLike & { subtle: PointerSubtle };\n}\n\n/** A derived pointer key, for one share-key epoch. The raw bytes are not kept. */\nexport interface PointerKey {\n readonly epoch: number;\n readonly handle: object;\n}\n\nconst utf8 = (s: string) => new TextEncoder().encode(s);\n\nexport async function derivePointerKey(shareKey: Uint8Array, epoch: number, subtle: PointerSubtle = webCrypto().subtle): Promise<PointerKey> {\n if (shareKey.length !== 32) throw new RangeError(`a share key is 32 bytes, not ${shareKey.length}`);\n const base = await subtle.importKey(\"raw\", shareKey, \"HKDF\", false, [\"deriveKey\"]);\n const handle = await subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt: new Uint8Array(0), info: utf8(POINTER_KEY_INFO) },\n base,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"],\n );\n return { epoch, handle };\n}\n\nfunction aad(streamId: number, epoch: number, senderConnectionId: number): Uint8Array {\n const out = new Uint8Array(AAD_TAG.length + 12);\n out.set(utf8(AAD_TAG), 0);\n const view = new DataView(out.buffer);\n view.setUint32(AAD_TAG.length, streamId >>> 0);\n view.setUint32(AAD_TAG.length + 4, epoch >>> 0);\n view.setUint32(AAD_TAG.length + 8, senderConnectionId >>> 0);\n return out;\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!);\n return btoa(s);\n}\n\nfunction fromBase64(b64: string): Uint8Array | null {\n try {\n return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n } catch {\n return null;\n }\n}\n\n/** Seal one message from `senderConnectionId` (our own datapath id) for `streamId`. */\nexport async function sealPointer(key: PointerKey, streamId: number, senderConnectionId: number, message: PointerMessage, crypto: CryptoLike & { subtle: PointerSubtle } = webCrypto()): Promise<string> {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const sealed = new Uint8Array(\n await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: aad(streamId, key.epoch, senderConnectionId), tagLength: 128 }, key.handle, utf8(JSON.stringify(message))),\n );\n const out = new Uint8Array(4 + 12 + sealed.length);\n new DataView(out.buffer).setUint32(0, key.epoch >>> 0);\n out.set(iv, 4);\n out.set(sealed, 16);\n return toBase64(out);\n}\n\n/**\n * Open a relayed message. `keys` are the epochs we hold (the current one, and the one before\n * across a rotation). Null for anything that does not open or does not parse: the caller drops it\n * and says nothing, because the only senders who can produce one are a confused client and a\n * node that is not relaying faithfully.\n */\nexport async function openPointer(\n keys: readonly PointerKey[],\n streamId: number,\n fromConnectionId: number,\n sealed: string,\n subtle: PointerSubtle = webCrypto().subtle,\n): Promise<PointerMessage | null> {\n if (sealed.length > MAX_SEALED_POINTER_CHARS) return null;\n const bytes = fromBase64(sealed);\n if (!bytes || bytes.length < 4 + 12 + 16) return null;\n const epoch = new DataView(bytes.buffer, bytes.byteOffset).getUint32(0);\n const key = keys.find((k) => k.epoch >>> 0 === epoch);\n if (!key) return null;\n let plain: ArrayBuffer;\n try {\n plain = await subtle.decrypt({ name: \"AES-GCM\", iv: bytes.subarray(4, 16), additionalData: aad(streamId, epoch, fromConnectionId), tagLength: 128 }, key.handle, bytes.subarray(16));\n } catch {\n return null;\n }\n try {\n const parsed = PointerMessageSchema.safeParse(JSON.parse(new TextDecoder().decode(plain)));\n return parsed.success ? parsed.data : null;\n } catch {\n return null;\n }\n}\n\n/** One colour per person pointing, picked by their datapath id so everybody sees the same one. */\nexport const POINTER_COLORS = [\"#ff3b6b\", \"#2ee6a8\", \"#ffb020\", \"#4da3ff\", \"#c86bff\", \"#ff7a2e\"] as const;\nexport const pointerColor = (connectionId: number) => POINTER_COLORS[(connectionId >>> 0) % POINTER_COLORS.length]!;\n\n/**\n * What to draw right now, in fractions of the shared picture. This is also the frame the desktop\n * shell's on-screen overlay takes, so it is kept plain and stable: the overlay ships with the\n * shell and the web UI does not.\n */\nexport interface PointerScene {\n /** `until`: when this pointer disappears if nothing moves it (the board's clock). */\n pointers: { from: number; label: string; color: string; x: number; y: number; until: number }[];\n /** `alpha` at the moment asked; `fadeFrom`..`fadeTo` is when it fades out if nothing extends it\n * (the board's clock), so a drawer that is not called every frame can animate it alone.\n * `live`: still being drawn (not ended, not stalled). A viewer of a share whose marks are in\n * the picture draws only its own live stroke (2026-10-05). */\n strokes: { from: number; color: string; alpha: number; pts: number[]; fadeFrom: number; fadeTo: number; arrow: boolean; live?: boolean }[];\n /** A click's rings. `at`..`until` is the animation (the board's clock); `t` is how far through\n * it the moment asked is, 0..1. */\n pings: { from: number; color: string; x: number; y: number; at: number; until: number; t: number }[];\n}\n\ninterface Stroke {\n id: number;\n pts: number[];\n lastAt: number;\n endedAt: number | null;\n arrow: boolean;\n}\n\ninterface Sender {\n label: string;\n lastSeq: number;\n pointer: { x: number; y: number; at: number } | null;\n strokes: Stroke[];\n pings: { x: number; y: number; at: number }[];\n}\n\n/**\n * Everybody's pointer and ink on one share, and how it fades. Pure and clock-injected, so a test\n * drives the fades directly; the UI calls {@link scene} once per animation frame while\n * {@link active} says anything is on screen.\n */\nexport class PointerBoard {\n private readonly senders = new Map<number, Sender>();\n\n /** A message from `from`. False when it was stale (a replay, or out of order). */\n apply(from: number, label: string | null, message: PointerMessage, now: number): boolean {\n let s = this.senders.get(from);\n if (!s) {\n s = { label: label ?? \"Somebody\", lastSeq: 0, pointer: null, strokes: [], pings: [] };\n this.senders.set(from, s);\n }\n if (message.seq <= s.lastSeq) return false;\n s.lastSeq = message.seq;\n if (label) s.label = label;\n switch (message.t) {\n case \"move\":\n s.pointer = { x: message.x, y: message.y, at: now };\n return true;\n case \"hide\":\n s.pointer = null;\n return true;\n case \"ping\":\n s.pings.push({ x: message.x, y: message.y, at: now });\n if (s.pings.length > MAX_PINGS_PER_SENDER) s.pings.shift();\n s.pointer = { x: message.x, y: message.y, at: now };\n return true;\n case \"ink\": {\n let stroke = s.strokes.find((k) => k.id === message.id && k.endedAt === null);\n if (!stroke) {\n stroke = { id: message.id, pts: [], lastAt: now, endedAt: null, arrow: false };\n s.strokes.push(stroke);\n if (s.strokes.length > MAX_STROKES_PER_SENDER) s.strokes.shift();\n }\n const room = MAX_POINTS_PER_STROKE * 2 - stroke.pts.length;\n if (room > 0) stroke.pts.push(...message.pts.slice(0, room));\n stroke.lastAt = now;\n if (message.done) stroke.endedAt = now;\n if (message.arrow) stroke.arrow = true;\n // Drawing moves the pointer too: it is where the pen is.\n s.pointer = { x: message.pts[message.pts.length - 2]!, y: message.pts[message.pts.length - 1]!, at: now };\n return true;\n }\n }\n }\n\n /** The name a sender's messages carry, for a caption. */\n labelOf(from: number): string | null {\n return this.senders.get(from)?.label ?? null;\n }\n\n /** Somebody stopped watching or left: their pointer and ink go at once. */\n forget(from: number): void {\n this.senders.delete(from);\n }\n\n clear(): void {\n this.senders.clear();\n }\n\n scene(now: number): PointerScene {\n const out: PointerScene = { pointers: [], strokes: [], pings: [] };\n for (const [from, s] of this.senders) {\n const color = pointerColor(from);\n if (s.pointer && now - s.pointer.at >= POINTER_IDLE_MS) s.pointer = null;\n if (s.pointer) out.pointers.push({ from, label: s.label, color, x: s.pointer.x, y: s.pointer.y, until: s.pointer.at + POINTER_IDLE_MS });\n s.strokes = s.strokes.filter((k) => {\n // A stroke still being drawn ends, at the latest, when it stalls.\n const fadeFrom = (k.endedAt ?? k.lastAt + INK_STALL_MS) + INK_HOLD_MS;\n const fadeTo = fadeFrom + INK_FADE_MS;\n const alpha = Math.min(1, (fadeTo - now) / INK_FADE_MS);\n if (alpha <= 0) return false;\n out.strokes.push({ from, color, alpha, pts: k.pts, fadeFrom, fadeTo, arrow: k.arrow, live: k.endedAt === null && now - k.lastAt < INK_STALL_MS });\n return true;\n });\n s.pings = s.pings.filter((p) => {\n if (now - p.at >= PING_MS) return false;\n out.pings.push({ from, color, x: p.x, y: p.y, at: p.at, until: p.at + PING_MS, t: Math.max(0, (now - p.at) / PING_MS) });\n return true;\n });\n }\n return out;\n }\n\n /** Anything to draw at `now` (or about to be, until it fades). */\n active(now: number): boolean {\n const s = this.scene(now);\n return s.pointers.length > 0 || s.strokes.length > 0 || s.pings.length > 0;\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Remote control of a screen share (capability `share-control`, contract §19 \"Remote control\"):\n * a viewer asks to drive the sharer's mouse and keyboard, the sharer's desktop app asks the sharer,\n * and while they allow it the viewer's input lands on the sharer's real screen. Isomorphic, like\n * the rest of this directory: the viewer's half runs in a tab or a Worker, the sharer's half runs\n * in the desktop shell's MAIN process (Node).\n *\n * Two layers, because there are two different things to keep out:\n *\n * 1. THE NODE. Every message rides the share signaling socket as `shareControl`, addressed from\n * one datapath id to one other, and is sealed under HKDF(share key, {@link CONTROL_KEY_INFO}),\n * as pointer messages are, with sender AND recipient in the AAD. The node relays it blind and\n * cannot redirect it to somebody else.\n *\n * 2. EVERYBODY ELSE WHO HOLDS THE SHARE KEY. That is every member of the call, and the control\n * plane, which mints the key. Keystrokes are passwords and a click is an action, so the input\n * itself is sealed under a key only the two installs hold: an X25519 exchange made for this\n * one grant. The exchange is committed first (the viewer sends a hash of its public key before\n * seeing the sharer's, as ZRTP does), so a man in the middle cannot grind keys until the two\n * sides' codes agree; both sides then show a six-digit code from the transcript, and two people\n * already on a voice call can read it to each other. The sharer's desktop app, never the web\n * page, holds the sharer's half, draws the consent dialog and injects the input, so a web UI\n * that has been tampered with cannot grant control on its own.\n *\n * The exchange:\n * viewer -> sharer commit { sid, h = SHA-256(viewer pub) }\n * sharer -> viewer offer { sid, pub } (or deny, with a reason)\n * viewer -> sharer reveal { sid, pub } (the sharer checks it against h)\n * both show the code; the sharer allows or declines\n * sharer -> viewer grant { sid, box } (or deny)\n * viewer -> sharer in { sid, box } ... input, ~60 a second at most\n * either -> other end { sid, reason }\n *\n * `box` is the pairwise layer: AES-256-GCM, one key per direction, and a COUNTER nonce, which is\n * safe because each key is fresh for this grant and has exactly one sender. The signaling socket\n * is reliable and ordered, so a receiver requires every counter to be the last one plus one; a\n * gap means the node dropped something (its rate cap), and the sharer then lets go of every key\n * and button it holds for the viewer, since the lost message might have been the key-up.\n */\n\nexport const CONTROL_KEY_INFO = \"frequency-talk share control v1\";\nconst AAD_TAG = \"ftc1\";\nconst PAIR_AAD_TAG = \"ftcp\";\nconst TRANSCRIPT_TAG = \"ftc-hs1\";\n\n/** The sealed blob, base64. An input batch of 64 events fits well inside. */\nexport const MAX_SEALED_CONTROL_CHARS = 8192;\n/** Input goes out at most this often, batched; a key press or a click goes at once. */\nexport const CONTROL_SEND_INTERVAL_MS = 16;\n/** A viewer in control with nothing to send says so this often... */\nexport const CONTROL_KEEPALIVE_MS = 1_000;\n/** ...and a sharer that hears nothing for this long lets go of everything and ends control. */\nexport const CONTROL_WATCHDOG_MS = 3_000;\n/** How long the sharer's consent dialog waits for an answer. */\nexport const CONTROL_CONSENT_MS = 30_000;\n/** Per sender per share per second, at the node. An honest viewer sends at most ~60. */\nexport const CONTROL_PER_SENDER_PER_SECOND = 120;\nexport const MAX_CONTROL_EVENTS_PER_BATCH = 64;\nexport const MAX_CONTROL_TEXT = 256;\n\n/** Why a request did not become control. */\nexport const CONTROL_DENY_REASONS = [\n /** The sharer said no. */\n \"declined\",\n /** Nobody answered the consent dialog in time. */\n \"timeout\",\n /** The sharer's app cannot be controlled: a browser, or a desktop app too old for it. */\n \"unsupported\",\n /** The sharer is showing a window or a region, not a whole screen. */\n \"window\",\n /** The operating system has not given the sharer's app permission to control the computer. */\n \"permission\",\n /** Somebody else is in control already, or a request is already on screen. */\n \"busy\",\n /** The exchange did not check out (a reveal that did not match its commit). */\n \"failed\",\n] as const;\nexport type ControlDenyReason = (typeof CONTROL_DENY_REASONS)[number];\n\n/** Why control that was granted stopped. */\nexport const CONTROL_END_REASONS = [\n /** The sharer took it back. */\n \"revoked\",\n /** The viewer let go. */\n \"released\",\n /** The share (or the call) ended. */\n \"ended\",\n /** The sharer heard nothing from the viewer for {@link CONTROL_WATCHDOG_MS}. */\n \"idle\",\n /** Something went wrong on one side. */\n \"error\",\n] as const;\nexport type ControlEndReason = (typeof CONTROL_END_REASONS)[number];\n\nconst sid = z.string().regex(/^[0-9a-f]{16}$/);\nconst b64 = (max: number) => z.string().min(1).max(max).regex(/^[A-Za-z0-9+/]+=*$/);\nconst key32 = b64(44);\n\n/** What rides inside the outer seal. */\nexport const ControlMessageSchema = z.discriminatedUnion(\"t\", [\n z.object({ t: z.literal(\"commit\"), sid, h: key32 }),\n z.object({ t: z.literal(\"offer\"), sid, pub: key32 }),\n z.object({ t: z.literal(\"reveal\"), sid, pub: key32 }),\n z.object({ t: z.literal(\"grant\"), sid, box: b64(256) }),\n z.object({ t: z.literal(\"deny\"), sid, reason: z.enum(CONTROL_DENY_REASONS) }),\n z.object({ t: z.literal(\"in\"), sid, box: b64(MAX_SEALED_CONTROL_CHARS) }),\n z.object({ t: z.literal(\"end\"), sid, reason: z.enum(CONTROL_END_REASONS) }),\n]);\nexport type ControlMessage = z.infer<typeof ControlMessageSchema>;\n\nconst frac = z.number().min(0).max(1);\nconst button = z.enum([\"left\", \"right\", \"middle\"]);\n\n/**\n * One piece of input, positions as fractions of the shared picture (0..1, origin top left), so a\n * viewer at any size lands on the same spot. Keys carry the browser's `KeyboardEvent.code` (which\n * key) AND `.key` (what it types), because the sharer's keyboard layout may differ: the sharer\n * types what the viewer typed.\n */\nexport const ControlInputSchema = z.discriminatedUnion(\"k\", [\n z.object({ k: z.literal(\"move\"), x: frac, y: frac }),\n /** `c`: the click count (`MouseEvent.detail`), so a double click lands as one. */\n z.object({ k: z.literal(\"down\"), b: button, x: frac, y: frac, c: z.number().int().min(1).max(3) }),\n z.object({ k: z.literal(\"up\"), b: button, x: frac, y: frac }),\n /** Pixels as the viewer's wheel reported them, clamped. */\n z.object({ k: z.literal(\"wheel\"), x: frac, y: frac, dx: z.number().min(-2000).max(2000), dy: z.number().min(-2000).max(2000) }),\n z.object({ k: z.literal(\"key\"), d: z.boolean(), code: z.string().max(32), key: z.string().max(32) }),\n /** Composed text (an input method, an emoji picker), typed as it is. */\n z.object({ k: z.literal(\"text\"), s: z.string().min(1).max(MAX_CONTROL_TEXT) }),\n]);\nexport type ControlInput = z.infer<typeof ControlInputSchema>;\n\n/** An empty batch is a keepalive. */\nexport const ControlBatchSchema = z.object({ ev: z.array(ControlInputSchema).max(MAX_CONTROL_EVENTS_PER_BATCH) });\nexport type ControlBatch = z.infer<typeof ControlBatchSchema>;\n\n// ---------------------------------------------------------------------------------------------\n// Crypto plumbing. The slice of SubtleCrypto this module uses; the real one is assignable to it.\n\ntype Key = object;\nexport interface ControlSubtle {\n importKey(format: \"raw\", keyData: Uint8Array, algorithm: \"HKDF\" | { name: \"X25519\" }, extractable: false, keyUsages: string[]): Promise<Key>;\n generateKey(algorithm: { name: \"X25519\" }, extractable: boolean, keyUsages: [\"deriveBits\"]): Promise<{ publicKey: Key; privateKey: Key }>;\n exportKey(format: \"raw\", key: Key): Promise<ArrayBuffer>;\n deriveBits(algorithm: { name: \"X25519\"; public: Key }, baseKey: Key, length: 256): Promise<ArrayBuffer>;\n deriveKey(\n algorithm: { name: \"HKDF\"; hash: \"SHA-256\"; salt: Uint8Array; info: Uint8Array },\n baseKey: Key,\n derivedKeyType: { name: \"AES-GCM\"; length: 256 },\n extractable: false,\n keyUsages: (\"encrypt\" | \"decrypt\")[],\n ): Promise<Key>;\n digest(algorithm: \"SHA-256\", data: Uint8Array): Promise<ArrayBuffer>;\n encrypt(algorithm: { name: \"AES-GCM\"; iv: Uint8Array; additionalData: Uint8Array; tagLength: 128 }, key: Key, data: Uint8Array): Promise<ArrayBuffer>;\n decrypt(algorithm: { name: \"AES-GCM\"; iv: Uint8Array; additionalData: Uint8Array; tagLength: 128 }, key: Key, data: Uint8Array): Promise<ArrayBuffer>;\n}\n\nexport interface ControlCrypto {\n subtle: ControlSubtle;\n getRandomValues<T extends Uint8Array>(array: T): T;\n}\n\nfunction webCrypto(): ControlCrypto {\n const c = (globalThis as { crypto?: Partial<ControlCrypto> }).crypto;\n if (!c?.subtle || !c.getRandomValues) throw new Error(\"WebCrypto is not available here (crypto.subtle needs a secure context)\");\n return c as ControlCrypto;\n}\n\nconst utf8 = (s: string) => new TextEncoder().encode(s);\n\nfunction toBase64(bytes: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!);\n return btoa(s);\n}\n\nfunction fromBase64(b64: string): Uint8Array | null {\n try {\n return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n } catch {\n return null;\n }\n}\n\nfunction concat(...parts: Uint8Array[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n let at = 0;\n for (const p of parts) {\n out.set(p, at);\n at += p.length;\n }\n return out;\n}\n\nfunction u32(n: number): Uint8Array {\n const out = new Uint8Array(4);\n new DataView(out.buffer).setUint32(0, n >>> 0);\n return out;\n}\n\nfunction hexBytes(hex: string): Uint8Array {\n const out = new Uint8Array(hex.length / 2);\n for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n return out;\n}\n\nfunction equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;\n return diff === 0;\n}\n\n// ---------------------------------------------------------------------------------------------\n// Layer 1: the envelope the node relays.\n\nexport interface ControlEnvelopeKey {\n readonly epoch: number;\n readonly handle: Key;\n}\n\nexport async function deriveControlKey(shareKey: Uint8Array, epoch: number, crypto: ControlCrypto = webCrypto()): Promise<ControlEnvelopeKey> {\n if (shareKey.length !== 32) throw new RangeError(`a share key is 32 bytes, not ${shareKey.length}`);\n const base = await crypto.subtle.importKey(\"raw\", shareKey, \"HKDF\", false, [\"deriveKey\"]);\n const handle = await crypto.subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt: new Uint8Array(0), info: utf8(CONTROL_KEY_INFO) },\n base,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"],\n );\n return { epoch, handle };\n}\n\nfunction envelopeAad(streamId: number, epoch: number, from: number, to: number): Uint8Array {\n return concat(utf8(AAD_TAG), u32(streamId), u32(epoch), u32(from), u32(to));\n}\n\n/** Seal one message from our datapath id `from` to theirs, `to`, on `streamId`. */\nexport async function sealControl(key: ControlEnvelopeKey, streamId: number, from: number, to: number, message: ControlMessage, crypto: ControlCrypto = webCrypto()): Promise<string> {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const sealed = new Uint8Array(\n await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: envelopeAad(streamId, key.epoch, from, to), tagLength: 128 }, key.handle, utf8(JSON.stringify(message))),\n );\n return toBase64(concat(u32(key.epoch), iv, sealed));\n}\n\n/**\n * Open a relayed message: `from` is the node's stamp, `to` is our own datapath id. Null for\n * anything that does not open or parse, which the caller drops without a word.\n */\nexport async function openControl(keys: readonly ControlEnvelopeKey[], streamId: number, from: number, to: number, sealed: string, crypto: ControlCrypto = webCrypto()): Promise<ControlMessage | null> {\n if (sealed.length > MAX_SEALED_CONTROL_CHARS * 2) return null;\n const bytes = fromBase64(sealed);\n if (!bytes || bytes.length < 4 + 12 + 16) return null;\n const epoch = new DataView(bytes.buffer, bytes.byteOffset).getUint32(0);\n const key = keys.find((k) => k.epoch >>> 0 === epoch);\n if (!key) return null;\n try {\n const plain = await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: bytes.subarray(4, 16), additionalData: envelopeAad(streamId, epoch, from, to), tagLength: 128 }, key.handle, bytes.subarray(16));\n const parsed = ControlMessageSchema.safeParse(JSON.parse(new TextDecoder().decode(plain)));\n return parsed.success ? parsed.data : null;\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------------------------\n// Layer 2: the exchange and the pairwise channel.\n\n/** Who the exchange is between: the share, the viewer's datapath id, the sharer's. */\nexport interface ControlParties {\n streamId: number;\n viewer: number;\n sharer: number;\n}\n\n/** The viewer's side before the sharer's offer: our key pair and what we committed to. */\nexport interface ControlRequest {\n sid: string;\n privateKey: Key;\n pub: Uint8Array;\n commit: ControlMessage & { t: \"commit\" };\n}\n\n/** The sharer's side before the reveal. */\nexport interface ControlOffer {\n sid: string;\n privateKey: Key;\n pub: Uint8Array;\n commitHash: Uint8Array;\n offer: ControlMessage & { t: \"offer\" };\n}\n\n/** A finished exchange: the code both people compare, and a channel for each direction. */\nexport interface ControlPairing {\n sid: string;\n /** Six digits, \"482 915\". The same on both sides unless somebody is in the middle. */\n code: string;\n channel: PairwiseChannel;\n}\n\nasync function keyPair(crypto: ControlCrypto): Promise<{ privateKey: Key; pub: Uint8Array }> {\n const pair = await crypto.subtle.generateKey({ name: \"X25519\" }, false, [\"deriveBits\"]);\n return { privateKey: pair.privateKey, pub: new Uint8Array(await crypto.subtle.exportKey(\"raw\", pair.publicKey)) };\n}\n\n/** Viewer: start a request. */\nexport async function startControlRequest(crypto: ControlCrypto = webCrypto()): Promise<ControlRequest> {\n const sidBytes = crypto.getRandomValues(new Uint8Array(8));\n const id = Array.from(sidBytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n const { privateKey, pub } = await keyPair(crypto);\n const h = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", pub));\n return { sid: id, privateKey, pub, commit: { t: \"commit\", sid: id, h: toBase64(h) } };\n}\n\n/** Sharer: answer a commit with our own public key. */\nexport async function answerControlRequest(commit: ControlMessage & { t: \"commit\" }, crypto: ControlCrypto = webCrypto()): Promise<ControlOffer> {\n const commitHash = fromBase64(commit.h);\n if (!commitHash || commitHash.length !== 32) throw new Error(\"a commit is a 32-byte hash\");\n const { privateKey, pub } = await keyPair(crypto);\n return { sid: commit.sid, privateKey, pub, commitHash, offer: { t: \"offer\", sid: commit.sid, pub: toBase64(pub) } };\n}\n\nasync function pair(\n role: \"viewer\" | \"sharer\",\n sidHex: string,\n parties: ControlParties,\n privateKey: Key,\n viewerPub: Uint8Array,\n sharerPub: Uint8Array,\n crypto: ControlCrypto,\n): Promise<ControlPairing> {\n const theirs = role === \"viewer\" ? sharerPub : viewerPub;\n const peer = await crypto.subtle.importKey(\"raw\", theirs, { name: \"X25519\" }, false, []);\n const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: \"X25519\", public: peer }, privateKey, 256));\n // An all-zero result means the peer sent a low-order point: nothing secret was agreed.\n if (shared.every((b) => b === 0)) throw new Error(\"the other side's key agrees on nothing\");\n const transcript = new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", concat(utf8(TRANSCRIPT_TAG), hexBytes(sidHex), u32(parties.streamId), u32(parties.viewer), u32(parties.sharer), viewerPub, sharerPub)),\n );\n const base = await crypto.subtle.importKey(\"raw\", shared, \"HKDF\", false, [\"deriveKey\"]);\n const derive = (info: string) =>\n crypto.subtle.deriveKey({ name: \"HKDF\", hash: \"SHA-256\", salt: transcript, info: utf8(info) }, base, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\"]);\n const [v2s, s2v] = await Promise.all([derive(\"ftc v2s\"), derive(\"ftc s2v\")]);\n const n = new DataView(transcript.buffer).getUint32(0) % 1_000_000;\n const digits = n.toString().padStart(6, \"0\");\n const channel =\n role === \"viewer\" ? new PairwiseChannel(sidHex, v2s, 0, s2v, 1, crypto) : new PairwiseChannel(sidHex, s2v, 1, v2s, 0, crypto);\n return { sid: sidHex, code: `${digits.slice(0, 3)} ${digits.slice(3)}`, channel };\n}\n\n/** Viewer: the sharer's offer arrived. Returns the pairing and the reveal to send. */\nexport async function finishControlRequest(\n request: ControlRequest,\n offer: ControlMessage & { t: \"offer\" },\n parties: ControlParties,\n crypto: ControlCrypto = webCrypto(),\n): Promise<{ pairing: ControlPairing; reveal: ControlMessage & { t: \"reveal\" } }> {\n if (offer.sid !== request.sid) throw new Error(\"an offer for another request\");\n const sharerPub = fromBase64(offer.pub);\n if (!sharerPub || sharerPub.length !== 32) throw new Error(\"an X25519 public key is 32 bytes\");\n const pairing = await pair(\"viewer\", request.sid, parties, request.privateKey, request.pub, sharerPub, crypto);\n return { pairing, reveal: { t: \"reveal\", sid: request.sid, pub: toBase64(request.pub) } };\n}\n\n/** Sharer: the viewer revealed its key. Null when it is not the key it committed to. */\nexport async function finishControlOffer(\n offer: ControlOffer,\n reveal: ControlMessage & { t: \"reveal\" },\n parties: ControlParties,\n crypto: ControlCrypto = webCrypto(),\n): Promise<ControlPairing | null> {\n if (reveal.sid !== offer.sid) return null;\n const viewerPub = fromBase64(reveal.pub);\n if (!viewerPub || viewerPub.length !== 32) return null;\n const h = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", viewerPub));\n if (!equalBytes(h, offer.commitHash)) return null;\n try {\n return await pair(\"sharer\", offer.sid, parties, offer.privateKey, viewerPub, offer.pub, crypto);\n } catch {\n return null;\n }\n}\n\n/**\n * One grant's two directions. `seal` numbers its messages 1, 2, 3...; `open` takes them only in\n * that order, and reports a GAP (the message is still opened) so the sharer can let go of what it\n * holds. A message at or below the last one opened is a replay and is refused.\n */\nexport class PairwiseChannel {\n private sent = 0;\n private received = 0;\n\n constructor(\n readonly sid: string,\n private readonly sendKey: Key,\n private readonly sendDir: number,\n private readonly recvKey: Key,\n private readonly recvDir: number,\n private readonly crypto: ControlCrypto,\n ) {}\n\n private aad(dir: number): Uint8Array {\n return concat(utf8(PAIR_AAD_TAG), hexBytes(this.sid), Uint8Array.of(dir));\n }\n\n private static iv(counter: number): Uint8Array {\n const iv = new Uint8Array(12);\n new DataView(iv.buffer).setBigUint64(4, BigInt(counter));\n return iv;\n }\n\n async seal(value: unknown): Promise<string> {\n const counter = ++this.sent;\n const ct = new Uint8Array(\n await this.crypto.subtle.encrypt({ name: \"AES-GCM\", iv: PairwiseChannel.iv(counter), additionalData: this.aad(this.sendDir), tagLength: 128 }, this.sendKey, utf8(JSON.stringify(value))),\n );\n const head = new Uint8Array(8);\n new DataView(head.buffer).setBigUint64(0, BigInt(counter));\n return toBase64(concat(head, ct));\n }\n\n /** Null when it does not open, or is a replay. `gap`: messages were skipped before this one. */\n async open(box: string): Promise<{ value: unknown; gap: boolean } | null> {\n const bytes = fromBase64(box);\n if (!bytes || bytes.length < 8 + 16) return null;\n const counter = Number(new DataView(bytes.buffer, bytes.byteOffset).getBigUint64(0));\n if (!Number.isSafeInteger(counter) || counter <= this.received) return null;\n let plain: ArrayBuffer;\n try {\n plain = await this.crypto.subtle.decrypt({ name: \"AES-GCM\", iv: PairwiseChannel.iv(counter), additionalData: this.aad(this.recvDir), tagLength: 128 }, this.recvKey, bytes.subarray(8));\n } catch {\n return null;\n }\n const gap = counter !== this.received + 1;\n this.received = counter;\n try {\n return { value: JSON.parse(new TextDecoder().decode(plain)), gap };\n } catch {\n return null;\n }\n }\n}\n\n/** Words a person reads, for each refusal. No em dashes: this is shown to customers. */\nexport function describeControlDeny(reason: ControlDenyReason, sharer: string): string {\n switch (reason) {\n case \"declined\":\n return `${sharer} did not allow control.`;\n case \"timeout\":\n return `${sharer} did not answer the request to control.`;\n case \"unsupported\":\n // Also what a Linux sharer on a Wayland desktop answers (linuxDesktop.ts): Wayland gives no\n // app a way to drive the rest of the desktop, so \"update the app\" alone would be wrong advice.\n return `${sharer} is sharing from somewhere that cannot be controlled. It works when they share from the latest Service Manager desktop app on Windows, on macOS, or on Linux in an X11 session.`;\n case \"window\":\n return `${sharer} is sharing a window, not a whole screen. Control works on a whole screen only.`;\n case \"permission\":\n return `${sharer}'s computer has not given Service Manager permission to control it yet.`;\n case \"busy\":\n return `Somebody else is controlling ${sharer}'s screen, or asking to.`;\n case \"failed\":\n return `The request to control ${sharer}'s screen could not be checked, so it was stopped.`;\n }\n}\n\nexport function describeControlEnd(reason: ControlEndReason, sharer: string): string {\n switch (reason) {\n case \"revoked\":\n return `${sharer} took back control.`;\n case \"released\":\n return `You let go of ${sharer}'s screen.`;\n case \"ended\":\n return `The share ended, and control with it.`;\n case \"idle\":\n return `Control of ${sharer}'s screen stopped because nothing arrived from you for a few seconds.`;\n case \"error\":\n return `Control of ${sharer}'s screen stopped because something went wrong.`;\n }\n}\n\n/** The same ends, told to the SHARER, about the viewer who had control. */\nexport function describeControlEndForSharer(reason: ControlEndReason, viewer: string): string {\n switch (reason) {\n case \"revoked\":\n return `You took back control from ${viewer}.`;\n case \"released\":\n return `${viewer} stopped controlling your screen.`;\n case \"ended\":\n return `Control by ${viewer} ended with the share.`;\n case \"idle\":\n return `Control by ${viewer} stopped because nothing arrived from them for a few seconds.`;\n case \"error\":\n return `Control by ${viewer} stopped because something went wrong.`;\n }\n}\n","import { z } from \"zod\";\n\n/**\n * What a viewer's tools can do on ONE share, as the SHARER's app knows it (contract §19 \"What the\n * sharer's app can do\"). The sharer announces it on `nativeShare { profile: \"screen\" }` as\n * `tools`, and the node relays it unchanged on `shareStarted`. Descriptive, like `width` and\n * `fps`: the node routes nothing on it and nothing enforces it, so a viewer uses it only to SAY\n * why a tool cannot do its job for this sharer, before or instead of a round trip that ends in\n * silence (a sharer on Linux sees no pointer overlay, one on Wayland cannot be controlled, one in\n * a browser on Linux has no sound to send).\n *\n * Each field is bounded free text on the wire, not an enum, for the reason `codec` is: a sender\n * that learns a new value must not have its whole `nativeShare` refused by an older node's\n * parser, which would take the picture down over a hint. A receiver reads the values below and\n * treats anything else, or an absent field, as \"not said\" (an older sharer's app says nothing,\n * and the viewer then behaves as it always did).\n */\n\n/** Where the sharer sees a viewer's pointer and ink. `screen`: drawn over their real screen. */\nexport const SHARE_MARKS = [\n /** The desktop app draws them over the shared screen, or over the shared window where it can\n * follow it (Windows, 2026-10-05), kept out of the capture. Viewers draw their own copy. */\n \"screen\",\n /** The desktop app draws them on the sharer's screen and they are IN THE PICTURE (the Linux app\n * on X11, 2026-10-05: nothing there can keep a window out of a capture). Viewers see them in\n * the video, a moment late, and must not draw their own copy, or every mark shows twice. */\n \"video\",\n /** A window is shared, and the app cannot follow where it sits. */\n \"window\",\n /** A whole screen is shared and the app could not tell which of the computer's screens it is. */\n \"unplaced\",\n /** The Linux app cannot draw them: a Wayland desktop, where no app may place a window over the\n * others, or a Linux app older than its overlay. */\n \"linux\",\n /** A browser: nothing can draw outside the page. */\n \"browser\",\n /** A desktop app older than the overlay. */\n \"app\",\n] as const;\nexport type ShareMarks = (typeof SHARE_MARKS)[number];\n\n/** Whether the sharer's screen can be controlled at all (consent and permission still apply). */\nexport const SHARE_CONTROL = [\n /** Possibly: a desktop app sharing a whole screen. The sharer is still asked. */\n \"yes\",\n /** A window is shared and the app cannot follow where it sits. */\n \"window\",\n /** A whole screen is shared and the app could not tell which of the computer's screens it is. */\n \"unplaced\",\n /** A Linux Wayland session: no app may drive the rest of the desktop there. */\n \"wayland\",\n /** A browser cannot move a mouse. */\n \"browser\",\n /** A desktop app older than remote control. */\n \"app\",\n] as const;\nexport type ShareControl = (typeof SHARE_CONTROL)[number];\n\n/** Why the share does, or does not, carry its sound. */\nexport const SHARE_SOUND = [\n /** A `screen-audio` stream goes with it. */\n \"sent\",\n /** The sharer did not include sound, or the platform offered none. */\n \"off\",\n /** Sound was captured and left out: it would have carried the call back to everybody. */\n \"unsafe\",\n /** A browser on Linux, which cannot capture a screen's sound. The Linux app can. */\n \"linux-browser\",\n /** The Linux app with its Share sound switch off (apps before the Sound picker, 2026-10-02). */\n \"linux-off\",\n /** The sharer picked a sound and it could not be captured: a failure, not a choice. */\n \"failed\",\n] as const;\nexport type ShareSound = (typeof SHARE_SOUND)[number];\n\n/**\n * What the SHARER allows (2026-10-05, owner: the streamer's Allow drawing and Allow control\n * switches). Unlike the three fields above these are ENFORCED: the node drops every viewer's\n * pointer and ink on a share whose `allowMarks` is \"no\", and every viewer's control message on\n * one whose `allowControl` is \"no\", and a viewer hides the matching buttons. Absent means\n * allowed, which is every share before the switches existed (a call's included).\n *\n * `allowCopy` (2026-10-05, owner: a third switch, Allow copy text) is the one that is NOT\n * enforced, and cannot be: Copy text reads a still on the VIEWER's own device (client\n * share/ocr/), from pixels that viewer already has, so the node has nothing to drop. It is a\n * courtesy the viewer's app honours by hiding Copy text, never a security boundary. The node\n * relays it like the rest; a container that predates it strips it, which reads as allowed.\n */\nexport const SHARE_ALLOW = [\"yes\", \"no\"] as const;\nexport type ShareAllow = (typeof SHARE_ALLOW)[number];\n\nexport interface ShareTools {\n marks?: ShareMarks;\n control?: ShareControl;\n sound?: ShareSound;\n allowMarks?: ShareAllow;\n allowControl?: ShareAllow;\n allowCopy?: ShareAllow;\n}\n\nconst hint = z.string().min(1).max(24);\n\n/** The wire shape, for `nativeShare`, `shareStarted` and `shareTools`. Unknown keys are stripped. */\nexport const ShareToolsWireSchema = z.object({\n marks: hint.optional(),\n control: hint.optional(),\n sound: hint.optional(),\n allowMarks: hint.optional(),\n allowControl: hint.optional(),\n allowCopy: hint.optional(),\n});\nexport type ShareToolsWire = z.infer<typeof ShareToolsWireSchema>;\n\nfunction known<T extends string>(list: readonly T[], v: unknown): T | undefined {\n return typeof v === \"string\" && (list as readonly string[]).includes(v) ? (v as T) : undefined;\n}\n\n/** A received `tools`, down to the values this build knows. Anything else reads as not said. */\nexport function readShareTools(wire: unknown): ShareTools {\n if (!wire || typeof wire !== \"object\") return {};\n const w = wire as Record<string, unknown>;\n const out: ShareTools = {};\n const marks = known(SHARE_MARKS, w.marks);\n const control = known(SHARE_CONTROL, w.control);\n const sound = known(SHARE_SOUND, w.sound);\n const allowMarks = known(SHARE_ALLOW, w.allowMarks);\n const allowControl = known(SHARE_ALLOW, w.allowControl);\n const allowCopy = known(SHARE_ALLOW, w.allowCopy);\n if (marks) out.marks = marks;\n if (control) out.control = control;\n if (sound) out.sound = sound;\n if (allowMarks) out.allowMarks = allowMarks;\n if (allowControl) out.allowControl = allowControl;\n if (allowCopy) out.allowCopy = allowCopy;\n return out;\n}\n\n/** Whether the sharer allows viewers' pointer and ink (absent: allowed). The node's check. */\nexport function marksAllowed(tools: { allowMarks?: string } | undefined): boolean {\n return tools?.allowMarks !== \"no\";\n}\n\n/**\n * Whether the sharer's app can honour Point and Draw on this share (2026-10-05, owner: viewers do\n * not see a tool the sharer's side cannot honour). Not said, or a value this build does not know\n * (`readShareTools` drops those), counts as able: that is how every viewer behaved before.\n */\nexport function marksSupported(tools: { marks?: string } | undefined): boolean {\n const m = tools?.marks;\n return m === undefined || m === \"screen\" || m === \"video\" || !(SHARE_MARKS as readonly string[]).includes(m);\n}\n\n/** Whether the marks are in the picture itself (`video`): a viewer then draws no copy of its own. */\nexport function marksInVideo(tools: { marks?: string } | undefined): boolean {\n return tools?.marks === \"video\";\n}\n\n/** Whether this share can be controlled at all, as its sharer's app said. Not said counts as able. */\nexport function controlSupported(tools: { control?: string } | undefined): boolean {\n const c = tools?.control;\n return c === undefined || c === \"yes\" || !(SHARE_CONTROL as readonly string[]).includes(c);\n}\n\n/** Whether the sharer allows viewers to ask for control (absent: allowed). The node's check. */\nexport function controlAllowed(tools: { allowControl?: string } | undefined): boolean {\n return tools?.allowControl !== \"no\";\n}\n\n/** Whether the sharer allows viewers' Copy text (absent: allowed). A courtesy the VIEWER's app honours: nothing enforces it. */\nexport function copyAllowed(tools: { allowCopy?: string } | undefined): boolean {\n return tools?.allowCopy !== \"no\";\n}\n","import { z } from \"zod\";\n\n/**\n * The machine-readable error catalogue.\n *\n * Every failure the control plane returns has the shape `{ error: { code, message } }`\n * (see the error handler in server/control-plane/src/index.ts). The shape was already\n * consistent; the CODES were not published anywhere — they existed only as string\n * literals scattered across ~15 route modules, so an integrator had to read the server\n * source to learn what they could receive. With several clients now integrating (web,\n * Tuner, a HAM scanner, a lightweight talk app), branching on a code you discovered by\n * hitting the error in development is not a contract.\n *\n * `message` is human-facing prose, may be reworded at any time, and is NOT part of the\n * contract. Branch on `code`. Codes are additive: a new one may appear in any release, so\n * treat an unrecognised code as a generic failure of its HTTP status rather than crashing.\n *\n * `status` records the status the server actually sends today, so the code can be\n * documented in OpenAPI against the right response. It is a description of current\n * behaviour, not a second source of truth — read the real status off the response.\n *\n * REMOVED: `COMPANY_CONTACT_REQUIRED` (2026-08-02, with the company/station split). Every\n * path that returned it now returns `ORGANIZATION_REQUIRED`, which says the same thing and\n * also covers \"give an existing company's id instead\". Advertised by the\n * `station-on-frequency` capability; a client still branching on the old code falls through\n * to its generic 422 handling.\n */\nexport const ERROR_CODES = {\n // --- Request validation -------------------------------------------------------------\n VALIDATION_ERROR: { status: 400, summary: \"The request body, query or params failed schema validation.\" },\n INVALID_SIGNATURE: { status: 400, summary: \"A signed payload (Stripe webhook, media-node callback) failed signature verification.\" },\n\n // --- Authentication -----------------------------------------------------------------\n UNAUTHENTICATED: { status: 401, summary: \"Missing, malformed or expired access token.\" },\n INVALID_CODE: { status: 401, summary: \"The emailed six-digit login code is wrong, expired, or out of attempts.\" },\n INVALID_REFRESH: { status: 401, summary: \"The refresh token is unknown, already used, or revoked.\" },\n WEBAUTHN_FAILED: { status: 401, summary: \"WebAuthn assertion or attestation could not be verified.\" },\n NO_PASSKEY_ENROLLED: {\n status: 400,\n summary:\n \"This account has no passkey, so it cannot confirm with one. Defensive: a client should offer the passkey \" +\n \"factor only after listing the account's credentials. Use the emailed code instead.\",\n },\n SIGNUP_REQUIRED: {\n status: 422,\n summary:\n \"First-ever login for this email: resubmit verify-code with `handle`. `displayName` is OPTIONAL and defaults to the account's Station ID — it was required until 2026-08-25, so a client that still sends both is correct and unchanged. Not a failure — it is the second step of signup, and the login code stays valid for the retry. \" +\n \"Only talk apps see this (capability `email-only-listeners`): a listen-only app's first login creates the account from the email alone.\",\n },\n CALLSIGN_REQUIRED: {\n status: 422,\n summary:\n \"This app requires a callsign and the account has none (it was created by a listen-only app from an email alone). From `/auth/verify-code`: resubmit the SAME login code with `handle` (and optionally `displayName`) to set it — like SIGNUP_REQUIRED, the code is not consumed by this rejection. From `/auth/webauthn/login-verify` (capability `passkey-callsign-gate`) the retry needs a FRESH assertion instead: a login code survives an answerable rejection, a WebAuthn challenge does not, so run the ceremony again with `handle` in the body. Also sent as 403 by transmit gates when a callsign-less token attempts to arm transmit.\",\n },\n PROFANE_CALLSIGN: {\n status: 400,\n summary:\n \"The requested callsign failed the profanity screen — the SAME predicate the signup handle has always used, surfaced here under its own code so a client can tell it from a charset or length refusal. `message` is presentable prose.\",\n },\n CALLSIGN_RENAME_COOLDOWN: {\n status: 409,\n summary:\n \"A callsign may only be changed once per cooldown window (30 days by default). `details` carries `unlockAt` (ISO 8601), `retryAfterSeconds` and `cooldownDays`, so the client can name the date instead of saying \\\"not yet\\\".\",\n },\n SESSION_CONFLICT: {\n status: 409,\n summary:\n \"This account is already signed in to another install of the same app, and the caller runs a broadcast station, so the older session is NOT closed automatically — interrupting a live show has to be a decision. `details.sessions` describes the other session(s), including whether one is transmitting right now. Resubmit the SAME login code with `signOutOtherSessions: true` to take over, or abandon the login. Like SIGNUP_REQUIRED, the code is not consumed by this rejection.\",\n },\n\n BROADCAST_ELSEWHERE: {\n status: 409,\n summary:\n \"One location per frequency (capability `one-location-per-frequency`): this account has a LIVE broadcast on this station from another install, and tuning in here would take that install off the frequency and the station off the air. Nothing was changed and nothing was consumed. `message` is presentable prose naming the station; `details.station` carries the name alone. Ask the user, then resend the same tune with `takeOver: true`, or abandon it.\",\n },\n FREQUENCY_OPENED_ELSEWHERE: {\n status: 409,\n summary:\n \"One location per frequency: a `resume: true` tune (an automatic reconnect) from an install the frequency has since moved away from. The account tuned in to it from another install, which now holds it. Drop the frequency locally exactly as on a `frequency.displaced` push, and do not retry. A deliberate tune (no `resume`) takes it back.\",\n },\n\n TOO_MANY_NOTICES: {\n status: 400,\n summary:\n \"Too many operator notices are already active to post another (`POST /internal/system/notices`). Internal/operator surface only — no end-user client can reach it. Withdraw an existing notice first; expired ones are pruned automatically and do not count.\",\n },\n\n // --- Authorisation ------------------------------------------------------------------\n FORBIDDEN: { status: 403, summary: \"Authenticated, but this user may not perform this action.\" },\n NOT_MEMBER: {\n status: 403,\n summary:\n \"The user is not a member of the target frequency. Also sent as 404 where membership is what makes the resource visible, and as 422 on operations that act on an existing membership.\",\n },\n NOT_ORG_MEMBER: { status: 403, summary: \"The user is not a member/staff of the target organization.\" },\n ACCESS_CODE_REQUIRED: {\n status: 403,\n summary:\n \"This frequency is access-code protected and the request carried no code. The station EXISTS at that number — intended design (owner decision 2026-08-06): sweeping the band can learn where private stations are, never what they are or who runs them.\",\n },\n ACCESS_CODE_INVALID: {\n status: 403,\n summary:\n \"An access code was supplied and it is wrong. Split from ACCESS_CODE_REQUIRED (additive, §8) so a client can react to a bad guess distinctly from a missing code. Wrong codes are rate-limited per user, and repeated wrong codes against one frequency earn a temporary automatic ban.\",\n },\n FREQUENCY_SUSPENDED: {\n status: 403,\n summary:\n \"The FREQUENCY is off the air — a platform or billing action against the station itself, not against the caller (contrast BANNED, which is about one person). `details.suspensionClass` is non_payment | voluntary | conduct | legal and `details.reinstatable` says whether the owner can lift it from the app; for non_payment and voluntary that means holding a live subscription again and calling POST /frequencies/{id}/reinstate. Nothing has been deleted: every station field survives a suspension, so keep showing the station and refuse only to tune it. ONE exception, and it is the only class that is not indefinite — a `voluntary` suspension raised by cancelling during the free trial also DELETES the station when that trial would have ended, because the customer is reclaiming a station they never paid for; reinstating at any point before then cancels the deletion.\",\n },\n BANNED: {\n status: 403,\n summary:\n \"This user is banned from the target frequency — by its admins, or automatically after too many wrong access-code attempts (those bans expire on their own). Joining, tuning by number and invitations are all refused until the ban is lifted or lapses.\",\n },\n FEEDBACK_BLOCKED: {\n status: 403,\n summary:\n \"This ACCOUNT may not send feedback (bug reports or feature requests): it was blocked after abusive submissions, or by an operator. It is account-wide, so it holds in every app, and it lasts until an operator lifts it. Not retryable. A client hides its feedback entry point on this answer, exactly as it does for `maySendFeedback: false` on the profile and for the `user.feedback` event.\",\n },\n INSUFFICIENT_SCOPE: {\n status: 403,\n summary:\n \"The access token's `scope` claim does not cover this operation; `details.requiredScope` names the missing one. Re-authenticating helps ONLY if the client's registered scopes have since widened — a session carries its original grant across rotation and never re-reads the client's allowlist, so a token issued before a grant stays narrow until the operator authorises again. If the client was never granted the scope, re-authenticating changes nothing.\",\n },\n INVALID_CLIENT: { status: 401, summary: \"Unknown, disabled, or wrongly-authenticated OAuth client_id.\" },\n HUMAN_ONLY: {\n status: 403,\n summary:\n \"The caller is an agent account (`users.kind = agent`, contract §25) and this operation is for a person's account only: passkeys, the account-deletion code, companies, phone numbers, Stripe mutations, sponsoring agents. Not retryable: it is a property of the account, not of the token or its scopes.\",\n },\n AGENT_ONLY: {\n status: 403,\n summary:\n \"The caller is a person and this route is an agent account's own surface (`/v1/agents/me/*`, contract §25). A person manages the agents they sponsor through `/v1/users/me/agents` instead.\",\n },\n AGENT_REGISTRATION_CLOSED: {\n status: 403,\n summary:\n \"Self-serve agent registration (`POST /v1/agents/register`) is switched off on this deployment. A person can still create a sponsored agent from their own account. Not retryable until an operator reopens it.\",\n },\n AGENT_ACCOUNT_KEY_INVALID: {\n status: 401,\n summary:\n \"The agent account key presented to `POST /v1/auth/agent` is unknown, revoked, expired, or not an agent account key at all. One answer for every case, deliberately. Not retryable with the same key: mint a new one from a session that still works, or ask the sponsor to.\",\n },\n AGENT_KEY_LIMIT: {\n status: 409,\n summary:\n \"The agent account already holds its maximum number of live keys (`liveKeysMax` on the key list). Delete one, then mint again. Rotation is mint-then-delete, so one slot is always free for the next key.\",\n },\n AGENT_LIMIT: {\n status: 409,\n summary:\n \"This person already sponsors the maximum number of agents (`max` on `GET /v1/users/me/agents`). Delete one before creating another.\",\n },\n SPONSORED_AGENT: {\n status: 403,\n summary:\n \"The caller is a SPONSORED agent (created by a person from their account, contract §25) and this is something its sponsor does: minting its keys and deleting it are `/v1/users/me/agents/*` from the sponsor's account. Not retryable.\",\n },\n SPONSORS_AGENTS: {\n status: 409,\n summary:\n \"The account cannot be deleted while it sponsors agents: `details.agents` is `[{id, handle, stationId}]`. Delete each sponsored agent (`DELETE /v1/users/me/agents/{id}`), then retry; like the other deletion blockers it consumes neither confirmation factor.\",\n },\n CREDIT_FUNDED_SUBSCRIPTION: {\n status: 409,\n summary:\n \"This subscription row is funded from the account's prepaid credit (`fundedBy: credit`, no Stripe subscription behind it), so the card-processor operations (cancel, resume, plan change, card on file, invoices) do not apply. Top up credit, or let the balance run out to stop. Not retryable.\",\n },\n MACHINE_PAYMENTS_NOT_CONFIGURED: {\n status: 503,\n summary:\n \"This server takes no machine payments: `POST /v1/billing/credit/topup` has no rail to challenge with (no Stripe key and profile, and not a development server). Not retryable until an operator configures it; `rails` on `GET /v1/billing/credit` is empty meanwhile.\",\n },\n\n // --- Missing resources --------------------------------------------------------------\n NOT_FOUND: { status: 404, summary: \"The addressed resource does not exist, or is not visible to this caller.\" },\n USER_NOT_FOUND: { status: 404, summary: \"No user matches the supplied handle, Station ID or email.\" },\n INVITE_INVALID: { status: 404, summary: \"The invite or invite link is unknown, expired, revoked, or fully used.\" },\n NO_BILLING_ACCOUNT: { status: 404, summary: \"No billing account exists for this organization yet.\" },\n NOT_LINKED: { status: 422, summary: \"The expected link (billing account, OAuth identity) is not established.\" },\n\n // --- Conflicts ----------------------------------------------------------------------\n INVITE_LINK_LIMIT: {\n status: 409,\n summary: \"The frequency (or organization) already carries the maximum number of live invite links — revoke one or let one expire.\",\n },\n FREQUENCY_TAKEN: { status: 409, summary: \"That frequency number is already allocated.\" },\n STATION_NAME_TAKEN: { status: 409, summary: \"Another station already uses that name.\" },\n STATION_CALLSIGN_TAKEN: { status: 409, summary: \"Another station already uses that callsign (callsigns are globally unique).\" },\n ALREADY_MEMBER: { status: 409, summary: \"The user is already a member of this frequency/organization.\" },\n ALREADY_INVITED: { status: 409, summary: \"An unaccepted invite for this user already exists.\" },\n AMBIGUOUS_HANDLE: { status: 409, summary: \"Several users share that callsign — address them by Station ID or email instead.\" },\n ALREADY_CONTACTS: { status: 409, summary: \"You are already contacts with that person.\" },\n CONTACT_REQUEST_PENDING: { status: 409, summary: \"A request between you and that person is already outstanding — accept theirs, or wait for yours to be answered.\" },\n CONTACT_LIMIT: { status: 409, summary: \"One of the two contact lists is full.\" },\n CALL_BUSY: {\n status: 409,\n summary:\n \"That person's ring queue is full, or their status is Busy. Returned ONLY when they are already visible to the caller. Distinct from CALL_UNAVAILABLE, which answers for a callee who reads `offline`: the two are never both applicable, because `busy` is by definition not `offline`, so a caller can tell 'they are here and cannot take it' from 'they are not here' — and can already tell both from their own contact list.\",\n },\n CALL_UNAVAILABLE: {\n status: 409,\n summary:\n \"Nobody the call was addressed to is reachable — every invitee reads `offline` to this caller. Answered immediately so the caller hears a busy signal instead of a 45-second ring-out at a closed app. This is NOT a presence oracle: it is derived from the same `visibleStatuses` read that already answers the caller's contact list, so an invisible callee produces this code at this speed exactly as a genuinely offline one does, and a blocked-or-muted callee who is offline is indistinguishable from either. A call with even one reachable invitee is placed as normal, and the unreachable ones are masked exactly as before.\",\n },\n CONTACT_BUSY: {\n status: 409,\n summary:\n \"The recipient's status is Busy, which refuses chats and waves outright — nothing is queued, so re-send later rather than expecting it to arrive. Like CALL_BUSY, returned ONLY when they are already visible to the sender: an invisible recipient reads as offline and their chat is accepted normally, because a refusal that only Busy could produce would be a presence oracle.\",\n },\n CONTACT_AWAY: {\n status: 409,\n summary:\n \"The recipient is Away and a wave needs somebody there to receive it — chats to an Away recipient are accepted and sit unread. Masked exactly like CONTACT_BUSY: only returned when they are already visible to the sender.\",\n },\n CHAT_CHANGED: {\n status: 409,\n summary:\n \"That group chat's members changed while you were acting on it (somebody else added a member or left first), so the group you named no longer exists. A `chat.membership` frame names where it went; act on that one.\",\n },\n CHAT_GROUP_FULL: { status: 409, summary: \"A group chat holds at most CHAT_GROUP_MAX_MEMBERS people.\" },\n ALREADY_IN_CHAT: { status: 409, summary: \"That person is already in this chat.\" },\n CONTACT_BLOCKED: {\n status: 403,\n summary:\n \"A block exists between the two accounts, in one direction or the other. Deliberately does not say WHICH — telling a blocked person they were blocked is an invitation to route around it.\",\n },\n\n // --- Domain rules -------------------------------------------------------------------\n CANNOT_BAN_OWNER: { status: 422, summary: \"The frequency's owner cannot be banned from it.\" },\n INVALID_FREQUENCY: { status: 422, summary: \"The frequency number is outside the band plan or off its channel grid.\" },\n HAM_NUMBER_REQUIRED_FOR_PTT: { status: 422, summary: \"A push-to-talk frequency must be allocated a HAM-band number.\" },\n STATION_REQUIRED_FOR_BROADCAST: { status: 422, summary: \"A broadcast frequency needs an on-air callsign and a company to own it.\" },\n NOT_A_STATION: { status: 422, summary: \"That frequency is not a broadcast station, so it has no on-air identity to read or change.\" },\n NOT_LISTENING: { status: 403, summary: \"A Cheer or Hush comes from somebody listening: the caller has no open listen on that station, on any transport.\" },\n NOTHING_PLAYING: {\n status: 409,\n summary: \"There is nothing to cheer or hush: the station has published nothing as now playing, or it is off the air. `nowPlaying.since` is null whenever this would be the answer.\",\n },\n ORGANIZATION_REQUIRED: {\n status: 422,\n summary:\n \"A company is required: give the id of one of your own (GET /orgs/mine) or the contact details to create a new one — exactly one, never both. Company names are not lookup keys.\",\n },\n UNSUPPORTED_COUNTRY: { status: 422, summary: \"The supplied country is not in the platform's supported-country allowlist.\" },\n AGE_ATTESTATION_REQUIRED: {\n status: 422,\n summary:\n \"The request must attest the account holder is at least 18 / the age of majority (ageConfirmed: true). details carries termsUrl + docVersion. Enforced on POST /frequencies and POST /billing/subscribe by servers advertising the \\\"age-attestation\\\" capability; the acceptance is durably recorded.\",\n },\n TERMS_ACCEPTANCE_REQUIRED: {\n status: 422,\n summary:\n \"The request must accept the Terms of Service (termsAccepted: true). details carries termsUrl + docVersion. Enforced on POST /frequencies, POST /billing/subscribe and both plan-change completions by servers advertising the \\\"terms-acceptance\\\" capability; the acceptance is durably recorded. First-party clients collect this with the age attestation in ONE checkbox, so the two arrive together.\",\n },\n DEFAULT_CHANNEL_IMMUTABLE: { status: 422, summary: \"The frequency's default channel cannot be renamed, moved or deleted.\" },\n MOVE_GRANT_REQUIRED: {\n status: 403,\n summary:\n \"POST /calls/:callId/move would leave somebody behind, and the request did not ask to grant them access. Re-send with grantAccess: true if the caller may grant it, or pick a destination everybody can already reach — GET /calls/:callId/destinations lists only the ones that work. details carries wouldGrantCount. It deliberately does NOT name who is missing: a banned participant is skipped silently, and naming the gap would leak their ban by elimination.\",\n },\n TUNING_ACCESS_REQUIRED: {\n status: 422,\n summary:\n \"PUT /frequencies/:id/members/:userId/tuning-state would put the member on a channel they may not use, and nothing was changed. details.channelIds lists the channels they lack access to: re-send with grantAccess: true to give it. details.forceMutedChannelIds lists talk channels they are force-muted on, which grantAccess never lifts: clear the force-mute first.\",\n },\n TUNING_CHANNEL_INVALID: {\n status: 422,\n summary:\n \"A channel id in a member tuning change is not one it may name: not a group channel of this frequency (talk.remove may also name the member's own personal channel). details.channelIds lists them. Nothing was changed.\",\n },\n TUNING_PROGRAM_CHANNEL: {\n status: 422,\n summary:\n \"A member tuning change tried to ADD talk on a broadcast station's default channel. A station is never armed remotely; whoever goes on the air switches it on themselves. Removing talk there is allowed.\",\n },\n PERSONAL_CHANNEL_IMMUTABLE: { status: 422, summary: \"A personal channel cannot be edited or have its membership changed.\" },\n PHONE_CHANNEL_IMMUTABLE: {\n status: 422,\n summary: \"A phone channel (capability phone-numbers) cannot be deleted or have its talk permission changed; release the number instead.\",\n },\n PHONE_NOT_CONFIGURED: { status: 503, summary: \"This deployment has no carrier configured, so no phone number can be searched, bought or released.\" },\n PHONE_NUMBER_UNAVAILABLE: { status: 409, summary: \"The number was taken between the search and the purchase, or is already ours. Search again.\" },\n PHONE_SUBSCRIPTION_REQUIRED: { status: 402, summary: \"Buying a number needs a paid, unclaimed phone line subscription (capability phone-numbers).\" },\n CARRIER_ERROR: { status: 502, summary: \"The carrier refused or did not answer. Nothing was changed on our side unless the message says otherwise; retry later.\" },\n PROTECTED_MEMBER: {\n status: 403,\n summary:\n \"Company staff using a station's channel controls (capability station-staff-channels) tried to remove, clear, or change the talk of the frequency's owner, an admin, or staff who outrank them. A clear-all including one is refused whole.\",\n },\n ORG_MANAGED_GROUP: { status: 422, summary: \"This group's membership is derived from its organization — edit the organization instead.\" },\n ORG_STAFF_MEMBER: { status: 422, summary: \"This member is organization staff — remove them from the organization instead.\" },\n ORG_HAS_FREQUENCIES: { status: 422, summary: \"The organization still owns frequencies; delete or reassign them first.\" },\n CANNOT_REMOVE_OWNER: { status: 422, summary: \"The owner cannot be removed from their own frequency/organization.\" },\n CANNOT_CHANGE_OWNER: { status: 422, summary: \"The owner's role cannot be changed.\" },\n OWNER_CANNOT_LEAVE: { status: 422, summary: \"The owner cannot leave; transfer ownership or delete instead.\" },\n OWNS_FREQUENCIES: {\n status: 409,\n summary:\n \"Account deletion is blocked while the account still owns frequencies: deleting would take other people's frequencies with it. details.frequencies lists each one (id, khz, name, mode, memberCount) — transfer ownership (POST /frequencies/:id/transfer-ownership) or delete each, then retry.\",\n },\n ACTIVE_SUBSCRIPTION: {\n status: 409,\n summary:\n \"Account deletion is blocked by a live subscription (owner policy: the deletion flow never cancels billing as a side effect). details.subscriptions lists them. Cancel through the normal billing path first; a subscription set to cancel at period end still blocks until it has fully ended. Retry deletion after.\",\n },\n // --- Chat file transfers (capability `contact-file-transfer`, contract §20) --------------\n FILE_TOO_LARGE: { status: 422, summary: \"The offered file is larger than this service allows (GET /contacts/transfers/config names the limit), or a voice message is longer than allowed.\" },\n TRANSFER_NOT_ALLOWED: { status: 409, summary: \"That transfer cannot do that from its current state, or you are not the side that may (only the recipient accepts, declines or reports complete).\" },\n RETRY_LIMIT: { status: 409, summary: \"This transfer has been retried as many times as the service allows (GET /contacts/transfers/config names the number). The sender has to offer the file again.\" },\n TOO_MANY_TRANSFERS: { status: 409, summary: \"You already have as many transfers running as this service allows at once. Wait for one to finish.\" },\n LOGO_TOO_LARGE: { status: 422, summary: \"The uploaded logo exceeds the maximum byte size.\" },\n LOGO_UNREADABLE: { status: 422, summary: \"The uploaded logo could not be decoded as PNG, JPEG or WebP.\" },\n\n // --- Avatars (capability `user-avatar`) ------------------------------------------------\n UNKNOWN_AVATAR: {\n status: 400,\n summary:\n \"The avatar id is not in this deployment's library, or has been retired. Re-read GET /avatars; setting `avatar: null` is always accepted.\",\n },\n AVATAR_ID_TAKEN: { status: 409, summary: \"An avatar already exists with that id. Ids are permanent — replace its artwork instead.\" },\n AVATAR_IMAGE_TOO_LARGE: { status: 422, summary: \"The uploaded avatar artwork exceeds the maximum byte size.\" },\n AVATAR_IMAGE_UNREADABLE: { status: 422, summary: \"The uploaded avatar artwork could not be decoded as PNG, JPEG or WebP.\" },\n AVATAR_HOLDER_COUNT_STALE: {\n status: 409,\n summary:\n \"The purge was refused: the number of accounts holding this avatar has changed since the console read it. Re-read and confirm again — a purge clears every holder's choice, so it must not run on a stale count.\",\n },\n SOUND_CHOOSER_COUNT_STALE: {\n status: 409,\n summary:\n \"The purge was refused: the number of per-contact settings using this sound has changed since the console read it. Re-read and confirm again — a purge clears every chooser's setting, so it must not run on a stale count.\",\n },\n\n // --- Billing ------------------------------------------------------------------------\n SUBSCRIPTION_REQUIRED: { status: 402, summary: \"This action needs an active subscription on the owning organization.\" },\n SETUP_NOT_COMPLETED: { status: 422, summary: \"Card setup has not finished for this billing account.\" },\n TAX_LOCATION_REQUIRED: {\n status: 422,\n summary:\n \"Sales tax could not be calculated because the customer has no usable billing location. Sales tax is charged on top of the listed price (the Prices are tax_behavior: exclusive), so a subscription cannot be created without one. The location is normally taken from the card's country + postal code, so this means a payment method carrying no country at all — the caller should retry with a card that has a billing address.\",\n },\n SUBSCRIPTION_NOT_RESUMABLE: { status: 422, summary: \"The subscription has fully ended; start a new subscription instead of resuming.\" },\n PLAN_CHANGE_NOT_ALLOWED: {\n status: 422,\n summary:\n \"The subscription cannot change plan: wrong direction for its current plan, not active/trialing (fix payment first), or not claimed by a frequency.\",\n },\n PAYMENT_FAILED: { status: 422, summary: \"The card was declined when the plan-change subscription tried to charge; nothing was changed.\" },\n COMPANY_RELEASE_REQUIRED: {\n status: 422,\n summary:\n \"Downgrading to push-to-talk deletes the station's stored company information — the request must confirm the release (companyInfoReleaseAccepted: true).\",\n },\n\n // --- Agent API keys (dev-codebase agents; internal/operator surface) ------------------\n AGENT_KEY_REQUIRED: {\n status: 401,\n summary:\n \"The request carried no x-agent-key header. Agent keys are minted through a human login (npm run agent:login); the agent must ask its operator to run it. Internal/operator surface only — end-user clients never see this.\",\n },\n AGENT_KEY_INVALID: {\n status: 401,\n summary:\n \"The presented agent key is unknown, expired, or revoked. Not retryable with the same key: ask the operator to re-run the login client to mint a fresh one. Internal/operator surface only — end-user clients never see this.\",\n },\n\n // --- Rate limiting ------------------------------------------------------------------\n RATE_LIMITED: { status: 429, summary: \"Too many requests. Back off and retry; see the Retry-After header.\" },\n\n // --- Server / upstream --------------------------------------------------------------\n INTERNAL_ERROR: { status: 500, summary: \"Unhandled server error. Safe to retry idempotent requests.\" },\n EMAIL_DELIVERY_FAILED: { status: 502, summary: \"The login-code email could not be handed to the mail provider.\" },\n SMTP_SEND_FAILED: {\n status: 502,\n summary:\n \"An operator-triggered SMTP test message could not be delivered; the message carries the provider's own text. Internal/admin surface only — clients never see this.\",\n },\n BILLING_NOT_CONFIGURED: { status: 503, summary: \"Billing is not configured on this deployment.\" },\n OAUTH_NOT_CONFIGURED: { status: 503, summary: \"The requested OAuth provider is not configured on this deployment.\" },\n UNKNOWN_MEDIA_NODE: { status: 410, summary: \"The media node backing this frequency is gone; re-tune to be placed on a new one.\" },\n NATIVE_TRANSPORT_DISABLED: {\n status: 404,\n summary:\n \"The native transport is not enabled on this deployment, so no channel-key material exists to serve. Internal surface only (the media node's bridge key poll) — clients never see this.\",\n },\n GENERATION_NOT_CLEARED: {\n status: 409,\n summary:\n \"A media node asked for bridge channel keys under a generation that is not the stored, cleared one (its boot id has not completed the §3.2 handshake). Ordinary during a container restart: the node retries on its poll cadence after clearance. Internal surface only — clients never see this.\",\n },\n MEDIA_NODE_NOT_RUNNING: {\n status: 409,\n summary:\n \"Native channel keys were requested for a frequency whose media node is not running, so there is no cleared generation to bind them to. Ordinary, not a fault: the container is idle-swept or still booting. Re-tune when it returns — that is when a client needs a fresh native identity anyway.\",\n },\n SHARE_NOT_ALLOWED: {\n status: 403,\n summary:\n \"A tune with `shareIntent` from a member who holds talk permission on no channel of the frequency, so the share container would refuse every share. Nothing is built. Not a sign-out and not retryable as-is: the member needs talk somewhere first.\",\n },\n SHARE_NODE_NOT_RUNNING: {\n status: 409,\n summary:\n \"The share key was requested for a frequency whose share container is not running with a cleared generation. Ordinary, not a fault: nobody is sharing, or the container is still booting. Wait for `shareNode.status` `running` and re-tune.\",\n },\n OFF_AIR: {\n status: 503,\n summary:\n \"The station is not broadcasting right now (the listen tier is transmit-gated). Not a fault: render static/off-air UI and retry with backoff rather than surfacing an error.\",\n },\n TICKET_EXPIRED: {\n status: 401,\n summary:\n \"The listen ticket on this request is missing, expired, or was minted for a different frequency. Not a sign-out: mint a fresh ticket via POST /listen/:frequencyId/ticket (refreshing the access token first if that returns UNAUTHENTICATED) and restart playback with the new playlist URL.\",\n },\n STREAM_CONFLICT: {\n status: 409,\n summary:\n \"One live stream per account per frequency, whichever transport it arrives over (WebRTC or the HLS listen route). The newest request always wins the lease, so receiving this means THIS client is the one that was displaced by a newer stream elsewhere on the account. Show 'playing somewhere else' and stop; do not retry in a loop, which would fight the other client for the lease.\",\n },\n LOAD_TEST_MINT_FAILED: {\n status: 400,\n summary:\n \"Synthetic load-test identities could not be minted (unknown frequency, or it has no default channel to subscribe to). Internal/operator surface only — clients never see this.\",\n },\n LOAD_TEST_PROVISION_FAILED: {\n status: 400,\n summary:\n \"The frequencies a load run puts under load could not be created (dial space exhausted, or the count exceeded LOAD_TEST_MAX_FREQUENCIES). A run creates its own frequencies so that no existing station can be targeted; each one is a container. Internal/operator surface only — clients never see this.\",\n },\n LOAD_TEST_DISABLED: {\n status: 503,\n summary:\n \"Load testing is switched off on this deployment. A superadmin turns it on in the admin console (Settings → Load testing); it is off by default and should be switched back off after a measurement session. Internal/operator surface only.\",\n },\n} as const satisfies Record<string, { status: number; summary: string }>;\n\nexport type ErrorCode = keyof typeof ERROR_CODES;\n\nexport const ERROR_CODE_NAMES = Object.keys(ERROR_CODES) as [ErrorCode, ...ErrorCode[]];\n\nexport const ErrorCodeSchema = z.enum(ERROR_CODE_NAMES);\n\n/**\n * The single error envelope every failing control-plane response uses.\n *\n * `code` is deliberately a plain string here, NOT ErrorCodeSchema. A client pinned to an\n * older build of this package must not fail to parse an error just because the server has\n * since added a code — that would turn a routine \"new error type\" release into a hard\n * break for every consumer that validates responses, and it would fail at the worst\n * moment, while something is already going wrong. Parse permissively; narrow with\n * `isErrorCode()` when you want to branch. ErrorCodeSchema is for documenting the spec\n * and for exhaustive handling, not for validating the wire.\n */\nexport const ApiErrorSchema = z.object({\n error: z.object({\n /** Stable, machine-readable. Branch on this — see isErrorCode. */\n code: z.string().describe(`One of: ${ERROR_CODE_NAMES.join(\", \")}. Unknown codes may be added at any time.`),\n /** Human-facing prose. Not part of the contract — do not parse or match on it. */\n message: z.string(),\n /** Optional structured context; shape varies by code. */\n details: z.unknown().optional(),\n }),\n});\nexport type ApiError = z.infer<typeof ApiErrorSchema>;\n\nexport function isErrorCode(value: unknown): value is ErrorCode {\n return typeof value === \"string\" && value in ERROR_CODES;\n}\n\n/** The status this code is documented as using. See the note on ERROR_CODES.status. */\nexport function statusForErrorCode(code: ErrorCode): number {\n return ERROR_CODES[code].status;\n}\n","import { z } from \"zod\";\n\n/**\n * OAuth scope catalogue (Phase 2).\n *\n * Access tokens carry a `scope` claim (space-delimited, RFC 8693 style) and routes gate\n * on it via the control plane's `requireScope` preHandler. Four first-party apps hold\n * deliberately different grants — the Tuner is listen-only, Switchboard never\n * manages stations — so a leaked or stolen token is only as powerful as the app it was\n * minted for.\n */\nexport const SCOPES = {\n \"stations:read\": \"Browse the station directory, band plan and public station metadata.\",\n \"stream:listen\": \"Tune frequencies and receive live program audio.\",\n \"channels:talk\": \"Transmit on channels the user is talk-eligible for.\",\n \"frequencies:manage\": \"Create, configure and administer frequencies, channels, groups and invites.\",\n \"org:manage\": \"Manage station organizations: branding, staff, now-playing.\",\n \"billing:manage\": \"View and change billing and subscription state.\",\n \"profile\": \"Read and update the signed-in user's own profile and sessions.\",\n // Service scope - never granted to a user-facing app. Carried by client_credentials\n // tokens minted for media-node containers calling /internal/* routes.\n \"internal:media-node\": \"Media-node service calls to the control plane's internal routes.\",\n} as const satisfies Record<string, string>;\n\nexport type Scope = keyof typeof SCOPES;\n\nexport const SCOPE_NAMES = Object.keys(SCOPES) as [Scope, ...Scope[]];\nexport const ScopeSchema = z.enum(SCOPE_NAMES);\n\n/** Every scope a user-facing (human-consented) app may hold. */\nexport const USER_SCOPES: readonly Scope[] = SCOPE_NAMES.filter((s) => !s.startsWith(\"internal:\"));\n\nexport function isScope(value: unknown): value is Scope {\n return typeof value === \"string\" && value in SCOPES;\n}\n\n/** Parse a space-delimited `scope` claim/parameter, dropping unknown entries. */\nexport function parseScopes(scope: string | undefined | null): Scope[] {\n if (!scope) return [];\n return scope.split(\" \").filter(isScope);\n}\n\nexport function formatScopes(scopes: readonly Scope[]): string {\n return scopes.join(\" \");\n}\n","/**\n * Words an operator has blocked from names, on top of the curated profanity lists\n * (profanity.ts). The admin console writes the `blocked_words` platform_settings row; the\n * control plane reads it and hands it to `setAdminBlockedWords`, so every name check on the\n * server refuses the word from the next settings reload on, without a deploy.\n *\n * `match` is the operator's choice because the two failure modes are opposite: \"word\" blocks\n * the word standing alone (safe for something like \"cum\", which hides inside \"cucumber\"),\n * \"anywhere\" blocks it inside longer words too (what an operator wants for a slur that people\n * glue to other words to get it through).\n *\n * Adding a word is NOT retroactive: names already taken keep working until somebody renames\n * them, which the console can do from the Users tab.\n */\nimport { z } from \"zod\";\nimport { normalizeBlockedWord } from \"./profanity.js\";\n\nexport const BLOCKED_WORDS_KEY = \"blocked_words\";\n\nexport const BlockedWordMatchSchema = z.enum([\"word\", \"anywhere\"]);\nexport type BlockedWordMatch = z.infer<typeof BlockedWordMatchSchema>;\n\nexport const BlockedWordSchema = z.object({\n word: z\n .string()\n .trim()\n .refine((w) => normalizeBlockedWord(w) !== null, \"Use one word of 2 to 40 letters (numbers and symbols that stand in for letters are fine).\"),\n match: BlockedWordMatchSchema,\n});\nexport type BlockedWord = z.infer<typeof BlockedWordSchema>;\n\nexport const BlockedWordsSchema = z.object({ words: z.array(BlockedWordSchema).max(2000) });\n\n/**\n * A malformed row reads as an empty list (only the curated words apply), and each bad entry\n * is dropped on its own rather than discarding the rest: one corrupt entry must not quietly\n * unblock everything an operator added.\n */\nexport function parseBlockedWords(value: unknown): BlockedWord[] {\n const raw = value && typeof value === \"object\" && !Array.isArray(value) ? (value as { words?: unknown }).words : undefined;\n if (!Array.isArray(raw)) return [];\n const out: BlockedWord[] = [];\n for (const entry of raw) {\n const parsed = BlockedWordSchema.safeParse(entry);\n if (parsed.success) out.push(parsed.data);\n }\n return out;\n}\n","/**\n * M1 native voice transport — the wire contract, in one place both ends build against.\n *\n * The media node (Rust datapath), the control plane, and the .NET Switchboard engine all\n * have to agree on the packet byte-for-byte. This module is the single source of that\n * agreement: the header layout, the AEAD/nonce rules, and the handful of review-hardened\n * invariants that are easy to reimplement subtly wrong on one side. It is a REFERENCE — pure\n * constants and types, no runtime behaviour — so importing it costs nothing and drifting\n * from it is a visible diff.\n *\n * The reasoning behind every rule here lives in ../switchboard docs/m1-threat-model.md and\n * docs/m1-voice-transport.md (§3–§4), signed off 2026-07-31. Where a rule below cites a\n * section, that is the argument; this file is the normative shape.\n *\n * Nothing in the shipping product reads this yet — the datapath is gated behind\n * NATIVE_TRANSPORT_ENABLED and unbuilt. It exists so the datapath and the engine are written\n * against the same numbers from their first commit.\n *\n * KNOWN-ANSWER VECTORS live beside this file, in ../vectors/native-transport-v1.json: the\n * constants below applied to fixed inputs, with every intermediate (AAD, nonce, senderMac,\n * ciphertext, tag) written out, so a client in another language can be proven byte-for-byte\n * with no backend to talk to. Anything here that moves changes those bytes — regenerate with\n * `npm run vectors:emit -w @frequency/load-generator` and treat the diff as a wire-format\n * change every native client has to be told about, not as artifact churn.\n */\n\n/** Protocol version in byte 0 (low nibble); flags occupy the high nibble. Bump on any\n * incompatible header change so a mixed fleet rejects rather than misparses.\n *\n * This is the version of everything the PLATFORM itself emits (the node's control packets and\n * the bridge's re-sealed browser audio stay version 1), and of keepalives, control packets and\n * screen share from any client. Wire v2 (NATIVE_TRANSPORT_WIRE_V2) changes VOICE AUDIO only. */\nexport const NATIVE_TRANSPORT_VERSION = 1;\n\n/**\n * WIRE VERSION 2 (0.107.0, card f0bded27, Switchboard's single-seal proposal): a sender seals\n * each audio frame ONCE, under a per-talkspurt CONTENT KEY `K_s`, and delivers `K_s` in small\n * KEY PACKETS, one per carrying channel, each sealed under that channel's existing key. A\n * listener can learn `K_s` only through a channel it is matched to, so authorization is exactly\n * v1's (the key rides the route the audio rode), and a talkspurt on nine channels costs one\n * audio datagram per frame instead of nine.\n *\n * What v2 covers, and nothing else:\n * - AUDIO: version 2, no flags. Header channelId is the stream's HOME channel's wire id, a\n * routing anchor only (no listener needs the home key to open it). Header keyEpoch carries\n * the CONTENT-KEY GENERATION (CONTENT_KEY_GENERATION below), not a channel-key epoch. Sealed\n * under `K_s`; the payload is v1's audio payload unchanged.\n * - KEY PACKETS: version 2 with FLAG_CONTENT_KEY. Header channelId is the channel whose key\n * wraps `K_s` and keyEpoch is that channel key's epoch, exactly as for v1 audio. The payload\n * is CONTENT_KEY_PAYLOAD.\n * Keepalives, control packets and screen share stay version 1, byte for byte. The node accepts\n * both versions (NATIVE_TRANSPORT_ACCEPTED_VERSIONS) for as long as any v1 client exists.\n *\n * NEGOTIATION, never a probe: a container that accepts v2 says so in `authOk.native.wireVersions`\n * on the media lane, which is the container itself answering, before the first datagram. A\n * deploy is not a fleet upgrade (running media containers keep their image until recycled), so\n * the control plane's `native-transport-v2` capability says only that the platform supports it;\n * the authOk list is what a sender acts on. Absent means [1].\n */\nexport const NATIVE_TRANSPORT_WIRE_V2 = 2;\n/** Every wire version this platform's media node accepts on its datapath. */\nexport const NATIVE_TRANSPORT_ACCEPTED_VERSIONS: readonly number[] = [NATIVE_TRANSPORT_VERSION, NATIVE_TRANSPORT_WIRE_V2];\n\n/**\n * Flag bits (high nibble of byte 0). All bits not defined here are MUST-be-zero, and the\n * whole byte is covered by both the senderMac and the AAD, so flags cannot be tampered\n * with or invented in flight.\n *\n * FLAG_CONTROL marks a CONTROL packet: senderMac-authenticated but NOT channel-sealed —\n * the node holds no channel key on all-native channels, yet path validation needs\n * node→client packets. A control packet is exactly HEADER.LENGTH + CONTROL_PAYLOAD bytes,\n * carries channelId = 0, is NEVER forwarded, and its payload is cleartext covered by\n * nothing but the MAC (it contains only a packet type and a random token — nothing\n * confidential).\n */\nexport const FLAG_CONTROL = 0x10;\n\n/**\n * FLAG_CONTENT_KEY marks a wire-v2 KEY PACKET: \"this datagram is sealed under a CHANNEL key, not\n * under the content key\". Defined ONLY with version 2, and never with FLAG_CONTROL; on any other\n * version it is an undefined bit and the packet is dropped on shape.\n *\n * It has to be a cleartext header bit, and that is the whole argument (Switchboard found it,\n * 2026-09-18): the payload's type byte is INSIDE the AEAD envelope, so a receiver must choose a\n * key BEFORE it can learn what kind of packet it holds, and under v2 the two kinds want\n * different keys. A distinct payload type cannot say it, and neither can `channelId == home`\n * (a single-channel sender's home IS its only channel, so the two kinds are byte-identical\n * there). Byte 0 is inside the AAD and the senderMac, so flipping the bit breaks the tag rather\n * than steering a receiver to the wrong key.\n *\n * ⚠️ Both ends reject unknown flag bits before any crypto, with no log: a v2 sender aimed at a\n * node or a peer that has not added this bit loses every key packet and is silently inaudible.\n * That is why v2 is negotiated through `authOk.native.wireVersions` and never assumed.\n */\nexport const FLAG_CONTENT_KEY = 0x20;\n\n/** Control-packet payload, immediately after senderMac (no GCM tag on control packets). */\nexport const CONTROL_PAYLOAD = {\n /** uint8: see CONTROL_TYPE. */\n TYPE_OFFSET: 0,\n /** 8 random bytes. A challenge's token; a response echoes it verbatim. */\n TOKEN_OFFSET: 1,\n TOKEN_BYTES: 8,\n LENGTH: 9,\n} as const;\nexport const CONTROL_TYPE = { pathChallenge: 1, pathResponse: 2 } as const;\n\n/**\n * Direction partition of the sequence space under a sender↔node MAC key. The same pairwise\n * key authenticates client→node packets AND node→client control packets (challenges), and\n * GMAC nonce uniqueness is per-key — so the two directions MUST draw from disjoint\n * sequence ranges or a node challenge could reuse a (connectionId, sequence) nonce a\n * client packet already spent, leaking the GHASH subkey (this is the job the original\n * design's \"direction salt\" did, re-homed into the sequence). Client-originated packets\n * use sequence < 2^63; node-originated use sequence >= 2^63 (top bit set). Each side keeps\n * its own monotonic counter in its own half and validates the other side's packets against\n * the other half.\n */\nexport const NODE_SEQUENCE_BASE = 1n << 63n;\n\n/**\n * The cleartext, authenticated header. Every field is covered by `senderMac` and used as\n * GCM AAD (§3.3), so a reader may trust these bytes without holding the channel key — but\n * none of them is confidential. Offsets are absolute from the start of the datagram.\n */\nexport const HEADER = {\n /** version (low nibble) + flags (high nibble). */\n VERSION_FLAGS_OFFSET: 0,\n /** uint32. The sender's generation-scoped connection id — node-allocated at control-WS\n * auth (NOT in TuneResult), fresh on every tune. Nonce input; see NONCE below. */\n CONNECTION_ID_OFFSET: 1,\n /** uint32. Which channel KEY sealed the payload; a routing key, never a permission claim\n * (§4: relay rights are server state, re-validated on every change).\n *\n * THE MAPPING, decided 2026-08-01 and binding on every client: this is the channel's\n * `nativeId` — a server-assigned uint32 that is STABLE for the channel's lifetime,\n * delivered to clients in `TuneResult.nativeTransport.channelKeys.keys[<uuid>].id`,\n * alongside the key it belongs to. Clients MUST use the id they were given and MUST NOT\n * derive one from the channel UUID: a hash-derived id has a silent collision mode, and\n * a separately-announced one has an announcement race. **0 is reserved** — control\n * packets (FLAG_CONTROL) carry channelId 0 and are never forwarded, so no real channel\n * may ever be issued 0. */\n CHANNEL_ID_OFFSET: 5,\n /** uint8. Bumped on rekey; receivers tolerate current + immediately-previous for a bounded\n * window (EPOCH_TOLERANCE). Wraps mod 256 — safe only because just two epochs are ever\n * live at once (§4.3). */\n KEY_EPOCH_OFFSET: 9,\n /** uint8, 0–255. Attacker-controlled cosmetic \"on air\" level; node-side speaking pushes\n * driven by it MUST be gated on an unpaused, talk-permitted stream and rate-limited (§5).\n * Never a security input. */\n VOICE_LEVEL_OFFSET: 10,\n /** uint64. Monotonic per connection, incremented PER SEAL — see SEQUENCE_PER_SEAL. Nonce\n * input and replay-window input. */\n SEQUENCE_OFFSET: 11,\n /** 16 bytes. Keyed MAC over bytes 0..18 under the sender↔node key (also from the auth\n * ack), so the node authenticates and rate-limits without the channel key (§3.3). */\n SENDER_MAC_OFFSET: 19,\n /** Total header length; the AEAD ciphertext begins here. */\n LENGTH: 35,\n} as const;\n\n/** The AAD is exactly the pre-MAC header bytes: offsets 0..18 inclusive, i.e. everything\n * before senderMac. Authenticating fewer (the stale \"13\" of the pre-per-channel-key header)\n * would leave routing/level bytes tamperable; see m1-voice-transport.md §4. */\nexport const AAD_BYTE_LENGTH = HEADER.SENDER_MAC_OFFSET; // 19\n\n/** AES-256-GCM. 12-byte nonce, 16-byte tag; the channel key is 32 bytes. */\nexport const AEAD = {\n KEY_BYTES: 32,\n NONCE_BYTES: 12,\n TAG_BYTES: 16,\n} as const;\n\n/**\n * Nonce = connectionId(4) ‖ sequence(8), both taken straight from the header (§3.1). This\n * is the whole point of node-side, per-generation connectionIds and per-seal sequence: under\n * a SHARED per-channel key, uniqueness of (connectionId, sequence) is what stops two senders\n * from ever colliding a GCM nonce. The original direction-salt‖sequence construction was\n * catastrophic under shared keys — reached by the second speaker on a channel, no attacker.\n */\nexport const NONCE = {\n CONNECTION_ID_BYTES: 4,\n SEQUENCE_BYTES: 8,\n} as const;\n\n/**\n * THE INVARIANT: within the lifetime of one channel key, no (connectionId, sequence) pair is\n * ever reused. Everything else here exists to make that hold by construction:\n * - connectionIds are node-allocated, generation-scoped, fresh per tune (§3.1a);\n * - a generation is a node BOOT ID, so an in-place container restart rotates keys (§3.2);\n * - sequence increments per seal (below);\n * - on wrap of the uint32 connectionId space the allocator MUST refuse and force a\n * container recycle rather than reuse a low id — see CONNECTION_ID_WRAP_REFUSES.\n */\n\n/**\n * Sequence increments PER SEAL, not per audio frame (§3.1c). Under wire v2 it is still per\n * DATAGRAM: audio and key packets each spend one, because the node's replay window runs over the\n * connection's whole sequence space and two datagrams sharing a sequence lose the second. A talkspurt tagged to N\n * channels is sealed N times on one connection and burns N sequence values — so each sealed\n * packet is unique on (connectionId, sequence) regardless of channel, and the per-connection\n * replay window stays sound. uint64 makes exhaustion irrelevant by many orders of magnitude.\n *\n * DOWNSTREAM CONSEQUENCE, and the round-2 review's one real find: because a listener receives\n * only its MATCHED-channel copy of each talkspurt, its view of header `sequence` is\n * legitimately sparse (0, 3, 6, … for a 3-channel stream). Any per-stream loss / QoS metric\n * MUST derive from the payload `timestamp` (consecutive frames differ by exactly the frame's\n * sample count), NEVER from header-sequence continuity — a naive gap estimator reads a clean\n * link as heavy loss and would drive Opus FEC to max out redundancy for no reason.\n */\nexport const SEQUENCE_PER_SEAL = true;\n\n/** The uint32 connectionId allocator is monotonic and never wraps in any realistic process\n * lifetime; if it ever reaches the ceiling it MUST refuse to allocate (forcing a container\n * recycle) rather than wrap into a low id still live under a channel key. The invariant\n * never rests on \"unreachable\". */\nexport const CONNECTION_ID_WRAP_REFUSES = true;\n\n/** keyEpoch tolerance: accept current and immediately-previous epoch for this long after a\n * rotation (§4.3). Matched to — but kept as its OWN constant from — the permissions-snapshot\n * poll, so retuning one later forces the relationship to be re-argued rather than silently\n * tracking. Real A3 exposure is min(this, sender-migration ≈ one RTT), so it is generous\n * rather than load-bearing. */\nexport const EPOCH_TOLERANCE_MS = 5_000;\n\n/** The decrypted payload, immediately after the auth tag. */\nexport const PAYLOAD = {\n /** uint8: 0 = audio, 1 = keepalive. */\n TYPE_OFFSET: 0,\n /** uint32. Which producer this is — FORGEABLE on its own (it rides inside the group-keyed\n * envelope), so a listener MUST verify owner(streamId) == header.connectionId against the\n * control-plane stream announcement before trusting attribution (§3.4; normative statement:\n * STREAM_ATTRIBUTION_REQUIRES_OWNER_CHECK below). The binding is a function, not a\n * bijection: one connection carries many streams, and a producer takeover is\n * producerClosed(old)+newProducer(new streamId) — streamIds are never rebound. */\n STREAM_ID_OFFSET: 1,\n /** uint32, 48 kHz sample counter. The ONLY sound basis for loss/QoS (see SEQUENCE_PER_SEAL). */\n TIMESTAMP_OFFSET: 5,\n /** Opus frame begins here. */\n OPUS_OFFSET: 9,\n} as const;\n\nexport type NativePayloadType = \"audio\" | \"keepalive\" | \"contentKey\" | \"videoShard\" | \"shareAudio\";\n/**\n * The payload's type byte. The datapath never reads it (it sits inside the sealed envelope), so\n * these are an agreement between native clients, named here so every client names them alike.\n * 2 is the wire-v2 key packet (CONTENT_KEY_PAYLOAD); it travels only in a FLAG_CONTENT_KEY\n * datagram, and the flag, not this byte, is what a receiver selects a key by.\n *\n * 3 and 4 are SCREEN SHARE (capability `screen-share`, 0.81.0). Both keep audio's first nine\n * bytes (type, streamId, timestamp), so the owner check below applies to them unchanged. A\n * receiver that does not understand a type MUST drop the packet: nothing is forwarded to a\n * connection that did not subscribe to a share, so an older client never sees one, but a\n * client that subscribes must still route by this byte, because one subscription carries both\n * of a sharer's streams (see SHARE_CHANNEL_ID).\n */\nexport const PAYLOAD_TYPE = { audio: 0, keepalive: 1, contentKey: 2, videoShard: 3, shareAudio: 4 } as const;\n\n/**\n * A wire-v2 KEY PACKET's plaintext: audio's first nine bytes (type, streamId, timestamp), so the\n * owner check (STREAM_ATTRIBUTION_REQUIRES_OWNER_CHECK) applies to it unchanged, then the\n * content key. 45 bytes, so a key packet is 35 + 45 + 16 = 96 bytes on the wire.\n */\nexport const CONTENT_KEY_PAYLOAD = {\n TYPE_OFFSET: 0,\n /** uint32. The stream whose audio `K_s` seals. */\n STREAM_ID_OFFSET: 1,\n /** uint32, 48 kHz. The talkspurt's timestamp when this key packet was sent; informational. */\n TIMESTAMP_OFFSET: 5,\n /** uint32. Monotonic per stream; its LOW BYTE is the generation an audio header carries. */\n CONTENT_KEY_ID_OFFSET: 9,\n /** 32 bytes: `K_s`, an AES-256-GCM key. */\n KEY_OFFSET: 13,\n LENGTH: 45,\n} as const;\n\n/**\n * THE CONTENT-KEY GENERATION: a v2 audio header's keyEpoch byte is `contentKeyId & 0xff` of the\n * key that sealed it. It is cleartext and authenticated (inside the AAD), so a receiver holding\n * two keys across a mid-talkspurt rotation knows which one to try, and in-flight audio under the\n * old key, arriving after the new key packet, still opens. Receivers keep the current and the\n * immediately-previous generation per stream, the same two-live rule as channel epochs.\n *\n * WHICH STREAM, and the rule a receiver gets wrong first: an audio datagram's header names no\n * streamId (it is inside the envelope). The stream is (header connectionId, header channelId),\n * because the header channelId is the stream's HOME, and one connection never holds two streams\n * on one home (a second produce on a home supersedes the first). A key packet names its streamId\n * in its plaintext; the receiver maps that stream to its home through the `nativeStream`\n * announcement and files the key under (connectionId, home, generation). After opening audio,\n * the receiver MUST check that the payload's streamId is the streamId the key packet named, and\n * drop the frame if not.\n */\nexport const CONTENT_KEY_GENERATION_IS_KEY_ID_LOW_BYTE = true;\n\n/**\n * THE KEY-PACKET CADENCE: a sender sends a key packet on every carrying channel with each of the\n * first FIRST_FRAMES audio frames of a talkspurt (and of each new generation), then every\n * REPEAT_MS while the talkspurt lasts. UDP has no retransmit, and a listener who joins\n * mid-talkspurt or loses the first key packet is deaf until the next one, so the repeat is the\n * listener's worst-case join latency. A platform constant rather than a client's choice, so every\n * client keeps the same promise. At nine channels it costs about 4 kbps.\n */\nexport const CONTENT_KEY_CADENCE = { FIRST_FRAMES: 5, REPEAT_MS: 200 } as const;\n\n/**\n * `K_s` ROTATES (new contentKeyId, new key) on a new streamId, on ANY shrink of the stream's\n * carrying set (re-wrapped to the survivors only, so a listener dropped from a channel\n * mid-talkspurt does not keep a working key), and on a channel-key epoch change. A fresh `K_s`\n * per talkspurt is the floor; nonce uniqueness under it is the v1 rule unchanged, because the\n * nonce is still connectionId || sequence.\n */\nexport const CONTENT_KEY_ROTATES_ON_CARRYING_SET_SHRINK = true;\n\n/**\n * THE SHARE KEY'S WIRE ID. A screen share is sealed ONCE, under the frequency's share key, and\n * its header channelId is this value.\n *\n * It is a RESERVED constant rather than an allocated id, and the reason is structural: channel\n * wire ids come from a Postgres `SERIAL` (int4), whose ceiling is 2^31 - 1, so no channel can\n * ever be issued a value at or above 2^31. This id therefore cannot collide with a voice channel\n * on any frequency, now or later, without anything having to remember that shares exist, which\n * is the same argument that keeps call frequencies off the dial with a NEGATIVE kHz. Clients\n * still take the id from `channelKeys.shareKey.id` rather than hard-coding it, exactly as for a\n * channel, so it can move without a wire change.\n *\n * The node forwards on it like any channel id, with two differences it enforces: this id never\n * enters a voice forward set (and no voice channel id enters a share's), and a share's forward\n * set is its SUBSCRIBERS rather than a channel's listeners. Because the node cannot read the\n * payload, a sharer's forward set is keyed on (sender, this id), which is shared by both of their\n * streams: a subscriber to either the video or the audio receives both, and routes by\n * PAYLOAD_TYPE.\n */\nexport const SHARE_CHANNEL_ID = 0xffff_ffff;\n\n/**\n * Layout of a type-3 VIDEO SHARD's plaintext (Switchboard docs/screen-share.md §5.2). The node\n * never parses it; it is here so the reference vectors and every client read the same offsets.\n */\nexport const VIDEO_SHARD = {\n TYPE_OFFSET: 0,\n STREAM_ID_OFFSET: 1,\n /** uint32, 90 kHz capture clock (audio's is 48 kHz). */\n TIMESTAMP_OFFSET: 5,\n /** uint32, monotonic per stream, wraps. */\n FRAME_ID_OFFSET: 9,\n /** uint32, length of the whole access unit. */\n FRAME_BYTES_OFFSET: 13,\n BLOCK_INDEX_OFFSET: 17,\n BLOCK_COUNT_OFFSET: 18,\n SHARD_INDEX_OFFSET: 19,\n DATA_SHARDS_OFFSET: 20,\n PARITY_SHARDS_OFFSET: 21,\n /** 0x01 keyframe, 0x02 recovery point, 0x04 end of share; other bits MUST be zero. */\n FLAGS_OFFSET: 22,\n /** The shard bytes begin here. */\n SHARD_OFFSET: 23,\n} as const;\nexport const VIDEO_SHARD_FLAG = { keyframe: 0x01, recoveryPoint: 0x02, endOfShare: 0x04 } as const;\n/** A share datagram's budget: under the IPv6 minimum MTU with headroom, so no path-MTU discovery. */\nexport const SHARE_DATAGRAM_MAX_BYTES = 1200;\n\n/**\n * THE HOME-SEAL REQUIREMENT: a sender MUST seal a copy of every audio packet under its\n * stream's HOME channel key, in addition to whatever relay channels the talkspurt is tagged\n * to. The home channel is not \"one more relay\" a sender may optimize away when it believes\n * nobody is listening there — it is the copy the platform itself consumes:\n *\n * - The mediasoup↔native BRIDGE taps exactly the home-channel copy (`room.ts` — the tap is\n * registered as a listener on the stream's home channel) to feed the DirectTransport\n * producer that browser/Electron listeners, HLS egress, and the speaking badge all hang\n * off. A sender that skips the home seal is audible to same-vintage native peers and\n * **completely silent to every browser listener**, with no error anywhere: signaling is\n * healthy, the roster is right, forward sets to native peers work. This is not\n * hypothetical — a pre-0.7.4 Switchboard engine shipped exactly this bug and was\n * invisible to browsers for weeks (2026-08-14).\n * - Sequence burn is already accounted for: SEQUENCE_PER_SEAL means the home copy is just\n * one more seal on the same connection.\n *\n * A listener never receives two copies (it gets its one matched-channel copy; the bridge\n * tap is a distinct listener), so there is no de-dup burden created by complying.\n */\nexport const HOME_CHANNEL_SEAL_REQUIRED = true;\n\n/**\n * THE HOME-WRAP REQUIREMENT, wire v2's form of HOME_CHANNEL_SEAL_REQUIRED: a v2 sender MUST send\n * a key packet under its stream's HOME channel key on every talkspurt and every generation,\n * whether or not it believes anyone listens there. The bridge holds the home key (and only the\n * keys of channels it bridges), so the home key packet is the only way it learns `K_s`. Skip it\n * and native peers hear you while every browser, the HLS stream and the speaking badge get\n * silence, which is the 2026-08-14 regression in a new form. The node's bridge tap reports a\n * sender in this state as DEAF (reason `no-content-key`).\n */\nexport const HOME_CHANNEL_WRAP_REQUIRED = true;\n\n/**\n * THE LISTENER-KEEPALIVE REQUIREMENT: after `authOk.native`, a listen-only client MUST send\n * a sealed keepalive packet (PAYLOAD_TYPE.keepalive) and repeat it periodically. The\n * datapath binds a connection's peer UDP address only on its first MAC-valid INBOUND packet\n * (address discipline — an address is trustworthy only once something MAC-valid arrived\n * from it), and forwarding skips any listener with no validated address. A seat that only\n * ever listens is therefore never sent anything for the life of its connection, with no\n * error surfaced at any layer — signaling open, authOk succeeded, roster correct, silence.\n * A transmitting client gets the binding for free from its own audio; a pure listener must\n * do it explicitly, and keep doing it so the binding survives NAT/idle timeouts. The\n * reference implementation is `load-generator/src/probeShared.ts`; the full argument is\n * docs/audio-routing-contract.md \"A native listener must SEND before it can RECEIVE\".\n */\nexport const LISTENER_KEEPALIVE_REQUIRED = true;\n\n/**\n * THE ATTRIBUTION REQUIREMENT: a listener MUST verify `owner(streamId) === header.connectionId`\n * against the control-plane `nativeStream` announcement before attributing audio to a speaker,\n * and MUST drop the packet when the binding is absent or disagrees.\n *\n * `streamId` rides INSIDE the channel-keyed envelope, so the AEAD proves only that *a channel\n * member* sealed the packet — never *which* member. Any other holder of the channel key can seal\n * a packet carrying someone else's streamId, and the node forwards it: the forger's own senderMac\n * is valid, and the node cannot open the envelope to notice. The platform enforces this rule on\n * the one native listener it controls — the bridge tap performs exactly this check before feeding\n * mediasoup (`room.ts`, `bridgeTapAttributionDrops`) — but on native→native forwarding there is\n * no server-side mitigation even in principle. Unlike HOME_CHANNEL_SEAL_REQUIRED and\n * LISTENER_KEEPALIVE_REQUIRED, whose violations the platform can at least observe, here the\n * client check is the only place the property can exist.\n *\n * It is also the only one of the three that fails OPEN: skip it and audio plays, the roster is\n * right, and it is attributed to the wrong person, with every surface on both sides healthy.\n * That is voice impersonation inside a channel.\n *\n * streamIds are never rebound — a producer takeover is producerClosed(old) + a FRESH id\n * (monotonic allocator, room.ts) — so a known id arriving under a different connectionId means\n * announcements crossed or something upstream is wrong, and is never a legitimate rebinding to\n * follow. The forwarded copy's senderMac is deliberately NOT part of this check: it is the\n * original sender's pairwise MAC under a key a listener does not hold and must never be given\n * (§3.4).\n */\nexport const STREAM_ATTRIBUTION_REQUIRES_OWNER_CHECK = true;\n\n/**\n * Address (re)binding rule (§3.3 / §5): the node learns a sender's UDP address from its\n * packets, but a MAC-valid, sequence-advancing packet from a new source only *initiates*\n * validation — it never migrates the flow by itself. The node challenges the NEW address\n * with a random token (authenticated under the sender↔node MAC key — never the channel key,\n * which the node may not hold) and migrates only on a matching response, continuing to serve\n * the old address meanwhile; rebind attempts are rate-capped. Monotonicity alone is spoofable\n * by an on-path relay forwarding genuine bytes from a victim's address — that is a reflection\n * primitive, and it is why QUIC path-validates. Sequence-advance is the pre-filter; the\n * challenge round trip is the decision.\n */\nexport const ADDRESS_REBIND_REQUIRES_ADVANCING_SEQUENCE = true;\nexport const ADDRESS_REBIND_REQUIRES_PATH_CHALLENGE = true;\n\n/**\n * The senderMac primitive, pinned (crypto-review Finding 7 / round 3): **AES-256-GMAC** —\n * AES-GCM over EMPTY plaintext with the 19 pre-MAC header bytes as AAD, under the\n * per-connection sender↔node key, same `connectionId(4) ‖ sequence(8)` nonce as the payload,\n * full 16-byte tag, constant-time comparison.\n *\n * Why GMAC over the alternatives weighed in the review:\n * - The nonce-coupling concern is weaker than it looks: the MAC key is CONNECTION-scoped and\n * dies with the connection, so its nonce-uniqueness requirement is purely local — one\n * counter, one process, one key that cannot outlive its allocator BY CONSTRUCTION (they are\n * the same object). Every allocator-lifetime failure this design has suffered involved a\n * key outliving an allocator across a boundary; this pair shares its lifetime and has no\n * boundary to fail at.\n * - Portability is the decider the review asked to confirm: GMAC is expressible as\n * plaintext-free AES-GCM on all three stacks IN-BOX (.NET `AesGcm`, Rust `aes-gcm`,\n * Node/OpenSSL) — AES-CMAC is in-box in NEITHER .NET nor node:crypto, failing the\n * no-new-dependency requirement, and HMAC-SHA-256 costs a meaningful fraction of a core at\n * the node's 1 M verifications/sec for portability we do not need.\n * Distinct keys mean the shared nonce with the channel-key GCM is sound (uniqueness is\n * per-key). Flag bits in byte 0 are MUST-be-zero and covered by both the MAC and the AAD.\n */\nexport const SENDER_MAC = {\n algorithm: \"AES-256-GMAC\",\n KEY_BYTES: 32,\n TAG_BYTES: 16,\n} as const;\n","/**\n * Makes a Redis connection failure VISIBLE to an operator, in whichever plane owns the client.\n *\n * THE FAILURE THIS EXISTS TO NAME. ioredis emits `error` on its client; with NO listener\n * attached it writes the condition to STDERR ITSELF (\"[ioredis] Unhandled error event:\n * connect ETIMEDOUT\"). That line never passes through pino, so it carries no `level` — and two\n * things follow that are both worse than the outage:\n *\n * - the level-50 error ingest that auto-files a task-board card cannot see it, so nothing\n * reaches an operator;\n * - `docker logs <c> | grep -E '\"level\":(50|60)'` — the documented healthy-container check —\n * returns EMPTY for a container whose Redis is entirely down. That check was run on the\n * 2026-08-26 relay pass, came back clean, and would have been believed had the raw log not\n * also been read.\n *\n * It matters most on the media-proxy relay, whose Redis lane is a SECURITY dependency rather\n * than a convenience: the revoked-session denylist is in-memory and Redis-pub/sub-fed, which is\n * the entire mechanism that makes a revocation bite immediately instead of surviving to token\n * expiry. Both the session and stream caps also fail OPEN when Redis is down. Failing open is\n * the right availability call and is NOT changed here; failing open SILENTLY is the defect — a\n * relay that has quietly stopped enforcing revocation still answers /health `ok:true`, still\n * passes the level-50 check, and still looks healthy in `docker ps`.\n *\n * EPISODES, NOT EVENTS (CLAUDE.md's rule, same shape as media-node's BridgeTapDeafWatch). A\n * flapping Redis emits errors as fast as it can retry, and one card per event would file\n * thousands. So the first error of an episode logs at `error`, the rest are counted in silence,\n * and `ready` closes the episode with a recovery line carrying the count and the duration — an\n * episode has both edges or it is not diagnosable. A long outage would otherwise be one line at\n * hour zero and nothing after, so an OPEN episode re-states itself on a slow heartbeat; that is\n * a bounded compromise on \"once per episode\", not an abandonment of it.\n *\n * NEVER log the Redis URL — it carries a credential. Only the error's `code` and `message` are\n * recorded, deliberately in place of handing the error object to pino's `err` serializer.\n * ioredis puts neither the URL nor the password in either field.\n *\n * Lives in shared rather than in either plane because both planes have the same blind spot and\n * a duplicated copy is exactly the drift `docs/agent-tasks.md` was consolidated to stop.\n */\n\n/** While an episode is OPEN, re-state it at most this often so a long outage keeps a pulse. */\nexport const REDIS_EPISODE_REPEAT_MS = 5 * 60_000;\n\n/** The slice of pino each plane's logger already satisfies — avoids a dependency either way. */\nexport interface RedisWatchLogger {\n error(obj: Record<string, unknown>, msg: string): void;\n warn(obj: Record<string, unknown>, msg: string): void;\n}\n\n/** The slice of an ioredis client this needs — structural, so shared takes no ioredis dep. */\nexport interface RedisWatchTarget {\n on(event: string, listener: (...args: never[]) => void): unknown;\n}\n\nexport function watchRedisClient(\n client: RedisWatchTarget,\n opts: {\n /** Which client this is, so a multi-client process names the one that broke. */\n clientName: string;\n logger: RedisWatchLogger;\n /** Distinguishes a control-plane episode from a relay one in a shared log group. */\n role: string;\n now?: () => number;\n repeatMs?: number;\n },\n): void {\n const now = () => opts.now?.() ?? Date.now();\n const repeatMs = opts.repeatMs ?? REDIS_EPISODE_REPEAT_MS;\n let openedAt = 0;\n let lastLoggedAt = 0;\n let suppressed = 0;\n\n client.on(\"error\", ((err: Error & { code?: string }) => {\n const at = now();\n if (openedAt === 0) {\n openedAt = at;\n lastLoggedAt = at;\n suppressed = 0;\n opts.logger.error(\n { client: opts.clientName, role: opts.role, code: err?.code ?? null, reason: err?.message ?? \"unknown\" },\n `[redis] connection lost on ${opts.clientName} — session revocation, platform settings and secret reload ride this lane, and the session/stream caps fail OPEN while it is down`,\n );\n return;\n }\n suppressed += 1;\n if (at - lastLoggedAt >= repeatMs) {\n lastLoggedAt = at;\n opts.logger.error(\n {\n client: opts.clientName,\n role: opts.role,\n code: err?.code ?? null,\n reason: err?.message ?? \"unknown\",\n suppressed,\n openForMs: at - openedAt,\n },\n `[redis] still down on ${opts.clientName}`,\n );\n }\n }) as (...args: never[]) => void);\n\n // `ready`, not `connect`: a connected-but-not-ready client cannot serve a command yet, so\n // announcing recovery there closes an episode that is still open in practice.\n client.on(\"ready\", (() => {\n if (openedAt === 0) return; // ordinary first connect — nothing had broken\n opts.logger.warn(\n { client: opts.clientName, role: opts.role, suppressed, downForMs: now() - openedAt },\n `[redis] recovered on ${opts.clientName}`,\n );\n openedAt = 0;\n lastLoggedAt = 0;\n suppressed = 0;\n }) as (...args: never[]) => void);\n}\n","/**\n * The task board's shared contract: status vocabulary, the transition table, create-time\n * rules, the machine-platform → allowed-projects map, and the notification-recipients parser.\n *\n * Lives here, not in either server plane, for the same reason `alertRecipients.ts` does:\n * the admin plane and the control plane BOTH enforce these transitions (human routes on\n * 4500, agent routes on 4000) and the admin console renders its buttons from the same\n * table — three copies would eventually disagree, with the failure showing up as a UI\n * offering a move the server refuses, or worse, one plane allowing a move the other\n * would have blocked.\n */\n\nexport const TASK_STATUSES = [\n \"backlog\",\n \"awaiting_approval\",\n \"in_progress\",\n \"blocked\",\n \"testing\",\n \"done\",\n \"cancelled\",\n] as const;\nexport type TaskStatus = (typeof TASK_STATUSES)[number];\n\nexport const TASK_PRIORITIES = [\"low\", \"medium\", \"high\", \"critical\"] as const;\nexport type TaskPriority = (typeof TASK_PRIORITIES)[number];\n\nexport const TASK_PRIORITY_RANK: Record<TaskPriority, number> = { low: 0, medium: 1, high: 2, critical: 3 };\n\nexport const TASK_PROJECTS = [\n \"frequency\",\n \"tuner\",\n \"tuner_apple\",\n \"switchboard\",\n \"broadcast\",\n \"site\",\n \"windows\",\n \"platform\",\n \"tuner_steamos\",\n \"broadcast_apple\",\n \"models\",\n \"switchboard_steamos\",\n] as const;\nexport type TaskProject = (typeof TASK_PROJECTS)[number];\n\nexport const TASK_TYPES = [\"feature\", \"bug\", \"chore\", \"error_report\"] as const;\nexport type TaskType = (typeof TASK_TYPES)[number];\n\nexport type TaskActorKind = \"human\" | \"agent\" | \"system\";\n\n/**\n * Agent identity is per-MACHINE, per-PROJECT (2026-08-20; replaced the per-role keys).\n * A key answers \"this machine may work the board\" and is bound to the machine's PLATFORM;\n * the platform fixes the allowed project set SERVER-SIDE, and the agent names which of\n * those projects it is (the repo it sits in) per request via the `x-agent-project` header\n * — each repo's committed agent-tasks skill states its own project. Project isolation is\n * still the point: a request scoped to `tuner` cannot see or claim `frequency` work, and\n * a key minted on the wrong OS cannot reach the other machine's projects at all.\n *\n * There are exactly two machines by construction: the Mac runs the mac/linux codebases,\n * the Windows box runs the Windows-side ones (Tuner and Switchboard build there).\n */\nexport const AGENT_PLATFORMS = [\"mac\", \"windows\"] as const;\nexport type AgentPlatform = (typeof AGENT_PLATFORMS)[number];\n\nexport function isAgentPlatform(value: string): value is AgentPlatform {\n return (AGENT_PLATFORMS as readonly string[]).includes(value);\n}\n\n/**\n * The SteamOS group of lanes (owner, 2026-11-03: *\"we need a new grouping for steamos, it isn't\n * windows or mac. As such, we can develop on either development environment since the code is\n * executed on a linux flavor SteamOS.\"*). The apps are built and measured on the shared SteamOS\n * hardware box, which either development machine reaches over SSH, so the development machine\n * is not a property of these lanes. They appear in BOTH platform lists below, exactly as\n * `frequency` does, and for the same reason: the map answers \"may this machine act as that\n * lane?\", and here both machines may. Each is still ONE queue: one in-flight task per PROJECT\n * across both machines, so `get` before you claim. Not a third `AgentPlatform`: a platform is\n * the machine a key is minted on, and no key is minted on the Deck.\n *\n * History, so the earlier rulings are not rediscovered as contradictions: `tuner_steamos` was a\n * WINDOWS lane by owner decision on 2026-09-21 (the Windows group ran the SteamOS VM there; the\n * arm64 Mac could not emulate gamescope), and `switchboard_steamos` followed it on 2026-10-12.\n * The hardware box replaced the VM, and the 2026-11-03 ruling supersedes both.\n */\nexport const STEAMOS_PROJECTS = [\"tuner_steamos\", \"switchboard_steamos\"] as const satisfies readonly TaskProject[];\n\nexport const PROJECTS_BY_PLATFORM = {\n // `frequency` is on BOTH platforms (owner, 2026-09-21): this repo ships a Mac client and a\n // Windows client, so both developer groups work it. A project appearing twice is deliberate\n // and is NOT a second lane — there is exactly one `frequency` queue, and the board's\n // one-in-flight-task-per-PROJECT rule still means one claim at a time across both machines.\n // The map answers \"may this machine act as that lane?\", which two machines can both answer yes to.\n // `broadcast_apple` is the macOS Broadcast app (owner, 2026-10-02): a native Swift build of the\n // same product the Windows `broadcast` lane builds, developed here on the Mac. Its own lane rather\n // than a rider on `broadcast` (a Windows lane) or `tuner_apple`, for the reason `broadcast` got\n // one: the board enforces one in-flight task per PROJECT, so a shared lane makes one app's claim\n // answer 409 AGENT_BUSY while the other holds the slot.\n // The SteamOS group (`STEAMOS_PROJECTS`, above) is on both platforms since 2026-11-03.\n mac: [\"frequency\", \"tuner_apple\", \"site\", \"platform\", \"broadcast_apple\", ...STEAMOS_PROJECTS],\n // `broadcast` is its own lane rather than a rider on `windows` (2026-08-31): the board\n // enforces one in-flight task per PROJECT, and `windows` already carries the Jacked\n // audio-driver work, so sharing it meant a Broadcast claim answered 409 AGENT_BUSY for\n // as long as Jacked held the slot, and one mixed queue neither agent could read as its own.\n // `tuner_steamos` and `switchboard_steamos` are each their own lane rather than a rider on\n // `windows`, `tuner` or `switchboard`, for the reason `broadcast` got one: the board enforces\n // one in-flight task per PROJECT, so sharing a lane means one project's claim answers 409\n // AGENT_BUSY for as long as the other holds the slot. Their machine story is `STEAMOS_PROJECTS`.\n // `models` is a WINDOWS lane (owner, 2026-10-07; named for its repo, ibNez/models), its own for the same one-in-flight reason.\n windows: [\"windows\", \"tuner\", \"switchboard\", \"broadcast\", \"frequency\", \"models\", ...STEAMOS_PROJECTS],\n} as const satisfies Record<AgentPlatform, readonly TaskProject[]>;\n\n/**\n * The DEV LEAD's lane. Lane scoping does not apply to it.\n *\n * Owner ruling, 2026-09-22: *\"you are the dev lead so you need complete access to the board.\n * You are the only one that can freely assign and move tickets around, and are the final say\n * in debates. Your the lead developer and own the backend Frequency Talk service that all the\n * other applications depend on.\"* Every other lane stays scoped to its own queue.\n *\n * ⚠️ **It is a LANE, deliberately not a flag on a key, and that choice is load-bearing rather\n * than tidy.** The obvious implementation is an `isLead` column on `agent_api_keys`, and it\n * carries a silent failure this does not: minting REVOKES the previous key for the same\n * (staff member, machine), so every rotation would have to remember to carry the capability\n * forward, and the day it did not, the lead would quietly lose board access with nothing\n * saying so. It would also need a granting surface, which is a second thing to get wrong. The\n * agent identity in this board already IS the project (see `PROJECTS_BY_PLATFORM`), and\n * `frequency` is the lane that owns the backend every other app depends on, so the authority\n * lands exactly where the responsibility already is and needs no new state at all.\n *\n * ⚠️ **Both machines can act as this lane** — `frequency` is in mac's set AND windows's,\n * because this repo ships a Mac client and a Windows client. So both of the owner's machines\n * hold lead authority. That is stated rather than discovered; it is not a hole, because both\n * keys are minted against a platform staff row with an emailed code.\n *\n * ⚠️ **What it lifts is LANE scoping and nothing else.** Two refusals on the same routes are a\n * DIFFERENT axis and are untouched: `ASSIGNED_TO_HUMAN` protects a person's work rather than a\n * queue boundary, and `APPROVAL_REQUIRED` is the human-in-the-loop gate for costly or\n * destructive work, which the lead is subject to like everybody else. A lead who could approve\n * their own way past that gate would be the gate not existing.\n *\n * ⚠️ **And it is authority over the BOARD, never over another repo's CODE** (owner, same\n * session: *\"You still only try to work in your frequency codebase though. Let the other devs\n * do their work.\"*). Moving somebody's card is routing; editing their tree is not. A change\n * another repo needs is still a card on their project, per the standing cross-repo rule — the\n * lead is simply the one who files and routes it.\n */\nexport const LEAD_PROJECT = \"frequency\" as const satisfies TaskProject;\n\n/**\n * Is this lane the dev lead's? Asked by every lane-scoped route rather than compared inline,\n * so the rule has one copy — the same discipline `refusesIncoming` and `hidesIncoming` carry\n * on the presence side, and for the same reason: a rule spelled out at each call site is a\n * rule that gets half-updated.\n */\nexport function isLeadLane(project: TaskProject): boolean {\n return project === LEAD_PROJECT;\n}\n\n/**\n * The state machine. Each edge names who may take it; everything absent is a\n * 409 INVALID_TRANSITION. Notes on the deliberate asymmetries:\n *\n * - `approve` (awaiting_approval → backlog) and any move INTO cancelled are human-only.\n * Approval is the human-in-the-loop gate for cost-increasing and destructive work;\n * cancelled is the human \"ignore this\" lever (for error tasks it means \"stop reopening\",\n * see the ingest rules).\n * ⚠️ \"Human-only\" here means the ACTOR, and since 2026-08-31 it no longer implies \"only\n * reachable from the admin console\". The agent API gained `/agent/tasks/:id/approve` and\n * `/agent/tasks/:id/cancel`, which RELAY an owner's decision made in conversation and\n * require their verbatim words (owner: \"I just told you to approve it, that is the gate\").\n * Those routes do not consult this table for authority — they supply the human actor it\n * demands — so **do not add \"agent\" to these edges to make them work.** Doing so would\n * also open the generic /status mover, which is precisely what stays shut: the evidence\n * requirement lives on the dedicated routes, and an edge marked \"agent\" here has no\n * evidence requirement at all. A relayed decision is always distinguishable from a\n * console one: `relayed: true` in the event detail, and a NULL `approvedByPlatformUserId`.\n * - done → backlog carries the system actor because error recurrence reopens tasks; a\n * human reopening by hand goes done → in_progress instead so the two paths stay\n * distinguishable in the event trail.\n * - blocked has no edge to done: a blocked task must pass back through work (or be\n * cancelled by a human) — \"it fixed itself\" still deserves a look.\n */\nexport const TASK_TRANSITIONS: Partial<Record<TaskStatus, Partial<Record<TaskStatus, readonly TaskActorKind[]>>>> = {\n backlog: {\n in_progress: [\"human\", \"agent\"],\n awaiting_approval: [\"human\", \"system\"],\n done: [\"human\"],\n cancelled: [\"human\"],\n },\n awaiting_approval: {\n backlog: [\"human\"],\n cancelled: [\"human\"],\n },\n in_progress: {\n blocked: [\"human\", \"agent\"],\n testing: [\"human\", \"agent\"],\n backlog: [\"human\", \"agent\"],\n },\n blocked: {\n in_progress: [\"human\", \"agent\"],\n backlog: [\"human\", \"agent\"],\n cancelled: [\"human\"],\n },\n testing: {\n done: [\"human\", \"agent\"],\n in_progress: [\"human\", \"agent\"],\n },\n done: {\n in_progress: [\"human\"],\n backlog: [\"human\", \"system\"],\n },\n};\n\nexport function canTransition(from: TaskStatus, to: TaskStatus, actor: TaskActorKind): boolean {\n return TASK_TRANSITIONS[from]?.[to]?.includes(actor) ?? false;\n}\n\n/** The moves an actor may offer from a given column — drives the console's buttons. */\nexport function transitionsFor(from: TaskStatus, actor: TaskActorKind): TaskStatus[] {\n const edges = TASK_TRANSITIONS[from];\n if (!edges) return [];\n return (Object.keys(edges) as TaskStatus[]).filter((to) => edges[to]?.includes(actor));\n}\n\n/**\n * Blocked is only meaningful with its paperwork: what is blocking, the plan to move\n * forward, and roughly how long the wait is. All three are required at the transition —\n * a bare \"blocked\" tells the next reader (often another agent) nothing actionable.\n */\nexport interface BlockedInfo {\n blockedReason: string;\n blockedPlan: string;\n blockedWaitEstimate: string;\n}\n\nexport function missingBlockedFields(info: Partial<BlockedInfo>): (keyof BlockedInfo)[] {\n const missing: (keyof BlockedInfo)[] = [];\n if (!info.blockedReason?.trim()) missing.push(\"blockedReason\");\n if (!info.blockedPlan?.trim()) missing.push(\"blockedPlan\");\n if (!info.blockedWaitEstimate?.trim()) missing.push(\"blockedWaitEstimate\");\n return missing;\n}\n\n/** Labels are free-form, but this one is load-bearing for the priority rule below. */\nexport const SECURITY_LABEL = \"security\";\nexport const FLAPPING_LABEL = \"flapping\";\n\n/**\n * Create-time rules, applied by BOTH creation paths (admin and agent):\n * security-labelled bugs are floored at high priority — owner rule, security fixes are\n * fast-tracked — while a deliberate `critical` is preserved. Returns the effective\n * priority rather than mutating, so callers stay explicit about what they store.\n */\nexport function effectiveCreatePriority(input: {\n type: TaskType;\n priority: TaskPriority;\n labels: readonly string[];\n}): TaskPriority {\n const isSecurity = input.type === \"bug\" && input.labels.some((l) => l.toLowerCase() === SECURITY_LABEL);\n if (isSecurity && TASK_PRIORITY_RANK[input.priority] < TASK_PRIORITY_RANK.high) return \"high\";\n return input.priority;\n}\n\n/** Reopens before a task is declared flapping (loudly escalated, never silently cycled). */\nexport const FLAPPING_REOPEN_THRESHOLD = 3;\n\n// ---------------------------------------------------------------------------------------\n// Task.model — which model the dispatcher runs a task under.\n// ---------------------------------------------------------------------------------------\n\n/**\n * Grammar: \"<provider>:<model>\". The BOARD validates the format only; whether a provider\n * is actually configured is the dispatching MACHINE's business — a laptop with no local\n * model must skip the task, not have the server reject work another machine could run.\n *\n * `claude` runs headless Claude Code directly; `ollama` and `openai` run it against an\n * Anthropic-compatible proxy the operator configures per machine.\n */\nexport const TASK_MODEL_PROVIDERS = [\"claude\", \"ollama\", \"openai\"] as const;\nexport type TaskModelProvider = (typeof TASK_MODEL_PROVIDERS)[number];\n\nexport const TASK_MODEL_MAX_LENGTH = 120;\n\n/**\n * Model part allows letters, digits and `._:/-` so ollama tags (\"llama3.1:8b\") and\n * registry paths (\"library/qwen2.5-coder\") pass — and NOTHING else, because this string\n * is handed to a spawned CLI. No whitespace, no shell metacharacters, no quotes.\n */\nconst TASK_MODEL_PATTERN = /^(claude|ollama|openai):[A-Za-z0-9][A-Za-z0-9._:/-]*$/;\n\nexport interface ParsedTaskModel {\n provider: TaskModelProvider;\n model: string;\n}\n\nexport function parseTaskModel(value: string): ParsedTaskModel | null {\n if (value.length > TASK_MODEL_MAX_LENGTH || !TASK_MODEL_PATTERN.test(value)) return null;\n const idx = value.indexOf(\":\");\n return { provider: value.slice(0, idx) as TaskModelProvider, model: value.slice(idx + 1) };\n}\n\nexport function isValidTaskModel(value: string): boolean {\n return parseTaskModel(value) !== null;\n}\n\n/**\n * The console's dropdown. Opus 5 is the default a null Task.model resolves to (the\n * dispatcher's `defaultModel` config ships as this). Anything outside the list is still\n * accepted as free text if it passes the grammar — that is how ollama/openai models and\n * newer Claude ids get used without a server deploy.\n */\nexport const TASK_MODEL_PRESETS: ReadonlyArray<{ value: string; label: string }> = [\n { value: \"claude:claude-opus-5\", label: \"Opus 5 (default)\" },\n { value: \"claude:claude-fable-5\", label: \"Fable 5\" },\n { value: \"claude:claude-sonnet-5\", label: \"Sonnet 5\" },\n { value: \"claude:claude-haiku-4-5\", label: \"Haiku 4.5\" },\n];\n\n/** What a null Task.model means when no dispatcher config says otherwise. */\nexport const DEFAULT_TASK_MODEL = \"claude:claude-opus-5\";\n\n// ---------------------------------------------------------------------------------------\n// Notification recipients — the `task_notifications` platform_settings row.\n// ---------------------------------------------------------------------------------------\n\nexport const TASK_NOTIFICATIONS_KEY = \"task_notifications\";\n\n/**\n * Unlike alert recipients (absent = alerting off), task notifications default ON to the\n * owner: the board is the owner's window into agent activity, and a lost settings row\n * degrading to silence would defeat it. Turning them off is an explicit `enabled: false`.\n */\nexport const DEFAULT_TASK_NOTIFICATION_RECIPIENTS = [\"tonyphilip+frequencytalk@gmail.com\"];\n\nexport interface TaskNotificationSettings {\n enabled: boolean;\n emails: string[];\n}\n\n/**\n * Read the stored row defensively — same contract as `parseAlertRecipients`: a settings\n * blob written by another service is not a trusted shape, and a malformed row must\n * degrade to the default recipient rather than to a throw inside the sweeper tick.\n */\nexport function parseTaskNotifications(value: unknown): TaskNotificationSettings {\n if (!value || typeof value !== \"object\") {\n return { enabled: true, emails: [...DEFAULT_TASK_NOTIFICATION_RECIPIENTS] };\n }\n const row = value as { enabled?: unknown; emails?: unknown };\n const enabled = row.enabled !== false;\n const emails = Array.isArray(row.emails)\n ? row.emails.filter((entry): entry is string => typeof entry === \"string\" && RECIPIENT_PATTERN.test(entry.trim()))\n : [];\n return { enabled, emails: emails.length > 0 ? emails : [...DEFAULT_TASK_NOTIFICATION_RECIPIENTS] };\n}\n\n// Same deliberately permissive shape as alertRecipients.ts, and for the same reason: an\n// operator-typed address only ever meets nodemailer, and rejecting an unusual-but-valid\n// address is worse than accepting one that bounces.\nconst RECIPIENT_PATTERN = /^[^\\s@,;<>]+@[^\\s@,;<>]+\\.[^\\s@,;<>]+$/;\n","import { z } from \"zod\";\nimport type { TaskProject } from \"./tasks.js\";\n\n/**\n * The suite FEEDBACK STANDARD: bug reports and feature requests, one process for every app\n * (contract \"Feedback\"). The server owns the rules and an app owns only its form, so the\n * vocabulary, the limits and the text screening all live here: every app validates with\n * the same definitions the intake enforces, and a body that fails them at the server\n * therefore did not come from a conforming app. That inference is what the abuse rules\n * rest on, which is why none of this may be re-declared in a client.\n */\n\nexport const FEEDBACK_KINDS = [\"bug\", \"feature_request\"] as const;\nexport type FeedbackKind = (typeof FEEDBACK_KINDS)[number];\n\n/** One list for both kinds and every app. An app may HIDE a category that cannot apply to\n * it; it may not add one, or the triage queue stops being filterable across the suite. */\nexport const FEEDBACK_CATEGORIES = [\n \"audio\",\n \"connection\",\n \"sign_in_account\",\n \"calls\",\n \"chat\",\n \"video_screen_share\",\n \"stations_broadcast\",\n \"billing\",\n \"interface\",\n \"install_update\",\n \"other\",\n] as const;\nexport type FeedbackCategory = (typeof FEEDBACK_CATEGORIES)[number];\n\n/** The words every app shows. Customer-facing. */\nexport const FEEDBACK_KIND_LABELS: Record<FeedbackKind, string> = {\n bug: \"Bug\",\n feature_request: \"Feature request\",\n};\nexport const FEEDBACK_CATEGORY_LABELS: Record<FeedbackCategory, string> = {\n audio: \"Audio\",\n connection: \"Connection\",\n sign_in_account: \"Sign in and account\",\n calls: \"Calls\",\n chat: \"Chat\",\n video_screen_share: \"Video and screen share\",\n stations_broadcast: \"Stations and broadcast\",\n billing: \"Billing\",\n interface: \"Look and layout\",\n install_update: \"Install and update\",\n other: \"Something else\",\n};\n\nexport const FEEDBACK_STATUSES = [\"new\", \"triaged\", \"promoted\", \"dismissed\"] as const;\nexport type FeedbackStatus = (typeof FEEDBACK_STATUSES)[number];\n\nexport const FEEDBACK_LIMITS = {\n summaryMin: 5,\n summaryMax: 120,\n descriptionMin: 10,\n descriptionMax: 4000,\n versionMax: 40,\n platformMax: 40,\n userAgentMax: 400,\n /** More than this many links in one report is link spam. */\n maxLinks: 5,\n /** The whole request body. Far above what the fields can add up to, far below anything\n * worth sending. */\n bodyBytes: 16 * 1024,\n} as const;\n\n/* ------------------------------------------------------------------------------------ *\n * Abuse\n * ------------------------------------------------------------------------------------ */\n\nexport const FEEDBACK_ABUSE_KINDS = [\"flooding\", \"tampered\", \"duplicate\", \"link_spam\", \"attack_payload\"] as const;\nexport type FeedbackAbuseKind = (typeof FEEDBACK_ABUSE_KINDS)[number];\n\n/** Strikes of ONE kind inside the window that block the account. A single odd report never\n * blocks anybody: every threshold is above one on purpose. */\nexport const FEEDBACK_ABUSE_THRESHOLDS: Record<FeedbackAbuseKind, number> = {\n flooding: 5,\n tampered: 3,\n duplicate: 3,\n link_spam: 3,\n attack_payload: 3,\n};\n/** Strikes of ANY kind inside the window that block the account. */\nexport const FEEDBACK_ABUSE_MIXED_THRESHOLD = 6;\nexport const FEEDBACK_ABUSE_WINDOW_HOURS = 24;\n\n/** Plain words for the alert email and the admin console. Operator-facing. */\nexport const FEEDBACK_ABUSE_LABELS: Record<FeedbackAbuseKind, string> = {\n flooding: \"kept submitting after being told to slow down\",\n tampered: \"sent requests the app cannot produce (a modified client or a script)\",\n duplicate: \"submitted the same text repeatedly\",\n link_spam: \"submitted reports that were mostly links\",\n attack_payload: \"submitted text that looks like an injection attempt\",\n};\n\n/** Per-user submission limits, both kinds together. */\nexport const FEEDBACK_RATE = {\n perTenMinutes: 3,\n perDay: 10,\n /** Service-wide ceiling. Past it every submitter is asked to wait and operators are told. */\n globalPerHour: 500,\n} as const;\n\n/**\n * Why the account was blocked, as stored on the user row. Either the abuse kind whose\n * threshold tripped, `mixed`, or `admin` for a block raised by hand in the console.\n */\nexport type FeedbackBlockReason = FeedbackAbuseKind | \"mixed\" | \"admin\";\n\n/* ------------------------------------------------------------------------------------ *\n * Text screening\n * ------------------------------------------------------------------------------------ */\n\n/**\n * Removes what a report has no use for and a reader can be attacked with: control\n * characters, bidi overrides (text that displays in a different order than it is stored)\n * and invisible filler. Newlines and tabs survive, and so do U+200C/U+200D, because a\n * joined emoji is made of them.\n *\n * Apps run this BEFORE sending, so text that still changes under it at the server was not\n * sent by an app.\n */\nexport function cleanFeedbackText(raw: string): string {\n let out = \"\";\n const text = raw.replace(/\\r\\n?/g, \"\\n\").replace(/[\\u2028\\u2029]/g, \"\\n\");\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i);\n if (code === 0x0a || code === 0x09) {\n out += text[i];\n continue;\n }\n if (\n code <= 0x1f || // C0 controls\n (code >= 0x7f && code <= 0x9f) || // DEL + C1\n code === 0x200b || // zero-width space\n code === 0x200e || code === 0x200f || // LTR / RTL marks\n (code >= 0x202a && code <= 0x202e) || // bidi embeddings / overrides\n (code >= 0x2060 && code <= 0x2064) || // word joiner + invisible operators\n (code >= 0x2066 && code <= 0x2069) || // bidi isolates\n code === 0xfeff // BOM\n ) {\n continue;\n }\n out += text[i];\n }\n return out.trim();\n}\n\n/** True when the text is not in the form `cleanFeedbackText` produces. */\nexport function hasForbiddenFeedbackChars(text: string): boolean {\n return cleanFeedbackText(text) !== text;\n}\n\nconst LINK_PATTERN = /\\bhttps?:\\/\\/[^\\s<>\"']+|\\bwww\\.[^\\s<>\"']+/gi;\n\nexport function countFeedbackLinks(text: string): number {\n return text.match(LINK_PATTERN)?.length ?? 0;\n}\n\n/** Too many links, or a report that is more link than words. */\nexport function isFeedbackLinkSpam(text: string): boolean {\n const links = text.match(LINK_PATTERN) ?? [];\n if (links.length > FEEDBACK_LIMITS.maxLinks) return true;\n if (links.length === 0) return false;\n const linkChars = links.reduce((sum, l) => sum + l.length, 0);\n return linkChars * 2 > text.length;\n}\n\n/**\n * Patterns that read as an attempt to attack whatever displays or processes the report.\n * Named, so the console can say which fired without echoing the text into a header or log.\n *\n * ⚠️ A match is a SIGNAL, never a verdict: a genuine report about a real bug can quote any\n * of these, so the intake stores a matching report and counts a strike instead of refusing.\n */\nconst ATTACK_PATTERNS: ReadonlyArray<{ name: string; pattern: RegExp }> = [\n { name: \"html_script\", pattern: /<\\s*\\/?\\s*(script|iframe|object|embed|svg|img|style|link|meta)\\b/i },\n { name: \"html_event_handler\", pattern: /\\bon(error|load|click|mouseover|focus)\\s*=/i },\n { name: \"script_url\", pattern: /\\b(javascript|vbscript)\\s*:|data:\\s*text\\/html/i },\n { name: \"sql_injection\", pattern: /\\bunion\\s+(all\\s+)?select\\b|;\\s*(drop|truncate)\\s+table\\b|['\"]\\s*(or|and)\\s+['\"]?\\d+['\"]?\\s*=\\s*['\"]?\\d+/i },\n { name: \"prompt_injection\", pattern: /\\b(ignore|disregard|forget)\\s+(all\\s+|any\\s+|the\\s+|your\\s+)?(previous|prior|above|earlier)\\s+(instructions?|prompts?|rules|messages)\\b|\\bsystem\\s+prompt\\b|\\byou\\s+are\\s+now\\s+(a|an|in)\\b/i },\n { name: \"template_injection\", pattern: /\\$\\{\\s*jndi:|\\{\\{\\s*constructor\\b|<%=?\\s/i },\n { name: \"path_traversal\", pattern: /(\\.\\.[\\\\/]){2,}|\\/etc\\/(passwd|shadow)\\b/i },\n];\n\nexport function feedbackAttackSignals(text: string): string[] {\n return ATTACK_PATTERNS.filter((p) => p.pattern.test(text)).map((p) => p.name);\n}\n\n/** The form two submissions are compared in to decide they are the same text. */\nexport function normaliseFeedbackForDuplicate(text: string): string {\n return text.toLowerCase().replace(/\\s+/g, \" \").trim();\n}\n\n/* ------------------------------------------------------------------------------------ *\n * Wire schema\n * ------------------------------------------------------------------------------------ */\n\nconst cleanText = (min: number, max: number) =>\n z\n .string()\n .min(min)\n .max(max)\n .refine((s) => !hasForbiddenFeedbackChars(s), { message: \"Contains characters that are not allowed.\" });\n\n/**\n * What the app knows about itself. Deliberately small and fixed: no logs, no tokens, no\n * free-form record, and WHICH app sent it is not here at all (the server reads that from\n * the access token, so a report cannot claim to come from another app).\n */\nexport const FeedbackContextSchema = z.strictObject({\n appVersion: z.string().max(FEEDBACK_LIMITS.versionMax).nullable(),\n shellVersion: z.string().max(FEEDBACK_LIMITS.versionMax).nullable(),\n platform: z.string().max(FEEDBACK_LIMITS.platformMax).nullable(),\n userAgent: z.string().max(FEEDBACK_LIMITS.userAgentMax).nullable(),\n});\nexport type FeedbackContext = z.infer<typeof FeedbackContextSchema>;\n\nexport const FeedbackBodySchema = z.strictObject({\n kind: z.enum(FEEDBACK_KINDS),\n category: z.enum(FEEDBACK_CATEGORIES),\n summary: cleanText(FEEDBACK_LIMITS.summaryMin, FEEDBACK_LIMITS.summaryMax).describe(\"One line. Already passed through the documented text cleaning.\"),\n description: cleanText(FEEDBACK_LIMITS.descriptionMin, FEEDBACK_LIMITS.descriptionMax).describe(\"The report, in words. Text only: no attachments.\"),\n context: FeedbackContextSchema,\n});\nexport type FeedbackBody = z.infer<typeof FeedbackBodySchema>;\n\n/**\n * What a person typed, checked the way the intake will check it. Returns the sentence to\n * show, or null when it may be sent. Apps call this before sending, so a refusal the server\n * would give for the same reason is never spent as an abuse strike.\n */\nexport function feedbackTextProblem(summary: string, description: string): string | null {\n if (summary.length < FEEDBACK_LIMITS.summaryMin) return \"Add a short summary.\";\n if (summary.length > FEEDBACK_LIMITS.summaryMax) return `Keep the summary under ${FEEDBACK_LIMITS.summaryMax} characters.`;\n if (description.length < FEEDBACK_LIMITS.descriptionMin) return \"Describe it in a sentence or two.\";\n if (description.length > FEEDBACK_LIMITS.descriptionMax) return `Keep the description under ${FEEDBACK_LIMITS.descriptionMax} characters.`;\n if (isFeedbackLinkSpam(`${summary}\\n${description}`)) return \"Describe it in words. A report cannot be mostly links.\";\n return null;\n}\n\n/* ------------------------------------------------------------------------------------ *\n * Routing\n * ------------------------------------------------------------------------------------ */\n\n/**\n * Which board lane a report belongs to, by the registered client that sent it. A client\n * missing here lands on `platform` rather than on somebody else's lane.\n */\nconst FEEDBACK_PROJECT_BY_CLIENT: Record<string, TaskProject> = {\n \"frequency-web\": \"frequency\",\n \"tuner-windows\": \"tuner\",\n \"tuner-apple\": \"tuner_apple\",\n \"tuner-steamos\": \"tuner_steamos\",\n switchboard: \"switchboard\",\n \"switchboard-steamos\": \"switchboard_steamos\",\n broadcast: \"broadcast\",\n \"broadcast-apple\": \"broadcast_apple\",\n \"frequency-site\": \"site\",\n};\n\nexport function feedbackProjectFor(clientId: string): TaskProject {\n return FEEDBACK_PROJECT_BY_CLIENT[clientId] ?? \"platform\";\n}\n","import { z } from \"zod\";\n\n/**\n * The owner's emoji art, mapped to the Unicode emoji each tile draws. ONE copy for the whole\n * platform: the Service Manager draws from it, and the control plane serves it to every other\n * app as the emoji library (`GET /emoji`, capability `emoji-library`, contract §21).\n *\n * ⚠️ **The wire carries the Unicode character, never a tile id.** A message says \"😀\"; this\n * catalog only decides what an app DRAWS for it. A pasted copy or an app without the library\n * shows its own emoji, so nothing about the art can break a conversation.\n *\n * Each row is `[tile, emoji, name, keywords]`, plus an optional `category` (below):\n * - `tile` is the sliced image's position (`client/public/emoji/<size>/<tile>.webp`, made by\n * `client/scripts/emoji/slice.mjs`). Positions, not codepoints, so relabelling a tile is\n * an edit here and never a rename. Tiles never leave this repo: the library's public id is\n * the character's code points (`emojiArtId`).\n * - `emoji` is the character. An EMPTY string marks a tile that duplicates one already\n * mapped (the sheets draw some emoji twice, e.g. a second nerd face); it is kept out of\n * the picker, the renderer and the library until someone gives it a character of its own.\n * Sheets 11 to 13 also draw app icons with no Unicode emoji at all (a stapler, a settings\n * sliders panel, a QR code); those are empty too, marked `// not a Unicode emoji`.\n * A tile drawn WRONG (a mirrored flag emblem, a clock hand on the wrong hour) is empty as\n * well, marked `// regenerate: <what is wrong>`: its name and keywords stay so the redrawn\n * tile only needs its character back.\n * - `name` is the search name and the source of the `:shortcode:`.\n * - `keywords` feed search and the \"pizza\" -> 🍕 suggestion.\n * - `category`, optional, is a category id that overrides the sheet's. Only the two MIXED\n * sheets (41 and 42: rare flags, symbols, objects, people and weather on one page) carry it,\n * on every row; every other sheet belongs whole to one category through `sheets` below.\n *\n * Labelled by eye from the sheets on 2026-09-27 (sheets 11 to 13 on 2026-09-30, 14 to 42 on\n * 2026-10-01, checked against Unicode emoji-test.txt 18.0).\n */\n\nexport type EmojiRow = readonly [tile: string, emoji: string, name: string, keywords: string, category?: string];\n\nexport interface EmojiCategory {\n id: string;\n label: string;\n /** Which sheets' tiles belong to it (a row's own `category` overrides this). */\n sheets: readonly number[];\n}\n\n/** Picker tabs, in order. Sheets 41 and 42 are in none: they are mixed, so each row names its own. */\nexport const EMOJI_CATEGORIES: readonly EmojiCategory[] = [\n { id: \"smileys\", label: \"Smileys\", sheets: [1, 2, 14] },\n { id: \"hands\", label: \"Hands and body\", sheets: [3, 21] },\n { id: \"people\", label: \"People\", sheets: [4, 16, 20, 26, 33, 38] },\n { id: \"symbols\", label: \"Hearts and symbols\", sheets: [5, 12, 19, 28, 29, 34] },\n { id: \"nature\", label: \"Animals and nature\", sheets: [6, 18, 39] },\n { id: \"food\", label: \"Food and drink\", sheets: [7, 15, 30] },\n { id: \"activities\", label: \"Activities\", sheets: [8, 23] },\n { id: \"objects\", label: \"Objects\", sheets: [9, 11, 13, 17, 27, 40] },\n { id: \"travel\", label: \"Travel and weather\", sheets: [10, 22, 25, 32, 44] },\n { id: \"flags\", label: \"Flags\", sheets: [24, 31, 35, 36, 37, 46, 47, 48, 49, 50, 51, 52, 53, 55, 56, 57, 58] },\n];\n\nexport const EMOJI_ROWS: readonly EmojiRow[] = [\n // ── sheet 1: smileys ──\n [\"s01-r1c1\", \"😄\", \"grinning face with smiling eyes\", \"happy smile joy laugh\"],\n [\"s01-r1c2\", \"😁\", \"beaming face\", \"grin happy teeth smile\"],\n [\"s01-r1c3\", \"😂\", \"tears of joy\", \"laugh lol funny crying haha\"],\n [\"s01-r1c4\", \"😉\", \"winking face\", \"wink flirt joke\"],\n [\"s01-r1c5\", \"🥰\", \"smiling face with hearts\", \"love adore crush affection\"],\n [\"s01-r1c6\", \"😍\", \"heart eyes\", \"love crush adore\"],\n [\"s01-r1c7\", \"🤩\", \"star struck\", \"wow amazing excited stars\"],\n [\"s01-r2c1\", \"😎\", \"cool sunglasses\", \"cool chill confident\"],\n [\"s01-r2c2\", \"😏\", \"smirking face\", \"smirk sly smug\"],\n [\"s01-r2c3\", \"🤔\", \"thinking face\", \"think hmm wonder consider\"],\n [\"s01-r2c4\", \"🤫\", \"shushing face\", \"quiet secret hush shh\"],\n [\"s01-r2c5\", \"😐\", \"neutral face\", \"meh blank\"],\n [\"s01-r2c6\", \"😑\", \"expressionless face\", \"blank unimpressed\"],\n [\"s01-r2c7\", \"🙄\", \"rolling eyes\", \"eyeroll whatever annoyed\"],\n [\"s01-r3c1\", \"😮\", \"face with open mouth\", \"surprised wow oh\"],\n [\"s01-r3c2\", \"😨\", \"fearful face\", \"scared afraid fear\"],\n [\"s01-r3c3\", \"🤯\", \"exploding head\", \"mind blown shocked\"],\n [\"s01-r3c4\", \"😴\", \"sleeping face\", \"sleep tired zzz\"],\n [\"s01-r3c5\", \"🥱\", \"yawning face\", \"tired bored sleepy yawn\"],\n [\"s01-r3c6\", \"😪\", \"sleepy face\", \"tired sleepy\"],\n [\"s01-r3c7\", \"🤮\", \"vomiting face\", \"sick gross puke\"],\n [\"s01-r4c1\", \"😢\", \"crying face\", \"sad tear cry\"],\n [\"s01-r4c2\", \"😭\", \"loudly crying\", \"sob sad cry tears\"],\n [\"s01-r4c3\", \"😮💨\", \"face exhaling\", \"sigh relief exhale\"],\n [\"s01-r4c4\", \"🥺\", \"pleading face\", \"please puppy eyes beg\"],\n [\"s01-r4c5\", \"😰\", \"anxious face with sweat\", \"nervous worried anxious\"],\n [\"s01-r4c6\", \"😱\", \"screaming in fear\", \"scream shock horror\"],\n [\"s01-r4c7\", \"😠\", \"angry face\", \"angry mad grumpy\"],\n [\"s01-r5c1\", \"😡\", \"enraged face\", \"furious rage angry mad\"],\n [\"s01-r5c2\", \"🫠\", \"melting face\", \"melt hot embarrassed\"],\n [\"s01-r5c3\", \"🤐\", \"zipper mouth\", \"secret quiet sealed\"],\n [\"s01-r5c4\", \"🤑\", \"money mouth\", \"money rich cash dollar\"],\n [\"s01-r5c5\", \"🤓\", \"nerd face\", \"nerd geek glasses smart\"],\n [\"s01-r5c6\", \"🧐\", \"face with monocle\", \"inspect curious fancy\"],\n [\"s01-r5c7\", \"🥳\", \"partying face\", \"party celebrate birthday\"],\n [\"s01-r6c1\", \"😇\", \"smiling face with halo\", \"angel innocent halo\"],\n [\"s01-r6c2\", \"😈\", \"smiling devil\", \"devil evil mischief\"],\n [\"s01-r6c3\", \"🤡\", \"clown face\", \"clown silly joke\"],\n [\"s01-r6c4\", \"💀\", \"skull\", \"dead dying lol skull\"],\n [\"s01-r6c5\", \"🤖\", \"robot\", \"robot bot machine\"],\n [\"s01-r6c6\", \"👽\", \"alien\", \"alien ufo space\"],\n [\"s01-r6c7\", \"🤗\", \"hugging face\", \"hug thanks warm\"],\n [\"s01-r7c1\", \"😸\", \"grinning cat\", \"cat happy\"],\n [\"s01-r7c2\", \"😻\", \"heart eyes cat\", \"cat love\"],\n [\"s01-r7c3\", \"😿\", \"crying cat\", \"cat sad\"],\n [\"s01-r7c4\", \"😾\", \"pouting cat\", \"cat angry grumpy\"],\n [\"s01-r7c5\", \"😽\", \"kissing cat\", \"cat kiss\"],\n [\"s01-r7c6\", \"😺\", \"smiling cat\", \"cat happy\"],\n [\"s01-r7c7\", \"🫢\", \"hand over mouth\", \"gasp oops surprised\"],\n // ── sheet 2: more smileys ──\n [\"s02-r1c1\", \"😘\", \"blowing a kiss\", \"kiss love heart\"],\n [\"s02-r1c2\", \"😊\", \"smiling blushing face\", \"blush happy shy\"],\n [\"s02-r1c3\", \"😜\", \"winking tongue\", \"silly playful joke\"],\n [\"s02-r1c4\", \"😝\", \"squinting tongue\", \"silly playful\"],\n [\"s02-r1c5\", \"🙃\", \"upside down face\", \"sarcasm silly irony\"],\n [\"s02-r1c6\", \"😬\", \"grimacing face\", \"awkward yikes cringe\"],\n [\"s02-r1c7\", \"😟\", \"worried face\", \"worried concerned nervous\"],\n [\"s02-r2c1\", \"😅\", \"sweat smile\", \"phew relief nervous laugh\"],\n [\"s02-r2c2\", \"🥵\", \"hot face\", \"hot heat sweating\"],\n [\"s02-r2c3\", \"🥶\", \"cold face\", \"cold freezing ice\"],\n [\"s02-r2c4\", \"🤕\", \"head bandage\", \"hurt injured ouch\"],\n [\"s02-r2c5\", \"🤒\", \"thermometer face\", \"sick ill fever\"],\n [\"s02-r2c6\", \"😵💫\", \"spiral eyes\", \"dizzy confused\"],\n [\"s02-r2c7\", \"🤢\", \"nauseated face\", \"sick gross nausea\"],\n [\"s02-r3c1\", \"😔\", \"pensive face\", \"sad thoughtful down\"],\n [\"s02-r3c2\", \"😞\", \"disappointed face\", \"sad disappointed\"],\n [\"s02-r3c3\", \"😫\", \"tired face\", \"tired exhausted fed up\"],\n [\"s02-r3c4\", \"😤\", \"face with steam\", \"frustrated triumph huff\"],\n [\"s02-r3c5\", \"😲\", \"astonished face\", \"shocked amazed wow\"],\n [\"s02-r3c6\", \"\", \"shushing face\", \"\"],\n [\"s02-r3c7\", \"🤥\", \"lying face\", \"lie liar pinocchio\"],\n [\"s02-r4c1\", \"🤧\", \"sneezing face\", \"sneeze sick tissue\"],\n [\"s02-r4c2\", \"😷\", \"face with mask\", \"mask sick\"],\n [\"s02-r4c3\", \"🤠\", \"cowboy\", \"cowboy yeehaw hat\"],\n [\"s02-r4c4\", \"\", \"cowgirl\", \"\"],\n [\"s02-r4c5\", \"🥲\", \"smiling with tear\", \"grateful touched bittersweet\"],\n [\"s02-r4c6\", \"🫣\", \"peeking face\", \"peek shy scared\"],\n [\"s02-r4c7\", \"🫡\", \"saluting face\", \"salute yes sir respect\"],\n [\"s02-r5c1\", \"😶🌫️\", \"face in clouds\", \"foggy distracted daydream\"],\n [\"s02-r5c2\", \"🫥\", \"dotted line face\", \"invisible hidden\"],\n [\"s02-r5c3\", \"🥹\", \"holding back tears\", \"touched grateful emotional\"],\n [\"s02-r5c4\", \"😵\", \"dizzy face\", \"dizzy knocked out\"],\n [\"s02-r5c5\", \"😩\", \"weary face\", \"weary tired ugh\"],\n [\"s02-r5c6\", \"😌\", \"relieved face\", \"relieved content calm\"],\n [\"s02-r5c7\", \"\", \"smirk with puff\", \"\"],\n [\"s02-r6c1\", \"😚\", \"kissing closed eyes\", \"kiss\"],\n [\"s02-r6c2\", \"☺️\", \"smiling face\", \"happy warm blush\"],\n [\"s02-r6c3\", \"🤤\", \"drooling face\", \"drool hungry want\"],\n [\"s02-r6c4\", \"🤪\", \"zany face\", \"crazy silly wild\"],\n [\"s02-r6c5\", \"\", \"nerd face\", \"\"],\n [\"s02-r6c6\", \"\", \"face with monocle\", \"\"],\n [\"s02-r6c7\", \"\", \"thinking face\", \"\"],\n [\"s02-r7c1\", \"\", \"zipper mouth\", \"\"],\n [\"s02-r7c2\", \"\", \"money mouth\", \"\"],\n [\"s02-r7c3\", \"\", \"hugging face\", \"\"],\n [\"s02-r7c4\", \"\", \"star struck\", \"\"],\n [\"s02-r7c5\", \"\", \"exploding head\", \"\"],\n [\"s02-r7c6\", \"\", \"pleading face\", \"\"],\n [\"s02-r7c7\", \"\", \"winking tongue\", \"\"],\n // ── sheet 3: hands and body ──\n [\"s03-r1c1\", \"👍\", \"thumbs up\", \"yes ok good agree like\"],\n [\"s03-r1c2\", \"👎\", \"thumbs down\", \"no bad dislike disagree\"],\n [\"s03-r1c3\", \"👏\", \"clapping hands\", \"clap applause bravo\"],\n [\"s03-r1c4\", \"🙌\", \"raising hands\", \"hooray celebrate yay\"],\n [\"s03-r1c5\", \"👋\", \"waving hand\", \"wave hello hi bye\"],\n [\"s03-r1c6\", \"👌\", \"ok hand\", \"ok perfect fine\"],\n [\"s03-r1c7\", \"✌️\", \"victory hand\", \"peace victory\"],\n [\"s03-r2c1\", \"🤞\", \"crossed fingers\", \"luck hope wish\"],\n [\"s03-r2c2\", \"🤟\", \"love you gesture\", \"love you rock\"],\n [\"s03-r2c3\", \"🤙\", \"call me hand\", \"call shaka hang loose\"],\n [\"s03-r2c4\", \"\", \"snapping fingers\", \"\"],\n [\"s03-r2c5\", \"🤏\", \"pinching hand\", \"small tiny little bit\"],\n [\"s03-r2c6\", \"👈\", \"pointing left\", \"left point\"],\n [\"s03-r2c7\", \"👉\", \"pointing right\", \"right point\"],\n [\"s03-r3c1\", \"☝️\", \"index pointing up\", \"one point up\"],\n [\"s03-r3c2\", \"👇\", \"pointing down\", \"down point below\"],\n [\"s03-r3c3\", \"\", \"pointing left\", \"\"],\n [\"s03-r3c4\", \"👆\", \"backhand pointing up\", \"up point above\"],\n [\"s03-r3c5\", \"✊\", \"raised fist\", \"fist power solidarity\"],\n [\"s03-r3c6\", \"\", \"raised fist\", \"\"],\n [\"s03-r3c7\", \"🤜\", \"right facing fist\", \"fist bump punch\"],\n [\"s03-r4c1\", \"💪\", \"flexed biceps\", \"strong muscle strength\"],\n [\"s03-r4c2\", \"🙏\", \"folded hands\", \"please thanks pray hope\"],\n [\"s03-r4c3\", \"🤝\", \"handshake\", \"deal agree partnership\"],\n [\"s03-r4c4\", \"✍️\", \"writing hand\", \"write sign note\"],\n [\"s03-r4c5\", \"💅\", \"nail polish\", \"nails sassy manicure\"],\n [\"s03-r4c6\", \"🤳\", \"selfie\", \"selfie phone photo\"],\n [\"s03-r4c7\", \"👐\", \"open hands\", \"open hands\"],\n [\"s03-r5c1\", \"🤲\", \"palms up together\", \"offer please\"],\n [\"s03-r5c2\", \"🫶\", \"heart hands\", \"love heart support\"],\n [\"s03-r5c3\", \"👂\", \"ear\", \"listen hear\"],\n [\"s03-r5c4\", \"🦻\", \"ear with hearing aid\", \"hearing listen\"],\n [\"s03-r5c5\", \"👁️\", \"eye\", \"see look watch\"],\n [\"s03-r5c6\", \"👀\", \"eyes\", \"look see watching\"],\n [\"s03-r5c7\", \"👄\", \"mouth\", \"lips kiss speak\"],\n [\"s03-r6c1\", \"👅\", \"tongue\", \"tongue taste\"],\n [\"s03-r6c2\", \"🦷\", \"tooth\", \"tooth dentist\"],\n [\"s03-r6c3\", \"🦴\", \"bone\", \"bone skeleton\"],\n [\"s03-r6c4\", \"👣\", \"footprints\", \"steps walk feet\"],\n [\"s03-r6c5\", \"🦵\", \"leg\", \"leg kick\"],\n [\"s03-r6c6\", \"🦶\", \"foot\", \"foot\"],\n [\"s03-r6c7\", \"✋\", \"raised hand\", \"stop high five hand\"],\n [\"s03-r7c1\", \"🖖\", \"vulcan salute\", \"spock live long\"],\n [\"s03-r7c2\", \"🤌\", \"pinched fingers\", \"what italian chef kiss\"],\n [\"s03-r7c3\", \"\", \"oncoming fist\", \"punch fist bump\"], // redrawn as s54-r1c1\n [\"s03-r7c4\", \"🫱\", \"rightwards hand\", \"hand reach\"],\n [\"s03-r7c5\", \"\", \"waving hand\", \"\"],\n [\"s03-r7c6\", \"🤛\", \"left facing fist\", \"fist bump\"],\n [\"s03-r7c7\", \"🫰\", \"finger heart\", \"love heart money\"],\n // ── sheet 4: people ──\n [\"s04-r1c1\", \"🤷\", \"person shrugging\", \"shrug idk whatever dunno\"],\n [\"s04-r1c2\", \"🤦\", \"person facepalming\", \"facepalm ugh disbelief\"],\n [\"s04-r1c3\", \"💁\", \"person tipping hand\", \"info sassy\"],\n [\"s04-r1c4\", \"🙋\", \"person raising hand\", \"me question hello\"],\n [\"s04-r1c5\", \"🙆\", \"person gesturing ok\", \"ok yes\"],\n [\"s04-r1c6\", \"🙇\", \"person bowing\", \"sorry thank you bow\"],\n [\"s04-r1c7\", \"🙅\", \"person gesturing no\", \"no stop nope\"],\n [\"s04-r2c1\", \"\", \"person ok wink\", \"\"],\n [\"s04-r2c2\", \"\", \"person thumbs up\", \"\"],\n [\"s04-r2c3\", \"\", \"person cheering\", \"\"],\n [\"s04-r2c4\", \"\", \"person peace sign\", \"\"],\n [\"s04-r2c5\", \"🕺\", \"dancing\", \"dance party music\"],\n [\"s04-r2c6\", \"🤸\", \"cartwheel\", \"fun joy gymnastics\"],\n [\"s04-r2c7\", \"🏃\", \"person running\", \"run hurry late\"],\n [\"s04-r3c1\", \"🚶\", \"person walking\", \"walk\"],\n [\"s04-r3c2\", \"🧎\", \"person kneeling\", \"kneel pray\"],\n [\"s04-r3c3\", \"🧘\", \"person in lotus position\", \"meditate calm yoga zen\"],\n [\"s04-r3c4\", \"🛌\", \"person in bed\", \"sleep bed night\"],\n [\"s04-r3c5\", \"🧑💻\", \"technologist\", \"laptop work coding computer\"],\n [\"s04-r3c6\", \"🧑🎤\", \"singer\", \"sing music microphone\"],\n [\"s04-r3c7\", \"🧑🎨\", \"artist\", \"art paint\"],\n [\"s04-r4c1\", \"\", \"gamer\", \"\"],\n [\"s04-r4c2\", \"\", \"reader\", \"\"],\n [\"s04-r4c3\", \"🧑🍳\", \"cook\", \"chef cooking kitchen\"],\n [\"s04-r4c4\", \"🧑🔬\", \"scientist\", \"science lab experiment\"],\n [\"s04-r4c5\", \"👷\", \"construction worker\", \"build work hard hat\"],\n [\"s04-r4c6\", \"🕵️\", \"detective\", \"detective investigate spy\"],\n [\"s04-r4c7\", \"🦸\", \"superhero\", \"hero super power\"],\n [\"s04-r5c1\", \"🧙\", \"mage\", \"wizard magic\"],\n [\"s04-r5c2\", \"👼\", \"baby angel\", \"angel innocent\"],\n [\"s04-r5c3\", \"🧛\", \"vampire\", \"vampire dracula halloween\"],\n [\"s04-r5c4\", \"🧜\", \"merperson\", \"mermaid ocean\"],\n [\"s04-r5c5\", \"🧚\", \"fairy\", \"fairy magic\"],\n [\"s04-r5c6\", \"🧞\", \"genie\", \"genie wish lamp\"],\n [\"s04-r5c7\", \"🥷\", \"ninja\", \"ninja stealth\"],\n [\"s04-r6c1\", \"🧑🚀\", \"astronaut\", \"space rocket astronaut\"],\n [\"s04-r6c2\", \"🧑🚒\", \"firefighter\", \"fire firefighter\"],\n [\"s04-r6c3\", \"👮\", \"police officer\", \"police cop\"],\n [\"s04-r6c4\", \"🧑⚕️\", \"health worker\", \"nurse doctor health\"],\n [\"s04-r6c5\", \"\", \"doctor\", \"\"],\n [\"s04-r6c6\", \"🧑🎓\", \"student\", \"graduate school degree\"],\n [\"s04-r6c7\", \"🧑🌾\", \"farmer\", \"farm garden\"],\n [\"s04-r7c1\", \"⛹️\", \"person bouncing ball\", \"basketball sport\"],\n [\"s04-r7c2\", \"\", \"soccer player\", \"\"],\n [\"s04-r7c3\", \"\", \"tennis player\", \"\"],\n [\"s04-r7c4\", \"\", \"guitarist\", \"\"],\n [\"s04-r7c5\", \"🏋️\", \"weightlifter\", \"gym workout lift\"],\n [\"s04-r7c6\", \"\", \"photographer\", \"\"],\n [\"s04-r7c7\", \"🏄\", \"surfer\", \"surf beach wave\"],\n // ── sheet 5: hearts and symbols ──\n [\"s05-r1c1\", \"❤️\", \"red heart\", \"love heart\"],\n [\"s05-r1c2\", \"🧡\", \"orange heart\", \"love heart\"],\n [\"s05-r1c3\", \"💛\", \"yellow heart\", \"love heart friendship\"],\n [\"s05-r1c4\", \"💚\", \"green heart\", \"love heart\"],\n [\"s05-r1c5\", \"💙\", \"blue heart\", \"love heart\"],\n [\"s05-r1c6\", \"💜\", \"purple heart\", \"love heart\"],\n [\"s05-r1c7\", \"🖤\", \"black heart\", \"love heart\"],\n [\"s05-r2c1\", \"🤍\", \"white heart\", \"love heart\"],\n [\"s05-r2c2\", \"🤎\", \"brown heart\", \"love heart\"],\n [\"s05-r2c3\", \"🩷\", \"pink heart\", \"love heart\"],\n [\"s05-r2c4\", \"💖\", \"sparkling heart\", \"love sparkle\"],\n [\"s05-r2c5\", \"💓\", \"beating heart\", \"love heartbeat\"],\n [\"s05-r2c6\", \"💔\", \"broken heart\", \"sad heartbreak\"],\n [\"s05-r2c7\", \"❤️🩹\", \"mending heart\", \"healing recovery\"],\n [\"s05-r3c1\", \"❤️🔥\", \"heart on fire\", \"passion burning love\"],\n [\"s05-r3c2\", \"💕\", \"two hearts\", \"love\"],\n [\"s05-r3c3\", \"💞\", \"revolving hearts\", \"love\"],\n [\"s05-r3c4\", \"💝\", \"heart with ribbon\", \"gift love\"],\n [\"s05-r3c5\", \"\", \"heart with arrow\", \"cupid love crush\"], // redrawn as s54-r1c2\n [\"s05-r3c6\", \"💬\", \"speech bubble\", \"chat talk message\"],\n [\"s05-r3c7\", \"💭\", \"thought bubble\", \"think thought\"],\n [\"s05-r4c1\", \"💢\", \"anger symbol\", \"angry mad\"],\n [\"s05-r4c2\", \"💥\", \"collision\", \"boom bang explosion\"],\n [\"s05-r4c3\", \"💫\", \"dizzy\", \"dizzy stars\"],\n [\"s05-r4c4\", \"💦\", \"sweat droplets\", \"water splash sweat\"],\n [\"s05-r4c5\", \"➖\", \"minus\", \"minus dash\"],\n [\"s05-r4c6\", \"💤\", \"zzz\", \"sleep tired zzz\"],\n [\"s05-r4c7\", \"💯\", \"hundred points\", \"100 perfect score\"],\n [\"s05-r5c1\", \"✅\", \"check mark\", \"done yes complete check\"],\n [\"s05-r5c2\", \"❌\", \"cross mark\", \"no wrong cancel\"],\n [\"s05-r5c3\", \"⚠️\", \"warning\", \"warning caution alert\"],\n [\"s05-r5c4\", \"❓\", \"question mark\", \"question what\"],\n [\"s05-r5c5\", \"❗\", \"exclamation mark\", \"important alert\"],\n [\"s05-r5c6\", \"‼️\", \"double exclamation\", \"important wow\"],\n [\"s05-r5c7\", \"♻️\", \"recycling\", \"recycle green\"],\n [\"s05-r6c1\", \"☮️\", \"peace symbol\", \"peace\"],\n [\"s05-r6c2\", \"☯️\", \"yin yang\", \"balance\"],\n [\"s05-r6c3\", \"⭐\", \"star\", \"star favorite\"],\n [\"s05-r6c4\", \"🌟\", \"glowing star\", \"star shine\"],\n [\"s05-r6c5\", \"✨\", \"sparkles\", \"sparkle magic new shiny\"],\n [\"s05-r6c6\", \"🔥\", \"fire\", \"fire hot lit\"],\n [\"s05-r6c7\", \"💩\", \"pile of poo\", \"poop poo\"],\n [\"s05-r7c1\", \"🔒\", \"lock\", \"lock secure private\"],\n [\"s05-r7c2\", \"🔑\", \"key\", \"key password\"],\n [\"s05-r7c3\", \"🔔\", \"bell\", \"bell notification alert\"],\n [\"s05-r7c4\", \"📢\", \"loudspeaker\", \"announcement megaphone\"],\n [\"s05-r7c5\", \"💎\", \"gem\", \"diamond gem jewel\"],\n [\"s05-r7c6\", \"👑\", \"crown\", \"king queen crown\"],\n [\"s05-r7c7\", \"🎯\", \"direct hit\", \"target goal bullseye\"],\n // ── sheet 6: animals and nature ──\n [\"s06-r1c1\", \"🐶\", \"dog face\", \"dog puppy pet\"],\n [\"s06-r1c2\", \"🐱\", \"cat face\", \"cat kitten pet\"],\n [\"s06-r1c3\", \"🐭\", \"mouse face\", \"mouse\"],\n [\"s06-r1c4\", \"🐹\", \"hamster\", \"hamster pet\"],\n [\"s06-r1c5\", \"🐰\", \"rabbit face\", \"bunny rabbit\"],\n [\"s06-r1c6\", \"🦊\", \"fox\", \"fox\"],\n [\"s06-r1c7\", \"🐻\", \"bear\", \"bear\"],\n [\"s06-r2c1\", \"🐼\", \"panda\", \"panda\"],\n [\"s06-r2c2\", \"🐨\", \"koala\", \"koala\"],\n [\"s06-r2c3\", \"🐯\", \"tiger face\", \"tiger\"],\n [\"s06-r2c4\", \"🦁\", \"lion\", \"lion\"],\n [\"s06-r2c5\", \"🐮\", \"cow face\", \"cow\"],\n [\"s06-r2c6\", \"🐷\", \"pig face\", \"pig\"],\n [\"s06-r2c7\", \"🐸\", \"frog\", \"frog\"],\n [\"s06-r3c1\", \"🐵\", \"monkey face\", \"monkey\"],\n [\"s06-r3c2\", \"🐔\", \"chicken\", \"chicken hen\"],\n [\"s06-r3c3\", \"🐣\", \"hatching chick\", \"chick baby egg\"],\n [\"s06-r3c4\", \"🐧\", \"penguin\", \"penguin\"],\n [\"s06-r3c5\", \"🐦\", \"bird\", \"bird\"],\n [\"s06-r3c6\", \"🐥\", \"baby chick\", \"chick\"],\n [\"s06-r3c7\", \"🦉\", \"owl\", \"owl wise night\"],\n [\"s06-r4c1\", \"🦅\", \"eagle\", \"eagle bird\"],\n [\"s06-r4c2\", \"🦇\", \"bat\", \"bat halloween\"],\n [\"s06-r4c3\", \"🐺\", \"wolf\", \"wolf\"],\n [\"s06-r4c4\", \"🦄\", \"unicorn\", \"unicorn magic\"],\n [\"s06-r4c5\", \"🐝\", \"honeybee\", \"bee busy\"],\n [\"s06-r4c6\", \"🦋\", \"butterfly\", \"butterfly\"],\n [\"s06-r4c7\", \"🐌\", \"snail\", \"snail slow\"],\n [\"s06-r5c1\", \"🐞\", \"lady beetle\", \"ladybug bug\"],\n [\"s06-r5c2\", \"🐜\", \"ant\", \"ant bug\"],\n [\"s06-r5c3\", \"🐠\", \"tropical fish\", \"fish\"],\n [\"s06-r5c4\", \"🐬\", \"dolphin\", \"dolphin ocean\"],\n [\"s06-r5c5\", \"🐳\", \"spouting whale\", \"whale ocean\"],\n [\"s06-r5c6\", \"🐙\", \"octopus\", \"octopus\"],\n [\"s06-r5c7\", \"🦀\", \"crab\", \"crab\"],\n [\"s06-r6c1\", \"🐢\", \"turtle\", \"turtle slow\"],\n [\"s06-r6c2\", \"🐍\", \"snake\", \"snake\"],\n [\"s06-r6c3\", \"🐲\", \"dragon face\", \"dragon\"],\n [\"s06-r6c4\", \"🦖\", \"t rex\", \"dinosaur rex\"],\n [\"s06-r6c5\", \"🐾\", \"paw prints\", \"paws pet\"],\n [\"s06-r6c6\", \"🌳\", \"tree\", \"tree nature\"],\n [\"s06-r6c7\", \"🌺\", \"hibiscus\", \"flower\"],\n [\"s06-r7c1\", \"🌻\", \"sunflower\", \"flower sunflower\"],\n [\"s06-r7c2\", \"🌵\", \"cactus\", \"cactus desert\"],\n [\"s06-r7c3\", \"🍄\", \"mushroom\", \"mushroom\"],\n [\"s06-r7c4\", \"🍁\", \"maple leaf\", \"leaf autumn fall\"],\n [\"s06-r7c5\", \"🌞\", \"sun with face\", \"sun sunny happy\"],\n [\"s06-r7c6\", \"🌛\", \"moon with face\", \"moon night sleep\"],\n [\"s06-r7c7\", \"☁️\", \"cloud\", \"cloud cloudy weather\"],\n // ── sheet 7: food and drink ──\n [\"s07-r1c1\", \"🍏\", \"green apple\", \"apple fruit\"],\n [\"s07-r1c2\", \"🍎\", \"red apple\", \"apple fruit\"],\n [\"s07-r1c3\", \"🍐\", \"pear\", \"pear fruit\"],\n [\"s07-r1c4\", \"🍑\", \"peach\", \"peach fruit\"],\n [\"s07-r1c5\", \"🍒\", \"cherries\", \"cherry fruit\"],\n [\"s07-r1c6\", \"🍓\", \"strawberry\", \"strawberry fruit\"],\n [\"s07-r1c7\", \"🫐\", \"blueberries\", \"blueberry fruit\"],\n [\"s07-r2c1\", \"🍇\", \"grapes\", \"grapes fruit\"],\n [\"s07-r2c2\", \"🍉\", \"watermelon\", \"watermelon fruit summer\"],\n [\"s07-r2c3\", \"🍋\", \"lemon\", \"lemon fruit\"],\n [\"s07-r2c4\", \"🍌\", \"banana\", \"banana fruit\"],\n [\"s07-r2c5\", \"🍍\", \"pineapple\", \"pineapple fruit\"],\n [\"s07-r2c6\", \"🥭\", \"mango\", \"mango fruit\"],\n [\"s07-r2c7\", \"🥥\", \"coconut\", \"coconut\"],\n [\"s07-r3c1\", \"🥑\", \"avocado\", \"avocado\"],\n [\"s07-r3c2\", \"🥕\", \"carrot\", \"carrot vegetable\"],\n [\"s07-r3c3\", \"🌽\", \"corn\", \"corn\"],\n [\"s07-r3c4\", \"🌶️\", \"hot pepper\", \"spicy chili pepper\"],\n [\"s07-r3c5\", \"🍄🟫\", \"brown mushroom\", \"mushroom\"],\n [\"s07-r3c6\", \"🍞\", \"bread\", \"bread toast\"],\n [\"s07-r3c7\", \"🥐\", \"croissant\", \"croissant breakfast\"],\n [\"s07-r4c1\", \"🥞\", \"pancakes\", \"pancakes breakfast\"],\n [\"s07-r4c2\", \"🧀\", \"cheese\", \"cheese\"],\n [\"s07-r4c3\", \"🍳\", \"cooking egg\", \"egg breakfast\"],\n [\"s07-r4c4\", \"🥓\", \"bacon\", \"bacon breakfast\"],\n [\"s07-r4c5\", \"🍔\", \"hamburger\", \"burger food\"],\n [\"s07-r4c6\", \"🍟\", \"french fries\", \"fries food\"],\n [\"s07-r4c7\", \"🍕\", \"pizza\", \"pizza food\"],\n [\"s07-r5c1\", \"🌭\", \"hot dog\", \"hotdog food\"],\n [\"s07-r5c2\", \"🌮\", \"taco\", \"taco food\"],\n [\"s07-r5c3\", \"🌯\", \"burrito\", \"burrito food\"],\n [\"s07-r5c4\", \"🍜\", \"steaming bowl\", \"noodles ramen soup\"],\n [\"s07-r5c5\", \"🍣\", \"sushi\", \"sushi\"],\n [\"s07-r5c6\", \"\", \"sushi nigiri\", \"\"],\n [\"s07-r5c7\", \"🍙\", \"rice ball\", \"rice onigiri\"],\n [\"s07-r6c1\", \"🍪\", \"cookie\", \"cookie dessert\"],\n [\"s07-r6c2\", \"🍩\", \"doughnut\", \"donut dessert\"],\n [\"s07-r6c3\", \"🧁\", \"cupcake\", \"cupcake dessert\"],\n [\"s07-r6c4\", \"🍦\", \"soft ice cream\", \"ice cream dessert\"],\n [\"s07-r6c5\", \"🍫\", \"chocolate bar\", \"chocolate\"],\n [\"s07-r6c6\", \"🍿\", \"popcorn\", \"popcorn movie\"],\n [\"s07-r6c7\", \"☕\", \"hot beverage\", \"coffee tea\"],\n [\"s07-r7c1\", \"🍵\", \"teacup\", \"tea matcha\"],\n [\"s07-r7c2\", \"🧋\", \"bubble tea\", \"boba tea\"],\n [\"s07-r7c3\", \"🧃\", \"juice box\", \"juice\"],\n [\"s07-r7c4\", \"🥛\", \"glass of milk\", \"milk\"],\n [\"s07-r7c5\", \"🍺\", \"beer mug\", \"beer drink cheers\"],\n [\"s07-r7c6\", \"🍹\", \"tropical drink\", \"cocktail drink\"],\n [\"s07-r7c7\", \"🍷\", \"wine glass\", \"wine drink\"],\n [\"s07-r7c8\", \"\", \"clinking glasses\", \"cheers celebrate champagne toast\"], // redrawn as s54-r2c1\n // ── sheet 8: activities ──\n [\"s08-r1c1\", \"⚽\", \"soccer ball\", \"soccer football sport\"],\n [\"s08-r1c2\", \"🏀\", \"basketball\", \"basketball sport\"],\n [\"s08-r1c3\", \"🏈\", \"american football\", \"football sport\"],\n [\"s08-r1c4\", \"⚾\", \"baseball\", \"baseball sport\"],\n [\"s08-r1c5\", \"🎾\", \"tennis\", \"tennis sport\"],\n [\"s08-r1c6\", \"🏐\", \"volleyball\", \"volleyball sport\"],\n [\"s08-r1c7\", \"🎳\", \"bowling\", \"bowling\"],\n [\"s08-r2c1\", \"🏓\", \"ping pong\", \"table tennis\"],\n [\"s08-r2c2\", \"🏸\", \"badminton\", \"badminton\"],\n [\"s08-r2c3\", \"🥊\", \"boxing glove\", \"boxing fight\"],\n [\"s08-r2c4\", \"🥋\", \"martial arts uniform\", \"karate judo\"],\n [\"s08-r2c5\", \"👟\", \"running shoe\", \"shoe sneaker\"],\n [\"s08-r2c6\", \"🛹\", \"skateboard\", \"skate\"],\n [\"s08-r2c7\", \"🛼\", \"roller skate\", \"skate\"],\n [\"s08-r3c1\", \"🚲\", \"bicycle\", \"bike cycling\"],\n [\"s08-r3c2\", \"🏆\", \"trophy\", \"win winner champion\"],\n [\"s08-r3c3\", \"🥇\", \"gold medal\", \"first winner\"],\n [\"s08-r3c4\", \"🏅\", \"sports medal\", \"medal award\"],\n [\"s08-r3c5\", \"🎫\", \"ticket\", \"ticket event\"],\n [\"s08-r3c6\", \"🎵\", \"musical note\", \"music song\"],\n [\"s08-r3c7\", \"🎧\", \"headphone\", \"headphones music listen\"],\n [\"s08-r4c1\", \"🎤\", \"microphone\", \"mic sing karaoke\"],\n [\"s08-r4c2\", \"🎸\", \"guitar\", \"guitar music rock\"],\n [\"s08-r4c3\", \"🎹\", \"musical keyboard\", \"piano music\"],\n [\"s08-r4c4\", \"🎷\", \"saxophone\", \"sax jazz\"],\n [\"s08-r4c5\", \"🥁\", \"drum\", \"drum\"],\n [\"s08-r4c6\", \"🎲\", \"game die\", \"dice game\"],\n [\"s08-r4c7\", \"\", \"chess pawn\", \"chess strategy\"], // redrawn as s54-r2c2\n [\"s08-r5c1\", \"🎮\", \"video game\", \"game controller gaming\"],\n [\"s08-r5c2\", \"🧩\", \"puzzle piece\", \"puzzle\"],\n [\"s08-r5c3\", \"🎨\", \"artist palette\", \"art paint\"],\n [\"s08-r5c4\", \"📸\", \"camera with flash\", \"photo picture\"],\n [\"s08-r5c5\", \"🎬\", \"clapper board\", \"movie film action\"],\n [\"s08-r5c6\", \"📚\", \"books\", \"books study read\"],\n [\"s08-r5c7\", \"🪄\", \"magic wand\", \"magic\"],\n [\"s08-r6c1\", \"🔮\", \"crystal ball\", \"future fortune\"],\n [\"s08-r6c2\", \"🎁\", \"wrapped gift\", \"gift present birthday\"],\n [\"s08-r6c3\", \"\", \"wrapped gift\", \"\"],\n [\"s08-r6c4\", \"🎉\", \"party popper\", \"party celebrate congrats\"],\n [\"s08-r6c5\", \"🎊\", \"confetti ball\", \"confetti celebrate\"],\n [\"s08-r6c6\", \"🎈\", \"balloon\", \"balloon party birthday\"],\n [\"s08-r6c7\", \"🪁\", \"kite\", \"kite\"],\n [\"s08-r7c1\", \"🪀\", \"yo-yo\", \"yoyo toy\"],\n [\"s08-r7c2\", \"\", \"alphabet blocks\", \"\"],\n [\"s08-r7c3\", \"🧸\", \"teddy bear\", \"teddy toy\"],\n [\"s08-r7c4\", \"\", \"crown\", \"\"],\n [\"s08-r7c5\", \"\", \"gem\", \"\"],\n [\"s08-r7c6\", \"🔦\", \"flashlight\", \"torch light\"],\n [\"s08-r7c7\", \"\", \"island\", \"\"],\n // ── sheet 9: objects ──\n [\"s09-r1c1\", \"📱\", \"mobile phone\", \"phone cell\"],\n [\"s09-r1c2\", \"💻\", \"laptop\", \"laptop computer\"],\n [\"s09-r1c3\", \"🖥️\", \"desktop computer\", \"computer monitor\"],\n [\"s09-r1c4\", \"⌨️\", \"keyboard\", \"keyboard type\"],\n [\"s09-r1c5\", \"🖱️\", \"computer mouse\", \"mouse click\"],\n [\"s09-r1c6\", \"🖨️\", \"printer\", \"print\"],\n [\"s09-r1c7\", \"📷\", \"camera\", \"photo camera\"],\n [\"s09-r2c1\", \"📹\", \"video camera\", \"video record\"],\n [\"s09-r2c2\", \"📺\", \"television\", \"tv\"],\n [\"s09-r2c3\", \"📻\", \"radio\", \"radio broadcast\"],\n [\"s09-r2c4\", \"📡\", \"satellite antenna\", \"signal broadcast dish\"],\n [\"s09-r2c5\", \"💡\", \"light bulb\", \"idea light\"],\n [\"s09-r2c6\", \"🔋\", \"battery\", \"battery power charge\"],\n [\"s09-r2c7\", \"🔌\", \"electric plug\", \"plug power\"],\n [\"s09-r3c1\", \"💾\", \"floppy disk\", \"save disk\"],\n [\"s09-r3c2\", \"💿\", \"optical disk\", \"cd disc\"],\n [\"s09-r3c3\", \"🔍\", \"magnifying glass\", \"search find zoom\"],\n [\"s09-r3c4\", \"🧰\", \"toolbox\", \"tools fix\"],\n [\"s09-r3c5\", \"🔧\", \"wrench\", \"fix tool\"],\n [\"s09-r3c6\", \"🔨\", \"hammer\", \"build tool\"],\n [\"s09-r3c7\", \"🪛\", \"screwdriver\", \"tool fix\"],\n [\"s09-r4c1\", \"🔩\", \"nut and bolt\", \"hardware\"],\n [\"s09-r4c2\", \"🖌️\", \"paintbrush\", \"paint art\"],\n [\"s09-r4c3\", \"✂️\", \"scissors\", \"cut\"],\n [\"s09-r4c4\", \"📏\", \"straight ruler\", \"ruler measure\"],\n [\"s09-r4c5\", \"📋\", \"clipboard\", \"list checklist tasks\"],\n [\"s09-r4c6\", \"💼\", \"briefcase\", \"work business\"],\n [\"s09-r4c7\", \"🎒\", \"backpack\", \"school bag\"],\n [\"s09-r5c1\", \"🛍️\", \"shopping bags\", \"shopping\"],\n [\"s09-r5c2\", \"📦\", \"package\", \"box delivery shipping\"],\n [\"s09-r5c3\", \"✉️\", \"envelope\", \"mail email letter\"],\n [\"s09-r5c4\", \"📬\", \"mailbox\", \"mail\"],\n [\"s09-r5c5\", \"📎\", \"paperclip\", \"attach attachment clip file\"],\n [\"s09-r5c6\", \"📌\", \"pushpin\", \"pin important\"],\n [\"s09-r5c7\", \"📅\", \"calendar\", \"date schedule calendar\"],\n [\"s09-r6c1\", \"\", \"clock\", \"time clock\"], // redrawn as s45-r1c5\n [\"s09-r6c2\", \"⏰\", \"alarm clock\", \"alarm wake time\"],\n [\"s09-r6c3\", \"⏳\", \"hourglass\", \"wait time\"],\n [\"s09-r6c4\", \"💰\", \"money bag\", \"money cash\"],\n [\"s09-r6c5\", \"💳\", \"credit card\", \"card pay\"],\n [\"s09-r6c6\", \"🧾\", \"receipt\", \"receipt bill\"],\n [\"s09-r6c7\", \"\", \"gem\", \"\"],\n [\"s09-r7c1\", \"💍\", \"ring\", \"ring engaged wedding\"],\n [\"s09-r7c2\", \"🛡️\", \"shield\", \"shield protect security\"],\n [\"s09-r7c3\", \"🗡️\", \"dagger\", \"sword blade\"],\n [\"s09-r7c4\", \"\", \"potion\", \"\"],\n [\"s09-r7c5\", \"🧪\", \"test tube\", \"science experiment\"],\n [\"s09-r7c6\", \"💉\", \"syringe\", \"vaccine shot\"],\n [\"s09-r7c7\", \"🧲\", \"magnet\", \"magnet attract\"],\n // ── sheet 10: travel and weather ──\n [\"s10-r1c1\", \"🚗\", \"car\", \"car drive\"],\n [\"s10-r1c2\", \"🚕\", \"taxi\", \"taxi cab\"],\n [\"s10-r1c3\", \"🚓\", \"police car\", \"police\"],\n [\"s10-r1c4\", \"🚌\", \"bus\", \"bus\"],\n [\"s10-r1c5\", \"🚚\", \"delivery truck\", \"truck delivery\"],\n [\"s10-r1c6\", \"🚜\", \"tractor\", \"tractor farm\"],\n [\"s10-r1c7\", \"🏍️\", \"motorcycle\", \"motorbike\"],\n [\"s10-r2c1\", \"\", \"bicycle\", \"\"],\n [\"s10-r2c2\", \"🚂\", \"locomotive\", \"train\"],\n [\"s10-r2c3\", \"🚋\", \"tram\", \"tram streetcar\"],\n [\"s10-r2c4\", \"✈️\", \"airplane\", \"plane flight travel\"],\n [\"s10-r2c5\", \"🚁\", \"helicopter\", \"helicopter\"],\n [\"s10-r2c6\", \"🚀\", \"rocket\", \"rocket launch ship it\"],\n [\"s10-r2c7\", \"⛵\", \"sailboat\", \"boat sail\"],\n [\"s10-r3c1\", \"🚢\", \"ship\", \"ship cruise\"],\n [\"s10-r3c2\", \"⚓\", \"anchor\", \"anchor\"],\n [\"s10-r3c3\", \"⛽\", \"fuel pump\", \"gas fuel\"],\n [\"s10-r3c4\", \"🚦\", \"traffic light\", \"traffic\"],\n [\"s10-r3c5\", \"🛑\", \"stop sign\", \"stop\"],\n [\"s10-r3c6\", \"\", \"world map\", \"map directions\"], // redrawn as s54-r1c3\n [\"s10-r3c7\", \"🧭\", \"compass\", \"compass direction\"],\n [\"s10-r4c1\", \"🏖️\", \"beach\", \"beach vacation\"],\n [\"s10-r4c2\", \"🏝️\", \"desert island\", \"island vacation\"],\n [\"s10-r4c3\", \"🏔️\", \"mountain\", \"mountain snow\"],\n [\"s10-r4c4\", \"🌋\", \"volcano\", \"volcano\"],\n [\"s10-r4c5\", \"🏜️\", \"desert\", \"desert\"],\n [\"s10-r4c6\", \"🏕️\", \"camping\", \"camp tent\"],\n [\"s10-r4c7\", \"🏠\", \"house\", \"home house\"],\n [\"s10-r5c1\", \"🏙️\", \"cityscape\", \"city\"],\n [\"s10-r5c2\", \"🏫\", \"school\", \"school\"],\n [\"s10-r5c3\", \"🏰\", \"castle\", \"castle\"],\n [\"s10-r5c4\", \"🌉\", \"bridge\", \"bridge\"],\n [\"s10-r5c5\", \"🎡\", \"ferris wheel\", \"fair\"],\n [\"s10-r5c6\", \"🌅\", \"sunrise\", \"sunrise morning\"],\n [\"s10-r5c7\", \"🌇\", \"sunset\", \"sunset evening\"],\n [\"s10-r6c1\", \"🌈\", \"rainbow\", \"rainbow\"],\n [\"s10-r6c2\", \"☂️\", \"umbrella\", \"rain umbrella\"],\n [\"s10-r6c3\", \"🌂\", \"closed umbrella\", \"umbrella\"],\n [\"s10-r6c4\", \"🌧️\", \"rain cloud\", \"rain weather\"],\n [\"s10-r6c5\", \"⛈️\", \"thunderstorm\", \"storm lightning weather\"],\n [\"s10-r6c6\", \"❄️\", \"snowflake\", \"snow cold winter\"],\n [\"s10-r6c7\", \"☃️\", \"snowman\", \"snow winter\"],\n [\"s10-r7c1\", \"🌪️\", \"tornado\", \"tornado storm\"],\n [\"s10-r7c2\", \"🌀\", \"cyclone\", \"hurricane storm\"],\n [\"s10-r7c3\", \"🌙\", \"crescent moon\", \"moon night\"],\n [\"s10-r7c4\", \"🌕\", \"full moon\", \"moon\"],\n [\"s10-r7c5\", \"🌍\", \"globe\", \"earth world\"],\n [\"s10-r7c6\", \"☀️\", \"sun\", \"sun sunny weather\"],\n [\"s10-r7c7\", \"🌃\", \"night with stars\", \"night\"],\n // ── sheet 11: office and school ──\n [\"s11-r1c1\", \"✏️\", \"pencil\", \"pencil write draw school\"],\n [\"s11-r1c2\", \"🖊️\", \"pen\", \"pen ballpoint write sign\"],\n [\"s11-r1c3\", \"\", \"ballpoint pen\", \"pen\"], // duplicate of s11-r1c2\n [\"s11-r1c4\", \"🖋️\", \"fountain pen\", \"pen ink write signature\"],\n [\"s11-r1c5\", \"🖍️\", \"crayon\", \"crayon draw color kids\"],\n [\"s11-r1c6\", \"\", \"highlighter\", \"highlighter marker\"], // not a Unicode emoji\n [\"s11-r1c7\", \"\", \"paintbrush\", \"paint\"], // duplicate of s09-r4c2\n [\"s11-r2c1\", \"\", \"eraser\", \"eraser rubber\"], // not a Unicode emoji on current devices ( eraser is Emoji 18.0)\n [\"s11-r2c2\", \"\", \"ruler\", \"ruler\"], // duplicate of s09-r4c4\n [\"s11-r2c3\", \"📐\", \"triangular ruler\", \"set square triangle geometry math\"],\n [\"s11-r2c4\", \"📓\", \"notebook\", \"notebook notes school\"],\n [\"s11-r2c5\", \"📒\", \"ledger\", \"ledger notebook notes\"],\n [\"s11-r2c6\", \"🗒️\", \"spiral notepad\", \"notepad notes memo list\"],\n [\"s11-r2c7\", \"\", \"checklist clipboard\", \"clipboard\"], // duplicate of s09-r4c5\n [\"s11-r3c1\", \"🗓️\", \"spiral calendar\", \"calendar date schedule planner\"],\n [\"s11-r3c2\", \"🔖\", \"bookmark\", \"bookmark save mark\"],\n [\"s11-r3c3\", \"\", \"stack of paper\", \"paper\"], // not a Unicode emoji\n [\"s11-r3c4\", \"📁\", \"file folder\", \"folder file directory\"],\n [\"s11-r3c5\", \"📂\", \"open file folder\", \"folder open files\"],\n [\"s11-r3c6\", \"🗄️\", \"file cabinet\", \"cabinet filing archive\"],\n [\"s11-r3c7\", \"\", \"paperclip\", \"paperclip\"], // duplicate of s09-r5c5\n [\"s11-r4c1\", \"\", \"pushpin\", \"pin\"], // duplicate of s09-r5c6\n [\"s11-r4c2\", \"\", \"stapler\", \"stapler\"], // not a Unicode emoji\n [\"s11-r4c3\", \"\", \"tape dispenser\", \"tape\"], // not a Unicode emoji\n [\"s11-r4c4\", \"\", \"scissors\", \"scissors\"], // duplicate of s09-r4c3\n [\"s11-r4c5\", \"\", \"glue bottle\", \"glue\"], // not a Unicode emoji\n [\"s11-r4c6\", \"\", \"calculator\", \"calculator\"], // not a Unicode emoji\n [\"s11-r4c7\", \"🧮\", \"abacus\", \"abacus count math\"],\n [\"s11-r5c1\", \"\", \"magnifying glass\", \"search\"], // duplicate of s09-r3c3\n [\"s11-r5c2\", \"🔬\", \"microscope\", \"microscope science lab\"],\n [\"s11-r5c3\", \"🎓\", \"graduation cap\", \"graduation school degree college\"],\n [\"s11-r5c4\", \"\", \"chalkboard\", \"chalkboard blackboard\"], // not a Unicode emoji\n [\"s11-r5c5\", \"\", \"stack of books\", \"books\"], // duplicate of s08-r5c6\n [\"s11-r5c6\", \"📕\", \"closed book\", \"book read\"],\n [\"s11-r5c7\", \"📖\", \"open book\", \"book read reading study\"],\n [\"s11-r6c1\", \"\", \"blueprint\", \"blueprint plan\"], // not a Unicode emoji\n [\"s11-r6c2\", \"📊\", \"bar chart\", \"chart graph stats data\"],\n [\"s11-r6c3\", \"\", \"pie chart\", \"chart\"], // not a Unicode emoji\n [\"s11-r6c4\", \"\", \"briefcase\", \"briefcase\"], // duplicate of s09-r4c6\n [\"s11-r6c5\", \"\", \"document tray\", \"tray papers\"], // not a Unicode emoji (📥 needs its arrow)\n [\"s11-r6c6\", \"📄\", \"page facing up\", \"document page file paper approved\"],\n [\"s11-r6c7\", \"\", \"certificate\", \"certificate diploma\"], // not a Unicode emoji\n [\"s11-r7c1\", \"\", \"ink bottle\", \"ink\"], // not a Unicode emoji\n [\"s11-r7c2\", \"\", \"desk lamp\", \"lamp\"], // not a Unicode emoji\n [\"s11-r7c3\", \"\", \"pen cup\", \"pens pencils\"], // not a Unicode emoji\n [\"s11-r7c4\", \"\", \"potted plant\", \"plant\"], // duplicate of s13-r6c7\n [\"s11-r7c5\", \"\", \"sticky note\", \"note\"], // not a Unicode emoji\n [\"s11-r7c6\", \"\", \"hourglass\", \"hourglass\"], // duplicate of s09-r6c3\n [\"s11-r7c7\", \"\", \"target\", \"target\"], // duplicate of s05-r7c7\n // ── sheet 12: interface symbols ──\n [\"s12-r1c1\", \"\", \"speech bubble\", \"chat\"], // duplicate of s05-r3c6\n [\"s12-r1c2\", \"\", \"conversation\", \"chat conversation\"], // not a Unicode emoji\n [\"s12-r1c3\", \"\", \"thought bubble\", \"think\"], // duplicate of s05-r3c7\n [\"s12-r1c4\", \"\", \"inbox with letter\", \"inbox\"], // not a Unicode emoji (📥 needs its arrow)\n [\"s12-r1c5\", \"📤\", \"outbox tray\", \"outbox send upload tray\"],\n [\"s12-r1c6\", \"\", \"envelope\", \"mail\"], // duplicate of s09-r5c3\n [\"s12-r1c7\", \"\", \"open envelope\", \"mail letter\"], // not a Unicode emoji\n [\"s12-r2c1\", \"\", \"paper plane\", \"send\"], // not a Unicode emoji\n [\"s12-r2c2\", \"\", \"bell\", \"bell\"], // duplicate of s05-r7c3\n [\"s12-r2c3\", \"🔕\", \"bell with slash\", \"mute silent notifications off quiet\"],\n [\"s12-r2c4\", \"\", \"phone notification\", \"phone\"], // duplicate of s09-r1c1\n [\"s12-r2c5\", \"⚙️\", \"gear\", \"settings gear cog options\"],\n [\"s12-r2c6\", \"🎚️\", \"level slider\", \"sliders settings adjust mixer volume\"],\n [\"s12-r2c7\", \"\", \"magnifying glass\", \"search\"], // duplicate of s09-r3c3\n [\"s12-r3c1\", \"\", \"house\", \"home\"], // duplicate of s10-r4c7\n [\"s12-r3c2\", \"\", \"menu\", \"menu hamburger\"], // not a Unicode emoji\n [\"s12-r3c3\", \"⬅️\", \"left arrow\", \"left back previous west\"],\n [\"s12-r3c4\", \"➡️\", \"right arrow\", \"right next forward east\"],\n [\"s12-r3c5\", \"⬆️\", \"up arrow\", \"up north top\"],\n [\"s12-r3c6\", \"⬇️\", \"down arrow\", \"down south bottom\"],\n [\"s12-r3c7\", \"🔃\", \"clockwise vertical arrows\", \"refresh reload repeat sync\"],\n [\"s12-r4c1\", \"\", \"sync arrows\", \"sync\"], // duplicate of s12-r3c7\n [\"s12-r4c2\", \"\", \"upload\", \"upload\"], // not a Unicode emoji\n [\"s12-r4c3\", \"\", \"download\", \"download\"], // not a Unicode emoji\n [\"s12-r4c4\", \"\", \"cloud upload\", \"upload cloud\"], // not a Unicode emoji\n [\"s12-r4c5\", \"\", \"cloud download\", \"download cloud\"], // not a Unicode emoji\n [\"s12-r4c6\", \"🛜\", \"wireless\", \"wifi wireless internet network signal\"],\n [\"s12-r4c7\", \"\", \"bluetooth\", \"bluetooth\"], // not a Unicode emoji\n [\"s12-r5c1\", \"📍\", \"round pushpin\", \"location pin place map here\"],\n [\"s12-r5c2\", \"\", \"map with pin\", \"map\"], // duplicate of s10-r3c6\n [\"s12-r5c3\", \"🔗\", \"link\", \"link chain url hyperlink\"],\n [\"s12-r5c4\", \"⛓️💥\", \"broken chain\", \"broken link unlink freedom\"],\n [\"s12-r5c5\", \"\", \"bookmark\", \"bookmark\"], // duplicate of s11-r3c2\n [\"s12-r5c6\", \"🏷️\", \"label\", \"label tag price\"],\n [\"s12-r5c7\", \"\", \"shield with check\", \"secure verified\"], // not a Unicode emoji\n [\"s12-r6c1\", \"🔓\", \"unlocked\", \"unlock open unlocked\"],\n [\"s12-r6c2\", \"\", \"lock\", \"lock\"], // duplicate of s05-r7c1\n [\"s12-r6c3\", \"\", \"power button\", \"power\"], // not a Unicode emoji\n [\"s12-r6c4\", \"▶️\", \"play button\", \"play start go\"],\n [\"s12-r6c5\", \"⏸️\", \"pause button\", \"pause hold\"],\n [\"s12-r6c6\", \"⏹️\", \"stop button\", \"stop end\"],\n [\"s12-r6c7\", \"🎙️\", \"studio microphone\", \"mic microphone podcast broadcast record\"],\n [\"s12-r7c1\", \"\", \"microphone off\", \"mute\"], // not a Unicode emoji\n [\"s12-r7c2\", \"\", \"video camera\", \"video\"], // duplicate of s09-r2c1\n [\"s12-r7c3\", \"\", \"video off\", \"camera off\"], // not a Unicode emoji\n [\"s12-r7c4\", \"\", \"full battery\", \"battery\"], // duplicate of s09-r2c6\n [\"s12-r7c5\", \"🪫\", \"low battery\", \"battery low empty charge\"],\n [\"s12-r7c6\", \"\", \"electric plug\", \"plug\"], // duplicate of s09-r2c7\n [\"s12-r7c7\", \"\", \"qr code\", \"qr scan\"], // not a Unicode emoji\n // ── sheet 13: household ──\n [\"s13-r1c1\", \"\", \"recycling bin\", \"recycle bin\"], // not a Unicode emoji\n [\"s13-r1c2\", \"\", \"recycling tub\", \"recycle\"], // not a Unicode emoji\n [\"s13-r1c3\", \"🗑️\", \"wastebasket\", \"trash garbage bin delete rubbish\"],\n [\"s13-r1c4\", \"\", \"wire wastebasket\", \"trash\"], // duplicate of s13-r1c3\n [\"s13-r1c5\", \"🧹\", \"broom\", \"broom sweep clean\"],\n [\"s13-r1c6\", \"\", \"mop and bucket\", \"mop clean\"], // not a Unicode emoji\n [\"s13-r1c7\", \"\", \"vacuum cleaner\", \"vacuum\"], // not a Unicode emoji\n [\"s13-r2c1\", \"🧽\", \"sponge\", \"sponge clean wash\"],\n [\"s13-r2c2\", \"\", \"spray bottle\", \"spray cleaner\"], // not a Unicode emoji\n [\"s13-r2c3\", \"🧴\", \"lotion bottle\", \"soap pump lotion sanitizer\"],\n [\"s13-r2c4\", \"🧻\", \"roll of paper\", \"toilet paper tissue\"],\n [\"s13-r2c5\", \"\", \"tissue box\", \"tissues\"], // not a Unicode emoji\n [\"s13-r2c6\", \"🧺\", \"basket\", \"laundry basket\"],\n [\"s13-r2c7\", \"\", \"washing machine\", \"laundry washer\"], // not a Unicode emoji\n [\"s13-r3c1\", \"\", \"clothes iron\", \"iron ironing\"], // not a Unicode emoji\n [\"s13-r3c2\", \"\", \"coat hanger\", \"hanger\"], // not a Unicode emoji\n [\"s13-r3c3\", \"\", \"light bulb\", \"light\"], // duplicate of s09-r2c5\n [\"s13-r3c4\", \"\", \"flashlight\", \"torch\"], // duplicate of s08-r7c6\n [\"s13-r3c5\", \"🕯️\", \"candle\", \"candle light flame\"],\n [\"s13-r3c6\", \"\", \"batteries\", \"battery\"], // duplicate of s09-r2c6\n [\"s13-r3c7\", \"\", \"power strip\", \"power outlet\"], // not a Unicode emoji\n [\"s13-r4c1\", \"\", \"toolbox\", \"tools\"], // duplicate of s09-r3c4\n [\"s13-r4c2\", \"\", \"hammer\", \"hammer\"], // duplicate of s09-r3c6\n [\"s13-r4c3\", \"\", \"wrench\", \"wrench\"], // duplicate of s09-r3c5\n [\"s13-r4c4\", \"\", \"pliers\", \"pliers\"], // not a Unicode emoji\n [\"s13-r4c5\", \"\", \"screwdriver\", \"screwdriver\"], // duplicate of s09-r3c7\n [\"s13-r4c6\", \"\", \"power drill\", \"drill\"], // not a Unicode emoji\n [\"s13-r4c7\", \"🪚\", \"carpentry saw\", \"saw cut wood carpentry\"],\n [\"s13-r5c1\", \"\", \"paint roller\", \"paint\"], // not a Unicode emoji\n [\"s13-r5c2\", \"\", \"paint can\", \"paint\"], // not a Unicode emoji\n [\"s13-r5c3\", \"🪣\", \"bucket\", \"bucket pail\"],\n [\"s13-r5c4\", \"\", \"key\", \"key\"], // duplicate of s05-r7c2\n [\"s13-r5c5\", \"\", \"key card\", \"keycard access\"], // not a Unicode emoji\n [\"s13-r5c6\", \"\", \"doormat\", \"welcome mat\"], // not a Unicode emoji\n [\"s13-r5c7\", \"🚪\", \"door\", \"door enter exit\"],\n [\"s13-r6c1\", \"🪟\", \"window\", \"window glass view\"],\n [\"s13-r6c2\", \"\", \"couch and lamp\", \"couch sofa living room\"], // redrawn as s54-r1c4\n [\"s13-r6c3\", \"🪑\", \"chair\", \"chair seat armchair\"],\n [\"s13-r6c4\", \"🛏️\", \"bed\", \"bed sleep bedroom\"],\n [\"s13-r6c5\", \"\", \"pillow\", \"pillow\"], // not a Unicode emoji\n [\"s13-r6c6\", \"🪞\", \"mirror\", \"mirror reflection\"],\n [\"s13-r6c7\", \"🪴\", \"potted plant\", \"plant houseplant pot grow\"],\n [\"s13-r7c1\", \"\", \"shopping basket\", \"shopping\"], // not a Unicode emoji\n [\"s13-r7c2\", \"🛒\", \"shopping cart\", \"cart shopping trolley\"],\n [\"s13-r7c3\", \"\", \"cardboard box\", \"box\"], // duplicate of s09-r5c2\n [\"s13-r7c4\", \"\", \"first aid kit\", \"first aid\"], // not a Unicode emoji\n [\"s13-r7c5\", \"🧯\", \"fire extinguisher\", \"fire extinguisher safety\"],\n [\"s13-r7c6\", \"\", \"umbrella stand\", \"umbrellas\"], // not a Unicode emoji\n [\"s13-r7c7\", \"\", \"recycling symbol\", \"recycle\"], // duplicate of s05-r5c7\n // ── sheet 14: faces ──\n [\"s14-r1c1\", \"😀\", \"grinning face\", \"cheerful cheery grin happy laugh nice smile smiling\"],\n [\"s14-r1c2\", \"😃\", \"grinning face with big eyes\", \"awesome grin happy mouth open smile smiling teeth\"],\n [\"s14-r1c3\", \"😆\", \"grinning squinting face\", \"closed eyes haha hahaha happy laugh lol mouth\"],\n [\"s14-r1c4\", \"🤣\", \"rolling on the floor laughing\", \"crying face funny haha happy hehe hilarious joy\"],\n [\"s14-r1c5\", \"🙂\", \"slightly smiling face\", \"happy smile\"],\n [\"s14-r1c6\", \"😗\", \"kissing face\", \"143 date dating flirt ily kiss love smooch\"],\n [\"s14-r1c7\", \"😙\", \"kissing face with smiling eyes\", \"143 closed date dating eye flirt ily kiss\"],\n [\"s14-r2c1\", \"😋\", \"face savoring food\", \"delicious eat full hungry savor smile smiling tasty\"],\n [\"s14-r2c2\", \"😛\", \"face with tongue\", \"awesome cool nice party stuck-out sweet\"],\n [\"s14-r2c3\", \"🤭\", \"face with hand over mouth\", \"giggle giggling oops realization secret shock sudden surprise\"],\n [\"s14-r2c4\", \"🤨\", \"face with raised eyebrow\", \"disapproval disbelief distrust emoji hmm mild skeptic skeptical\"],\n [\"s14-r2c5\", \"😶\", \"face without mouth\", \"awkward blank expressionless mouthless mute quiet secret silence\"],\n [\"s14-r2c6\", \"😒\", \"unamused face\", \"bored fine jealous jel jelly pissed smh ugh\"],\n [\"s14-r2c7\", \"🫨\", \"shaking face\", \"crazy daze earthquake omg panic shock surprise vibrate\"],\n [\"s14-r3c1\", \"🙂↔️\", \"head shaking horizontally\", \"no shake\"],\n [\"s14-r3c2\", \"🙂↕️\", \"head shaking vertically\", \"nod yes\"],\n [\"s14-r3c3\", \"\", \"face with bags under eyes\", \"bored exhausted fatigued late sleepy tired weary\"],\n [\"s14-r3c4\", \"🥴\", \"woozy face\", \"dizzy drunk eyes intoxicated mouth tipsy uneven wavy\"],\n [\"s14-r3c5\", \"🥸\", \"disguised face\", \"disguise eyebrow glasses incognito moustache mustache nose person\"],\n [\"s14-r3c6\", \"😕\", \"confused face\", \"befuddled confusing dunno frown hm meh not sad\"],\n [\"s14-r3c7\", \"🫤\", \"face with diagonal mouth\", \"confused confusion disappointed doubt doubtful frustrated frustration meh\"],\n [\"s14-r4c1\", \"🙁\", \"slightly frowning face\", \"frown sad\"],\n [\"s14-r4c2\", \"☹️\", \"frowning face\", \"frown sad\"],\n [\"s14-r4c3\", \"😯\", \"hushed face\", \"epic omg stunned surprised whoa woah\"],\n [\"s14-r4c4\", \"😳\", \"flushed face\", \"amazed awkward crazy dazed dead disbelief embarrassed geez\"],\n [\"s14-r4c5\", \"\", \"distorted face\", \"anxiety bloated panic shocked surprised vulnerable\"],\n [\"s14-r4c6\", \"😦\", \"frowning face with open mouth\", \"caught frown guard scared scary surprise what wow\"],\n [\"s14-r4c7\", \"😧\", \"anguished face\", \"forgot scared scary stressed surprise unhappy what wow\"],\n [\"s14-r5c1\", \"😥\", \"sad but relieved face\", \"anxious call close complicated disappointed not sweat time\"],\n [\"s14-r5c2\", \"😖\", \"confounded face\", \"annoyed confused cringe distraught feels frustrated mad sad\"],\n [\"s14-r5c3\", \"😣\", \"persevering face\", \"concentrate concentration focus headache persevere\"],\n [\"s14-r5c4\", \"😓\", \"downcast face with sweat\", \"close cold feels headache nervous sad scared yikes\"],\n [\"s14-r5c5\", \"🤬\", \"face with symbols on mouth\", \"censor cursing cussing mad pissed swearing\"],\n [\"s14-r5c6\", \"👿\", \"angry face with horns\", \"demon devil evil fairy fairytale fantasy imp mischievous\"],\n [\"s14-r5c7\", \"☠️\", \"skull and crossbones\", \"bone dead death face monster\"],\n [\"s14-r6c1\", \"👹\", \"ogre\", \"creature devil face fairy fairytale fantasy mask monster\"],\n [\"s14-r6c2\", \"👺\", \"goblin\", \"angry creature face fairy fairytale fantasy mask mean\"],\n [\"s14-r6c3\", \"👻\", \"ghost\", \"boo creature excited face fairy fairytale fantasy halloween\"],\n [\"s14-r6c4\", \"👾\", \"alien monster\", \"creature extraterrestrial face fairy fairytale fantasy game gamer\"],\n [\"s14-r6c5\", \"😹\", \"cat with tears of joy\", \"animal face laugh laughing lol tear\"],\n [\"s14-r6c6\", \"😼\", \"cat with wry smile\", \"animal face ironic\"],\n [\"s14-r6c7\", \"🙀\", \"weary cat\", \"animal face oh surprised\"],\n [\"s14-r7c1\", \"🙈\", \"see-no-evil monkey\", \"embarrassed face forbidden forgot gesture hide omg prohibited\"],\n [\"s14-r7c2\", \"🙉\", \"hear-no-evil monkey\", \"animal ears face forbidden gesture listen not prohibited\"],\n [\"s14-r7c3\", \"🙊\", \"speak-no-evil monkey\", \"animal face forbidden gesture not oops prohibited quiet\"],\n [\"s14-r7c4\", \"💗\", \"growing heart\", \"143 emotion excited heartpulse ily kisses muah nervous\"],\n [\"s14-r7c5\", \"❣️\", \"heart exclamation\", \"heavy mark punctuation\"],\n [\"s14-r7c6\", \"💋\", \"kiss mark\", \"dating emotion heart kissing lips romance sexy\"],\n [\"s14-r7c7\", \"💨\", \"dashing away\", \"cloud comic dash fart fast go gone gotta\"],\n // ── sheet 15: plants, fruit, vegetables and food ──\n [\"s15-r1c1\", \"💐\", \"bouquet\", \"anniversary birthday date flower love plant romance\"],\n [\"s15-r1c2\", \"🌸\", \"cherry blossom\", \"flower plant spring springtime\"],\n [\"s15-r1c3\", \"🏵️\", \"rosette\", \"plant\"],\n [\"s15-r1c4\", \"🌹\", \"rose\", \"beauty elegant flower love plant red valentine\"],\n [\"s15-r1c5\", \"🥀\", \"wilted flower\", \"dying\"],\n [\"s15-r1c6\", \"🌼\", \"blossom\", \"buttercup dandelion flower plant\"],\n [\"s15-r1c7\", \"🌷\", \"tulip\", \"blossom flower growth plant\"],\n [\"s15-r2c1\", \"🌱\", \"seedling\", \"plant sapling sprout young\"],\n [\"s15-r2c2\", \"🌴\", \"palm tree\", \"beach plant tropical\"],\n [\"s15-r2c3\", \"🌾\", \"sheaf of rice\", \"ear grain grains plant\"],\n [\"s15-r2c4\", \"🌿\", \"herb\", \"leaf plant\"],\n [\"s15-r2c5\", \"☘️\", \"shamrock\", \"irish plant\"],\n [\"s15-r2c6\", \"🍀\", \"four leaf clover\", \"4 four-leaf irish lucky plant\"],\n [\"s15-r2c7\", \"🍂\", \"fallen leaf\", \"autumn fall falling\"],\n [\"s15-r3c1\", \"🍃\", \"leaf fluttering in wind\", \"blow flutter\"],\n [\"s15-r3c2\", \"🍊\", \"tangerine\", \"c citrus fruit nectarine orange vitamin\"],\n [\"s15-r3c3\", \"🍅\", \"tomato\", \"food fruit vegetable\"],\n [\"s15-r3c4\", \"🍆\", \"eggplant\", \"aubergine vegetable\"],\n [\"s15-r3c5\", \"🥔\", \"potato\", \"food vegetable\"],\n [\"s15-r3c6\", \"🥒\", \"cucumber\", \"food pickle vegetable\"],\n [\"s15-r3c7\", \"🥦\", \"broccoli\", \"cabbage wild\"],\n [\"s15-r4c1\", \"🥜\", \"peanuts\", \"food nut peanut vegetable\"],\n [\"s15-r4c2\", \"🍖\", \"meat on bone\", \"bone food meat barbecue\"],\n [\"s15-r4c3\", \"🍗\", \"poultry leg\", \"bone chicken drumstick hungry turkey\"],\n [\"s15-r4c4\", \"🥩\", \"cut of meat\", \"chop lambchop porkchop red steak\"],\n [\"s15-r4c5\", \"🥪\", \"sandwich\", \"bread\"],\n [\"s15-r4c6\", \"🥚\", \"egg\", \"breakfast food\"],\n [\"s15-r4c7\", \"🥗\", \"green salad\", \"food\"],\n [\"s15-r5c1\", \"🍚\", \"cooked rice\", \"food\"],\n [\"s15-r5c2\", \"🍝\", \"spaghetti\", \"food meatballs pasta restaurant\"],\n [\"s15-r5c3\", \"🍤\", \"fried shrimp\", \"prawn tempura\"],\n [\"s15-r5c4\", \"🍡\", \"dango\", \"dessert japanese skewer stick sweet\"],\n [\"s15-r5c5\", \"🍧\", \"shaved ice\", \"dessert restaurant sweet\"],\n [\"s15-r5c6\", \"🍨\", \"ice cream\", \"dessert food restaurant sweet\"],\n [\"s15-r5c7\", \"🎂\", \"birthday cake\", \"bday celebration dessert happy pastry sweet\"],\n [\"s15-r6c1\", \"🍰\", \"shortcake\", \"cake dessert pastry slice sweet\"],\n [\"s15-r6c2\", \"🥧\", \"pie\", \"apple filling fruit meat pastry pumpkin slice\"],\n [\"s15-r6c3\", \"🍬\", \"candy\", \"cavities dessert halloween restaurant sweet tooth wrapper\"],\n [\"s15-r6c4\", \"🍭\", \"lollipop\", \"candy dessert food restaurant sweet\"],\n [\"s15-r6c5\", \"🍯\", \"honey pot\", \"barrel bear food honeypot jar sweet\"],\n [\"s15-r6c6\", \"🍼\", \"baby bottle\", \"babies birth born drink infant milk newborn\"],\n [\"s15-r6c7\", \"🍾\", \"bottle with popping cork\", \"bar drink\"],\n [\"s15-r7c1\", \"🍸\", \"cocktail glass\", \"alcohol bar booze club drink drinking drinks mad\"],\n [\"s15-r7c2\", \"🍻\", \"clinking beer mugs\", \"alcohol bar booze bottoms cheers clink drinking drinks\"],\n [\"s15-r7c3\", \"🥃\", \"tumbler glass\", \"liquor scotch shot whiskey whisky\"],\n [\"s15-r7c4\", \"🥤\", \"cup with straw\", \"drink juice malt soda soft water\"],\n [\"s15-r7c5\", \"🍽️\", \"fork and knife with plate\", \"cooking dinner eat\"],\n [\"s15-r7c6\", \"🍴\", \"fork and knife\", \"breakfast breaky cooking cutlery delicious dinner eat feed\"],\n [\"s15-r7c7\", \"🔪\", \"kitchen knife\", \"chef cooking hocho tool weapon\"],\n // ── sheet 16: people ──\n [\"s16-r1c1\", \"👶\", \"baby\", \"babies children goo infant newborn pregnant young\"],\n [\"s16-r1c2\", \"👦\", \"boy\", \"bright-eyed child grandson kid son young younger\"],\n [\"s16-r1c3\", \"👧\", \"girl\", \"bright-eyed child daughter granddaughter kid virgo young younger\"],\n [\"s16-r1c4\", \"👩\", \"woman\", \"adult lady\"],\n [\"s16-r1c5\", \"👴\", \"old man\", \"adult bald elderly gramps grandfather grandpa wise\"],\n [\"s16-r1c6\", \"👵\", \"old woman\", \"adult elderly grandma grandmother granny lady wise\"],\n [\"s16-r1c7\", \"👮♂️\", \"man police officer\", \"apprehend arrest citation cop law over pulled undercover\"],\n [\"s16-r2c1\", \"👮♀️\", \"woman police officer\", \"apprehend arrest citation cop law over pulled undercover\"],\n [\"s16-r2c2\", \"🤴\", \"prince\", \"crown fairy fairytale fantasy king royal royalty tale\"],\n [\"s16-r2c3\", \"👸\", \"princess\", \"crown fairy fairytale fantasy queen royal royalty tale\"],\n [\"s16-r2c4\", \"🤰\", \"pregnant woman\", \"baby belly expecting mother pregnancy pregnant woman\"],\n [\"s16-r2c5\", \"\", \"breast-feeding\", \"baby breast-feeding mom mother nursing woman\"], // redrawn as s54-r1c5\n [\"s16-r2c6\", \"🧚♂️\", \"man fairy\", \"fairytale fantasy myth oberon person pixie puck tale\"],\n [\"s16-r2c7\", \"🧚♀️\", \"woman fairy\", \"fairytale fantasy myth person pixie tale titania wings\"],\n [\"s16-r3c1\", \"🧟\", \"zombie\", \"apocalypse dead halloween horror scary undead walking\"],\n [\"s16-r3c2\", \"🧟♂️\", \"man zombie\", \"apocalypse dead halloween horror scary undead walking\"],\n [\"s16-r3c3\", \"🧟♀️\", \"woman zombie\", \"apocalypse dead halloween horror scary undead walking\"],\n [\"s16-r3c4\", \"💆\", \"person getting massage\", \"face headache relax relaxing salon soothe spa tension\"],\n [\"s16-r3c5\", \"💆♂️\", \"man getting massage\", \"face headache relax relaxing salon soothe spa tension\"],\n [\"s16-r3c6\", \"💆♀️\", \"woman getting massage\", \"face headache relax relaxing salon soothe spa tension\"],\n [\"s16-r3c7\", \"🚶♂️\", \"man walking\", \"amble gait hike pace pedestrian stride stroll walk\"],\n [\"s16-r4c1\", \"🚶♀️\", \"woman walking\", \"amble gait hike man pace pedestrian stride stroll\"],\n [\"s16-r4c2\", \"🚶➡️\", \"person walking facing right\", \"amble gait hike man pace pedestrian stride stroll\"],\n [\"s16-r4c3\", \"🚶♀️➡️\", \"woman walking facing right\", \"amble gait hike man pace pedestrian stride stroll\"],\n [\"s16-r4c4\", \"🚶♂️➡️\", \"man walking facing right\", \"amble gait hike pace pedestrian stride stroll walk\"],\n [\"s16-r4c5\", \"🏃♂️\", \"man running\", \"fast hurry marathon move quick race racing run\"],\n [\"s16-r4c6\", \"🏃♀️\", \"woman running\", \"fast hurry marathon move quick race racing run\"],\n [\"s16-r4c7\", \"🏃➡️\", \"person running facing right\", \"fast hurry marathon move quick race racing run\"],\n [\"s16-r5c1\", \"🏃♀️➡️\", \"woman running facing right\", \"fast hurry marathon move quick race racing run\"],\n [\"s16-r5c2\", \"🏃♂️➡️\", \"man running facing right\", \"fast hurry marathon move quick race racing run\"],\n [\"s16-r5c3\", \"💃\", \"woman dancing\", \"dance dancer elegant festive flair flamenco groove let’s\"],\n [\"s16-r5c4\", \"\", \"people with bunny ears\", \"bestie bff counterpart dancer double ear identical pair\"], // redrawn as s43-r1c1\n [\"s16-r5c5\", \"👯♂️\", \"men with bunny ears\", \"bestie bff counterpart dancer double ear identical pair\"],\n [\"s16-r5c6\", \"👯♀️\", \"women with bunny ears\", \"bestie bff counterpart dancer double ear identical pair\"],\n [\"s16-r5c7\", \"🏄♂️\", \"man surfing\", \"beach ocean sport surf surfer swell waves\"],\n [\"s16-r6c1\", \"🏄♀️\", \"woman surfing\", \"beach ocean person sport surf surfer swell waves\"],\n [\"s16-r6c2\", \"🏋️♂️\", \"man lifting weights\", \"barbell bodybuilder deadlift lifter powerlifting weight weightlifter workout\"],\n [\"s16-r6c3\", \"\", \"woman lifting weights\", \"barbell bodybuilder deadlift lifter powerlifting weight weightlifter workout\"], // redrawn as s43-r1c2\n [\"s16-r6c4\", \"🚴\", \"person biking\", \"bicycle bicyclist bike cycle cyclist riding sport\"],\n [\"s16-r6c5\", \"🚴♂️\", \"man biking\", \"bicycle bicyclist bike cycle cyclist riding sport\"],\n [\"s16-r6c6\", \"🚴♀️\", \"woman biking\", \"bicycle bicyclist bike cycle cyclist riding sport\"],\n [\"s16-r6c7\", \"\", \"man cartwheeling\", \"active cartwheel excited flip gymnastics happy somersault\"], // redrawn as s54-r1c7\n [\"s16-r7c1\", \"\", \"woman cartwheeling\", \"active cartwheel excited flip gymnastics happy somersault\"], // redrawn as s54-r1c6\n [\"s16-r7c2\", \"🧘♂️\", \"man in lotus position\", \"cross legged legs meditation peace relax serenity yoga\"],\n [\"s16-r7c3\", \"🧘♀️\", \"woman in lotus position\", \"cross legged legs meditation peace relax serenity yoga\"],\n [\"s16-r7c4\", \"👫\", \"woman and man holding hands\", \"bae bestie bff couple dating flirt friends hand\"],\n [\"s16-r7c5\", \"💏\", \"kiss\", \"anniversary babe bae couple date dating heart love\"],\n [\"s16-r7c6\", \"🗣️\", \"speaking head\", \"face silhouette speak\"],\n [\"s16-r7c7\", \"👤\", \"bust in silhouette\", \"mysterious shadow\"],\n // ── sheet 17: objects ──\n [\"s17-r1c1\", \"👓\", \"glasses\", \"clothing eye eyeglasses eyewear\"],\n [\"s17-r1c2\", \"🕶️\", \"sunglasses\", \"dark eye eyewear glasses\"],\n [\"s17-r1c3\", \"👔\", \"necktie\", \"clothing employed serious shirt tie\"],\n [\"s17-r1c4\", \"👕\", \"t-shirt\", \"blue casual clothes clothing collar dressed shopping t-shirt\"],\n [\"s17-r1c5\", \"👖\", \"jeans\", \"blue casual clothes clothing denim dressed pants shopping\"],\n [\"s17-r1c6\", \"👗\", \"dress\", \"clothes clothing dressed fancy shopping\"],\n [\"s17-r1c7\", \"👙\", \"bikini\", \"bathing beach clothing pool suit swim\"],\n [\"s17-r2c1\", \"👠\", \"high-heeled shoe\", \"clothes clothing dress fashion heel heels high-heeled shoes\"],\n [\"s17-r2c2\", \"👒\", \"woman’s hat\", \"clothes clothing garden hats party woman’s\"],\n [\"s17-r2c3\", \"🎩\", \"top hat\", \"clothes clothing fancy formal magic tophat\"],\n [\"s17-r2c4\", \"🧢\", \"billed cap\", \"baseball bent dad hat\"],\n [\"s17-r2c5\", \"📿\", \"prayer beads\", \"clothing necklace religion\"],\n [\"s17-r2c6\", \"💄\", \"lipstick\", \"cosmetics date makeup\"],\n [\"s17-r2c7\", \"🔊\", \"speaker high volume\", \"loud music sound\"],\n [\"s17-r3c1\", \"📣\", \"megaphone\", \"cheering sound\"],\n [\"s17-r3c2\", \"🎼\", \"musical score\", \"music note\"],\n [\"s17-r3c3\", \"🎶\", \"musical notes\", \"music note sound\"],\n [\"s17-r3c4\", \"🎺\", \"trumpet\", \"instrument music\"],\n [\"s17-r3c5\", \"🎻\", \"violin\", \"instrument music\"],\n [\"s17-r3c6\", \"📲\", \"mobile phone with arrow\", \"build call cell communication receive telephone\"],\n [\"s17-r3c7\", \"☎️\", \"telephone\", \"phone\"],\n [\"s17-r4c1\", \"📞\", \"telephone receiver\", \"communication phone voip\"],\n [\"s17-r4c2\", \"🎥\", \"movie camera\", \"bollywood cinema film hollywood record\"],\n [\"s17-r4c3\", \"\", \"magnifying glass tilted right\", \"contact lab right-pointing science search tool\"], // redrawn as s43-r2c2\n [\"s17-r4c4\", \"📰\", \"newspaper\", \"communication news paper\"],\n [\"s17-r4c5\", \"💵\", \"dollar banknote\", \"bank bill currency money note\"],\n [\"s17-r4c6\", \"💸\", \"money with wings\", \"bank banknote bill billion cash dollar fly million\"],\n [\"s17-r4c7\", \"📩\", \"envelope with arrow\", \"communication down e-mail email letter mail outgoing send\"],\n [\"s17-r5c1\", \"📮\", \"postbox\", \"mail mailbox\"],\n [\"s17-r5c2\", \"📝\", \"memo\", \"communication media notes pencil\"],\n [\"s17-r5c3\", \"📆\", \"tear-off calendar\", \"tear-off\"],\n [\"s17-r5c4\", \"📈\", \"chart increasing\", \"data graph growth right trend up upward\"],\n [\"s17-r5c5\", \"📉\", \"chart decreasing\", \"data down downward graph negative trend\"],\n [\"s17-r5c6\", \"🔐\", \"locked with key\", \"bike closed lock secure\"],\n [\"s17-r5c7\", \"🗝️\", \"old key\", \"clue lock\"],\n [\"s17-r6c1\", \"⚔️\", \"crossed swords\", \"weapon\"],\n [\"s17-r6c2\", \"💣\", \"bomb\", \"boom comic dangerous explosion hot\"],\n [\"s17-r6c3\", \"🏹\", \"bow and arrow\", \"archer archery sagittarius tool weapon zodiac\"],\n [\"s17-r6c4\", \"⚖️\", \"balance scale\", \"justice libra scales tool weight zodiac\"],\n [\"s17-r6c5\", \"🧬\", \"dna\", \"biologist evolution gene genetics life\"],\n [\"s17-r6c6\", \"💊\", \"pill\", \"doctor drugs medicated medicine pills sick vitamin\"],\n [\"s17-r6c7\", \"🚽\", \"toilet\", \"bathroom\"],\n [\"s17-r7c1\", \"🚿\", \"shower\", \"water\"],\n [\"s17-r7c2\", \"🛁\", \"bathtub\", \"bath\"],\n [\"s17-r7c3\", \"🧼\", \"soap\", \"bar bathing clean cleaning lather soapdish\"],\n [\"s17-r7c4\", \"🚬\", \"cigarette\", \"smoking\"],\n [\"s17-r7c5\", \"⚰️\", \"coffin\", \"dead death vampire\"],\n [\"s17-r7c6\", \"🧿\", \"nazar amulet\", \"bead blue charm evil-eye talisman\"],\n [\"s17-r7c7\", \"🗿\", \"moai\", \"face moyai statue stoneface travel\"],\n // ── sheet 18: animals ──\n [\"s18-r1c1\", \"🐒\", \"monkey\", \"animal banana\"],\n [\"s18-r1c2\", \"🦍\", \"gorilla\", \"animal\"],\n [\"s18-r1c3\", \"🐕\", \"dog\", \"animal animals dogs pet\"],\n [\"s18-r1c4\", \"🐩\", \"poodle\", \"animal dog fluffy\"],\n [\"s18-r1c5\", \"🦝\", \"raccoon\", \"animal curious sly\"],\n [\"s18-r1c6\", \"🐈\", \"cat\", \"animal animals cats kitten pet\"],\n [\"s18-r1c7\", \"🐅\", \"tiger\", \"animal big cat predator zoo\"],\n [\"s18-r2c1\", \"🐆\", \"leopard\", \"animal big cat predator zoo\"],\n [\"s18-r2c2\", \"🐴\", \"horse face\", \"animal dressage equine farm horses\"],\n [\"s18-r2c3\", \"🐎\", \"horse\", \"animal equestrian farm racehorse racing\"],\n [\"s18-r2c4\", \"🦌\", \"deer\", \"animal\"],\n [\"s18-r2c5\", \"🐂\", \"ox\", \"animal animals bull farm taurus zodiac\"],\n [\"s18-r2c6\", \"🐃\", \"water buffalo\", \"animal zoo\"],\n [\"s18-r2c7\", \"🐄\", \"cow\", \"animal animals farm milk moo\"],\n [\"s18-r3c1\", \"🐖\", \"pig\", \"animal bacon farm pork sow\"],\n [\"s18-r3c2\", \"🐽\", \"pig nose\", \"animal face farm smell snout\"],\n [\"s18-r3c3\", \"🐏\", \"ram\", \"animal aries horns male sheep zodiac zoo\"],\n [\"s18-r3c4\", \"🐑\", \"ewe\", \"animal baa farm female fluffy lamb sheep wool\"],\n [\"s18-r3c5\", \"🐐\", \"goat\", \"animal capricorn farm milk zodiac\"],\n [\"s18-r3c6\", \"🐪\", \"camel\", \"animal desert dromedary hump one\"],\n [\"s18-r3c7\", \"🦙\", \"llama\", \"alpaca animal guanaco vicuña wool\"],\n [\"s18-r4c1\", \"🐘\", \"elephant\", \"animal\"],\n [\"s18-r4c2\", \"🐁\", \"mouse\", \"animal animals\"],\n [\"s18-r4c3\", \"🐀\", \"rat\", \"animal\"],\n [\"s18-r4c4\", \"🐇\", \"rabbit\", \"animal bunny pet\"],\n [\"s18-r4c5\", \"🐿️\", \"chipmunk\", \"animal squirrel\"],\n [\"s18-r4c6\", \"🦘\", \"kangaroo\", \"animal joey jump marsupial\"],\n [\"s18-r4c7\", \"🦃\", \"turkey\", \"bird gobble thanksgiving\"],\n [\"s18-r5c1\", \"🐓\", \"rooster\", \"animal bird ornithology\"],\n [\"s18-r5c2\", \"🐤\", \"baby chick\", \"animal bird ornithology\"],\n [\"s18-r5c3\", \"🕊️\", \"dove\", \"bird fly ornithology peace\"],\n [\"s18-r5c4\", \"🦆\", \"duck\", \"animal bird ornithology\"],\n [\"s18-r5c5\", \"🦚\", \"peacock\", \"animal bird colorful ornithology ostentatious peahen pretty proud\"],\n [\"s18-r5c6\", \"🦜\", \"parrot\", \"animal bird ornithology pirate talk\"],\n [\"s18-r5c7\", \"🐊\", \"crocodile\", \"animal zoo\"],\n [\"s18-r6c1\", \"🦎\", \"lizard\", \"animal reptile\"],\n [\"s18-r6c2\", \"🐉\", \"dragon\", \"animal fairy fairytale knights tale\"],\n [\"s18-r6c3\", \"🦕\", \"sauropod\", \"brachiosaurus brontosaurus dinosaur diplodocus\"],\n [\"s18-r6c4\", \"🐟\", \"fish\", \"animal dinner fishes fishing pisces zodiac\"],\n [\"s18-r6c5\", \"🦈\", \"shark\", \"animal fish\"],\n [\"s18-r6c6\", \"🐚\", \"spiral shell\", \"animal beach conch sea\"],\n [\"s18-r6c7\", \"🦞\", \"lobster\", \"animal bisque claws seafood\"],\n [\"s18-r7c1\", \"🦐\", \"shrimp\", \"food shellfish small\"],\n [\"s18-r7c2\", \"🦑\", \"squid\", \"animal food mollusk\"],\n [\"s18-r7c3\", \"🐛\", \"bug\", \"animal garden insect\"],\n [\"s18-r7c4\", \"🦗\", \"cricket\", \"animal bug grasshopper insect orthoptera\"],\n [\"s18-r7c5\", \"🕷️\", \"spider\", \"animal insect\"],\n [\"s18-r7c6\", \"🦟\", \"mosquito\", \"bite disease fever insect malaria pest virus\"],\n [\"s18-r7c7\", \"🦠\", \"microbe\", \"amoeba bacteria science virus\"],\n [\"s19-r1c1\", \"🚮\", \"litter in bin sign\", \"litterbin\"],\n [\"s19-r1c2\", \"⛔\", \"no entry\", \"do fail forbidden not pass prohibited traffic\"],\n [\"s19-r1c3\", \"🚫\", \"prohibited\", \"entry forbidden no not smoke\"],\n [\"s19-r1c4\", \"🚭\", \"no smoking\", \"forbidden not prohibited smoke\"],\n [\"s19-r1c5\", \"🔞\", \"no one under eighteen\", \"18 age forbidden not prohibited restriction underage\"],\n [\"s19-r1c6\", \"↗️\", \"up-right arrow\", \"direction intercardinal northeast up-right\"],\n [\"s19-r1c7\", \"⤵️\", \"right arrow curving down\", \"arrow curve down turn\"],\n [\"s19-r2c1\", \"🔙\", \"BACK arrow\", \"arrow back return left\"],\n [\"s19-r2c2\", \"🔛\", \"ON! arrow\", \"mark\"],\n [\"s19-r2c3\", \"🔜\", \"SOON arrow\", \"brb omw\"],\n [\"s19-r2c4\", \"🔝\", \"TOP arrow\", \"homie up\"],\n [\"s19-r2c5\", \"🛐\", \"place of worship\", \"pray religion\"],\n [\"s19-r2c6\", \"🕉️\", \"om\", \"hindu religion\"],\n [\"s19-r2c7\", \"✝️\", \"latin cross\", \"christ christian religion\"],\n [\"s19-r3c1\", \"♈\", \"Aries\", \"horoscope ram zodiac\"],\n [\"s19-r3c2\", \"⏩\", \"fast-forward button\", \"arrow double fast-forward\"],\n [\"s19-r3c3\", \"🔽\", \"downwards button\", \"arrow down red\"],\n [\"s19-r3c4\", \"🔅\", \"dim button\", \"brightness low\"],\n [\"s19-r3c5\", \"🔆\", \"bright button\", \"brightness light\"],\n [\"s19-r3c6\", \"📴\", \"mobile phone off\", \"cell telephone\"],\n [\"s19-r3c7\", \"✖️\", \"multiply\", \"cancel multiplication sign x\"],\n [\"s19-r4c1\", \"➕\", \"plus\", \"add math plus sign\"],\n [\"s19-r4c2\", \"♾️\", \"infinity\", \"forever unbounded universal\"],\n [\"s19-r4c3\", \"⁉️\", \"exclamation question mark\", \"interrobang punctuation\"],\n [\"s19-r4c4\", \"❕\", \"white exclamation mark\", \"outlined punctuation\"],\n [\"s19-r4c5\", \"\", \"wavy dash\", \"punctuation\"], // redrawn as s43-r2c3\n [\"s19-r4c6\", \"💲\", \"heavy dollar sign\", \"billion cash charge currency million money pay\"],\n [\"s19-r4c7\", \"⚜️\", \"fleur-de-lis\", \"fleur-de-lis knights\"],\n [\"s19-r5c1\", \"🔱\", \"trident emblem\", \"anchor poseidon ship tool\"],\n [\"s19-r5c2\", \"📛\", \"name badge\", \"badge name tag label\"],\n [\"s19-r5c3\", \"🔰\", \"Japanese symbol for beginner\", \"chevron green leaf tool yellow\"],\n [\"s19-r5c4\", \"⭕\", \"hollow red circle\", \"heavy large o\"],\n [\"s19-r5c5\", \"☑️\", \"check box with check\", \"ballot checked done off tick\"],\n [\"s19-r5c6\", \"✔️\", \"check mark\", \"checked checkmark done heavy tick\"],\n [\"s19-r5c7\", \"❎\", \"cross mark button\", \"multiplication multiply square x\"],\n [\"s19-r6c1\", \"🔴\", \"red circle\", \"geometric\"],\n [\"s19-r6c2\", \"🔵\", \"blue circle\", \"geometric\"],\n [\"s19-r6c3\", \"⚫\", \"black circle\", \"geometric\"],\n [\"s19-r6c4\", \"⚪\", \"white circle\", \"geometric\"],\n [\"s19-r6c5\", \"⬛\", \"black large square\", \"geometric\"],\n [\"s19-r6c6\", \"⬜\", \"white large square\", \"geometric\"],\n [\"s19-r6c7\", \"▪️\", \"black small square\", \"geometric\"],\n [\"s19-r7c1\", \"🔶\", \"large orange diamond\", \"geometric\"],\n [\"s19-r7c2\", \"🔷\", \"large blue diamond\", \"geometric\"],\n [\"s19-r7c3\", \"🔸\", \"small orange diamond\", \"geometric\"],\n [\"s19-r7c4\", \"🔹\", \"small blue diamond\", \"geometric\"],\n [\"s19-r7c5\", \"🔺\", \"red triangle pointed up\", \"geometric\"],\n [\"s19-r7c6\", \"🔻\", \"red triangle pointed down\", \"geometric\"],\n [\"s19-r7c7\", \"💠\", \"diamond with a dot\", \"comic geometric\"],\n // ── sheet 20: people ──\n [\"s20-r1c1\", \"👱\", \"person: blond hair\", \"blond-haired human\"],\n [\"s20-r1c2\", \"👨\", \"man\", \"adult bro\"],\n [\"s20-r1c3\", \"🧔\", \"person: beard\", \"bearded whiskers\"],\n [\"s20-r1c4\", \"🧔♂️\", \"man: beard\", \"bearded whiskers\"],\n [\"s20-r1c5\", \"🧔♀️\", \"woman: beard\", \"bearded whiskers\"],\n [\"s20-r1c6\", \"👱♀️\", \"woman: blond hair\", \"blond-haired blonde\"],\n [\"s20-r1c7\", \"👱♂️\", \"man: blond hair\", \"blond-haired\"],\n [\"s20-r2c1\", \"🧓\", \"older person\", \"adult elderly grandparent old wise\"],\n [\"s20-r2c2\", \"🕵️♂️\", \"man detective\", \"sleuth spy\"],\n [\"s20-r2c3\", \"🕵️♀️\", \"woman detective\", \"sleuth spy\"],\n [\"s20-r2c4\", \"👷♂️\", \"man construction worker\", \"build fix hardhat hat rebuild remodel repair work\"],\n [\"s20-r2c5\", \"👷♀️\", \"woman construction worker\", \"build fix hardhat hat man rebuild remodel repair\"],\n [\"s20-r2c6\", \"🤵\", \"person in tuxedo\", \"formal wedding\"],\n [\"s20-r2c7\", \"🤵♂️\", \"man in tuxedo\", \"formal groom wedding\"],\n [\"s20-r3c1\", \"🤵♀️\", \"woman in tuxedo\", \"formal wedding\"],\n [\"s20-r3c2\", \"\", \"person with veil\", \"wedding\"], // redrawn as s43-r1c3\n [\"s20-r3c3\", \"👰♂️\", \"man with veil\", \"wedding\"],\n [\"s20-r3c4\", \"👰♀️\", \"woman with veil\", \"bride wedding\"],\n [\"s20-r3c5\", \"🦸♂️\", \"man superhero\", \"good hero superpower\"],\n [\"s20-r3c6\", \"🦸♀️\", \"woman superhero\", \"good hero heroine superpower\"],\n [\"s20-r3c7\", \"🦹\", \"supervillain\", \"bad criminal evil superpower villain\"],\n [\"s20-r4c1\", \"🦹♂️\", \"man supervillain\", \"bad criminal evil superpower villain\"],\n [\"s20-r4c2\", \"🦹♀️\", \"woman supervillain\", \"bad criminal evil superpower villain\"],\n [\"s20-r4c3\", \"🧙♂️\", \"man mage\", \"fantasy magic play sorcerer sorceress sorcery spell summon\"],\n [\"s20-r4c4\", \"🧙♀️\", \"woman mage\", \"fantasy magic play sorcerer sorceress sorcery spell summon\"],\n [\"s20-r4c5\", \"🧛♂️\", \"man vampire\", \"blood fangs halloween scary supernatural teeth undead\"],\n [\"s20-r4c6\", \"🧛♀️\", \"woman vampire\", \"blood fangs halloween scary supernatural teeth undead\"],\n [\"s20-r4c7\", \"🧜♂️\", \"merman\", \"creature fairytale folklore neptune ocean poseidon sea siren\"],\n [\"s20-r5c1\", \"🧜♀️\", \"mermaid\", \"creature fairytale folklore merwoman ocean sea siren trident\"],\n [\"s20-r5c2\", \"💇\", \"person getting haircut\", \"barber beauty chop cosmetology cut groom hair parlor\"],\n [\"s20-r5c3\", \"💇♂️\", \"man getting haircut\", \"barber beauty chop cosmetology cut groom hair parlor\"],\n [\"s20-r5c4\", \"💇♀️\", \"woman getting haircut\", \"barber beauty chop cosmetology cut groom hair parlor\"],\n [\"s20-r5c5\", \"🕴️\", \"person in suit levitating\", \"business\"],\n [\"s20-r5c6\", \"🤺\", \"person fencing\", \"fencer sword\"],\n [\"s20-r5c7\", \"🏇\", \"horse racing\", \"jockey racehorse riding sport\"],\n [\"s20-r6c1\", \"🏌️\", \"person golfing\", \"ball birdie caddy driving golf green pga putt\"],\n [\"s20-r6c2\", \"🏌️♂️\", \"man golfing\", \"ball birdie caddy driving golf green pga putt\"],\n [\"s20-r6c3\", \"🏌️♀️\", \"woman golfing\", \"ball birdie caddy driving golf green pga putt\"],\n [\"s20-r6c4\", \"🏊\", \"person swimming\", \"freestyle sport swim swimmer triathlon\"],\n [\"s20-r6c5\", \"\", \"man swimming\", \"freestyle sport swim swimmer triathlon\"], // redrawn as s43-r1c4\n [\"s20-r6c6\", \"🏊♀️\", \"woman swimming\", \"freestyle man sport swim swimmer triathlon\"],\n [\"s20-r6c7\", \"🛀\", \"person taking bath\", \"bathtub tub\"],\n [\"s20-r7c1\", \"👭\", \"women holding hands\", \"bae bestie bff couple dating flirt friends girls\"],\n [\"s20-r7c2\", \"👬\", \"men holding hands\", \"bae bestie bff boys brothers couple dating flirt\"],\n [\"s20-r7c3\", \"👩❤️💋👨\", \"kiss: woman, man\", \"anniversary babe bae couple date dating heart love\"],\n [\"s20-r7c4\", \"👩❤️💋👩\", \"kiss: woman, woman\", \"anniversary babe bae couple date dating heart love\"],\n [\"s20-r7c5\", \"💑\", \"couple with heart\", \"anniversary babe bae dating kiss love person relationship\"],\n [\"s20-r7c6\", \"👩❤️👨\", \"couple with heart: woman, man\", \"anniversary babe bae dating kiss love person relationship\"],\n [\"s20-r7c7\", \"👥\", \"busts in silhouette\", \"bff bust everyone friend friends people\"],\n // ── sheet 21: hearts, feelings, hands and gestures ──\n [\"s21-r1c1\", \"💌\", \"love letter\", \"heart mail romance valentine\"],\n [\"s21-r1c2\", \"💟\", \"heart decoration\", \"143 emotion hearth purple white\"],\n [\"s21-r1c3\", \"🩵\", \"light blue heart\", \"143 cute cyan emotion ily like love sky\"],\n [\"s21-r1c4\", \"🩶\", \"grey heart\", \"143 emotion gray ily love silver slate special\"],\n [\"s21-r1c5\", \"\", \"fight cloud\", \"argument brawl debate disagreement ruckus wrestle\"],\n [\"s21-r1c6\", \"🕳️\", \"hole\", \"pit dig empty dark gap\"],\n [\"s21-r1c7\", \"👁️🗨️\", \"eye in speech bubble\", \"balloon witness\"],\n [\"s21-r2c1\", \"🗨️\", \"left speech bubble\", \"balloon dialog\"],\n [\"s21-r2c2\", \"🗯️\", \"right anger bubble\", \"angry balloon mad\"],\n [\"s21-r2c3\", \"🤚\", \"raised back of hand\", \"backhand\"],\n [\"s21-r2c4\", \"🖐️\", \"hand with fingers splayed\", \"finger raised stop\"],\n [\"s21-r2c5\", \"🫲\", \"leftwards hand\", \"handshake hold left leftward reach shake\"],\n [\"s21-r2c6\", \"🫳\", \"palm down hand\", \"dismiss drop dropped pick shoo up\"],\n [\"s21-r2c7\", \"🫴\", \"palm up hand\", \"beckon catch come hold know lift me offer\"],\n [\"s21-r3c1\", \"🫷\", \"leftwards pushing hand\", \"block five halt high hold leftward pause push\"],\n [\"s21-r3c2\", \"🫸\", \"rightwards pushing hand\", \"block five halt high hold pause push refuse\"],\n [\"s21-r3c3\", \"🤘\", \"sign of the horns\", \"finger hand rock-on\"],\n [\"s21-r3c4\", \"🖕\", \"middle finger\", \"hand\"],\n [\"s21-r3c5\", \"🫵\", \"index pointing at the viewer\", \"finger hand poke you\"],\n [\"s21-r3c6\", \"🦾\", \"mechanical arm\", \"accessibility prosthetic\"],\n [\"s21-r3c7\", \"🦿\", \"mechanical leg\", \"accessibility prosthetic\"],\n [\"s21-r4c1\", \"👃\", \"nose\", \"body noses nosey odor smell smells\"],\n [\"s21-r4c2\", \"🧠\", \"brain\", \"intelligent smart\"],\n [\"s21-r4c3\", \"🫀\", \"anatomical heart\", \"beat cardiology heartbeat organ pulse real red\"],\n [\"s21-r4c4\", \"🫁\", \"lungs\", \"breath breathe exhalation inhalation lung organ respiration\"],\n [\"s21-r4c5\", \"🫦\", \"biting lip\", \"anxious bite fear flirt flirting kiss lipstick nervous\"],\n [\"s21-r4c6\", \"🙍\", \"person frowning\", \"annoyed disappointed disgruntled disturbed frown frustrated gesture irritated\"],\n [\"s21-r4c7\", \"🙍♂️\", \"man frowning\", \"annoyed disappointed disgruntled disturbed frown frustrated gesture irritated\"],\n [\"s21-r5c1\", \"🙍♀️\", \"woman frowning\", \"annoyed disappointed disgruntled disturbed frown frustrated gesture irritated\"],\n [\"s21-r5c2\", \"🙎\", \"person pouting\", \"disappointed downtrodden frown grimace scowl sulk upset whine\"],\n [\"s21-r5c3\", \"🙎♂️\", \"man pouting\", \"disappointed downtrodden frown grimace scowl sulk upset whine\"],\n [\"s21-r5c4\", \"🙎♀️\", \"woman pouting\", \"disappointed downtrodden frown grimace scowl sulk upset whine\"],\n [\"s21-r5c5\", \"🙅♂️\", \"man gesturing NO\", \"forbidden gesture hand not prohibit\"],\n [\"s21-r5c6\", \"🙅♀️\", \"woman gesturing NO\", \"forbidden gesture hand not prohibit\"],\n [\"s21-r5c7\", \"🙆♂️\", \"man gesturing OK\", \"exercise gesture hand omg\"],\n [\"s21-r6c1\", \"🙆♀️\", \"woman gesturing OK\", \"exercise gesture hand omg\"],\n [\"s21-r6c2\", \"💁♂️\", \"man tipping hand\", \"fetch flick flip gossip sarcasm sarcastic sassy seriously\"],\n [\"s21-r6c3\", \"💁♀️\", \"woman tipping hand\", \"fetch flick flip gossip sarcasm sarcastic sassy seriously\"],\n [\"s21-r6c4\", \"\", \"man raising hand\", \"gesture here know me pick question raise\"], // redrawn as s43-r1c5\n [\"s21-r6c5\", \"🙋♀️\", \"woman raising hand\", \"gesture here know me pick question raise\"],\n [\"s21-r6c6\", \"🧏\", \"deaf person\", \"accessibility ear gesture hear\"],\n [\"s21-r6c7\", \"🧏♂️\", \"deaf man\", \"accessibility ear gesture hear\"],\n [\"s21-r7c1\", \"🧏♀️\", \"deaf woman\", \"accessibility ear gesture hear\"],\n [\"s21-r7c2\", \"🙇♂️\", \"man bowing\", \"apology ask beg bow favor forgive gesture meditate\"],\n [\"s21-r7c3\", \"🙇♀️\", \"woman bowing\", \"apology ask beg bow favor forgive gesture meditate\"],\n [\"s21-r7c4\", \"🤦♂️\", \"man facepalming\", \"again bewilder disbelief exasperation facepalm no not oh\"],\n [\"s21-r7c5\", \"🤦♀️\", \"woman facepalming\", \"again bewilder disbelief exasperation facepalm no not oh\"],\n [\"s21-r7c6\", \"🤷♂️\", \"man shrugging\", \"doubt dunno guess idk ignorance indifference knows maybe\"],\n [\"s21-r7c7\", \"🤷♀️\", \"woman shrugging\", \"doubt dunno guess idk ignorance indifference knows maybe\"],\n // ── sheet 22: places and transport ──\n [\"s22-r1c1\", \"🌎\", \"globe showing Americas\", \"earth world\"],\n [\"s22-r1c2\", \"🌏\", \"globe showing Asia-Australia\", \"asia-australia earth world\"],\n [\"s22-r1c3\", \"🌐\", \"globe with meridians\", \"earth internet web world worldwide\"],\n [\"s22-r1c4\", \"⛰️\", \"mountain\", \"mountain peak hill rock climb\"],\n [\"s22-r1c5\", \"🗻\", \"mount fuji\", \"mountain nature\"],\n [\"s22-r1c6\", \"🏞️\", \"national park\", \"national park landscape nature outdoors valley\"],\n [\"s22-r1c7\", \"🏟️\", \"stadium\", \"stadium arena sport game venue\"],\n [\"s22-r2c1\", \"🧱\", \"brick\", \"bricks clay mortar wall\"],\n [\"s22-r2c2\", \"🏘️\", \"houses\", \"house\"],\n [\"s22-r2c3\", \"🏡\", \"house with garden\", \"building country heart home ranch settle simple suburban\"],\n [\"s22-r2c4\", \"🏢\", \"office building\", \"city cubical job\"],\n [\"s22-r2c5\", \"🏥\", \"hospital\", \"building doctor medicine\"],\n [\"s22-r2c6\", \"🏦\", \"bank\", \"building\"],\n [\"s22-r2c7\", \"🏨\", \"hotel\", \"building\"],\n [\"s22-r3c1\", \"🏩\", \"love hotel\", \"building\"],\n [\"s22-r3c2\", \"🏯\", \"Japanese castle\", \"building\"],\n [\"s22-r3c3\", \"💒\", \"wedding\", \"chapel hitched nuptials romance\"],\n [\"s22-r3c4\", \"🗼\", \"Tokyo tower\", \"tokyo tower japan landmark city\"],\n [\"s22-r3c5\", \"🗽\", \"Statue of Liberty\", \"new ny nyc york\"],\n [\"s22-r3c6\", \"⛪\", \"church\", \"bless chapel christian cross religion\"],\n [\"s22-r3c7\", \"🕌\", \"mosque\", \"islam masjid muslim religion\"],\n [\"s22-r4c1\", \"🕋\", \"kaaba\", \"hajj islam muslim religion umrah\"],\n [\"s22-r4c2\", \"⛲\", \"fountain\", \"fountain water park plaza\"],\n [\"s22-r4c3\", \"\", \"tent\", \"camping\"], // redrawn as s43-r2c4\n [\"s22-r4c4\", \"🌄\", \"sunrise over mountains\", \"morning sun\"],\n [\"s22-r4c5\", \"🌆\", \"cityscape at dusk\", \"building city evening landscape sun sunset\"],\n [\"s22-r4c6\", \"♨️\", \"hot springs\", \"hotsprings steaming\"],\n [\"s22-r4c7\", \"🎠\", \"carousel horse\", \"entertainment\"],\n [\"s22-r5c1\", \"🎢\", \"roller coaster\", \"amusement park theme\"],\n [\"s22-r5c2\", \"💈\", \"barber pole\", \"cut fresh haircut shave\"],\n [\"s22-r5c3\", \"🎪\", \"circus tent\", \"circus tent big top show carnival\"],\n [\"s22-r5c4\", \"🚃\", \"railway car\", \"electric train tram travel trolleybus\"],\n [\"s22-r5c5\", \"🚐\", \"minibus\", \"bus drive van vehicle\"],\n [\"s22-r5c6\", \"🚑\", \"ambulance\", \"emergency vehicle\"],\n [\"s22-r5c7\", \"🚒\", \"fire engine\", \"truck\"],\n [\"s22-r6c1\", \"\", \"oncoming police car\", \"police car cop oncoming siren\"], // redrawn as s45-r5c4\n [\"s22-r6c2\", \"\", \"oncoming automobile\", \"car cars drove vehicle\"], // redrawn as s45-r5c5\n [\"s22-r6c3\", \"🚙\", \"sport utility vehicle\", \"car drive recreational sportutility\"],\n [\"s22-r6c4\", \"🚛\", \"articulated lorry\", \"car drive move semi truck vehicle\"],\n [\"s22-r6c5\", \"🏎️\", \"racing car\", \"zoom\"],\n [\"s22-r6c6\", \"🛵\", \"motor scooter\", \"motor scooter moped vespa ride\"],\n [\"s22-r6c7\", \"🛴\", \"kick scooter\", \"kick scooter ride push wheels\"],\n [\"s22-r7c1\", \"\", \"motorway\", \"highway road\"], // redrawn as s45-r5c6\n [\"s22-r7c2\", \"🚨\", \"police car light\", \"alarm alert beacon emergency revolving siren\"],\n [\"s22-r7c3\", \"🚧\", \"construction\", \"barrier\"],\n [\"s22-r7c4\", \"\", \"airplane departure\", \"aeroplane check-in departures plane\"], // redrawn as s45-r5c7\n [\"s22-r7c5\", \"💺\", \"seat\", \"chair\"],\n [\"s22-r7c6\", \"🛸\", \"flying saucer\", \"aliens extra terrestrial ufo\"],\n [\"s22-r7c7\", \"🧳\", \"luggage\", \"bag packing roller suitcase travel\"],\n // ── sheet 23: activities ──\n [\"s23-r1c1\", \"🎃\", \"jack-o-lantern\", \"celebration halloween jack-o-lantern pumpkin\"],\n [\"s23-r1c2\", \"🎄\", \"Christmas tree\", \"celebration\"],\n [\"s23-r1c3\", \"\", \"fireworks\", \"boom celebration entertainment yolo\"], // redrawn as s45-r5c1\n [\"s23-r1c4\", \"\", \"sparkler\", \"boom celebration fireworks sparkle\"], // redrawn as s45-r5c2\n [\"s23-r1c5\", \"🧨\", \"firecracker\", \"dynamite explosive fire fireworks light pop popping spark\"],\n [\"s23-r1c6\", \"🎋\", \"tanabata tree\", \"banner celebration japanese\"],\n [\"s23-r1c7\", \"🎍\", \"pine decoration\", \"bamboo celebration japanese plant\"],\n [\"s23-r2c1\", \"🎎\", \"Japanese dolls\", \"celebration doll festival\"],\n [\"s23-r2c2\", \"🎏\", \"carp streamer\", \"celebration\"],\n [\"s23-r2c3\", \"🎐\", \"wind chime\", \"bell celebration\"],\n [\"s23-r2c4\", \"\", \"moon viewing ceremony\", \"celebration\"], // redrawn as s45-r5c3\n [\"s23-r2c5\", \"🧧\", \"red envelope\", \"gift good hóngbāo lai luck money see\"],\n [\"s23-r2c6\", \"🎀\", \"ribbon\", \"celebration\"],\n [\"s23-r2c7\", \"🎗️\", \"reminder ribbon\", \"celebration\"],\n [\"s23-r3c1\", \"🎟️\", \"admission tickets\", \"ticket\"],\n [\"s23-r3c2\", \"🎖️\", \"military medal\", \"award celebration\"],\n [\"s23-r3c3\", \"🥈\", \"2nd place medal\", \"second silver\"],\n [\"s23-r3c4\", \"🥉\", \"3rd place medal\", \"bronze third\"],\n [\"s23-r3c5\", \"🥎\", \"softball\", \"ball glove sports underarm\"],\n [\"s23-r3c6\", \"\", \"rugby football\", \"ball sport\"], // redrawn as s43-r2c5\n [\"s23-r3c7\", \"🥏\", \"flying disc\", \"ultimate\"],\n [\"s23-r4c1\", \"🏏\", \"cricket game\", \"ball bat\"],\n [\"s23-r4c2\", \"🏑\", \"field hockey\", \"ball game stick\"],\n [\"s23-r4c3\", \"🏒\", \"ice hockey\", \"game puck stick\"],\n [\"s23-r4c4\", \"🥍\", \"lacrosse\", \"ball goal sports stick\"],\n [\"s23-r4c5\", \"🥅\", \"goal net\", \"soccer football net goal sport\"],\n [\"s23-r4c6\", \"⛳\", \"flag in hole\", \"golf sport\"],\n [\"s23-r4c7\", \"⛸️\", \"ice skate\", \"skating\"],\n [\"s23-r5c1\", \"🎣\", \"fishing pole\", \"entertainment fish sport\"],\n [\"s23-r5c2\", \"🤿\", \"diving mask\", \"scuba snorkeling\"],\n [\"s23-r5c3\", \"🎽\", \"running shirt\", \"athletics sash\"],\n [\"s23-r5c4\", \"🎿\", \"skis\", \"ski snow sport\"],\n [\"s23-r5c5\", \"🛷\", \"sled\", \"luge sledge sleigh snow toboggan\"],\n [\"s23-r5c6\", \"🥌\", \"curling stone\", \"game rock\"],\n [\"s23-r5c7\", \"🔫\", \"water pistol\", \"gun handgun revolver tool weapon\"],\n [\"s23-r6c1\", \"🎱\", \"pool 8 ball\", \"8ball billiard eight game\"],\n [\"s23-r6c2\", \"🕹️\", \"joystick\", \"game video videogame\"],\n [\"s23-r6c3\", \"🎰\", \"slot machine\", \"casino gamble gambling game slots\"],\n [\"s23-r6c4\", \"♠️\", \"spade suit\", \"card game\"],\n [\"s23-r6c5\", \"♥️\", \"heart suit\", \"card emotion game hearts\"],\n [\"s23-r6c6\", \"♦️\", \"diamond suit\", \"card game\"],\n [\"s23-r6c7\", \"♣️\", \"club suit\", \"card clubs game\"],\n [\"s23-r7c1\", \"🃏\", \"joker\", \"card game wildcard\"],\n [\"s23-r7c2\", \"🀄\", \"mahjong red dragon\", \"game\"],\n [\"s23-r7c3\", \"🎴\", \"flower playing cards\", \"card game japanese\"],\n [\"s23-r7c4\", \"🎭\", \"performing arts\", \"actor actress art entertainment mask theater theatre thespian\"],\n [\"s23-r7c5\", \"🖼️\", \"framed picture\", \"art frame museum painting\"],\n [\"s23-r7c6\", \"🧵\", \"thread\", \"needle sewing spool string\"],\n [\"s23-r7c7\", \"🧶\", \"yarn\", \"ball crochet knit\"],\n // ── sheet 24: flags ──\n [\"s24-r1c1\", \"🏁\", \"chequered flag\", \"checkered finish flags game race racing sport win\"],\n [\"s24-r1c2\", \"🚩\", \"triangular flag\", \"construction golf post\"],\n [\"s24-r1c3\", \"🎌\", \"crossed flags\", \"celebration cross japanese\"],\n [\"s24-r1c4\", \"🏴\", \"black flag\", \"waving\"],\n [\"s24-r1c5\", \"🏳️\", \"white flag\", \"waving\"],\n [\"s24-r1c6\", \"🏳️🌈\", \"rainbow flag\", \"bisexual gay genderqueer glbt glbtq lesbian lgbt lgbtq\"],\n [\"s24-r1c7\", \"🏴☠️\", \"pirate flag\", \"jolly plunder roger treasure\"],\n [\"s24-r2c1\", \"🇦🇪\", \"flag: United Arab Emirates\", \"flag united arab emirates ae\"],\n [\"s24-r2c2\", \"🇦🇷\", \"flag: Argentina\", \"flag argentina ar\"],\n [\"s24-r2c3\", \"🇦🇹\", \"flag: Austria\", \"flag austria at\"],\n [\"s24-r2c4\", \"🇦🇺\", \"flag: Australia\", \"flag australia au\"],\n [\"s24-r2c5\", \"🇧🇷\", \"flag: Brazil\", \"flag brazil br\"],\n [\"s24-r2c6\", \"🇨🇦\", \"flag: Canada\", \"flag canada ca\"],\n [\"s24-r2c7\", \"🇨🇱\", \"flag: Chile\", \"flag chile cl\"],\n [\"s24-r3c1\", \"🇨🇳\", \"flag: China\", \"flag china cn\"],\n [\"s24-r3c2\", \"🇨🇴\", \"flag: Colombia\", \"flag colombia co\"],\n [\"s24-r3c3\", \"🇩🇪\", \"flag: Germany\", \"flag germany de\"],\n [\"s24-r3c4\", \"🇩🇿\", \"flag: Algeria\", \"flag algeria dz\"],\n [\"s24-r3c5\", \"🇪🇬\", \"flag: Egypt\", \"flag egypt eg\"],\n [\"s24-r3c6\", \"🇪🇸\", \"flag: Spain\", \"flag spain es\"],\n [\"s24-r3c7\", \"🇫🇷\", \"flag: France\", \"flag france fr\"],\n [\"s24-r4c1\", \"🇬🇧\", \"flag: United Kingdom\", \"flag united kingdom gb\"],\n [\"s24-r4c2\", \"🇮🇩\", \"flag: Indonesia\", \"flag indonesia id\"],\n [\"s24-r4c3\", \"🇮🇪\", \"flag: Ireland\", \"flag ireland ie\"],\n [\"s24-r4c4\", \"🇮🇱\", \"flag: Israel\", \"flag israel il\"],\n [\"s24-r4c5\", \"🇮🇳\", \"flag: India\", \"flag india in\"],\n [\"s24-r4c6\", \"🇮🇹\", \"flag: Italy\", \"flag italy it\"],\n [\"s24-r4c7\", \"🇯🇵\", \"flag: Japan\", \"flag japan jp\"],\n [\"s24-r5c1\", \"🇰🇷\", \"flag: South Korea\", \"flag south korea kr\"],\n [\"s24-r5c2\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // redrawn as s46-r1c1\n [\"s24-r5c3\", \"🇲🇦\", \"flag: Morocco\", \"flag morocco ma\"],\n [\"s24-r5c4\", \"🇲🇽\", \"flag: Mexico\", \"flag mexico mx\"],\n [\"s24-r5c5\", \"🇳🇬\", \"flag: Nigeria\", \"flag nigeria ng\"],\n [\"s24-r5c6\", \"🇵🇪\", \"flag: Peru\", \"flag peru pe\"],\n [\"s24-r5c7\", \"🇵🇭\", \"flag: Philippines\", \"flag philippines ph\"],\n [\"s24-r6c1\", \"🇵🇰\", \"flag: Pakistan\", \"flag pakistan pk\"],\n [\"s24-r6c2\", \"🇵🇱\", \"flag: Poland\", \"flag poland pl\"],\n [\"s24-r6c3\", \"🇵🇷\", \"flag: Puerto Rico\", \"flag puerto rico pr\"],\n [\"s24-r6c4\", \"🇵🇸\", \"flag: Palestinian Territories\", \"flag palestinian territories ps\"],\n [\"s24-r6c5\", \"🇵🇹\", \"flag: Portugal\", \"flag portugal pt\"],\n [\"s24-r6c6\", \"🇷🇺\", \"flag: Russia\", \"flag russia ru\"],\n [\"s24-r6c7\", \"🇸🇦\", \"flag: Saudi Arabia\", \"flag saudi arabia sa\"],\n [\"s24-r7c1\", \"🇸🇪\", \"flag: Sweden\", \"flag sweden se\"],\n [\"s24-r7c2\", \"🇹🇭\", \"flag: Thailand\", \"flag thailand th\"],\n [\"s24-r7c3\", \"🇹🇷\", \"flag: Türkiye\", \"flag türkiye turkiye tr\"],\n [\"s24-r7c4\", \"🇺🇲\", \"flag: U.S. Outlying Islands\", \"flag u.s outlying islands um\"],\n [\"s24-r7c5\", \"🇺🇸\", \"flag: United States\", \"flag united states us\"],\n [\"s24-r7c6\", \"🇻🇪\", \"flag: Venezuela\", \"flag venezuela ve\"],\n [\"s24-r7c7\", \"🇿🇦\", \"flag: South Africa\", \"flag south africa za\"],\n // ── sheet 25: sky, weather and time ──\n [\"s25-r1c1\", \"⌛\", \"hourglass done\", \"sand time timer\"],\n [\"s25-r1c2\", \"⌚\", \"watch\", \"clock time\"],\n [\"s25-r1c3\", \"\", \"twelve o’clock\", \"12 00 o’clock time\"], // redrawn as s45-r4c2\n [\"s25-r1c4\", \"\", \"twelve-thirty\", \"12 30 clock time twelve-thirty\"], // redrawn as s45-r4c3\n [\"s25-r1c5\", \"\", \"one o’clock\", \"1 00 o’clock time\"], // redrawn as s45-r1c1\n [\"s25-r1c6\", \"\", \"one-thirty\", \"1 30 clock one-thirty time\"], // redrawn as s45-r1c2\n [\"s25-r1c7\", \"\", \"two o’clock\", \"2 00 o’clock time\"], // redrawn as s45-r1c3\n [\"s25-r2c1\", \"\", \"two-thirty\", \"2 30 clock time two-thirty\"], // redrawn as s45-r1c4\n [\"s25-r2c2\", \"\", \"three-thirty\", \"3 30 clock three-thirty time\"], // redrawn as s45-r1c6\n [\"s25-r2c3\", \"\", \"four o’clock\", \"4 00 o’clock time\"], // redrawn as s45-r1c7\n [\"s25-r2c4\", \"\", \"four-thirty\", \"30 4 clock four-thirty time\"], // redrawn as s45-r2c1\n [\"s25-r2c5\", \"\", \"five o’clock\", \"5 00 o’clock time\"], // redrawn as s45-r2c2\n [\"s25-r2c6\", \"\", \"five-thirty\", \"30 5 clock five-thirty time\"], // redrawn as s45-r2c3\n [\"s25-r2c7\", \"\", \"six o’clock\", \"6 00 o’clock time\"], // redrawn as s45-r2c4\n [\"s25-r3c1\", \"\", \"six-thirty\", \"30 6 clock six-thirty\"], // redrawn as s45-r2c5\n [\"s25-r3c2\", \"\", \"seven o’clock\", \"0 7 00 o’clock\"], // redrawn as s45-r2c6\n [\"s25-r3c3\", \"\", \"seven-thirty\", \"30 7 clock seven-thirty\"], // redrawn as s45-r2c7\n [\"s25-r3c4\", \"\", \"eight o’clock\", \"8 00 o’clock time\"], // redrawn as s45-r3c1\n [\"s25-r3c5\", \"\", \"eight-thirty\", \"30 8 clock eight-thirty time\"], // redrawn as s45-r3c2\n [\"s25-r3c6\", \"\", \"nine o’clock\", \"9 00 o’clock time\"], // redrawn as s45-r3c3\n [\"s25-r3c7\", \"\", \"nine-thirty\", \"30 9 clock nine-thirty time\"], // redrawn as s45-r3c4\n [\"s25-r4c1\", \"\", \"ten o’clock\", \"0 10 00 o’clock\"], // redrawn as s45-r3c5\n [\"s25-r4c2\", \"\", \"ten-thirty\", \"10 30 clock ten-thirty time\"], // redrawn as s45-r3c6\n [\"s25-r4c3\", \"\", \"eleven o’clock\", \"11 00 o’clock time\"], // redrawn as s45-r3c7\n [\"s25-r4c4\", \"\", \"eleven-thirty\", \"11 30 clock eleven-thirty time\"], // redrawn as s45-r4c1\n [\"s25-r4c5\", \"🌑\", \"new moon\", \"dark space\"],\n [\"s25-r4c6\", \"🌒\", \"waxing crescent moon\", \"dreams space\"],\n [\"s25-r4c7\", \"🌓\", \"first quarter moon\", \"space\"],\n [\"s25-r5c1\", \"🌔\", \"waxing gibbous moon\", \"space\"],\n [\"s25-r5c2\", \"🌖\", \"waning gibbous moon\", \"space\"],\n [\"s25-r5c3\", \"🌘\", \"waning crescent moon\", \"space\"],\n [\"s25-r5c4\", \"🌚\", \"new moon face\", \"space\"],\n [\"s25-r5c5\", \"🌜\", \"last quarter moon face\", \"dreams\"],\n [\"s25-r5c6\", \"🌡️\", \"thermometer\", \"weather\"],\n [\"s25-r5c7\", \"🌝\", \"full moon face\", \"bright\"],\n [\"s25-r6c1\", \"\", \"shooting star\", \"falling night space\"], // redrawn as s45-r4c5\n [\"s25-r6c2\", \"\", \"milky way\", \"space\"], // redrawn as s45-r4c6\n [\"s25-r6c3\", \"⛅\", \"sun behind cloud\", \"cloudy weather\"],\n [\"s25-r6c4\", \"🌤️\", \"sun behind small cloud\", \"weather\"],\n [\"s25-r6c5\", \"🌨️\", \"cloud with snow\", \"cold weather\"],\n [\"s25-r6c6\", \"🌩️\", \"cloud with lightning\", \"weather\"],\n [\"s25-r6c7\", \"🌬️\", \"wind face\", \"blow cloud\"],\n [\"s25-r7c1\", \"☔\", \"umbrella with rain drops\", \"clothing drop weather\"],\n [\"s25-r7c2\", \"⛱️\", \"umbrella on ground\", \"rain sun\"],\n [\"s25-r7c3\", \"⚡\", \"high voltage\", \"danger electric electricity lightning nature thunder thunderbolt zap\"],\n [\"s25-r7c4\", \"⛄\", \"snowman without snow\", \"cold man\"],\n [\"s25-r7c5\", \"\", \"comet\", \"space\"], // redrawn as s45-r4c7\n [\"s25-r7c6\", \"💧\", \"droplet\", \"cold comic drop nature sad sweat tear water\"],\n [\"s25-r7c7\", \"🌊\", \"water wave\", \"nature ocean surf surfer surfing\"],\n // ── sheet 26: people ──\n [\"s26-r1c1\", \"🧒\", \"child\", \"bright-eyed grandchild kid young younger\"],\n [\"s26-r1c2\", \"🧑\", \"person\", \"adult\"],\n [\"s26-r1c3\", \"👨⚕️\", \"man health worker\", \"doctor healthcare nurse therapist\"],\n [\"s26-r1c4\", \"👩⚕️\", \"woman health worker\", \"doctor healthcare nurse therapist\"],\n [\"s26-r1c5\", \"👨🎓\", \"man student\", \"graduate\"],\n [\"s26-r1c6\", \"👩🎓\", \"woman student\", \"graduate\"],\n [\"s26-r1c7\", \"🧑🏫\", \"teacher\", \"instructor lecturer professor\"],\n [\"s26-r2c1\", \"👨🏫\", \"man teacher\", \"instructor lecturer professor\"],\n [\"s26-r2c2\", \"👩🏫\", \"woman teacher\", \"instructor lecturer professor\"],\n [\"s26-r2c3\", \"👨🍳\", \"man cook\", \"chef\"],\n [\"s26-r2c4\", \"👩🍳\", \"woman cook\", \"chef\"],\n [\"s26-r2c5\", \"👨💻\", \"man technologist\", \"coder computer developer inventor software\"],\n [\"s26-r2c6\", \"👩💻\", \"woman technologist\", \"coder computer developer inventor software\"],\n [\"s26-r2c7\", \"👳\", \"person wearing turban\", \"turban headwear head wrap\"],\n [\"s26-r3c1\", \"👳♂️\", \"man wearing turban\", \"turban headwear head wrap man\"],\n [\"s26-r3c2\", \"👳♀️\", \"woman wearing turban\", \"turban headwear head wrap woman\"],\n [\"s26-r3c3\", \"🧕\", \"woman with headscarf\", \"bandana head hijab kerchief mantilla tichel\"],\n [\"s26-r3c4\", \"🎅\", \"Santa Claus\", \"celebration christmas fairy fantasy father holiday merry tale\"],\n [\"s26-r3c5\", \"🧞♂️\", \"man genie\", \"djinn fantasy jinn lamp myth rub wishes\"],\n [\"s26-r3c6\", \"🧞♀️\", \"woman genie\", \"djinn fantasy jinn lamp myth rub wishes\"],\n [\"s26-r3c7\", \"🧖\", \"person in steamy room\", \"day luxurious pamper relax sauna spa steam steambath\"],\n [\"s26-r4c1\", \"🧖♂️\", \"man in steamy room\", \"day luxurious pamper relax sauna spa steam steambath\"],\n [\"s26-r4c2\", \"🧖♀️\", \"woman in steamy room\", \"day luxurious pamper relax sauna spa steam steambath\"],\n [\"s26-r4c3\", \"🧗\", \"person climbing\", \"climb climber mountain rock scale up\"],\n [\"s26-r4c4\", \"🧗♂️\", \"man climbing\", \"climb climber mountain rock scale up\"],\n [\"s26-r4c5\", \"🧗♀️\", \"woman climbing\", \"climb climber mountain rock scale up\"],\n [\"s26-r4c6\", \"⛷️\", \"skier\", \"ski snow\"],\n [\"s26-r4c7\", \"🏂\", \"snowboarder\", \"ski snow snowboard sport\"],\n [\"s26-r5c1\", \"🚣\", \"person rowing boat\", \"canoe cruise fishing lake oar paddle raft river\"],\n [\"s26-r5c2\", \"🚣♂️\", \"man rowing boat\", \"canoe cruise fishing lake oar paddle raft river\"],\n [\"s26-r5c3\", \"🚣♀️\", \"woman rowing boat\", \"canoe cruise fishing lake oar paddle raft river\"],\n [\"s26-r5c4\", \"⛹️♂️\", \"man bouncing ball\", \"athletic basketball championship dribble net player throw\"],\n [\"s26-r5c5\", \"⛹️♀️\", \"woman bouncing ball\", \"athletic basketball championship dribble net player throw\"],\n [\"s26-r5c6\", \"🚵\", \"person mountain biking\", \"bicycle bicyclist bike cycle cyclist riding sport\"],\n [\"s26-r5c7\", \"🚵♂️\", \"man mountain biking\", \"bicycle bicyclist bike cycle cyclist riding sport\"],\n [\"s26-r6c1\", \"🚵♀️\", \"woman mountain biking\", \"bicycle bicyclist bike cycle cyclist riding sport\"],\n [\"s26-r6c2\", \"🤼\", \"people wrestling\", \"combat duel grapple ring tournament wrestle\"],\n [\"s26-r6c3\", \"🤼♂️\", \"men wrestling\", \"combat duel grapple ring tournament wrestle\"],\n [\"s26-r6c4\", \"🤼♀️\", \"women wrestling\", \"combat duel grapple ring tournament wrestle\"],\n [\"s26-r6c5\", \"🤾\", \"person playing handball\", \"athletics ball catch chuck hurl lob pitch sport\"],\n [\"s26-r6c6\", \"🤾♂️\", \"man playing handball\", \"athletics ball catch chuck hurl lob pitch sport\"],\n [\"s26-r6c7\", \"🤾♀️\", \"woman playing handball\", \"athletics ball catch chuck hurl lob pitch sport\"],\n [\"s26-r7c1\", \"🤹\", \"person juggling\", \"act balance balancing handle juggle manage multitask skill\"],\n [\"s26-r7c2\", \"🤹♂️\", \"man juggling\", \"act balance balancing handle juggle manage multitask skill\"],\n [\"s26-r7c3\", \"🤹♀️\", \"woman juggling\", \"act balance balancing handle juggle manage multitask skill\"],\n [\"s26-r7c4\", \"👨❤️💋👨\", \"kiss: man, man\", \"anniversary babe bae couple date dating heart love\"],\n [\"s26-r7c5\", \"👨❤️👨\", \"couple with heart: man, man\", \"anniversary babe bae dating kiss love person relationship\"],\n [\"s26-r7c6\", \"👩❤️👩\", \"couple with heart: woman, woman\", \"anniversary babe bae dating kiss love person relationship\"],\n [\"s26-r7c7\", \"👪\", \"family\", \"child\"],\n // ── sheet 27: objects ──\n [\"s27-r1c1\", \"🥽\", \"goggles\", \"dive eye protection scuba swimming welding\"],\n [\"s27-r1c2\", \"🧣\", \"scarf\", \"bundle cold neck up\"],\n [\"s27-r1c3\", \"🧤\", \"gloves\", \"hand\"],\n [\"s27-r1c4\", \"🧥\", \"coat\", \"brr bundle cold jacket up\"],\n [\"s27-r1c5\", \"🧦\", \"socks\", \"stocking\"],\n [\"s27-r1c6\", \"👘\", \"kimono\", \"clothing comfortable\"],\n [\"s27-r1c7\", \"👚\", \"woman’s clothes\", \"blouse clothing collar dress dressed lady shirt shopping\"],\n [\"s27-r2c1\", \"👛\", \"purse\", \"clothes clothing coin dress fancy handbag shopping\"],\n [\"s27-r2c2\", \"👜\", \"handbag\", \"bag clothes clothing dress lady purse shopping\"],\n [\"s27-r2c3\", \"👞\", \"man’s shoe\", \"brown clothes clothing feet foot kick man’s shoes\"],\n [\"s27-r2c4\", \"🥾\", \"hiking boot\", \"backpacking brown camping outdoors shoe\"],\n [\"s27-r2c5\", \"👡\", \"woman’s sandal\", \"clothing shoe woman’s\"],\n [\"s27-r2c6\", \"👢\", \"woman’s boot\", \"clothes clothing dress shoe shoes shopping woman’s\"],\n [\"s27-r2c7\", \"⛑️\", \"rescue worker’s helmet\", \"aid cross face hat worker’s\"],\n [\"s27-r3c1\", \"🔇\", \"muted speaker\", \"mute quiet silent sound\"],\n [\"s27-r3c2\", \"🔈\", \"speaker low volume\", \"soft sound\"],\n [\"s27-r3c3\", \"🔉\", \"speaker medium volume\", \"sound\"],\n [\"s27-r3c4\", \"📯\", \"postal horn\", \"post\"],\n [\"s27-r3c5\", \"📠\", \"fax machine\", \"communication\"],\n [\"s27-r3c6\", \"💽\", \"computer disk\", \"minidisk optical\"],\n [\"s27-r3c7\", \"📀\", \"dvd\", \"blu-ray cd computer disk optical\"],\n [\"s27-r4c1\", \"🎞️\", \"film frames\", \"cinema movie\"],\n [\"s27-r4c2\", \"📽️\", \"film projector\", \"cinema movie video\"],\n [\"s27-r4c3\", \"📼\", \"videocassette\", \"old school tape vcr vhs video\"],\n [\"s27-r4c4\", \"🏮\", \"red paper lantern\", \"bar light restaurant\"],\n [\"s27-r4c5\", \"📔\", \"notebook with decorative cover\", \"book decorated education school writing\"],\n [\"s27-r4c6\", \"📗\", \"green book\", \"education fantasy library reading\"],\n [\"s27-r4c7\", \"📘\", \"blue book\", \"education fantasy library reading\"],\n [\"s27-r5c1\", \"📙\", \"orange book\", \"education fantasy library reading\"],\n [\"s27-r5c2\", \"📃\", \"page with curl\", \"document paper\"],\n [\"s27-r5c3\", \"📜\", \"scroll\", \"paper\"],\n [\"s27-r5c4\", \"🗞️\", \"rolled-up newspaper\", \"news paper rolled-up\"],\n [\"s27-r5c5\", \"📑\", \"bookmark tabs\", \"mark marker\"],\n [\"s27-r5c6\", \"💴\", \"yen banknote\", \"bank bill currency money note\"],\n [\"s27-r5c7\", \"💶\", \"euro banknote\", \"100 bank bill currency money note rich\"],\n [\"s27-r6c1\", \"💷\", \"pound banknote\", \"bank bill billion cash currency money note pounds\"],\n [\"s27-r6c2\", \"💹\", \"chart increasing with yen\", \"bank currency graph growth market money rise trend\"],\n [\"s27-r6c3\", \"📧\", \"e-mail\", \"e-mail email letter\"],\n [\"s27-r6c4\", \"📨\", \"incoming envelope\", \"delivering e-mail email letter mail receive sent\"],\n [\"s27-r6c5\", \"📥\", \"inbox tray\", \"box email letter mail receive zero\"],\n [\"s27-r6c6\", \"🗳️\", \"ballot box with ballot\", \"ballot box election vote voting\"],\n [\"s27-r6c7\", \"✒️\", \"black nib\", \"pen\"],\n [\"s27-r7c1\", \"🖇️\", \"linked paperclips\", \"link paperclip\"],\n [\"s27-r7c2\", \"⛏️\", \"pick\", \"hammer mining tool\"],\n [\"s27-r7c3\", \"⚒️\", \"hammer and pick\", \"tool\"],\n [\"s27-r7c4\", \"🛠️\", \"hammer and wrench\", \"spanner tool\"],\n [\"s27-r7c5\", \"⛓️\", \"chains\", \"chain\"],\n [\"s27-r7c6\", \"🧫\", \"petri dish\", \"bacteria biologist biology culture lab\"],\n [\"s27-r7c7\", \"🔭\", \"telescope\", \"contact extraterrestrial science tool\"],\n [\"s28-r1c1\", \"🏧\", \"ATM sign\", \"automated bank cash money teller\"],\n [\"s28-r1c2\", \"🚰\", \"potable water\", \"drinking\"],\n [\"s28-r1c3\", \"♿\", \"wheelchair symbol\", \"access handicap\"],\n [\"s28-r1c4\", \"🚹\", \"men’s room\", \"bathroom lavatory man men’s restroom toilet wc\"],\n [\"s28-r1c5\", \"🚺\", \"women’s room\", \"bathroom lavatory restroom toilet wc woman women’s\"],\n [\"s28-r1c6\", \"🚼\", \"baby symbol\", \"changing\"],\n [\"s28-r1c7\", \"🚸\", \"children crossing\", \"child pedestrian traffic\"],\n [\"s28-r2c1\", \"☢️\", \"radioactive\", \"sign\"],\n [\"s28-r2c2\", \"☣️\", \"biohazard\", \"sign\"],\n [\"s28-r2c3\", \"↘️\", \"down-right arrow\", \"direction down-right intercardinal southeast\"],\n [\"s28-r2c4\", \"↙️\", \"down-left arrow\", \"direction down-left intercardinal southwest\"],\n [\"s28-r2c5\", \"↔️\", \"left-right arrow\", \"left-right\"],\n [\"s28-r2c6\", \"⤴️\", \"right arrow curving up\", \"arrow curve up turn\"],\n [\"s28-r2c7\", \"🔄\", \"counterclockwise arrows button\", \"again anticlockwise arrow deja refresh rewindershins vu\"],\n [\"s28-r3c1\", \"🔚\", \"END arrow\", \"arrow end finish left\"],\n [\"s28-r3c2\", \"✡️\", \"star of David\", \"jew jewish judaism religion\"],\n [\"s28-r3c3\", \"☪️\", \"star and crescent\", \"islam muslim ramadan religion\"],\n [\"s28-r3c4\", \"🔯\", \"dotted six-pointed star\", \"fortune jewish judaism six-pointed\"],\n [\"s28-r3c5\", \"♉\", \"Taurus\", \"bull horoscope ox zodiac\"],\n [\"s28-r3c6\", \"♊\", \"Gemini\", \"horoscope twins zodiac\"],\n [\"s28-r3c7\", \"♋\", \"Cancer\", \"crab horoscope zodiac\"],\n [\"s28-r4c1\", \"♌\", \"Leo\", \"horoscope lion zodiac\"],\n [\"s28-r4c2\", \"♍\", \"Virgo\", \"horoscope zodiac\"],\n [\"s28-r4c3\", \"♎\", \"Libra\", \"balance horoscope justice scales zodiac\"],\n [\"s28-r4c4\", \"♏\", \"Scorpio\", \"horoscope scorpion scorpius zodiac\"],\n [\"s28-r4c5\", \"♐\", \"Sagittarius\", \"archer horoscope zodiac\"],\n [\"s28-r4c6\", \"♑\", \"Capricorn\", \"goat horoscope zodiac\"],\n [\"s28-r4c7\", \"♒\", \"Aquarius\", \"bearer horoscope water zodiac\"],\n [\"s28-r5c1\", \"♓\", \"Pisces\", \"fish horoscope zodiac\"],\n [\"s28-r5c2\", \"🔁\", \"repeat button\", \"arrow clockwise\"],\n [\"s28-r5c3\", \"⏯️\", \"play or pause button\", \"arrow right triangle\"],\n [\"s28-r5c4\", \"◀️\", \"reverse button\", \"arrow left triangle\"],\n [\"s28-r5c5\", \"⏪\", \"fast reverse button\", \"arrow double rewind\"],\n [\"s28-r5c6\", \"🔼\", \"upwards button\", \"arrow red up\"],\n [\"s28-r5c7\", \"⏬\", \"fast down button\", \"arrow double\"],\n [\"s28-r6c1\", \"🎦\", \"cinema\", \"camera film movie\"],\n [\"s28-r6c2\", \"📶\", \"antenna bars\", \"bar cell communication mobile phone signal telephone\"],\n [\"s28-r6c3\", \"❔\", \"white question mark\", \"outlined punctuation\"],\n [\"s28-r6c4\", \"➰\", \"curly loop\", \"curl\"],\n [\"s28-r6c5\", \"〽️\", \"part alternation mark\", \"mark part alternation song\"],\n [\"s28-r6c6\", \"\", \"eight-spoked asterisk\", \"eight-spoked\"], // redrawn as s54-r2c4\n [\"s28-r6c7\", \"✴️\", \"eight-pointed star\", \"eight-pointed\"],\n [\"s28-r7c1\", \"❇️\", \"sparkle\", \"sparkle star shine\"],\n [\"s28-r7c2\", \"◼️\", \"black medium square\", \"geometric\"],\n [\"s28-r7c3\", \"◾\", \"black medium-small square\", \"geometric medium-small\"],\n [\"s28-r7c4\", \"◽\", \"white medium-small square\", \"geometric medium-small\"],\n [\"s28-r7c5\", \"▫️\", \"white small square\", \"geometric\"],\n [\"s28-r7c6\", \"🔘\", \"radio button\", \"geometric\"],\n [\"s28-r7c7\", \"🔲\", \"black square button\", \"geometric\"],\n // ── sheet 29: letters, numbers and keycaps ──\n [\"s29-r1c1\", \"#️⃣\", \"keycap: #\", \"keycap hash number pound sign\"],\n [\"s29-r1c2\", \"*️⃣\", \"keycap: *\", \"keycap asterisk star\"],\n [\"s29-r1c3\", \"0️⃣\", \"keycap: 0\", \"zero\"],\n [\"s29-r1c4\", \"1️⃣\", \"keycap: 1\", \"one\"],\n [\"s29-r1c5\", \"2️⃣\", \"keycap: 2\", \"two\"],\n [\"s29-r1c6\", \"3️⃣\", \"keycap: 3\", \"three\"],\n [\"s29-r1c7\", \"4️⃣\", \"keycap: 4\", \"four\"],\n [\"s29-r2c1\", \"5️⃣\", \"keycap: 5\", \"five\"],\n [\"s29-r2c2\", \"6️⃣\", \"keycap: 6\", \"six\"],\n [\"s29-r2c3\", \"7️⃣\", \"keycap: 7\", \"seven\"],\n [\"s29-r2c4\", \"8️⃣\", \"keycap: 8\", \"eight\"],\n [\"s29-r2c5\", \"9️⃣\", \"keycap: 9\", \"nine\"],\n [\"s29-r2c6\", \"🔟\", \"keycap: 10\", \"keycap ten 10 number\"],\n [\"s29-r2c7\", \"🔠\", \"input latin uppercase\", \"abcd letters\"],\n [\"s29-r3c1\", \"🔡\", \"input latin lowercase\", \"abcd letters\"],\n [\"s29-r3c2\", \"🔢\", \"input numbers\", \"1234\"],\n [\"s29-r3c3\", \"🔤\", \"input latin letters\", \"abc alphabet\"],\n [\"s29-r3c4\", \"🅰️\", \"A button (blood type)\", \"a button blood type letter\"],\n [\"s29-r3c5\", \"🆎\", \"AB button (blood type)\", \"ab button blood type letters\"],\n [\"s29-r3c6\", \"🅱️\", \"B button (blood type)\", \"b button blood type letter\"],\n [\"s29-r3c7\", \"🆑\", \"CL button\", \"cl clear button sign\"],\n [\"s29-r4c1\", \"🆒\", \"COOL button\", \"cool button word sign\"],\n [\"s29-r4c2\", \"🆓\", \"FREE button\", \"free button word sign\"],\n [\"s29-r4c3\", \"ℹ️\", \"information\", \"i\"],\n [\"s29-r4c4\", \"🆔\", \"ID button\", \"identity\"],\n [\"s29-r4c5\", \"Ⓜ️\", \"circled M\", \"circle\"],\n [\"s29-r4c6\", \"🆕\", \"NEW button\", \"new button word sign\"],\n [\"s29-r4c7\", \"🆖\", \"NG button\", \"ng no good button sign\"],\n [\"s29-r5c1\", \"🅾️\", \"O button (blood type)\", \"o button blood type letter\"],\n [\"s29-r5c2\", \"🆗\", \"OK button\", \"okay\"],\n [\"s29-r5c3\", \"🅿️\", \"P button\", \"parking\"],\n [\"s29-r5c4\", \"🆘\", \"SOS button\", \"help\"],\n [\"s29-r5c5\", \"🆙\", \"UP! button\", \"mark\"],\n [\"s29-r5c6\", \"🆚\", \"VS button\", \"versus\"],\n [\"s29-r5c7\", \"🈷️\", \"Japanese “monthly amount” button\", \"ideograph\"],\n [\"s29-r6c1\", \"🈶\", \"Japanese “not free of charge” button\", \"ideograph\"],\n [\"s29-r6c2\", \"🈯\", \"Japanese “reserved” button\", \"ideograph\"],\n [\"s29-r6c3\", \"🉐\", \"Japanese “bargain” button\", \"ideograph\"],\n [\"s29-r6c4\", \"🈹\", \"Japanese “discount” button\", \"ideograph\"],\n [\"s29-r6c5\", \"🈚\", \"Japanese “free of charge” button\", \"ideograph\"],\n [\"s29-r6c6\", \"🈲\", \"Japanese “prohibited” button\", \"ideograph\"],\n [\"s29-r6c7\", \"🉑\", \"Japanese “acceptable” button\", \"ideograph\"],\n [\"s29-r7c1\", \"🈸\", \"Japanese “application” button\", \"ideograph\"],\n [\"s29-r7c2\", \"🈴\", \"Japanese “passing grade” button\", \"ideograph\"],\n [\"s29-r7c3\", \"🈳\", \"Japanese “vacancy” button\", \"ideograph\"],\n [\"s29-r7c4\", \"㊗️\", \"Japanese “congratulations” button\", \"ideograph\"],\n [\"s29-r7c5\", \"㊙️\", \"Japanese “secret” button\", \"ideograph\"],\n [\"s29-r7c6\", \"🈺\", \"Japanese “open for business” button\", \"ideograph\"],\n [\"s29-r7c7\", \"🈵\", \"Japanese “no vacancy” button\", \"ideograph\"],\n // ── sheet 30: food and drink ──\n [\"s30-r1c1\", \"🍈\", \"melon\", \"cantaloupe fruit\"],\n [\"s30-r1c2\", \"🍋🟩\", \"lime\", \"acidity citrus cocktail fruit garnish key margarita mojito\"],\n [\"s30-r1c3\", \"🥝\", \"kiwi fruit\", \"food\"],\n [\"s30-r1c4\", \"🫒\", \"olive\", \"food\"],\n [\"s30-r1c5\", \"🫑\", \"bell pepper\", \"capsicum food vegetable\"],\n [\"s30-r1c6\", \"🥬\", \"leafy green\", \"bok burgers cabbage choy kale lettuce salad\"],\n [\"s30-r1c7\", \"🧄\", \"garlic\", \"flavoring\"],\n [\"s30-r2c1\", \"🧅\", \"onion\", \"flavoring\"],\n [\"s30-r2c2\", \"🫘\", \"beans\", \"food kidney legume small\"],\n [\"s30-r2c3\", \"🌰\", \"chestnut\", \"almond plant\"],\n [\"s30-r2c4\", \"🫚\", \"ginger root\", \"beer health herb natural spice\"],\n [\"s30-r2c5\", \"🫛\", \"pea pod\", \"beans beanstalk edamame legume soybean vegetable veggie\"],\n [\"s30-r2c6\", \"\", \"root vegetable\", \"beet food garden radish salad turnip vegetarian\"],\n [\"s30-r2c7\", \"🥖\", \"baguette bread\", \"food french\"],\n [\"s30-r3c1\", \"🫓\", \"flatbread\", \"arepa bread food gordita lavash naan pita\"],\n [\"s30-r3c2\", \"🥨\", \"pretzel\", \"convoluted twisted\"],\n [\"s30-r3c3\", \"🥯\", \"bagel\", \"bakery bread breakfast schmear\"],\n [\"s30-r3c4\", \"🧇\", \"waffle\", \"breakfast indecisive iron\"],\n [\"s30-r3c5\", \"🫔\", \"tamale\", \"food mexican pamonha wrapped\"],\n [\"s30-r3c6\", \"🥙\", \"stuffed flatbread\", \"falafel food gyro kebab\"],\n [\"s30-r3c7\", \"🧆\", \"falafel\", \"chickpea meatball\"],\n [\"s30-r4c1\", \"🥘\", \"shallow pan of food\", \"casserole paella\"],\n [\"s30-r4c2\", \"🍲\", \"pot of food\", \"soup stew\"],\n [\"s30-r4c3\", \"🫕\", \"fondue\", \"cheese chocolate food melted pot ski\"],\n [\"s30-r4c4\", \"🥣\", \"bowl with spoon\", \"breakfast cereal congee oatmeal porridge\"],\n [\"s30-r4c5\", \"🧈\", \"butter\", \"dairy\"],\n [\"s30-r4c6\", \"🧂\", \"salt\", \"condiment flavor mad salty shaker taste upset\"],\n [\"s30-r4c7\", \"🥫\", \"canned food\", \"can\"],\n [\"s30-r5c1\", \"🍱\", \"bento box\", \"food\"],\n [\"s30-r5c2\", \"🍘\", \"rice cracker\", \"food\"],\n [\"s30-r5c3\", \"🍛\", \"curry rice\", \"food\"],\n [\"s30-r5c4\", \"🍠\", \"roasted sweet potato\", \"food\"],\n [\"s30-r5c5\", \"🍢\", \"oden\", \"food kebab restaurant seafood skewer stick\"],\n [\"s30-r5c6\", \"🍥\", \"fish cake with swirl\", \"food pastry restaurant\"],\n [\"s30-r5c7\", \"🥮\", \"moon cake\", \"autumn festival yuèbǐng\"],\n [\"s30-r6c1\", \"🥟\", \"dumpling\", \"empanada gyōza jiaozi pierogi potsticker\"],\n [\"s30-r6c2\", \"🥠\", \"fortune cookie\", \"prophecy\"],\n [\"s30-r6c3\", \"🥡\", \"takeout box\", \"chopsticks delivery food oyster pail\"],\n [\"s30-r6c4\", \"🍮\", \"custard\", \"dessert pudding sweet\"],\n [\"s30-r6c5\", \"🫖\", \"teapot\", \"brew drink food pot tea\"],\n [\"s30-r6c6\", \"🍶\", \"sake\", \"bar beverage bottle cup drink restaurant\"],\n [\"s30-r6c7\", \"🫗\", \"pouring liquid\", \"accident drink empty glass oops pour spill water\"],\n [\"s30-r7c1\", \"🧉\", \"mate\", \"drink\"],\n [\"s30-r7c2\", \"🧊\", \"ice\", \"cold cube iceberg\"],\n [\"s30-r7c3\", \"🥢\", \"chopsticks\", \"hashi jeotgarak kuaizi\"],\n [\"s30-r7c4\", \"🥄\", \"spoon\", \"eat tableware\"],\n [\"s30-r7c5\", \"🫙\", \"jar\", \"condiment container empty nothing sauce store\"],\n [\"s30-r7c6\", \"🏺\", \"amphora\", \"aquarius cooking drink jug tool weapon zodiac\"],\n [\"s30-r7c7\", \"\", \"canned food\", \"can\"], // duplicate of s30-r4c7\n // ── sheet 31: flags ──\n [\"s31-r1c1\", \"🇦🇱\", \"flag: Albania\", \"flag albania al\"],\n [\"s31-r1c2\", \"🇦🇲\", \"flag: Armenia\", \"flag armenia am\"],\n [\"s31-r1c3\", \"🇦🇿\", \"flag: Azerbaijan\", \"flag azerbaijan az\"],\n [\"s31-r1c4\", \"🇧🇪\", \"flag: Belgium\", \"flag belgium be\"],\n [\"s31-r1c5\", \"🇧🇬\", \"flag: Bulgaria\", \"flag bulgaria bg\"],\n [\"s31-r1c6\", \"🇧🇭\", \"flag: Bahrain\", \"flag bahrain bh\"],\n [\"s31-r1c7\", \"🇧🇴\", \"flag: Bolivia\", \"flag bolivia bo\"],\n [\"s31-r2c1\", \"🇨🇩\", \"flag: Congo - Kinshasa\", \"-\"],\n [\"s31-r2c2\", \"🇨🇭\", \"flag: Switzerland\", \"flag switzerland ch\"],\n [\"s31-r2c3\", \"🇨🇮\", \"flag: Côte d’Ivoire\", \"d’ivoire\"],\n [\"s31-r2c4\", \"🇨🇲\", \"flag: Cameroon\", \"flag cameroon cm\"],\n [\"s31-r2c5\", \"🇨🇵\", \"flag: Clipperton Island\", \"flag clipperton island cp\"],\n [\"s31-r2c6\", \"🇨🇺\", \"flag: Cuba\", \"flag cuba cu\"],\n [\"s31-r2c7\", \"🇩🇰\", \"flag: Denmark\", \"flag denmark dk\"],\n [\"s31-r3c1\", \"🇩🇴\", \"flag: Dominican Republic\", \"flag dominican republic do\"],\n [\"s31-r3c2\", \"🇪🇦\", \"flag: Ceuta & Melilla\", \"flag ceuta melilla ea\"],\n [\"s31-r3c3\", \"🇪🇨\", \"flag: Ecuador\", \"flag ecuador ec\"],\n [\"s31-r3c4\", \"🇪🇺\", \"flag: European Union\", \"flag european union eu\"],\n [\"s31-r3c5\", \"🇫🇮\", \"flag: Finland\", \"flag finland fi\"],\n [\"s31-r3c6\", \"🇬🇪\", \"flag: Georgia\", \"flag georgia ge\"],\n [\"s31-r3c7\", \"🇬🇭\", \"flag: Ghana\", \"flag ghana gh\"],\n [\"s31-r4c1\", \"🇬🇷\", \"flag: Greece\", \"flag greece gr\"],\n [\"s31-r4c2\", \"🇬🇹\", \"flag: Guatemala\", \"flag guatemala gt\"],\n [\"s31-r4c3\", \"🇭🇳\", \"flag: Honduras\", \"flag honduras hn\"],\n [\"s31-r4c4\", \"🇭🇹\", \"flag: Haiti\", \"flag haiti ht\"],\n [\"s31-r4c5\", \"🇭🇺\", \"flag: Hungary\", \"flag hungary hu\"],\n [\"s31-r4c6\", \"🇮🇶\", \"flag: Iraq\", \"flag iraq iq\"],\n [\"s31-r4c7\", \"🇯🇲\", \"flag: Jamaica\", \"flag jamaica jm\"],\n [\"s31-r5c1\", \"🇰🇼\", \"flag: Kuwait\", \"flag kuwait kw\"],\n [\"s31-r5c2\", \"🇱🇧\", \"flag: Lebanon\", \"flag lebanon lb\"],\n [\"s31-r5c3\", \"🇱🇾\", \"flag: Libya\", \"flag libya ly\"],\n [\"s31-r5c4\", \"🇲🇨\", \"flag: Monaco\", \"flag monaco mc\"],\n [\"s31-r5c5\", \"🇲🇾\", \"flag: Malaysia\", \"flag malaysia my\"],\n [\"s31-r5c6\", \"🇳🇮\", \"flag: Nicaragua\", \"flag nicaragua ni\"],\n [\"s31-r5c7\", \"🇳🇱\", \"flag: Netherlands\", \"flag netherlands nl\"],\n [\"s31-r6c1\", \"🇳🇴\", \"flag: Norway\", \"flag norway no\"],\n [\"s31-r6c2\", \"🇵🇦\", \"flag: Panama\", \"flag panama pa\"],\n [\"s31-r6c3\", \"🇵🇾\", \"flag: Paraguay\", \"flag paraguay py\"],\n [\"s31-r6c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // redrawn as s52-r1c1\n [\"s31-r6c5\", \"🇸🇬\", \"flag: Singapore\", \"flag singapore sg\"],\n [\"s31-r6c6\", \"🇸🇻\", \"flag: El Salvador\", \"flag el salvador sv\"],\n [\"s31-r6c7\", \"🇹🇼\", \"flag: Taiwan\", \"flag taiwan tw\"],\n [\"s31-r7c1\", \"🇺🇦\", \"flag: Ukraine\", \"flag ukraine ua\"],\n [\"s31-r7c2\", \"🇺🇾\", \"flag: Uruguay\", \"flag uruguay uy\"],\n [\"s31-r7c3\", \"🇻🇳\", \"flag: Vietnam\", \"flag vietnam vn\"],\n [\"s31-r7c4\", \"🇾🇪\", \"flag: Yemen\", \"flag yemen ye\"],\n [\"s31-r7c5\", \"🏴\", \"flag: England\", \"flag england gb eng\"],\n [\"s31-r7c6\", \"🏴\", \"flag: Scotland\", \"flag scotland gb sct\"],\n [\"s31-r7c7\", \"🏴\", \"flag: Wales\", \"flag wales gb wls\"],\n // ── sheet 32: places and transport ──\n [\"s32-r1c1\", \"\", \"map of Japan\", \"map japan country island\"], // redrawn as s44-r1c1\n [\"s32-r1c2\", \"\", \"landslide\", \"avalanche danger disaster earthquake mountain mudslide rocks\"], // redrawn as s44-r1c2\n [\"s32-r1c3\", \"\", \"classical building\", \"classical building columns museum government\"], // redrawn as s44-r1c3\n [\"s32-r1c4\", \"\", \"building construction\", \"crane\"], // redrawn as s44-r1c4\n [\"s32-r1c5\", \"\", \"rock\", \"boulder heavy solid stone tough\"], // redrawn as s44-r1c5\n [\"s32-r1c6\", \"\", \"wood\", \"log lumber timber\"], // redrawn as s44-r1c6\n [\"s32-r1c7\", \"\", \"hut\", \"home house roundhouse shelter yurt\"], // redrawn as s44-r1c7\n [\"s32-r2c1\", \"\", \"derelict house\", \"home\"], // redrawn as s44-r2c1\n [\"s32-r2c2\", \"\", \"Japanese post office\", \"building\"], // redrawn as s44-r2c2\n [\"s32-r2c3\", \"\", \"post office\", \"building european\"], // redrawn as s44-r2c3\n [\"s32-r2c4\", \"\", \"convenience store\", \"24 building hours\"], // redrawn as s44-r2c4\n [\"s32-r2c5\", \"\", \"department store\", \"building\"], // redrawn as s44-r2c5\n [\"s32-r2c6\", \"\", \"factory\", \"building\"], // redrawn as s44-r2c6\n [\"s32-r2c7\", \"\", \"hindu temple\", \"hindu temple religion worship\"], // redrawn as s44-r2c7\n [\"s32-r3c1\", \"\", \"synagogue\", \"jew jewish judaism religion temple\"], // redrawn as s44-r3c1\n [\"s32-r3c2\", \"\", \"shinto shrine\", \"religion\"], // redrawn as s44-r3c2\n [\"s32-r3c3\", \"\", \"foggy\", \"fog\"], // redrawn as s44-r3c3\n [\"s32-r3c4\", \"\", \"playground slide\", \"amusement park play playing sliding theme\"], // redrawn as s44-r3c4\n [\"s32-r3c5\", \"\", \"high-speed train\", \"high-speed railway shinkansen\"], // redrawn as s44-r3c5\n [\"s32-r3c6\", \"\", \"bullet train\", \"high-speed nose railway shinkansen speed travel\"], // redrawn as s44-r3c6\n [\"s32-r3c7\", \"\", \"train\", \"arrived choo railway\"], // redrawn as s44-r3c7\n [\"s32-r4c1\", \"\", \"metro\", \"subway travel\"], // redrawn as s44-r4c1\n [\"s32-r4c2\", \"\", \"light rail\", \"arrived monorail railway\"], // redrawn as s44-r4c2\n [\"s32-r4c3\", \"\", \"station\", \"railway train\"], // redrawn as s44-r4c3\n [\"s32-r4c4\", \"\", \"tram\", \"trolleybus\"], // redrawn as s44-r4c4\n [\"s32-r4c5\", \"\", \"monorail\", \"vehicle\"], // redrawn as s44-r4c5\n [\"s32-r4c6\", \"\", \"mountain railway\", \"car trip\"], // redrawn as s44-r4c6\n [\"s32-r4c7\", \"\", \"oncoming bus\", \"cars\"], // redrawn as s44-r4c7\n [\"s32-r5c1\", \"\", \"trolleybus\", \"bus tram trolley\"], // redrawn as s44-r5c1\n [\"s32-r5c2\", \"\", \"oncoming taxi\", \"cab cabbie cars drove hail yellow\"], // redrawn as s44-r5c2\n [\"s32-r5c3\", \"\", \"pickup truck\", \"automobile car flatbed pick-up transportation\"], // redrawn as s44-r5c3\n [\"s32-r5c4\", \"\", \"manual wheelchair\", \"accessibility\"], // redrawn as s44-r5c4\n [\"s32-r5c5\", \"\", \"motorized wheelchair\", \"accessibility\"], // redrawn as s44-r5c5\n [\"s32-r5c6\", \"\", \"bus stop\", \"busstop\"], // redrawn as s44-r5c6\n [\"s32-r5c7\", \"\", \"railway track\", \"train\"], // redrawn as s44-r5c7\n [\"s32-r6c1\", \"\", \"oil drum\", \"oil drum barrel fuel petrol\"], // redrawn as s44-r6c1\n [\"s32-r6c2\", \"\", \"horizontal traffic light\", \"intersection signal stop stoplight\"], // redrawn as s44-r6c2\n [\"s32-r6c3\", \"\", \"canoe\", \"boat\"], // redrawn as s44-r6c3\n [\"s32-r6c4\", \"\", \"speedboat\", \"billionaire boat lake luxury millionaire summer travel\"], // redrawn as s44-r6c4\n [\"s32-r6c5\", \"\", \"passenger ship\", \"passenger ship cruise boat ocean\"], // redrawn as s44-r6c5\n [\"s32-r6c6\", \"\", \"ferry\", \"boat passenger\"], // redrawn as s44-r6c6\n [\"s32-r6c7\", \"\", \"motor boat\", \"motorboat\"], // redrawn as s44-r6c7\n [\"s32-r7c1\", \"\", \"small airplane\", \"aeroplane plane\"], // redrawn as s44-r7c1\n [\"s32-r7c2\", \"\", \"airplane arrival\", \"aeroplane arrivals arriving landing plane\"], // redrawn as s45-r6c1\n [\"s32-r7c3\", \"\", \"suspension railway\", \"suspension railway monorail train transit\"], // redrawn as s44-r7c3\n [\"s32-r7c4\", \"\", \"mountain cableway\", \"cable gondola lift ski\"], // redrawn as s44-r7c4\n [\"s32-r7c5\", \"\", \"aerial tramway\", \"cable car gondola ropeway\"], // redrawn as s44-r7c5\n [\"s32-r7c6\", \"\", \"satellite\", \"space\"], // redrawn as s44-r7c6\n [\"s32-r7c7\", \"\", \"bellhop bell\", \"hotel\"], // redrawn as s44-r7c7\n // ── sheet 33: people ──\n [\"s33-r1c1\", \"👨🦰\", \"man: red hair\", \"adult bro\"],\n [\"s33-r1c2\", \"👨🦱\", \"man: curly hair\", \"adult bro\"],\n [\"s33-r1c3\", \"👨🦳\", \"man: white hair\", \"adult bro\"],\n [\"s33-r1c4\", \"👨🦲\", \"man: bald\", \"adult bro\"],\n [\"s33-r1c5\", \"👩🦰\", \"woman: red hair\", \"adult lady\"],\n [\"s33-r1c6\", \"🧑🦰\", \"person: red hair\", \"adult\"],\n [\"s33-r1c7\", \"👩🦱\", \"woman: curly hair\", \"adult lady\"],\n [\"s33-r2c1\", \"🧑🦱\", \"person: curly hair\", \"adult\"],\n [\"s33-r2c2\", \"👩🦳\", \"woman: white hair\", \"adult lady\"],\n [\"s33-r2c3\", \"🧑🦳\", \"person: white hair\", \"adult\"],\n [\"s33-r2c4\", \"👩🦲\", \"woman: bald\", \"adult lady\"],\n [\"s33-r2c5\", \"🧑🦲\", \"person: bald\", \"adult\"],\n [\"s33-r2c6\", \"👨🌾\", \"man farmer\", \"gardener rancher\"],\n [\"s33-r2c7\", \"👩🌾\", \"woman farmer\", \"gardener rancher\"],\n [\"s33-r3c1\", \"🧑🔧\", \"mechanic\", \"electrician plumber tradesperson\"],\n [\"s33-r3c2\", \"👨🔧\", \"man mechanic\", \"electrician plumber tradesperson\"],\n [\"s33-r3c3\", \"👩🔧\", \"woman mechanic\", \"electrician plumber tradesperson\"],\n [\"s33-r3c4\", \"🧑💼\", \"office worker\", \"architect business manager white-collar\"],\n [\"s33-r3c5\", \"👨💼\", \"man office worker\", \"architect business manager white-collar\"],\n [\"s33-r3c6\", \"👩💼\", \"woman office worker\", \"architect business manager white-collar\"],\n [\"s33-r3c7\", \"👨🔬\", \"man scientist\", \"biologist chemist engineer mathematician physicist\"],\n [\"s33-r4c1\", \"\", \"woman scientist\", \"biologist chemist engineer mathematician physicist\"], // redrawn as s43-r1c6\n [\"s33-r4c2\", \"👨🎤\", \"man singer\", \"actor entertainer rock rockstar star\"],\n [\"s33-r4c3\", \"👩🎤\", \"woman singer\", \"actor entertainer rock rockstar star\"],\n [\"s33-r4c4\", \"👨🎨\", \"man artist\", \"palette\"],\n [\"s33-r4c5\", \"👩🎨\", \"woman artist\", \"palette\"],\n [\"s33-r4c6\", \"\", \"pilot\", \"plane\"], // redrawn as s43-r1c7\n [\"s33-r4c7\", \"👨✈️\", \"man pilot\", \"plane\"],\n [\"s33-r5c1\", \"👩✈️\", \"woman pilot\", \"plane\"],\n [\"s33-r5c2\", \"👨🚀\", \"man astronaut\", \"rocket space\"],\n [\"s33-r5c3\", \"👩🚀\", \"woman astronaut\", \"rocket space\"],\n [\"s33-r5c4\", \"👨🚒\", \"man firefighter\", \"fire firetruck\"],\n [\"s33-r5c5\", \"👩🚒\", \"woman firefighter\", \"fire firetruck\"],\n [\"s33-r5c6\", \"💂\", \"guard\", \"buckingham helmet london palace\"],\n [\"s33-r5c7\", \"💂♂️\", \"man guard\", \"buckingham helmet london palace\"],\n [\"s33-r6c1\", \"💂♀️\", \"woman guard\", \"buckingham helmet london palace\"],\n [\"s33-r6c2\", \"👲\", \"person with skullcap\", \"cap chinese gua guapi hat mao pi\"],\n [\"s33-r6c3\", \"🤶\", \"Mrs. Claus\", \"celebration christmas fairy fantasy holiday merry mother santa\"],\n [\"s33-r6c4\", \"🧝\", \"elf\", \"elves enchantment fantasy folklore magic magical myth\"],\n [\"s33-r6c5\", \"🧝♂️\", \"man elf\", \"elves enchantment fantasy folklore magic magical myth\"],\n [\"s33-r6c6\", \"🧝♀️\", \"woman elf\", \"elves enchantment fantasy folklore magic magical myth\"],\n [\"s33-r6c7\", \"🤽\", \"person playing water polo\", \"sport swimming waterpolo\"],\n [\"s33-r7c1\", \"🤽♂️\", \"man playing water polo\", \"sport swimming waterpolo\"],\n [\"s33-r7c2\", \"🤽♀️\", \"woman playing water polo\", \"sport swimming waterpolo\"],\n [\"s33-r7c3\", \"👨👩👦\", \"family: man, woman, boy\", \"child\"],\n [\"s33-r7c4\", \"👨👩👧\", \"family: man, woman, girl\", \"child\"],\n [\"s33-r7c5\", \"👨👩👧👦\", \"family: man, woman, girl, boy\", \"child\"],\n [\"s33-r7c6\", \"👨👩👧👧\", \"family: man, woman, girl, girl\", \"child\"],\n [\"s33-r7c7\", \"👩👧\", \"family: woman, girl\", \"child\"],\n [\"s34-r1c1\", \"🚻\", \"restroom\", \"bathroom lavatory toilet wc\"],\n [\"s34-r1c2\", \"🚾\", \"water closet\", \"bathroom lavatory restroom toilet wc\"],\n [\"s34-r1c3\", \"🛂\", \"passport control\", \"passport control border travel\"],\n [\"s34-r1c4\", \"🛃\", \"customs\", \"packing\"],\n [\"s34-r1c5\", \"🛄\", \"baggage claim\", \"arrived bags case checked journey packing plane ready\"],\n [\"s34-r1c6\", \"🛅\", \"left luggage\", \"baggage case locker\"],\n [\"s34-r1c7\", \"🚳\", \"no bicycles\", \"bicycle bike forbidden not prohibited\"],\n [\"s34-r2c1\", \"🚯\", \"no littering\", \"forbidden litter not prohibited\"],\n [\"s34-r2c2\", \"🚱\", \"non-potable water\", \"dry non-drinking non-potable prohibited\"],\n [\"s34-r2c3\", \"🚷\", \"no pedestrians\", \"forbidden not pedestrian prohibited\"],\n [\"s34-r2c4\", \"📵\", \"no mobile phones\", \"cell forbidden not phone prohibited telephone\"],\n [\"s34-r2c5\", \"↖️\", \"up-left arrow\", \"direction intercardinal northwest up-left\"],\n [\"s34-r2c6\", \"↕️\", \"up-down arrow\", \"up-down\"],\n [\"s34-r2c7\", \"↩️\", \"right arrow curving left\", \"arrow curve return left back\"],\n [\"s34-r3c1\", \"↪️\", \"left arrow curving right\", \"arrow curve forward right\"],\n [\"s34-r3c2\", \"⚛️\", \"atom symbol\", \"atheist\"],\n [\"s34-r3c3\", \"☸️\", \"wheel of dharma\", \"buddhist religion\"],\n [\"s34-r3c4\", \"☦️\", \"orthodox cross\", \"christian religion\"],\n [\"s34-r3c5\", \"\", \"menorah\", \"candelabrum candlestick hanukkah jewish judaism religion\"], // redrawn as s45-r4c4\n [\"s34-r3c6\", \"🪯\", \"khanda\", \"deg fateh khalsa religion sikh sikhism tegh\"],\n [\"s34-r3c7\", \"⛎\", \"Ophiuchus\", \"bearer serpent snake zodiac\"],\n [\"s34-r4c1\", \"🔀\", \"shuffle tracks button\", \"arrow crossed\"],\n [\"s34-r4c2\", \"🔂\", \"repeat single button\", \"arrow clockwise once\"],\n [\"s34-r4c3\", \"⏭️\", \"next track button\", \"arrow scene triangle\"],\n [\"s34-r4c4\", \"⏮️\", \"last track button\", \"arrow previous scene triangle\"],\n [\"s34-r4c5\", \"⏫\", \"fast up button\", \"arrow double\"],\n [\"s34-r4c6\", \"⏺️\", \"record button\", \"circle\"],\n [\"s34-r4c7\", \"⏏️\", \"eject button\", \"eject button media\"],\n [\"s34-r5c1\", \"📳\", \"vibration mode\", \"cell communication mobile phone telephone\"],\n [\"s34-r5c2\", \"♀️\", \"female sign\", \"woman\"],\n [\"s34-r5c3\", \"♂️\", \"male sign\", \"man\"],\n [\"s34-r5c4\", \"\", \"transgender symbol\", \"transgender symbol trans\"], // redrawn as s54-r2c3\n [\"s34-r5c5\", \"➗\", \"divide\", \"division heavy math sign\"],\n [\"s34-r5c6\", \"🟰\", \"heavy equals sign\", \"answer equal equality math\"],\n [\"s34-r5c7\", \"💱\", \"currency exchange\", \"bank money\"],\n [\"s34-r6c1\", \"⚕️\", \"medical symbol\", \"aesculapius medicine staff\"],\n [\"s34-r6c2\", \"➿\", \"double curly loop\", \"curl\"],\n [\"s34-r6c3\", \"©️\", \"copyright\", \"c\"],\n [\"s34-r6c4\", \"®️\", \"registered\", \"r\"],\n [\"s34-r6c5\", \"™️\", \"trade mark\", \"tm trademark\"],\n [\"s34-r6c6\", \"\", \"splatter\", \"drip holi ink liquid mess paint spill stain\"],\n [\"s34-r6c7\", \"🟠\", \"orange circle\", \"orange circle geometric\"],\n [\"s34-r7c1\", \"🟡\", \"yellow circle\", \"yellow circle geometric\"],\n [\"s34-r7c2\", \"🟢\", \"green circle\", \"green circle geometric\"],\n [\"s34-r7c3\", \"🟣\", \"purple circle\", \"purple circle geometric\"],\n [\"s34-r7c4\", \"🟤\", \"brown circle\", \"brown circle geometric\"],\n [\"s34-r7c5\", \"🟥\", \"red square\", \"card penalty\"],\n [\"s34-r7c6\", \"◻️\", \"white medium square\", \"geometric\"],\n [\"s34-r7c7\", \"🔳\", \"white square button\", \"geometric outlined\"],\n // ── sheet 35: flags ──\n [\"s35-r1c1\", \"🇦🇨\", \"flag: Ascension Island\", \"flag ascension island ac\"],\n [\"s35-r1c2\", \"🇦🇩\", \"flag: Andorra\", \"flag andorra ad\"],\n [\"s35-r1c3\", \"🇦🇫\", \"flag: Afghanistan\", \"flag afghanistan af\"],\n [\"s35-r1c4\", \"🇦🇴\", \"flag: Angola\", \"flag angola ao\"],\n [\"s35-r1c5\", \"🇦🇶\", \"flag: Antarctica\", \"flag antarctica aq\"],\n [\"s35-r1c6\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // redrawn as s55-r1c1\n [\"s35-r1c7\", \"🇧🇧\", \"flag: Barbados\", \"flag barbados bb\"],\n [\"s35-r2c1\", \"🇧🇩\", \"flag: Bangladesh\", \"flag bangladesh bd\"],\n [\"s35-r2c2\", \"🇧🇯\", \"flag: Benin\", \"flag benin bj\"],\n [\"s35-r2c3\", \"🇧🇳\", \"flag: Brunei\", \"flag brunei bn\"],\n [\"s35-r2c4\", \"🇧🇼\", \"flag: Botswana\", \"flag botswana bw\"],\n [\"s35-r2c5\", \"🇧🇾\", \"flag: Belarus\", \"flag belarus by\"],\n [\"s35-r2c6\", \"🇨🇷\", \"flag: Costa Rica\", \"flag costa rica cr\"],\n [\"s35-r2c7\", \"🇨🇿\", \"flag: Czechia\", \"flag czechia cz\"],\n [\"s35-r3c1\", \"🇪🇪\", \"flag: Estonia\", \"flag estonia ee\"],\n [\"s35-r3c2\", \"🇪🇹\", \"flag: Ethiopia\", \"flag ethiopia et\"],\n [\"s35-r3c3\", \"🇬🇳\", \"flag: Guinea\", \"flag guinea gn\"],\n [\"s35-r3c4\", \"🇬🇾\", \"flag: Guyana\", \"flag guyana gy\"],\n [\"s35-r3c5\", \"🇭🇰\", \"flag: Hong Kong SAR China\", \"flag hong kong sar china hk\"],\n [\"s35-r3c6\", \"🇭🇷\", \"flag: Croatia\", \"flag croatia hr\"],\n [\"s35-r3c7\", \"🇮🇷\", \"flag: Iran\", \"flag iran ir\"],\n [\"s35-r4c1\", \"🇮🇸\", \"flag: Iceland\", \"flag iceland is\"],\n [\"s35-r4c2\", \"🇯🇴\", \"flag: Jordan\", \"flag jordan jo\"],\n [\"s35-r4c3\", \"🇰🇪\", \"flag: Kenya\", \"flag kenya ke\"],\n [\"s35-r4c4\", \"🇰🇿\", \"flag: Kazakhstan\", \"flag kazakhstan kz\"],\n [\"s35-r4c5\", \"🇱🇦\", \"flag: Laos\", \"flag laos la\"],\n [\"s35-r4c6\", \"🇱🇺\", \"flag: Luxembourg\", \"flag luxembourg lu\"],\n [\"s35-r4c7\", \"🇱🇻\", \"flag: Latvia\", \"flag latvia lv\"],\n [\"s35-r5c1\", \"🇲🇰\", \"flag: North Macedonia\", \"flag north macedonia mk\"],\n [\"s35-r5c2\", \"🇳🇪\", \"flag: Niger\", \"flag niger ne\"],\n [\"s35-r5c3\", \"🇳🇵\", \"flag: Nepal\", \"flag nepal np\"],\n [\"s35-r5c4\", \"🇳🇿\", \"flag: New Zealand\", \"flag new zealand nz\"],\n [\"s35-r5c5\", \"🇴🇲\", \"flag: Oman\", \"flag oman om\"],\n [\"s35-r5c6\", \"🇷🇴\", \"flag: Romania\", \"flag romania ro\"],\n [\"s35-r5c7\", \"🇷🇸\", \"flag: Serbia\", \"flag serbia rs\"],\n [\"s35-r6c1\", \"🇸🇩\", \"flag: Sudan\", \"flag sudan sd\"],\n [\"s35-r6c2\", \"🇸🇳\", \"flag: Senegal\", \"flag senegal sn\"],\n [\"s35-r6c3\", \"🇸🇴\", \"flag: Somalia\", \"flag somalia so\"],\n [\"s35-r6c4\", \"🇸🇾\", \"flag: Syria\", \"flag syria sy\"],\n [\"s35-r6c5\", \"🇹🇬\", \"flag: Togo\", \"flag togo tg\"],\n [\"s35-r6c6\", \"🇹🇳\", \"flag: Tunisia\", \"flag tunisia tn\"],\n [\"s35-r6c7\", \"🇹🇹\", \"flag: Trinidad & Tobago\", \"flag trinidad tobago tt\"],\n [\"s35-r7c1\", \"🇹🇿\", \"flag: Tanzania\", \"flag tanzania tz\"],\n [\"s35-r7c2\", \"🇺🇬\", \"flag: Uganda\", \"flag uganda ug\"],\n [\"s35-r7c3\", \"🇺🇳\", \"flag: United Nations\", \"flag united nations un\"],\n [\"s35-r7c4\", \"🇻🇮\", \"flag: U.S. Virgin Islands\", \"flag u.s virgin islands vi\"],\n [\"s35-r7c5\", \"🇼🇸\", \"flag: Samoa\", \"flag samoa ws\"],\n [\"s35-r7c6\", \"🇿🇲\", \"flag: Zambia\", \"flag zambia zm\"],\n [\"s35-r7c7\", \"🇿🇼\", \"flag: Zimbabwe\", \"flag zimbabwe zw\"],\n // ── sheet 36: flags ──\n [\"s36-r1c1\", \"🇦🇬\", \"flag: Antigua & Barbuda\", \"flag antigua barbuda ag\"],\n [\"s36-r1c2\", \"🇦🇮\", \"flag: Anguilla\", \"flag anguilla ai\"],\n [\"s36-r1c3\", \"🇦🇸\", \"flag: American Samoa\", \"flag american samoa as\"],\n [\"s36-r1c4\", \"🇦🇼\", \"flag: Aruba\", \"flag aruba aw\"],\n [\"s36-r1c5\", \"🇦🇽\", \"flag: Åland Islands\", \"flag åland aland islands ax\"],\n [\"s36-r1c6\", \"🇧🇫\", \"flag: Burkina Faso\", \"flag burkina faso bf\"],\n [\"s36-r1c7\", \"🇧🇮\", \"flag: Burundi\", \"flag burundi bi\"],\n [\"s36-r2c1\", \"🇧🇲\", \"flag: Bermuda\", \"flag bermuda bm\"],\n [\"s36-r2c2\", \"🇧🇸\", \"flag: Bahamas\", \"flag bahamas bs\"],\n [\"s36-r2c3\", \"🇧🇹\", \"flag: Bhutan\", \"flag bhutan bt\"],\n [\"s36-r2c4\", \"🇧🇻\", \"flag: Bouvet Island\", \"flag bouvet island bv\"],\n [\"s36-r2c5\", \"🇨🇨\", \"flag: Cocos (Keeling) Islands\", \"flag cocos keeling islands cc\"],\n [\"s36-r2c6\", \"🇨🇬\", \"flag: Congo - Brazzaville\", \"-\"],\n [\"s36-r2c7\", \"🇨🇾\", \"flag: Cyprus\", \"flag cyprus cy\"],\n [\"s36-r3c1\", \"🇪🇭\", \"flag: Western Sahara\", \"flag western sahara eh\"],\n [\"s36-r3c2\", \"🇪🇷\", \"flag: Eritrea\", \"flag eritrea er\"],\n [\"s36-r3c3\", \"🇬🇦\", \"flag: Gabon\", \"flag gabon ga\"],\n [\"s36-r3c4\", \"🇬🇱\", \"flag: Greenland\", \"flag greenland gl\"],\n [\"s36-r3c5\", \"🇭🇲\", \"flag: Heard Island & McDonald Islands\", \"flag heard island mcdonald islands hm\"],\n [\"s36-r3c6\", \"🇮🇨\", \"flag: Canary Islands\", \"flag canary islands ic\"],\n [\"s36-r3c7\", \"🇰🇬\", \"flag: Kyrgyzstan\", \"flag kyrgyzstan kg\"],\n [\"s36-r4c1\", \"🇰🇭\", \"flag: Cambodia\", \"flag cambodia kh\"],\n [\"s36-r4c2\", \"🇰🇵\", \"flag: North Korea\", \"flag north korea kp\"],\n [\"s36-r4c3\", \"🇱🇰\", \"flag: Sri Lanka\", \"flag sri lanka lk\"],\n [\"s36-r4c4\", \"🇱🇹\", \"flag: Lithuania\", \"flag lithuania lt\"],\n [\"s36-r4c5\", \"🇲🇪\", \"flag: Montenegro\", \"flag montenegro me\"],\n [\"s36-r4c6\", \"🇲🇫\", \"flag: St. Martin\", \"flag st martin mf\"],\n [\"s36-r4c7\", \"🇲🇱\", \"flag: Mali\", \"flag mali ml\"],\n [\"s36-r5c1\", \"🇲🇲\", \"flag: Myanmar (Burma)\", \"flag myanmar burma mm\"],\n [\"s36-r5c2\", \"🇲🇴\", \"flag: Macao SAR China\", \"flag macao sar china mo\"],\n [\"s36-r5c3\", \"🇲🇷\", \"flag: Mauritania\", \"flag mauritania mr\"],\n [\"s36-r5c4\", \"🇲🇹\", \"flag: Malta\", \"flag malta mt\"],\n [\"s36-r5c5\", \"🇲🇺\", \"flag: Mauritius\", \"flag mauritius mu\"],\n [\"s36-r5c6\", \"🇷🇼\", \"flag: Rwanda\", \"flag rwanda rw\"],\n [\"s36-r5c7\", \"🇸🇮\", \"flag: Slovenia\", \"flag slovenia si\"],\n [\"s36-r6c1\", \"🇸🇰\", \"flag: Slovakia\", \"flag slovakia sk\"],\n [\"s36-r6c2\", \"🇸🇱\", \"flag: Sierra Leone\", \"flag sierra leone sl\"],\n [\"s36-r6c3\", \"🇸🇸\", \"flag: South Sudan\", \"flag south sudan ss\"],\n [\"s36-r6c4\", \"🇹🇩\", \"flag: Chad\", \"flag chad td\"],\n [\"s36-r6c5\", \"🇹🇯\", \"flag: Tajikistan\", \"flag tajikistan tj\"],\n [\"s36-r6c6\", \"🇹🇲\", \"flag: Turkmenistan\", \"flag turkmenistan tm\"], // checked against the real flag 2026-10-01: correct as drawn\n [\"s36-r6c7\", \"🇹🇴\", \"flag: Tonga\", \"flag tonga to\"],\n [\"s36-r7c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // regenerate: only eight yellow stars on the fly; Tuvalu has NINE yellow five-point stars in the island map arrangement\n [\"s36-r7c2\", \"🇺🇿\", \"flag: Uzbekistan\", \"flag uzbekistan uz\"],\n [\"s36-r7c3\", \"🇻🇦\", \"flag: Vatican City\", \"flag vatican city va\"],\n [\"s36-r7c4\", \"🇻🇨\", \"flag: St. Vincent & Grenadines\", \"flag st vincent grenadines vc\"],\n [\"s36-r7c5\", \"🇻🇬\", \"flag: British Virgin Islands\", \"flag british virgin islands vg\"],\n [\"s36-r7c6\", \"🇻🇺\", \"flag: Vanuatu\", \"flag vanuatu vu\"],\n [\"s36-r7c7\", \"🇽🇰\", \"flag: Kosovo\", \"flag kosovo xk\"],\n // ── sheet 37: flags ──\n [\"s37-r1c1\", \"🇧🇱\", \"flag: St. Barthélemy\", \"flag st barthélemy barthelemy bl\"],\n [\"s37-r1c2\", \"🇧🇶\", \"flag: Caribbean Netherlands\", \"flag caribbean netherlands bq\"],\n [\"s37-r1c3\", \"🇧🇿\", \"flag: Belize\", \"flag belize bz\"],\n [\"s37-r1c4\", \"🇨🇫\", \"flag: Central African Republic\", \"flag central african republic cf\"],\n [\"s37-r1c5\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // regenerate: only twelve white stars in the ring (reads as the EU ring); the Cook Islands ring has FIFTEEN white stars\n [\"s37-r1c6\", \"🇨🇻\", \"flag: Cape Verde\", \"flag cape verde cv\"],\n [\"s37-r1c7\", \"🇩🇯\", \"flag: Djibouti\", \"flag djibouti dj\"],\n [\"s37-r2c1\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // redrawn as s56-r1c1\n [\"s37-r2c2\", \"🇫🇯\", \"flag: Fiji\", \"flag fiji fj\"],\n [\"s37-r2c3\", \"🇫🇰\", \"flag: Falkland Islands\", \"flag falkland islands fk\"],\n [\"s37-r2c4\", \"🇫🇲\", \"flag: Micronesia\", \"flag micronesia fm\"],\n [\"s37-r2c5\", \"🇫🇴\", \"flag: Faroe Islands\", \"flag faroe islands fo\"],\n [\"s37-r2c6\", \"🇬🇩\", \"flag: Grenada\", \"flag grenada gd\"],\n [\"s37-r2c7\", \"🇬🇬\", \"flag: Guernsey\", \"flag guernsey gg\"],\n [\"s37-r3c1\", \"🇬🇲\", \"flag: Gambia\", \"flag gambia gm\"],\n [\"s37-r3c2\", \"🇬🇶\", \"flag: Equatorial Guinea\", \"flag equatorial guinea gq\"],\n [\"s37-r3c3\", \"🇬🇺\", \"flag: Guam\", \"flag guam gu\"],\n [\"s37-r3c4\", \"🇬🇼\", \"flag: Guinea-Bissau\", \"guinea-bissau\"],\n [\"s37-r3c5\", \"🇮🇲\", \"flag: Isle of Man\", \"flag isle of man im\"], // checked against the real flag 2026-10-01: correct as drawn\n [\"s37-r3c6\", \"🇮🇴\", \"flag: British Indian Ocean Territory\", \"flag british indian ocean territory io\"],\n [\"s37-r3c7\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // redrawn as s57-r1c1\n [\"s37-r4c1\", \"\", \"flag: Comoros\", \"flag comoros km\"], // regenerate: only three white stars beside the crescent in the green triangle; Comoros has FOUR white stars in a vertical row inside the crescent\n [\"s37-r4c2\", \"🇰🇳\", \"flag: St. Kitts & Nevis\", \"flag st kitts nevis kn\"],\n [\"s37-r4c3\", \"🇱🇨\", \"flag: St. Lucia\", \"flag st lucia lc\"],\n [\"s37-r4c4\", \"🇱🇸\", \"flag: Lesotho\", \"flag lesotho ls\"],\n [\"s37-r4c5\", \"🇲🇩\", \"flag: Moldova\", \"flag moldova md\"],\n [\"s37-r4c6\", \"🇲🇬\", \"flag: Madagascar\", \"flag madagascar mg\"],\n [\"s37-r4c7\", \"🇲🇳\", \"flag: Mongolia\", \"flag mongolia mn\"],\n [\"s37-r5c1\", \"🇲🇻\", \"flag: Maldives\", \"flag maldives mv\"],\n [\"s37-r5c2\", \"🇲🇿\", \"flag: Mozambique\", \"flag mozambique mz\"],\n [\"s37-r5c3\", \"🇳🇦\", \"flag: Namibia\", \"flag namibia na\"],\n [\"s37-r5c4\", \"🇳🇫\", \"flag: Norfolk Island\", \"flag norfolk island nf\"],\n [\"s37-r5c5\", \"🇵🇬\", \"flag: Papua New Guinea\", \"flag papua new guinea pg\"],\n [\"s37-r5c6\", \"🇷🇪\", \"flag: Réunion\", \"flag réunion reunion re\"],\n [\"s37-r5c7\", \"🇸🇧\", \"flag: Solomon Islands\", \"flag solomon islands sb\"],\n [\"s37-r6c1\", \"🇸🇨\", \"flag: Seychelles\", \"flag seychelles sc\"],\n [\"s37-r6c2\", \"🇸🇯\", \"flag: Svalbard & Jan Mayen\", \"flag svalbard jan mayen sj\"],\n [\"s37-r6c3\", \"🇸🇲\", \"flag: San Marino\", \"flag san marino sm\"],\n [\"s37-r6c4\", \"🇸🇷\", \"flag: Suriname\", \"flag suriname sr\"],\n [\"s37-r6c5\", \"🇸🇹\", \"flag: São Tomé & Príncipe\", \"flag são sao tomé tome príncipe principe st\"],\n [\"s37-r6c6\", \"🇸🇽\", \"flag: Sint Maarten\", \"flag sint maarten sx\"],\n [\"s37-r6c7\", \"🇸🇿\", \"flag: Eswatini\", \"flag eswatini sz\"],\n [\"s37-r7c1\", \"🇹🇦\", \"flag: Tristan da Cunha\", \"flag tristan da cunha ta\"],\n [\"s37-r7c2\", \"🇹🇨\", \"flag: Turks & Caicos Islands\", \"flag turks caicos islands tc\"],\n [\"s37-r7c3\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // redrawn as s58-r1c1\n [\"s37-r7c4\", \"🇹🇰\", \"flag: Tokelau\", \"flag tokelau tk\"],\n [\"s37-r7c5\", \"🇹🇱\", \"flag: Timor-Leste\", \"timor-leste\"],\n [\"s37-r7c6\", \"🇼🇫\", \"flag: Wallis & Futuna\", \"flag wallis futuna wf\"],\n [\"s37-r7c7\", \"🇾🇹\", \"flag: Mayotte\", \"flag mayotte yt\"],\n // ── sheet 38: people ──\n [\"s38-r1c1\", \"🧑⚖️\", \"judge\", \"justice law scales\"],\n [\"s38-r1c2\", \"👨⚖️\", \"man judge\", \"justice law scales\"],\n [\"s38-r1c3\", \"👩⚖️\", \"woman judge\", \"justice law scales\"],\n [\"s38-r1c4\", \"🧑🏭\", \"factory worker\", \"assembly industrial\"],\n [\"s38-r1c5\", \"👨🏭\", \"man factory worker\", \"assembly industrial\"],\n [\"s38-r1c6\", \"👩🏭\", \"woman factory worker\", \"assembly industrial\"],\n [\"s38-r1c7\", \"🫅\", \"person with crown\", \"monarch noble regal royal royalty\"],\n [\"s38-r2c1\", \"🫃\", \"pregnant man\", \"belly bloated full overeat\"],\n [\"s38-r2c2\", \"🫄\", \"pregnant person\", \"belly bloated full overeat stuffed\"],\n [\"s38-r2c3\", \"👩🍼\", \"woman feeding baby\", \"feed mom mother nanny newborn nursing\"],\n [\"s38-r2c4\", \"👨🍼\", \"man feeding baby\", \"dad father feed nanny newborn nursing\"],\n [\"s38-r2c5\", \"🧑🍼\", \"person feeding baby\", \"feed nanny newborn nursing parent\"],\n [\"s38-r2c6\", \"🧑🎄\", \"Mx Claus\", \"celebration christmas fairy fantasy holiday merry santa tale\"],\n [\"s38-r2c7\", \"🧌\", \"troll\", \"fairy fantasy monster tale trolling\"],\n [\"s38-r3c1\", \"\", \"hairy creature\", \"bigfoot cryptid forest giant sasquatch woodwose yeti\"],\n [\"s38-r3c2\", \"🧍\", \"person standing\", \"stand\"],\n [\"s38-r3c3\", \"🧍♂️\", \"man standing\", \"stand\"],\n [\"s38-r3c4\", \"🧍♀️\", \"woman standing\", \"stand\"],\n [\"s38-r3c5\", \"🧎♂️\", \"man kneeling\", \"kneel knees\"],\n [\"s38-r3c6\", \"🧎♀️\", \"woman kneeling\", \"kneel knees\"],\n [\"s38-r3c7\", \"🧎➡️\", \"person kneeling facing right\", \"kneel knees\"],\n [\"s38-r4c1\", \"🧎♀️➡️\", \"woman kneeling facing right\", \"kneel knees\"],\n [\"s38-r4c2\", \"🧎♂️➡️\", \"man kneeling facing right\", \"kneel knees\"],\n [\"s38-r4c3\", \"🧑🦯\", \"person with white cane\", \"accessibility blind probing\"],\n [\"s38-r4c4\", \"🧑🦯➡️\", \"person with white cane facing right\", \"accessibility blind probing\"],\n [\"s38-r4c5\", \"👨🦯\", \"man with white cane\", \"accessibility blind probing\"],\n [\"s38-r4c6\", \"👨🦯➡️\", \"man with white cane facing right\", \"accessibility blind probing\"],\n [\"s38-r4c7\", \"\", \"woman with white cane\", \"accessibility blind probing\"], // redrawn as s43-r2c1\n [\"s38-r5c1\", \"👩🦯➡️\", \"woman with white cane facing right\", \"accessibility blind probing\"],\n [\"s38-r5c2\", \"👨👩👦👦\", \"family: man, woman, boy, boy\", \"child\"],\n [\"s38-r5c3\", \"👨👨👦\", \"family: man, man, boy\", \"child\"],\n [\"s38-r5c4\", \"👨👨👧\", \"family: man, man, girl\", \"child\"],\n [\"s38-r5c5\", \"👨👨👧👦\", \"family: man, man, girl, boy\", \"child\"],\n [\"s38-r5c6\", \"👨👨👦👦\", \"family: man, man, boy, boy\", \"child\"],\n [\"s38-r5c7\", \"👨👨👧👧\", \"family: man, man, girl, girl\", \"child\"],\n [\"s38-r6c1\", \"👩👩👦\", \"family: woman, woman, boy\", \"child\"],\n [\"s38-r6c2\", \"👩👩👧\", \"family: woman, woman, girl\", \"child\"],\n [\"s38-r6c3\", \"👩👩👧👦\", \"family: woman, woman, girl, boy\", \"child\"],\n [\"s38-r6c4\", \"👩👩👦👦\", \"family: woman, woman, boy, boy\", \"child\"],\n [\"s38-r6c5\", \"👩👩👧👧\", \"family: woman, woman, girl, girl\", \"child\"],\n [\"s38-r6c6\", \"👨👦\", \"family: man, boy\", \"child\"],\n [\"s38-r6c7\", \"👨👦👦\", \"family: man, boy, boy\", \"child\"],\n [\"s38-r7c1\", \"👨👧\", \"family: man, girl\", \"child\"],\n [\"s38-r7c2\", \"👨👧👦\", \"family: man, girl, boy\", \"child\"],\n [\"s38-r7c3\", \"👨👧👧\", \"family: man, girl, girl\", \"child\"],\n [\"s38-r7c4\", \"👩👦\", \"family: woman, boy\", \"child\"],\n [\"s38-r7c5\", \"👩👦👦\", \"family: woman, boy, boy\", \"child\"],\n [\"s38-r7c6\", \"👩👧👦\", \"family: woman, girl, boy\", \"child\"],\n [\"s38-r7c7\", \"👩👧👧\", \"family: woman, girl, girl\", \"child\"],\n // ── sheet 39: animals and plants ──\n [\"s39-r1c1\", \"🦧\", \"orangutan\", \"animal ape monkey\"],\n [\"s39-r1c2\", \"🦮\", \"guide dog\", \"accessibility animal blind\"],\n [\"s39-r1c3\", \"🐕🦺\", \"service dog\", \"accessibility animal assistance\"],\n [\"s39-r1c4\", \"🐈⬛\", \"black cat\", \"animal feline halloween meow unlucky\"],\n [\"s39-r1c5\", \"🫎\", \"moose\", \"alces animal antlers elk mammal\"],\n [\"s39-r1c6\", \"🫏\", \"donkey\", \"animal ass burro hinny mammal mule stubborn\"],\n [\"s39-r1c7\", \"🦓\", \"zebra\", \"animal stripe\"],\n [\"s39-r2c1\", \"🦬\", \"bison\", \"animal buffalo herd wisent\"],\n [\"s39-r2c2\", \"🐗\", \"boar\", \"animal pig\"],\n [\"s39-r2c3\", \"🐫\", \"two-hump camel\", \"animal bactrian desert two-hump\"],\n [\"s39-r2c4\", \"🦒\", \"giraffe\", \"animal spots\"],\n [\"s39-r2c5\", \"🦣\", \"mammoth\", \"animal extinction large tusk wooly\"],\n [\"s39-r2c6\", \"🦏\", \"rhinoceros\", \"animal\"],\n [\"s39-r2c7\", \"🦛\", \"hippopotamus\", \"animal hippo\"],\n [\"s39-r3c1\", \"🦫\", \"beaver\", \"animal dam teeth\"],\n [\"s39-r3c2\", \"🦔\", \"hedgehog\", \"animal spiny\"],\n [\"s39-r3c3\", \"🐻❄️\", \"polar bear\", \"animal arctic white\"],\n [\"s39-r3c4\", \"🦥\", \"sloth\", \"lazy slow\"],\n [\"s39-r3c5\", \"🦦\", \"otter\", \"animal fishing playful\"],\n [\"s39-r3c6\", \"🦨\", \"skunk\", \"animal stink\"],\n [\"s39-r3c7\", \"🦡\", \"badger\", \"animal honey pester\"],\n [\"s39-r4c1\", \"🦢\", \"swan\", \"animal bird cygnet duckling ornithology ugly\"],\n [\"s39-r4c2\", \"🦤\", \"dodo\", \"animal bird extinction large ornithology\"],\n [\"s39-r4c3\", \"🪶\", \"feather\", \"bird flight light plumage\"],\n [\"s39-r4c4\", \"🦩\", \"flamingo\", \"animal bird flamboyant ornithology tropical\"],\n [\"s39-r4c5\", \"🪽\", \"wing\", \"angelic ascend aviation bird fly flying heavenly mythology\"],\n [\"s39-r4c6\", \"🐦⬛\", \"black bird\", \"animal beak caw corvid crow ornithology raven rook\"],\n [\"s39-r4c7\", \"🪿\", \"goose\", \"animal bird duck flock fowl gaggle gander geese\"],\n [\"s39-r5c1\", \"🐦🔥\", \"phoenix\", \"ascend ascension emerge fantasy firebird glory immortal rebirth\"],\n [\"s39-r5c2\", \"🐋\", \"whale\", \"animal beach ocean\"],\n [\"s39-r5c3\", \"\", \"orca\", \"marine ocean whale\"],\n [\"s39-r5c4\", \"🦭\", \"seal\", \"animal lion ocean sea\"],\n [\"s39-r5c5\", \"🐡\", \"blowfish\", \"animal fish\"],\n [\"s39-r5c6\", \"🪸\", \"coral\", \"change climate ocean reef sea\"],\n [\"s39-r5c7\", \"🪼\", \"jellyfish\", \"animal aquarium burn invertebrate jelly life marine ocean\"],\n [\"s39-r6c1\", \"🦪\", \"oyster\", \"diving pearl\"],\n [\"s39-r6c2\", \"🪲\", \"beetle\", \"animal bug insect\"],\n [\"s39-r6c3\", \"🪳\", \"cockroach\", \"animal insect pest roach\"],\n [\"s39-r6c4\", \"🕸️\", \"spider web\", \"cobweb spider halloween spooky silk\"],\n [\"s39-r6c5\", \"🦂\", \"scorpion\", \"scorpio scorpius zodiac\"],\n [\"s39-r6c6\", \"🪰\", \"fly\", \"animal disease insect maggot pest rotting\"],\n [\"s39-r6c7\", \"🪱\", \"worm\", \"animal annelid earthworm parasite\"],\n [\"s39-r7c1\", \"💮\", \"white flower\", \"flower blossom stamp well done japanese\"],\n [\"s39-r7c2\", \"🪷\", \"lotus\", \"beauty buddhism calm flower hinduism peace purity serenity\"],\n [\"s39-r7c3\", \"🪻\", \"hyacinth\", \"bloom bluebonnet flower indigo lavender lilac lupine plant\"],\n [\"s39-r7c4\", \"🌲\", \"evergreen tree\", \"christmas forest pine\"],\n [\"s39-r7c5\", \"🪹\", \"empty nest\", \"branch home nesting\"],\n [\"s39-r7c6\", \"🪺\", \"nest with eggs\", \"bird branch egg nesting\"],\n [\"s39-r7c7\", \"\", \"leafless tree\", \"bare barren branches dead drought trunk winter wood\"],\n // ── sheet 40: objects ──\n [\"s40-r1c1\", \"🥼\", \"lab coat\", \"clothes doctor dr experiment jacket scientist white\"],\n [\"s40-r1c2\", \"🦺\", \"safety vest\", \"emergency\"],\n [\"s40-r1c3\", \"🥻\", \"sari\", \"clothing dress\"],\n [\"s40-r1c4\", \"🩱\", \"one-piece swimsuit\", \"bathing one-piece suit\"],\n [\"s40-r1c5\", \"🩲\", \"briefs\", \"bathing one-piece suit swimsuit underwear\"],\n [\"s40-r1c6\", \"🩳\", \"shorts\", \"bathing pants suit swimsuit underwear\"],\n [\"s40-r1c7\", \"🪭\", \"folding hand fan\", \"clack clap cool cooling dance flirt flutter hot\"],\n [\"s40-r2c1\", \"👝\", \"clutch bag\", \"clothes clothing dress handbag pouch purse\"],\n [\"s40-r2c2\", \"🩴\", \"thong sandal\", \"beach flip flop sandals shoe thongs zōri\"],\n [\"s40-r2c3\", \"🥿\", \"flat shoe\", \"ballet comfy flats slip-on slipper\"],\n [\"s40-r2c4\", \"🩰\", \"ballet shoes\", \"dance\"],\n [\"s40-r2c5\", \"🪮\", \"hair pick\", \"afro comb groom\"],\n [\"s40-r2c6\", \"🪖\", \"military helmet\", \"army soldier war warrior\"],\n [\"s40-r2c7\", \"🎛️\", \"control knobs\", \"music\"],\n [\"s40-r3c1\", \"\", \"trombone\", \"brass instrument jazz music sad slide\"],\n [\"s40-r3c2\", \"🪗\", \"accordion\", \"box concertina instrument music squeeze squeezebox\"],\n [\"s40-r3c3\", \"🪕\", \"banjo\", \"music stringed\"],\n [\"s40-r3c4\", \"🪘\", \"long drum\", \"beat conga instrument rhythm\"],\n [\"s40-r3c5\", \"🪇\", \"maracas\", \"cha dance instrument music party percussion rattle shake\"],\n [\"s40-r3c6\", \"🪈\", \"flute\", \"band fife flautist instrument marching music orchestra piccolo\"],\n [\"s40-r3c7\", \"\", \"harp\", \"cupid instrument love music orchestra\"],\n [\"s40-r4c1\", \"📟\", \"pager\", \"communication\"],\n [\"s40-r4c2\", \"🖲️\", \"trackball\", \"computer\"],\n [\"s40-r4c3\", \"🪔\", \"diya lamp\", \"light oil\"],\n [\"s40-r4c4\", \"🪙\", \"coin\", \"dollar euro gold metal money rich silver treasure\"],\n [\"s40-r4c5\", \"\", \"treasure chest\", \"gem gold jewels loot money prize silver valuables\"],\n [\"s40-r4c6\", \"📫\", \"closed mailbox with raised flag\", \"communication mail postbox\"],\n [\"s40-r4c7\", \"📪\", \"closed mailbox with lowered flag\", \"mail postbox\"],\n [\"s40-r5c1\", \"📭\", \"open mailbox with lowered flag\", \"mail postbox\"],\n [\"s40-r5c2\", \"🗂️\", \"card index dividers\", \"card dividers file folder index organize tabs\"],\n [\"s40-r5c3\", \"📇\", \"card index\", \"old rolodex school\"],\n [\"s40-r5c4\", \"🗃️\", \"card file box\", \"box card file archive cabinet index\"],\n [\"s40-r5c5\", \"🔏\", \"locked with pen\", \"ink lock nib privacy\"],\n [\"s40-r5c6\", \"🪓\", \"axe\", \"ax chop hatchet split wood\"],\n [\"s40-r5c7\", \"🪃\", \"boomerang\", \"rebound repercussion weapon\"],\n [\"s40-r6c1\", \"🗜️\", \"clamp\", \"compress tool vice\"],\n [\"s40-r6c2\", \"🦯\", \"white cane\", \"accessibility blind probing\"],\n [\"s40-r6c3\", \"🪝\", \"hook\", \"catch crook curve ensnare point selling\"],\n [\"s40-r6c4\", \"🪜\", \"ladder\", \"climb rung step\"],\n [\"s40-r6c5\", \"\", \"shovel\", \"bury dig garden hole plant scoop snow spade\"],\n [\"s40-r6c6\", \"⚗️\", \"alembic\", \"chemistry tool\"],\n [\"s40-r6c7\", \"🩸\", \"drop of blood\", \"bleed donation injury medicine menstruation\"],\n [\"s40-r7c1\", \"🩹\", \"adhesive bandage\", \"bandage first aid hurt injury plaster\"],\n [\"s40-r7c2\", \"🩼\", \"crutch\", \"aid cane disability help hurt injured mobility stick\"],\n [\"s40-r7c3\", \"🩺\", \"stethoscope\", \"doctor heart medicine\"],\n [\"s40-r7c4\", \"🩻\", \"x-ray\", \"bones doctor medical skeleton skull x-ray xray\"],\n [\"s40-r7c5\", \"🛗\", \"elevator\", \"accessibility hoist lift\"],\n [\"s40-r7c6\", \"🧷\", \"safety pin\", \"diaper punk rock\"],\n [\"s40-r7c7\", \"⚱️\", \"funeral urn\", \"ashes death\"],\n // ── sheet 41: extras: rare flags, symbols, objects and places ──\n [\"s41-r1c1\", \"🛺\", \"auto rickshaw\", \"tuk\", \"travel\"],\n [\"s41-r1c2\", \"🛞\", \"wheel\", \"car circle tire turn vehicle\", \"travel\"],\n [\"s41-r1c3\", \"🛟\", \"ring buoy\", \"float life lifesaver preserver rescue safety save saver\", \"travel\"],\n [\"s41-r1c4\", \"🪂\", \"parachute\", \"hang-glide parasail skydive\", \"travel\"],\n [\"s41-r1c5\", \"⏱️\", \"stopwatch\", \"clock time\", \"travel\"],\n [\"s41-r1c6\", \"⏲️\", \"timer clock\", \"timer clock kitchen countdown time\", \"travel\"],\n [\"s41-r1c7\", \"🪠\", \"plunger\", \"cup force plumber poop suction toilet\", \"objects\"],\n [\"s41-r2c1\", \"🪤\", \"mouse trap\", \"bait cheese lure mousetrap snare\", \"objects\"],\n [\"s41-r2c2\", \"🪒\", \"razor\", \"sharp shave\", \"objects\"],\n [\"s41-r2c3\", \"🫧\", \"bubbles\", \"bubble burp clean floating pearl soap underwater\", \"objects\"],\n [\"s41-r2c4\", \"🪥\", \"toothbrush\", \"bathroom brush clean dental hygiene teeth toiletry\", \"objects\"],\n [\"s41-r2c5\", \"🪦\", \"headstone\", \"cemetery dead grave graveyard memorial rip tomb tombstone\", \"objects\"],\n [\"s41-r2c6\", \"🪬\", \"hamsa\", \"amulet fatima fortune guide hand mary miriam palm\", \"objects\"],\n [\"s41-r2c7\", \"🪧\", \"placard\", \"card demonstration notice picket plaque protest sign\", \"objects\"],\n [\"s41-r3c1\", \"🪪\", \"identification card\", \"credentials document id license security\", \"objects\"],\n [\"s41-r3c2\", \"🔣\", \"input symbols\", \"input symbols ampersand percent music note\", \"symbols\"],\n [\"s41-r3c3\", \"🈁\", \"Japanese “here” button\", \"katakana\", \"symbols\"],\n [\"s41-r3c4\", \"🈂️\", \"Japanese “service charge” button\", \"katakana\", \"symbols\"],\n [\"s41-r3c5\", \"🟧\", \"orange square\", \"orange square shape colour color\", \"symbols\"],\n [\"s41-r3c6\", \"🟨\", \"yellow square\", \"card penalty\", \"symbols\"],\n [\"s41-r3c7\", \"🟩\", \"green square\", \"green square shape colour color\", \"symbols\"],\n [\"s41-r4c1\", \"🟦\", \"blue square\", \"blue square shape colour color\", \"symbols\"],\n [\"s41-r4c2\", \"🟪\", \"purple square\", \"purple square shape colour color\", \"symbols\"],\n [\"s41-r4c3\", \"🟫\", \"brown square\", \"brown square shape colour color\", \"symbols\"],\n [\"s41-r4c4\", \"🏳️⚧️\", \"transgender flag\", \"blue light pink white\", \"flags\"],\n [\"s41-r4c5\", \"🇨🇶\", \"flag: Sark\", \"flag sark cq\", \"flags\"],\n [\"s41-r4c6\", \"🇨🇼\", \"flag: Curaçao\", \"flag curaçao curacao cw\", \"flags\"],\n [\"s41-r4c7\", \"🇨🇽\", \"flag: Christmas Island\", \"flag christmas island cx\", \"flags\"],\n [\"s41-r5c1\", \"🇩🇬\", \"flag: Diego Garcia\", \"flag diego garcia dg\", \"flags\"],\n [\"s41-r5c2\", \"🇬🇫\", \"flag: French Guiana\", \"flag french guiana gf\", \"flags\"],\n [\"s41-r5c3\", \"🇬🇮\", \"flag: Gibraltar\", \"flag gibraltar gi\", \"flags\"],\n [\"s41-r5c4\", \"🇬🇵\", \"flag: Guadeloupe\", \"flag guadeloupe gp\", \"flags\"],\n [\"s41-r5c5\", \"🇬🇸\", \"flag: South Georgia & South Sandwich Islands\", \"flag south georgia sandwich islands gs\", \"flags\"],\n [\"s41-r5c6\", \"🇯🇪\", \"flag: Jersey\", \"flag jersey je\", \"flags\"],\n [\"s41-r5c7\", \"🇰🇾\", \"flag: Cayman Islands\", \"flag cayman islands ky\", \"flags\"],\n [\"s41-r6c1\", \"🇱🇮\", \"flag: Liechtenstein\", \"flag liechtenstein li\", \"flags\"],\n [\"s41-r6c2\", \"🇲🇭\", \"flag: Marshall Islands\", \"flag marshall islands mh\", \"flags\"],\n [\"s41-r6c3\", \"🇲🇵\", \"flag: Northern Mariana Islands\", \"flag northern mariana islands mp\", \"flags\"],\n [\"s41-r6c4\", \"🇲🇶\", \"flag: Martinique\", \"flag martinique mq\", \"flags\"],\n [\"s41-r6c5\", \"🇲🇸\", \"flag: Montserrat\", \"flag montserrat ms\", \"flags\"],\n [\"s41-r6c6\", \"🇲🇼\", \"flag: Malawi\", \"flag malawi mw\", \"flags\"],\n [\"s41-r6c7\", \"🇳🇨\", \"flag: New Caledonia\", \"flag new caledonia nc\", \"flags\"],\n [\"s41-r7c1\", \"🇳🇷\", \"flag: Nauru\", \"flag nauru nr\", \"flags\"],\n [\"s41-r7c2\", \"\", \"flag: Niue\", \"flag niue nu\", \"flags\"], // redrawn as s51-r1c1\n [\"s41-r7c3\", \"🇵🇫\", \"flag: French Polynesia\", \"flag french polynesia pf\", \"flags\"],\n [\"s41-r7c4\", \"🇵🇲\", \"flag: St. Pierre & Miquelon\", \"flag st pierre miquelon pm\", \"flags\"],\n [\"s41-r7c5\", \"🇵🇳\", \"flag: Pitcairn Islands\", \"flag pitcairn islands pn\", \"flags\"],\n [\"s41-r7c6\", \"🇵🇼\", \"flag: Palau\", \"flag palau pw\", \"flags\"],\n [\"s41-r7c7\", \"🇸🇭\", \"flag: St. Helena, Ascension & Tristan da Cunha\", \"flag st helena ascension tristan da cunha sh\", \"flags\"],\n // ── sheet 42: extras: rare people, weather and activities, and emoji 18.0 ──\n [\"s42-r1c1\", \"\", \"cracking face\", \"broken cracked crumbling face stress strained\", \"smileys\"],\n [\"s42-r1c2\", \"\", \"leftwards thumb sign\", \"hand left point that way thumb\", \"hands\"],\n [\"s42-r1c3\", \"\", \"rightwards thumb sign\", \"hand point right that way thumb\", \"hands\"],\n [\"s42-r1c4\", \"🧑🦼\", \"person in motorized wheelchair\", \"accessibility\", \"people\"],\n [\"s42-r1c5\", \"🧑🦼➡️\", \"person in motorized wheelchair facing right\", \"accessibility\", \"people\"],\n [\"s42-r1c6\", \"👨🦼\", \"man in motorized wheelchair\", \"accessibility\", \"people\"],\n [\"s42-r1c7\", \"👨🦼➡️\", \"man in motorized wheelchair facing right\", \"accessibility\", \"people\"],\n [\"s42-r2c1\", \"👩🦼\", \"woman in motorized wheelchair\", \"accessibility\", \"people\"],\n [\"s42-r2c2\", \"👩🦼➡️\", \"woman in motorized wheelchair facing right\", \"accessibility\", \"people\"],\n [\"s42-r2c3\", \"🧑🦽\", \"person in manual wheelchair\", \"accessibility\", \"people\"],\n [\"s42-r2c4\", \"🧑🦽➡️\", \"person in manual wheelchair facing right\", \"accessibility\", \"people\"],\n [\"s42-r2c5\", \"👨🦽\", \"man in manual wheelchair\", \"accessibility\", \"people\"],\n [\"s42-r2c6\", \"👨🦽➡️\", \"man in manual wheelchair facing right\", \"accessibility\", \"people\"],\n [\"s42-r2c7\", \"👩🦽\", \"woman in manual wheelchair\", \"accessibility\", \"people\"],\n [\"s42-r3c1\", \"👩🦽➡️\", \"woman in manual wheelchair facing right\", \"accessibility\", \"people\"],\n [\"s42-r3c2\", \"🧑🩰\", \"ballet dancer\", \"ballet dance dancer pointe tiptoe\", \"people\"],\n [\"s42-r3c3\", \"🧑🤝🧑\", \"people holding hands\", \"bae bestie bff couple dating flirt friends hand\", \"people\"],\n [\"s42-r3c4\", \"🫂\", \"people hugging\", \"comfort embrace farewell friendship goodbye hello hug love\", \"people\"],\n [\"s42-r3c5\", \"🧑🧑🧒\", \"family: adult, adult, child\", \"child family parents people\", \"people\"],\n [\"s42-r3c6\", \"🧑🧑🧒🧒\", \"family: adult, adult, child, child\", \"children family parents people\", \"people\"],\n [\"s42-r3c7\", \"🧑🧒\", \"family: adult, child\", \"child family parent people\", \"people\"],\n [\"s42-r4c1\", \"🧑🧒🧒\", \"family: adult, child, child\", \"children family parent people\", \"people\"],\n [\"s42-r4c2\", \"\", \"fingerprint\", \"clue crime detective forensics identity mystery print safety\", \"people\"],\n [\"s42-r4c3\", \"\", \"monarch butterfly\", \"butterfly insect migration monarch orange\", \"nature\"],\n [\"s42-r4c4\", \"\", \"pickle\", \"cucumber dill gherkin pickle sour\", \"food\"],\n [\"s42-r4c5\", \"\", \"lighthouse\", \"beacon coast light lighthouse sea\", \"travel\"],\n [\"s42-r4c6\", \"🕰️\", \"mantelpiece clock\", \"time\", \"travel\"],\n [\"s42-r4c7\", \"🌗\", \"last quarter moon\", \"space\", \"travel\"],\n [\"s42-r5c1\", \"🪐\", \"ringed planet\", \"saturn saturnine\", \"travel\"],\n [\"s42-r5c2\", \"🌥️\", \"sun behind large cloud\", \"weather\", \"travel\"],\n [\"s42-r5c3\", \"🌦️\", \"sun behind rain cloud\", \"weather\", \"travel\"],\n [\"s42-r5c4\", \"🌫️\", \"fog\", \"cloud weather\", \"travel\"],\n [\"s42-r5c5\", \"\", \"meteor\", \"fireball meteor shooting space star\", \"travel\"],\n [\"s42-r5c6\", \"🪅\", \"piñata\", \"candy celebrate celebration cinco de festive mayo party\", \"activities\"],\n [\"s42-r5c7\", \"🪩\", \"mirror ball\", \"dance disco glitter party\", \"activities\"],\n [\"s42-r6c1\", \"🪆\", \"nesting dolls\", \"babooshka baboushka babushka doll matryoshka russia\", \"activities\"],\n [\"s42-r6c2\", \"🪡\", \"sewing needle\", \"embroidery sew stitches sutures tailoring thread\", \"activities\"],\n [\"s42-r6c3\", \"🪢\", \"knot\", \"cord rope tangled tie twine twist\", \"activities\"],\n [\"s42-r6c4\", \"\", \"eraser\", \"eraser mistake rubber school undo\", \"objects\"],\n [\"s42-r6c5\", \"\", \"net with handle\", \"bug butterfly catch insect net\", \"objects\"],\n [\"s42-r6c6\", \"\", \"cracking face\", \"broken cracked crumbling face stress strained\", \"smileys\"], // duplicate of s42-r1c1\n [\"s42-r6c7\", \"\", \"leftwards thumb sign\", \"hand left point that way thumb\", \"hands\"], // duplicate of s42-r1c2\n [\"s42-r7c1\", \"\", \"rightwards thumb sign\", \"hand point right that way thumb\", \"hands\"], // duplicate of s42-r1c3\n [\"s42-r7c2\", \"\", \"monarch butterfly\", \"butterfly insect migration monarch orange\", \"nature\"], // duplicate of s42-r4c3\n [\"s42-r7c3\", \"\", \"pickle\", \"cucumber dill gherkin pickle sour\", \"food\"], // duplicate of s42-r4c4\n [\"s42-r7c4\", \"\", \"lighthouse\", \"beacon coast light lighthouse sea\", \"travel\"], // duplicate of s42-r4c5\n [\"s42-r7c5\", \"\", \"meteor\", \"fireball meteor shooting space star\", \"travel\"], // duplicate of s42-r5c5\n [\"s42-r7c6\", \"\", \"eraser\", \"eraser mistake rubber school undo\", \"objects\"], // duplicate of s42-r6c4\n [\"s42-r7c7\", \"\", \"net with handle\", \"bug butterfly catch insect net\", \"objects\"], // duplicate of s42-r6c5\n // ── sheet 43: redraws ──\n [\"s43-r1c1\", \"👯\", \"people with bunny ears\", \"bestie bff counterpart dancer double ear identical pair\", \"people\"],\n [\"s43-r1c2\", \"🏋️♀️\", \"woman lifting weights\", \"barbell bodybuilder deadlift lifter powerlifting weight weightlifter workout\", \"people\"],\n [\"s43-r1c3\", \"👰\", \"person with veil\", \"wedding\", \"people\"],\n [\"s43-r1c4\", \"🏊♂️\", \"man swimming\", \"freestyle sport swim swimmer triathlon\", \"people\"],\n [\"s43-r1c5\", \"🙋♂️\", \"man raising hand\", \"gesture here know me pick question raise\", \"hands\"],\n [\"s43-r1c6\", \"👩🔬\", \"woman scientist\", \"biologist chemist engineer mathematician physicist\", \"people\"],\n [\"s43-r1c7\", \"🧑✈️\", \"pilot\", \"plane\", \"people\"],\n [\"s43-r2c1\", \"👩🦯\", \"woman with white cane\", \"accessibility blind probing\", \"people\"],\n [\"s43-r2c2\", \"🔎\", \"magnifying glass tilted right\", \"contact lab right-pointing science search tool\", \"objects\"],\n [\"s43-r2c3\", \"〰️\", \"wavy dash\", \"punctuation\", \"symbols\"],\n [\"s43-r2c4\", \"⛺\", \"tent\", \"camping\", \"travel\"],\n [\"s43-r2c5\", \"🏉\", \"rugby football\", \"ball sport\", \"activities\"],\n [\"s43-r2c6\", \"\", \"menorah\", \"candelabrum candlestick hanukkah jewish judaism religion\", \"symbols\"], // off-list: ChatGPT drew an hourglass in a wooden frame, not used\n [\"s43-r2c7\", \"\", \"shooting star\", \"falling night space\", \"travel\"], // off-list: ChatGPT drew a gold pocket compass, not used\n [\"s43-r3c1\", \"\", \"milky way\", \"space\", \"travel\"], // off-list: ChatGPT drew gold balance scales, not used\n [\"s43-r3c2\", \"\", \"comet\", \"space\", \"travel\"], // off-list: ChatGPT drew a gold trophy cup, not used\n [\"s43-r3c3\", \"\", \"fireworks\", \"boom celebration entertainment yolo\", \"activities\"], // off-list: ChatGPT drew a graduation cap, not used\n [\"s43-r3c4\", \"\", \"sparkler\", \"boom celebration fireworks sparkle\", \"activities\"], // off-list: ChatGPT drew an open blue umbrella, not used\n [\"s43-r3c5\", \"\", \"moon viewing ceremony\", \"celebration\", \"activities\"], // off-list: ChatGPT drew a red toadstool with white spots, not used\n [\"s43-r3c6\", \"\", \"oncoming police car\", \"police car cop oncoming siren\", \"travel\"], // off-list: ChatGPT drew an erupting volcano, not used\n [\"s43-r3c7\", \"\", \"oncoming automobile\", \"car cars drove vehicle\", \"travel\"], // off-list: ChatGPT drew a saguaro cactus, not used\n [\"s43-r4c1\", \"\", \"motorway\", \"highway road\", \"travel\"], // off-list: ChatGPT drew a four-leaf clover, not used\n [\"s43-r4c2\", \"\", \"airplane departure\", \"aeroplane check-in departures plane\", \"travel\"], // off-list: ChatGPT drew a red rose, not used\n [\"s43-r4c3\", \"\", \"twelve-thirty\", \"12 30 clock time twelve-thirty\", \"travel\"], // off-list: ChatGPT drew a sunflower, not used\n [\"s43-r4c4\", \"\", \"one-thirty\", \"1 30 clock one-thirty time\", \"travel\"], // off-list: ChatGPT drew a red maple leaf, not used\n [\"s43-r4c5\", \"\", \"two-thirty\", \"2 30 clock time two-thirty\", \"travel\"], // off-list: ChatGPT drew an orange oak leaf, not used\n [\"s43-r4c6\", \"\", \"four-thirty\", \"30 4 clock four-thirty time\", \"travel\"], // off-list: ChatGPT drew a snowflake, not used\n [\"s43-r4c7\", \"\", \"five-thirty\", \"30 5 clock five-thirty time\", \"travel\"], // off-list: ChatGPT drew a pink cherry blossom, not used\n [\"s43-r5c1\", \"\", \"six-thirty\", \"30 6 clock six-thirty\", \"travel\"], // off-list: ChatGPT drew a yellow sun with rays, not used\n [\"s43-r5c2\", \"\", \"seven o’clock\", \"0 7 00 o’clock\", \"travel\"], // off-list: ChatGPT drew a crescent moon with stars, not used\n [\"s43-r5c3\", \"\", \"eight-thirty\", \"30 8 clock eight-thirty time\", \"travel\"], // off-list: ChatGPT drew a storm cloud with lightning and rain, not used\n [\"s43-r5c4\", \"\", \"nine-thirty\", \"30 9 clock nine-thirty time\", \"travel\"], // off-list: ChatGPT drew a tornado, not used\n [\"s43-r5c5\", \"\", \"ten o’clock\", \"0 10 00 o’clock\", \"travel\"], // off-list: ChatGPT drew a rainbow with clouds, not used\n [\"s43-r5c6\", \"\", \"eleven-thirty\", \"11 30 clock eleven-thirty time\", \"travel\"], // off-list: ChatGPT drew a spiral galaxy, not used\n [\"s43-r5c7\", \"\", \"flag: Liberia\", \"flag liberia lr\", \"flags\"], // off-list: ChatGPT drew a globe showing the Americas, not used\n [\"s43-r6c1\", \"\", \"flag: Qatar\", \"flag qatar qa\", \"flags\"], // off-list: ChatGPT drew a palm tree on a beach, not used\n [\"s43-r6c2\", \"\", \"flag: Turkmenistan\", \"flag turkmenistan tm\", \"flags\"], // off-list: ChatGPT drew snow-capped mountains with pine trees, not used\n [\"s43-r6c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\", \"flags\"], // off-list: ChatGPT drew a desert with dunes and a cactus, not used\n [\"s43-r6c4\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\", \"flags\"], // off-list: ChatGPT drew a red barn with a silo, not used\n [\"s43-r6c5\", \"\", \"flag: Isle of Man\", \"flag isle of man im\", \"flags\"], // off-list: ChatGPT drew a stone castle, not used\n [\"s43-r6c6\", \"\", \"flag: Comoros\", \"flag comoros km\", \"flags\"], // off-list: ChatGPT drew a city skyline, not used\n [\"s43-r6c7\", \"\", \"flag: Niue\", \"flag niue nu\", \"flags\"], // off-list: ChatGPT drew a house with a red roof, not used\n [\"s43-r7c1\", \"\", \"twelve-thirty\", \"12 30 clock time twelve-thirty\", \"travel\"], // off-list: ChatGPT drew a small red hatchback car, not used\n [\"s43-r7c2\", \"\", \"five-thirty\", \"30 5 clock five-thirty time\", \"travel\"], // off-list: ChatGPT drew a blue bicycle, not used\n [\"s43-r7c3\", \"\", \"flag: Isle of Man\", \"flag isle of man im\", \"flags\"], // off-list: ChatGPT drew a white airliner, not used\n [\"s43-r7c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\", \"flags\"], // off-list: ChatGPT drew a red steam train, not used\n [\"s43-r7c5\", \"\", \"flag: Niue\", \"flag niue nu\", \"flags\"], // off-list: ChatGPT drew a sailboat, not used\n [\"s43-r7c6\", \"\", \"person with veil\", \"wedding\", \"people\"], // off-list: ChatGPT drew a hot-air balloon, not used\n [\"s43-r7c7\", \"\", \"people with bunny ears\", \"bestie bff counterpart dancer double ear identical pair\", \"people\"], // off-list: ChatGPT drew a yellow school bus, not used\n // ── sheet 44: places and transport, redrawn ──\n [\"s44-r1c1\", \"🗾\", \"map of Japan\", \"map japan country island\"],\n [\"s44-r1c2\", \"\", \"landslide\", \"avalanche danger disaster earthquake mountain mudslide rocks\"],\n [\"s44-r1c3\", \"🏛️\", \"classical building\", \"classical building columns museum government\"],\n [\"s44-r1c4\", \"🏗️\", \"building construction\", \"crane\"],\n [\"s44-r1c5\", \"🪨\", \"rock\", \"boulder heavy solid stone tough\"],\n [\"s44-r1c6\", \"🪵\", \"wood\", \"log lumber timber\"],\n [\"s44-r1c7\", \"🛖\", \"hut\", \"home house roundhouse shelter yurt\"],\n [\"s44-r2c1\", \"🏚️\", \"derelict house\", \"home\"],\n [\"s44-r2c2\", \"🏣\", \"Japanese post office\", \"building\"],\n [\"s44-r2c3\", \"🏤\", \"post office\", \"building european\"],\n [\"s44-r2c4\", \"🏪\", \"convenience store\", \"24 building hours\"],\n [\"s44-r2c5\", \"🏬\", \"department store\", \"building\"],\n [\"s44-r2c6\", \"🏭\", \"factory\", \"building\"],\n [\"s44-r2c7\", \"🛕\", \"hindu temple\", \"hindu temple religion worship\"],\n [\"s44-r3c1\", \"🕍\", \"synagogue\", \"jew jewish judaism religion temple\"],\n [\"s44-r3c2\", \"⛩️\", \"shinto shrine\", \"religion\"],\n [\"s44-r3c3\", \"🌁\", \"foggy\", \"fog\"],\n [\"s44-r3c4\", \"🛝\", \"playground slide\", \"amusement park play playing sliding theme\"],\n [\"s44-r3c5\", \"🚄\", \"high-speed train\", \"high-speed railway shinkansen\"],\n [\"s44-r3c6\", \"🚅\", \"bullet train\", \"high-speed nose railway shinkansen speed travel\"],\n [\"s44-r3c7\", \"🚆\", \"train\", \"arrived choo railway\"],\n [\"s44-r4c1\", \"🚇\", \"metro\", \"subway travel\"],\n [\"s44-r4c2\", \"🚈\", \"light rail\", \"arrived monorail railway\"],\n [\"s44-r4c3\", \"🚉\", \"station\", \"railway train\"],\n [\"s44-r4c4\", \"🚊\", \"tram\", \"trolleybus\"],\n [\"s44-r4c5\", \"🚝\", \"monorail\", \"vehicle\"],\n [\"s44-r4c6\", \"🚞\", \"mountain railway\", \"car trip\"],\n [\"s44-r4c7\", \"🚍\", \"oncoming bus\", \"cars\"],\n [\"s44-r5c1\", \"🚎\", \"trolleybus\", \"bus tram trolley\"],\n [\"s44-r5c2\", \"🚖\", \"oncoming taxi\", \"cab cabbie cars drove hail yellow\"],\n [\"s44-r5c3\", \"🛻\", \"pickup truck\", \"automobile car flatbed pick-up transportation\"],\n [\"s44-r5c4\", \"🦽\", \"manual wheelchair\", \"accessibility\"],\n [\"s44-r5c5\", \"🦼\", \"motorized wheelchair\", \"accessibility\"],\n [\"s44-r5c6\", \"🚏\", \"bus stop\", \"busstop\"],\n [\"s44-r5c7\", \"🛤️\", \"railway track\", \"train\"],\n [\"s44-r6c1\", \"🛢️\", \"oil drum\", \"oil drum barrel fuel petrol\"],\n [\"s44-r6c2\", \"🚥\", \"horizontal traffic light\", \"intersection signal stop stoplight\"],\n [\"s44-r6c3\", \"🛶\", \"canoe\", \"boat\"],\n [\"s44-r6c4\", \"🚤\", \"speedboat\", \"billionaire boat lake luxury millionaire summer travel\"],\n [\"s44-r6c5\", \"🛳️\", \"passenger ship\", \"passenger ship cruise boat ocean\"],\n [\"s44-r6c6\", \"⛴️\", \"ferry\", \"boat passenger\"],\n [\"s44-r6c7\", \"🛥️\", \"motor boat\", \"motorboat\"],\n [\"s44-r7c1\", \"🛩️\", \"small airplane\", \"aeroplane plane\"],\n [\"s44-r7c2\", \"\", \"airplane arrival\", \"aeroplane arrivals arriving landing plane\"], // rejected: the nose points UP to the upper right with the tail low, the climbing pose of airplane departure, so it does not read as an arrival\n [\"s44-r7c3\", \"🚟\", \"suspension railway\", \"suspension railway monorail train transit\"],\n [\"s44-r7c4\", \"🚠\", \"mountain cableway\", \"cable gondola lift ski\"],\n [\"s44-r7c5\", \"🚡\", \"aerial tramway\", \"cable car gondola ropeway\"],\n [\"s44-r7c6\", \"🛰️\", \"satellite\", \"space\"],\n [\"s44-r7c7\", \"🛎️\", \"bellhop bell\", \"hotel\"],\n // ── sheet 45: redraws, second round ──\n [\"s45-r1c1\", \"🕐\", \"one o’clock\", \"1 00 o’clock time\", \"travel\"],\n [\"s45-r1c2\", \"🕜\", \"one-thirty\", \"1 30 clock one-thirty time\", \"travel\"],\n [\"s45-r1c3\", \"🕑\", \"two o’clock\", \"2 00 o’clock time\", \"travel\"],\n [\"s45-r1c4\", \"🕝\", \"two-thirty\", \"2 30 clock time two-thirty\", \"travel\"],\n [\"s45-r1c5\", \"🕒\", \"clock\", \"time clock\", \"objects\"],\n [\"s45-r1c6\", \"🕞\", \"three-thirty\", \"3 30 clock three-thirty time\", \"travel\"],\n [\"s45-r1c7\", \"🕓\", \"four o’clock\", \"4 00 o’clock time\", \"travel\"],\n [\"s45-r2c1\", \"🕟\", \"four-thirty\", \"30 4 clock four-thirty time\", \"travel\"],\n [\"s45-r2c2\", \"🕔\", \"five o’clock\", \"5 00 o’clock time\", \"travel\"],\n [\"s45-r2c3\", \"🕠\", \"five-thirty\", \"30 5 clock five-thirty time\", \"travel\"],\n [\"s45-r2c4\", \"🕕\", \"six o’clock\", \"6 00 o’clock time\", \"travel\"],\n [\"s45-r2c5\", \"🕡\", \"six-thirty\", \"30 6 clock six-thirty\", \"travel\"],\n [\"s45-r2c6\", \"🕖\", \"seven o’clock\", \"0 7 00 o’clock\", \"travel\"],\n [\"s45-r2c7\", \"🕢\", \"seven-thirty\", \"30 7 clock seven-thirty\", \"travel\"],\n [\"s45-r3c1\", \"🕗\", \"eight o’clock\", \"8 00 o’clock time\", \"travel\"],\n [\"s45-r3c2\", \"🕣\", \"eight-thirty\", \"30 8 clock eight-thirty time\", \"travel\"],\n [\"s45-r3c3\", \"🕘\", \"nine o’clock\", \"9 00 o’clock time\", \"travel\"],\n [\"s45-r3c4\", \"🕤\", \"nine-thirty\", \"30 9 clock nine-thirty time\", \"travel\"],\n [\"s45-r3c5\", \"🕙\", \"ten o’clock\", \"0 10 00 o’clock\", \"travel\"],\n [\"s45-r3c6\", \"🕥\", \"ten-thirty\", \"10 30 clock ten-thirty time\", \"travel\"],\n [\"s45-r3c7\", \"🕚\", \"eleven o’clock\", \"11 00 o’clock time\", \"travel\"],\n [\"s45-r4c1\", \"🕦\", \"eleven-thirty\", \"11 30 clock eleven-thirty time\", \"travel\"],\n [\"s45-r4c2\", \"🕛\", \"twelve o’clock\", \"12 00 o’clock time\", \"travel\"],\n [\"s45-r4c3\", \"🕧\", \"twelve-thirty\", \"12 30 clock time twelve-thirty\", \"travel\"],\n [\"s45-r4c4\", \"🕎\", \"menorah\", \"candelabrum candlestick hanukkah jewish judaism religion\", \"symbols\"],\n [\"s45-r4c5\", \"🌠\", \"shooting star\", \"falling night space\", \"travel\"],\n [\"s45-r4c6\", \"🌌\", \"milky way\", \"space\", \"travel\"],\n [\"s45-r4c7\", \"☄️\", \"comet\", \"space\", \"travel\"],\n [\"s45-r5c1\", \"🎆\", \"fireworks\", \"boom celebration entertainment yolo\", \"activities\"],\n [\"s45-r5c2\", \"🎇\", \"sparkler\", \"boom celebration fireworks sparkle\", \"activities\"],\n [\"s45-r5c3\", \"🎑\", \"moon viewing ceremony\", \"celebration\", \"activities\"],\n [\"s45-r5c4\", \"🚔\", \"oncoming police car\", \"police car cop oncoming siren\", \"travel\"],\n [\"s45-r5c5\", \"🚘\", \"oncoming automobile\", \"car cars drove vehicle\", \"travel\"],\n [\"s45-r5c6\", \"🛣️\", \"motorway\", \"highway road\", \"travel\"],\n [\"s45-r5c7\", \"🛫\", \"airplane departure\", \"aeroplane check-in departures plane\", \"travel\"],\n [\"s45-r6c1\", \"🛬\", \"airplane arrival\", \"aeroplane arrivals arriving landing plane\", \"travel\"],\n [\"s45-r6c2\", \"\", \"flag: Liberia\", \"flag liberia lr\", \"flags\"], // rejected: both takes have 9 stripes (5 red, 4 white), not 11\n [\"s45-r6c3\", \"\", \"flag: Qatar\", \"flag qatar qa\", \"flags\"], // rejected: both takes have 7 white serration points, not 9\n [\"s45-r6c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\", \"flags\"], // rejected: both takes have 7 yellow stars, not 9, so neither matches the real arrangement\n [\"s45-r6c5\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\", \"flags\"], // rejected: both takes have 13 white stars in the ring, not 15\n [\"s45-r6c6\", \"\", \"flag: Comoros\", \"flag comoros km\", \"flags\"], // rejected: both takes have 3 white stars beside the crescent, not 4\n [\"s45-r6c7\", \"\", \"flag: Niue\", \"flag niue nu\", \"flags\"], // rejected: both takes have only 2 stars: a small one at the Union Jack centre and a big star on a blue disc on the yellow field at the canton corner; the four small stars on the cross arms are missing\n [\"s45-r7c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\", \"flags\"], // rejected: both takes have 7 yellow stars, not 9, so neither matches the real arrangement\n [\"s45-r7c2\", \"\", \"flag: Niue\", \"flag niue nu\", \"flags\"], // rejected: both takes have only 2 stars: a small one at the Union Jack centre and a big star on a blue disc on the yellow field at the canton corner; the four small stars on the cross arms are missing\n [\"s45-r7c3\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\", \"flags\"], // rejected: both takes have 13 white stars in the ring, not 15\n [\"s45-r7c4\", \"\", \"flag: Comoros\", \"flag comoros km\", \"flags\"], // rejected: both takes have 3 white stars beside the crescent, not 4\n [\"s45-r7c5\", \"\", \"flag: Liberia\", \"flag liberia lr\", \"flags\"], // rejected: both takes have 9 stripes (5 red, 4 white), not 11\n [\"s45-r7c6\", \"\", \"flag: Qatar\", \"flag qatar qa\", \"flags\"], // rejected: both takes have 7 white serration points, not 9\n [\"s45-r7c7\", \"\", \"menorah\", \"candelabrum candlestick hanukkah jewish judaism religion\", \"symbols\"], // duplicate of s45-r4c4\n // ── sheet 46: flag of liberia, 49 takes ──\n [\"s46-r1c1\", \"🇱🇷\", \"flag: Liberia\", \"flag liberia lr\"],\n [\"s46-r1c2\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r1c3\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r1c4\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r1c5\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r1c6\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r1c7\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r2c1\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r2c2\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r2c3\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r2c4\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r2c5\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r2c6\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r2c7\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r3c1\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r3c2\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r3c3\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r3c4\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r3c5\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r3c6\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r3c7\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r4c1\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r4c2\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r4c3\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r4c4\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r4c5\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r4c6\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r4c7\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r5c1\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r5c2\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r5c3\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r5c4\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r5c5\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r5c6\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r5c7\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r6c1\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r6c2\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r6c3\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r6c4\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r6c5\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r6c6\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r6c7\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r7c1\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r7c2\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r7c3\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r7c4\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r7c5\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r7c6\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n [\"s46-r7c7\", \"\", \"flag: Liberia\", \"flag liberia lr\"], // duplicate of s46-r1c1\n // ── sheet 47: flag of qatar, 49 takes ──\n [\"s47-r1c1\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r1c2\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r1c3\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r1c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r1c5\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r1c6\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r1c7\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r2c1\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r2c2\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r2c3\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r2c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r2c5\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r2c6\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r2c7\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r3c1\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r3c2\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r3c3\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r3c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r3c5\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r3c6\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r3c7\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r4c1\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r4c2\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r4c3\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r4c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r4c5\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r4c6\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r4c7\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r5c1\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r5c2\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r5c3\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r5c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r5c5\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r5c6\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r5c7\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r6c1\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r6c2\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r6c3\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r6c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r6c5\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r6c6\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r6c7\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r7c1\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r7c2\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r7c3\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r7c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r7c5\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r7c6\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n [\"s47-r7c7\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // rejected: all 49 takes have 7 white serration points, not 9\n // ── sheet 48: flag of tuvalu, 49 takes ──\n [\"s48-r1c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r1c2\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r1c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r1c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r1c5\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r1c6\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r1c7\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r2c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r2c2\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r2c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r2c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r2c5\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r2c6\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r2c7\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r3c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r3c2\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r3c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r3c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r3c5\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r3c6\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r3c7\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r4c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r4c2\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r4c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r4c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r4c5\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r4c6\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r4c7\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r5c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r5c2\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r5c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r5c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r5c5\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r5c6\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r5c7\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r6c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r6c2\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r6c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r6c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r6c5\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r6c6\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r6c7\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r7c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r7c2\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r7c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r7c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r7c5\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r7c6\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n [\"s48-r7c7\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: all 49 takes have 8 yellow stars, not 9\n // ── sheet 49: flag of the cook islands, 49 takes ──\n [\"s49-r1c1\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r1c2\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r1c3\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r1c4\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r1c5\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r1c6\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r1c7\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r2c1\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r2c2\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r2c3\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r2c4\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r2c5\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r2c6\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r2c7\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r3c1\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r3c2\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r3c3\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r3c4\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r3c5\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r3c6\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r3c7\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r4c1\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r4c2\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r4c3\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r4c4\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r4c5\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r4c6\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r4c7\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r5c1\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r5c2\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r5c3\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r5c4\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r5c5\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r5c6\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r5c7\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r6c1\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r6c2\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r6c3\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r6c4\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r6c5\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r6c6\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r6c7\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r7c1\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r7c2\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r7c3\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r7c4\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r7c5\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r7c6\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n [\"s49-r7c7\", \"\", \"flag: Cook Islands\", \"flag cook islands ck\"], // rejected: all 49 takes have 14 white stars in the ring, not 15\n // ── sheet 50: flag of the comoros, 49 takes ──\n [\"s50-r1c1\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r1c2\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r1c3\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r1c4\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r1c5\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r1c6\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r1c7\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r2c1\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r2c2\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r2c3\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r2c4\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r2c5\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r2c6\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r2c7\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r3c1\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r3c2\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r3c3\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r3c4\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r3c5\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r3c6\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r3c7\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r4c1\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r4c2\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r4c3\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r4c4\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r4c5\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r4c6\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r4c7\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r5c1\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r5c2\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r5c3\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r5c4\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r5c5\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r5c6\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r5c7\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r6c1\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r6c2\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r6c3\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r6c4\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r6c5\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r6c6\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r6c7\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r7c1\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r7c2\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r7c3\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r7c4\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r7c5\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r7c6\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n [\"s50-r7c7\", \"\", \"flag: Comoros\", \"flag comoros km\"], // rejected: all 49 takes have 3 white stars beside the crescent, not 4\n // ── sheet 51: flag of niue, 49 takes ──\n [\"s51-r1c1\", \"🇳🇺\", \"flag: Niue\", \"flag niue nu\"],\n [\"s51-r1c2\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r1c3\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r1c4\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r1c5\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r1c6\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r1c7\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r2c1\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r2c2\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r2c3\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r2c4\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r2c5\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r2c6\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r2c7\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r3c1\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r3c2\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r3c3\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r3c4\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r3c5\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r3c6\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r3c7\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r4c1\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r4c2\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r4c3\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r4c4\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r4c5\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r4c6\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r4c7\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r5c1\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r5c2\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r5c3\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r5c4\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r5c5\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r5c6\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r5c7\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r6c1\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r6c2\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r6c3\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r6c4\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r6c5\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r6c6\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r6c7\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r7c1\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r7c2\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r7c3\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r7c4\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r7c5\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r7c6\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n [\"s51-r7c7\", \"\", \"flag: Niue\", \"flag niue nu\"], // duplicate of s51-r1c1\n // ── sheet 52: flag of qatar, 49 takes, regenerated ──\n [\"s52-r1c1\", \"🇶🇦\", \"flag: Qatar\", \"flag qatar qa\"],\n [\"s52-r1c2\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r1c3\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r1c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r1c5\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r1c6\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r1c7\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r2c1\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r2c2\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r2c3\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r2c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r2c5\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r2c6\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r2c7\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r3c1\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r3c2\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r3c3\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r3c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r3c5\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r3c6\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r3c7\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r4c1\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r4c2\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r4c3\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r4c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r4c5\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r4c6\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r4c7\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r5c1\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r5c2\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r5c3\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r5c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r5c5\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r5c6\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r5c7\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r6c1\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r6c2\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r6c3\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r6c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r6c5\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r6c6\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r6c7\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r7c1\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r7c2\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r7c3\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r7c4\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r7c5\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r7c6\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n [\"s52-r7c7\", \"\", \"flag: Qatar\", \"flag qatar qa\"], // duplicate of s52-r1c1\n // ── sheet 53: flag of tuvalu, 49 takes, regenerated ──\n [\"s53-r1c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r1c2\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r1c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r1c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r1c5\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r1c6\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r1c7\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r2c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r2c2\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r2c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r2c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r2c5\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r2c6\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r2c7\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r3c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r3c2\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r3c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r3c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r3c5\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r3c6\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r3c7\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r4c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r4c2\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r4c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r4c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r4c5\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r4c6\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r4c7\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r5c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r5c2\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r5c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r5c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r5c5\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r5c6\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r5c7\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r6c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r6c2\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r6c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r6c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r6c5\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r6c6\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r6c7\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r7c1\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r7c2\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r7c3\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r7c4\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r7c5\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r7c6\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n [\"s53-r7c7\", \"\", \"flag: Tuvalu\", \"flag tuvalu tv\"], // rejected: 9 stars, but not the real flag's layout: the lowest-left star sits under the Union Jack and the band runs down to the bottom edge; on the real flag every star is right of the Union Jack\n // ── sheet 54: redraws from the 2026-10 image review ──\n [\"s54-r1c1\", \"👊\", \"oncoming fist\", \"punch fist bump\", \"hands\"],\n [\"s54-r1c2\", \"💘\", \"heart with arrow\", \"cupid love crush\", \"symbols\"],\n [\"s54-r1c3\", \"🗺️\", \"world map\", \"map directions\", \"travel\"],\n [\"s54-r1c4\", \"🛋️\", \"couch and lamp\", \"couch sofa living room\", \"objects\"],\n [\"s54-r1c5\", \"🤱\", \"breast-feeding\", \"baby breast-feeding mom mother nursing woman\", \"people\"],\n [\"s54-r1c6\", \"🤸♀️\", \"woman cartwheeling\", \"active cartwheel excited flip gymnastics happy somersault\", \"people\"],\n [\"s54-r1c7\", \"🤸♂️\", \"man cartwheeling\", \"active cartwheel excited flip gymnastics happy somersault\", \"people\"],\n [\"s54-r2c1\", \"🥂\", \"clinking glasses\", \"cheers celebrate champagne toast\", \"food\"],\n [\"s54-r2c2\", \"♟️\", \"chess pawn\", \"chess strategy\", \"activities\"],\n [\"s54-r2c3\", \"⚧️\", \"transgender symbol\", \"transgender symbol trans\", \"symbols\"],\n [\"s54-r2c4\", \"✳️\", \"eight-spoked asterisk\", \"eight-spoked\", \"symbols\"],\n [\"s54-r2c5\", \"\", \"oncoming fist\", \"punch fist bump\", \"hands\"], // duplicate of s54-r1c1\n [\"s54-r2c6\", \"\", \"heart with arrow\", \"cupid love crush\", \"symbols\"], // duplicate of s54-r1c2\n [\"s54-r2c7\", \"\", \"world map\", \"map directions\", \"travel\"], // duplicate of s54-r1c3\n [\"s54-r3c1\", \"\", \"couch and lamp\", \"couch sofa living room\", \"objects\"], // duplicate of s54-r1c4\n [\"s54-r3c2\", \"\", \"breast-feeding\", \"baby breast-feeding mom mother nursing woman\", \"people\"], // duplicate of s54-r1c5\n [\"s54-r3c3\", \"\", \"woman cartwheeling\", \"active cartwheel excited flip gymnastics happy somersault\", \"people\"], // duplicate of s54-r1c6\n [\"s54-r3c4\", \"\", \"man cartwheeling\", \"active cartwheel excited flip gymnastics happy somersault\", \"people\"], // duplicate of s54-r1c7\n [\"s54-r3c5\", \"\", \"clinking glasses\", \"cheers celebrate champagne toast\", \"food\"], // duplicate of s54-r2c1\n [\"s54-r3c6\", \"\", \"chess pawn\", \"chess strategy\", \"activities\"], // duplicate of s54-r2c2\n [\"s54-r3c7\", \"\", \"transgender symbol\", \"transgender symbol trans\", \"symbols\"], // duplicate of s54-r2c3\n [\"s54-r4c1\", \"\", \"eight-spoked asterisk\", \"eight-spoked\", \"symbols\"], // duplicate of s54-r2c4\n [\"s54-r4c2\", \"\", \"oncoming fist\", \"punch fist bump\", \"hands\"], // duplicate of s54-r1c1\n [\"s54-r4c3\", \"\", \"heart with arrow\", \"cupid love crush\", \"symbols\"], // duplicate of s54-r1c2\n [\"s54-r4c4\", \"\", \"world map\", \"map directions\", \"travel\"], // duplicate of s54-r1c3\n [\"s54-r4c5\", \"\", \"couch and lamp\", \"couch sofa living room\", \"objects\"], // duplicate of s54-r1c4\n [\"s54-r4c6\", \"\", \"breast-feeding\", \"baby breast-feeding mom mother nursing woman\", \"people\"], // duplicate of s54-r1c5\n [\"s54-r4c7\", \"\", \"woman cartwheeling\", \"active cartwheel excited flip gymnastics happy somersault\", \"people\"], // duplicate of s54-r1c6\n [\"s54-r5c1\", \"\", \"man cartwheeling\", \"active cartwheel excited flip gymnastics happy somersault\", \"people\"], // duplicate of s54-r1c7\n [\"s54-r5c2\", \"\", \"clinking glasses\", \"cheers celebrate champagne toast\", \"food\"], // duplicate of s54-r2c1\n [\"s54-r5c3\", \"\", \"chess pawn\", \"chess strategy\", \"activities\"], // duplicate of s54-r2c2\n [\"s54-r5c4\", \"\", \"transgender symbol\", \"transgender symbol trans\", \"symbols\"], // duplicate of s54-r2c3\n [\"s54-r5c5\", \"\", \"eight-spoked asterisk\", \"eight-spoked\", \"symbols\"], // duplicate of s54-r2c4\n [\"s54-r5c6\", \"\", \"oncoming fist\", \"punch fist bump\", \"hands\"], // duplicate of s54-r1c1\n [\"s54-r5c7\", \"\", \"heart with arrow\", \"cupid love crush\", \"symbols\"], // duplicate of s54-r1c2\n [\"s54-r6c1\", \"\", \"world map\", \"map directions\", \"travel\"], // duplicate of s54-r1c3\n [\"s54-r6c2\", \"\", \"couch and lamp\", \"couch sofa living room\", \"objects\"], // duplicate of s54-r1c4\n [\"s54-r6c3\", \"\", \"breast-feeding\", \"baby breast-feeding mom mother nursing woman\", \"people\"], // duplicate of s54-r1c5\n [\"s54-r6c4\", \"\", \"woman cartwheeling\", \"active cartwheel excited flip gymnastics happy somersault\", \"people\"], // duplicate of s54-r1c6\n [\"s54-r6c5\", \"\", \"man cartwheeling\", \"active cartwheel excited flip gymnastics happy somersault\", \"people\"], // duplicate of s54-r1c7\n [\"s54-r6c6\", \"\", \"clinking glasses\", \"cheers celebrate champagne toast\", \"food\"], // duplicate of s54-r2c1\n [\"s54-r6c7\", \"\", \"chess pawn\", \"chess strategy\", \"activities\"], // duplicate of s54-r2c2\n [\"s54-r7c1\", \"\", \"transgender symbol\", \"transgender symbol trans\", \"symbols\"], // duplicate of s54-r2c3\n [\"s54-r7c2\", \"\", \"eight-spoked asterisk\", \"eight-spoked\", \"symbols\"], // duplicate of s54-r2c4\n [\"s54-r7c3\", \"\", \"oncoming fist\", \"punch fist bump\", \"hands\"], // duplicate of s54-r1c1\n [\"s54-r7c4\", \"\", \"heart with arrow\", \"cupid love crush\", \"symbols\"], // duplicate of s54-r1c2\n [\"s54-r7c5\", \"\", \"world map\", \"map directions\", \"travel\"], // duplicate of s54-r1c3\n [\"s54-r7c6\", \"\", \"couch and lamp\", \"couch sofa living room\", \"objects\"], // duplicate of s54-r1c4\n [\"s54-r7c7\", \"\", \"breast-feeding\", \"baby breast-feeding mom mother nursing woman\", \"people\"], // duplicate of s54-r1c5\n // ── sheet 55: flag of bosnia & herzegovina, 49 takes ──\n [\"s55-r1c1\", \"🇧🇦\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"],\n [\"s55-r1c2\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r1c3\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r1c4\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r1c5\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r1c6\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r1c7\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r2c1\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r2c2\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r2c3\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r2c4\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r2c5\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r2c6\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r2c7\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r3c1\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r3c2\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r3c3\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r3c4\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r3c5\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r3c6\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r3c7\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r4c1\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r4c2\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r4c3\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r4c4\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r4c5\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r4c6\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r4c7\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r5c1\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r5c2\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r5c3\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r5c4\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r5c5\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r5c6\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r5c7\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r6c1\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r6c2\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r6c3\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r6c4\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r6c5\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r6c6\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r6c7\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r7c1\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r7c2\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r7c3\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r7c4\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r7c5\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r7c6\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n [\"s55-r7c7\", \"\", \"flag: Bosnia & Herzegovina\", \"flag bosnia herzegovina ba\"], // duplicate of s55-r1c1\n // ── sheet 56: flag of dominica, 49 takes ──\n [\"s56-r1c1\", \"🇩🇲\", \"flag: Dominica\", \"flag dominica dm\"],\n [\"s56-r1c2\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r1c3\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r1c4\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r1c5\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r1c6\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r1c7\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r2c1\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r2c2\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r2c3\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r2c4\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r2c5\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r2c6\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r2c7\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r3c1\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r3c2\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r3c3\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r3c4\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r3c5\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r3c6\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r3c7\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r4c1\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r4c2\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r4c3\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r4c4\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r4c5\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r4c6\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r4c7\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r5c1\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r5c2\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r5c3\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r5c4\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r5c5\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r5c6\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r5c7\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r6c1\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r6c2\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r6c3\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r6c4\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r6c5\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r6c6\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r6c7\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r7c1\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r7c2\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r7c3\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r7c4\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r7c5\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r7c6\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n [\"s56-r7c7\", \"\", \"flag: Dominica\", \"flag dominica dm\"], // duplicate of s56-r1c1\n // ── sheet 57: flag of kiribati, 49 takes ──\n [\"s57-r1c1\", \"🇰🇮\", \"flag: Kiribati\", \"flag kiribati ki\"],\n [\"s57-r1c2\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r1c3\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r1c4\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r1c5\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r1c6\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r1c7\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r2c1\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r2c2\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r2c3\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r2c4\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r2c5\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r2c6\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r2c7\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r3c1\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r3c2\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r3c3\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r3c4\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r3c5\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r3c6\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r3c7\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r4c1\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r4c2\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r4c3\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r4c4\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r4c5\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r4c6\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r4c7\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r5c1\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r5c2\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r5c3\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r5c4\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r5c5\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r5c6\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r5c7\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r6c1\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r6c2\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r6c3\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r6c4\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r6c5\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r6c6\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r6c7\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r7c1\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r7c2\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r7c3\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r7c4\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r7c5\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r7c6\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n [\"s57-r7c7\", \"\", \"flag: Kiribati\", \"flag kiribati ki\"], // duplicate of s57-r1c1\n // ── sheet 58: flag of french southern and antarctic lands, 49 takes ──\n [\"s58-r1c1\", \"🇹🇫\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"],\n [\"s58-r1c2\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r1c3\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r1c4\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r1c5\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r1c6\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r1c7\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r2c1\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r2c2\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r2c3\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r2c4\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r2c5\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r2c6\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r2c7\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r3c1\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r3c2\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r3c3\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r3c4\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r3c5\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r3c6\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r3c7\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r4c1\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r4c2\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r4c3\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r4c4\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r4c5\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r4c6\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r4c7\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r5c1\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r5c2\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r5c3\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r5c4\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r5c5\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r5c6\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r5c7\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r6c1\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r6c2\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r6c3\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r6c4\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r6c5\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r6c6\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r6c7\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r7c1\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r7c2\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r7c3\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r7c4\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r7c5\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r7c6\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n [\"s58-r7c7\", \"\", \"flag: French Southern and Antarctic Lands\", \"flag french southern and antarctic lands tf\"], // duplicate of s58-r1c1\n];\n\n/**\n * The comparison key for an emoji: VARIATION SELECTOR-16 removed. \"❤️\" arrives as U+2764\n * U+FE0F from one keyboard and a bare U+2764 from another; both are the same heart and must\n * find the same art.\n */\nexport function emojiKey(text: string): string {\n return text.replace(/\\uFE0F/g, \"\");\n}\n\n/** `grinning face with smiling eyes` -> `grinning_face_with_smiling_eyes` (no colons). */\nexport function emojiShortcode(name: string): string {\n return name.replace(/[^a-z0-9]+/gi, \"_\").replace(/^_|_$/g, \"\").toLowerCase();\n}\n\n/** The category a tile belongs to: the row's own `category` when it has one, else its sheet's. */\nexport function emojiCategoryOf(tile: string, override?: string): string {\n if (override) return override;\n const sheet = Number(tile.slice(1, 3));\n return EMOJI_CATEGORIES.find((c) => c.sheets.includes(sheet))?.id ?? \"other\";\n}\n\n/**\n * The library's public id for an emoji: its code points in lowercase hex, joined by `-`, with\n * VS16 removed (`emojiKey`), e.g. `1f600`, `2764`, `1f62e-200d-1f4a8`. Derived from the\n * character, so it is stable across any re-cut or relabelling of the sheets, and a client\n * that knows the character can compute it without the catalog.\n */\nexport function emojiArtId(emoji: string): string {\n return [...emojiKey(emoji)].map((c) => c.codePointAt(0)!.toString(16)).join(\"-\");\n}\n\n/**\n * Every tile with a character, in picker order (the library's `sortOrder` too): grouped by\n * category in `EMOJI_CATEGORIES` order, and in catalog order within a category. So a later\n * sheet joins its category's END rather than the end of the whole list: sheet 14's faces\n * follow sheet 2's smileys, not sheet 13's household objects. The sort is stable, so within a\n * category it is exactly the order of the rows above.\n */\nexport function emojiRowsWithCharacter(): readonly EmojiRow[] {\n const rank = new Map(EMOJI_CATEGORIES.map((c, i) => [c.id, i]));\n const rankOf = ([tile, , , , category]: EmojiRow) => rank.get(emojiCategoryOf(tile, category)) ?? EMOJI_CATEGORIES.length;\n return EMOJI_ROWS.filter(([, emoji]) => emoji !== \"\").sort((a, b) => rankOf(a) - rankOf(b));\n}\n\nexport const EmojiLibraryEntrySchema = z\n .object({\n id: z.string().describe(\"Code points in lowercase hex joined by `-`, VS16 removed (`1f600`, `1f62e-200d-1f4a8`). The image route's key.\"),\n emoji: z.string().describe(\"The character exactly as it goes on the wire, including any VS16 and ZWJ.\"),\n name: z.string(),\n shortcode: z.string().describe(\"Without colons: `grinning_face_with_smiling_eyes`.\"),\n keywords: z.array(z.string()),\n category: z.string().describe(\"A `categories[].id`.\"),\n sortOrder: z.number().int().describe(\"Picker order within the whole library, ascending.\"),\n version: z.string().describe(\"Changes when the artwork does. Pass as `?v=` on the image route.\"),\n })\n .describe(\"One emoji the platform has artwork for.\");\n\nexport const EmojiLibrarySchema = z\n .object({\n categories: z.array(z.object({ id: z.string(), label: z.string() })).describe(\"Picker tabs, in order.\"),\n emoji: z.array(EmojiLibraryEntrySchema),\n licence: z.string().describe(\"Terms for the artwork, which clients cache on disk.\"),\n })\n .describe(\"The platform emoji library (capability `emoji-library`).\");\nexport type EmojiLibrary = z.infer<typeof EmojiLibrarySchema>;\nexport type EmojiLibraryEntry = z.infer<typeof EmojiLibraryEntrySchema>;\n","/**\n * The screen share's forward error correction: a systematic Reed-Solomon erasure code over\n * GF(2^8), byte-compatible with Switchboard's (`Switchboard.Screen.Core/Fec/ReedSolomon.cs`).\n *\n * `k` data shards plus `m` parity shards, `k + m <= 255`; ANY `k` of them rebuild the data.\n * The parity rows are a Cauchy matrix, coefficient `1 / ((k + i) xor j)` for parity `i` and data\n * `j`. Every square submatrix of a Cauchy matrix is invertible, so `[I; C]` is MDS: whichever `k`\n * shards survive, the system they give is solvable. The field is the byte-oriented standard,\n * polynomial x^8+x^4+x^3+x^2+1 (0x11D).\n *\n * ⚠️ The construction is a WIRE fact, not an implementation choice: a viewer rebuilds a sender's\n * lost shards from the sender's parity, so a different matrix, field or generator produces\n * parity that \"recovers\" garbage with no error anywhere. Both sides are pinned by the same\n * vectors (packages/shared/vectors/share-fec-v1.json, generated by Switchboard's own code).\n */\n\nconst POLYNOMIAL = 0x11d;\n\nconst EXP = new Uint8Array(512);\nconst LOG = new Uint8Array(256);\n{\n let x = 1;\n for (let i = 0; i < 255; i++) {\n EXP[i] = x;\n LOG[x] = i;\n x <<= 1;\n if (x & 0x100) x ^= POLYNOMIAL;\n }\n // Doubled so a product never has to reduce log(a) + log(b) modulo 255.\n for (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255]!;\n}\n\n/** Row `c` of the product table, built on first use: `row[b] = c * b`. */\nconst ROWS: (Uint8Array | undefined)[] = new Array(256);\nfunction rowFor(c: number): Uint8Array {\n let row = ROWS[c];\n if (!row) {\n row = new Uint8Array(256);\n if (c !== 0) {\n const logC = LOG[c]!;\n for (let b = 1; b < 256; b++) row[b] = EXP[logC + LOG[b]!]!;\n }\n ROWS[c] = row;\n }\n return row;\n}\n\nexport function gfMultiply(a: number, b: number): number {\n if (a === 0 || b === 0) return 0;\n return EXP[LOG[a]! + LOG[b]!]!;\n}\n\nexport function gfInverse(a: number): number {\n if (a === 0) throw new RangeError(\"0 has no inverse in GF(2^8)\");\n return EXP[255 - LOG[a]!]!;\n}\n\n/** `destination[i] ^= c * source[i]` over the first `length` bytes. */\nfunction multiplyAdd(c: number, source: Uint8Array, destination: Uint8Array, length: number): void {\n if (c === 0) return;\n if (c === 1) {\n for (let i = 0; i < length; i++) destination[i]! ^= source[i]!;\n return;\n }\n const row = rowFor(c);\n for (let i = 0; i < length; i++) destination[i]! ^= row[source[i]!]!;\n}\n\n/** GF(2^8) has 255 non-zero elements; beyond that the Cauchy x and y values cannot be distinct. */\nexport const RS_MAX_TOTAL_SHARDS = 255;\n\nexport class ReedSolomon {\n private readonly parityMatrix: Uint8Array; // m rows x k columns\n\n constructor(\n readonly dataShards: number,\n readonly parityShards: number,\n ) {\n if (!Number.isInteger(dataShards) || dataShards < 1) throw new RangeError(\"at least one data shard\");\n if (!Number.isInteger(parityShards) || parityShards < 0 || dataShards + parityShards > RS_MAX_TOTAL_SHARDS) {\n throw new RangeError(`data plus parity must not exceed ${RS_MAX_TOTAL_SHARDS}`);\n }\n this.parityMatrix = new Uint8Array(parityShards * dataShards);\n for (let i = 0; i < parityShards; i++) {\n for (let j = 0; j < dataShards; j++) {\n this.parityMatrix[i * dataShards + j] = gfInverse((dataShards + i) ^ j);\n }\n }\n }\n\n get totalShards(): number {\n return this.dataShards + this.parityShards;\n }\n\n coefficient(parity: number, data: number): number {\n return this.parityMatrix[parity * this.dataShards + data]!;\n }\n\n /** Fills each of `parity` (first `shardLength` bytes) from `data`. */\n encode(data: readonly Uint8Array[], parity: readonly Uint8Array[], shardLength: number): void {\n if (data.length !== this.dataShards || parity.length !== this.parityShards) throw new RangeError(\"shard counts do not match the code\");\n for (let i = 0; i < this.parityShards; i++) {\n const output = parity[i]!;\n output.fill(0, 0, shardLength);\n for (let j = 0; j < this.dataShards; j++) multiplyAdd(this.coefficient(i, j), data[j]!, output, shardLength);\n }\n }\n\n /**\n * Rebuilds every missing DATA shard in place. `shards` holds all `totalShards` slots, data\n * first; a present slot holds a received shard and a missing data slot must already hold a\n * buffer of at least `shardLength` bytes. Parity is never rebuilt: nobody needs it once the data\n * is back. Returns false when fewer than `dataShards` shards are present.\n */\n reconstruct(shards: (Uint8Array | null)[], present: readonly boolean[], shardLength: number): boolean {\n const k = this.dataShards;\n if (shards.length !== this.totalShards || present.length !== this.totalShards) throw new RangeError(\"shard slots do not match the code\");\n\n let missingData = 0;\n for (let j = 0; j < k; j++) if (!present[j]) missingData++;\n if (missingData === 0) return true;\n\n // k surviving rows: every present data shard, topped up with present parity.\n const rows: number[] = [];\n for (let s = 0; s < this.totalShards && rows.length < k; s++) if (present[s]) rows.push(s);\n if (rows.length < k) return false;\n\n const matrix = new Uint8Array(k * k);\n rows.forEach((shard, r) => {\n if (shard < k) matrix[r * k + shard] = 1;\n else for (let c = 0; c < k; c++) matrix[r * k + c] = this.coefficient(shard - k, c);\n });\n const inverse = invert(matrix, k);\n\n for (let j = 0; j < k; j++) {\n if (present[j]) continue;\n const output = shards[j];\n if (!output || output.length < shardLength) throw new RangeError(`missing data slot ${j} has no buffer`);\n output.fill(0, 0, shardLength);\n for (let r = 0; r < k; r++) multiplyAdd(inverse[j * k + r]!, shards[rows[r]!]!, output, shardLength);\n }\n return true;\n }\n}\n\n/** Gauss-Jordan inversion over GF(2^8). */\nfunction invert(matrix: Uint8Array, n: number): Uint8Array {\n const work = matrix.slice();\n const inverse = new Uint8Array(n * n);\n for (let i = 0; i < n; i++) inverse[i * n + i] = 1;\n\n for (let col = 0; col < n; col++) {\n let pivot = col;\n while (pivot < n && work[pivot * n + col] === 0) pivot++;\n // Unreachable for a Cauchy-derived system (that is the MDS property); loud if it ever is not.\n if (pivot === n) throw new Error(\"singular recovery matrix: the code is not MDS\");\n if (pivot !== col) {\n swapRows(work, n, pivot, col);\n swapRows(inverse, n, pivot, col);\n }\n const scale = gfInverse(work[col * n + col]!);\n scaleRow(work, n, col, scale);\n scaleRow(inverse, n, col, scale);\n for (let row = 0; row < n; row++) {\n if (row === col) continue;\n const factor = work[row * n + col]!;\n if (factor === 0) continue;\n multiplyAdd(factor, work.subarray(col * n, col * n + n), work.subarray(row * n, row * n + n), n);\n multiplyAdd(factor, inverse.subarray(col * n, col * n + n), inverse.subarray(row * n, row * n + n), n);\n }\n }\n return inverse;\n}\n\nfunction swapRows(m: Uint8Array, n: number, a: number, b: number): void {\n for (let i = 0; i < n; i++) {\n const t = m[a * n + i]!;\n m[a * n + i] = m[b * n + i]!;\n m[b * n + i] = t;\n }\n}\n\nfunction scaleRow(m: Uint8Array, n: number, row: number, scale: number): void {\n const r = rowFor(scale);\n for (let i = 0; i < n; i++) m[row * n + i] = r[m[row * n + i]!]!;\n}\n","import { AEAD, HEADER, PAYLOAD_TYPE, SHARE_DATAGRAM_MAX_BYTES, VIDEO_SHARD, VIDEO_SHARD_FLAG } from \"../nativeTransport.js\";\n\n/**\n * The geometry of a type-3 video shard, byte-compatible with Switchboard's `ShareWire` /\n * `ShardPlan` (docs/screen-share.md §5.2 in their repo). Every field a peer controls is validated\n * here before anything is sized from it.\n */\n\n/** Everything before the shard bytes. */\nexport const SHARD_HEADER_BYTES = VIDEO_SHARD.SHARD_OFFSET; // 23\n/** The native record's cleartext header plus the GCM tag. */\nexport const RECORD_OVERHEAD_BYTES = HEADER.LENGTH + AEAD.TAG_BYTES; // 51\n/** The largest shard a receiver accepts: the 1200-byte UDP budget less the record and shard headers. */\nexport const MAX_SHARD_BYTES = SHARE_DATAGRAM_MAX_BYTES - RECORD_OVERHEAD_BYTES - SHARD_HEADER_BYTES; // 1126\n/**\n * The WebTransport door's datagram budget (contract §19): Chrome drops what the path cannot carry,\n * and the QUIC minimum guarantees about this much on any path.\n */\nexport const SHARE_WEBTRANSPORT_DATAGRAM_MAX_BYTES = 1150;\n/** What a native (UDP) sender aims for: Switchboard's size. */\nexport const SHARE_UDP_SHARD_TARGET_BYTES = 1100;\n/**\n * What a WebTransport sender aims for, so every datagram fits the door's budget: 1150 - 51 - 23.\n * The receiver measures the shard length off the datagram, so either size interoperates.\n */\nexport const SHARE_WEBTRANSPORT_SHARD_TARGET_BYTES = SHARE_WEBTRANSPORT_DATAGRAM_MAX_BYTES - RECORD_OVERHEAD_BYTES - SHARD_HEADER_BYTES; // 1076\n/** Data shards per FEC block, so a block and its parity stay inside GF(2^8)'s 255. */\nexport const MAX_DATA_SHARDS_PER_BLOCK = 200;\n/**\n * The largest access unit a share may carry. Load-bearing: below `shardTarget^2` a receiver's\n * `ceil(frameBytes / shardLength)` is guaranteed to recover the sender's data-shard count, and\n * 1076^2 is about 1.16 MB.\n */\nexport const MAX_FRAME_BYTES = 1024 * 1024;\n/**\n * The FIXED parity rule: what a sender uses when it has nothing better to go on (no viewer has\n * reported yet), what keyframes always get at least, and what Switchboard's sharder sends.\n *\n * ⚠️ It is a SENDER default, not a wire fact. Every shard carries its block's `(dataShards,\n * parityShards)`, and a receiver builds its Reed-Solomon code from those two numbers alone\n * (assembler.ts, and Switchboard's `FrameAssembler`), so a sender may choose any parity per block.\n * The Service Manager sharer adapts it to the loss its viewers report (fecControl.ts). Nothing on\n * the receive side may derive a parity count from this rule: the loss meter did until the\n * adaptive sender, and would have read every shard it was never sent as lost.\n */\nexport const PARITY_RATIO = 0.2;\nexport const MIN_PARITY_SHARDS = 2;\nexport const KNOWN_SHARD_FLAGS = VIDEO_SHARD_FLAG.keyframe | VIDEO_SHARD_FLAG.recoveryPoint | VIDEO_SHARD_FLAG.endOfShare;\n\n/** Parity for a block of `dataShards` at `ratio`: `ceil(k * ratio)`, at least `minShards`, and never past 255 in total. */\nexport function parityAt(dataShards: number, ratio: number, minShards: number): number {\n return Math.min(255 - dataShards, Math.max(minShards, Math.ceil(dataShards * ratio)));\n}\n\n/** The fixed rule: 20%, at least 2, and never past 255 in total. */\nexport function parityFor(dataShards: number): number {\n return parityAt(dataShards, PARITY_RATIO, MIN_PARITY_SHARDS);\n}\n\n/** How many parity shards a block of `dataShards` gets, given the frame's shard flags. */\nexport type ParityPolicy = (dataShards: number, flags: number) => number;\n\nconst ceilDiv = (a: number, b: number): number => Math.floor((a + b - 1) / b);\n\n/**\n * Where every byte of a frame sits. Both ends derive it from two numbers, the sender from\n * `frameBytes` and its shard target, the receiver from `frameBytes` and the shard length it\n * measured, so there is no announcement to lose and one packet locates itself.\n */\nexport class ShardPlan {\n private constructor(\n readonly frameBytes: number,\n readonly shardLength: number,\n readonly totalDataShards: number,\n readonly blockCount: number,\n ) {}\n\n /** The sender's plan. Shards are balanced (1500 bytes is two of 750, not 1100 + 400 of padding),\n * because every byte of padding is multiplied by the parity too. */\n static forFrame(frameBytes: number, shardTarget: number): ShardPlan {\n if (!Number.isInteger(frameBytes) || frameBytes < 1 || frameBytes > MAX_FRAME_BYTES) throw new RangeError(`frame of ${frameBytes} bytes is outside the share limits`);\n if (!Number.isInteger(shardTarget) || shardTarget < 1 || shardTarget > MAX_SHARD_BYTES) throw new RangeError(`shard target ${shardTarget} is outside 1..${MAX_SHARD_BYTES}`);\n const shards = ceilDiv(frameBytes, shardTarget);\n return new ShardPlan(frameBytes, ceilDiv(frameBytes, shards), shards, ceilDiv(shards, MAX_DATA_SHARDS_PER_BLOCK));\n }\n\n /** The receiver's plan, from what it can measure; null when the numbers describe no frame. */\n static fromReceived(frameBytes: number, shardLength: number): ShardPlan | null {\n if (frameBytes < 1 || frameBytes > MAX_FRAME_BYTES || shardLength < 1) return null;\n const shards = ceilDiv(frameBytes, shardLength);\n const blocks = ceilDiv(shards, MAX_DATA_SHARDS_PER_BLOCK);\n if (blocks > 255) return null;\n return new ShardPlan(frameBytes, shardLength, shards, blocks);\n }\n\n /** Blocks are balanced: the first `N mod blocks` take one extra shard. */\n dataShardsIn(block: number): number {\n const base = Math.floor(this.totalDataShards / this.blockCount);\n return base + (block < this.totalDataShards % this.blockCount ? 1 : 0);\n }\n\n /** The frame-wide index of a block's first data shard. */\n firstShardOf(block: number): number {\n const base = Math.floor(this.totalDataShards / this.blockCount);\n return block * base + Math.min(block, this.totalDataShards % this.blockCount);\n }\n\n /** How many frame bytes data shard `globalShard` carries (the last one is short). */\n bytesIn(globalShard: number): number {\n return Math.min(this.shardLength, this.frameBytes - globalShard * this.shardLength);\n }\n}\n\nexport interface ShardHeader {\n streamId: number;\n /** 90 kHz capture clock. */\n timestamp: number;\n frameId: number;\n frameBytes: number;\n blockIndex: number;\n blockCount: number;\n shardIndex: number;\n dataShards: number;\n parityShards: number;\n flags: number;\n}\n\nexport function writeShardHeader(payload: Uint8Array, h: ShardHeader): void {\n const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);\n payload[VIDEO_SHARD.TYPE_OFFSET] = PAYLOAD_TYPE.videoShard;\n view.setUint32(VIDEO_SHARD.STREAM_ID_OFFSET, h.streamId);\n view.setUint32(VIDEO_SHARD.TIMESTAMP_OFFSET, h.timestamp);\n view.setUint32(VIDEO_SHARD.FRAME_ID_OFFSET, h.frameId);\n view.setUint32(VIDEO_SHARD.FRAME_BYTES_OFFSET, h.frameBytes);\n payload[VIDEO_SHARD.BLOCK_INDEX_OFFSET] = h.blockIndex;\n payload[VIDEO_SHARD.BLOCK_COUNT_OFFSET] = h.blockCount;\n payload[VIDEO_SHARD.SHARD_INDEX_OFFSET] = h.shardIndex;\n payload[VIDEO_SHARD.DATA_SHARDS_OFFSET] = h.dataShards;\n payload[VIDEO_SHARD.PARITY_SHARDS_OFFSET] = h.parityShards;\n payload[VIDEO_SHARD.FLAGS_OFFSET] = h.flags;\n}\n\n/**\n * Reads and validates a decrypted type-3 payload. Null when anything is out of shape, including a\n * geometry that disagrees with the plan the frame's own numbers derive: two shards of one frame\n * must never disagree about where their bytes go.\n */\nexport function readShardHeader(payload: Uint8Array): { header: ShardHeader; shardLength: number; plan: ShardPlan } | null {\n const shardLength = payload.length - SHARD_HEADER_BYTES;\n if (payload.length <= SHARD_HEADER_BYTES || shardLength > MAX_SHARD_BYTES || payload[VIDEO_SHARD.TYPE_OFFSET] !== PAYLOAD_TYPE.videoShard) return null;\n const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);\n const header: ShardHeader = {\n streamId: view.getUint32(VIDEO_SHARD.STREAM_ID_OFFSET),\n timestamp: view.getUint32(VIDEO_SHARD.TIMESTAMP_OFFSET),\n frameId: view.getUint32(VIDEO_SHARD.FRAME_ID_OFFSET),\n frameBytes: view.getUint32(VIDEO_SHARD.FRAME_BYTES_OFFSET),\n blockIndex: payload[VIDEO_SHARD.BLOCK_INDEX_OFFSET]!,\n blockCount: payload[VIDEO_SHARD.BLOCK_COUNT_OFFSET]!,\n shardIndex: payload[VIDEO_SHARD.SHARD_INDEX_OFFSET]!,\n dataShards: payload[VIDEO_SHARD.DATA_SHARDS_OFFSET]!,\n parityShards: payload[VIDEO_SHARD.PARITY_SHARDS_OFFSET]!,\n flags: payload[VIDEO_SHARD.FLAGS_OFFSET]!,\n };\n if (\n header.frameBytes === 0 ||\n header.frameBytes > MAX_FRAME_BYTES ||\n (header.flags & ~KNOWN_SHARD_FLAGS) !== 0 ||\n header.blockCount === 0 ||\n header.blockIndex >= header.blockCount ||\n header.dataShards === 0 ||\n header.dataShards + header.parityShards > 255 ||\n header.shardIndex >= header.dataShards + header.parityShards\n ) {\n return null;\n }\n const plan = ShardPlan.fromReceived(header.frameBytes, shardLength);\n if (!plan || plan.blockCount !== header.blockCount || plan.dataShardsIn(header.blockIndex) !== header.dataShards) return null;\n return { header, shardLength, plan };\n}\n","import { VIDEO_SHARD_FLAG } from \"../nativeTransport.js\";\nimport { ReedSolomon } from \"./reedSolomon.js\";\nimport { readShardHeader, SHARD_HEADER_BYTES, type ShardHeader, type ShardPlan } from \"./shardWire.js\";\nimport { ShardLossMeter } from \"./lossMeter.js\";\n\nexport interface AssembledFrame {\n frameId: number;\n /** 90 kHz capture clock. */\n timestamp: number;\n flags: number;\n keyframe: boolean;\n recoveryPoint: boolean;\n endOfShare: boolean;\n /** Data shards rebuilt from parity for this frame. */\n recoveredShards: number;\n accessUnit: Uint8Array;\n}\n\nexport interface FrameSink {\n onFrame(frame: AssembledFrame): void;\n /**\n * Frames `first`..`last` (inclusive, wrapping) will never arrive: a newer frame completed first.\n * The decoder's reference chain is broken until a keyframe or recovery point; what to do about it\n * is the viewer's policy.\n */\n onLost(first: number, last: number): void;\n}\n\n/** A frame id this far ahead of the last delivered one is garbage, not the future. */\nconst MAX_FORWARD_JUMP = 1 << 16;\n\n/** Signed distance from `from` to `to` in uint32 frame-id space. */\nconst distance = (to: number, from: number): number => ((to - from) | 0);\n\ninterface BlockState {\n dataShards: number;\n parityShards: number;\n shards: (Uint8Array | null)[];\n present: boolean[];\n count: number;\n done: boolean;\n}\n\ninterface PendingFrame {\n header: ShardHeader;\n shardLength: number;\n plan: ShardPlan;\n blocks: (BlockState | null)[];\n blocksDone: number;\n recovered: number;\n}\n\n/**\n * Receiver side, one per share stream: collects shards, rebuilds lost data shards from parity, and\n * hands each access unit on the moment it is whole. Behaviour matches Switchboard's\n * `FrameAssembler`.\n *\n * PRESENT ON ARRIVAL, NEVER REORDER-AND-WAIT. A frame is delivered as soon as its last needed shard\n * lands. A frame older than one already delivered is useless to a decoder that has moved past it,\n * so it is dropped as late, and every frame between the last delivered one and a newly completed\n * one is declared lost at that instant rather than waited for. There is no jitter buffer, which is\n * the latency the whole design is for.\n */\nexport class FrameAssembler {\n private readonly pending = new Map<number, PendingFrame>();\n private readonly codes = new Map<number, ReedSolomon>();\n private lastDelivered = 0;\n private delivered = false;\n\n shardsAccepted = 0;\n shardsRecovered = 0;\n framesDelivered = 0;\n framesLost = 0;\n malformed = 0;\n late = 0;\n /** Shards already held, or arriving for a block already rebuilt. */\n surplus = 0;\n /** This share's loss as the viewer sees it, for `shareFeedback {kind: \"stats\"}`. */\n readonly meter = new ShardLossMeter();\n\n constructor(\n private readonly sink: FrameSink,\n private readonly windowFrames = 16,\n private readonly now: () => number = () => Date.now(),\n ) {}\n\n get pendingFrames(): number {\n return this.pending.size;\n }\n\n /** One decrypted type-3 payload. */\n accept(payload: Uint8Array): void {\n const read = readShardHeader(payload);\n if (!read) {\n this.malformed++;\n return;\n }\n const { header, shardLength, plan } = read;\n this.meter.saw(header, plan, payload.byteLength, this.now());\n\n if (this.delivered) {\n const ahead = distance(header.frameId, this.lastDelivered);\n if (ahead <= 0) {\n this.late++;\n return;\n }\n if (ahead > MAX_FORWARD_JUMP) {\n this.malformed++;\n return;\n }\n }\n\n let frame = this.pending.get(header.frameId);\n if (!frame) {\n frame = { header, shardLength, plan, blocks: new Array(header.blockCount).fill(null), blocksDone: 0, recovered: 0 };\n this.pending.set(header.frameId, frame);\n this.evictBeyondWindow();\n if (!this.pending.has(header.frameId)) {\n this.late++; // older than everything the window still holds: it was the one evicted\n return;\n }\n } else if (!matches(frame, header, shardLength)) {\n this.malformed++;\n return;\n }\n\n let block = frame.blocks[header.blockIndex];\n if (!block) {\n const total = header.dataShards + header.parityShards;\n block = { dataShards: header.dataShards, parityShards: header.parityShards, shards: new Array(total).fill(null), present: new Array(total).fill(false), count: 0, done: false };\n frame.blocks[header.blockIndex] = block;\n }\n if (block.done || block.present[header.shardIndex]) {\n this.surplus++;\n return;\n }\n\n block.shards[header.shardIndex] = payload.slice(SHARD_HEADER_BYTES, SHARD_HEADER_BYTES + shardLength);\n block.present[header.shardIndex] = true;\n block.count++;\n this.shardsAccepted++;\n if (block.count < block.dataShards) return;\n\n this.completeBlock(frame, block, shardLength);\n if (++frame.blocksDone === frame.plan.blockCount) this.deliver(frame);\n }\n\n /** Forgets everything: a share restarting, or the viewer closing it. */\n reset(): void {\n this.pending.clear();\n this.delivered = false;\n }\n\n private completeBlock(frame: PendingFrame, block: BlockState, shardLength: number): void {\n let missing = 0;\n for (let j = 0; j < block.dataShards; j++) {\n if (!block.present[j]) {\n block.shards[j] = new Uint8Array(shardLength);\n missing++;\n }\n }\n if (missing > 0) {\n const key = (block.dataShards << 8) | block.parityShards;\n let code = this.codes.get(key);\n if (!code) {\n code = new ReedSolomon(block.dataShards, block.parityShards);\n this.codes.set(key, code);\n }\n code.reconstruct(block.shards, block.present, shardLength);\n this.shardsRecovered += missing;\n frame.recovered += missing;\n }\n block.done = true;\n }\n\n private deliver(frame: PendingFrame): void {\n const id = frame.header.frameId;\n if (this.delivered && distance(id, this.lastDelivered) > 1) {\n const first = (this.lastDelivered + 1) >>> 0;\n const last = (id - 1) >>> 0;\n const count = distance(last, first) + 1;\n this.framesLost += count;\n this.meter.framesLost(count);\n this.sink.onLost(first, last);\n }\n\n const { plan } = frame;\n const accessUnit = new Uint8Array(plan.frameBytes);\n for (let b = 0; b < plan.blockCount; b++) {\n const block = frame.blocks[b]!;\n const first = plan.firstShardOf(b);\n for (let j = 0; j < block.dataShards; j++) {\n const global = first + j;\n accessUnit.set(block.shards[j]!.subarray(0, plan.bytesIn(global)), global * plan.shardLength);\n }\n }\n\n this.lastDelivered = id;\n this.delivered = true;\n this.framesDelivered++;\n this.meter.frameDelivered();\n // Everything at or behind this frame is now useless to the decoder.\n for (const pendingId of [...this.pending.keys()]) if (distance(pendingId, id) <= 0) this.pending.delete(pendingId);\n\n const flags = frame.header.flags;\n this.sink.onFrame({\n frameId: id,\n timestamp: frame.header.timestamp,\n flags,\n keyframe: (flags & VIDEO_SHARD_FLAG.keyframe) !== 0,\n recoveryPoint: (flags & VIDEO_SHARD_FLAG.recoveryPoint) !== 0,\n endOfShare: (flags & VIDEO_SHARD_FLAG.endOfShare) !== 0,\n recoveredShards: frame.recovered,\n accessUnit,\n });\n }\n\n private evictBeyondWindow(): void {\n while (this.pending.size > this.windowFrames) {\n let oldest: number | null = null;\n for (const id of this.pending.keys()) if (oldest === null || distance(id, oldest) < 0) oldest = id;\n this.pending.delete(oldest!);\n }\n }\n}\n\nfunction matches(frame: PendingFrame, other: ShardHeader, length: number): boolean {\n const h = frame.header;\n const block = frame.blocks[other.blockIndex];\n return (\n length === frame.shardLength &&\n other.frameBytes === h.frameBytes &&\n other.blockCount === h.blockCount &&\n other.flags === h.flags &&\n other.timestamp === h.timestamp &&\n other.streamId === h.streamId &&\n (!block || (block.dataShards === other.dataShards && block.parityShards === other.parityShards))\n );\n}\n","/**\n * The sharer's rate controller for a screen share (contract §19, \"Quality\"). Pure and clock-free:\n * the Worker feeds it viewer reports and its own backpressure, calls `tick` once a second, and\n * applies whatever it returns to the encoder.\n *\n * WHY IT EXISTS. There is one encoding per share and the node forwards it to every viewer, so the\n * sender's bitrate is the whole quality policy. Too high and a slow viewer loses frames FEC cannot\n * rebuild, which is a frozen picture waiting for a keyframe; too low and text blurs for everyone.\n * It is also the cost lever: every bit is paid for again as egress per viewer.\n *\n * THE RULES.\n * - Loss-based, AIMD. FEC absorbs pre-FEC loss up to ~10% (its parity follows the same reports,\n * fecControl.ts: lean on a clean path, ~25% at 10% loss), so that much costs a viewer nothing and\n * is not a reason to cut. Over it, or any residual (unrebuildable) loss, cuts\n * multiplicatively; a clean path climbs 8% a second.\n * - It rates to the LIMITING viewer: the worst one, except that with three or more viewers the\n * single worst is left out, so one viewer on a bad hotel link cannot blur the share for four\n * others. That viewer still gets the stream and recovers on keyframes.\n * - It never climbs past what the encoder is actually producing. A still screen encodes to a\n * fraction of the target, and a clean path at 200 kbps says nothing about 4 Mbit/s; without this\n * the target would ratchet to the ceiling during a quiet slide and flood the path on the next\n * scroll.\n * - Our own send pipe backing up is congestion too, and cuts the same way.\n * - What gives way under pressure is the POLICY, which is the sharer's mode:\n * - `detail` (Screen mode: documents, a desktop, remote control) lowers the frame rate (30, 15,\n * 5) and keeps the resolution, because a readable slide at 5 fps beats a smooth blur.\n * Resolution moves only for a frame too big to send (below).\n * - `motion` (Game mode) keeps the frame rate and steps the resolution down the rungs\n * (1080, 900, 720, 540), because a game at 5 fps is unplayable to watch while a softer\n * picture at 60 is not. Only at the lowest rung does the frame rate give way, to 30 and no\n * lower. On the way back the frame rate returns first, then the resolution.\n * The two differ in what they trade and nothing else: the AIMD loop above is one loop.\n * - One thing moves the resolution under BOTH policies: an encoded frame too big for the wire\n * (`frameTooLarge`). A receiver refuses an access unit over MAX_FRAME_BYTES, so the sender cannot\n * send it at all, and a detailed 4K or 5K screen's keyframe can be 1.2 MB (measured 2026-09-30,\n * card b810b009). Bitrate is a weak lever on that: an IDR's size is set by its pixels and the\n * encoder's keyframe quantiser far more than by the rate target, so the controller caps the\n * encode HEIGHT to a rung whose pixel count brings the frame under FRAME_BYTES_TARGET, and\n * scales the rate by the same pixel ratio so the bits per pixel, and with them the frame rate,\n * are unchanged. The cap holds for the rest of the share: the same screen would produce the same\n * keyframe. Every step is to a strictly lower rung, so it can happen at most once per rung.\n */\n\nimport { MAX_FRAME_BYTES } from \"./shardWire.js\";\nimport { heightForViewers, VIEWER_SHRINK_AFTER_MS, type ViewerBox } from \"./viewerSize.js\";\n\nexport interface ViewerStats {\n loss?: number;\n residualLoss?: number;\n kbps?: number;\n /** The box the viewer shows the share in, device pixels (viewerSize.ts). Absent: the full size. */\n viewWidth?: number;\n viewHeight?: number;\n}\n\n/** What gives way under pressure: frame rate (`detail`, Screen mode) or resolution (`motion`, Game mode). */\nexport type SharePolicy = \"detail\" | \"motion\";\n\nexport interface RateDecision {\n bitrate: number;\n fps: number;\n /**\n * The height to encode at: the share's full height (`setResolution`), or, under the motion\n * policy, a rung below it. The width follows at the full size's aspect ratio.\n */\n height: number;\n /** Why the share is below its ceiling, or null when it is not held down. */\n limitedBy: \"viewer\" | \"network\" | null;\n /** Viewers whose reports are current. */\n viewers: number;\n}\n\nexport interface RateControlOptions {\n maxBitrate: number;\n startBitrate: number;\n maxFps: number;\n minBitrate?: number;\n /** Defaults to `detail`, the behaviour every share had before modes. */\n policy?: SharePolicy;\n}\n\n/** Pre-FEC loss the parity absorbs. */\nexport const LOSS_TOLERATED = 0.1;\n/** Below this the path is called clean and the rate may climb. */\nexport const LOSS_CLEAN = 0.02;\nexport const RESIDUAL_TOLERATED = 0.01;\nexport const INCREASE_PER_SECOND = 1.08;\n/** A viewer who has not reported for this long is not counted. */\nexport const VIEWER_STALE_MS = 5_000;\n/** No climbing for this long after a cut: the cut has not had time to show in the reports. */\nexport const HOLD_AFTER_DECREASE_MS = 2_000;\n/** The target may run this far ahead of what the encoder is really producing, no further. */\nexport const HEADROOM_OVER_SENT = 1.5;\n/** Bits per pixel per frame below which the frame rate steps down (and, with 20% hysteresis, back up). */\nexport const DETAIL_BITS_PER_PIXEL = 0.02;\n/**\n * The motion policy's line: below it the resolution steps down a rung (and, with 20% hysteresis,\n * back up). Higher than detail's because motion defeats H.264's inter-frame prediction: a still\n * desktop reuses almost every block, a game reuses almost none. 1080p60 holds it from 3.7 Mbit/s.\n */\nexport const MOTION_BITS_PER_PIXEL = 0.03;\n/** The motion policy's frame rate floor, reached only at the lowest rung. */\nexport const MOTION_MIN_FPS = 30;\n/** The heights the motion policy steps through, and the lowest it goes. */\nexport const MOTION_RUNGS = [2160, 1440, 1080, 900, 720, 540] as const;\n/**\n * What a frame is aimed at after one came out too big: three quarters of the wire limit, because\n * the next screen may be a little busier than the one that tripped it, and a second drop is a\n * second hitch for every viewer.\n */\nexport const FRAME_BYTES_TARGET = Math.floor(MAX_FRAME_BYTES * 0.75);\n/** The lowest a frame-size cap goes: the bottom of the rungs. */\nexport const FRAME_CAP_MIN_HEIGHT = MOTION_RUNGS[MOTION_RUNGS.length - 1];\n\n/** What `frameTooLarge` did about an encoded frame over the wire limit. */\nexport interface FrameTooLargeDecision {\n /** The encode got smaller (height, or at the lowest rung the rate): false for a frame that was\n * encoded before an earlier step and says nothing new. */\n reduced: boolean;\n /** The height is the encoder's new top: it rebuilds at it on the next frame. */\n decision: RateDecision;\n}\nconst FPS_STEPS = [30, 15, 5];\nconst HYSTERESIS = 1.2;\n/** Changes smaller than this are not worth an encoder reconfigure. */\nconst APPLY_THRESHOLD = 0.05;\n\ninterface Viewer {\n stats: ViewerStats;\n /** The latest window, not the worst: a size is not a loss figure. */\n box: ViewerBox | null;\n at: number;\n /** Not yet decided on. The worst report since the last decision is kept, not the latest. */\n fresh: boolean;\n}\n\nexport class ShareRateController {\n private readonly viewers = new Map<number, Viewer>();\n private o: RateControlOptions;\n private policy: SharePolicy;\n private target: number;\n private fps: number;\n /** The full encode size: the source fitted to the sender's cap. */\n private fullWidth = 0;\n private fullHeight = 0;\n /** The height the motion policy is at; the full height under the detail policy. */\n private height = 0;\n private lastDecreaseAt = Number.NEGATIVE_INFINITY;\n private localCongestionAt = Number.NEGATIVE_INFINITY;\n private applied: RateDecision | null = null;\n private limitedBy: RateDecision[\"limitedBy\"] = null;\n private readonly minBitrate: number;\n /** The configured ceiling, or a lower one while the path cannot carry it (`setCeiling`). */\n private ceiling: number;\n /** The height the biggest viewer's window needs (viewerSize.ts), or 0 for the full size. */\n private viewerHeight = 0;\n /** Since when the windows have needed less than `viewerHeight`: a shrink waits, a growth does not. */\n private smallerSince: number | null = null;\n /** The highest the share may encode at because a frame at more was too big for the wire; 0 for none. */\n private frameCapHeight = 0;\n\n constructor(o: RateControlOptions) {\n this.o = o;\n this.policy = o.policy ?? \"detail\";\n this.minBitrate = o.minBitrate ?? 250_000;\n this.ceiling = o.maxBitrate;\n this.target = clamp(o.startBitrate, this.minBitrate, o.maxBitrate);\n this.fps = o.maxFps;\n }\n\n /**\n * Move the share's ceiling, e.g. when its path moves to the TCP tunnel (a lower ceiling) or back\n * (the configured one). A ceiling below the current rate cuts to it at once and says the network\n * is why; a higher one is only climbed to, like any other headroom.\n */\n setCeiling(maxBitrate: number, now: number): void {\n const ceiling = clamp(maxBitrate, this.minBitrate, this.o.maxBitrate);\n this.ceiling = ceiling;\n if (this.target > ceiling) {\n this.target = ceiling;\n this.lastDecreaseAt = now;\n }\n this.limitedBy = ceiling < this.o.maxBitrate ? \"network\" : this.target >= ceiling * 0.9 ? null : this.limitedBy;\n this.reshape();\n }\n\n /**\n * The sharer switched mode mid-share (Screen and Game). The rate the path has proven is kept,\n * cut to the new ceiling if it is over it; a higher ceiling is climbed to, never jumped to. The\n * frame rate and resolution start again from the new policy's best and settle on the next tick.\n * The caller re-applies any lowered path ceiling (`setCeiling`) after this.\n */\n setPolicy(o: { policy: SharePolicy; maxBitrate: number; maxFps: number }, now: number): void {\n this.o = { ...this.o, ...o };\n this.policy = o.policy;\n this.ceiling = o.maxBitrate;\n if (this.target > o.maxBitrate) {\n this.target = o.maxBitrate;\n this.lastDecreaseAt = now;\n }\n this.target = Math.max(this.minBitrate, this.target);\n this.fps = o.maxFps;\n this.height = this.fullHeight;\n if (this.target >= this.ceiling * 0.9) this.limitedBy = null;\n this.reshape();\n // Whatever was applied belongs to the old policy: the next tick applies afresh.\n this.applied = null;\n }\n\n /**\n * The share's FULL encode size: the source fitted to the sender's resolution cap. Under the\n * detail policy the share encodes at exactly this; under motion, at this or a rung below it.\n */\n setResolution(width: number, height: number): void {\n if (width === this.fullWidth && height === this.fullHeight) return;\n this.fullWidth = width;\n this.fullHeight = height;\n this.height = height;\n this.reshape();\n }\n\n /** A viewer's `shareFeedback {kind: \"stats\"}`, keyed by its `fromConnectionId`. */\n report(viewer: number, stats: ViewerStats, now: number): void {\n // Viewers report and `tick` decides on separate once-a-second timers, so two reports can land\n // between decisions. Keeping only the later one lost a congested second whenever a clean one\n // followed it before the decision (the real-browser e2e caught it as a cut that never came).\n const prev = this.viewers.get(viewer);\n const keep = prev?.fresh && worse(prev.stats, stats) ? prev.stats : stats;\n const box = stats.viewWidth !== undefined && stats.viewHeight !== undefined ? { width: stats.viewWidth, height: stats.viewHeight } : null;\n this.viewers.set(viewer, { stats: keep, box, at: now, fresh: true });\n }\n\n /** The viewer stopped watching. */\n forget(viewer: number): void {\n this.viewers.delete(viewer);\n }\n\n /** Our own send pipe was full and a capture frame was skipped. */\n localCongestion(now: number): void {\n this.localCongestionAt = now;\n }\n\n /**\n * The encoder produced a frame of `frameBytes` at `encodedHeight` that the wire cannot carry\n * (over MAX_FRAME_BYTES). Caps the encode height at the largest rung whose pixels bring such a\n * frame to FRAME_BYTES_TARGET (frame bytes taken as proportional to pixels), and scales the rate\n * by the same pixel ratio. At the lowest rung the rate is the only lever left and takes the whole\n * ratio. A frame encoded ABOVE a cap already in force was queued before that step: it changes\n * nothing and says `reduced: false`, so a burst of stale frames cannot walk the ladder down.\n */\n frameTooLarge(frameBytes: number, encodedHeight: number, now: number): FrameTooLargeDecision {\n const ratio = Math.min(1, FRAME_BYTES_TARGET / Math.max(1, frameBytes));\n const top = this.topHeight();\n const from = encodedHeight > 0 ? encodedHeight : top;\n let reduced = false;\n if (from > 0 && from <= top) {\n const want = from * Math.sqrt(ratio);\n const below = MOTION_RUNGS.filter((r) => r < from);\n const rung = below.find((r) => r <= want) ?? below[below.length - 1];\n if (rung !== undefined) {\n this.frameCapHeight = this.frameCapHeight > 0 ? Math.min(this.frameCapHeight, rung) : rung;\n this.target = Math.max(this.minBitrate, this.target * (rung / from) ** 2);\n reduced = true;\n } else if (this.target > this.minBitrate) {\n this.target = Math.max(this.minBitrate, this.target * ratio);\n reduced = true;\n }\n }\n if (reduced) {\n this.lastDecreaseAt = now;\n this.reshape();\n }\n const decision = this.decision();\n this.applied = decision;\n return { reduced, decision };\n }\n\n /**\n * Once a second. `sentBps` is what the encoder actually produced over the last second. Returns\n * the decision when it moved enough to apply, otherwise null.\n */\n tick(now: number, sentBps: number): RateDecision | null {\n for (const [id, v] of this.viewers) if (now - v.at > VIEWER_STALE_MS) this.viewers.delete(id);\n this.followViewerWindows(now);\n const limiting = this.limitingViewer();\n for (const v of this.viewers.values()) v.fresh = false;\n const congestedHere = now - this.localCongestionAt < 1_000;\n\n const loss = limiting?.loss ?? 0;\n const residual = limiting?.residualLoss ?? 0;\n const viewerOveruse = limiting !== null && (loss > LOSS_TOLERATED || residual > RESIDUAL_TOLERATED);\n\n if (viewerOveruse || congestedHere) {\n const cut = viewerOveruse ? 1 - 0.5 * Math.max(loss, LOSS_TOLERATED) : 0.85;\n let next = this.target * cut;\n // A report of what actually arrived bounds the cut from above: the path took that much.\n if (viewerOveruse && limiting.kbps !== undefined && limiting.kbps > 0) next = Math.min(next, Math.max(limiting.kbps * 1000, this.target * 0.5));\n this.target = Math.max(this.minBitrate, next);\n this.lastDecreaseAt = now;\n this.limitedBy = viewerOveruse ? \"viewer\" : \"network\";\n } else if (loss < LOSS_CLEAN && residual === 0 && now - this.lastDecreaseAt >= HOLD_AFTER_DECREASE_MS) {\n const provenCeiling = Math.max(this.minBitrate, sentBps * HEADROOM_OVER_SENT);\n if (this.target < provenCeiling) this.target = Math.min(this.target * INCREASE_PER_SECOND, provenCeiling);\n this.target = Math.min(this.target, this.ceiling);\n // Held under a lowered ceiling is still held down by the network, however clean the path.\n if (this.target >= this.ceiling * 0.9) this.limitedBy = this.ceiling < this.o.maxBitrate ? \"network\" : null;\n }\n\n this.reshape();\n const decision = this.decision();\n if (!this.worthApplying(decision)) return null;\n this.applied = decision;\n return decision;\n }\n\n /** What the encoder should be doing now. Frame rate and height move the moment the shape does\n * (a new size or a new policy), not only on the next worthwhile tick. */\n get current(): RateDecision {\n return { ...(this.applied ?? this.decision()), fps: this.fps, height: this.height };\n }\n\n private decision(): RateDecision {\n return { bitrate: Math.round(this.target), fps: this.fps, height: this.height, limitedBy: this.limitedBy, viewers: this.viewers.size };\n }\n\n private limitingViewer(): ViewerStats | null {\n const reports = [...this.viewers.values()].map((v) => v.stats);\n if (reports.length === 0) return null;\n reports.sort(byWorst);\n return reports.length >= 3 ? reports[1]! : reports[0]!;\n }\n\n /**\n * The most the viewers' windows need (viewerSize.ts): a larger need applies at once, so a viewer\n * who enlarges or goes full screen gets detail back on the next tick; a smaller one only once it\n * has held for `VIEWER_SHRINK_AFTER_MS`, so a window being dragged costs one rebuild, not ten.\n */\n private followViewerWindows(now: number): void {\n const need = heightForViewers(\n [...this.viewers.values()].map((v) => v.box),\n this.fullWidth,\n this.fullHeight,\n );\n const current = this.viewerHeight || this.fullHeight;\n if (need >= current) {\n this.viewerHeight = need;\n this.smallerSince = null;\n return;\n }\n this.smallerSince ??= now;\n if (now - this.smallerSince >= VIEWER_SHRINK_AFTER_MS) {\n this.viewerHeight = need;\n this.smallerSince = null;\n }\n }\n\n /** The largest height worth encoding: the full size, or less while every viewer's window is\n * smaller, and never above a frame-size cap (`frameTooLarge`). */\n private topHeight(): number {\n const forViewers = this.viewerHeight > 0 ? Math.min(this.fullHeight, this.viewerHeight) : this.fullHeight;\n return this.frameCapHeight > 0 ? Math.min(forViewers, this.frameCapHeight) : forViewers;\n }\n\n /** Frame rate and height for the current target, under the current policy. */\n private reshape(): void {\n if (this.policy === \"motion\") this.motionShape(this.target);\n else {\n this.height = this.topHeight();\n this.fps = this.fpsFor(this.target);\n }\n }\n\n private fpsFor(bitrate: number): number {\n const top = this.topHeight();\n const pixels = this.fullHeight === 0 ? 0 : this.fullWidth * this.fullHeight * (top / this.fullHeight) ** 2;\n const steps = FPS_STEPS.filter((f) => f <= this.o.maxFps);\n if (steps.length === 0 || pixels === 0) return this.o.maxFps;\n const at = (fps: number) => bitrate / (pixels * fps);\n const index = Math.max(0, steps.indexOf(this.fps));\n let i = steps.includes(this.fps) ? index : 0;\n // Step down while this rate cannot hold detail; step up only with 20% to spare.\n while (i < steps.length - 1 && at(steps[i]!) < DETAIL_BITS_PER_PIXEL) i++;\n while (i > 0 && at(steps[i - 1]!) >= DETAIL_BITS_PER_PIXEL * HYSTERESIS) i--;\n return steps[i]!;\n }\n\n /** The top height (full, or what the viewers' windows need), then every rung below it: the\n * motion policy's ladder. */\n private rungs(): number[] {\n if (this.fullHeight === 0) return [0];\n const top = this.topHeight();\n return [top, ...MOTION_RUNGS.filter((r) => r < top)];\n }\n\n private motionShape(bitrate: number): void {\n const rungs = this.rungs();\n const maxFps = this.o.maxFps;\n const floorFps = Math.min(maxFps, MOTION_MIN_FPS);\n if (this.fullHeight === 0) {\n this.height = 0;\n this.fps = maxFps;\n return;\n }\n const aspect = this.fullWidth / this.fullHeight;\n const at = (h: number, fps: number) => bitrate / (h * h * aspect * fps);\n // Where we are: the rung at or just below the current height.\n let i = rungs.findIndex((h) => h <= this.height);\n if (i < 0) i = rungs.length - 1;\n let fps = this.fps === floorFps ? floorFps : maxFps;\n // Down: resolution first, the frame rate only once there is no rung left.\n for (;;) {\n if (at(rungs[i]!, fps) >= MOTION_BITS_PER_PIXEL) break;\n if (i < rungs.length - 1) i++;\n else if (fps > floorFps) fps = floorFps;\n else break;\n }\n // Up, with 20% to spare: the frame rate first, then the resolution.\n for (;;) {\n if (fps < maxFps) {\n if (at(rungs[i]!, maxFps) >= MOTION_BITS_PER_PIXEL * HYSTERESIS) {\n fps = maxFps;\n continue;\n }\n break;\n }\n if (i > 0 && at(rungs[i - 1]!, fps) >= MOTION_BITS_PER_PIXEL * HYSTERESIS) {\n i--;\n continue;\n }\n break;\n }\n this.height = rungs[i]!;\n this.fps = fps;\n }\n\n private worthApplying(d: RateDecision): boolean {\n const a = this.applied;\n if (!a) return true;\n if (a.fps !== d.fps || a.height !== d.height || a.limitedBy !== d.limitedBy || a.viewers !== d.viewers) return true;\n if (d.bitrate === a.bitrate) return false;\n // Reaching a bound is always applied, or a climb that ends 3% short of the ceiling stays short.\n if (d.bitrate === this.ceiling || d.bitrate === this.minBitrate) return true;\n return Math.abs(d.bitrate - a.bitrate) / a.bitrate >= APPLY_THRESHOLD;\n }\n}\n\nconst clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n));\n\n/** Worst first: residual loss is what a viewer sees, pre-FEC loss breaks the tie. */\nconst byWorst = (a: ViewerStats, b: ViewerStats) => (b.residualLoss ?? 0) - (a.residualLoss ?? 0) || (b.loss ?? 0) - (a.loss ?? 0);\nconst worse = (a: ViewerStats, b: ViewerStats) => byWorst(a, b) < 0;\n","import { VIDEO_SHARD_FLAG } from \"../nativeTransport.js\";\nimport { VIEWER_STALE_MS, type ViewerStats } from \"./rateControl.js\";\nimport { MIN_PARITY_SHARDS, PARITY_RATIO, parityAt } from \"./shardWire.js\";\n\n/**\n * The sharer's forward-error-correction controller for a screen share. Pure and clock-free, like\n * the rate controller beside it: the Worker feeds it the same viewer reports, ticks it once a\n * second, and asks it for each block's parity as a frame is sharded.\n *\n * WHY IT EXISTS. The fixed rule (shardWire.ts: 20%, at least 2 shards) protects every frame as if\n * the path lost ~8% of its packets. On a clean path that is pure overhead, paid again as egress per\n * viewer: a 4K share measured on production at ~5 Mbit/s with 0% loss spent a fifth of its bytes on\n * parity nobody used, and small frames paid more (the 2-shard floor is 200% of a 1-shard frame).\n *\n * IT IS SENDER-SIDE ONLY. Every shard names its block's `(dataShards, parityShards)` and a receiver\n * builds its code from those alone (assembler.ts, and Switchboard's `FrameAssembler`), so varying\n * parity per block needs nothing from any viewer or from the node, which forwards sealed datagrams\n * it cannot read. `shareFecWire.test.ts` proves an unchanged assembler decodes it.\n *\n * THE RULES.\n * - No current viewer report (the share just started, or every report went stale): the fixed rule,\n * exactly. Without evidence, today's protection is the safe answer.\n * - Demand from pre-FEC loss: `5% + 2 x loss`, in whole percents rounded up, capped at 30%. Twice\n * the loss leaves room for loss that arrives in bursts rather than evenly; at 7.5% loss this is\n * the fixed rule's 20%, and the rate controller cuts over 10% (where this asks for 25%).\n * - Residual loss (a frame FEC could not rebuild, which the viewer SAW as a frozen picture waiting\n * for a keyframe) steps up fast: at once to at least 20%, then 10 points more per second while\n * frames are still being lost, to the ceiling.\n * - Up at once, down slowly: parity falls only after the demand has stayed below it for 5 s, and\n * then 2 points a second. A noisy path therefore rests at its worst recent second rather than\n * see-sawing, and a single lossy second is answered on the next frame.\n * - The floor is one parity shard per block on a clean path, two once measured loss asks for 10% or\n * more: at a few percent loss a 3-shard frame with one parity shard is lost about once in 70\n * frames, which at 30 fps is a freeze every couple of seconds.\n * - Keyframes and recovery points keep at least the fixed rule. Losing one costs a keyframe round\n * trip (a request, a new IDR, the biggest frame there is), and they are rare enough that their\n * parity is a sliver of the bytes.\n * - It fits the LIMITING viewer the same way the rate controller does: the worst one, except that\n * with three or more viewers the single worst is left out. Parity is paid on every viewer's\n * egress and every viewer's downlink, and the left-out viewer is by definition one the share is\n * not being fitted to (the rate controller will not blur it for them either); they still recover\n * on keyframes, which keep full protection. A viewer that sends no reports at all (Switchboard\n * does not yet) is invisible here, as it is to the rate controller.\n */\n\n/** With nothing to go on: the fixed rule's 20%. */\nexport const FEC_START_RATIO = PARITY_RATIO;\n/** A clean path: one shard in twenty, and never less than one per block. */\nexport const FEC_CLEAN_RATIO = 0.05;\nexport const FEC_LOSS_GAIN = 2;\nexport const FEC_MAX_RATIO = 0.3;\n/** What a keyframe or recovery point always gets at least. */\nexport const FEC_KEYFRAME_RATIO = PARITY_RATIO;\n/** How far one second of residual loss raises the ratio. */\nexport const FEC_RESIDUAL_STEP = 0.1;\nexport const FEC_STEP_DOWN_PER_TICK = 0.02;\n/** The demand must stay below the ratio this long before it falls. */\nexport const FEC_HOLD_BEFORE_DECREASE_MS = 5_000;\n/** At or above this ratio every block carries at least two parity shards, as the fixed rule's do. */\nexport const FEC_TWO_SHARD_FLOOR_FROM = 0.1;\n\n// Ratios are held in whole percents, so a step of 2 is exactly 2 and 20 is exactly the fixed rule's\n// 0.2 once divided back (20 / 100 === 0.2 in IEEE doubles): at the start ratio the parity is\n// byte-identical to parityFor's, which the vectors pin.\nconst pct = (ratio: number) => Math.round(ratio * 100);\nconst START = pct(FEC_START_RATIO);\nconst CLEAN = pct(FEC_CLEAN_RATIO);\nconst MAX = pct(FEC_MAX_RATIO);\nconst KEYFRAME = pct(FEC_KEYFRAME_RATIO);\nconst RESIDUAL_STEP = pct(FEC_RESIDUAL_STEP);\nconst STEP_DOWN = pct(FEC_STEP_DOWN_PER_TICK);\nconst TWO_SHARD_FLOOR_FROM = pct(FEC_TWO_SHARD_FLOOR_FROM);\nconst PROTECTED_FLAGS = VIDEO_SHARD_FLAG.keyframe | VIDEO_SHARD_FLAG.recoveryPoint;\n\ninterface Viewer {\n stats: ViewerStats;\n at: number;\n /** Not yet decided on. The worst report since the last decision is kept, not the latest. */\n fresh: boolean;\n}\n\n/** A fraction in 0..1, or 0 for anything that is not one. */\nconst fraction = (n: number | undefined) => (typeof n === \"number\" && Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : 0);\n\nexport class ShareFecController {\n private readonly viewers = new Map<number, Viewer>();\n private current = START;\n private belowSince: number | null = null;\n\n /** The parity ratio for ordinary frames now, 0..1. */\n get ratio(): number {\n return this.current / 100;\n }\n\n /** A viewer's `shareFeedback {kind: \"stats\"}`, keyed by its `fromConnectionId`. */\n report(viewer: number, stats: ViewerStats, now: number): void {\n // Two reports can land between ticks, as with the rate controller: keep the one that asks more.\n const prev = this.viewers.get(viewer);\n const keep = prev?.fresh && this.demandOf(prev.stats) > this.demandOf(stats) ? prev.stats : stats;\n this.viewers.set(viewer, { stats: keep, at: now, fresh: true });\n }\n\n /** The viewer stopped watching. */\n forget(viewer: number): void {\n this.viewers.delete(viewer);\n }\n\n /** Once a second. Returns true when the ratio moved. */\n tick(now: number): boolean {\n for (const [id, v] of this.viewers) if (now - v.at > VIEWER_STALE_MS) this.viewers.delete(id);\n const demand = this.limitingDemand();\n for (const v of this.viewers.values()) v.fresh = false;\n\n const before = this.current;\n if (demand >= this.current) {\n this.current = demand;\n this.belowSince = null;\n } else {\n this.belowSince ??= now;\n if (now - this.belowSince >= FEC_HOLD_BEFORE_DECREASE_MS) this.current = Math.max(demand, this.current - STEP_DOWN);\n }\n return this.current !== before;\n }\n\n /** Parity shards for a block of `dataShards` in a frame with these shard flags. */\n parityFor(dataShards: number, flags: number): number {\n const percent = (flags & PROTECTED_FLAGS) !== 0 ? Math.max(this.current, KEYFRAME) : this.current;\n const floor = percent >= TWO_SHARD_FLOOR_FROM ? MIN_PARITY_SHARDS : 1;\n return parityAt(dataShards, percent / 100, floor);\n }\n\n /** `parityFor`, bound, for `FrameSharder.shard`'s policy argument. */\n readonly policy = (dataShards: number, flags: number): number => this.parityFor(dataShards, flags);\n\n private limitingDemand(): number {\n const demands = [...this.viewers.values()].map((v) => this.demandOf(v.stats));\n if (demands.length === 0) return START;\n demands.sort((a, b) => b - a);\n return demands.length >= 3 ? demands[1]! : demands[0]!;\n }\n\n /** What one viewer's report asks for, in whole percents. */\n private demandOf(stats: ViewerStats): number {\n // Rounded UP, less a hair so float noise (200 x 0.03 is 6.000000000000001) does not cost a point.\n const fromLoss = Math.min(MAX, CLEAN + Math.ceil(FEC_LOSS_GAIN * 100 * fraction(stats.loss) - 1e-6));\n if (fraction(stats.residualLoss) === 0) return fromLoss;\n return Math.min(MAX, Math.max(fromLoss, START, this.current + RESIDUAL_STEP));\n }\n}\n","import {\n AAD_BYTE_LENGTH,\n AEAD,\n CONTROL_PAYLOAD,\n CONTROL_TYPE,\n FLAG_CONTROL,\n HEADER,\n NATIVE_TRANSPORT_VERSION,\n NODE_SEQUENCE_BASE,\n PAYLOAD,\n PAYLOAD_TYPE,\n} from \"../nativeTransport.js\";\n\n/**\n * The native record layer in WebCrypto, so a browser tab and the desktop renderer seal and open\n * exactly what `server/load-generator/src/probeShared.ts` does with node:crypto (the reference\n * vectors prove it byte for byte). Isomorphic on purpose: no node:crypto, no DOM types.\n *\n * ⚠️ NONCE SAFETY IS THE CALLER'S JOB AND IT IS ONE RULE: exactly ONE `NativeSealer` per\n * `connectionId`, for the life of that connectionId. The nonce is connectionId || sequence under a\n * key many senders share; two sealers under one connectionId repeat nonces, which breaks AES-GCM\n * outright. A restarted Worker re-authenticates and gets a fresh connectionId instead.\n */\n\n/** The slice of SubtleCrypto this module uses. The real one is assignable to it. */\nexport interface ShareSubtle {\n importKey(format: \"raw\", keyData: Uint8Array, algorithm: { name: \"AES-GCM\" }, extractable: false, keyUsages: (\"encrypt\" | \"decrypt\")[]): Promise<object>;\n encrypt(algorithm: { name: \"AES-GCM\"; iv: Uint8Array; additionalData: Uint8Array; tagLength: 128 }, key: object, data: Uint8Array): Promise<ArrayBuffer>;\n decrypt(algorithm: { name: \"AES-GCM\"; iv: Uint8Array; additionalData: Uint8Array; tagLength: 128 }, key: object, data: Uint8Array): Promise<ArrayBuffer>;\n}\n\nexport function defaultSubtle(): ShareSubtle {\n const subtle = (globalThis as { crypto?: { subtle?: ShareSubtle } }).crypto?.subtle;\n if (!subtle) throw new Error(\"WebCrypto is not available here (crypto.subtle needs a secure context)\");\n return subtle;\n}\n\n/** An imported AES-256 key. The raw bytes are not kept. */\nexport interface RecordKey {\n readonly handle: object;\n}\n\nexport async function importRecordKey(raw: Uint8Array, subtle: ShareSubtle = defaultSubtle()): Promise<RecordKey> {\n if (raw.length !== AEAD.KEY_BYTES) throw new RangeError(`a record key is ${AEAD.KEY_BYTES} bytes, not ${raw.length}`);\n return { handle: await subtle.importKey(\"raw\", raw, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]) };\n}\n\nexport function nonceFor(connectionId: number, sequence: bigint): Uint8Array {\n const nonce = new Uint8Array(AEAD.NONCE_BYTES);\n const view = new DataView(nonce.buffer);\n view.setUint32(0, connectionId);\n view.setBigUint64(4, sequence);\n return nonce;\n}\n\nconst EMPTY = new Uint8Array(0);\n\n/** AES-256-GMAC: AES-GCM over EMPTY plaintext, the 19 pre-MAC header bytes as AAD. */\nasync function gmac(subtle: ShareSubtle, key: RecordKey, header19: Uint8Array, connectionId: number, sequence: bigint): Promise<Uint8Array> {\n const tag = await subtle.encrypt({ name: \"AES-GCM\", iv: nonceFor(connectionId, sequence), additionalData: header19, tagLength: 128 }, key.handle, EMPTY);\n return new Uint8Array(tag);\n}\n\nfunction timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;\n return diff === 0;\n}\n\nexport interface SealTarget {\n /** The key's wire id: the header channelId (for a share, `shareKey.id`). */\n channelId: number;\n keyEpoch: number;\n key: RecordKey;\n}\n\n/**\n * Seals this connection's outbound datagrams. Owns the sequence counter, which advances PER SEAL\n * and stays in the client half of the space (below NODE_SEQUENCE_BASE).\n */\nexport class NativeSealer {\n private sequence: bigint;\n\n constructor(\n readonly connectionId: number,\n private readonly senderMacKey: RecordKey,\n private readonly subtle: ShareSubtle = defaultSubtle(),\n firstSequence = 0n,\n ) {\n this.sequence = firstSequence;\n }\n\n /** The sequence the next seal will spend. */\n get nextSequence(): bigint {\n return this.sequence;\n }\n\n private take(): bigint {\n const sequence = this.sequence;\n // Refuse rather than wrap into the node's half: that would reuse a GMAC nonce under the pairwise key.\n if (sequence >= NODE_SEQUENCE_BASE) throw new Error(\"sequence space exhausted: re-authenticate for a fresh connectionId\");\n this.sequence = sequence + 1n;\n return sequence;\n }\n\n private header(flags: number, channelId: number, keyEpoch: number, voiceLevel: number, sequence: bigint, length: number): Uint8Array {\n const packet = new Uint8Array(length);\n const view = new DataView(packet.buffer);\n packet[HEADER.VERSION_FLAGS_OFFSET] = NATIVE_TRANSPORT_VERSION | flags;\n view.setUint32(HEADER.CONNECTION_ID_OFFSET, this.connectionId);\n view.setUint32(HEADER.CHANNEL_ID_OFFSET, channelId);\n packet[HEADER.KEY_EPOCH_OFFSET] = keyEpoch & 0xff;\n packet[HEADER.VOICE_LEVEL_OFFSET] = voiceLevel & 0xff;\n view.setBigUint64(HEADER.SEQUENCE_OFFSET, sequence);\n return packet;\n }\n\n /** One sealed datagram carrying `payload` under `target`. */\n async seal(target: SealTarget, payload: Uint8Array, voiceLevel = 0): Promise<Uint8Array> {\n const sequence = this.take();\n const packet = this.header(0, target.channelId, target.keyEpoch, voiceLevel, sequence, HEADER.LENGTH + payload.length + AEAD.TAG_BYTES);\n const header19 = packet.subarray(0, AAD_BYTE_LENGTH);\n const [mac, sealed] = await Promise.all([\n gmac(this.subtle, this.senderMacKey, header19, this.connectionId, sequence),\n this.subtle.encrypt({ name: \"AES-GCM\", iv: nonceFor(this.connectionId, sequence), additionalData: header19, tagLength: 128 }, target.key.handle, payload),\n ]);\n packet.set(mac, HEADER.SENDER_MAC_OFFSET);\n packet.set(new Uint8Array(sealed), HEADER.LENGTH);\n return packet;\n }\n\n /**\n * A viewer's keepalive (LISTENER_KEEPALIVE_REQUIRED): the datapath forwards nothing to a\n * connection until it has sent something MAC-valid, and forgets idle bindings.\n */\n keepalive(target: SealTarget): Promise<Uint8Array> {\n const payload = new Uint8Array(PAYLOAD.OPUS_OFFSET);\n payload[PAYLOAD.TYPE_OFFSET] = PAYLOAD_TYPE.keepalive;\n return this.seal(target, payload);\n }\n\n /** A path response echoing a verified challenge's token. MAC'd, never channel-sealed. */\n async pathResponse(token: Uint8Array): Promise<Uint8Array> {\n if (token.length !== CONTROL_PAYLOAD.TOKEN_BYTES) throw new RangeError(\"a path token is 8 bytes\");\n const sequence = this.take();\n const packet = this.header(FLAG_CONTROL, 0, 0, 0, sequence, HEADER.LENGTH + CONTROL_PAYLOAD.LENGTH);\n packet[HEADER.LENGTH + CONTROL_PAYLOAD.TYPE_OFFSET] = CONTROL_TYPE.pathResponse;\n packet.set(token, HEADER.LENGTH + CONTROL_PAYLOAD.TOKEN_OFFSET);\n packet.set(await gmac(this.subtle, this.senderMacKey, packet.subarray(0, AAD_BYTE_LENGTH), this.connectionId, sequence), HEADER.SENDER_MAC_OFFSET);\n return packet;\n }\n}\n\nexport interface ParsedHeader {\n versionFlags: number;\n control: boolean;\n connectionId: number;\n channelId: number;\n keyEpoch: number;\n voiceLevel: number;\n sequence: bigint;\n}\n\n/** The cleartext header, or null when the datagram is not a v1 native record. */\nexport function parseHeader(packet: Uint8Array): ParsedHeader | null {\n if (packet.length < HEADER.LENGTH) return null;\n const versionFlags = packet[HEADER.VERSION_FLAGS_OFFSET]!;\n if ((versionFlags & 0x0f) !== NATIVE_TRANSPORT_VERSION || (versionFlags & 0xf0 & ~FLAG_CONTROL) !== 0) return null;\n const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);\n return {\n versionFlags,\n control: (versionFlags & FLAG_CONTROL) !== 0,\n connectionId: view.getUint32(HEADER.CONNECTION_ID_OFFSET),\n channelId: view.getUint32(HEADER.CHANNEL_ID_OFFSET),\n keyEpoch: packet[HEADER.KEY_EPOCH_OFFSET]!,\n voiceLevel: packet[HEADER.VOICE_LEVEL_OFFSET]!,\n sequence: view.getBigUint64(HEADER.SEQUENCE_OFFSET),\n };\n}\n\n/**\n * Opens a forwarded record under `key`. Null when it does not authenticate. The forwarded copy's\n * senderMac is the ORIGINAL sender's, under a key a receiver never holds, so it is not checked.\n * Attribution is the caller's next step: owner(streamId) must equal the header connectionId\n * (STREAM_ATTRIBUTION_REQUIRES_OWNER_CHECK).\n */\nexport async function openRecord(packet: Uint8Array, key: RecordKey, subtle: ShareSubtle = defaultSubtle()): Promise<Uint8Array | null> {\n const header = parseHeader(packet);\n if (!header || header.control || packet.length < HEADER.LENGTH + 1 + AEAD.TAG_BYTES) return null;\n try {\n const plain = await subtle.decrypt(\n { name: \"AES-GCM\", iv: nonceFor(header.connectionId, header.sequence), additionalData: packet.subarray(0, AAD_BYTE_LENGTH), tagLength: 128 },\n key.handle,\n packet.subarray(HEADER.LENGTH),\n );\n return new Uint8Array(plain);\n } catch {\n return null;\n }\n}\n\n/**\n * A node path challenge addressed to this connection, verified: the token to echo, or null when\n * the packet is not a genuine challenge. The node spends the TOP half of the sequence space under\n * the pairwise key, so a \"challenge\" from the client half is forged.\n */\nexport async function readPathChallenge(packet: Uint8Array, connectionId: number, senderMacKey: RecordKey, subtle: ShareSubtle = defaultSubtle()): Promise<Uint8Array | null> {\n const header = parseHeader(packet);\n if (!header || !header.control || packet.length !== HEADER.LENGTH + CONTROL_PAYLOAD.LENGTH) return null;\n if (header.connectionId !== connectionId || header.sequence < NODE_SEQUENCE_BASE) return null;\n if (packet[HEADER.LENGTH + CONTROL_PAYLOAD.TYPE_OFFSET] !== CONTROL_TYPE.pathChallenge) return null;\n const expected = await gmac(subtle, senderMacKey, packet.subarray(0, AAD_BYTE_LENGTH), connectionId, header.sequence);\n if (!timingSafeEqual(expected, packet.subarray(HEADER.SENDER_MAC_OFFSET, HEADER.LENGTH))) return null;\n const start = HEADER.LENGTH + CONTROL_PAYLOAD.TOKEN_OFFSET;\n return packet.slice(start, start + CONTROL_PAYLOAD.TOKEN_BYTES);\n}\n","import type { ControlInput } from \"./control.js\";\n\n/**\n * Remote control, the sharer's side (contract §19 \"Remote control\"): how a viewer's input becomes\n * input on the sharer's real screen. The desktop shell's main process runs this and hands the\n * operations it returns to the injector, which only executes them; everything that decides\n * anything lives here so it is tested without Electron, as the pointer overlay's rules are.\n *\n * What it decides, and why each is here:\n * - WHERE: a position is a fraction of the shared screen, mapped onto that display's bounds.\n * - WHAT IS HELD: every key and button the viewer has pressed and not released, so that ANY end\n * (the viewer letting go, the sharer taking it back, a gap in the counter, the watchdog) lets\n * go of all of them. A key the viewer never releases is a key stuck down on somebody else's\n * computer.\n * - WHAT IS OFF LIMITS: our own windows. The viewer cannot see them (they are kept out of the\n * capture) and must not be able to click them blind: the banner's Stop button, a consent\n * dialog, the app itself. A press or a scroll that lands on one is dropped, and while one of\n * our windows has the keyboard, keys are dropped too. So is the sharer's take-it-back hotkey.\n * - WHAT A KEY TYPES: the viewer's layout may not be the sharer's, so a key is sent as what it\n * TYPES (`KeyboardEvent.key`) where it can be, and as which key it is (`.code`) only for keys\n * that type nothing and for shortcuts.\n */\n\nexport type ControlButton = \"left\" | \"right\" | \"middle\";\n/** The injector's modifier names. */\nexport type ControlModifier = \"shift\" | \"control\" | \"alt\" | \"command\";\n\n/** What the injector executes. Points are in the shell's screen coordinates (DIP). */\nexport type ControlOp =\n | { op: \"move\"; x: number; y: number }\n /** A move with a button held: macOS needs a drag event, or nothing under the mouse follows. */\n | { op: \"drag\"; x: number; y: number; b: ControlButton }\n | { op: \"button\"; b: ControlButton; down: boolean }\n /** macOS: one click marked as the second of a double click (its click count is not a timer). */\n | { op: \"double\"; b: ControlButton }\n /** In the injector's own units (pixels on macOS, wheel units on Windows, wheel notches on X11). */\n | { op: \"scroll\"; dx: number; dy: number }\n /** `name` is the injector's key name; when it has no key for a character it types it instead. */\n | { op: \"key\"; name: string; down: boolean; mods: ControlModifier[] }\n | { op: \"type\"; text: string };\n\nexport interface ControlRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface ControlTarget {\n /** `linux` means an X11 session: a Wayland desktop cannot be controlled at all (linuxDesktop.ts). */\n platform: \"darwin\" | \"win32\" | \"linux\";\n /** Where the shared picture is on the real screen: a display's bounds, or (a followed window,\n * 2026-10-05) a function asked at each event, which answers null while the window cannot take\n * input (minimised, closed). Then presses, moves and wheels are dropped; a release still lets\n * go, at the last place the window was. */\n display: ControlRect | (() => ControlRect | null);\n /** Our own windows' bounds, right now. */\n ownWindows: () => ControlRect[];\n /** One of our own windows has the keyboard. (A followed window's shell also answers true while\n * the shared window does not have it: the viewer must not type into a window they cannot see.) */\n ownWindowFocused: () => boolean;\n /** A followed window only: whether a press at this point lands on the shared window itself and\n * not on another window covering it, which the viewer cannot see. Absent: a whole screen. */\n onPicture?: (p: { x: number; y: number }) => boolean;\n}\n\n/** The sharer's take-it-back shortcut, as an Electron accelerator and as the keys it is. */\nexport function revokeShortcut(platform: ControlTarget[\"platform\"]): { accelerator: string; label: string; mods: ControlModifier[] } {\n // Not plain Esc: the viewer needs Esc for the app they are driving. Not Ctrl+Shift+Esc on\n // Windows, which the system keeps for Task Manager, nor Cmd+Option+Esc on macOS (Force Quit).\n // Not Ctrl+Alt+Esc on Linux either: KDE Plasma (SteamOS's desktop mode) binds it to \"kill a\n // window\", so the desktop would take the press, the shell could not register it, and pressing it\n // would turn the cursor into a window killer instead of taking control back.\n if (platform === \"darwin\") return { accelerator: \"Command+Shift+Escape\", label: \"⌘ Shift Esc\", mods: [\"command\", \"shift\"] };\n if (platform === \"linux\") return { accelerator: \"Control+Alt+Shift+Escape\", label: \"Ctrl Alt Shift Esc\", mods: [\"control\", \"alt\", \"shift\"] };\n return { accelerator: \"Control+Alt+Escape\", label: \"Ctrl Alt Esc\", mods: [\"control\", \"alt\"] };\n}\n\nconst MODIFIER_CODES: Record<string, { name: string; mod: ControlModifier }> = {\n ShiftLeft: { name: \"shift\", mod: \"shift\" },\n ShiftRight: { name: \"right_shift\", mod: \"shift\" },\n ControlLeft: { name: \"control\", mod: \"control\" },\n ControlRight: { name: \"right_control\", mod: \"control\" },\n AltLeft: { name: \"alt\", mod: \"alt\" },\n AltRight: { name: \"right_alt\", mod: \"alt\" },\n MetaLeft: { name: \"command\", mod: \"command\" },\n MetaRight: { name: \"command\", mod: \"command\" },\n};\n\n/** Keys that type nothing, by which key they are. */\nconst NAMED_CODES: Record<string, string> = {\n Backspace: \"backspace\",\n Delete: \"delete\",\n Enter: \"enter\",\n NumpadEnter: \"enter\",\n Tab: \"tab\",\n Escape: \"escape\",\n ArrowUp: \"up\",\n ArrowDown: \"down\",\n ArrowLeft: \"left\",\n ArrowRight: \"right\",\n Home: \"home\",\n End: \"end\",\n PageUp: \"pageup\",\n PageDown: \"pagedown\",\n Space: \"space\",\n Insert: \"insert\",\n CapsLock: \"capslock\",\n ContextMenu: \"menu\",\n PrintScreen: \"printscreen\",\n NumpadAdd: \"numpad_+\",\n NumpadSubtract: \"numpad_-\",\n NumpadMultiply: \"numpad_*\",\n NumpadDivide: \"numpad_/\",\n NumpadDecimal: \"numpad_.\",\n};\nfor (let i = 1; i <= 24; i++) NAMED_CODES[`F${i}`] = `f${i}`;\nfor (let i = 0; i <= 9; i++) NAMED_CODES[`Numpad${i}`] = `numpad_${i}`;\n\n/** Which key, for a shortcut: the US character on it. */\nconst SHORTCUT_CODES: Record<string, string> = {\n Minus: \"-\",\n Equal: \"=\",\n BracketLeft: \"[\",\n BracketRight: \"]\",\n Backslash: \"\\\\\",\n Semicolon: \";\",\n Quote: \"'\",\n Backquote: \"`\",\n Comma: \",\",\n Period: \".\",\n Slash: \"/\",\n};\n\n/**\n * The injector key for a viewer's key, or text to type, or null for a key that does nothing on\n * its own (a dead key, an input method's placeholder: what it composes arrives as `text`).\n * `shortcut`: a modifier other than Shift is held, so which key it is matters more than what it\n * would type (Ctrl+C is C whatever the layout, and Option+C on a Mac types a character the\n * sharer's Option+C already would).\n */\nexport function mapControlKey(code: string, key: string, shortcut: boolean): { name: string } | { text: string } | null {\n const named = NAMED_CODES[code];\n if (named) return { name: named };\n if (shortcut) {\n const letter = /^Key([A-Z])$/.exec(code);\n if (letter) return { name: letter[1]!.toLowerCase() };\n const digit = /^Digit([0-9])$/.exec(code);\n if (digit) return { name: digit[1]! };\n const punct = SHORTCUT_CODES[code];\n if (punct) return { name: punct };\n }\n const chars = [...key];\n if (chars.length !== 1 || key < \" \" || key === \"\\u007f\") return null;\n if (/^[A-Za-z]$/.test(key)) return { name: key.toLowerCase() };\n // A character the injector may or may not have a key for on this layout: it tries the key and\n // types the character if there is none.\n return { name: key };\n}\n\n/** Browser wheel pixels in one X11 wheel notch: a mouse wheel reports about 100 a click. */\nexport const X11_PIXELS_PER_NOTCH = 100;\n/** The most notches one wheel event may press on X11. */\nconst X11_MAX_NOTCHES = 10;\n\nconst clampInt = (v: number, lo: number, hi: number) => Math.round(Math.min(hi, Math.max(lo, v)));\n\nfunction inside(r: ControlRect, x: number, y: number): boolean {\n return x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height;\n}\n\n/**\n * One grant's input, as operations. Holds what is pressed so {@link releaseAll} can let go of it.\n */\nexport class ControlInputModel {\n private readonly buttons = new Set<ControlButton>();\n /** Held keys by `code`, with the injector name they went down as (the up must match it). */\n private readonly keys = new Map<string, { name: string; mod: ControlModifier | null }>();\n /** macOS: the second press of a double click, sent as one marked click on its release. */\n private readonly pendingDouble = new Set<ControlButton>();\n private readonly revoke: ControlModifier[];\n /** X11: wheel movement not yet worth a whole notch, carried to the next event (see `notches`). */\n private notchCarry = { x: 0, y: 0 };\n\n constructor(private readonly target: ControlTarget) {\n this.revoke = revokeShortcut(target.platform).mods;\n }\n\n /** The last place the shared picture was, so a release can still let go when it is gone. */\n private lastArea: ControlRect | null = null;\n\n /** Where a fraction of the picture lands now, or null when the picture is nowhere to click. */\n private point(fx: number, fy: number): { x: number; y: number } | null {\n const target = this.target.display;\n const d = typeof target === \"function\" ? target() : target;\n if (!d || d.width <= 0 || d.height <= 0) return null;\n this.lastArea = d;\n return { x: d.x + clampInt(fx * d.width, 0, d.width - 1), y: d.y + clampInt(fy * d.height, 0, d.height - 1) };\n }\n\n /** Where a release lands: now, or the last place the picture was. */\n private releasePoint(fx: number, fy: number): { x: number; y: number } | null {\n const p = this.point(fx, fy);\n if (p) return p;\n const d = this.lastArea;\n return d ? { x: d.x + clampInt(fx * d.width, 0, d.width - 1), y: d.y + clampInt(fy * d.height, 0, d.height - 1) } : null;\n }\n\n private blocked(p: { x: number; y: number }): boolean {\n if (this.target.onPicture && !this.target.onPicture(p)) return true;\n return this.target.ownWindows().some((r) => inside(r, p.x, p.y));\n }\n\n private mods(): ControlModifier[] {\n const out = new Set<ControlModifier>();\n for (const k of this.keys.values()) if (k.mod) out.add(k.mod);\n return [...out];\n }\n\n private moveTo(p: { x: number; y: number }): ControlOp {\n const held = [...this.buttons][0];\n return held ? { op: \"drag\", x: p.x, y: p.y, b: held } : { op: \"move\", x: p.x, y: p.y };\n }\n\n /** What is held right now (for a test, and for the banner's \"keys held\" safety check). */\n held(): { buttons: ControlButton[]; keys: string[] } {\n return { buttons: [...this.buttons], keys: [...this.keys.keys()] };\n }\n\n apply(ev: ControlInput): ControlOp[] {\n switch (ev.k) {\n case \"move\": {\n const p = this.point(ev.x, ev.y);\n return p ? [this.moveTo(p)] : [];\n }\n case \"down\": {\n const p = this.point(ev.x, ev.y);\n if (!p || this.blocked(p) || this.buttons.has(ev.b) || this.pendingDouble.has(ev.b)) return [];\n if (this.target.platform === \"darwin\" && ev.c >= 2) {\n this.pendingDouble.add(ev.b);\n return [this.moveTo(p)];\n }\n const ops: ControlOp[] = [this.moveTo(p), { op: \"button\", b: ev.b, down: true }];\n this.buttons.add(ev.b);\n return ops;\n }\n case \"up\": {\n const p = this.releasePoint(ev.x, ev.y);\n if (this.pendingDouble.delete(ev.b)) return p ? [this.moveTo(p), { op: \"double\", b: ev.b }] : [];\n if (!this.buttons.has(ev.b)) return [];\n const ops: ControlOp[] = p ? [this.moveTo(p)] : [];\n this.buttons.delete(ev.b);\n ops.push({ op: \"button\", b: ev.b, down: false });\n return ops;\n }\n case \"wheel\": {\n const p = this.point(ev.x, ev.y);\n if (!p || this.blocked(p)) return [];\n // The browser's delta is positive DOWN (and right); the injectors' is positive up (and left).\n // Windows counts wheel units of 120 a notch where a browser reports about 100 pixels.\n if (this.target.platform === \"linux\") return this.notches(p, -ev.dx, -ev.dy);\n const scale = this.target.platform === \"win32\" ? 1.2 : 1;\n const dx = Math.round(-ev.dx * scale);\n const dy = Math.round(-ev.dy * scale);\n if (dx === 0 && dy === 0) return [];\n return [this.moveTo(p), { op: \"scroll\", dx, dy }];\n }\n case \"key\":\n return ev.d ? this.keyDown(ev.code, ev.key) : this.keyUp(ev.code);\n case \"text\":\n return this.target.ownWindowFocused() ? [] : [{ op: \"type\", text: ev.s }];\n }\n }\n\n /**\n * X11 has no smooth scroll to inject: the injector presses the wheel \"button\" once per unit, so\n * a unit is a whole NOTCH (about {@link X11_PIXELS_PER_NOTCH} browser pixels), and passing pixels\n * through would scroll a hundred notches for one. A trackpad reports a few pixels at a time,\n * which rounds to no notch at all, so the remainder is carried until it adds up rather than\n * dropped. Capped per event so one flung wheel cannot queue a long run of presses; what the cap\n * cuts off is dropped, not carried.\n */\n private notches(p: { x: number; y: number }, px: number, py: number): ControlOp[] {\n const take = (carry: number, delta: number): [number, number] => {\n const total = carry + delta / X11_PIXELS_PER_NOTCH;\n const whole = Math.trunc(total);\n const capped = Math.max(-X11_MAX_NOTCHES, Math.min(X11_MAX_NOTCHES, whole));\n // `+ 0` turns a -0 (a still axis, negated) into 0, so an op never carries a signed zero.\n return [capped + 0, capped === whole ? total - whole : 0];\n };\n const [dx, cx] = take(this.notchCarry.x, px);\n const [dy, cy] = take(this.notchCarry.y, py);\n this.notchCarry = { x: cx, y: cy };\n if (dx === 0 && dy === 0) return [];\n return [this.moveTo(p), { op: \"scroll\", dx, dy }];\n }\n\n private keyDown(code: string, key: string): ControlOp[] {\n if (this.target.ownWindowFocused()) return this.releaseKeys();\n if (this.keys.has(code)) return []; // auto-repeat arrives as more downs: the OS repeats on its own\n const modifier = MODIFIER_CODES[code];\n if (modifier) {\n const ops: ControlOp[] = [{ op: \"key\", name: modifier.name, down: true, mods: this.mods() }];\n this.keys.set(code, { name: modifier.name, mod: modifier.mod });\n return ops;\n }\n const mods = this.mods();\n if (code === \"Escape\" && this.revoke.every((m) => mods.includes(m))) return [];\n const mapped = mapControlKey(code, key, mods.some((m) => m !== \"shift\"));\n if (!mapped) return [];\n if (\"text\" in mapped) return [{ op: \"type\", text: mapped.text }];\n this.keys.set(code, { name: mapped.name, mod: null });\n return [{ op: \"key\", name: mapped.name, down: true, mods }];\n }\n\n private keyUp(code: string): ControlOp[] {\n const held = this.keys.get(code);\n if (!held) return [];\n this.keys.delete(code);\n return [{ op: \"key\", name: held.name, down: false, mods: this.mods() }];\n }\n\n private releaseKeys(): ControlOp[] {\n const ops: ControlOp[] = [];\n // Ordinary keys first, then the modifiers, so nothing is released as a shortcut.\n for (const [code, k] of [...this.keys].filter(([, k]) => !k.mod)) {\n this.keys.delete(code);\n ops.push({ op: \"key\", name: k.name, down: false, mods: this.mods() });\n }\n for (const [code, k] of [...this.keys]) {\n this.keys.delete(code);\n ops.push({ op: \"key\", name: k.name, down: false, mods: this.mods() });\n }\n return ops;\n }\n\n /** Let go of everything: buttons, then keys. Called on every end and on a counter gap. */\n releaseAll(): ControlOp[] {\n const ops: ControlOp[] = [];\n this.pendingDouble.clear();\n for (const b of this.buttons) ops.push({ op: \"button\", b, down: false });\n this.buttons.clear();\n ops.push(...this.releaseKeys());\n return ops;\n }\n}\n","import {\n CONTROL_CONSENT_MS,\n CONTROL_KEEPALIVE_MS,\n CONTROL_SEND_INTERVAL_MS,\n MAX_CONTROL_EVENTS_PER_BATCH,\n describeControlDeny,\n describeControlEnd,\n finishControlRequest,\n startControlRequest,\n type ControlCrypto,\n type ControlInput,\n type ControlMessage,\n type ControlPairing,\n type ControlRequest,\n} from \"./control.js\";\n\n/**\n * Remote control, the viewer's side (contract §19 \"Remote control\"): ask, show the code, and while\n * in control, send input in batches. Runs in the web UI (a tab or the desktop app alike: anybody\n * can drive, only a desktop app can be driven). Pure but for its timers, which are injected.\n *\n * Input is batched to one message every {@link CONTROL_SEND_INTERVAL_MS}: moves coalesce (only\n * the last position of a batch matters), while a press, a release or a key goes out at once, since\n * a click that waits 16 ms behind a move is a click that lands late. With nothing to send, a\n * keepalive goes every {@link CONTROL_KEEPALIVE_MS}, or the sharer's watchdog ends control.\n *\n * A request that gets no answer gives up on its own: {@link CONTROL_OFFER_WAIT_MS} for the offer\n * (a sharer's app that does not know the frame, or a node that dropped it, never answers), then\n * the consent dialog's own time and a margin for the grant.\n */\n\nexport const CONTROL_OFFER_WAIT_MS = 8_000;\nconst GRANT_WAIT_MS = CONTROL_CONSENT_MS + 5_000;\n\nexport type ControlViewerState =\n | { kind: \"idle\" }\n /** Waiting for the sharer. `code` once the exchange has one. */\n | { kind: \"asking\"; code: string | null }\n | { kind: \"controlling\"; code: string }\n /** It did not start, or it stopped: in words. */\n | { kind: \"ended\"; text: string };\n\nexport interface ControlViewerDeps {\n /** Seal and send to the sharer's datapath id. */\n send(message: ControlMessage): void;\n changed(state: ControlViewerState): void;\n setTimer(fn: () => void, ms: number): unknown;\n clearTimer(handle: unknown): void;\n now(): number;\n crypto?: ControlCrypto;\n}\n\nexport class ControlViewer {\n private state: ControlViewerState = { kind: \"idle\" };\n private request: ControlRequest | null = null;\n private pairing: ControlPairing | null = null;\n private pending: ControlInput[] = [];\n private flushTimer: unknown = null;\n private keepaliveTimer: unknown = null;\n private answerTimer: unknown = null;\n private lastSent = 0;\n private queue: Promise<void> = Promise.resolve();\n\n constructor(\n private readonly streamId: number,\n private readonly self: number,\n /** The sharer's datapath id, and their name for the words. */\n private readonly sharer: { connectionId: number; callsign: string },\n private readonly deps: ControlViewerDeps,\n ) {}\n\n current(): ControlViewerState {\n return this.state;\n }\n\n private set(state: ControlViewerState): void {\n this.state = state;\n this.deps.changed(state);\n }\n\n private enqueue(work: () => void | Promise<void>): Promise<void> {\n this.queue = this.queue.then(work).catch(() => undefined);\n return this.queue;\n }\n\n /** Ask to control. A request already in progress, or control already on, is left as it is. */\n ask(): Promise<void> {\n return this.enqueue(async () => {\n if (this.state.kind === \"asking\" || this.state.kind === \"controlling\") return;\n try {\n this.request = await startControlRequest(this.deps.crypto);\n } catch {\n // The queue swallows a throw, so without this the Control button did nothing and said\n // nothing (no WebCrypto X25519 here, or no secure context).\n this.set({ kind: \"ended\", text: `Could not ask ${this.sharer.callsign} for control: this app cannot make the secure code remote control needs.` });\n return;\n }\n this.pairing = null;\n this.set({ kind: \"asking\", code: null });\n this.waitForAnswer(CONTROL_OFFER_WAIT_MS);\n this.deps.send(this.request.commit);\n });\n }\n\n /** A message from the sharer, out of its envelope. */\n handle(message: ControlMessage): Promise<void> {\n return this.enqueue(() => this.step(message));\n }\n\n private async step(m: ControlMessage): Promise<void> {\n const req = this.request;\n if (!req || m.sid !== req.sid) return;\n switch (m.t) {\n case \"offer\": {\n if (this.state.kind !== \"asking\" || this.pairing) return;\n try {\n const { pairing, reveal } = await finishControlRequest(req, m, { streamId: this.streamId, viewer: this.self, sharer: this.sharer.connectionId }, this.deps.crypto);\n this.pairing = pairing;\n this.set({ kind: \"asking\", code: pairing.code });\n this.waitForAnswer(GRANT_WAIT_MS);\n this.deps.send(reveal);\n } catch {\n this.stop({ kind: \"ended\", text: describeControlDeny(\"failed\", this.sharer.callsign) }, \"error\");\n }\n return;\n }\n case \"grant\": {\n if (this.state.kind !== \"asking\" || !this.pairing) return;\n const opened = await this.pairing.channel.open(m.box);\n const v = opened?.value as { t?: unknown } | undefined;\n if (v?.t !== \"grant\") return;\n this.clearAnswerTimer();\n this.set({ kind: \"controlling\", code: this.pairing.code });\n this.lastSent = this.deps.now();\n this.armKeepalive();\n return;\n }\n case \"deny\":\n if (this.state.kind === \"asking\") this.stop({ kind: \"ended\", text: describeControlDeny(m.reason, this.sharer.callsign) }, null);\n return;\n case \"end\":\n if (this.state.kind === \"asking\" || this.state.kind === \"controlling\") this.stop({ kind: \"ended\", text: describeControlEnd(m.reason, this.sharer.callsign) }, null);\n return;\n default:\n return;\n }\n }\n\n /** Let go (or stop asking). */\n release(): Promise<void> {\n return this.enqueue(async () => {\n if (this.state.kind !== \"asking\" && this.state.kind !== \"controlling\") return;\n if (this.state.kind === \"controlling\") await this.flush();\n this.stop({ kind: \"ended\", text: describeControlEnd(\"released\", this.sharer.callsign) }, \"released\");\n });\n }\n\n /** The share went away: stop without a word to the sharer (there is nobody to tell). */\n close(): void {\n if (this.state.kind === \"asking\" || this.state.kind === \"controlling\") this.stop({ kind: \"idle\" }, null);\n }\n\n /** Clear an \"ended\" message once it has been read. */\n dismiss(): void {\n if (this.state.kind === \"ended\") this.set({ kind: \"idle\" });\n }\n\n private waitForAnswer(ms: number): void {\n this.clearAnswerTimer();\n const request = this.request;\n this.answerTimer = this.deps.setTimer(() => {\n this.answerTimer = null;\n void this.enqueue(() => {\n if (this.request === request && this.state.kind === \"asking\") this.stop({ kind: \"ended\", text: describeControlDeny(\"timeout\", this.sharer.callsign) }, \"released\");\n });\n }, ms);\n }\n\n private clearAnswerTimer(): void {\n if (this.answerTimer !== null) this.deps.clearTimer(this.answerTimer);\n this.answerTimer = null;\n }\n\n private stop(next: ControlViewerState, tell: \"released\" | \"error\" | null): void {\n this.clearAnswerTimer();\n const sid = this.request?.sid;\n this.request = null;\n this.pairing = null;\n this.pending = [];\n if (this.flushTimer !== null) this.deps.clearTimer(this.flushTimer);\n if (this.keepaliveTimer !== null) this.deps.clearTimer(this.keepaliveTimer);\n this.flushTimer = this.keepaliveTimer = null;\n this.set(next);\n if (tell && sid) this.deps.send({ t: \"end\", sid, reason: tell });\n }\n\n /** One piece of input. Dropped unless in control. */\n input(ev: ControlInput): void {\n if (this.state.kind !== \"controlling\") return;\n const last = this.pending.at(-1);\n if (ev.k === \"move\" && last?.k === \"move\") this.pending[this.pending.length - 1] = ev;\n else this.pending.push(ev);\n const urgent = ev.k !== \"move\" && ev.k !== \"wheel\";\n if (urgent || this.pending.length >= MAX_CONTROL_EVENTS_PER_BATCH) {\n void this.enqueue(() => this.flush());\n } else if (this.flushTimer === null) {\n this.flushTimer = this.deps.setTimer(() => {\n this.flushTimer = null;\n void this.enqueue(() => this.flush());\n }, CONTROL_SEND_INTERVAL_MS);\n }\n }\n\n private async flush(): Promise<void> {\n const pairing = this.pairing;\n const req = this.request;\n if (this.state.kind !== \"controlling\" || !pairing || !req) return;\n if (this.flushTimer !== null) {\n this.deps.clearTimer(this.flushTimer);\n this.flushTimer = null;\n }\n const ev = this.pending.splice(0, MAX_CONTROL_EVENTS_PER_BATCH);\n const box = await pairing.channel.seal({ ev });\n if (this.pairing !== pairing) return;\n this.lastSent = this.deps.now();\n this.deps.send({ t: \"in\", sid: req.sid, box });\n if (this.pending.length) void this.enqueue(() => this.flush());\n }\n\n private armKeepalive(): void {\n const beat = () => {\n this.keepaliveTimer = null;\n if (this.state.kind !== \"controlling\") return;\n if (this.deps.now() - this.lastSent >= CONTROL_KEEPALIVE_MS - 50) void this.enqueue(() => this.flush());\n this.keepaliveTimer = this.deps.setTimer(beat, CONTROL_KEEPALIVE_MS / 2);\n };\n this.keepaliveTimer = this.deps.setTimer(beat, CONTROL_KEEPALIVE_MS / 2);\n }\n}\n","import { z } from \"zod\";\nimport { HandleSchema, PublicDisplayNameSchema } from \"./api.js\";\nimport { UserSummarySchema } from \"./responses.js\";\nimport { ScopeSchema } from \"./scopes.js\";\n\n/**\n * Agent accounts (contract §25, capability `agents`): the wire shapes of registration, the key\n * exchange and an agent's own keys.\n *\n * An agent is an ordinary account (`UserSummary.kind = \"agent\"`) whose only credential is a\n * key. `POST /v1/agents/register` creates one and hands back its first key and a session;\n * `POST /v1/auth/agent` turns a key into the same 15-minute access token every app carries.\n * There are no refresh tokens for an agent: re-exchange the key. Everything after that is the\n * ordinary API.\n */\n\nexport const AGENT_KEY_LABEL_MAX = 100;\n\n/** What the operator calls the key: a machine, a deployment, a purpose. Shown back in the key list. */\nexport const AgentKeyLabelSchema = z.string().trim().min(1).max(AGENT_KEY_LABEL_MAX);\n\nexport const RegisterAgentBodySchema = z.object({\n handle: HandleSchema.describe(\"The agent's callsign, shown to everyone beside its badge. Same grammar and profanity screen as a person's.\"),\n displayName: PublicDisplayNameSchema.optional().describe(\"Optional. Defaults to the Station ID the server issues.\"),\n label: AgentKeyLabelSchema.describe(\"A label for the first key, for example the machine or deployment that will hold it.\"),\n ageConfirmed: z\n .boolean()\n .describe(\n \"Must be true. The OPERATOR running this agent attests that they are at least 18 / the age of majority in their jurisdiction. Recorded durably against the account, like a person's attestation on their first frequency.\",\n ),\n termsAccepted: z.boolean().describe(\"Must be true. The operator accepts the Terms of Service on the agent's behalf; recorded durably.\"),\n});\nexport type RegisterAgentBody = z.infer<typeof RegisterAgentBodySchema>;\n\nexport const AgentKeySummarySchema = z.object({\n id: z.string(),\n label: z.string(),\n scopes: z.array(ScopeSchema).describe(\"The scopes a token minted from this key carries. Every user scope today.\"),\n createdAt: z.iso.datetime(),\n expiresAt: z.iso.datetime().describe(\"A year after minting. Mint a replacement before this and delete the old one; minting never revokes.\"),\n lastUsedAt: z.iso.datetime().nullable().describe(\"The last exchange, to the minute. Null until the key has been used.\"),\n revokedAt: z.iso.datetime().nullable(),\n});\nexport type AgentKeySummary = z.infer<typeof AgentKeySummarySchema>;\n\nexport const AgentKeyListSchema = z.object({\n keys: z.array(AgentKeySummarySchema).describe(\"Newest first, revoked and expired ones included so a deletion can be seen.\"),\n liveKeysMax: z.number().int().describe(\"How many live (unrevoked, unexpired) keys the account may hold at once.\"),\n});\nexport type AgentKeyList = z.infer<typeof AgentKeyListSchema>;\n\nexport const MintAgentKeyBodySchema = z.object({ label: AgentKeyLabelSchema });\nexport type MintAgentKeyBody = z.infer<typeof MintAgentKeyBodySchema>;\n\nexport const MintedAgentKeySchema = z.object({\n key: AgentKeySummarySchema,\n secret: z\n .string()\n .describe(\n \"The key itself, prefixed `ftag_`. Shown exactly ONCE: the server keeps only a hash. Store it outside any repository and never log it.\",\n ),\n});\nexport type MintedAgentKey = z.infer<typeof MintedAgentKeySchema>;\n\nexport const AgentAuthBodySchema = z.object({\n key: z.string().min(16).max(256).describe(\"An agent account key, as minted by registration or `POST /v1/agents/me/keys`.\"),\n});\nexport type AgentAuthBody = z.infer<typeof AgentAuthBodySchema>;\n\nexport const AgentSessionSchema = z.object({\n accessToken: z.string().describe(\"Short-lived bearer token. Send as `Authorization: Bearer <token>`.\"),\n tokenType: z.literal(\"Bearer\"),\n expiresIn: z.number().int().describe(\"Seconds until the token expires. Exchange the key again before then; there is no refresh token.\"),\n expiresAt: z.iso.datetime(),\n user: UserSummarySchema,\n});\nexport type AgentSession = z.infer<typeof AgentSessionSchema>;\n\nexport const AgentRegistrationSchema = AgentSessionSchema.extend({\n key: AgentKeySummarySchema,\n secret: MintedAgentKeySchema.shape.secret,\n});\nexport type AgentRegistration = z.infer<typeof AgentRegistrationSchema>;\n\n/** How many agents one person may sponsor (contract §25, \"Sponsored agents\"). */\nexport const SPONSORED_AGENTS_MAX = 5;\n\nexport const SponsoredAgentSchema = z.object({\n user: UserSummarySchema,\n createdAt: z.iso.datetime(),\n keys: z.array(AgentKeySummarySchema).describe(\"Every key the agent has held, newest first; the secret is in none of them.\"),\n});\nexport type SponsoredAgent = z.infer<typeof SponsoredAgentSchema>;\n\nexport const SponsoredAgentListSchema = z.object({\n agents: z.array(SponsoredAgentSchema),\n max: z.number().int().describe(\"How many agents one person may sponsor.\"),\n});\nexport type SponsoredAgentList = z.infer<typeof SponsoredAgentListSchema>;\n\nexport const SponsoredAgentCreatedSchema = z.object({\n user: UserSummarySchema,\n createdAt: z.iso.datetime(),\n key: AgentKeySummarySchema,\n secret: MintedAgentKeySchema.shape.secret,\n});\nexport type SponsoredAgentCreated = z.infer<typeof SponsoredAgentCreatedSchema>;\n","import { z } from \"zod\";\n\n/**\n * Prepaid credit (docs/work-orders/machine-payments.md; capability `credit-balance` at\n * 0.124.0, contract §26). The wire shapes of a balance and its ledger. Everything is in US\n * cents, signed on the ledger: positive credits the account, negative debits it.\n */\n\nexport const CREDIT_LEDGER_KINDS = [\"topup_mpp\", \"topup_x402\", \"debit_frequency_day\", \"refund\", \"adjustment\", \"promo\"] as const;\nexport type CreditLedgerKind = (typeof CREDIT_LEDGER_KINDS)[number];\nexport const CreditLedgerKindSchema = z.enum(CREDIT_LEDGER_KINDS);\n\nexport const SUBSCRIPTION_FUNDINGS = [\"stripe\", \"credit\"] as const;\nexport type SubscriptionFunding = (typeof SUBSCRIPTION_FUNDINGS)[number];\n\n/** The smallest top-up a rail accepts (Stripe's Shared Payment Token floor), and the largest one we take. */\nexport const CREDIT_MIN_TOPUP_CENTS = 50;\nexport const CREDIT_MAX_TOPUP_CENTS = 50_000;\n\nexport const CreditLedgerEntrySchema = z.object({\n id: z.string(),\n kind: CreditLedgerKindSchema,\n amountCents: z.number().int().describe(\"Signed: positive credits the account, negative debits it.\"),\n externalRef: z.string().nullable().describe(\"The rail's reference for a top-up, `frequency:<id>:day:<yyyy-mm-dd>` for a daily debit; null for an operator row.\"),\n rail: z.string().nullable(),\n subscriptionId: z.string().nullable(),\n frequencyId: z.string().nullable(),\n planKey: z.string().nullable(),\n memo: z.string().nullable(),\n createdAt: z.iso.datetime(),\n});\nexport type CreditLedgerEntry = z.infer<typeof CreditLedgerEntrySchema>;\n\nexport const CreditBalanceSchema = z.object({\n balanceCents: z.number().int().describe(\"The account's prepaid credit, in US cents. Can be negative only after an operator refund or adjustment.\"),\n currency: z.literal(\"usd\"),\n /** How the credit is spent, so a program can plan: one UTC day of a credit-funded frequency's plan at a time. */\n dailyDebitCents: z.object({ operator: z.number().int(), broadcast: z.number().int() }).describe(\"What one day of each plan costs, in cents, as the sweeper debits it. Thirty-one days sum to the monthly price.\"),\n minTopupCents: z.number().int(),\n maxTopupCents: z.number().int(),\n rails: z.array(z.string()).describe(\"The payment methods this server offers in a top-up challenge, by mppx method name (`stripe`, `tempo`, `evm`; `fake` on a development server). Empty when it takes no machine payments.\"),\n ledger: z.array(CreditLedgerEntrySchema).describe(\"The newest movements, newest first.\"),\n});\nexport type CreditBalance = z.infer<typeof CreditBalanceSchema>;\n\n/**\n * One UTC day of a plan, in cents, such that a month's worth of days sums exactly to the\n * monthly price: the remainder of priceCents / daysInMonth is spread one cent at a time over\n * the first `remainder` days of the month, so no day is more than a cent off its neighbours\n * and the month closes on the price. `day` is the day of month (1-based) and `daysInMonth`\n * the month's length.\n */\nexport function dailyDebitCents(priceCents: number, day: number, daysInMonth: number): number {\n const base = Math.floor(priceCents / daysInMonth);\n const remainder = priceCents - base * daysInMonth;\n return base + (day <= remainder ? 1 : 0);\n}\n\n/** Days in the UTC month of `date`. */\nexport function daysInUtcMonth(date: Date): number {\n return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)).getUTCDate();\n}\n\n/** The idempotency key of one frequency's one-day debit. */\nexport function frequencyDayRef(frequencyId: string, dayUtc: Date): string {\n return `frequency:${frequencyId}:day:${dayUtc.toISOString().slice(0, 10)}`;\n}\n\nexport const TopupBodySchema = z.object({\n amountCents: z.number().int().min(CREDIT_MIN_TOPUP_CENTS).max(CREDIT_MAX_TOPUP_CENTS).describe(\"US cents to add to the balance.\"),\n});\nexport type TopupBody = z.infer<typeof TopupBodySchema>;\n\nexport const TopupReceiptSchema = z.object({\n balanceCents: z.number().int().describe(\"The balance after this top-up.\"),\n creditedCents: z.number().int(),\n replayed: z.boolean().describe(\"True when this receipt had already been credited and nothing moved.\"),\n receipt: z.object({ method: z.string(), reference: z.string().describe(\"The card PaymentIntent id or the chain transaction hash.\") }),\n entryId: z.string().describe(\"The ledger row.\"),\n});\nexport type TopupReceipt = z.infer<typeof TopupReceiptSchema>;\n","/**\n * The native UDP transport RECORD LAYER: the normative seal/open codec for\n * nativeTransport.ts, moved verbatim out of server/load-generator/src/probeShared.ts (the\n * reference client, which re-exports it) so the vectors, the probes and any Node-side\n * sender share ONE implementation.\n *\n * ⚠️ This module imports node:crypto. It is published ONLY as the subpath\n * `@frequency/shared/native-codec` and must never be re-exported from src/index.ts, which the\n * client bundles for the browser.\n */\n\nimport { createCipheriv, createDecipheriv } from \"node:crypto\";\nimport {\n AEAD,\n CONTENT_KEY_PAYLOAD,\n FLAG_CONTENT_KEY,\n HEADER,\n NATIVE_TRANSPORT_VERSION,\n NATIVE_TRANSPORT_WIRE_V2,\n PAYLOAD,\n PAYLOAD_TYPE,\n} from \"../nativeTransport.js\";\n\n// ---------------------------------------------------------------------------------------\n// Wire helpers — the normative shapes, built straight from @frequency/shared's constants so\n// this file cannot drift from the contract without a compile-visible diff.\n// ---------------------------------------------------------------------------------------\n\n/** nonce = connectionId(4) ‖ sequence(8). The uniqueness of THIS pair under a channel key is\n * the invariant the entire record layer rests on (nativeTransport.ts). */\nexport function nonceFor(connectionId: number, sequence: bigint): Buffer {\n const nonce = Buffer.alloc(AEAD.NONCE_BYTES);\n nonce.writeUInt32BE(connectionId, 0);\n nonce.writeBigUInt64BE(sequence, 4);\n return nonce;\n}\n\n/** AES-256-GMAC: AES-GCM over EMPTY plaintext with the 19 pre-MAC header bytes as AAD. */\nexport function gmac(key: Buffer, header19: Buffer, connectionId: number, sequence: bigint): Buffer {\n const cipher = createCipheriv(\"aes-256-gcm\", key, nonceFor(connectionId, sequence));\n cipher.setAAD(header19);\n cipher.final();\n return cipher.getAuthTag();\n}\n\nexport interface SealArgs {\n connectionId: number;\n channelNativeId: number;\n keyEpoch: number;\n sequence: bigint;\n voiceLevel: number;\n channelKey: Buffer;\n senderMacKey: Buffer;\n payload: Buffer;\n /** Byte 0. Defaults to a v1 audio packet (version 1, no flags). Wire v2 passes\n * NATIVE_TRANSPORT_WIRE_V2 for audio (sealed under the content key, `channelKey` is then\n * `K_s`) and NATIVE_TRANSPORT_WIRE_V2 | FLAG_CONTENT_KEY for a key packet. */\n versionFlags?: number;\n}\n\n/** Wire v2 AUDIO: the frame sealed once under the content key `K_s`. channelNativeId is the\n * stream's HOME wire id (a routing anchor) and the epoch byte is the content-key generation,\n * contentKeyId's low byte. */\nexport function sealV2Audio(a: Omit<SealArgs, \"channelKey\" | \"keyEpoch\" | \"versionFlags\"> & { contentKey: Buffer; contentKeyId: number }): Buffer {\n return seal({ ...a, channelKey: a.contentKey, keyEpoch: a.contentKeyId & 0xff, versionFlags: NATIVE_TRANSPORT_WIRE_V2 });\n}\n\n/** A wire-v2 key packet's plaintext: type 2, streamId, timestamp, contentKeyId, then `K_s`. */\nexport function contentKeyPayload(streamId: number, timestamp: number, contentKeyId: number, contentKey: Buffer): Buffer {\n const payload = Buffer.alloc(CONTENT_KEY_PAYLOAD.LENGTH);\n payload[CONTENT_KEY_PAYLOAD.TYPE_OFFSET] = PAYLOAD_TYPE.contentKey;\n payload.writeUInt32BE(streamId, CONTENT_KEY_PAYLOAD.STREAM_ID_OFFSET);\n payload.writeUInt32BE(timestamp >>> 0, CONTENT_KEY_PAYLOAD.TIMESTAMP_OFFSET);\n payload.writeUInt32BE(contentKeyId >>> 0, CONTENT_KEY_PAYLOAD.CONTENT_KEY_ID_OFFSET);\n contentKey.copy(payload, CONTENT_KEY_PAYLOAD.KEY_OFFSET);\n return payload;\n}\n\n/** Wire v2 KEY PACKET: `K_s` wrapped under one carrying channel's key, with that channel's id\n * and epoch in the header exactly as v1 audio has them. One per carrying channel, and always\n * one for the HOME channel (HOME_CHANNEL_WRAP_REQUIRED). */\nexport function sealKeyPacket(\n a: Omit<SealArgs, \"payload\" | \"versionFlags\"> & { streamId: number; timestamp: number; contentKeyId: number; contentKey: Buffer },\n): Buffer {\n return seal({\n ...a,\n payload: contentKeyPayload(a.streamId, a.timestamp, a.contentKeyId, a.contentKey),\n versionFlags: NATIVE_TRANSPORT_WIRE_V2 | FLAG_CONTENT_KEY,\n });\n}\n\nexport function seal(a: SealArgs): Buffer {\n const header = Buffer.alloc(HEADER.LENGTH);\n header[HEADER.VERSION_FLAGS_OFFSET] = a.versionFlags ?? NATIVE_TRANSPORT_VERSION; // v1 default: no flags, an audio packet\n header.writeUInt32BE(a.connectionId, HEADER.CONNECTION_ID_OFFSET);\n header.writeUInt32BE(a.channelNativeId, HEADER.CHANNEL_ID_OFFSET);\n header[HEADER.KEY_EPOCH_OFFSET] = a.keyEpoch;\n header[HEADER.VOICE_LEVEL_OFFSET] = a.voiceLevel;\n header.writeBigUInt64BE(a.sequence, HEADER.SEQUENCE_OFFSET);\n\n const header19 = header.subarray(0, HEADER.SENDER_MAC_OFFSET);\n gmac(a.senderMacKey, header19, a.connectionId, a.sequence).copy(header, HEADER.SENDER_MAC_OFFSET);\n\n const cipher = createCipheriv(\"aes-256-gcm\", a.channelKey, nonceFor(a.connectionId, a.sequence));\n cipher.setAAD(header19); // the WHOLE pre-MAC header is authenticated, not just part of it\n const ciphertext = Buffer.concat([cipher.update(a.payload), cipher.final()]);\n return Buffer.concat([header, ciphertext, cipher.getAuthTag()]);\n}\n\nexport function open(packet: Buffer, channelKey: Buffer): { streamId: number; timestamp: number; type: number; opus: Buffer } {\n const header19 = packet.subarray(0, HEADER.SENDER_MAC_OFFSET);\n const connectionId = packet.readUInt32BE(HEADER.CONNECTION_ID_OFFSET);\n const sequence = packet.readBigUInt64BE(HEADER.SEQUENCE_OFFSET);\n const body = packet.subarray(HEADER.LENGTH, packet.length - AEAD.TAG_BYTES);\n const tag = packet.subarray(packet.length - AEAD.TAG_BYTES);\n\n const decipher = createDecipheriv(\"aes-256-gcm\", channelKey, nonceFor(connectionId, sequence));\n decipher.setAAD(header19);\n decipher.setAuthTag(tag);\n const payload = Buffer.concat([decipher.update(body), decipher.final()]);\n return {\n type: payload[PAYLOAD.TYPE_OFFSET]!,\n streamId: payload.readUInt32BE(PAYLOAD.STREAM_ID_OFFSET),\n timestamp: payload.readUInt32BE(PAYLOAD.TIMESTAMP_OFFSET),\n opus: payload.subarray(PAYLOAD.OPUS_OFFSET),\n };\n}\n\nexport function audioPayload(streamId: number, timestamp: number, opus: Buffer): Buffer {\n const payload = Buffer.alloc(PAYLOAD.OPUS_OFFSET + opus.length);\n payload[PAYLOAD.TYPE_OFFSET] = PAYLOAD_TYPE.audio;\n payload.writeUInt32BE(streamId, PAYLOAD.STREAM_ID_OFFSET);\n payload.writeUInt32BE(timestamp, PAYLOAD.TIMESTAMP_OFFSET);\n opus.copy(payload, PAYLOAD.OPUS_OFFSET);\n return payload;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { FRAME_SAMPLES, SAMPLE_RATE, createOpus, type OpusCodec } from \"./audio/opus.js\";\nimport { downmix, readWav } from \"./audio/wav.js\";\nimport { frames, resample } from \"./audio/resample.js\";\nimport type { NativeSession } from \"./audio/native.js\";\n\n/**\n * Speaking on a frequency: PCM in (a WAV file, or samples an agent rendered with its own TTS),\n * Opus frames out on the native session at a real-time pace, one every 20 ms. The session is\n * told the stream starts and ends around it, so the roster shows the agent on air exactly\n * while it speaks.\n */\nexport class Speaker {\n private codec: OpusCodec | null = null;\n\n constructor(private readonly session: NativeSession) {}\n\n private async opus(): Promise<OpusCodec> {\n this.codec ??= await createOpus();\n return this.codec;\n }\n\n /** Speak 16-bit mono PCM at `sampleRate`; resampled to 48 kHz. */\n async speakPcm(samples: Int16Array, sampleRate: number, options: { relayChannelIds?: string[] } = {}): Promise<void> {\n const codec = await this.opus();\n const pcm = resample(samples, sampleRate, SAMPLE_RATE);\n await this.session.startTalking({ relayChannelIds: options.relayChannelIds });\n try {\n const started = Date.now();\n let i = 0;\n for (const frame of frames(pcm, FRAME_SAMPLES)) {\n this.session.sendOpusFrame(codec.encode(frame), options.relayChannelIds);\n i += 1;\n const due = started + i * 20;\n const wait = due - Date.now();\n if (wait > 0) await new Promise((r) => setTimeout(r, wait));\n }\n } finally {\n this.session.stopTalking();\n }\n }\n\n /** Speak a WAV file (16-bit PCM, any rate, mono or stereo). */\n async speakWav(path: string, options: { relayChannelIds?: string[] } = {}): Promise<void> {\n const wav = readWav(await readFile(path));\n await this.speakPcm(downmix(wav.samples, wav.channels), wav.sampleRate, options);\n }\n\n close(): void {\n this.codec?.close();\n this.codec = null;\n }\n}\n","/**\n * Opus for the native transport: 48 kHz mono, 20 ms frames, 32 kbps, in-band FEC on, DTX off\n * (the voice profile the media node and the Switchboard engine agree on). `opusscript` (pure\n * WebAssembly, no native build) is the default; `@discordjs/opus` is used when it is installed\n * and loads, for the lower CPU cost. Both expose encode/decode over 16-bit PCM.\n */\n\nexport const SAMPLE_RATE = 48_000;\nexport const CHANNELS = 1;\nexport const FRAME_MS = 20;\nexport const FRAME_SAMPLES = (SAMPLE_RATE * FRAME_MS) / 1000;\nexport const BITRATE = 32_000;\n\nexport interface OpusCodec {\n encode(pcm: Int16Array): Buffer;\n decode(packet: Buffer): Int16Array;\n /** Packet-loss concealment for one missing frame. */\n conceal(): Int16Array;\n close(): void;\n}\n\ntype DiscordOpus = { new (rate: number, channels: number): { encode(buf: Buffer): Buffer; decode(buf: Buffer): Buffer; setBitrate(b: number): void; applyEncoderCTL(ctl: number, value: number): void; delete?(): void } };\ntype OpusScript = {\n new (rate: number, channels: number, application: number, options?: { wasm?: boolean }): { encode(buf: Buffer, frameSize: number): Buffer; decode(buf: Buffer): Buffer; encoderCTL(ctl: number, value: number): void; delete(): void };\n Application: { VOIP: number; AUDIO: number };\n};\n\nconst CTL_SET_BITRATE = 4002;\nconst CTL_SET_INBAND_FEC = 4012;\nconst CTL_SET_DTX = 4016;\n\n// The native codec is optional and NOT a dependency of this package: a user who wants it installs\n// it beside us. The specifier is a variable so that neither tsc nor the bundler resolves it.\nconst NATIVE_OPUS = \"@discordjs/opus\";\n\nexport async function createOpus(): Promise<OpusCodec> {\n try {\n const mod = (await import(/* @vite-ignore */ NATIVE_OPUS)) as unknown as { OpusEncoder: DiscordOpus };\n const enc = new mod.OpusEncoder(SAMPLE_RATE, CHANNELS);\n enc.setBitrate(BITRATE);\n enc.applyEncoderCTL(CTL_SET_INBAND_FEC, 1);\n enc.applyEncoderCTL(CTL_SET_DTX, 0);\n return {\n encode: (pcm) => enc.encode(Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength)),\n decode: (packet) => toInt16(enc.decode(packet)),\n conceal: () => new Int16Array(FRAME_SAMPLES),\n close: () => enc.delete?.(),\n };\n } catch {\n const mod = (await import(\"opusscript\")) as unknown as { default: OpusScript };\n const Opus = mod.default;\n const codec = new Opus(SAMPLE_RATE, CHANNELS, Opus.Application.VOIP, { wasm: true });\n codec.encoderCTL(CTL_SET_BITRATE, BITRATE);\n codec.encoderCTL(CTL_SET_INBAND_FEC, 1);\n codec.encoderCTL(CTL_SET_DTX, 0);\n return {\n encode: (pcm) => codec.encode(Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength), FRAME_SAMPLES),\n decode: (packet) => toInt16(codec.decode(packet)),\n conceal: () => new Int16Array(FRAME_SAMPLES),\n close: () => codec.delete(),\n };\n }\n}\n\nfunction toInt16(buf: Buffer): Int16Array {\n return new Int16Array(buf.buffer, buf.byteOffset, Math.floor(buf.byteLength / 2));\n}\n","/**\n * WAV in and out: 16-bit PCM, any rate and channel count on read (callers resample and\n * downmix); 48 kHz mono on write. Enough for an agent that plays a file it rendered and\n * records what it heard; not a general audio library.\n */\n\nexport interface WavData {\n sampleRate: number;\n channels: number;\n samples: Int16Array;\n}\n\nexport function readWav(buf: Buffer): WavData {\n if (buf.toString(\"ascii\", 0, 4) !== \"RIFF\" || buf.toString(\"ascii\", 8, 12) !== \"WAVE\") throw new Error(\"not a RIFF/WAVE file\");\n let offset = 12;\n let format: { channels: number; sampleRate: number; bits: number } | null = null;\n while (offset + 8 <= buf.length) {\n const id = buf.toString(\"ascii\", offset, offset + 4);\n const size = buf.readUInt32LE(offset + 4);\n const body = offset + 8;\n if (id === \"fmt \") {\n const audioFormat = buf.readUInt16LE(body);\n if (audioFormat !== 1) throw new Error(`unsupported WAV format ${audioFormat}: only 16-bit PCM`);\n format = { channels: buf.readUInt16LE(body + 2), sampleRate: buf.readUInt32LE(body + 4), bits: buf.readUInt16LE(body + 14) };\n if (format.bits !== 16) throw new Error(`unsupported WAV bit depth ${format.bits}: only 16-bit PCM`);\n } else if (id === \"data\") {\n if (!format) throw new Error(\"WAV data before fmt\");\n const end = Math.min(buf.length, body + size);\n const bytes = buf.subarray(body, end - ((end - body) % 2));\n const samples = new Int16Array(bytes.length / 2);\n for (let i = 0; i < samples.length; i++) samples[i] = bytes.readInt16LE(i * 2);\n return { sampleRate: format.sampleRate, channels: format.channels, samples };\n }\n offset = body + size + (size % 2);\n }\n throw new Error(\"WAV has no data chunk\");\n}\n\nexport function writeWav(samples: Int16Array, sampleRate = 48_000, channels = 1): Buffer {\n const dataBytes = samples.length * 2;\n const buf = Buffer.alloc(44 + dataBytes);\n buf.write(\"RIFF\", 0, \"ascii\");\n buf.writeUInt32LE(36 + dataBytes, 4);\n buf.write(\"WAVE\", 8, \"ascii\");\n buf.write(\"fmt \", 12, \"ascii\");\n buf.writeUInt32LE(16, 16);\n buf.writeUInt16LE(1, 20);\n buf.writeUInt16LE(channels, 22);\n buf.writeUInt32LE(sampleRate, 24);\n buf.writeUInt32LE(sampleRate * channels * 2, 28);\n buf.writeUInt16LE(channels * 2, 32);\n buf.writeUInt16LE(16, 34);\n buf.write(\"data\", 36, \"ascii\");\n buf.writeUInt32LE(dataBytes, 40);\n for (let i = 0; i < samples.length; i++) buf.writeInt16LE(samples[i]!, 44 + i * 2);\n return buf;\n}\n\n/** Interleaved multichannel to mono by averaging. */\nexport function downmix(samples: Int16Array, channels: number): Int16Array {\n if (channels === 1) return samples;\n const out = new Int16Array(Math.floor(samples.length / channels));\n for (let i = 0; i < out.length; i++) {\n let sum = 0;\n for (let c = 0; c < channels; c++) sum += samples[i * channels + c]!;\n out[i] = Math.round(sum / channels);\n }\n return out;\n}\n","/**\n * Linear resampling, mono 16-bit. Good enough for speech between the common rates (8, 16,\n * 22.05, 44.1 and 48 kHz); an agent that cares about fidelity renders at 48 kHz to begin with.\n */\nexport function resample(samples: Int16Array, from: number, to: number): Int16Array {\n if (from === to) return samples;\n const ratio = from / to;\n const out = new Int16Array(Math.floor(samples.length / ratio));\n for (let i = 0; i < out.length; i++) {\n const pos = i * ratio;\n const i0 = Math.floor(pos);\n const i1 = Math.min(i0 + 1, samples.length - 1);\n const frac = pos - i0;\n out[i] = Math.round(samples[i0]! * (1 - frac) + samples[i1]! * frac);\n }\n return out;\n}\n\n/** Splits a mono stream into exact 20 ms frames at 48 kHz, zero-padding the last. */\nexport function frames(samples: Int16Array, frameSamples = 960): Int16Array[] {\n const out: Int16Array[] = [];\n for (let i = 0; i < samples.length; i += frameSamples) {\n const frame = new Int16Array(frameSamples);\n frame.set(samples.subarray(i, Math.min(i + frameSamples, samples.length)));\n out.push(frame);\n }\n return out;\n}\n","import { FRAME_SAMPLES, createOpus, type OpusCodec } from \"./audio/opus.js\";\nimport { writeWav } from \"./audio/wav.js\";\nimport type { NativeSession } from \"./audio/native.js\";\n\n/**\n * Hearing a frequency: Opus frames from the native session, one jitter buffer per stream,\n * decoded to 48 kHz mono PCM with packet-loss concealment for the gaps, and recorded into a\n * WAV an agent can hand to its speech recogniser. Streams are mixed by summing with clipping;\n * the stream ids and owners are kept so a transcript can say who spoke.\n */\nexport interface Heard {\n streamId: number;\n connectionId: number;\n samples: Int16Array;\n firstTimestamp: number;\n}\n\nexport class Listener {\n private codec: OpusCodec | null = null;\n private readonly streams = new Map<number, { connectionId: number; chunks: Int16Array[]; lastTimestamp: number | null; first: number }>();\n private detach: (() => void) | null = null;\n\n constructor(private readonly session: NativeSession) {}\n\n /** Start recording everything the session hears. */\n async start(): Promise<void> {\n this.codec ??= await createOpus();\n const codec = this.codec;\n const handler = (frame: { streamId: number; timestamp: number; opus: Buffer; connectionId: number }) => {\n let s = this.streams.get(frame.streamId);\n if (!s) {\n s = { connectionId: frame.connectionId, chunks: [], lastTimestamp: null, first: frame.timestamp };\n this.streams.set(frame.streamId, s);\n }\n if (s.lastTimestamp !== null) {\n // Fill a gap with concealment, one frame per missing 20 ms, capped so a long silence\n // (a talkspurt boundary) does not become minutes of padding.\n const missing = Math.min(50, Math.round((frame.timestamp - s.lastTimestamp) / FRAME_SAMPLES) - 1);\n for (let i = 0; i < missing; i++) s.chunks.push(codec.conceal());\n }\n s.chunks.push(codec.decode(frame.opus));\n s.lastTimestamp = frame.timestamp;\n };\n this.detach = this.session.attachAudio(handler);\n }\n\n /** Stop and return what was heard, per stream. */\n stop(): Heard[] {\n this.detach?.();\n this.detach = null;\n const heard: Heard[] = [];\n for (const [streamId, s] of this.streams) {\n const total = s.chunks.reduce((n, c) => n + c.length, 0);\n const samples = new Int16Array(total);\n let at = 0;\n for (const c of s.chunks) {\n samples.set(c, at);\n at += c.length;\n }\n heard.push({ streamId, connectionId: s.connectionId, samples, firstTimestamp: s.first });\n }\n this.streams.clear();\n return heard;\n }\n\n /** Everything heard, mixed to one 48 kHz mono WAV. */\n static mixToWav(heard: Heard[]): Buffer {\n const length = Math.max(0, ...heard.map((h) => h.samples.length));\n const mix = new Int16Array(length);\n for (const h of heard) {\n for (let i = 0; i < h.samples.length; i++) {\n const v = mix[i]! + h.samples[i]!;\n mix[i] = v > 32767 ? 32767 : v < -32768 ? -32768 : v;\n }\n }\n return writeWav(mix, 48_000, 1);\n }\n\n close(): void {\n this.detach?.();\n this.codec?.close();\n this.codec = null;\n }\n}\n","import { FrequencyClient, type FrequencyClientOptions } from \"./client.js\";\nimport { Realtime, type RealtimeOptions } from \"./realtime.js\";\nimport { Frequencies } from \"./api/frequencies.js\";\nimport { Contacts } from \"./api/contacts.js\";\nimport { Chat } from \"./chat.js\";\nimport { Calls } from \"./calls.js\";\nimport { NativeSession, type NativeSessionOptions } from \"./audio/native.js\";\nimport { Speaker } from \"./speaker.js\";\nimport { Listener } from \"./listener.js\";\n\n/**\n * One object that holds everything: the client, the socket, the typed modules, and the\n * native sessions it has open. `await Agent.connect({ baseUrl, key })` and go.\n */\nexport interface AgentOptions extends FrequencyClientOptions {\n realtime?: RealtimeOptions;\n}\n\nexport class Agent {\n readonly client: FrequencyClient;\n readonly realtime: Realtime;\n readonly frequencies: Frequencies;\n readonly contacts: Contacts;\n readonly chat: Chat;\n readonly calls: Calls;\n private readonly sessions = new Map<string, NativeSession>();\n\n private constructor(options: AgentOptions) {\n this.client = new FrequencyClient(options);\n this.realtime = new Realtime(this.client, options.realtime);\n this.frequencies = new Frequencies(this.client);\n this.contacts = new Contacts(this.client);\n this.chat = new Chat(this.client, this.realtime);\n this.calls = new Calls(this.client, this.realtime);\n }\n\n /** Sign in with the key and open the socket. */\n static async connect(options: AgentOptions): Promise<Agent> {\n const agent = new Agent(options);\n await agent.client.signIn();\n await agent.realtime.connect();\n return agent;\n }\n\n /** A native audio session on a frequency, opened once and reused. */\n async session(frequencyId: string, options: NativeSessionOptions & { transmitIntent?: boolean } = {}): Promise<NativeSession> {\n const existing = this.sessions.get(frequencyId);\n if (existing) return existing;\n const session = new NativeSession(this.client, this.frequencies, frequencyId, options);\n await session.open({ transmitIntent: options.transmitIntent ?? true });\n this.sessions.set(frequencyId, session);\n this.realtime.subscribe(frequencyId);\n return session;\n }\n\n async closeSession(frequencyId: string): Promise<void> {\n const session = this.sessions.get(frequencyId);\n if (!session) return;\n this.sessions.delete(frequencyId);\n await session.close();\n }\n\n speaker(session: NativeSession): Speaker {\n return new Speaker(session);\n }\n\n listener(session: NativeSession): Listener {\n return new Listener(session);\n }\n\n async close(): Promise<void> {\n for (const id of [...this.sessions.keys()]) await this.closeSession(id);\n this.realtime.close();\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\n/**\n * Where the key comes from, in order: the `FREQUENCY_AGENT_KEY` environment variable, then\n * `~/.config/frequencytalk/agent.json` (`{ \"key\": \"ftag_...\", \"baseUrl\"?: \"...\" }`), then the\n * file `npm run agent:account` writes (`~/.config/frequency/agent-account.json`, which carries\n * `secret`). Never argv: a key on a command line is in every process listing and shell history.\n */\nexport interface AgentKeySource {\n key: string;\n baseUrl: string;\n source: \"env\" | \"config\" | \"account-file\";\n}\n\nexport const DEFAULT_BASE_URL = \"https://frequencytalk.com\";\n\nexport async function loadKey(options: { baseUrl?: string } = {}): Promise<AgentKeySource> {\n const envKey = process.env.FREQUENCY_AGENT_KEY;\n const envUrl = options.baseUrl ?? process.env.FREQUENCY_BASE_URL;\n if (envKey) return { key: envKey, baseUrl: envUrl ?? DEFAULT_BASE_URL, source: \"env\" };\n for (const [path, field, source] of [\n [join(homedir(), \".config\", \"frequencytalk\", \"agent.json\"), \"key\", \"config\"],\n [join(homedir(), \".config\", \"frequency\", \"agent-account.json\"), \"secret\", \"account-file\"],\n ] as const) {\n try {\n const parsed = JSON.parse(await readFile(path, \"utf8\")) as Record<string, unknown>;\n const key = parsed[field];\n if (typeof key === \"string\" && key.startsWith(\"ftag_\")) {\n const fileUrl = typeof parsed.baseUrl === \"string\" ? parsed.baseUrl : undefined;\n return { key, baseUrl: envUrl ?? fileUrl ?? DEFAULT_BASE_URL, source };\n }\n } catch {\n // not there, or not ours\n }\n }\n throw new Error(\"No agent key: set FREQUENCY_AGENT_KEY, or write ~/.config/frequencytalk/agent.json, or run `npm run agent:account` in the Frequency repo.\");\n}\n","import { writeFile } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { Agent } from \"../agent.js\";\nimport { PaymentRequired } from \"../client.js\";\nimport { Listener } from \"../listener.js\";\nimport { Speaker } from \"../speaker.js\";\n\n/**\n * The tools, named by surface: `frequency_*`, `contacts_*`, `chat_*`, `call_*`, `audio_*`,\n * `credit_*`. Each answers plain text the model can read, and never a key.\n */\n\nconst IDLE_CLOSE_MS = 60_000;\n\nfunction text(value: unknown): { content: Array<{ type: \"text\"; text: string }> } {\n return { content: [{ type: \"text\", text: typeof value === \"string\" ? value : JSON.stringify(value, null, 2) }] };\n}\n\nasync function run<T>(fn: () => Promise<T>): Promise<{ content: Array<{ type: \"text\"; text: string }>; isError?: boolean }> {\n try {\n return text(await fn());\n } catch (err) {\n if (err instanceof PaymentRequired) {\n return { ...text({ paymentRequired: true, error: err.error, challenge: err.challenge }), isError: true };\n }\n return { ...text(err instanceof Error ? `${err.name}: ${err.message}` : String(err)), isError: true };\n }\n}\n\nexport function registerTools(server: McpServer, agent: Agent): void {\n const idleTimers = new Map<string, NodeJS.Timeout>();\n const touch = (frequencyId: string) => {\n const existing = idleTimers.get(frequencyId);\n if (existing) clearTimeout(existing);\n const t = setTimeout(() => void agent.closeSession(frequencyId), IDLE_CLOSE_MS);\n t.unref?.();\n idleTimers.set(frequencyId, t);\n };\n\n server.tool(\"whoami\", \"The signed-in agent: callsign, Station ID, kind, and the balance that pays for it.\", {}, async () =>\n run(async () => ({ me: await agent.client.me(), credit: await agent.client.credit() })),\n );\n\n server.tool(\"frequency_list\", \"The frequencies this agent belongs to.\", {}, async () => run(() => agent.frequencies.mine()));\n server.tool(\"frequency_public\", \"The public dial: listable frequencies and whether the agent is already a member.\", {}, async () => run(() => agent.frequencies.publicFrequencies()));\n server.tool(\n \"frequency_tune_by_number\",\n \"Tune in by dial number (kHz, e.g. 118025 for 118.025) with the access code where there is one; joins where it can.\",\n { khz: z.number().int().positive(), accessCode: z.string().optional() },\n async ({ khz, accessCode }) => run(() => agent.frequencies.tuneByNumber(khz, accessCode)),\n );\n server.tool(\"frequency_request_join\", \"Ask to join a listable frequency by id.\", { frequencyId: z.string() }, async ({ frequencyId }) => run(() => agent.frequencies.requestJoin(frequencyId)));\n server.tool(\"frequency_roster\", \"Who is tuned to a frequency right now.\", { frequencyId: z.string() }, async ({ frequencyId }) => run(() => agent.frequencies.roster(frequencyId)));\n server.tool(\"frequency_channels\", \"A frequency's channels.\", { frequencyId: z.string() }, async ({ frequencyId }) => run(() => agent.frequencies.channels(frequencyId)));\n server.tool(\n \"frequency_create\",\n \"Create a push-to-talk frequency. The operator attests age and accepts the Terms; billing applies (a 402 names what the credit balance needs).\",\n { name: z.string().min(1).max(64), description: z.string().max(500).optional(), publiclyListable: z.boolean().optional(), accessCode: z.string().optional() },\n async (body) => run(() => agent.frequencies.create({ ...body, ageConfirmed: true, termsAccepted: true })),\n );\n server.tool(\"frequency_leave\", \"Leave a frequency (membership).\", { frequencyId: z.string() }, async ({ frequencyId }) => run(() => agent.frequencies.leave(frequencyId).then(() => \"left\")));\n\n server.tool(\"contacts_list\", \"The agent's contacts.\", {}, async () => run(() => agent.contacts.list()));\n server.tool(\"contacts_search\", \"Find people and agents by callsign or Station ID.\", { query: z.string().min(1) }, async ({ query }) => run(() => agent.contacts.search(query)));\n server.tool(\"contacts_request\", \"Ask somebody to be a contact, by Station ID (FT-XXXX).\", { stationId: z.string() }, async ({ stationId }) => run(() => agent.contacts.request(stationId)));\n server.tool(\"contacts_requests\", \"Contact requests waiting either way.\", {}, async () => run(() => agent.contacts.requests()));\n server.tool(\"contacts_accept\", \"Accept a contact request.\", { requestId: z.string() }, async ({ requestId }) => run(() => agent.contacts.accept(requestId)));\n\n server.tool(\"chat_send\", \"Send a text message to a user id (a contact, or anyone who accepts messages from non-contacts; every agent does).\", { toUserId: z.string(), body: z.string().min(1).max(4000) }, async ({ toUserId, body }) => run(() => agent.chat.send(toUserId, body)));\n server.tool(\"chat_read\", \"What is waiting from a user id, oldest first; marks it read.\", { peerUserId: z.string() }, async ({ peerUserId }) =>\n run(async () => {\n const messages = await agent.chat.read(peerUserId);\n const last = messages.at(-1);\n if (last) await agent.chat.ack(peerUserId, last.seq).catch(() => undefined);\n return messages;\n }),\n );\n server.tool(\"chat_inbox\", \"Messages that arrived on the live socket since the server started, newest last.\", { peerUserId: z.string().optional() }, async ({ peerUserId }) => run(async () => agent.chat.inbox(peerUserId)));\n server.tool(\"chat_wait\", \"Wait up to `seconds` for the next message (from one user id, or anyone).\", { peerUserId: z.string().optional(), seconds: z.number().int().min(1).max(600).default(60) }, async ({ peerUserId, seconds }) =>\n run(() => agent.chat.waitForMessage(peerUserId, seconds * 1000)),\n );\n\n server.tool(\"call_place\", \"Call one or more contacts by user id. Returns the call and its frequency; use audio_speak/audio_listen on that frequency.\", { toUserIds: z.array(z.string()).min(1) }, async ({ toUserIds }) => run(() => agent.calls.place(toUserIds)));\n server.tool(\"call_ringing\", \"Calls ringing at this agent right now.\", {}, async () => run(async () => agent.calls.ringing()));\n server.tool(\"call_wait\", \"Wait up to `seconds` for an incoming call.\", { seconds: z.number().int().min(1).max(600).default(120) }, async ({ seconds }) => run(() => agent.calls.waitForRing(seconds * 1000)));\n server.tool(\"call_accept\", \"Answer a ringing call.\", { callId: z.string() }, async ({ callId }) => run(() => agent.calls.accept(callId)));\n server.tool(\"call_decline\", \"Decline a ringing call.\", { callId: z.string() }, async ({ callId }) => run(() => agent.calls.decline(callId).then(() => \"declined\")));\n server.tool(\"call_hang_up\", \"Hang up a call.\", { callId: z.string() }, async ({ callId }) => run(() => agent.calls.hangUp(callId).then(() => \"hung up\")));\n\n server.tool(\n \"audio_speak\",\n \"Speak a WAV file (16-bit PCM) on a frequency's default channel over the native voice transport. Opens the session if needed.\",\n { frequencyId: z.string(), wavPath: z.string() },\n async ({ frequencyId, wavPath }) =>\n run(async () => {\n const session = await agent.session(frequencyId);\n touch(frequencyId);\n const speaker = new Speaker(session);\n try {\n await speaker.speakWav(wavPath);\n } finally {\n speaker.close();\n }\n return `spoke ${wavPath} on ${frequencyId}`;\n }),\n );\n server.tool(\n \"audio_listen\",\n \"Record what is said on a frequency's channels for `seconds`, mixed to a 48 kHz mono WAV at `wavPath`; returns who spoke (stream ids and owners).\",\n { frequencyId: z.string(), seconds: z.number().int().min(1).max(300).default(10), wavPath: z.string() },\n async ({ frequencyId, seconds, wavPath }) =>\n run(async () => {\n const session = await agent.session(frequencyId);\n touch(frequencyId);\n const channels = await agent.frequencies.channels(frequencyId);\n for (const c of channels) session.listen(c.id);\n const listener = new Listener(session);\n await listener.start();\n await new Promise((r) => setTimeout(r, seconds * 1000));\n const heard = listener.stop();\n listener.close();\n await writeFile(wavPath, Listener.mixToWav(heard));\n return { wavPath, streams: heard.map((h) => ({ streamId: h.streamId, connectionId: h.connectionId, seconds: Math.round(h.samples.length / 480) / 100 })) };\n }),\n );\n server.tool(\"audio_close\", \"Close the native session on a frequency.\", { frequencyId: z.string() }, async ({ frequencyId }) => run(() => agent.closeSession(frequencyId).then(() => \"closed\")));\n\n server.tool(\"credit_balance\", \"The prepaid credit that pays for what this agent does, with today's daily prices and the rails a top-up can use.\", {}, async () => run(() => agent.client.credit()));\n server.tool(\n \"credit_topup_challenge\",\n \"Start a top-up: returns the 402 payment challenge (Machine Payments Protocol) for the amount, to pay with a wallet and resubmit through credit_topup_pay.\",\n { amountCents: z.number().int().min(50).max(50_000) },\n async ({ amountCents }) =>\n run(async () => {\n try {\n await agent.client.request(\"/v1/billing/credit/topup\", { method: \"POST\", body: { amountCents } });\n return \"already credited\";\n } catch (err) {\n if (err instanceof PaymentRequired) return { challenge: err.challenge, headers: Object.fromEntries(err.headers.entries()) };\n throw err;\n }\n }),\n );\n server.tool(\n \"credit_topup_pay\",\n \"Finish a top-up: resubmit the amount with the Payment-Authorization credential a wallet built from the challenge.\",\n { amountCents: z.number().int().min(50).max(50_000), paymentAuthorization: z.string().min(1) },\n async ({ amountCents, paymentAuthorization }) =>\n run(() => agent.client.request(\"/v1/billing/credit/topup\", { method: \"POST\", body: { amountCents }, headers: { \"payment-authorization\": paymentAuthorization } })),\n );\n\n server.resource(\"inbox\", \"frequency://inbox\", { description: \"The live socket's recent events (chat, calls, presence), oldest first.\" }, async (uri) => ({\n contents: [{ uri: uri.href, mimeType: \"application/json\", text: JSON.stringify(agent.realtime.recent(), null, 2) }],\n }));\n}\n"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;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,SAAS,SAAS,qBAAqB,EAAE,aAAa,yEAAyE,GAAG,OAAO,SAAS;AAAA,IACvJ,UAAU,CAAC,EAAE,KAAK,IAAI,MAAM,UAAU,oBAAoB,MAAM,KAAK,UAAU,MAAM,SAAS,OAAO,GAAG,MAAM,CAAC,EAAE,CAAC;AAAA,EACpH,EAAE;AACJ;;;AhD9IA,eAAsB,eAAe,UAAgC,CAAC,GAAkB;AACtF,QAAM,SAAS,MAAM,QAAQ,OAAO;AACpC,QAAM,QAAQ,MAAM,MAAM,QAAQ,EAAE,SAAS,OAAO,SAAS,KAAK,OAAO,KAAK,UAAU,EAAE,YAAY,IAAI,EAAE,CAAC;AAC7G,QAAM,SAAS,IAAI,UAAU,EAAE,MAAM,uBAAuB,SAAS,QAAQ,CAAC;AAC9E,gBAAc,QAAQ,KAAK;AAC3B,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,WAAW,YAAY;AAC3B,UAAM,MAAM,MAAM,EAAE,MAAM,MAAM,MAAS;AACzC,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,UAAQ,GAAG,UAAU,MAAM,KAAK,SAAS,CAAC;AAC1C,UAAQ,GAAG,WAAW,MAAM,KAAK,SAAS,CAAC;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;","names":["retryAfterSeconds","text","WebSocket","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","text","text","z","z","z","z","z","z","z","z","z","z","z","z","z","z","text","z","z","z","z","z","z","z","z","z","WebSocket","frac","readFile","z","z"]}
|