# ctx.ai

Ask an AI model from your app — Claude, ChatGPT, Gemini or Grok on Fave1 AI, paid from the person’s Fave1 credits. No keys anywhere, and you never pay.

ai · card mode · app mode

## Ask

Add `"ai"` to `permissions` in manifest.json, then ask:

`src/index.ts`

```ts
const res = await ctx.ai.chat({
  system: 'Summarize in three short bullets.',
  messages: ctx.page.title + '\n\n' + (ctx.page.text ?? ''),
});
ctx.ui.toast(res.text);
```

One string is one question — `ctx.ai.chat('Say hi')` works with no options at all. For a conversation, pass turns — `{ role: 'user' | 'assistant', content }` — starting and ending with the person. Up to 100 turns and 120,000 characters, `system` included.

> **Nothing to sign up for, nothing to pay.** Every AI in Fave1 is **Fave1 AI** — four models (Claude, ChatGPT, Gemini and Grok), paid from the person’s Fave1 credits, each at its own price. Fave1 picks which one answers, calls it for you and hands back only the answer. There’s no AI key to set up — not for you, not for them.

## fast and smart

You don’t name a model — Fave1 picks the AI and the model. You choose how hard it should think (or pass `ai` from `choices()` to ask a specific one):

| model | Use it for | default |
| --- | --- | --- |
| `'fast'` | Summaries, rewrites, tags, short answers — almost everything. Quick, and cheap for them | yes |
| `'smart'` | Harder thinking — planning, comparing, long writing. Slower, and costs them more | — |

`maxTokens` caps the answer (1 to 4,096, default 1,024 — more is lowered to 4,096). Lower is cheaper for the person — ask for what you’ll show. An answer that runs into it comes back cut off with `res.stop` `'length'` — check for that before you show it (with `json` it rejects instead).

The result’s `provider` and `model` say who answered. When the model Fave1 picked is busy or down before it starts answering, Fave1 hands the call to another of its four, charged at that model’s price — so label an answer from `res.provider`, never from what you expected. A call that names one with `ai` is never moved; it rejects instead.

## Streaming

Show the answer as it comes:

`src/index.ts`

```ts
const out = document.createElement('p');
const s = ctx.ai.stream({ messages: 'Write a haiku about this page.' });
for await (const part of s) {
  out.textContent += part.text;
}
const res = s.result();   // the whole answer — usage, model, stop — once the loop ends
```

Same options, same errors — an error is thrown from the loop. To stop a call, pass an `AbortSignal` as `signal`; it rejects with `aborted` and nothing more is charged.

## Pictures

Put a picture in a turn and ask about it — a product photo, a chart, a screenshot of the page:

`src/index.ts`

```ts
const res = await ctx.ai.chat({
  messages: [{ role: 'user', content: [
    { type: 'text', text: 'What is this, and roughly what does it cost?' },
    { type: 'image', image: canvas },
  ] }],
});
```

