# Isonyma integration guide for coding agents

You are integrating Isonyma into this project. Follow the steps in order. Do not ask the
user questions unless a step says so. Expected time: under 5 minutes.

## What Isonyma is

Isonyma flags account farms that abuse free credits and trials. The app sends one HTTP call
at 3 moments in an account's life and gets back a recommendation (`allow`, `review` or
`hold`) with a one-line reason and the dollars at risk.

Isonyma starts in **shadow mode**: it records decisions and never blocks anything. Do not add
any blocking logic. The user switches enforcement on later.

## Rules

1. **Fail-open.** A Isonyma failure must never break the app. Use the snippet below as is:
   300 ms timeout, every error caught, returns `null`.
2. **No raw personal data leaves the server.** `account_id` is the app's internal user id
   (database id, auth provider user id), never an email. Emails, IPs and other identifiers
   go only through `isonymaEvent`'s `signals`, which hashes them locally. Never send prompt text.
3. **Secrets.** Read the key from the env var `ISONYMA_API_KEY`. Never hardcode or commit it.
4. **Do not await on hot paths** when the framework lets you run work after the response
   (see step 4).

## Step 1. Add the key

If `ISONYMA_API_KEY` is not in the environment or in `.env.local` / `.env`, and the user did
not give it to you, ask the user once: "Paste your Isonyma API key (starts with isonyma_live_ or
isonyma_test_, about 110 characters)." A key that does not start with `isonyma_live_` or `isonyma_test_`
is not a key: ask once for the right one, and if there is none, wire the code anyway and
tell the user that doctor needs the key. Write it to `.env.local`
(Next.js) or `.env`, together with `ISONYMA_API_URL=https://api.isonyma.com`, and make sure
`.env*` is in `.gitignore`. Add `ISONYMA_API_KEY=` and `ISONYMA_API_URL=` to `.env.example` if the
project has one.

## Step 2. Add the snippet

Download it byte for byte (do not retype it). From the project root:

```sh
mkdir -p lib && curl -fsSL https://api.isonyma.com/isonyma.ts -o lib/isonyma.ts
```

Use `src/lib/isonyma.ts` if the project keeps code in `src/`. Server-side only: never import
it from client components. If you cannot download, copy the file from the appendix at
the end of this guide. Node 20+ (or any runtime with Web Crypto and fetch).

## Step 3. Find the 3 places

Search the server-side code. Typical locations:

