ai-chat example #
On this page
A web app with sign-in and a conversation with an AI model under the allowance, kept in the page.
These files come from the same source as the scaffold command. They are the starter files before the command adds library packages, application settings, and installed dependencies.
With a shell #
This template downloads Turn Zero library packages. The command needs this computer's token, kept by turnzero login or turnzero authorize, or TURNZERO_CLOUD_MINTED_TOKEN set for this invocation. Without either, it writes nothing, prints the authorization steps, and exits with status 3.
Authorize this computer, or read How the command finds its credential to use an existing token.
With no CLI token, follow From a chat to adapt these files and deploy through a signed-in MCP connection.
Run this in a new project's root:
turnzero scaffold --template ai-chat
Follow the command's next steps. It writes the application in app/, takes the required library packages, installs dependencies, and runs the tests. The turnzero command explains setup and options.
From a chat #
A Cloud tool name without a prefix is its HTTP API name; your MCP connection lists it with tzcloud_ before it. The copied AGENTS.md instructions below use the names listed by the MCP connection.
Follow Deploy from a chat. Adapt this example if it fits the app the person requested.
The scaffold can bind its manifest to an application with --application <application id>. From a chat, name the application explicitly in submit_manifest and deploy_files. The platform uses the application named in the call and checks an uploaded manifest's optional application ID only for lowercase UUID form. turnzero deploy and turnzero check refuse a folder whose manifest names another application.
Keep the application paths shown in the table. The download URLs end in .txt so a browser reads the code instead of running it; that suffix is not part of the application filename. Each file is also reproduced below for tools reading this page through MCP.
The template manifest starts with an empty packages list. Read each @turnzero/ dependency's library entry and copy its current name and version into that list. Keep the file:lib/… dependencies in package.json. Leave the files under those lib/ paths out of the deploy_files request; Cloud supplies them from the library. Send no placeholder versions or hashes.
Files #
Paths are relative to the application root—the folder containing package.json. deploy_files uses these paths without an app/ prefix.
| Application path | Read source |
|---|---|
.gitignore |
Text |
AGENTS.md |
Text |
client/app.js |
Text |
client/index.html |
Text |
client/styles.css |
Text |
manifest.json |
Text |
package.json |
Text |
src/ai.mjs |
Text |
src/main.mjs |
Text |
src/server.mjs |
Text |
src/session.mjs |
Text |
test/app.test.mjs |
Text |
File contents #
.gitignore #
node_modules/
.env
.env.*
AGENTS.md #
# This service runs on Turn Zero Cloud
The service in this folder is hosted on Turn Zero Cloud. It started from the platform's `ai-chat` template: a Node.js service with a web page and sign-in for its users. The page keeps a conversation with an AI model called through the platform's AI route. Calls draw the account's balance, with no key of your own. This file describes the template the service started from: keep it current as the service changes.
## Where you build
- The page: `client/`, plain HTML, CSS, and script, which the platform serves at the application's address. It keeps the conversation for the page's life and posts its turns with each message.
- The routes: `src/server.mjs`. The service started with one route under `/api/`, `POST /api/ask`, which reads the signed-in user and answers the conversation's next turn.
- The AI model: `src/ai.mjs`, which calls the platform's AI route with the conversation's most recent turns. Calls draw the account's balance, with no key of your own.
## Where the rules are
Turn Zero Cloud serves its rules to a coding tool through the MCP server `turnzero`, one connection to the products your account holds. The rules change with the platform, so none is repeated here.
- Where the server is not connected, set up Turn Zero Cloud first: https://turnzero.ai/cloud/getting-started/set-up/
- Before you change or deploy this service, read the server's `deploy` skill, and before you change its sign-in or its AI call, the server's `add-sign-in` or `use-ai-allowance` skill.
## What you run here
- The tests: `npm test`, in this folder.
- A local run and a deploy: the `deploy` skill gives each step and the line to run, in this order: `tzcloud_submit_manifest`, the local run, `tzcloud_deploy_command`.
- Sign-in on a local run: start it with `--sign-in` and the application's own hostname, then open the address its port line names; the command sends the sign-in routes to that hostname. Without `--sign-in`, the page a local run serves has no sign-in routes, sign-in is on the deployed application's own address, and a local run's API routes take a session as a Bearer.
client/app.js #
// client/app.js: the page's script. It calls the backend on the same
// address, so the browser sends the sign-in cookie with each request. The
// conversation lives in this page for the page's life: each message posts the
// turns so far with the new one, and the server keeps nothing.
// Why the AI model gave no answer, by the error the route answers with 503.
const UNANSWERED = {
allowance_unavailable: 'The platform has no key for its AI route, so the model cannot answer.',
account_paused: 'AI calls for this account are paused at a zero balance until the next UTC month starts.',
upstream_quota: 'The AI model is out of capacity now: ask again in a while.',
};
// The conversation after one exchange: the turns with the user's message and
// the model's answer added; or, where the answer has no text or none came,
// the turns as they were, the message dropped with it, so the turns keep
// alternating and the next message ends them on the user's turn.
export function afterExchange(turns, message, answer) {
if (typeof answer !== 'string' || answer.trim() === '') return turns;
return [...turns, { role: 'user', content: message }, { role: 'assistant', content: answer }];
}
const byId = (id) => document.getElementById(id);
// The signed-in user, from the platform's own route: null where no one is signed in.
async function signedInUser() {
const response = await fetch('/__account/me');
if (response.status === 200) return (await response.json()).user;
if (response.status === 404) {
byId('who').textContent = "Sign-in is unavailable at this address. For a local run, start with --sign-in and the application's hostname. Otherwise sign in at the application's deployed address.";
return undefined;
}
return null;
}
function showTurns(turns) {
const list = byId('turns');
list.replaceChildren();
for (const turn of turns) {
const item = document.createElement('li');
item.className = turn.role;
item.textContent = `${turn.role === 'user' ? 'You' : 'AI'}: ${turn.content}`;
list.append(item);
}
}
function buildChat() {
let turns = [];
byId('send').addEventListener('submit', async (event) => {
event.preventDefault();
const message = byId('message').value;
if (message.trim() === '') return;
const status = byId('status');
status.textContent = 'Waiting for the answer.';
const messages = [...turns, { role: 'user', content: message }];
showTurns(messages);
let answer = null;
try {
const response = await fetch('/api/ask', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ messages }) });
if (response.status === 200) answer = (await response.json()).answer;
if (response.status === 200) status.textContent = answer?.trim() ? '' : 'The AI model gave no answer.';
else if (response.status === 503) status.textContent = UNANSWERED[(await response.json()).error] ?? 'The AI model gave no answer now.';
else status.textContent = `The message was not answered (status ${response.status}).`;
} catch {
status.textContent = 'The message was not sent.';
}
// An answered message clears the box; an unanswered one stays in it to send again.
const kept = afterExchange(turns, message, answer);
if (kept !== turns) byId('send').reset();
turns = kept;
showTurns(turns);
});
}
async function start() {
const user = await signedInUser();
if (user === undefined) return;
if (user === null) {
byId('who').textContent = 'No one is signed in.';
byId('sign-in').hidden = false;
return;
}
const address = user.addresses?.find((held) => held.verified)?.email;
byId('who').textContent = `Signed in as ${address ?? user.id}.`;
byId('sign-out').hidden = false;
byId('signed-in').hidden = false;
buildChat();
}
// The page starts in a browser; a test imports afterExchange alone.
if (typeof document !== 'undefined') start();
client/index.html #
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AI chat</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<header>
<h1>AI chat</h1>
<p id="who">Reading who is signed in.</p>
<nav>
<a id="sign-in" href="/__account/signin" hidden>Sign in</a>
<a id="sign-out" href="/__account/signout" hidden>Sign out</a>
</nav>
</header>
<main id="signed-in" hidden>
<ol id="turns"></ol>
<form id="send">
<textarea id="message" rows="3" maxlength="4000" required></textarea>
<button type="submit">Send</button>
</form>
<p id="status"></p>
</main>
<script type="module" src="/app.js"></script>
</body>
</html>
client/styles.css #
/* client/styles.css */
:root {
color-scheme: light dark;
font-family: system-ui, sans-serif;
line-height: 1.5;
}
body {
max-width: 40rem;
margin: 0 auto;
padding: 1rem;
}
header nav a {
margin-right: 1rem;
}
ol {
list-style: none;
padding: 0;
}
ol li {
margin: 0.5rem 0;
white-space: pre-wrap;
}
ol li.user {
font-weight: 600;
}
form {
display: grid;
gap: 0.5rem;
margin: 1rem 0;
}
textarea,
button {
font: inherit;
padding: 0.4rem;
}
button {
justify-self: start;
}
manifest.json #
{
"manifest_version": 1,
"services": [{ "kind": "accounts" }],
"health": "/health",
"region": "usa",
"egress": [],
"audience": { "kind": "public" },
"packages": []
}
package.json #
{
"name": "ai-chat",
"private": true,
"type": "module",
"scripts": {
"start": "node src/main.mjs",
"test": "node --test"
},
"dependencies": {
"@turnzero/account": "file:lib/account",
"@turnzero/ai_allowance": "file:lib/ai_allowance"
}
}
src/ai.mjs #
// src/ai.mjs: a reply from an AI model through the platform's AI route.
// Calls draw the account's balance, with no key of your own (Call an AI model).
import { AllowanceRefusal, AllowanceUpstreamError, generateText } from '@turnzero/ai_allowance';
// The most recent turns a reply sends to the model: an odd count, so the
// window of a conversation that ends on the user's turn starts on one too.
export const RECENT_TURNS = 11;
// The live transport, which only the process entry opens: the platform's
// origin and this copy's credential, from the settings it receives. A local
// run receives the development credential, so the same transport works there.
// Where the credential is not set, it sends nothing and says which line writes it.
export function liveTransport() {
const origin = process.env.TURNZERO_CLOUD_GATEWAY_URL ?? process.env.TURNZERO_CLOUD_API;
return (path, init = {}) => {
const credential = process.env.TURNZERO_CLOUD_APP_TOKEN;
if (!credential) throw new Error('TURNZERO_CLOUD_APP_TOKEN is not set, so no request was sent. Run the provision line again, then start the app again.');
return fetch(origin + path, { ...init, headers: { ...init.headers, authorization: `Bearer ${credential}` } });
};
}
// The replier over any transport: the live one, or a test double's. It is
// handed a conversation, turns that alternate and start and end on the
// user's, and sends its most recent RECENT_TURNS to the model in one call.
// It answers { answer }, the model's next turn, or { unanswered } naming why
// the model gave none: allowance_unavailable, the platform's key is not in
// place; account_paused, the account's AI calls are paused at a zero
// balance; or upstream_quota, the provider is out of capacity. It keeps
// nothing: the page holds the conversation.
export function createReplier(transport) {
return async (messages, signal) => {
try {
const answer = await generateText(transport, {
system: 'You are a helpful assistant. Answer in a few sentences.',
messages: messages.slice(-RECENT_TURNS),
maxOutputTokens: 400,
}, { signal });
return { answer: answer.text };
} catch (error) {
// Choose the fallback by the refusal's name, never by its message.
const refusal = error instanceof AllowanceRefusal ? error.refusal : null;
if (refusal === 'allowance_unavailable') return { unanswered: 'allowance_unavailable' };
if (refusal === 'account_paused') return { unanswered: 'account_paused' };
const providerFull = error instanceof AllowanceUpstreamError && error.quota;
if (providerFull) return { unanswered: 'upstream_quota' };
throw error;
}
};
}
src/main.mjs #
// src/main.mjs, the process entry the start script runs
import { createReplier, liveTransport } from './ai.mjs';
import { createUserReader, openLiveAccounts } from './session.mjs';
import { createAppServer } from './server.mjs';
const port = Number(process.env.PORT ?? 8080);
const server = createAppServer({ userIdOf: createUserReader(openLiveAccounts()), reply: createReplier(liveTransport()) });
server.listen(port, () => console.log(`listening on ${port}`));
src/server.mjs #
// src/server.mjs
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
// The web client's three files, by the path a browser asks for them. On the
// platform, the deploy serves them from client/ ahead of these routes, and a
// local run that names a port answers them the same way. A test, or a local
// run that names none, has nothing in front of it, so this server answers them.
const CLIENT_FILES = Object.freeze({
'/': ['index.html', 'text/html; charset=utf-8'],
'/index.html': ['index.html', 'text/html; charset=utf-8'],
'/app.js': ['app.js', 'text/javascript; charset=utf-8'],
'/styles.css': ['styles.css', 'text/css; charset=utf-8'],
});
// The longest turn the chat route takes, in characters.
export const TURN_LENGTH_MAX = 4000;
const readBody = async (request) => {
// One decoder for the whole body: a character whose bytes arrive in two chunks is read whole.
request.setEncoding('utf8');
let text = '';
for await (const chunk of request) text += chunk;
return text;
};
// The conversation a request posts as { messages }, or null where it is not
// one the route takes: an array of { role, content } turns that alternate,
// user then assistant, and start and end on a user turn, each content a
// string with a character that is not white space and at most
// TURN_LENGTH_MAX characters.
export function conversationOf(posted) {
const messages = posted?.messages;
if (!Array.isArray(messages) || messages.length % 2 === 0) return null;
const turns = [];
for (const [index, turn] of messages.entries()) {
const role = index % 2 === 0 ? 'user' : 'assistant';
if (turn === null || typeof turn !== 'object' || turn.role !== role || typeof turn.content !== 'string') return null;
if (turn.content.trim() === '' || turn.content.length > TURN_LENGTH_MAX) return null;
turns.push({ role, content: turn.content });
}
return turns;
}
// A request's abort signal. The deployed runtime attaches its own signal to each
// request, and it aborts at the request's window. A local run has none of its own,
// and Node's request.signal can abort at a normal request end on some Node 24
// releases, so a local run's signal aborts when the response closes unfinished.
function abortSignalOf(request, response) {
const own = Object.hasOwn(request, 'signal') ? request.signal : undefined;
if (own) return own;
const controller = new AbortController();
response.once('close', () => {
if (!response.writableFinished) controller.abort();
});
return controller.signal;
}
// The server over its two parts: userIdOf, which reads the signed-in user's
// id from a request, or null; and reply, which answers a conversation's next
// turn under the AI allowance, or names why the model gave no answer.
export function createAppServer({ userIdOf, reply }) {
return createServer(async (request, response) => {
// End the response when the request is aborted (abortSignalOf, above).
const signal = abortSignalOf(request, response);
signal.addEventListener('abort', () => response.destroy(), { once: true });
const send = (status, body) => {
if (response.destroyed) return;
response.writeHead(status, { 'content-type': 'application/json' });
response.end(JSON.stringify(body));
};
try {
// A target that does not parse as a URL names no route, so it is answered 404 below.
let pathname = null;
try {
pathname = new URL(request.url, 'http://localhost').pathname;
} catch {}
// The service keeps no store, so its health is the process answering.
if (request.method === 'GET' && pathname === '/health') return send(200, { ok: true });
if (request.method === 'GET' && Object.hasOwn(CLIENT_FILES, pathname)) {
const [file, type] = CLIENT_FILES[pathname];
try {
const body = await readFile(new URL(`../client/${file}`, import.meta.url));
if (!response.destroyed) response.writeHead(200, { 'content-type': type }).end(body);
return;
} catch (error) {
if (error?.code === 'ENOENT') return send(404, { error: 'not_found' });
throw error;
}
}
// The route under /api/ answers the signed-in user alone.
if (pathname === '/api/ask') {
const user = await userIdOf(request);
if (user === null) return send(401, { error: 'sign_in_required' });
if (request.method === 'POST') {
const conversation = conversationOf(JSON.parse(await readBody(request)));
if (conversation === null) return send(400, { error: 'invalid_messages' });
// 503 names why the model gave no answer: allowance_unavailable,
// account_paused, or upstream_quota (src/ai.mjs).
const replied = await reply(conversation, signal);
return 'answer' in replied ? send(200, { answer: replied.answer }) : send(503, { error: replied.unanswered });
}
}
send(404, { error: 'not_found' });
} catch (error) {
const refused = error instanceof SyntaxError ? 'invalid_json' : null;
if (refused === null && !signal.aborted) console.error(error);
send(refused === null ? 500 : 400, { error: refused ?? 'internal' });
}
});
}
src/session.mjs #
// src/session.mjs: the signed-in user who sent a request, as the guide Add
// sign-in to your app shows it.
import { makeVerifyClient } from '@turnzero/account';
// The cookie a signed-in browser sends with each request to the application's address.
const SESSION_COOKIE = '__Host-turnzero_cloud_realm';
// The live client, which only the process entry opens. A deployed copy
// receives all three settings. A local run has no TURNZERO_CLOUD_REALM_KEYS,
// so the client is built without keys there and verifies through the
// platform's route. Where the credential is not set, the start stops and
// says which line writes it.
export function openLiveAccounts() {
const keys = process.env.TURNZERO_CLOUD_REALM_KEYS;
if (!process.env.TURNZERO_CLOUD_APP_TOKEN) throw new Error('TURNZERO_CLOUD_APP_TOKEN is not set, so no session can be verified. Run the provision line again, then start the app again.');
return makeVerifyClient({
baseUrl: process.env.TURNZERO_CLOUD_API,
credential: process.env.TURNZERO_CLOUD_APP_TOKEN,
...(keys ? { realmKeys: keys } : {}),
});
}
// The session token: the cookie's value from a browser, or the bearer from a
// native app or a local run.
export function sessionOf(request) {
const auth = request.headers.authorization ?? '';
if (auth.startsWith('Bearer ')) return auth.slice('Bearer '.length);
for (const part of (request.headers.cookie ?? '').split(';')) {
// Spaces and tabs come off a pair and nothing else, so a name is read as it stands.
let from = 0;
let to = part.length;
while (from < to && (part.charCodeAt(from) === 0x20 || part.charCodeAt(from) === 0x09)) from += 1;
while (to > from && (part.charCodeAt(to - 1) === 0x20 || part.charCodeAt(to - 1) === 0x09)) to -= 1;
const pair = part.slice(from, to);
const at = pair.indexOf('=');
if (at > 0 && pair.slice(0, at) === SESSION_COOKIE) return pair.slice(at + 1);
}
return null;
}
// The reader of a request's user: the signed-in user's id, or null with no
// live session. The token is verified by the Account package's client, with
// the x-turnzero-cloud-session header the serving router sets on each
// request it forwards.
export function createUserReader(accounts) {
return async (request) => {
const verdict = await accounts.verifySession(sessionOf(request), {
sessionHeader: request.headers['x-turnzero-cloud-session'] ?? null,
});
return 'user' in verdict ? verdict.user.id : null;
};
}
test/app.test.mjs #
// test/app.test.mjs
import assert from 'node:assert/strict';
import { after, before, beforeEach, test } from 'node:test';
import { createAccountDouble } from '@turnzero/account/testing';
import { createAiAllowanceDouble } from '@turnzero/ai_allowance/testing';
import { afterExchange } from '../client/app.js';
import { RECENT_TURNS, createReplier } from '../src/ai.mjs';
import { TURN_LENGTH_MAX, createAppServer } from '../src/server.mjs';
import { createUserReader } from '../src/session.mjs';
// The packages' two test doubles for the file: the realm's sign-in and the AI
// allowance. The server runs over them on a port of this machine.
let accounts;
let ai;
let server;
let base;
// A signed-in user, and the headers a browser of theirs sends.
let sam;
const signedIn = (user) => ({ cookie: `__Host-turnzero_cloud_realm=${user.session}`, 'x-turnzero-cloud-session': user.header });
// A conversation of the given length: user and assistant turns in turn, from the user's.
const conversation = (length) => Array.from({ length }, (_, index) => ({ role: index % 2 === 0 ? 'user' : 'assistant', content: `turn ${index + 1}` }));
const ask = (body, headers = signedIn(sam), at = base) =>
fetch(`${at}/api/ask`, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: typeof body === 'string' ? body : JSON.stringify(body) });
before(async () => {
accounts = await createAccountDouble();
ai = createAiAllowanceDouble();
server = createAppServer({ userIdOf: createUserReader(accounts.client()), reply: createReplier(ai.transport) });
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
base = `http://127.0.0.1:${server.address().port}`;
sam = accounts.signIn({ id: 'user-sam' });
});
// The allowance's answers and its record of calls cleared between tests, so each test starts from empty.
beforeEach(() => ai.reset());
after(async () => {
await new Promise((resolve) => server.close(resolve));
});
test('GET /health returns 200, with no store to reach', async () => {
const response = await fetch(`${base}/health`);
assert.equal(response.status, 200);
assert.deepEqual(await response.json(), { ok: true });
});
test('a local run serves the page, its script, and its stylesheet from client/', async () => {
for (const [path, type] of [['/', 'text/html'], ['/app.js', 'text/javascript'], ['/styles.css', 'text/css']]) {
const response = await fetch(`${base}${path}`);
assert.equal(response.status, 200, path);
assert.ok(response.headers.get('content-type').startsWith(type), path);
assert.ok((await response.text()).length > 0, path);
}
});
test('POST /api/ask answers 401 to a request with no session, and reads a session sent as a Bearer', async () => {
const signedOut = await ask({ messages: conversation(1) }, {});
assert.equal(signedOut.status, 401);
assert.deepEqual(await signedOut.json(), { error: 'sign_in_required' });
assert.equal(ai.calls.length, 0);
ai.prime('Hello.');
const bearer = await ask({ messages: conversation(1) }, { authorization: `Bearer ${sam.session}`, 'x-turnzero-cloud-session': sam.header });
assert.equal(bearer.status, 200);
});
test("POST /api/ask sends the conversation's turns to the model and answers its next turn through the platform's AI route", async () => {
ai.prime({ text: 'Lunch is at noon.', usage: { input: 40, output: 12 } }, { text: 'At one on Fridays.', usage: { input: 60, output: 10 } });
const first = [{ role: 'user', content: 'When is lunch?' }];
const answered = await ask({ messages: first });
assert.equal(answered.status, 200);
assert.deepEqual(await answered.json(), { answer: 'Lunch is at noon.' });
const second = [...first, { role: 'assistant', content: 'Lunch is at noon.' }, { role: 'user', content: 'And on Fridays?' }];
const followed = await ask({ messages: second });
assert.deepEqual(await followed.json(), { answer: 'At one on Fridays.' });
assert.deepEqual(ai.calls.map((call) => call.messages), [first, second]);
});
test(`a longer conversation sends its most recent ${RECENT_TURNS} turns, the window starting on the user's turn`, async () => {
ai.prime('The fifteenth turn answered.');
const long = conversation(15);
const response = await ask({ messages: long });
assert.equal(response.status, 200);
const sent = ai.calls[0].messages;
assert.equal(sent.length, RECENT_TURNS);
assert.equal(sent[0].role, 'user');
assert.deepEqual(sent, long.slice(-RECENT_TURNS));
});
test('a history that is not a conversation the route takes is refused 400, and no model is called', async () => {
const refused = [
{},
{ messages: [] },
{ messages: 'When is lunch?' },
{ messages: [{ role: 'assistant', content: 'Hello.' }] },
{ messages: [{ role: 'user', content: 'One.' }, { role: 'user', content: 'Two.' }, { role: 'user', content: 'Three.' }] },
{ messages: conversation(2) },
{ messages: [{ role: 'user', content: '' }] },
{ messages: [{ role: 'user', content: ' ' }] },
{ messages: [{ role: 'user', content: 7 }] },
{ messages: [null] },
{ messages: [{ role: 'user', content: 'x'.repeat(TURN_LENGTH_MAX + 1) }] },
];
for (const body of refused) {
const response = await ask(body);
assert.equal(response.status, 400, JSON.stringify(body).slice(0, 80));
assert.deepEqual(await response.json(), { error: 'invalid_messages' });
}
const notJson = await ask('{');
assert.equal(notJson.status, 400);
assert.deepEqual(await notJson.json(), { error: 'invalid_json' });
assert.equal(ai.calls.length, 0);
ai.prime('Read.');
const longest = await ask({ messages: [{ role: 'user', content: 'x'.repeat(TURN_LENGTH_MAX) }] });
assert.equal(longest.status, 200);
});
test('POST /api/ask answers 503 naming why the model gave no answer, for each of the three reasons', async () => {
const unanswered = async (error, status = 503) => {
const res = await ask({ messages: conversation(1) });
assert.equal(res.status, status, error);
assert.deepEqual(await res.json(), { error });
};
ai.refuseNext('allowance_unavailable');
await unanswered('allowance_unavailable');
ai.refuseNext('account_paused');
await unanswered('account_paused');
ai.prime({ status: 429, json: { error: { status: 'RESOURCE_EXHAUSTED' } } });
await unanswered('upstream_quota');
ai.refuseNext('allowance_exhausted');
await unanswered('internal', 500);
});
test("POST /api/ask hands the model call the request's signal, which ends it", async () => {
const controller = new AbortController();
const aborting = (path, init) => (controller.abort(), ai.transport(path, init));
const signalled = createAppServer({ userIdOf: createUserReader(accounts.client()), reply: createReplier(aborting) });
signalled.prependListener('request', (request) => Object.defineProperty(request, 'signal', { value: controller.signal }));
await new Promise((resolve) => signalled.listen(0, '127.0.0.1', resolve));
try {
await assert.rejects(ask({ messages: conversation(1) }, signedIn(sam), `http://127.0.0.1:${signalled.address().port}`));
assert.deepEqual(ai.calls.map((call) => [call.outcome, call.units]), [['aborted', null]]);
} finally {
await new Promise((resolve) => signalled.close(resolve));
}
});
test("the page keeps an answered exchange and drops a message the model left unanswered, so the next message ends the turns on the user's", () => {
const answered = afterExchange([], 'When is lunch?', 'Lunch is at noon.');
assert.deepEqual(answered, [
{ role: 'user', content: 'When is lunch?' },
{ role: 'assistant', content: 'Lunch is at noon.' },
]);
for (const answer of [null, undefined, '', ' ']) assert.equal(afterExchange(answered, 'And on Fridays?', answer), answered);
const next = [...answered, { role: 'user', content: 'And on Fridays?' }];
assert.deepEqual(next.map((turn) => turn.role), ['user', 'assistant', 'user']);
});