`image` takes a Blob, an `<img>`, a canvas, an `ImageBitmap`, `ImageData` or an image URL. Fave1 shrinks it to 1,568 pixels on the long side and 1.2 megapixels at most, and sends a JPEG — the same on every provider. A picture from another site that won’t share its pixels is fetched without cookies, like [fetchImage()](https://developers.fave1.com/docs/ctx-page.md#images); one it still can’t read rejects with `invalid` (`reason` `image`). Up to 8 pictures a call. Each one costs the person about as much as a page of text — send the one the feature needs.

## Answers in a shape

Give `json` a schema and read `res.data` — parsed, and already checked against it:

`src/index.ts`

```ts
const res = await ctx.ai.chat({
  messages: ctx.page.text ?? '',
  json: {
    type: 'object',
    properties: {
      title: { type: 'string', maxLength: 80 },
      price: { type: ['number', 'null'] },
      tags: { type: 'array', items: { type: 'string' }, maxItems: 5 },
    },
    required: ['title', 'price'],
  },
});
const product = res.data as { title: string; price: number | null; tags?: string[] };
```

The schema is a slice of JSON Schema: `type` (one type, or one plus `'null'`), `properties`, `required`, `items`, `enum`, `description`, and the checks `minimum` · `maximum` · `minLength` · `maxLength` · `minItems` · `maxItems`. Up to 6 levels below the top, 16,000 characters as JSON. Objects never get keys you didn’t name, and a property left out of `required` may be missing. If the model’s answer doesn’t fit, the call rejects with `provider` (`reason` `json`, `retryable`) — `err.detail` says where, `err.text` is what came back.

## Tools

Tools let the model ask your app for something mid-answer — the price on this page, the person’s saved list, a search in your data. `run()` handles the back and forth: when the model calls a tool, Fave1 runs yours, sends the result back and asks again, until it answers.

`src/index.ts`

```ts
const res = await ctx.ai.run({
  model: 'smart',
  messages: 'Is this cheaper than the one I saved yesterday?',
  tools: [{
    name: 'saved_items',
    description: 'The products this person saved, with prices. Call it to compare.',
    input: { type: 'object', properties: { limit: { type: 'integer', maximum: 20 } } },
    run: async ({ limit }) => (await ctx.storage.get('saved') as unknown[] ?? []).slice(0, limit ?? 20),
  }],
});
fill(res.text);
```

A tool’s `input` is an object schema; the model’s input is checked against it before `run` sees it, and a mismatch goes back to the model as an error so it can try again. Return anything — it goes back as JSON, cut at 50,000 characters, so return the part the model needs instead of a whole page — or throw to report a failure. Up to 32 tools a call, each with a name and a description of up to 2,000 characters. Each step is one call that counts against their limit; `maxSteps` (default 6, up to 10 — more is lowered) stops it, `onStep` tells you after each round of tool calls, and `res.steps` says how many it took. `res.messages` is the whole conversation — pass it back to ask a follow-up.

Want to decide yourself? Pass `tools` to `chat()` instead. When `res.stop` is `'tool'`, run `res.calls` (the same calls sit in `res.message` as `tool-call` parts), then continue with `res.message` and your results:

`src/index.ts`

```ts
const messages: AiMessage[] = [{ role: 'user', content: 'What does this cost in won?' }];
const tools = [{
  name: 'page_price',
  description: 'The price shown on this page, in dollars.',
  input: { type: 'object' as const, properties: {} },
}];
let res = await ctx.ai.chat({ messages, tools });
while (res.stop === 'tool') {
  messages.push(res.message);
  messages.push({ role: 'user', content: res.calls.map((c) => ({ type: 'tool-result' as const, id: c.id, content: '$12.99' })) });
  res = await ctx.ai.chat({ messages, tools });
}
fill(res.text);
```

> **Keep res.message as it is.** It carries the tool calls and a sealed `state` part — the model’s reasoning, which some providers need back on the next call. Don’t edit or drop it.

A tool can hand back a picture for the model to look at — a crop of the page, a chart you drew. Return the picture, or an array of words and pictures:

`src/index.ts`

```ts
const res = await ctx.ai.run({
  messages: 'Does the photo match what the listing says?',
  tools: [{
    name: 'product_photo',
    description: 'The main product photo on this page.',
    input: { type: 'object', properties: {} },
    run: () => {
      const img = document.querySelector('main img');
      return img instanceof HTMLImageElement ? ['The main photo:', img] : 'No photo on this page.';
    },
  }],
});
```

Anything `image` takes works here — a Blob, an `<img>`, a canvas, an `ImageBitmap`, `ImageData`. With `chat()`, put them on the result part: `{ type: 'tool-result', id, content, images: [canvas] }`. They count toward the 8 pictures a call. With `run()`, one that can’t be read is left out and the model is told; with `chat()`, it rejects with `invalid` (`reason` `image`).

## Voices

`speak()` turns text into a voice — an audio file you play, mix into your own sound, or record. There are **eighteen voices**: six each from OpenAI, Gemini and Grok. Pick one — or let them pick from your own list — and that voice’s company speaks it, on their Fave1 credits.

`src/index.ts`

```ts
const voices = await ctx.ai.voices();     // 18 — { id, name, by, tone, ready, pays, credits }
showPicker(voices);                        // your own UI: name, by, tone — and what it costs

const line = await ctx.ai.speak('Plum on my feet, two left, now I own it', {
  voice: 'fenrir',          // an id from voices() — or a tone: 'bold'
  style: 'Rap it on the beat, hype and punchy',
  speed: 1.2,               // 0.5 – 2
});
const audio = new Audio(URL.createObjectURL(line.audio));
audio.play();               // line.seconds — how long it runs
```

**The `ai` permission is all it takes.** Voices are Fave1 AI like everything else — paid from the person’s Fave1 credits, with nothing more to declare. Without credits `speak()` rejects with `no-credits`, like `chat()`, and Fave1 shows them how to get some.

| voices() | What it is | type |
| --- | --- | --- |
| `id` | What you pass to `speak({ voice })` — `nova`, `fenrir`, `rex`… | string |
| `name · by` | Its name and who makes it — `Grok`, `OpenAI` or `Gemini`. Show both in your picker. The list comes cheapest first: the fewest credits, then voices that aren’t ready | string |
| `tone` | `bright` · `warm` · `deep` · `calm` · `bold` · `smooth` — each company has one of each | string |
| `ready` | Would speak right now. Before the person has allowed AI every voice is `false` — call `speak()` anyway and Fave1 asks them | boolean |
| `pays` | `credits` — their Fave1 credits · `null` — not ready | string \| null |
| `credits` | About how many Fave1 credits 1,000 characters cost (2 – 6 today, by company) | number \| null |

| speak() | What it is | type |
| --- | --- | --- |
| `audio` | The voice — MP3 or WAV, as the company makes it | Blob |
| `type` | `audio/mpeg` or `audio/wav` | string |
| `seconds` | About how long it runs. Decode it (`AudioContext.decodeAudioData`) for the exact length | number |
| `voice · provider` | The voice `id` that spoke, and its company (`openai` · `google` · `xai`) | string |
| `paid` | `credits` — voices are paid from Fave1 credits | string \| null |
| `mock` | `true` in the sandbox — a short tone the length of your text, so timing works without spending credits | boolean |

- **Don’t care which company?** Pass a tone instead of an id — `voice: 'bold'`. Fave1 picks a company the person can pay for and uses its bold voice. `line.voice` tells you which one spoke. With a tone you can also pass `ai: 'openai'` · `'google'` · `'xai'` to pick the company.
- **One line at a time.** Up to 1,200 characters and a 300-character `style`. For a song or a story, speak it line by line — you get each piece sooner and can place it on your own timing.
- **Same limit, same rules.** It counts against your app’s monthly limit like `chat()`, asks the same Allow first, and takes a `signal`. With no Fave1 credits it rejects with `no-credits` — Fave1 has already shown them where to get credits.
- **No real people.** Don’t ask a voice to sound like a real singer, rapper or anyone else. Styles are fine — “warm and slow”, “hype”.

## Asking again

A chat sends the whole conversation every time. Set `cache: true` when you’ll ask again with the same start — a chat that keeps going, the same long `system` or page text — and the next call reads that start from the provider’s cache for a fraction of the price:

`src/index.ts`

```ts
const messages: AiMessage[] = [{ role: 'user', content: 'Page:\n' + (ctx.page.text ?? '') + '\n\nWhat is this about?' }];
let res = await ctx.ai.chat({ messages, cache: true });
messages.push(res.message, { role: 'user', content: 'And who wrote it?' });
res = await ctx.ai.chat({ messages, cache: true });
console.log(res.usage.cached); // tokens that came from the cache
```

The first call costs a little more to store it, so leave it off for one-off questions. `run()` turns it on for you — every step resends everything so far. Fave1 counts cached tokens at the cheaper price against the person’s limit, and so does every provider: some cache on their own even without it.

## Before they press the button

`status()` tells you whether a call would go through — so you can fold the feature or say what’s needed before anyone taps:

`src/index.ts`

```ts
const state = await ctx.ai.status();
if (state === 'ready' || state === 'ask') {
  // show the AI button — 'ask' means the first call will ask them once
} else {
  // 'no-credits' · 'off' · 'limit' · 'signed-out' · 'not-installed' · 'blocked' · 'unreachable'
  if (state === 'blocked' || state === 'unreachable') return;   // nothing they can turn on — fold the feature
  ctx.ui.render([
    ctx.ui.button(state === 'no-credits' ? 'Get Fave1 credits' : 'Set up AI', { onClick: () => { void ctx.ai.setup(); } }),
  ]);
}
```

| status | What it means | setup() opens |
| --- | --- | --- |
| `ready` | A call goes straight through | — |
| `ask` | The first call shows Fave1’s one-time OK, then goes through | the OK |
| `no-credits` | No Fave1 credits yet, or none left | Fave1 credits |
| `off` | They said Not now, turned AI off for your app, or Fave1 paused AI for your app | Settings › AI |
| `blocked` | Fave1 stopped your app — AI stays off for it. Fold the feature | nothing |
| `unreachable` | This page blocks Fave1 from reaching their account, or no answer came back. AI still works in app mode and on other sites — say so | nothing |
| `limit` | Your app’s monthly limit, or their total, is reached | Fave1’s card — raise the limit |
| `signed-out · not-installed` | Nobody’s signed in, or they haven’t added your app (Try it from the store) | sign in · add it |

`setup()` opens whatever fixes the state — the one-time OK, Fave1’s card to get credits or raise a limit, or Fave1 Settings › AI to add your app or turn it back on — and resolves `true` when AI is ready now. For `blocked` and `unreachable` there’s nothing to open; it resolves `false`. Only the person can turn things on. `ctx.can('ai')` is the cheap check: false when `ai` isn’t declared. Word your app the same way: AI runs on **Fave1 credits** — there’s no key for anyone to add.

## How much is left

`usage()` says what this person has spent on your app this month — show it, or go easy as it runs low:

`src/index.ts`

```ts
const u = await ctx.ai.usage();
if (u && u.left !== null && u.left < 0.05) {
  ctx.ui.toast('Running low on AI this month — short answers from here.');
}
const line = document.createElement('p');
if (u) line.textContent = `$${u.spent.toFixed(2)} of ${u.limit === null ? 'no limit' : '$' + u.limit.toFixed(2)} this month`;
```

| field | What it is | unit |
| --- | --- | --- |
| `spent` | Spent on your app this month (UTC), calls in flight included | $ |
| `limit` | Their limit for your app — `null` if they removed it | $ |
| `left` | What your app can still spend — the smallest of your limit, their total limit and their Fave1 credits. `null` when nothing limits it | $ |
| `requests` | Calls to the model this month | calls |
| `resetAt` | When it starts over — the 1st, UTC. `null` in a DEV build | ISO · null |
| `mock` | `true` in a DEV build that isn’t spending credits — the numbers are zeros | boolean |

Only your app’s numbers — never what they spend elsewhere. It resolves `null` wherever a call wouldn’t go through yet (signed out, before the first OK, no credits); `status()` tells you why. A DEV build gets zeros with `mock: true`. Amounts are in US dollars, worked out from the tokens each call used at that model’s Fave1 AI price.

## Ask another AI

Fave1 AI has four models — **Claude**, **ChatGPT**, **Gemini** and **Grok** — and every person can use all four on the same Fave1 credits. A plain `chat()` goes to the one Fave1 picks. `choices()` lists the rest, so your app can offer a second opinion, put two answers side by side or let them choose who answers — something no single AI’s own app can do.

`src/index.ts`

```ts
const question = 'Is this blender worth $49?';
const ais = await ctx.ai.choices();
const other = ais.others[0];

// Ask two at once and show both answers side by side
const [first, second] = await Promise.all([
  ctx.ai.chat(question),
  other ? ctx.ai.chat({ messages: question, ai: other.id }) : null,
]);
// Name each answer by who actually answered — a busy model can hand a plain chat() to another
const name = (id: string) => [ais.current, ...ais.others].find((c) => c?.id === id)?.name ?? 'AI';
showAnswers(`${name(first.provider)}: ${first.text}`, second ? `${name(second.provider)}: ${second.text}` : '');
```

| field | What it is | type |
| --- | --- | --- |
| `current` | The AI a plain `chat()` goes to right now — Fave1’s pick. If it’s busy, another may answer; `res.provider` says which. `null` where AI can’t be used right now | { id, name } |
| `others` | The other models that can answer right now. Pass an `id` (`anthropic` · `openai` · `google` · `xai`) as `ai` to `chat()` · `stream()` · `run()` | list |
| `locked` | Always `false` — kept so older code still reads it. There’s nothing extra to allow | boolean |

- **Comparing is fine.** Asking two or more models the same question is a normal use — it’s what a second opinion is. Each call is charged at that model’s price, so ask from something the person did and say in your UI which AI answered.
- **No extra question.** The one-time OK for your app covers all four models. `choices({ ask: true })` still works and behaves like `choices()`.
- **Same credits, same limit.** Every model is paid from the same Fave1 credits and counts against your app’s one monthly limit; `usage()` adds them up.
- **Send text across.** A `state` part belongs to the AI that made it. When you bring another AI into a conversation, send the question and the answers as plain text — not the first AI’s `result.message`.
- **One can rest.** Fave1 sometimes rests a model for a short while. If the one you picked is resting, the call rejects with `no-credits` and `err.reason` `'choice'` — read `choices()` again and offer another. Fave1 shows them nothing for this one. A call you pin with `ai` is never handed to another model: if that one is busy or over its per-minute limit, it rejects with `provider` (`busy` · `rate` · `model`).

In the sandbox (`npm run dev`, a review link) you get two mock AIs — `mock` and `mock2` — so you can build the whole flow without spending credits.

## When it doesn’t work

Every rejection is a `Fave1Error`. `err.message` is a plain sentence you can show as it is — it names the AI (`err.by`), says why in everyday words, and what to do right now — get Fave1 credits, wait for next month, try another AI. When `err.fixable` is `true` the person can fix it themselves — keep the message on screen (not a toast that fades) with a button that calls `ctx.ai.setup()`. When `err.shown` is `true`, Fave1 already put a card in front of them with their options, so don’t stack another popup.

| code | What happened · what to do | retry |
| --- | --- | --- |
| `no-credits` | No Fave1 credits — never had any (`reason` `none`) or none left (`credits-empty`); Fave1 showed them where to get some. Or the `ai` you asked for is resting right now (`choice`) — read `choices()` again | no |
| `no-voice` | `speak()` only — `reason` `maker`: that company’s voices are off for a moment, offer another · `choice`: `ai` isn’t `openai` · `google` · `xai` · `credits`: their credits ran out on the way (no credits up front is `no-credits`) | no |
| `denied` | Not declared (`reason` `undeclared`), they said Not now just now (`not-now`) or earlier (`off`), they turned AI off for your app (`off-in-settings`), or Fave1 paused AI for your app (`paused`) | no |
| `limit` | This month’s limit — yours (`scope` `app`) or their total (`all`). `resetAt` is the 1st, UTC | no |
| `rate` | More than 20 calls a minute from your app or 60 across all their apps (`reason` `minute`), or 2 at once (`busy`). Wait `retryAfter` seconds | later |
| `too-big` | Too much for one call (`reason` `images` · `text` · `style`, or none when the whole call is over) — a system prompt over 20,000 characters, a schema over 16,000, 120,000 characters of input including your schema and tools, 8 pictures, 1,200 characters to speak — trim what you send | no |
| `invalid` | The call itself is wrong — `reason` says which part (`messages` — 1 to 100 turns, 64 parts a message · `system` · `model` · `maxTokens` · `image` · `json` · `tools` · `cache` · `ai` · `maxSteps` · `text` · `voice` · `style` · `speed`) and `err.detail` says what to change | no |
| `provider` | The AI service failed — `reason` `busy` is worth one retry (`retryable`); `rate` — that AI’s per-minute limit (wait a minute, or ask another AI); `refused` means it declined the request; `json` — the answer didn’t fit your schema (worth a retry); `length` — it hit `maxTokens` first; `model` — that model isn’t available right now (try again later, or pass another `ai` from `choices()`); `bad` — the AI service gave an unexpected error. `err.text` holds what came back, if anything. From `speak()` the `reason` is `busy` (one retry) · `model` · `bad` · `refused`, with no `err.by` | if retryable |
| `aborted` | Your signal, the tab went to the background (`reason` `hidden`), or your app closed | no |
| `blocked` | Fave1 stopped your app — AI stays off for it. Fold the feature | no |
| `signed-out` | Nobody’s signed in to Fave1 here | no |
| `not-installed` | They haven’t added your app — a sideloaded run or Try it from the store. `ctx.ai.setup()` takes them to add it | no |
| `unreachable · timeout · server` | This page blocks Fave1’s frame, no answer came back, or something broke on our side | later |

`src/index.ts`

```ts
try {
  const res = await ctx.ai.chat({ messages: input.value });
  fill(res.text);
} catch (err) {
  const e = err as Fave1Error;
  if (e.code === 'aborted') return;                       // your signal, or the tab went to the background
  if (e.code === 'rate' || e.retryable) ctx.ui.toast(e.message);
  else if (e.fixable && !e.shown) fill(e.message);          // keep it on screen, next to a button that calls ctx.ai.setup()
  else if (e.code === 'denied' || e.code === 'blocked') fold();   // not for this app — fold the feature
}
function fold() { input.disabled = true; }
```

## What the person sees

The first call shows Fave1’s own line: **Let \<your app> use your Fave1 credits?** — what it sends, that it’s paid from their Fave1 credits, and the limit, with an Allow button that only Fave1 can press. Your call waits for it, then goes through. On a new site it asks once more for that site, like storage.

Each app has a monthly limit (**$5** unless they change it) and they have a total (**$20**). In Settings › AI they see what each app spent this month and switch any app off. Fave1 counts only how much was used — **what your app sends and what comes back isn’t kept**.

Before they get it, the store shows a **✦ AI** badge on every app that declares `ai` (**✦ Fave1 AI** on its page), so people know up front that its AI runs on Fave1 credits.

## While you build

> A DEV build gets a stand-in answer — `[mock] You asked: …` with `mock: true` — so the whole flow runs at no cost. With `tools` it calls your first tool once, with input that fits its schema; with `json` it returns the smallest value that fits. Set Data to “My account” in the DEV panel to try real answers on your own Fave1 credits; your DEV slot has a $2 limit.

## The rules

> **Ask from something the person did.** No calls at launch, no loops in the background, no calls just to fill space — it’s their money. Send what the feature needs, not the whole page every time. Say in your listing what you send to the AI. Apps that spend without asking get sent back in review, and Fave1 can pause AI for an app at any time.