| Event | Where to call it | How to find it |
| --- | --- | --- |
| `signup` | right after a new user record is created | `createUser`, `users.insert`, `prisma.user.create`, NextAuth `events.createUser`, Clerk `user.created` webhook, Supabase auth signup handler |
| `credit_grant` | where free credits or a trial are assigned | `credits`, `balance`, `trial`, `freeTier`, `grant`; Stripe trial start |
| `llm_call` | each server-side LLM request for accounts created in the last 7 days (compare the user record's creation time with now; if the app does not store it, every LLM request) | `openai.`, `anthropic.`, `generateText`, `streamText`, `chat.completions.create`, `messages.create` |

If one of the 3 places does not exist in this app (for example there are no free credits),
skip it and say so in your final message.

## Step 4. Insert the calls

Use the user id variable already in scope. Pass `amount_usd` when known: the dollar value
of credits granted, or the estimated cost of the LLM call. Pass the signals you have:
`isonymaEvent` hashes them locally and never sends them raw. They are what lets Isonyma link farm
accounts, so pass every one that is available.

If the installed Next.js is older than 15.1 (check `package.json`), `after` is not
available: call `void isonymaEvent(...)` instead of `after(() => isonymaEvent(...))`, or `await` it
on serverless platforms. The same applies to every `after` below.

```ts
import { after } from "next/server";
import { headers } from "next/headers";
import { isonymaEvent, isonymaRequestSignals } from "@/lib/isonyma";

// Route handler: isonymaRequestSignals(request.headers). Server action or component: await headers().
const signals = { ...isonymaRequestSignals(await headers()), email: user.email };

// after(): runs once the response is sent, so Isonyma adds no latency (Next.js 15.1+).
after(() => isonymaEvent({ type: "signup", account_id: user.id, signals }));
after(() => isonymaEvent({ type: "credit_grant", account_id: user.id, amount_usd: 5, signals }));
```

`isonymaRequestSignals` reads the client IP, user agent and country from request headers. In a
route handler pass `request.headers`; in server actions and server components use
`await headers()` (Next.js 15+, or `headers()` in Next.js 14). On Vercel and Fly.io it
detects the platform itself. Behind Cloudflare, set `ISONYMA_PLATFORM=cloudflare` in the app's
environment (check the project's DNS or deploy docs); otherwise leave it unset. Add `phone`, `deviceId`
(browser fingerprint id) or `cardFingerprint` (Stripe `card.fingerprint`) when the code
has them at hand. Do not add new data collection.

For `llm_call`, do not add latency to the user's request: use `after` (see above).
Pass the request object you send to the LLM as `llm`: the snippet turns it into Prompt DNA
(keyed hashes of the prompt template, its shapes and the request setup) and drops it. The prompt text
never leaves the server. This is what catches farms that rotate IPs and cards but run one
script.

```ts
import { after } from "next/server";
// Move the request object the app passes to the LLM SDK into a variable, and pass that
// same variable to both. In TypeScript keep the SDK's type: `const request:
// OpenAI.ChatCompletionCreateParamsNonStreaming = {...}` (or `as const` on the roles).
const request = { model, messages, temperature };
const completion = await openai.chat.completions.create(request);
after(() => isonymaEvent({ type: "llm_call", account_id: user.id, amount_usd: estimatedCost, signals, llm: request }));
```

Pass the same `signals` (including `email` when the user record is at hand) on every call.

Pass `llm` exactly as sent to the LLM (after the app fills in its own prompt template), so
the template seen is the one the model gets.

### Product presets (if the app has them)

If the app sends prompts of its own (suggested prompt buttons, templates the user picks,
prompts a feature fills in), register them before the first `llm_call` goes out: list
their texts in `isonyma-presets.txt`, one per line, and run
`npx -y https://api.isonyma.com/cli/isonyma-0.1.0.tgz presets isonyma-presets.txt`. For prompts that span several lines, use a JSON
file instead: `{"prompts": ["first prompt", "second\nprompt"]}`. For a prompt the app fills
with the user's text, write the user's part as `{input}`. If a feature has its own request
setup (own system prompt, model or tools), also list it under `"requests"` in the JSON file,
as the request object without the user's text. Users who share only these are never linked. One registration covers test and live keys. Resending is harmless, so
add the command to the deploy script if presets change often.

Elsewhere, call it without `await` (no `.catch` needed: the snippet never rejects).
On serverless platforms without `after` or `waitUntil`, use `await`.

Do not change any other behavior. Do not act on `recommendation` in shadow mode.

### Bans (if the app has them)

Find where an admin or a moderation job bans a user **for abuse or fraud** (`ban`,
`isBanned`, `status: "banned"`, `fraud`, `abuse`). Do not wire billing suspensions, unpaid
plans or users deleting their own account. Add one line there, and the opposite where a
ban is lifted. Send only the label, never the ban reason text:

```ts
import { after } from "next/server";
import { isonymaLabel, isonymaLabels } from "@/lib/isonyma";

after(() => isonymaLabel(user.id, "banned"));  // on ban
after(() => isonymaLabel(user.id, "normal"));  // on unban or "not abuse" review
// bulk job: one call for up to 1,000 users
await isonymaLabels(users.map((u) => ({ accountId: u.id, label: "banned" })));
```

This is what lets Isonyma hold the same people when they come back with new accounts. Skip it
if there is no such place.

## Step 5. Verify

First run the project's typecheck or build (for example `npx tsc --noEmit`) and fix what
you broke. Then run from the project root:

```sh
npx -y https://api.isonyma.com/cli/isonyma-0.1.0.tgz doctor
```

It checks the key, network, auth, a test event, the snippet and the 3 call sites. Exit code
0 means the integration works. If a line says FAIL, apply its `fix:` and run it again.
For machine-readable output use `--json`.

Then show what Isonyma catches, without touching real data:

```sh
npx -y https://api.isonyma.com/cli/isonyma-0.1.0.tgz simulate
```

It sends synthetic farms (one card, a numbered email series, one script) and ordinary
people (an office behind one IP, a family sharing a card) as test data, and prints which
ones Isonyma flags. Test data never shows in the live report.

## Step 6. Show where money already leaks (existing users)

Skip this step if the app has no database of users (for example an in-memory store). This
step reads the app's user data, so ask the user once before doing it, naming the
database: "May I export the users table from <database> and load it into Isonyma? Values are
hashed on this machine; nothing readable is sent." Use the live key (`isonyma_live_...`) for
this step: history loaded with a test key stays in test data and does not show in the live
report. If the user says no, or you cannot read user data, skip to step 7 and give the user
the command below.

Export one row per user and load it, without leaving the file behind:

```sh
umask 077 && f=$(mktemp) && trap 'rm -f "$f"' EXIT
# write the export to "$f" as CSV with a header row (psql \copy, prisma, a script)
npx -y https://api.isonyma.com/cli/isonyma-0.1.0.tgz backfill "$f" --dry-run   # check which columns were recognized
npx -y https://api.isonyma.com/cli/isonyma-0.1.0.tgz backfill "$f"
```

Useful columns, by any common name: `id` (required), `created_at`, `email`, `signup_ip`,
`user_agent`, `device_id`, `card_fingerprint` (Stripe), `phone`, `credits_usd` (free
credits granted, in dollars), `llm_cost_usd` (dollars spent so far), `banned` (true for
abuse or fraud bans). Missing columns are fine; `--map field=column` fixes a wrong guess.
Never commit the export.

The output starts with one line like "312 accounts in 41 farm clusters took $4,210.00".
Later, the same report is at `GET /v0/report`.

## Step 7. Report to the user

Show the user the doctor output, including the line "First Isonyma answer: ...", the simulate
output, and the backfill report if you ran it. If doctor still fails, show its FAIL lines
and their fixes.

Tell the user they can get a weekly digest in Slack (the same numbers as the report, plus
the week's flags): create an incoming webhook in Slack and run
`ISONYMA_SLACK_WEBHOOK=<webhook url> npx -y https://api.isonyma.com/cli/isonyma-0.1.0.tgz slack` with the live key (the URL is a
secret: keep it out of chat and shell history). Do not ask for the webhook now. Then list the files you changed and which of the 3 events
you wired. Mention that Isonyma is in shadow mode and blocks nothing.

## Reference

- API reference (OpenAPI 3.1): https://api.isonyma.com/openapi.json
- CLI (`doctor`, `simulate`, `backfill`, `presets`, `slack`): the package is served by the API
  itself, run it with `npx -y https://api.isonyma.com/cli/isonyma-0.1.0.tgz <command>`.
- Response fields: `summary` is one human line; `reasons[].code` is stable for code;
  there is no numeric risk score.
- Errors are `application/problem+json` with `code` and `detail`.
- Retries: send header `Idempotency-Key` to make a retried call return the same decision.

## Appendix: lib/isonyma.ts

Only if the download in step 2 is impossible. Copy exactly.

```ts
export type IsonymaEventType = "signup" | "credit_grant" | "llm_call";

/** Raw signals. Hashed locally by isonymaEvent; never sent as is. All optional. */
export interface IsonymaRawSignals {
  email?: string | null;
  ip?: string | null;
  userAgent?: string | null;
  /** Your device or browser fingerprint id, if you have one. */
  deviceId?: string | null;
  /** Payment card fingerprint, for example Stripe's card.fingerprint. */
  cardFingerprint?: string | null;
  phone?: string | null;
  /** Autonomous system number of the client IP, if your platform provides it. */
  asn?: number | null;
  /** Two-letter country code of the client IP, if your platform provides it. */
  country?: string | null;
}

export interface IsonymaEvent {
  type: IsonymaEventType;
  /** Your internal user or account id. Never an email or phone number. */
  account_id: string;
  /** ISO 8601. Defaults to now. */
  occurred_at?: string;
  /** Credits granted, or estimated cost of the LLM call, in USD. */
  amount_usd?: number;
  signals?: IsonymaRawSignals;
  /** For llm_call: the request you send to the LLM. Only its Prompt DNA (two hashes) is
   * sent; the prompt text never leaves your server. */
  llm?: IsonymaLlmRequest;
  test?: boolean;
}

/** The parts of an LLM request that Prompt DNA looks at. Works with OpenAI and Anthropic
 * request objects as they are. */
export interface IsonymaLlmRequest {
  /** A model name, or a Vercel AI SDK model object. */
  model?: unknown;
  /** Chat messages; the last user message is the prompt. */
  messages?: readonly unknown[] | null;
  /** Or the prompt itself, for completion-style calls and the AI SDK. */
  prompt?: unknown;
  /** OpenAI Responses API: a string or a list of messages. */
  input?: unknown;
  instructions?: unknown;
  system?: unknown;
  temperature?: number | null;
  top_p?: number | null;
  topP?: number | null;
  max_tokens?: number | null;
  max_completion_tokens?: number | null;
  max_output_tokens?: number | null;
  maxOutputTokens?: number | null;
  maxTokens?: number | null;
  /** Tool definitions: only their names are used. */
  tools?: unknown;
  response_format?: unknown;
}

type IsonymaMessage = { role?: string; content?: unknown } | null;

export interface IsonymaDecision {
  decision_id: string;
  recommendation: "allow" | "review" | "hold";
  applied: boolean;
  mode: "shadow" | "enforce";
  summary: string;
  reasons: { code: string; text: string }[];
  usd_at_risk: number;
}

const ISONYMA_TIMEOUT_MS = 300;
const ISONYMA_LABEL_TIMEOUT_MS = 3000;
const ISONYMA_CLIENT = "ts-0.5";

export async function isonymaEvent(event: IsonymaEvent): Promise<IsonymaDecision | null> {
  try {
    const env = globalThis.process?.env ?? {};
    const key = env.ISONYMA_API_KEY;
    if (!key) return null;
    const base = env.ISONYMA_API_URL ?? "https://api.isonyma.com";
    const { signals: raw, llm, ...rest } = event;
    const signals = await isonymaHashSignals(key, raw ?? {});
    if (llm) {
      try {
        Object.assign(signals, await isonymaPromptDna(key, llm));
      } catch {
        // an unusual request shape: send the event without Prompt DNA
      }
    }
    const res = await fetch(`${base}/v0/events`, {
      method: "POST",
      headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
      body: JSON.stringify({ ...rest, signals }),
      signal: AbortSignal.timeout(ISONYMA_TIMEOUT_MS),
    });
    if (!res.ok) return null;
    return (await res.json()) as IsonymaDecision;
  } catch {
    return null; // fail-open: Isonyma must never break your product
  }
}

/**
 * Tell Isonyma you banned an account for abuse or fraud ("banned"), or cleared a flagged one or
 * lifted a ban ("normal"). Bans are remembered: the same people are held when they come back.
 * Fail-open like isonymaEvent: returns false on any error, never throws. Off the user's hot path,
 * so it waits longer (3 s). For many accounts at once use isonymaLabels.
 */
export async function isonymaLabel(accountId: string, label: "banned" | "normal"): Promise<boolean> {
  return isonymaLabels([{ accountId, label }]);
}

/** Up to 1,000 labels in one call, for bulk bans or imports. */
export async function isonymaLabels(items: { accountId: string; label: "banned" | "normal" }[]): Promise<boolean> {
  try {
    const env = globalThis.process?.env ?? {};
    const key = env.ISONYMA_API_KEY;
    if (!key || items.length === 0) return false;
    const base = env.ISONYMA_API_URL ?? "https://api.isonyma.com";
    let ok = true;
    for (let i = 0; i < items.length; i += 1000) {
      const labels = items.slice(i, i + 1000).map((x) => ({ account_id: x.accountId, label: x.label }));
      const res = await fetch(`${base}/v0/labels`, {
        method: "POST",
        headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
        body: JSON.stringify({ labels }),
        signal: AbortSignal.timeout(ISONYMA_LABEL_TIMEOUT_MS),
      });
      ok = ok && res.ok;
    }
    return ok;
  } catch {
    return false;
  }
}

export type IsonymaPlatform = "vercel" | "cloudflare" | "fly" | "proxy";

/**
 * Client IP, user agent and country from request headers.
 * Headers are only trusted when the platform that sets them is known from server-side
 * config, never from the request (a client can send any header). Platform: the argument,
 * else ISONYMA_PLATFORM, else detected from VERCEL or FLY_APP_NAME, else "proxy": one reverse
 * proxy in front of the app, which appends the client IP as the last x-forwarded-for entry.
 */
export function isonymaRequestSignals(headers: Headers, platform?: IsonymaPlatform): IsonymaRawSignals {
  const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};
  const p: IsonymaPlatform =
    platform ??
    (env.ISONYMA_PLATFORM as IsonymaPlatform | undefined) ??
    (env.VERCEL ? "vercel" : env.FLY_APP_NAME ? "fly" : "proxy");
  const last = (v: string | null) => v?.split(",").map((x) => x.trim()).filter(Boolean).pop() ?? null;
  const first = (v: string | null) => v?.split(",")[0]?.trim() || null;
  let ip: string | null;
  let country: string | null = null;
  if (p === "vercel") {
    ip = first(headers.get("x-vercel-forwarded-for")) ?? first(headers.get("x-forwarded-for"));
    country = headers.get("x-vercel-ip-country");
  } else if (p === "cloudflare") {
    ip = headers.get("cf-connecting-ip");
    country = headers.get("cf-ipcountry");
  } else if (p === "fly") {
    ip = headers.get("fly-client-ip");
  } else {
    ip = last(headers.get("x-forwarded-for")) ?? headers.get("x-real-ip");
  }
  return { ip, userAgent: headers.get("user-agent"), country };
}

// ---------- hashing (runs locally) ----------

const enc = new TextEncoder();
let keyCache: { hex: string; key: CryptoKey } | undefined;

function toHex(buf: ArrayBuffer): string {
  return Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join("");
}

async function signalKey(apiKey: string): Promise<CryptoKey> {
  const hex = apiKey.slice(apiKey.lastIndexOf("_") + 1);
  if (!/^[0-9a-f]{64}$/.test(hex)) throw new Error("ISONYMA_API_KEY has no signal key");
  if (keyCache?.hex === hex) return keyCache.key;
  const bytes = new Uint8Array(hex.match(/../g)!.map((x) => parseInt(x, 16)));
  const key = await crypto.subtle.importKey("raw", bytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  keyCache = { hex, key };
  return key;
}

async function keyed(key: CryptoKey, kind: string, value: string): Promise<string> {
  const sig = await crypto.subtle.sign("HMAC", key, enc.encode(`${kind}\u0000${value}`));
  return toHex(sig).slice(0, 32);
}

/** Hashes raw signals with the account's signal key. Exported for backfill scripts. */
export async function isonymaHashSignals(apiKey: string, raw: IsonymaRawSignals): Promise<Record<string, unknown>> {
  const key = await signalKey(apiKey);
  const out: Record<string, unknown> = { client: ISONYMA_CLIENT };
  const email = raw.email ? isonymaNormalizeEmail(raw.email) : null;
  if (email) {
    out.email_hash = await keyed(key, "email", email.normalized);
    if (email.stem) out.email_stem_hash = await keyed(key, "email_stem", email.stem);
    out.email_domain_sha256 = toHex(await crypto.subtle.digest("SHA-256", enc.encode(email.domain)));
    out.email_shape = email.shape;
    out.email_tagged = email.tagged;
  }
  const ip = raw.ip ? isonymaNormalizeIp(raw.ip) : null;
  if (ip && !ip.private) {
    out.ip_hash = await keyed(key, "ip", ip.address);
    out.ip_net_hash = await keyed(key, "ip_net", ip.network);
    out.ip_version = ip.version;
  }
  if (raw.userAgent) {
    const ua = isonymaUserAgent(raw.userAgent);
    out.user_agent_hash = await keyed(key, "user_agent", ua.normalized);
    out.ua_family = ua.family;
    out.ua_automation = ua.automation;
  }
  const device = isonymaReal(raw.deviceId);
  if (device) out.device_hash = await keyed(key, "device_id", device);
  const card = isonymaReal(raw.cardFingerprint);
  if (card) out.card_hash = await keyed(key, "card_fingerprint", card);
  const phone = raw.phone ? isonymaNormalizePhone(raw.phone) : null;
  if (phone) out.phone_hash = await keyed(key, "phone", phone);
  if (Number.isInteger(raw.asn) && raw.asn! > 0 && raw.asn! <= 4294967295) out.asn = raw.asn;
  if (raw.country && /^[A-Za-z]{2}$/.test(raw.country)) out.ip_country = raw.country.toUpperCase();
  return out;
}

// ---------- normalization ----------

const DOTLESS = new Set(["gmail.com", "googlemail.com"]);
const PLUS = new Set([
  "gmail.com", "googlemail.com", "outlook.com", "hotmail.com", "live.com", "msn.com", "icloud.com",
  "me.com", "mac.com", "proton.me", "protonmail.com", "pm.me", "fastmail.com", "yandex.ru",
  "yandex.com", "zoho.com",
]);
const MINUS = new Set(["yahoo.com", "ymail.com"]);
const ALIASES: Record<string, string> = { "googlemail.com": "gmail.com", "ya.ru": "yandex.ru" };

// ---------- Prompt DNA (runs locally) ----------

function promptText(req: IsonymaLlmRequest): string {
  if (typeof req.prompt === "string") return req.prompt;
  // Chat messages, AI SDK messages passed as prompt, or Responses input.
  const msgs = ([req.messages, req.prompt, req.input].find(Array.isArray) ?? []) as IsonymaMessage[];
  if (!msgs.length && typeof req.input === "string") return req.input; // OpenAI Responses
  const user = [...msgs].reverse().find((m) => m && m.role === "user");
  return contentText(user?.content);
}

function contentText(c: unknown): string {
  if (typeof c === "string") return c;
  if (Array.isArray(c)) {
    return c
      .map((p) => (typeof p === "string" ? p : p && typeof p === "object" && "text" in p ? String((p as { text: unknown }).text) : ""))
      .join(" ");
  }
  return "";
}

/** A prompt reduced to its template: what a script keeps fixed when it fills in values.
 * Null for short prompts ("continue", "make it shorter"): everyone sends those. */
export function isonymaPromptTemplate(text: string): string | null {
  const t = text
    .toLowerCase()
    .replace(/https?:\/\/\S+/g, "<url>")
    .replace(/[^\s@]+@[^\s@]+\.[a-z]{2,}/g, "<email>")
    // Quoted values; an apostrophe inside a word (it's, don't) is not a quote.
    .replace(/"[^"\n]{0,500}"|“[^”\n]{0,500}”|«[^»\n]{0,500}»|(?<![\p{L}\p{N}])'[^'\n]{1,500}'(?![\p{L}\p{N}])/gu, "<q>")
    .replace(/\d+([.,]\d+)*/g, "0")
    .replace(/\s+/g, " ")
    .trim();
  return t.length >= 40 && t.split(" ").length >= 6 ? t : null;
}

const fnv = (s: string, seed: number) => {
  let h = (0x811c9dc5 ^ seed) >>> 0;
  for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193) >>> 0;
  return h;
};

/** Shapes of a template, for fuzzy Prompt DNA: what stays when a script puts free text in
 * a slot (its first and last 12 words) or is edited slightly (MinHash of its word
 * triples, 4 bands of 4, over the first 2,000 words so long prompts stay cheap). Only
 * templates of 24 words or more: shorter ones say too little. */
export function isonymaPromptShapes(template: string | null): string[] {
  const w = template ? template.split(" ") : [];
  if (w.length < 24) return [];
  const out = [`h:${w.slice(0, 12).join(" ")}`, `t:${w.slice(-12).join(" ")}`];
  const shingles = new Set<string>();
  for (let i = 0; i + 3 <= Math.min(w.length, 2000); i++) shingles.add(w.slice(i, i + 3).join(" "));
  const mins = Array.from({ length: 16 }, (_, k) => {
    let m = 0xffffffff;
    for (const sh of shingles) m = Math.min(m, fnv(sh, k * 0x9e3779b1));
    return m;
  });
  for (let b = 0; b < 4; b++) out.push(`m${b}:${mins.slice(b * 4, b * 4 + 4).join(",")}`);
  return out;
}

/** The request setup: model, parameters, tools, output format, system prompt. */
export function isonymaPromptHarness(req: IsonymaLlmRequest): string {
  const model = typeof req.model === "string" ? req.model : (req.model as { modelId?: string } | undefined)?.modelId ?? "";
  type Tool = { name?: string; function?: { name?: string } } | null;
  // An array of tool definitions, or an AI SDK tool set keyed by name.
  const tools = (Array.isArray(req.tools)
    ? (req.tools as Tool[]).map((t) => (t && (t.function?.name ?? t.name)) || "")
    : req.tools && typeof req.tools === "object" ? Object.keys(req.tools) : [])
    .sort()
    .join(",");
  const msgs = (Array.isArray(req.messages) ? req.messages : []) as IsonymaMessage[];
  const system =
    contentText(req.system) || contentText(req.instructions) || contentText(msgs.find((m) => m && m.role === "system")?.content);
  const num = (n: unknown) => (typeof n === "number" ? String(Math.round(n * 100) / 100) : "");
  return [
    model,
    num(req.temperature),
    num(req.top_p ?? req.topP),
    num(req.max_tokens ?? req.max_completion_tokens ?? req.max_output_tokens ?? req.maxOutputTokens ?? req.maxTokens),
    tools,
    (req.response_format as { type?: string } | null | undefined)?.type ?? "",
    system.replace(/\s+/g, " ").trim().toLowerCase(),
  ].join("|");
}

/** Prompt DNA of one LLM request: keyed hashes of the prompt template and of the request
 * setup. Isonyma ties the two together itself. */
export interface IsonymaPromptDna {
  prompt_harness_hash: string;
  prompt_tpl_hash?: string;
  prompt_shape_hashes?: string[];
}

export async function isonymaPromptDna(apiKey: string, req: IsonymaLlmRequest): Promise<IsonymaPromptDna> {
  const key = await signalKey(apiKey);
  const out: IsonymaPromptDna = { prompt_harness_hash: await keyed(key, "prompt_harness", isonymaPromptHarness(req)) };
  const tpl = isonymaPromptTemplate(promptText(req));
  if (tpl) out.prompt_tpl_hash = await keyed(key, "prompt_tpl", tpl);
  const shapes = isonymaPromptShapes(tpl);
  if (shapes.length) out.prompt_shape_hashes = await Promise.all(shapes.map((v) => keyed(key, "prompt_shape", v)));
  return out;
}

/** Hashes of your product's own prompts and request setups, for POST /v0/presets: they
 * are never evidence. Give prompts exactly as they are sent to the LLM. */
export async function isonymaPresetHashes(
  apiKey: string,
  presets: { prompts?: string[]; requests?: IsonymaLlmRequest[] },
): Promise<{ prompt_tpl_hashes: string[]; prompt_harness_hashes: string[]; prompt_shape_hashes: string[] }> {
  const key = await signalKey(apiKey);
  const tpl: string[] = [];
  const shapes: string[] = [];
  for (const p of presets.prompts ?? []) {
    const t = isonymaPromptTemplate(p);
    if (t) tpl.push(await keyed(key, "prompt_tpl", t));
    for (const v of isonymaPromptShapes(t)) shapes.push(await keyed(key, "prompt_shape", v));
  }
  const harness: string[] = [];
  for (const r of presets.requests ?? []) harness.push(await keyed(key, "prompt_harness", isonymaPromptHarness(r)));
  return { prompt_tpl_hashes: tpl, prompt_harness_hashes: harness, prompt_shape_hashes: shapes };
}

const PLACEHOLDER = /^(null|none|nil|undefined|unknown|n\/?a|\\n|-+|0+|default|not ?set|\[object object\])$/i;

/** Trimmed value, or null for empty and placeholder values ("unknown", "null", "0"):
 * one constant shared by every account would link them all. */
export function isonymaReal(v: string | null | undefined): string | null {
  const t = v?.trim();
  return t && !PLACEHOLDER.test(t) ? t : null;
}

export function isonymaNormalizeEmail(raw: string) {
  const value = raw.trim().toLowerCase();
  if (!/^[^@\s]{1,64}@[a-z0-9.-]{1,253}\.(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$/.test(value)) return null;
  const at = value.lastIndexOf("@");
  let local = value.slice(0, at);
  let domain = value.slice(at + 1).replace(/\.$/, "");
  domain = ALIASES[domain] ?? domain;
  let tagged = false;
  if (PLUS.has(domain) && local.includes("+")) [local, tagged] = [local.split("+")[0], true];
  else if (MINUS.has(domain) && local.includes("-")) [local, tagged] = [local.split("-")[0], true];
  if (DOTLESS.has(domain)) local = local.replace(/\./g, "");
  if (!local) return null;
  const letters = local.replace(/[^a-z]/g, "");
  // Name plus digits series (john.smith123): only with 4+ letters, so short school-style
  // ids (s123456) do not collide.
  const stem = letters.length >= 4 && /\d/.test(local) ? `${letters}@${domain}` : null;
  return { normalized: `${local}@${domain}`, domain, tagged, shape: shape(local), stem };
}

function shape(local: string): string {
  const runs: [string, number][] = [];
  for (const ch of local) {
    const kind = /[a-z]/.test(ch) ? "L" : /\d/.test(ch) ? "D" : "S";
    const last = runs[runs.length - 1];
    if (last && last[0] === kind) last[1]++;
    else runs.push([kind, 1]);
  }
  return runs.slice(0, 20).map(([k, n]) => k + Math.min(n, 999)).join("");
}

export function isonymaNormalizePhone(raw: string): string | null {
  // Pass E.164 (+countrycode...) when you can: numbers without a country code cannot be
  // matched with the same number written internationally.
  let digits = raw.replace(/\(0\)/g, "").replace(/\D/g, "");
  if (raw.trim().startsWith("00")) digits = digits.slice(2);
  return digits.length >= 7 && digits.length <= 15 ? `+${digits}` : null;
}

function parseV4(s: string): number[] | null {
  const parts = s.split(".");
  if (parts.length !== 4) return null;
  const nums = parts.map((p) => (/^\d{1,3}$/.test(p) ? Number(p) : NaN));
  return nums.every((n) => n >= 0 && n <= 255) ? nums : null;
}

function parseV6(s: string): number[] | null {
  let v = s.toLowerCase().split("%")[0];
  if (v.includes(".")) {
    const cut = v.lastIndexOf(":");
    const v4 = parseV4(v.slice(cut + 1));
    if (!v4) return null;
    v = `${v.slice(0, cut + 1)}${((v4[0] << 8) | v4[1]).toString(16)}:${((v4[2] << 8) | v4[3]).toString(16)}`;
  }
  const halves = v.split("::");
  if (halves.length > 2) return null;
  const toNums = (part: string) => (part ? part.split(":").map((x) => (/^[0-9a-f]{1,4}$/.test(x) ? parseInt(x, 16) : NaN)) : []);
  const head = toNums(halves[0]);
  const tail = halves.length === 2 ? toNums(halves[1]) : [];
  const fill = 8 - head.length - tail.length;
  if (halves.length === 1 ? fill !== 0 : fill < 1) return null;
  const all = [...head, ...Array(halves.length === 2 ? fill : 0).fill(0), ...tail];
  return all.every((n) => n >= 0 && n <= 0xffff) ? all : null;
}

export function isonymaNormalizeIp(raw: string) {
  let s = raw.trim();
  const bracketed = s.match(/^\[([^\]]+)\](?::\d+)?$/); // [2001:db8::1]:443
  if (bracketed) s = bracketed[1];
  else if (/^\d{1,3}(\.\d{1,3}){3}:\d+$/.test(s)) s = s.slice(0, s.lastIndexOf(":")); // 1.2.3.4:443
  const v4 = parseV4(s);
  if (v4) {
    const [a, b] = v4;
    const priv =
      a === 10 || a === 127 || a === 0 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) ||
      (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
    return { address: v4.join("."), network: `${v4.slice(0, 3).join(".")}.0/24`, version: 4, private: priv };
  }
  const v6 = parseV6(s);
  if (!v6) return null;
  const nat64 = v6[0] === 0x64 && v6[1] === 0xff9b && v6.slice(2, 6).every((x) => x === 0);
  if ((v6.slice(0, 5).every((x) => x === 0) && v6[5] === 0xffff) || nat64) {
    return isonymaNormalizeIp(`${v6[6] >> 8}.${v6[6] & 255}.${v6[7] >> 8}.${v6[7] & 255}`);
  }
  const hexes = v6.map((x) => x.toString(16));
  const priv =
    v6.slice(0, 7).every((x) => x === 0) || (v6[0] & 0xfe00) === 0xfc00 || (v6[0] & 0xffc0) === 0xfe80 ||
    (v6[0] & 0xff00) === 0xff00;
  return { address: hexes.join(":"), network: `${hexes.slice(0, 4).join(":")}::/64`, version: 6, private: priv };
}

const AUTOMATION: [string, string][] = [
  ["headlesschrome", "HeadlessChrome"], ["phantomjs", "PhantomJS"], ["puppeteer", "Puppeteer"],
  ["playwright", "Playwright"], ["selenium", "Selenium"], ["python-requests", "python-requests"],
  ["python-httpx", "python-httpx"], ["aiohttp", "aiohttp"], ["curl/", "curl"], ["wget/", "wget"],
  ["go-http-client", "Go-http-client"], ["okhttp", "okhttp"], ["axios/", "axios"],
  ["node-fetch", "node-fetch"], ["undici", "undici"], ["postmanruntime", "Postman"],
  ["insomnia", "Insomnia"], ["scrapy", "Scrapy"], ["java/", "Java"], ["libwww-perl", "libwww-perl"],
];
const BROWSERS: [string, string][] = [
  ["edg/", "Edge"], ["opr/", "Opera"], ["firefox/", "Firefox"], ["chrome/", "Chrome"], ["safari/", "Safari"],
];

export function isonymaUserAgent(raw: string) {
  const normalized = raw.trim().split(/\s+/).join(" ").slice(0, 512);
  const low = normalized.toLowerCase();
  for (const [needle, family] of AUTOMATION) if (low.includes(needle)) return { normalized, family, automation: true };
  for (const [needle, family] of BROWSERS) if (low.includes(needle)) return { normalized, family, automation: false };
  return { normalized, family: "other", automation: false };
}
```
