// 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; } }; }