# Many customers

Serve many customers from one product: an enterprise account, one workspace and one install token per customer, tokens kept encrypted and rotated, usage per customer, and bringing an existing workspace under your account.

Source: https://docs.omazy.ai/build-on-omazy/many-customers/

import { Tabs, TabItem } from '@astrojs/starlight/components'

Your product has customers, and each one has its own knowledge, its own
people and its own bill. On Omazy each customer gets a workspace of its own,
and your backend holds one token per customer. This page is the pattern a
product in production runs today, with the lessons it learned.

## The shape

```
Enterprise account            one per product, with an account key (eak_)
  ├─ workspace for customer A  its knowledge, agent, usage and budget
  │    └─ install token (cai_) your backend's key to this workspace only
  ├─ workspace for customer B
  │    └─ install token (cai_)
  └─ ...
```

Why a workspace per customer, and not one workspace with a field that says
which customer: the workspace is already the wall for knowledge, members,
audit, budgets and usage. A search with customer A's token cannot return
customer B's documents, because nothing in the request can name B. A filter
can be forgotten in one query. A wall cannot.

The token is the tenant. Every call your product makes for a customer goes out
on that customer's token, so usage and cost split by customer with no extra
work.

## The account key

The Omazy team issues an account key to a product. There is no screen for it
yet. It carries up to three scopes:

| Scope | Lets the key |
|---|---|
| `workspaces:manage` | Create, list, read, rename, suspend, resume and close your customers' workspaces |
| `installs:manage` | Mint a customer's install token when the workspace is made, and rotate it |
| `usage:read` | Read usage and cost across all your workspaces |

An account key reaches only workspaces your account created. It never calls a
model, never reads knowledge and never runs the agent. That work is done with
each customer's own token.

Keep it as a secret on your server, as you keep the install tokens:

```sh
npx wrangler secret put OMAZY_ACCOUNT_KEY
```

## Create a customer's workspace

`workspaces.create` makes the workspace, its agent, its plan and its install,
and returns the install token. Your own id for the customer goes in
`external_id`.

```ts
/** Creates the customer's workspace, or finds it, and makes sure a token for it is stored. */
export async function onboard(env: Env, customer: { id: string; name: string }) {
  const account = new OmazyEnterprise({ token: env.OMAZY_ACCOUNT_KEY })

  // Your own id for the customer makes this safe to repeat.
  const made = await account.workspaces.create({ external_id: customer.id, name: customer.name })

  if (made.token && made.install) {
    // Shown once, on the call that minted it. Store it now.
    await storeToken(env, customer.id, made.workspace.id, made.token, made.install.token_prefix)
    return made.workspace
  }

  // A repeat returns the workspace and no token. If you hold one, you are done.
  const stored = await env.DB.prepare('SELECT 1 FROM omazy_tokens WHERE customer_id = ?').bind(customer.id).first()
  if (!stored) {
    // The first answer was lost before its token was stored: mint a new one.
    const rotated = await account.workspaces.rotateInstall(made.workspace.id, { overlap_hours: 0 })
    await storeToken(env, customer.id, made.workspace.id, rotated.token, rotated.install.token_prefix)
  }
  return made.workspace
}
```

Two rules make this safe to run again, from a retry, a second click or a
deploy that crashed halfway:

- **The same `external_id` is the same workspace.** A repeat answers
  `created: false` with the workspace that exists. The client retries it after
  a dropped connection for that reason.
- **The token is in the answer once**, on the call that minted it. A repeat
  has `token: null`. If you hold a token for that customer, you are done. If
  you do not, because the first answer was lost before you stored it, rotate:
  that mints a new one. `overlap_hours: 0` cuts off the lost one at once,
  since nothing holds it.

`external_id` is 1 to 128 letters, digits and `. _ : -`. Use the id your own
database already has for the customer. Never a name, which changes.

<Tabs syncKey="sdk-lang">
<TabItem label="TypeScript">

```ts
const account = new OmazyEnterprise({ token: env.OMAZY_ACCOUNT_KEY })
const made = await account.workspaces.create({ external_id: customer.id, name: customer.name })
```

</TabItem>
<TabItem label="Python">

