Files
CatoandClaude a7acf30fb6 feat(ai-kit 1.33.0, chatkit 0.48.0): own key, free models or a paid plan, as one packaged choice (#20)
ai-kit/choice: chooseChain, readOwnKey, preferFirst, pickableModels,
redactKeys, checkOwnKey: whose model answers a request and whose money
it spends, decided once instead of in each product.

chatkit: ModelSheet `plan` (the product's paid way to a stronger model),
`freeNote`, `ownTitle`; useModelOptions wires chip, sheet, browser store,
key check and free list; ModelNudge under an answer a free model wrote.


Claude-Session: https://claude.ai/code/session_019MDtmvTCDbJAYNKQpNyKzz

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-30 21:18:44 +01:00

136 lines
12 KiB
JavaScript

"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { Sheet } from "./Sheet.js";
export const DEFAULT_MODEL_SHEET_LABELS = {
title: "Connect your own model",
lead: "Add your own API key and choose the model that answers. The calls are billed by your provider.",
close: "Close",
freeNow: "Without a key, these free models answer, in this order:",
vendor: "Provider",
getKey: "Get a key",
key: "API key",
keyPlaceholder: "sk-…",
pasteHint: "Paste a key. It is checked at once, and the models it can use are listed.",
checking: "Checking …",
model: "Model",
strongest: "strongest",
use: "Use this model",
connected: "Connected",
connectedWith: "Connected with",
failed: "That did not work",
unreachable: "The provider could not be reached just now. Your key may well be fine; try again in a moment.",
vendorSaid: "The provider says:",
remove: "Remove key",
pickTitle: "Model",
pickHint: "Without a key, a free model answers. Tap one to ask it first.",
auto: "Automatic",
autoHint: "The best free model that is up, in this order.",
compare: "Compare the free models",
answeredBy: "Answered by",
planTitle: "A stronger model, without a key",
planBody: "With a plan, a stronger model answers you here. Nothing to set up.",
planAction: "See the plans",
planActive: "Your plan is active: a stronger model answers you.",
};
const IDLE = { state: "idle", models: [], suggested: null, message: "", reachable: true };
/** Long enough to finish pasting, short enough to feel immediate. */
const CHECK_AFTER_MS = 600;
/**
* The button in a chat's header. Everybody gets it, not only somebody who has
* connected a key: without one it was nowhere, and the only way to the sheet
* was a settings page. It names the reader's own model, or says `label`
* ("Model") while the product's answers.
*/
export function ModelChip({ model, label, onOpen, picked, served, format = (id) => id, answeredBy = DEFAULT_MODEL_SHEET_LABELS.answeredBy, className = "", }) {
const state = model ? "own" : picked ? "picked" : "free";
const name = model || (picked ? format(picked) : served ? format(served) : label);
const title = model ? model : picked ? picked : served ? `${answeredBy} ${served}` : label;
return (_jsxs("button", { type: "button", className: `ck-glass ck-model-chip${model ? " ck-model-own" : ""}${className ? ` ${className}` : ""}`, "data-model-chip": state, onClick: onOpen, title: title, "aria-label": name === label ? label : `${label}: ${name}`, children: [model && _jsx("span", { "aria-hidden": "true", className: "ck-model-dot" }), _jsx("span", { className: "ck-model-name", children: name })] }));
}
export function ModelSheet({ open, onClose, vendors, current, check, onSave, onClear, freeModels, freePick, onFreePick, compareHref, plan, format = (id) => id, labels: overrides, }) {
const t = { ...DEFAULT_MODEL_SHEET_LABELS, ...overrides };
const [vendorId, setVendorId] = useState(current?.vendor ?? vendors[0]?.id ?? "");
const [key, setKey] = useState(current?.key ?? "");
const [model, setModel] = useState(current?.model ?? "");
const [result, setResult] = useState(IDLE);
const [saved, setSaved] = useState(false);
const timer = useRef(undefined);
const seq = useRef(0);
const vendor = vendors.find((v) => v.id === vendorId);
/** Check a key, debounced from the event that changed it; the newest check wins. */
function schedule(nextVendor, nextKey, delay = CHECK_AFTER_MS) {
clearTimeout(timer.current);
setSaved(false);
if (nextKey.trim().length < 8) {
setResult(IDLE);
return;
}
timer.current = setTimeout(() => {
const n = ++seq.current;
setResult({ ...IDLE, state: "checking" });
check(nextVendor, nextKey.trim())
.then((data) => {
if (n !== seq.current)
return;
const models = [...(data.models ?? [])];
setResult({
state: data.ok ? "ok" : "error",
models,
suggested: data.suggested ?? null,
message: data.message ?? "",
reachable: data.reachable !== false,
});
// Keep the saved choice when this key still reaches it; else the strongest.
if (data.ok)
setModel((m) => (models.includes(m) ? m : (data.suggested ?? models[0] ?? m)));
})
.catch(() => n === seq.current && setResult({ ...IDLE, state: "error", reachable: false }));
}, delay);
}
// A key already saved is checked once when the sheet opens, so its models are there.
useEffect(() => {
if (open && current)
schedule(current.vendor, current.key, 0);
if (!open)
clearTimeout(timer.current);
// On opening only: `current` is the saved choice at that moment.
}, [open]);
useEffect(() => () => clearTimeout(timer.current), []);
const listed = result.state === "ok" && result.models.length > 0;
function use() {
if (!vendor || !key.trim() || !model.trim())
return;
onSave({ vendor: vendor.id, key: key.trim(), model: model.trim() });
setSaved(true);
}
return (_jsx(Sheet, { open: open, onClose: onClose, title: t.title, closeLabel: t.close, children: _jsxs("div", { className: "ck-model-sheet", "data-model-sheet": true, children: [_jsx("p", { className: "ck-model-lead", children: t.lead }), current && (_jsxs("p", { className: "ck-model-current", children: [_jsx("span", { className: "ck-model-tag", children: t.connected }), _jsxs("span", { className: "ck-model-id", children: [t.connectedWith, " ", current.model] })] })), !current && freeModels && freeModels.length > 0 && onFreePick && (_jsxs("fieldset", { className: "ck-model-free ck-model-pick", "data-model-free": true, children: [_jsx("legend", { className: "ck-model-label", children: t.pickTitle }), _jsx("p", { children: t.pickHint }), _jsx("div", { role: "radiogroup", "aria-label": t.pickTitle, children: ["", ...freeModels].map((name) => {
const on = (freePick ?? "") === name ||
(name === "" && !freeModels.includes(freePick ?? ""));
return (_jsxs("button", { type: "button", role: "radio", "aria-checked": on, "data-model-pick": name || "auto", className: "ck-model-option", onClick: () => onFreePick(name), children: [_jsx("span", { "aria-hidden": "true", className: "ck-model-radio" }), _jsxs("span", { className: "ck-model-option-text", children: [_jsx("span", { className: "ck-model-id", children: name ? format(name) : t.auto }), !name && _jsx("span", { className: "ck-model-hint", children: t.autoHint })] })] }, name || "auto"));
}) }), t.freeNote && _jsx("p", { className: "ck-model-hint", children: t.freeNote }), compareHref && (_jsx("a", { className: "ck-model-link", href: compareHref, children: t.compare }))] })), !current && freeModels && freeModels.length > 0 && !onFreePick && (_jsxs("div", { className: "ck-model-free", "data-model-free": true, children: [_jsx("p", { children: t.freeNow }), _jsx("ol", { children: freeModels.map((name) => (_jsx("li", { className: "ck-model-id", children: name }, name))) }), t.freeNote && _jsx("p", { className: "ck-model-hint", children: t.freeNote })] })), plan && !current && (_jsxs("div", { className: "ck-model-plan", "data-model-plan": plan.active ? "active" : "offer", children: [_jsx("h3", { className: "ck-model-label", children: t.planTitle }), _jsx("p", { children: plan.active ? t.planActive : t.planBody }), !plan.active && plan.href && (_jsx("a", { className: "ck-model-use ck-model-plan-go", href: plan.href, children: t.planAction })), !plan.active && !plan.href && plan.onOpen && (_jsx("button", { type: "button", className: "ck-model-use ck-model-plan-go", onClick: plan.onOpen, children: t.planAction }))] })), t.ownTitle && _jsx("h3", { className: "ck-model-label ck-model-own-title", children: t.ownTitle }), _jsxs("div", { className: "ck-model-fields", children: [_jsxs("div", { children: [_jsx("label", { htmlFor: "ck-model-vendor", className: "ck-model-label", children: t.vendor }), _jsx("select", { id: "ck-model-vendor", className: "ck-model-input", value: vendorId, onChange: (e) => {
setVendorId(e.target.value);
setModel("");
schedule(e.target.value, key);
}, children: vendors.map((v) => (_jsx("option", { value: v.id, children: v.label }, v.id))) }), vendor?.keyUrl && (_jsxs("a", { className: "ck-model-link", href: vendor.keyUrl, target: "_blank", rel: "noreferrer noopener", children: [t.getKey, " \u2197"] }))] }), _jsxs("div", { children: [_jsx("label", { htmlFor: "ck-model-key", className: "ck-model-label", children: t.key }), _jsx("input", { id: "ck-model-key", className: "ck-model-input ck-model-mono", type: "password", autoComplete: "off", spellCheck: false, value: key, placeholder: vendor?.keyHint || t.keyPlaceholder, onChange: (e) => {
setKey(e.target.value);
schedule(vendorId, e.target.value);
} }), _jsx("p", { className: "ck-model-hint", role: "status", children: result.state === "checking"
? t.checking
: result.state === "idle"
? t.pasteHint
: null })] }), result.state === "ok" && (_jsxs("div", { children: [_jsx("label", { htmlFor: "ck-model-model", className: "ck-model-label", children: t.model }), listed ? (_jsx("select", { id: "ck-model-model", className: "ck-model-input ck-model-mono", value: model, onChange: (e) => {
setModel(e.target.value);
setSaved(false);
}, children: result.models.map((m) => (_jsx("option", { value: m, children: m === result.suggested ? `${m} — ${t.strongest}` : m }, m))) })) : (_jsx("input", { id: "ck-model-model", className: "ck-model-input ck-model-mono", value: model, spellCheck: false, placeholder: vendor?.modelExample, onChange: (e) => {
setModel(e.target.value);
setSaved(false);
} }))] }))] }), _jsxs("div", { className: "ck-model-actions", children: [result.state === "ok" && (_jsx("button", { type: "button", className: "ck-model-use", onClick: use, disabled: !model.trim(), children: t.use })), current && (_jsx("button", { type: "button", className: "ck-model-remove", onClick: () => {
onClear();
setKey("");
setModel("");
setResult(IDLE);
setSaved(false);
}, children: t.remove }))] }), saved && (_jsxs("p", { role: "status", className: "ck-model-saved ck-model-id", children: [t.connected, " \u00B7 ", model] })), result.state === "error" && (_jsxs("div", { role: "alert", className: "ck-model-error", children: [_jsx("p", { children: result.reachable ? t.failed : t.unreachable }), result.reachable && result.message && (_jsxs("p", { className: "ck-model-vendor-said", children: [t.vendorSaid, " ", _jsx("q", { children: result.message })] }))] })), (t.safetyBody || t.whyBody) && (_jsxs("div", { className: "ck-model-notes", children: [t.safetyBody && (_jsxs(_Fragment, { children: [t.safetyTitle && _jsx("h3", { children: t.safetyTitle }), _jsx("p", { children: t.safetyBody })] })), t.whyBody && (_jsxs(_Fragment, { children: [t.whyTitle && _jsx("h3", { children: t.whyTitle }), _jsx("p", { children: t.whyBody })] }))] }))] }) }));
}
//# sourceMappingURL=ModelSheet.js.map