import { createContext, html, useCallback, useContext, useEffect, useMemo, useRef, useState } from "./runtime.js";
// ---------------------------------------------------------------------------
// Account, shared content, plans, models and money.
//
// Everything shared between visitors lives in Supabase. If no project is
// connected yet the app runs in "preview" mode: the developer screens still
// work, but changes stay in this browser. That lets you set the site up,
// try it, then connect Supabase and publish the same edits to everyone.
// ---------------------------------------------------------------------------
export const DEVELOPER_EMAIL = "lucas.owen13@icloud.com";
const CONFIG_KEY = "explication.cloud.config.v1";
const PREVIEW_KEY = "explication.cloud.preview.v1";
const SDK_URL = "https://esm.sh/@supabase/supabase-js@2.45.4";
const T = {
settings: "explication_settings",
plans: "explication_plans",
models: "explication_models",
secrets: "explication_model_secrets",
content: "explication_content",
entitlements: "explication_entitlements",
usage: "explication_usage"
};
// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------
export function readConfig() {
let saved = {};
try {
saved = JSON.parse(localStorage.getItem(CONFIG_KEY) || "null") || {};
} catch {
saved = {};
}
const fromFile = (typeof window !== "undefined" && window.EXPLICATION_CONFIG) || {};
const url = String(saved.url || fromFile.supabaseUrl || "").trim().replace(/\/+$/, "");
const anonKey = String(saved.anonKey || fromFile.supabaseAnonKey || "").trim();
return { url, anonKey, developerEmail: DEVELOPER_EMAIL, ready: !!url && !!anonKey };
}
export function saveConfig({ url, anonKey }) {
const clean = { url: String(url || "").trim().replace(/\/+$/, ""), anonKey: String(anonKey || "").trim() };
localStorage.setItem(CONFIG_KEY, JSON.stringify(clean));
return clean;
}
export function forgetConfig() {
localStorage.removeItem(CONFIG_KEY);
}
// Where Supabase sends people back to after an email link. It must not include
// the app's #/route: Supabase appends the session to this address itself, and
// a second # would bury the tokens inside the route.
function appRedirect() {
if (typeof window === "undefined") return undefined;
return window.location.origin + window.location.pathname.replace(/\/+$/, "");
}
let sdkPromise = null;
let sdkKey = "";
async function loadSdk(config) {
const key = config.url + "|" + config.anonKey;
if (sdkPromise && sdkKey === key) return sdkPromise;
sdkKey = key;
sdkPromise = import(SDK_URL).then((mod) => mod.createClient(config.url, config.anonKey, {
auth: { persistSession: true, autoRefreshToken: true }
}));
return sdkPromise;
}
// ---------------------------------------------------------------------------
// Preview data (used until Supabase is connected)
// ---------------------------------------------------------------------------
export const DEFAULT_PLANS = [
{
id: "paragraph-lite",
name: "Paragraph Lite",
kind: "one_time",
price_cents: 400,
currency: "GBP",
interval: null,
blurb: "The little model that started it all, yours to keep. Download it once and mark paragraphs on the bus, on the train, anywhere.",
features: [
"Paragraph Lite — 2.5 GB, trained on 300 essays",
"Qwen3-4B base, runs offline after one download",
"Every marking tool, forever",
"Use your own AI key if you have one"
],
cost_limit_cents: 0,
download_tier: 1,
byok: true,
paypal_plan_id: "",
paypal_payment_link: "",
active: true,
sort: 1
},
{
id: "model-library",
name: "Model Library",
kind: "one_time",
price_cents: 1400,
currency: "GBP",
interval: null,
blurb: "All four Paragraph models in one go: Lite, Turbo, Novel and Ace. Nothing else to buy.",
features: [
"Paragraph Lite (2.5 GB) and Turbo (5.8 GB)",
"Paragraph Novel (7.4 GB) and Ace (61 GB)",
"Download on every device you own",
"Free updates when new models arrive"
],
cost_limit_cents: 0,
download_tier: 4,
byok: true,
paypal_plan_id: "",
paypal_payment_link: "",
active: true,
sort: 2
},
{
id: "exam-season",
name: "Exam Season",
kind: "one_time",
price_cents: 2400,
currency: "GBP",
interval: null,
blurb: "Everything unlocked for the run-up to the exams, including a pot of hosted AI for the nights you want the big models.",
features: [
"All four Paragraph models",
"Priority access to the hosted models",
"One payment, nothing renews"
],
cost_limit_cents: 600,
download_tier: 4,
byok: true,
paypal_plan_id: "",
paypal_payment_link: "",
active: true,
sort: 3
},
{
id: "ai-booster",
name: "AI Booster",
kind: "one_time",
price_cents: 600,
currency: "GBP",
interval: null,
blurb: "Already have a membership? Drop another pot of hosted AI into your account and keep the big models coming.",
features: [
"Stacks with any plan you already have",
"Never expires",
"No subscription, no renewal"
],
cost_limit_cents: 500,
download_tier: 0,
byok: true,
paypal_plan_id: "",
paypal_payment_link: "",
active: true,
sort: 4
},
{
id: "student",
name: "Student",
kind: "subscription",
price_cents: 400,
currency: "GBP",
interval: "month",
blurb: "The whole shelf of hosted models, plus two Paragraph downloads. About the price of a coffee a month.",
features: [
"Every hosted model, including the big ones",
"Paragraph Lite (2.5 GB) and Turbo (5.8 GB) offline",
"Use your own key and keep it free of limits"
],
cost_limit_cents: 120,
download_tier: 2,
byok: true,
paypal_plan_id: "",
paypal_payment_link: "",
active: true,
sort: 5
},
{
id: "scholar",
name: "Scholar",
kind: "subscription",
price_cents: 900,
currency: "GBP",
interval: "month",
blurb: "For long essays and heavy revision weeks: more AI, more downloads, and Novel offline.",
features: [
"Everything in Student",
"Adds Paragraph Novel (7.4 GB)",
"Priority when the hosted models are busy"
],
cost_limit_cents: 400,
download_tier: 3,
byok: true,
paypal_plan_id: "",
paypal_payment_link: "",
active: true,
sort: 6
},
{
id: "examiner",
name: "Examiner",
kind: "subscription",
price_cents: 1900,
currency: "GBP",
interval: "month",
blurb: "The full shelf, the biggest budget and every model offline. For the year it really matters.",
features: [
"Everything in Scholar",
"All four Paragraph models, including Ace (61 GB)",
"Early access to new models and marking prompts"
],
cost_limit_cents: 1000,
download_tier: 4,
byok: true,
paypal_plan_id: "",
paypal_payment_link: "",
active: true,
sort: 7
}
];
// The Paragraph family, exactly as published by quantilimited on Hugging Face.
// Sizes are the real file sizes. Ace is safetensors-only, so it has no GGUF
// download, but it is still the fourth and largest tier.
export const DEFAULT_MODELS = [
{
id: "paragraph-lite",
name: "Paragraph Lite",
host: "GGUF · Q4_K_M",
endpoint_url: "",
model_name: "Qwen3-4B-Instruct-2507",
base_model: "Qwen3-4B-Instruct-2507",
params: "4B",
essays: 300,
format: "GGUF · Q4_K_M",
download_url: "https://huggingface.co/quantilimited/Paragraph-Lite/resolve/main/Qwen3-4B-Instruct-2507.Q4_K_M.gguf",
card_url: "https://huggingface.co/quantilimited/Paragraph-Lite",
cost_in_per_million: 0,
cost_out_per_million: 0,
min_tier: 1,
download_size: "2.5 GB",
note: "The fast tier. Small enough for an 8 GB iPhone, iPad or Mac.",
enabled: true,
sort: 1
},
{
id: "paragraph-turbo",
name: "Paragraph Turbo",
host: "GGUF · Q4_K_M",
endpoint_url: "",
model_name: "Qwen3.5-9B",
base_model: "Qwen3.5-9B",
params: "9B",
essays: 500,
format: "GGUF · Q4_K_M",
download_url: "https://huggingface.co/quantilimited/Paragraph-Turbo-gguf/resolve/main/Qwen3.5-9B.Q4_K_M.gguf",
card_url: "https://huggingface.co/quantilimited/Paragraph-Turbo",
cost_in_per_million: 0,
cost_out_per_million: 0,
min_tier: 2,
download_size: "5.8 GB",
note: "Sharper method and effect analysis. Needs about 16 GB of memory.",
enabled: true,
sort: 2
},
{
id: "paragraph-novel",
name: "Paragraph Novel",
host: "GGUF · Q4_K_M",
endpoint_url: "",
model_name: "Gemma 4 12B",
base_model: "Gemma 4 12B",
params: "12B",
essays: 750,
format: "GGUF · Q4_K_M",
download_url: "https://huggingface.co/quantilimited/Paragraph-Novel/resolve/main/gemma-4-12b-it.Q4_K_M.gguf",
card_url: "https://huggingface.co/quantilimited/Paragraph-Novel",
cost_in_per_million: 0,
cost_out_per_million: 0,
min_tier: 3,
download_size: "7.4 GB",
note: "12B Gemma 4 for voice, structure and whole-text argument. Needs about 16 GB.",
enabled: true,
sort: 3
},
{
id: "paragraph-ace",
name: "Paragraph Ace",
host: "Safetensors · 16 shards",
endpoint_url: "",
model_name: "Qwen3-30B-A3B-Instruct-2507",
base_model: "Qwen3-30B-A3B-Instruct-2507",
params: "30B MoE · 3B active",
essays: 1000,
format: "Safetensors · 16 shards",
download_url: "",
card_url: "https://huggingface.co/quantilimited/Paragraph-Ace",
cost_in_per_million: 0,
cost_out_per_million: 0,
min_tier: 4,
download_size: "61 GB",
note: "The full 30B mixture-of-experts checkpoint. Published as safetensors; there is no GGUF build yet.",
enabled: true,
sort: 4
}
];
export const DEFAULT_SETTINGS = {
paypal_client_id: "",
paypal_mode: "live",
checkout_mode: "function",
checkout_function: "paypal-checkout",
currency: "GBP",
support_email: DEVELOPER_EMAIL
};
function previewDefaults() {
return { plans: DEFAULT_PLANS, models: DEFAULT_MODELS, content: {}, settings: DEFAULT_SETTINGS, entitlements: [], usage: [] };
}
function readPreview() {
try {
const raw = JSON.parse(localStorage.getItem(PREVIEW_KEY) || "null");
if (!raw) return previewDefaults();
return { ...previewDefaults(), ...raw };
} catch {
return previewDefaults();
}
}
function writePreview(next) {
try {
localStorage.setItem(PREVIEW_KEY, JSON.stringify(next));
} catch {
// ignore quota
}
}
// ---------------------------------------------------------------------------
// Money helpers
// ---------------------------------------------------------------------------
export function money(cents, currency = "GBP") {
try {
return new Intl.NumberFormat("en-GB", { style: "currency", currency: currency || "GBP" }).format((Number(cents) || 0) / 100);
} catch {
return `£${((Number(cents) || 0) / 100).toFixed(2)}`;
}
}
export function planPeriod(plan) {
if (!plan) return "";
if (plan.kind === "one_time") return "one-off";
return `per ${plan.interval || "month"}`;
}
export function isDeveloper(user) {
return !!user && String(user.email || "").toLowerCase() === DEVELOPER_EMAIL;
}
// ---------------------------------------------------------------------------
// Provider
// ---------------------------------------------------------------------------
const CloudContext = createContext(null);
export function CloudProvider({ children }) {
const [config, setConfig] = useState(readConfig);
const [client, setClient] = useState(null);
const [user, setUser] = useState(null);
const [ready, setReady] = useState(false);
const [error, setError] = useState("");
const [preview, setPreview] = useState(() => readPreview());
const [cloud, setCloud] = useState({
settings: { ...DEFAULT_SETTINGS },
plans: [],
models: [],
content: {},
entitlements: [],
usage: []
});
const [busy, setBusy] = useState(false);
const [notice, setNotice] = useState("");
const mounted = useRef(true);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
const flash = useCallback((message) => {
if (!mounted.current) return;
setNotice(message);
setTimeout(() => mounted.current && setNotice(""), 2600);
}, []);
const refresh = useCallback(
async (sb, currentUser) => {
if (!sb) return;
const who = currentUser === undefined ? user : currentUser;
try {
const [settingsRes, plansRes, modelsRes, contentRes] = await Promise.all([
sb.from(T.settings).select("*").eq("id", 1).maybeSingle(),
sb.from(T.plans).select("*").order("sort", { ascending: true }),
sb.from(T.models).select("*").order("sort", { ascending: true }),
sb.from(T.content).select("*")
]);
const map = {};
(contentRes.data || []).forEach((row) => {
map[row.key] = row.value;
});
let entitlements = [];
let usage = [];
if (who) {
const [entRes, useRes] = await Promise.all([
sb.from(T.entitlements).select("*").order("granted_at", { ascending: false }),
sb.from(T.usage).select("*").order("created_at", { ascending: false }).limit(2000)
]);
entitlements = entRes.data || [];
usage = useRes.data || [];
}
if (!mounted.current) return;
setCloud({
settings: { ...DEFAULT_SETTINGS, ...(settingsRes.data || {}) },
plans: plansRes.data || [],
models: modelsRes.data || [],
content: map,
entitlements,
usage
});
setError("");
} catch (err) {
if (mounted.current) setError(err && err.message ? err.message : "Could not read the shared settings.");
}
},
[user]
);
useEffect(() => {
let cancelled = false;
if (!config.ready) {
setReady(true);
setClient(null);
setUser(null);
return () => {
cancelled = true;
};
}
(async () => {
setReady(false);
try {
const sb = await loadSdk(config);
if (cancelled) return;
setClient(sb);
const { data } = await sb.auth.getSession();
const sessionUser = data && data.session ? data.session.user : null;
if (cancelled) return;
setUser(sessionUser);
await refresh(sb, sessionUser);
sb.auth.onAuthStateChange((_event, session) => {
const nextUser = session ? session.user : null;
setUser(nextUser);
refresh(sb, nextUser);
});
} catch (err) {
if (!cancelled) setError("Supabase could not be reached. Check the project URL and public key in Developer settings.");
} finally {
if (!cancelled) setReady(true);
}
})();
return () => {
cancelled = true;
};
}, [config.ready, config.url, config.anonKey]);
// Preview-mode writes keep working with no backend.
const previewWrite = useCallback((mutate) => {
setPreview((current) => {
const next = mutate({ ...current });
writePreview(next);
return next;
});
}, []);
const entitlements = config.ready ? cloud.entitlements : preview.entitlements;
const usage = config.ready ? cloud.usage : preview.usage;
const activeEntitlements = useMemo(() => {
const now = Date.now();
return entitlements.filter((e) => {
if (e.revoked) return false;
if (e.expires_at && new Date(e.expires_at).getTime() < now) return false;
return true;
});
}, [entitlements]);
const activeEntitlement = activeEntitlements[0] || null;
const plans = config.ready ? cloud.plans : preview.plans;
const models = config.ready ? cloud.models : preview.models;
// Purchases stack: the best download tier wins and the included AI adds up.
const plan = useMemo(() => {
const owned = activeEntitlements.map((e) => plans.find((p) => p.id === e.plan_id)).filter(Boolean);
return (
owned.sort(
(a, b) => Number(b.download_tier || 0) - Number(a.download_tier || 0) || Number(b.cost_limit_cents || 0) - Number(a.cost_limit_cents || 0)
)[0] || null
);
}, [plans, activeEntitlements]);
const budget = useMemo(() => {
const owned = activeEntitlements.map((e) => plans.find((p) => p.id === e.plan_id)).filter(Boolean);
const limit = owned.reduce((sum, p) => sum + Number(p.cost_limit_cents || 0), 0);
if (!limit) return { limit: 0, spent: 0, remaining: 0, unlimited: false };
const hasSub = owned.some((p) => p.kind === "subscription");
const since = hasSub ? new Date(new Date().getFullYear(), new Date().getMonth(), 1).getTime() : 0;
const spent = usage
.filter((u) => new Date(u.created_at || 0).getTime() >= since)
.reduce((sum, u) => sum + Number(u.cost_cents || 0), 0);
return { limit, spent, remaining: Math.max(0, limit - spent), unlimited: false };
}, [plans, activeEntitlements, usage]);
const isDev = config.ready ? isDeveloper(user) : true;
const signIn = useCallback(
async (email, password) => {
if (!client) throw new Error("Connect Supabase first.");
const { error: err } = await client.auth.signInWithPassword({ email, password });
if (err) throw err;
},
[client]
);
const signUp = useCallback(
async (email, password) => {
if (!client) throw new Error("Connect Supabase first.");
const { data, error: err } = await client.auth.signUp({ email, password, options: { emailRedirectTo: appRedirect() } });
if (err) throw err;
return data;
},
[client]
);
const magicLink = useCallback(
async (email) => {
if (!client) throw new Error("Connect Supabase first.");
const { error: err } = await client.auth.signInWithOtp({ email, options: { emailRedirectTo: appRedirect() } });
if (err) throw err;
},
[client]
);
const resetPassword = useCallback(
async (email) => {
if (!client) throw new Error("Connect Supabase first.");
const { error: err } = await client.auth.resetPasswordForEmail(email, { redirectTo: appRedirect() });
if (err) throw err;
},
[client]
);
// Used by the screen a recovery or invite link lands on. The link itself has
// already signed the person in, so this only sets the new password.
const updatePassword = useCallback(
async (password) => {
if (!client) throw new Error("Connect Supabase first.");
const { error: err } = await client.auth.updateUser({ password });
if (err) throw err;
},
[client]
);
// The six-digit code printed in the sign-in emails. Supabase labels the token
// by the flow that produced it, so try the likely types in order and keep the
// last refusal.
const verifyCode = useCallback(
async (email, token) => {
if (!client) throw new Error("Connect Supabase first.");
const types = ["signup", "invite", "recovery", "email", "magiclink"];
let lastError = null;
for (const type of types) {
const { data, error: err } = await client.auth.verifyOtp({ email, token, type });
if (!err && data && data.session) return data;
lastError = err;
}
throw lastError || new Error("That code did not work.");
},
[client]
);
const signOut = useCallback(async () => {
if (client) await client.auth.signOut();
setUser(null);
}, [client]);
const connect = useCallback(async ({ url, anonKey }) => {
saveConfig({ url, anonKey });
setConfig(readConfig());
}, []);
const disconnect = useCallback(async () => {
forgetConfig();
setCloud({ settings: { ...DEFAULT_SETTINGS }, plans: [], models: [], content: {}, entitlements: [], usage: [] });
setConfig(readConfig());
}, []);
// ---- writes -------------------------------------------------------------
const upsertPlan = useCallback(
async (next) => {
if (!config.ready) {
previewWrite((data) => ({ ...data, plans: [...data.plans.filter((p) => p.id !== next.id), next].sort((a, b) => (a.sort || 0) - (b.sort || 0)) }));
return;
}
const { error: err } = await client.from(T.plans).upsert(next);
if (err) throw err;
await refresh(client);
},
[config.ready, client, previewWrite, refresh]
);
const deletePlan = useCallback(
async (id) => {
if (!config.ready) {
previewWrite((data) => ({ ...data, plans: data.plans.filter((p) => p.id !== id) }));
return;
}
const { error: err } = await client.from(T.plans).delete().eq("id", id);
if (err) throw err;
await refresh(client);
},
[config.ready, client, previewWrite, refresh]
);
const upsertModel = useCallback(
async (next) => {
if (!config.ready) {
previewWrite((data) => ({ ...data, models: [...data.models.filter((m) => m.id !== next.id), next].sort((a, b) => (a.sort || 0) - (b.sort || 0)) }));
return;
}
const { error: err } = await client.from(T.models).upsert(next);
if (err) throw err;
await refresh(client);
},
[config.ready, client, previewWrite, refresh]
);
const deleteModel = useCallback(
async (id) => {
if (!config.ready) {
previewWrite((data) => ({ ...data, models: data.models.filter((m) => m.id !== id) }));
return;
}
const { error: err } = await client.from(T.models).delete().eq("id", id);
if (err) throw err;
await refresh(client);
},
[config.ready, client, previewWrite, refresh]
);
const saveModelKey = useCallback(
async (modelId, apiKey) => {
if (!config.ready) {
previewWrite((data) => ({ ...data, secrets: { ...(data.secrets || {}), [modelId]: apiKey } }));
return;
}
const { error: err } = await client.from(T.secrets).upsert({ model_id: modelId, api_key: apiKey, updated_at: new Date().toISOString() });
if (err) throw err;
},
[config.ready, client, previewWrite]
);
const setContent = useCallback(
async (key, value) => {
const clean = String(value == null ? "" : value);
if (!config.ready) {
previewWrite((data) => ({ ...data, content: { ...data.content, [key]: clean } }));
return;
}
const { error: err } = await client
.from(T.content)
.upsert({ key, value: clean, updated_at: new Date().toISOString(), updated_by: (user && user.email) || "" });
if (err) throw err;
setCloud((c) => ({ ...c, content: { ...c.content, [key]: clean } }));
},
[config.ready, client, previewWrite, user]
);
const clearContent = useCallback(
async (key) => {
if (!config.ready) {
previewWrite((data) => {
const content = { ...data.content };
delete content[key];
return { ...data, content };
});
return;
}
const { error: err } = await client.from(T.content).delete().eq("key", key);
if (err) throw err;
setCloud((c) => {
const content = { ...c.content };
delete content[key];
return { ...c, content };
});
},
[config.ready, client, previewWrite]
);
const setSettings = useCallback(
async (patch) => {
if (!config.ready) {
previewWrite((data) => ({ ...data, settings: { ...data.settings, ...patch } }));
return;
}
const { error: err } = await client.from(T.settings).upsert({ id: 1, ...patch, updated_at: new Date().toISOString() });
if (err) throw err;
setCloud((c) => ({ ...c, settings: { ...c.settings, ...patch } }));
},
[config.ready, client, previewWrite]
);
const grantPlan = useCallback(
async (email, planId, months = 1) => {
if (!config.ready) {
previewWrite((data) => ({
...data,
entitlements: [
{ id: "preview-" + Date.now(), email, plan_id: planId, source: "grant", granted_at: new Date().toISOString(), expires_at: null, revoked: false },
...data.entitlements
]
}));
return;
}
const { error: err } = await client.from(T.entitlements).insert({
email: String(email || "").toLowerCase(),
plan_id: planId,
source: "grant",
expires_at: null
});
if (err) throw err;
await refresh(client);
},
[config.ready, client, previewWrite, refresh]
);
const revokeGrant = useCallback(
async (id) => {
if (!config.ready) {
previewWrite((data) => ({ ...data, entitlements: data.entitlements.map((e) => (e.id === id ? { ...e, revoked: true } : e)) }));
return;
}
const { error: err } = await client.from(T.entitlements).update({ revoked: true }).eq("id", id);
if (err) throw err;
await refresh(client);
},
[config.ready, client, previewWrite, refresh]
);
const startCheckout = useCallback(
async (chosen) => {
if (!chosen) throw new Error("Pick a plan first.");
if (!user) throw new Error("Sign in first, so the purchase can be attached to your account.");
const settings = config.ready ? cloud.settings : preview.settings;
if ((settings.checkout_mode || "function") === "payment_links") {
if (!chosen.paypal_payment_link) {
throw new Error("This plan has no PayPal payment link yet. Add one in Developer → Plans.");
}
window.location.href = chosen.paypal_payment_link;
return { redirect: true };
}
if (!config.ready) throw new Error("PayPal checkout needs Supabase. Connect it in Developer settings.");
const fn = settings.checkout_function || "paypal-checkout";
const { data, error: err } = await client.functions.invoke(fn, {
body: { plan_id: chosen.id, origin: window.location.origin }
});
if (err) {
let message = err.message || "PayPal checkout could not start.";
if (err.context && typeof err.context.json === "function") {
try {
const body = await err.context.json();
if (body && body.message) message = body.message;
} catch {
// keep the original message
}
}
throw new Error(message);
}
if (data && data.url) {
window.location.href = data.url;
return { redirect: true };
}
if (data && data.message) throw new Error(data.message);
throw new Error("PayPal did not return an approval link.");
},
[user, client, config.ready, cloud.settings, preview.settings]
);
const hostedChat = useCallback(
async (model, messages, onToken) => {
if (!config.ready) throw new Error("Hosted models need Supabase. Connect it in Developer settings.");
if (!user) throw new Error("Sign in to use the hosted models.");
const { data: sessionData } = await client.auth.getSession();
const token = sessionData && sessionData.session ? sessionData.session.access_token : "";
const base = config.url;
const res = await fetch(`${base}/functions/v1/ai`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
apikey: config.anonKey
},
body: JSON.stringify({ model_id: model.id, messages, stream: true })
});
if (res.status === 402) {
const info = await res.json().catch(() => ({}));
throw new Error(info.message || "You have used your included model budget for this period.");
}
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(text || `The hosted model returned ${res.status}.`);
}
if (!res.body) {
const data = await res.json();
const text = (data && data.text) || "";
onToken && onToken(text);
return text;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let full = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed.startsWith("data:")) continue;
const payload = trimmed.slice(5).trim();
if (payload === "[DONE]") continue;
try {
const json = JSON.parse(payload);
const delta = (json.choices && json.choices[0] && json.choices[0].delta && json.choices[0].delta.content) || "";
if (delta) {
full += delta;
onToken && onToken(full);
}
} catch {
// wait for the rest of the line
}
}
}
return full;
},
[config, client, user]
);
const value = useMemo(
() => ({
config,
configured: config.ready,
mode: config.ready ? "cloud" : "preview",
client,
user,
isDev,
ready,
error,
notice,
flash,
settings: config.ready ? cloud.settings : preview.settings,
plans,
models,
content: config.ready ? cloud.content : preview.content,
entitlements,
usage,
plan,
entitlement: activeEntitlement,
budget,
signIn,
signUp,
magicLink,
resetPassword,
updatePassword,
verifyCode,
signOut,
connect,
disconnect,
upsertPlan,
deletePlan,
upsertModel,
deleteModel,
saveModelKey,
setContent,
clearContent,
setSettings,
grantPlan,
revokeGrant,
startCheckout,
hostedChat,
refresh: () => refresh(client),
canDownload: (tier) => Number(tier || 0) <= 1 || (!!plan && Number(plan.download_tier || 0) >= Number(tier || 0)),
canHost: (model) => !!model && budget.limit > 0 && budget.remaining > 0
}),
[
config,
client,
user,
isDev,
ready,
error,
notice,
flash,
cloud,
preview,
plans,
models,
entitlements,
usage,
plan,
activeEntitlement,
activeEntitlements,
budget,
signIn,
signUp,
magicLink,
resetPassword,
updatePassword,
verifyCode,
signOut,
connect,
disconnect,
upsertPlan,
deletePlan,
upsertModel,
deleteModel,
saveModelKey,
setContent,
clearContent,
setSettings,
grantPlan,
revokeGrant,
startCheckout,
hostedChat,
refresh
]
);
return html`<${CloudContext.Provider} value=${value}>${children}/>`;
}
export function useCloud() {
const value = useContext(CloudContext);
if (!value) throw new Error("useCloud must be used inside CloudProvider");
return value;
}