```python
account = OmazyEnterprise(os.environ["OMAZY_ACCOUNT_KEY"])
made = account.workspaces.create(external_id=customer_id, name=name)
if made["token"]:
    store_token(customer_id, made["workspace"]["id"], made["token"])  # shown once
elif not has_token(customer_id):
    rotated = account.workspaces.rotate_install(made["workspace"]["id"], overlap_hours=0)
    store_token(customer_id, made["workspace"]["id"], rotated["token"])
```

</TabItem>
<TabItem label="Go">

```go
acct := omazy.NewEnterprise(os.Getenv("OMAZY_ACCOUNT_KEY"))
made, err := acct.CreateWorkspace(ctx, omazy.CreateWorkspaceRequest{ExternalID: customerID, Name: name})
if err != nil {
	return err
}
if made.Token != "" {
	err = storeToken(customerID, made.Workspace.ID, made.Token) // shown once
} else if !hasToken(customerID) {
	now := 0
	r, rerr := acct.RotateInstall(ctx, made.Workspace.ID, omazy.RotateInstallRequest{OverlapHours: &now})
	if rerr != nil {
		return rerr
	}
	err = storeToken(customerID, made.Workspace.ID, r.Token)
}
```

</TabItem>
</Tabs>

### What a customer's token may do

Unless your account asks for something else, each customer's install gets
these scopes: `ai:complete`, `ai:configure`, `agent:run`, `agent:configure`,
`kb:search`, `kb:read`, `kb:write`, `voice:speech`, `core:read`, `core:write`,
`memory:write` and `usage:read`. `ai:configure` (model roles and spend caps)
joined the list on 24 Nov 2026. An install made before then keeps the scopes
it was made with, and rotating its token keeps them too; ask the Omazy team to
add the scope.

Placing phone calls (`voice:calls`), publishing to a page
(`channels:publish`), connecting MCP tool servers to the agent (`agent:tools`)
and binding a person's own tool credential (`sessions:credentials`) are left
out. Ask the Omazy team to add them to your account's install if your product
needs them. A customer's token never expires unless your account sets a
lifetime: you rotate on your own schedule.

## Keep each token encrypted

A customer's token reaches everything that customer has on Omazy. Store it
encrypted, with a key that lives in your Worker's secrets and not in the
database. If the database leaks, the tokens in it are useless.

This uses AES-GCM from `crypto.subtle`, which every Worker has. The customer's
id is bound into each ciphertext, so a sealed token copied into another
customer's row fails to open instead of quietly serving the wrong customer.

```ts
const b64 = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
const unb64 = (s: string) =>
  Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (s.length % 4)) % 4)), (c) => c.charCodeAt(0))

async function aesKey(keyText: string): Promise<CryptoKey> {
  const raw = unb64(keyText)
  if (raw.length !== 32) throw new Error('TOKEN_KEY must be 32 bytes, base64url')
  return crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt', 'decrypt'])
}

// The customer id is bound into the ciphertext, so a sealed token copied to
// another customer's row will not open.
const aad = (customerId: string) => new TextEncoder().encode(`omazy-token.v1.${customerId}`)

async function seal(env: Env, customerId: string, token: string): Promise<string> {
  const iv = crypto.getRandomValues(new Uint8Array(12))
  const ct = await crypto.subtle.encrypt(
    { name: 'AES-GCM', iv, additionalData: aad(customerId) },
    await aesKey(env.TOKEN_KEY),
    new TextEncoder().encode(token),
  )
  return `v1.${b64(iv)}.${b64(new Uint8Array(ct))}`
}

async function open(env: Env, customerId: string, sealed: string): Promise<string> {
  const [v, iv, ct] = sealed.split('.')
  if (v !== 'v1' || !iv || !ct) throw new Error('unknown sealed token format')
  const pt = await crypto.subtle.decrypt(
    { name: 'AES-GCM', iv: unb64(iv), additionalData: aad(customerId) },
    await aesKey(env.TOKEN_KEY),
    unb64(ct),
  )
  return new TextDecoder().decode(pt)
}
```

```ts
async function storeToken(env: Env, customerId: string, workspaceId: string, token: string, prefix: string) {
  await env.DB.prepare(
    `INSERT INTO omazy_tokens (customer_id, workspace_id, sealed, prefix) VALUES (?, ?, ?, ?)
     ON CONFLICT (customer_id) DO UPDATE SET workspace_id = excluded.workspace_id, sealed = excluded.sealed, prefix = excluded.prefix`,
  )
    .bind(customerId, workspaceId, await seal(env, customerId, token), prefix)
    .run()
}
```

The table this writes:

```sql
CREATE TABLE omazy_tokens (
  customer_id  TEXT PRIMARY KEY,
  workspace_id TEXT NOT NULL,
  sealed       TEXT NOT NULL,  -- v1.<iv>.<ciphertext>
  prefix       TEXT NOT NULL   -- cai_<prefix>: safe to show and log
);
```

Make the key once and keep it as a secret:

```sh
node -e "console.log(Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64url'))"
npx wrangler secret put TOKEN_KEY
```

Show and log the `prefix`, never the token. It is enough to tell tokens apart
in a support conversation.

## Call Omazy as a customer

`account.core(token)` gives the Core API client for one customer, pointed at
the same deployment as the account client. Pick the token from the request
you are serving, open it, and call.

```ts
const opened = new Map<string, { token: string; until: number }>()

/** The Core API client for one customer. Decrypted tokens are kept for a minute. */
export async function omazyFor(env: Env, customerId: string): Promise<Omazy> {
  let hit = opened.get(customerId)
  if (!hit || hit.until < Date.now()) {
    const row = await env.DB.prepare('SELECT sealed FROM omazy_tokens WHERE customer_id = ?')
      .bind(customerId)
      .first<{ sealed: string }>()
    if (!row) throw new Error(`customer ${customerId} has no Omazy token`)
    hit = { token: await open(env, customerId, row.sealed), until: Date.now() + 60_000 }
    opened.set(customerId, hit)
  }
  return new OmazyEnterprise({ token: env.OMAZY_ACCOUNT_KEY }).core(hit.token)
}

export async function answer(env: Env, customerId: string, question: string) {
  const omazy = await omazyFor(env, customerId)
  const passages = await omazy.knowledge.search(question, { top_k: 4 })
  return omazy.ai.complete({
    system: 'Answer from these passages only.\n\n' + passages.map((p) => p.content).join('\n\n'),
    messages: [{ role: 'user', content: question }],
    cache_ttl: 0,
  })
}
```

Opening a token costs a database read and a decrypt. Keeping the opened token
for a minute saves both on every request, and a rotation still takes effect
within that minute.

## Rotate a token

Rotate on a schedule, when someone who could read it leaves, and at once when
one may have leaked. The old token keeps working for `overlap_hours` (24 by
default, at most 168), so requests in flight finish and every instance of
your Worker has time to pick up the new one.

```ts
export async function rotate(env: Env, customerId: string, workspaceId: string) {
  const account = new OmazyEnterprise({ token: env.OMAZY_ACCOUNT_KEY })
  // The old token keeps working for a day, so requests in flight finish.
  const { token, install } = await account.workspaces.rotateInstall(workspaceId, { overlap_hours: 24 })
  await storeToken(env, customerId, workspaceId, token, install.token_prefix)
  opened.delete(customerId)
}

export async function stillOnOldToken(omazy: Omazy) {
  const me = await omazy.whoami()
  return me.token === 'previous' || omazy.last.tokenIsPrevious
}
```

While a request still uses the replaced token, every response says so:
`omazy.last.tokenIsPrevious` is true, and `whoami()` answers
`token: 'previous'`. Alert on it and you find the instance that missed the
new token before the overlap ends.

For a leak, rotate with `overlap_hours: 0`. The leaked token stops on its next
request.

The client never sends a rotation twice: each run replaces the token before
it, so a blind retry would cut off the token the first run gave you.

## Usage per customer

Two ways, depending on who asks.

Across all your customers, with the account key: one page of workspaces at a
time, each with its totals and days, and the totals of the whole account on
every page.

```ts
export async function monthlyUsage(env: Env) {
  const account = new OmazyEnterprise({ token: env.OMAZY_ACCOUNT_KEY })
  const rows: { customer: string; ai_turns: number; voice_minutes: number; cost_usd: number }[] = []
  let cursor: string | undefined
  do {
    const page = await account.usage({ from: '2026-11-01', to: '2026-11-30', cursor })
    for (const w of page.workspaces) {
      rows.push({
        customer: w.workspace.external_id,
        ai_turns: w.totals.ai_turns,
        voice_minutes: w.totals.voice_minutes,
        cost_usd: w.totals.cost_usd,
      })
    }
    cursor = page.next_cursor
  } while (cursor)
  return rows
}

export async function oneCustomerUsage(env: Env, customerId: string) {
  const omazy = await omazyFor(env, customerId)
  const report = await omazy.usage.get({ from: '2026-11-01', to: '2026-11-30' })
  return report.totals
}
```

<Tabs syncKey="sdk-lang">
<TabItem label="TypeScript">

```ts
const page = await account.usage({ from: '2026-11-01', to: '2026-11-30' })
for (const w of page.workspaces) console.log(w.workspace.external_id, w.totals.ai_turns, w.totals.cost_usd)
```

</TabItem>
<TabItem label="Python">

```python
page = account.usage(from_="2026-11-01", to="2026-11-30")
for w in page["workspaces"]:
    print(w["workspace"]["external_id"], w["totals"]["ai_turns"], w["totals"]["cost_usd"])
```

</TabItem>
<TabItem label="Go">

```go
page, err := acct.Usage(ctx, omazy.AccountUsageQuery{From: "2026-11-01", To: "2026-11-30"})
if err != nil {
	return err
}
for _, w := range page.Workspaces {
	fmt.Println(w.Workspace.ExternalID, w.Totals.AITurns, w.Totals.CostUSD)
}
```

</TabItem>
</Tabs>

A range is at most 90 days, both ends included, as UTC days. The cost fields
are the base cost of the calls, in US dollars and in millionths of one
(`cost_micros`): the vendor's price (`vendor_cost_micros`) plus the Omazy
service fee on speech (`fee_micros`). Omazy sets them; nothing in a request
changes them. Calls a workspace makes on its own provider key are not in
them. `ai_turns`, `api_calls`, `conversations` and
`voice_minutes` are what the plan counts. Your prices to your customers are
yours: add your margin to `cost_micros`, or to the `usage` on each answer,
which you can tag with your own feature names as you log them. Keep no copy of
the vendors' prices.

## Suspend, resume and close

```ts
const ws = await account.workspaces.findByExternalId(customer.id)
if (ws) await account.workspaces.suspend(ws.id)
```

A suspended workspace's calls are refused with `403 WORKSPACE_INACTIVE` within
about 30 seconds. A call already running finishes. `resume` serves it again.
`close` stops it for good from your side; nothing is erased, and `resume`
reopens it. A refused call never costs an AI turn.

## Bring an existing workspace under your account

Sometimes a customer already has an Omazy workspace, with its knowledge, its
widget and its phone line set up, before they become your customer. You do
not have to copy it into a new one. The Omazy team can adopt it into your
account.

Adoption is done by an Omazy operator, never with an account key. An account
key must not be able to claim a workspace someone else built just by knowing
its name. Ask the team, and say which workspace and which `external_id` it
should have.

What adoption does:

- The workspace joins your account under the `external_id` you gave.
- Its plan follows your account's, as a workspace you created would.
- It gets an install with your account's scopes. The token is handed to you
  once, as on a create.
- It keeps its owner, its knowledge, its agent and everything else it had.
- It is refused for a workspace that belongs to another account, for an
  `external_id` you already use, and past your account's workspace limit.

After that it is one of your workspaces like the others: the same calls, the
same usage report.

## Lessons from production

These come from a product that serves its customers this way today.

- **Pick the token per request, from the request.** The customer comes from
  the screen, the session or the subdomain you are serving, never from a
  global. A token held in a module-level variable serves whoever came last.
- **One token per customer, always.** A shared fallback token keeps a screen
  answering when a customer's token is missing or refused, but it bills the
  wrong workspace and searches the wrong knowledge. If you keep one while
  customers move over, log every use of it as its own event, and remove it.
- **Treat `401` and `403` on a customer's token as a broken link, not a bad
  request.** The token was rotated away, revoked, or the workspace was
  suspended. Alert, and show the customer a calm message.
- **Never send a token to a browser.** A browser talks to your backend, your
  backend talks to Omazy. For live speech, relay the audio: see
  [Speech](/build-on-omazy/speech/#relay-from-a-browser).
- **Read the account's limit.** `account.account()` reports how many
  workspaces you manage and the cap (`limits.managed_workspaces`). Check it
  before a sales push, not after the first refusal.

## Reference

- [Client libraries](/reference/core-api/client-libraries/): every method
- [Authentication](/reference/core-api/authentication/): tokens, scopes and rotation
- [Errors and limits](/reference/core-api/errors-and-limits/): every code
