v1.5.0
AtheraStudio Code
- (function () {
- "use strict";
-
- var A = window.Athera;
- var ai = A.ai;
- var t = ai.t;
-
- var URLS = {
- anthropic: "https://api.anthropic.com/v1/messages",
- openai: "https://api.openai.com/v1/responses",
- openaiChat: "https://api.openai.com/v1/chat/completions",
- gemini: "https://generativelanguage.googleapis.com/v1beta/models/",
- openrouter: "https://openrouter.ai/api/v1/chat/completions",
- groq: "https://api.groq.com/openai/v1/chat/completions"
- };
-
- var MAX_RETRIES = 2;
- var MAX_RECOVERIES = 5;
- var IMAGE_TOKENS = 1600;
- var active = new Set();
- var seq = 0;
-
- function uid(prefix) {
- seq += 1;
- return prefix + Date.now().toString(36) + seq.toString(36);
- }
-
- function clone(v) {
- return v == null ? v : JSON.parse(JSON.stringify(v));
- }
-
- function num(v) {
- var n = Number(v);
- return isFinite(n) && n > 0 ? n : 0;
- }
-
- function hash(text) {
- var h = 2166136261;
- for (var i = 0; i < text.length; i++) {
- h ^= text.charCodeAt(i);
- h = Math.imul(h, 16777619);
- }
- return (h >>> 0).toString(36);
- }
-
- function dataUrl(part) {
- return "data:" + part.mime + ";base64," + part.data;
- }
-
- function systemText(req) {
- return (req.system || []).map(function (b) { return b.text; }).filter(Boolean).join("\n\n");
- }
-
- function resultText(content) {
- if (typeof content === "string") return content;
- return (content || []).filter(function (p) { return p.type === "text"; }).map(function (p) { return p.text; }).join("\n");
- }
-
- function resultImages(content) {
- return typeof content === "string" ? [] : (content || []).filter(function (p) { return p.type === "image"; });
- }
-
- function emptyUsage() {
- return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, searches: 0 };
- }
-
- function mapEffort(effort, levels) {
- var order = ["low", "medium", "high", "max"];
- var i = Math.max(0, order.indexOf(effort || "medium"));
- while (i > 0 && levels.indexOf(order[i]) < 0) i--;
- return levels.indexOf(order[i]) >= 0 ? order[i] : levels[0];
- }
-
- function wait(ms, signal) {
- return new Promise(function (resolve, reject) {
- var timer = setTimeout(function () {
- if (signal) signal.removeEventListener("abort", onAbort);
- resolve();
- }, ms);
- function onAbort() {
- clearTimeout(timer);
- reject(new DOMException("Aborted", "AbortError"));
- }
- if (signal) {
- if (signal.aborted) return onAbort();
- signal.addEventListener("abort", onAbort, { once: true });
- }
- });
- }
-
- function providerError(provider, key, params, extra) {
- var e = new Error(t(key, Object.assign({ provider: ai.providerLabel(provider) }, params || {})));
- e.provider = provider;
- e.code = key;
- return Object.assign(e, extra || {});
- }
-
- async function httpError(provider, res) {
- var raw = "";
- try { raw = await res.text(); } catch (x) { }
- var detail = raw.slice(0, 600);
- try {
- var j = JSON.parse(raw);
- var err = Array.isArray(j) ? j[0] && j[0].error : j.error;
- detail = (err && (err.message || err.type || (typeof err === "string" ? err : ""))) || j.message || detail;
- if (err && err.metadata && err.metadata.raw) detail += " " + String(err.metadata.raw).slice(0, 300);
- } catch (x) { }
- var status = res.status;
- var badKey = status === 400 && /api[ _-]?key (?:not valid|invalid)|invalid api[ _-]?key|API_KEY_INVALID/i.test(detail);
- var key = status === 401 || status === 403 || badKey ? "ai.err.auth"
- : status === 429 ? "ai.err.rate"
- : status === 529 || status === 503 ? "ai.err.overloaded"
- : status === 402 ? "ai.err.credit"
- : "ai.err.http";
- var retryAfter = Number(res.headers.get("retry-after"));
- return providerError(provider, key, { status: status, message: detail }, {
- status: status,
- detail: detail,
- retryable: status === 408 || status === 409 || status === 429 || status >= 500,
- retryAfter: isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : 0
- });
- }
-
- function streamError(provider, message) {
- return providerError(provider, "ai.err.stream", { message: String(message || "").slice(0, 600) }, { detail: message });
- }
-
- function send(built, signal) {
- return fetch(built.url, { method: "POST", headers: built.headers, body: JSON.stringify(built.body), signal: signal, cache: "no-store", credentials: "omit", referrerPolicy: "no-referrer" });
- }
-
- async function readSSE(res, onEvent) {
- var reader = res.body.getReader();
- var decoder = new TextDecoder();
- var buf = "";
- function dispatch(chunk) {
- var name = "message";
- var data = [];
- chunk.split("\n").forEach(function (line) {
- if (!line || line.charAt(0) === ":") return;
- var i = line.indexOf(":");
- var field = i < 0 ? line : line.slice(0, i);
- var value = i < 0 ? "" : line.slice(i + 1).replace(/^ /, "");
- if (field === "event") name = value;
- else if (field === "data") data.push(value);
- });
- if (!data.length) return;
- var text = data.join("\n");
- if (text === "[DONE]") return onEvent("done", null);
- var obj;
- try { obj = JSON.parse(text); } catch (e) { return; }
- onEvent(name, obj);
- }
- for (;;) {
- var r = await reader.read();
- if (r.done) break;
- buf += decoder.decode(r.value, { stream: true });
- var tail = buf.slice(-1) === "\r" ? "\r" : "";
- if (tail) buf = buf.slice(0, -1);
- buf = buf.replace(/\r\n?/g, "\n");
- var idx;
- while ((idx = buf.indexOf("\n\n")) >= 0) {
- var chunk = buf.slice(0, idx);
- buf = buf.slice(idx + 2);
- dispatch(chunk);
- }
- buf += tail;
- }
- buf += decoder.decode();
- if (buf.trim()) dispatch(buf.replace(/\r\n?/g, "\n").trim());
- }
-
- function emit(state, name, payload) {
- var h = state.handlers || {};
- var fn = h[name];
- if (!fn) return;
- try { fn(payload, state); } catch (e) { console.error(e); }
- }
-
- function parseArgs(text) {
- if (!text) return { value: {}, ok: true };
- try {
- var v = JSON.parse(text);
- return { value: v && typeof v === "object" && !Array.isArray(v) ? v : {}, ok: true };
- } catch (e) {
- return { value: {}, ok: false, raw: text };
- }
- }
-
- function webConfig(req) {
- var w = req.web || {};
- return {
- search: !!w.search,
- fetch: !!w.fetch,
- allow: (w.allow || []).slice(0, 50),
- deny: (w.deny || []).slice(0, 50),
- maxUses: Math.max(1, Math.min(10, w.maxUses || 5))
- };
- }
-
- var CLAUDE5 = /^claude-(?:fable|mythos|opus|sonnet|haiku)-5/;
- var CLAUDE_FALLBACK = /^claude-(?:fable-5-1|mythos-5-1|opus-5|opus-5-5|sonnet-5-5)$/;
- var CLAUDE_DYNAMIC_WEB = /^claude-(?:opus-5|opus-4-[6-9]|sonnet-5|sonnet-4-6)/;
- var CLAUDE_EFFORT = /^claude-(?:fable|mythos|opus-5|opus-4-[5-9]|sonnet-5|sonnet-4-6|haiku-5)/;
- var CLAUDE_MAX_EFFORT = /^claude-(?:fable|mythos|opus-5|opus-4-[6-9]|sonnet-5|sonnet-4-6|haiku-5)/;
- var CLAUDE_ADAPTIVE_OPT_IN = /^claude-(?:opus-4-[6-9]|sonnet-4-6)/;
-
- function anthropicEcho(blocks) {
- var list = clone(blocks || []);
- var boundary = -1;
- list.forEach(function (b, i) { if (b.type === "fallback") boundary = i; });
- if (boundary < 0) return list;
- var results = {};
- list.forEach(function (b) { if (b.tool_use_id) results[b.tool_use_id] = true; });
- return list.filter(function (b, i) {
- if (i >= boundary) return true;
- if (b.type === "thinking" || b.type === "redacted_thinking" || b.type === "tool_use") return false;
- if (b.type === "server_tool_use") return !!results[b.id];
- return b.type === "text" || !!b.tool_use_id;
- });
- }
-
- function anthropicMessages(messages) {
- var out = [];
- function push(role, blocks) {
- if (!blocks.length) return;
- var last = out[out.length - 1];
- if (last && last.role === role) last.content = last.content.concat(blocks);
- else out.push({ role: role, content: blocks });
- }
- function image(p) {
- return { type: "image", source: { type: "base64", media_type: p.mime, data: p.data } };
- }
- messages.forEach(function (m) {
- if (m.role === "assistant") {
- if (m.native && m.native.provider === "anthropic") return push("assistant", anthropicEcho(m.native.data));
- push("assistant", (m.content || []).map(function (p) {
- if (p.type === "text" && p.text) return { type: "text", text: p.text };
- if (p.type === "tool_call") return { type: "tool_use", id: p.id, name: p.name, input: p.input || {} };
- return null;
- }).filter(Boolean));
- return;
- }
- var results = [];
- var rest = [];
- (m.content || []).forEach(function (p) {
- if (p.type === "tool_result") {
- var content = typeof p.content === "string" ? p.content : (p.content || []).map(function (c) {
- return c.type === "image" ? image(c) : { type: "text", text: c.text || "" };
- });
- results.push({ type: "tool_result", tool_use_id: p.id, content: content, is_error: !!p.isError });
- } else if (p.type === "image") {
- rest.push(image(p));
- } else if (p.type === "text" && p.text) {
- rest.push({ type: "text", text: p.text });
- }
- });
- push("user", results.concat(rest));
- });
- return out;
- }
-
- function markLastCacheable(messages) {
- var last = messages[messages.length - 1];
- if (!last) return;
- for (var i = last.content.length - 1; i >= 0; i--) {
- var b = last.content[i];
- if (b.type === "text" || b.type === "tool_result" || b.type === "image" || b.type === "tool_use") {
- last.content[i] = Object.assign({}, b, { cache_control: { type: "ephemeral" } });
- return;
- }
- }
- }
-
- var anthropic = {
- id: "anthropic",
-
- build: function (req, key, flags) {
- var model = req.model;
- var messages = anthropicMessages(req.messages || []);
- if (!flags.noMsgCache && req.cache !== false) markLastCacheable(messages);
- var system = (req.system || []).filter(function (b) { return b.text; }).map(function (b) { return { type: "text", text: b.text }; });
- if (req.cache !== false) {
- var stableEnd = -1;
- (req.system || []).filter(function (b) { return b.text; }).forEach(function (b, i) { if (b.cache) stableEnd = i; });
- if (stableEnd < 0 && system.length) stableEnd = system.length - 1;
- if (stableEnd >= 0) system[stableEnd].cache_control = { type: "ephemeral" };
- }
- var body = { model: model, max_tokens: req.maxTokens || 8192, stream: true, messages: messages };
- if (system.length) body.system = system;
- var tools = (req.tools || []).map(function (tool) {
- var def = { name: tool.name, description: tool.description, input_schema: tool.parameters };
- if (!flags.noEager) def.eager_input_streaming = true;
- return def;
- });
- var web = webConfig(req);
- var basic = flags.basicWeb || !CLAUDE_DYNAMIC_WEB.test(model);
- function domains(def) {
- if (web.allow.length) def.allowed_domains = web.allow;
- else if (web.deny.length) def.blocked_domains = web.deny;
- return def;
- }
- if (web.search && !flags.noWeb) tools.push(domains({ type: basic ? "web_search_20250305" : "web_search_20260209", name: "web_search", max_uses: web.maxUses }));
- if (web.fetch && !flags.noWeb && !flags.noFetch) tools.push(domains({ type: basic ? "web_fetch_20250910" : "web_fetch_20260209", name: "web_fetch", max_uses: web.maxUses }));
- if (tools.length) body.tools = tools;
- if (req.stop && req.stop.length && !flags.noStop) body.stop_sequences = req.stop.slice(0, 8);
- var betas = [];
- if (!flags.noThinking) {
- if (CLAUDE5.test(model)) {
- body.thinking = { type: "adaptive" };
- if (req.showThinking) body.thinking.display = "summarized";
- if (!flags.noBinding) {
- body.thinking.block_binding = { prefix_mismatch_behavior: "drop_block" };
- betas.push("thinking-binding-controls-2026-08-01");
- }
- } else if (req.reasoning && CLAUDE_ADAPTIVE_OPT_IN.test(model)) {
- body.thinking = { type: "adaptive" };
- }
- }
- if (!flags.noEffort && CLAUDE_EFFORT.test(model)) {
- body.output_config = { effort: mapEffort(req.effort, CLAUDE_MAX_EFFORT.test(model) ? ["low", "medium", "high", "max"] : ["low", "medium", "high"]) };
- }
- if (!flags.noFallbacks && CLAUDE_FALLBACK.test(model)) {
- body.fallbacks = "default";
- betas.push("server-side-fallback-2026-07-01");
- }
- var headers = {
- "content-type": "application/json",
- "x-api-key": key,
- "anthropic-version": "2023-06-01",
- "anthropic-dangerous-direct-browser-access": "true"
- };
- if (betas.length) headers["anthropic-beta"] = betas.join(",");
- return { url: URLS.anthropic, headers: headers, body: body };
- },
-
- recover: function (msg, flags) {
- var m = String(msg);
- if (!flags.noBinding && /block_binding|prefix_mismatch|thinking-binding/i.test(m)) return "noBinding";
- if (!flags.noFallbacks && /fallback/i.test(m)) return "noFallbacks";
- if (!flags.noEager && /eager_input_streaming/i.test(m)) return "noEager";
- if (!flags.noEffort && /effort|output_config/i.test(m)) return "noEffort";
- if (!flags.basicWeb && /web_(?:search|fetch)_2026/i.test(m)) return "basicWeb";
- if (!flags.noFetch && /web_fetch/i.test(m)) return "noFetch";
- if (!flags.noWeb && /web_search/i.test(m)) return "noWeb";
- if (!flags.noThinking && /thinking/i.test(m)) return "noThinking";
- if (!flags.noMsgCache && /cache_control/i.test(m)) return "noMsgCache";
- if (!flags.noStop && /stop_sequences/i.test(m)) return "noStop";
- return null;
- },
-
- start: function (req) {
- return { model: req.model, blocks: [], json: {}, usage: emptyUsage(), stop: null, refusal: null };
- },
-
- event: function (s, name, d) {
- if (!d) return;
- var type = d.type || name;
- if (type === "error") throw streamError("anthropic", d.error && d.error.message || "error");
- if (type === "message_start") {
- var msg = d.message || {};
- if (msg.model) s.model = msg.model;
- readAnthropicUsage(s.usage, msg.usage);
- } else if (type === "content_block_start") {
- var block = clone(d.content_block || {});
- s.blocks[d.index] = block;
- if (block.type === "fallback") {
- emit(s, "onStatus", { type: "fallback", from: block.from && block.from.model, to: block.to && block.to.model });
- } else if (block.type === "tool_use") {
- emit(s, "onToolStart", { id: block.id, name: block.name });
- }
- } else if (type === "content_block_delta") {
- var b = s.blocks[d.index];
- var delta = d.delta || {};
- if (!b) return;
- if (delta.type === "text_delta") {
- b.text = (b.text || "") + delta.text;
- emit(s, "onText", delta.text);
- } else if (delta.type === "thinking_delta") {
- b.thinking = (b.thinking || "") + delta.thinking;
- emit(s, "onThinking", delta.thinking);
- } else if (delta.type === "signature_delta") {
- b.signature = delta.signature;
- } else if (delta.type === "input_json_delta") {
- s.json[d.index] = (s.json[d.index] || "") + (delta.partial_json || "");
- } else if (delta.type === "citations_delta") {
- b.citations = (b.citations || []).concat([delta.citation]);
- }
- } else if (type === "content_block_stop") {
- var done = s.blocks[d.index];
- if (!done) return;
- if (s.json[d.index] != null) {
- var parsed = parseArgs(s.json[d.index]);
- done.input = parsed.value;
- if (!parsed.ok) done._invalid = parsed.raw;
- }
- if (done.type === "server_tool_use") {
- var input = done.input || {};
- emit(s, "onStatus", done.name === "web_fetch" ? { type: "fetch", url: input.url } : { type: "search", query: input.query });
- }
- } else if (type === "message_delta") {
- if (d.delta && d.delta.stop_reason) s.stop = d.delta.stop_reason;
- if (d.delta && d.delta.stop_details) s.refusal = d.delta.stop_details;
- readAnthropicUsage(s.usage, d.usage);
- }
- },
-
- finish: function (s) {
- var blocks = s.blocks.filter(Boolean);
- var boundary = -1;
- blocks.forEach(function (b, i) { if (b.type === "fallback") boundary = i; });
- var visible = blocks.slice(boundary + 1);
- var invalid = {};
- var calls = visible.filter(function (b) { return b.type === "tool_use"; }).map(function (b) {
- if (b._invalid != null) invalid[b.id] = b._invalid;
- return { id: b.id, name: b.name, input: b.input || {}, invalid: b._invalid != null };
- });
- var text = visible.filter(function (b) { return b.type === "text"; }).map(function (b) { return b.text || ""; }).join("");
- var native = blocks.map(function (b) {
- var c = Object.assign({}, b);
- delete c._invalid;
- return c;
- });
- var stop = { end_turn: "end", stop_sequence: "end", tool_use: "tool", max_tokens: "length", model_context_window_exceeded: "length", pause_turn: "pause", refusal: "refusal" }[s.stop] || (calls.length ? "tool" : "end");
- return {
- model: s.model,
- text: text,
- toolCalls: calls,
- stopReason: stop,
- refusal: s.refusal,
- usage: s.usage,
- native: native
- };
- },
-
- partial: function (s) {
- return s.usage;
- }
- };
-
- function readAnthropicUsage(target, u) {
- if (!u) return;
- if (u.input_tokens != null) target.input = num(u.input_tokens);
- if (u.cache_read_input_tokens != null) target.cacheRead = num(u.cache_read_input_tokens);
- if (u.cache_creation_input_tokens != null) target.cacheWrite = num(u.cache_creation_input_tokens);
- if (u.output_tokens != null) target.output = num(u.output_tokens);
- if (u.server_tool_use && u.server_tool_use.web_search_requests != null) target.searches = num(u.server_tool_use.web_search_requests);
- }
-
- function openaiInput(messages) {
- var input = [];
- messages.forEach(function (m) {
- if (m.role === "assistant") {
- var text = (m.content || []).filter(function (p) { return p.type === "text" && p.text; }).map(function (p) { return p.text; }).join("");
- if (text) input.push({ role: "assistant", content: [{ type: "output_text", text: text }] });
- (m.content || []).forEach(function (p) {
- if (p.type === "tool_call") input.push({ type: "function_call", call_id: p.id, name: p.name, arguments: JSON.stringify(p.input || {}) });
- });
- return;
- }
- var parts = [];
- var images = [];
- (m.content || []).forEach(function (p) {
- if (p.type === "tool_result") {
- input.push({ type: "function_call_output", call_id: p.id, output: resultText(p.content) || (p.isError ? "error" : "ok") });
- resultImages(p.content).forEach(function (img) { images.push(img); });
- } else if (p.type === "image") {
- parts.push({ type: "input_image", image_url: dataUrl(p) });
- } else if (p.type === "text" && p.text) {
- parts.push({ type: "input_text", text: p.text });
- }
- });
- images.forEach(function (img) { parts.unshift({ type: "input_image", image_url: dataUrl(img) }); });
- if (parts.length) input.push({ role: "user", content: parts });
- });
- return input;
- }
-
- var openai = {
- id: "openai",
-
- build: function (req, key, flags) {
- if (req.lite) return openaiChat.build(req, key, flags);
- var instructions = systemText(req);
- var body = {
- model: req.model,
- input: openaiInput(req.messages || []),
- stream: true,
- store: false,
- max_output_tokens: req.maxTokens || 8192
- };
- if (instructions) body.instructions = instructions;
- if (!flags.noCacheKey && instructions && req.cache !== false) body.prompt_cache_key = req.cacheKey || "athera-" + hash(instructions);
- if (!flags.noReasoning) body.reasoning = { effort: mapEffort(req.effort, ["low", "medium", "high"]) };
- var tools = (req.tools || []).map(function (tool) {
- return { type: "function", name: tool.name, description: tool.description, parameters: tool.parameters, strict: false };
- });
- var web = webConfig(req);
- if ((web.search || web.fetch) && !flags.noWeb) {
- var ws = { type: "web_search" };
- if (web.allow.length && !flags.noWebFilter) ws.filters = { allowed_domains: web.allow };
- tools.push(ws);
- }
- if (tools.length) body.tools = tools;
- return {
- url: URLS.openai,
- headers: { "content-type": "application/json", authorization: "Bearer " + key },
- body: body
- };
- },
-
- recover: function (msg, flags, req) {
- if (req.lite) return openaiChat.recover(msg, flags, req);
- var m = String(msg);
- if (!flags.noReasoning && /reasoning/i.test(m)) return "noReasoning";
- if (!flags.noCacheKey && /prompt_cache_key/i.test(m)) return "noCacheKey";
- if (!flags.noWebFilter && /filters|allowed_domains/i.test(m)) return "noWebFilter";
- if (!flags.noWeb && /web_search/i.test(m)) return "noWeb";
- return null;
- },
-
- start: function (req, flags) {
- if (req.lite) return openaiChat.start(req, flags);
- return { lite: false, model: req.model, text: "", calls: {}, order: [], usage: emptyUsage(), stop: null, refusal: null };
- },
-
- event: function (s, name, d) {
- if (s.lite) return openaiChat.event(s, name, d);
- if (!d) return;
- var type = d.type || name;
- if (type === "error") throw streamError("openai", d.message || (d.error && d.error.message));
- if (type === "response.failed") throw streamError("openai", d.response && d.response.error && d.response.error.message);
- if (type === "response.created" && d.response && d.response.model) s.model = d.response.model;
- else if (type === "response.output_text.delta") {
- s.text += d.delta || "";
- emit(s, "onText", d.delta || "");
- } else if (type === "response.reasoning_summary_text.delta") {
- emit(s, "onThinking", d.delta || "");
- } else if (type === "response.refusal.delta") {
- s.refusal = { explanation: ((s.refusal && s.refusal.explanation) || "") + (d.delta || "") };
- } else if (type === "response.output_item.added") {
- var item = d.item || {};
- if (item.type === "function_call") {
- s.calls[item.id] = { id: item.call_id, name: item.name, args: "" };
- s.order.push(item.id);
- emit(s, "onToolStart", { id: item.call_id, name: item.name });
- }
- } else if (type === "response.function_call_arguments.delta") {
- if (s.calls[d.item_id]) s.calls[d.item_id].args += d.delta || "";
- } else if (type === "response.output_item.done") {
- var done = d.item || {};
- if (done.type === "function_call" && s.calls[done.id]) {
- s.calls[done.id].args = done.arguments || s.calls[done.id].args;
- } else if (done.type === "web_search_call") {
- s.usage.searches += 1;
- var action = done.action || {};
- emit(s, "onStatus", action.type === "open_page" ? { type: "fetch", url: action.url } : { type: "search", query: action.query || "" });
- }
- } else if (type === "response.completed" || type === "response.incomplete") {
- var r = d.response || {};
- if (r.model) s.model = r.model;
- var u = r.usage || {};
- var cached = num(u.input_tokens_details && u.input_tokens_details.cached_tokens);
- s.usage.input = Math.max(0, num(u.input_tokens) - cached);
- s.usage.cacheRead = cached;
- s.usage.output = num(u.output_tokens);
- if (type === "response.incomplete") s.stop = r.incomplete_details && r.incomplete_details.reason === "content_filter" ? "refusal" : "length";
- }
- },
-
- finish: function (s) {
- if (s.lite) return openaiChat.finish(s);
- var calls = s.order.map(function (k) {
- var c = s.calls[k];
- var parsed = parseArgs(c.args);
- return { id: c.id, name: c.name, input: parsed.value, invalid: !parsed.ok };
- });
- return {
- model: s.model,
- text: s.text,
- toolCalls: calls,
- stopReason: s.refusal ? "refusal" : s.stop || (calls.length ? "tool" : "end"),
- refusal: s.refusal,
- usage: s.usage,
- native: null
- };
- },
-
- partial: function (s) {
- return s.usage;
- }
- };
-
- function chatMessages(req, cacheSystem) {
- var out = [];
- var sys = (req.system || []).filter(function (b) { return b.text; });
- if (sys.length) {
- if (cacheSystem) {
- out.push({ role: "system", content: sys.map(function (b, i) {
- var part = { type: "text", text: b.text };
- if (i === sys.length - 1 || b.cache) part.cache_control = { type: "ephemeral" };
- return part;
- }) });
- } else {
- out.push({ role: "system", content: sys.map(function (b) { return b.text; }).join("\n\n") });
- }
- }
- (req.messages || []).forEach(function (m) {
- if (m.role === "assistant") {
- if (m.native && m.native.provider === req.provider && m.native.model === req.model && m.native.data) return out.push(clone(m.native.data));
- var text = (m.content || []).filter(function (p) { return p.type === "text" && p.text; }).map(function (p) { return p.text; }).join("");
- var calls = (m.content || []).filter(function (p) { return p.type === "tool_call"; }).map(function (p) {
- return { id: p.id, type: "function", function: { name: p.name, arguments: JSON.stringify(p.input || {}) } };
- });
- var msg = { role: "assistant", content: text || null };
- if (calls.length) msg.tool_calls = calls;
- if (text || calls.length) out.push(msg);
- return;
- }
- var parts = [];
- var images = [];
- (m.content || []).forEach(function (p) {
- if (p.type === "tool_result") {
- out.push({ role: "tool", tool_call_id: p.id, content: resultText(p.content) || (p.isError ? "error" : "ok") });
- resultImages(p.content).forEach(function (img) { images.push(img); });
- } else if (p.type === "image") {
- parts.push({ type: "image_url", image_url: { url: dataUrl(p) } });
- } else if (p.type === "text" && p.text) {
- parts.push({ type: "text", text: p.text });
- }
- });
- images.forEach(function (img) { parts.unshift({ type: "image_url", image_url: { url: dataUrl(img) } }); });
- if (!parts.length) return;
- var onlyText = parts.every(function (p) { return p.type === "text"; });
- out.push({ role: "user", content: onlyText ? parts.map(function (p) { return p.text; }).join("\n\n") : parts });
- });
- return out;
- }
-
- function chatAdapter(cfg) {
- var adapter = {
- id: cfg.id,
-
- build: function (req, key, flags) {
- var model = cfg.model ? cfg.model(req, flags) : req.model;
- var body = {
- model: model,
- messages: chatMessages(req, cfg.cacheSystem && cfg.cacheSystem(req, flags)),
- stream: true
- };
- if (!flags.noStreamOptions) body.stream_options = { include_usage: true };
- body[flags.altMax ? cfg.altMax : cfg.maxParam] = req.maxTokens || 8192;
- var tools = (req.tools || []).map(function (tool) {
- return { type: "function", function: { name: tool.name, description: tool.description, parameters: tool.parameters } };
- });
- if (tools.length) body.tools = tools;
- if (req.stop && req.stop.length && !flags.noStop) body.stop = req.stop.slice(0, 4);
- if (cfg.extra) cfg.extra(body, req, flags);
- var headers = { "content-type": "application/json", authorization: "Bearer " + key };
- if (cfg.headers) Object.assign(headers, cfg.headers());
- return { url: cfg.url, headers: headers, body: body };
- },
-
- recover: function (msg, flags) {
- var m = String(msg);
- if (!flags.noReasoning && /reasoning/i.test(m)) return "noReasoning";
- if (!flags.noStreamOptions && /stream_options|include_usage/i.test(m)) return "noStreamOptions";
- if (!flags.altMax && cfg.altMax && new RegExp(cfg.maxParam).test(m)) return "altMax";
- if (!flags.noStop && /\bstop\b/i.test(m)) return "noStop";
- if (!flags.noCache && /cache_control/i.test(m)) return "noCache";
- if (!flags.noWeb && /online|plugin|web/i.test(m)) return "noWeb";
- return null;
- },
-
- start: function (req) {
- return { lite: true, provider: cfg.id, model: req.model, reqModel: req.model, text: "", reasoning: "", reasoningDetails: null, calls: [], usage: emptyUsage(), cost: null, stop: null, refusal: null };
- },
-
- event: function (s, name, d) {
- if (!d) return;
- if (d.error) throw streamError(cfg.id, d.error.message || d.error);
- if (d.model) s.model = d.model;
- var choice = d.choices && d.choices[0];
- if (choice) {
- var delta = choice.delta || {};
- if (delta.content) {
- s.text += delta.content;
- emit(s, "onText", delta.content);
- }
- var thought = delta.reasoning || delta.reasoning_content;
- if (thought) {
- s.reasoning += thought;
- emit(s, "onThinking", thought);
- }
- if (delta.reasoning_details) s.reasoningDetails = (s.reasoningDetails || []).concat(delta.reasoning_details);
- if (delta.refusal) s.refusal = { explanation: ((s.refusal && s.refusal.explanation) || "") + delta.refusal };
- (delta.tool_calls || []).forEach(function (tc) {
- var i = tc.index != null ? tc.index : s.calls.length;
- var c = s.calls[i];
- if (!c) {
- c = s.calls[i] = { id: tc.id || uid("call_"), name: "", args: "" };
- if (tc.function && tc.function.name) emit(s, "onToolStart", { id: c.id, name: tc.function.name });
- }
- if (tc.id) c.id = tc.id;
- if (tc.function && tc.function.name) c.name += tc.function.name;
- if (tc.function && tc.function.arguments) c.args += tc.function.arguments;
- });
- (delta.executed_tools || []).forEach(function (x) {
- if (/search/i.test(x.type || x.name || "")) {
- s.usage.searches += 1;
- emit(s, "onStatus", { type: "search", query: String(x.arguments || "").slice(0, 200) });
- }
- });
- if (choice.finish_reason) s.stop = choice.finish_reason;
- }
- var u = d.usage || (d.x_groq && d.x_groq.usage);
- if (u) {
- var details = u.prompt_tokens_details || {};
- var cached = num(details.cached_tokens);
- var written = num(details.cache_write_tokens);
- s.usage.input = Math.max(0, num(u.prompt_tokens) - cached - written);
- s.usage.cacheRead = cached;
- s.usage.cacheWrite = written;
- s.usage.output = num(u.completion_tokens);
- if (typeof u.cost === "number" && isFinite(u.cost)) s.cost = u.cost;
- }
- },
-
- finish: function (s) {
- var calls = s.calls.filter(Boolean).map(function (c) {
- var parsed = parseArgs(c.args);
- return { id: c.id, name: c.name, input: parsed.value, invalid: !parsed.ok };
- });
- var native = { role: "assistant", content: s.text || null };
- if (calls.length) {
- native.tool_calls = s.calls.filter(Boolean).map(function (c) {
- return { id: c.id, type: "function", function: { name: c.name, arguments: c.args || "{}" } };
- });
- }
- if (s.reasoningDetails) native.reasoning_details = s.reasoningDetails;
- var stop = { stop: "end", tool_calls: "tool", function_call: "tool", length: "length", content_filter: "refusal" }[s.stop] || (calls.length ? "tool" : "end");
- return {
- model: s.model,
- text: s.text,
- toolCalls: calls,
- stopReason: s.refusal ? "refusal" : stop,
- refusal: s.refusal,
- usage: s.usage,
- cost: s.cost,
- native: cfg.keepNative ? native : null
- };
- },
-
- partial: function (s) {
- return s.usage;
- }
- };
- return adapter;
- }
-
- var openaiChat = chatAdapter({
- id: "openai",
- url: URLS.openaiChat,
- maxParam: "max_completion_tokens",
- altMax: "max_tokens",
- extra: function (body, req, flags) {
- if (!flags.noReasoning && req.reasoning) body.reasoning_effort = mapEffort(req.effort, ["low", "medium", "high"]);
- if (!flags.noCacheKey && req.cache !== false && body.messages[0] && body.messages[0].role === "system") {
- body.prompt_cache_key = req.cacheKey || "athera-" + hash(String(body.messages[0].content));
- }
- }
- });
-
- var openrouter = chatAdapter({
- id: "openrouter",
- url: URLS.openrouter,
- maxParam: "max_tokens",
- keepNative: true,
- cacheSystem: function (req, flags) {
- return req.cache !== false && !flags.noCache && /^(anthropic|google)\//.test(req.model);
- },
- model: function (req, flags) {
- var w = webConfig(req);
- return (w.search || w.fetch) && !flags.noWeb && !/:online$/.test(req.model) ? req.model + ":online" : req.model;
- },
- headers: function () {
- var h = { "X-Title": "AtheraStudio Code" };
- if (/^https?:$/.test(location.protocol)) h["HTTP-Referer"] = location.origin;
- return h;
- },
- extra: function (body, req, flags) {
- if (!flags.noReasoning) body.reasoning = { effort: mapEffort(req.effort, ["low", "medium", "high"]), exclude: !req.showThinking };
- }
- });
-
- var groq = chatAdapter({
- id: "groq",
- url: URLS.groq,
- maxParam: "max_completion_tokens",
- altMax: "max_tokens",
- extra: function (body, req, flags) {
- if (!flags.noReasoning && /gpt-oss|qwen3/i.test(req.model)) body.reasoning_effort = mapEffort(req.effort, ["low", "medium", "high"]);
- }
- });
-
- var SCHEMA_KEYS = ["type", "description", "properties", "required", "items", "enum", "nullable", "format", "minimum", "maximum", "minItems", "maxItems"];
-
- function geminiSchema(schema) {
- if (!schema || typeof schema !== "object") return schema;
- var out = {};
- SCHEMA_KEYS.forEach(function (k) {
- if (schema[k] === undefined) return;
- if (k === "properties") {
- out.properties = {};
- Object.keys(schema.properties).forEach(function (p) { out.properties[p] = geminiSchema(schema.properties[p]); });
- } else if (k === "items") {
- out.items = geminiSchema(schema.items);
- } else if (k === "type" && Array.isArray(schema.type)) {
- var types = schema.type.filter(function (x) { return x !== "null"; });
- out.type = types[0] || "string";
- if (schema.type.indexOf("null") >= 0) out.nullable = true;
- } else {
- out[k] = clone(schema[k]);
- }
- });
- return out;
- }
-
- function geminiModel(model) {
- return String(model || "").replace(/^models\//, "");
- }
-
- function geminiThinking(model, req) {
- if (/gemini-3/i.test(model)) return { thinkingLevel: req.reasoning ? "high" : "low", includeThoughts: !!req.showThinking };
- if (/gemini-2\.5-flash/i.test(model)) return { thinkingBudget: req.reasoning ? -1 : 0, includeThoughts: !!req.showThinking };
- if (/gemini-2\.5-pro/i.test(model)) return { thinkingBudget: req.reasoning ? -1 : 128, includeThoughts: !!req.showThinking };
- return null;
- }
-
- function geminiContents(req, flags) {
- var out = [];
- var gids = {};
- function push(role, parts) {
- if (!parts.length) return;
- var last = out[out.length - 1];
- if (last && last.role === role) last.parts = last.parts.concat(parts);
- else out.push({ role: role, parts: parts });
- }
- function inline(p) {
- return { inlineData: { mimeType: p.mime, data: p.data } };
- }
- (req.messages || []).forEach(function (m) {
- if (m.role === "assistant") {
- (m.content || []).forEach(function (p) { if (p.type === "tool_call" && p.gid) gids[p.id] = true; });
- if (m.native && m.native.provider === "gemini" && m.native.model === geminiModel(req.model)) return push("model", clone(m.native.data));
- push("model", (m.content || []).map(function (p) {
- if (p.type === "text" && p.text) return { text: p.text };
- if (p.type === "tool_call") {
- var part = { functionCall: { name: p.name, args: p.input || {} } };
- if (flags.dummySig) part.thoughtSignature = "skip_thought_signature_validator";
- return part;
- }
- return null;
- }).filter(Boolean));
- return;
- }
- var parts = [];
- var images = [];
- (m.content || []).forEach(function (p) {
- if (p.type === "tool_result") {
- var fr = { name: p.name || "tool", response: p.isError ? { error: resultText(p.content) } : { result: resultText(p.content) } };
- if (gids[p.id]) fr.id = p.id;
- parts.push({ functionResponse: fr });
- resultImages(p.content).forEach(function (img) { images.push(inline(img)); });
- } else if (p.type === "image") {
- parts.push(inline(p));
- } else if (p.type === "text" && p.text) {
- parts.push({ text: p.text });
- }
- });
- push("user", parts.concat(images));
- });
- return out;
- }
-
- var gemini = {
- id: "gemini",
-
- build: function (req, key, flags) {
- var model = geminiModel(req.model);
- var body = { contents: geminiContents(req, flags) };
- var sys = systemText(req);
- if (sys) body.systemInstruction = { parts: [{ text: sys }] };
- var tools = [];
- var decls = (req.tools || []).map(function (tool) {
- return { name: tool.name, description: tool.description, parameters: geminiSchema(tool.parameters) };
- });
- if (decls.length) tools.push({ functionDeclarations: decls });
- var web = webConfig(req);
- if (web.search && !flags.noWeb) tools.push({ google_search: {} });
- if (web.fetch && !flags.noWeb && !flags.noFetch) tools.push({ url_context: {} });
- if (tools.length) body.tools = tools;
- var gen = { maxOutputTokens: req.maxTokens || 8192 };
- if (req.stop && req.stop.length && !flags.noStop) gen.stopSequences = req.stop.slice(0, 5);
- var thinking = flags.noThinking ? null : geminiThinking(model, req);
- if (thinking) gen.thinkingConfig = thinking;
- body.generationConfig = gen;
- return {
- url: URLS.gemini + encodeURIComponent(model) + ":streamGenerateContent?alt=sse",
- headers: { "content-type": "application/json", "x-goog-api-key": key },
- body: body
- };
- },
-
- recover: function (msg, flags) {
- var m = String(msg);
- if (!flags.dummySig && /signature/i.test(m)) return "dummySig";
- if (!flags.noThinking && /thinking/i.test(m)) return "noThinking";
- if (!flags.noFetch && /url_context|urlContext/i.test(m)) return "noFetch";
- if (!flags.noWeb && /google_search|googleSearch|search/i.test(m)) return "noWeb";
- if (!flags.noStop && /stop/i.test(m)) return "noStop";
- return null;
- },
-
- start: function (req) {
- return { model: geminiModel(req.model), text: "", parts: [], calls: [], usage: emptyUsage(), stop: null, refusal: null, queries: {} };
- },
-
- event: function (s, name, d) {
- if (!d) return;
- if (d.error) throw streamError("gemini", d.error.message || d.error.status);
- if (d.modelVersion) s.model = d.modelVersion;
- if (d.promptFeedback && d.promptFeedback.blockReason) s.refusal = { category: d.promptFeedback.blockReason };
- var cand = d.candidates && d.candidates[0];
- if (cand) {
- ((cand.content && cand.content.parts) || []).forEach(function (part) {
- if (part.functionCall) {
- var fc = part.functionCall;
- var call = { id: fc.id || uid("gcall_"), name: fc.name, input: fc.args || {}, gid: !!fc.id };
- s.calls.push(call);
- emit(s, "onToolStart", { id: call.id, name: call.name });
- s.parts.push(clone(part));
- return;
- }
- if (part.thought) {
- if (part.text) emit(s, "onThinking", part.text);
- s.parts.push(clone(part));
- return;
- }
- if (typeof part.text === "string") {
- s.text += part.text;
- if (part.text) emit(s, "onText", part.text);
- var last = s.parts[s.parts.length - 1];
- if (last && typeof last.text === "string" && !last.thought && !last.thoughtSignature && !part.thoughtSignature && !last.functionCall) last.text += part.text;
- else s.parts.push(clone(part));
- return;
- }
- s.parts.push(clone(part));
- });
- if (cand.finishReason) s.stop = cand.finishReason;
- var gm = cand.groundingMetadata;
- if (gm && gm.webSearchQueries) {
- gm.webSearchQueries.forEach(function (q) {
- if (s.queries[q]) return;
- s.queries[q] = true;
- s.usage.searches += 1;
- emit(s, "onStatus", { type: "search", query: q });
- });
- }
- }
- var u = d.usageMetadata;
- if (u) {
- var cached = num(u.cachedContentTokenCount);
- s.usage.input = Math.max(0, num(u.promptTokenCount) + num(u.toolUsePromptTokenCount) - cached);
- s.usage.cacheRead = cached;
- s.usage.output = num(u.candidatesTokenCount) + num(u.thoughtsTokenCount);
- }
- },
-
- finish: function (s) {
- var stop = s.calls.length ? "tool"
- : s.stop === "MAX_TOKENS" ? "length"
- : /SAFETY|RECITATION|BLOCKLIST|PROHIBITED|SPII/.test(s.stop || "") || s.refusal ? "refusal"
- : "end";
- return {
- model: s.model,
- text: s.text,
- toolCalls: s.calls.map(function (c) { return { id: c.id, name: c.name, input: c.input, gid: c.gid }; }),
- stopReason: stop,
- refusal: s.refusal || (stop === "refusal" ? { category: s.stop } : null),
- usage: s.usage,
- native: s.parts
- };
- },
-
- partial: function (s) {
- return s.usage;
- }
- };
-
- var ADAPTERS = { anthropic: anthropic, openai: openai, gemini: gemini, openrouter: openrouter, groq: groq };
-
- function estimateInput(req) {
- var chars = systemText(req).length;
- var images = 0;
- (req.messages || []).forEach(function (m) {
- (m.content || []).forEach(function (p) {
- if (p.type === "text") chars += (p.text || "").length;
- else if (p.type === "image") images += 1;
- else if (p.type === "tool_call") chars += JSON.stringify(p.input || {}).length + 40;
- else if (p.type === "tool_result") {
- chars += resultText(p.content).length + 40;
- images += resultImages(p.content).length;
- }
- });
- });
- (req.tools || []).forEach(function (tool) { chars += JSON.stringify(tool).length; });
- return ai.budget.tokensFromChars(chars) + images * IMAGE_TOKENS;
- }
-
- function estimateRequest(req, row) {
- var output = Math.min(req.maxTokens || 8192, req.expectedOutput || 1500);
- var web = webConfig(req);
- return ai.budget.estimate(row, {
- input: estimateInput(req),
- output: output,
- searches: web.search ? 1 : 0
- });
- }
-
- function estimateOutputFromText(text) {
- return ai.budget.tokens(text || "");
- }
-
- function neutralMessage(provider, model, result) {
- var content = [];
- if (result.text) content.push({ type: "text", text: result.text });
- result.toolCalls.forEach(function (c) {
- var part = { type: "tool_call", id: c.id, name: c.name, input: c.input };
- if (c.gid) part.gid = true;
- content.push(part);
- });
- var msg = { role: "assistant", content: content };
- if (result.native) msg.native = { provider: provider, model: model, data: result.native };
- return msg;
- }
-
- async function record(req, model, usage, cost) {
- try {
- await ai.budget.record({
- provider: req.provider,
- model: model,
- role: req.role || "",
- kind: req.kind || "chat",
- usage: usage,
- cost: cost
- });
- } catch (e) {
- console.error(e);
- }
- }
-
- var providers = (ai.providers = {
- adapters: ADAPTERS,
-
- estimateInput: estimateInput,
-
- estimate: function (req) {
- var row = req.row || ai.findModel(req.provider, req.model);
- return estimateRequest(req, row);
- },
-
- stream: async function (req, handlers) {
- ai.assertNetwork();
- if (ai.redact) req = ai.redact.request(req);
- var adapter = ADAPTERS[req.provider];
- if (!adapter) throw providerError(req.provider, "ai.err.unknown_provider");
- if (!req.model) throw providerError(req.provider, "ai.err.no_model");
- var key;
- try {
- key = await ai.keys.get(req.provider);
- } catch (e) {
- if (e.code === "locked") throw e;
- throw providerError(req.provider, "ai.err.no_key");
- }
- if (!key) throw providerError(req.provider, "ai.err.no_key");
- var row = req.row || ai.findModel(req.provider, req.model);
- if (req.budget !== false) {
- var check = await ai.budget.check(estimateRequest(req, row));
- if (!check.ok) {
- var be = new Error(ai.t(check.reason, check.params));
- be.code = "budget";
- throw be;
- }
- }
-
- var controller = new AbortController();
- if (req.signal) {
- if (req.signal.aborted) controller.abort();
- else req.signal.addEventListener("abort", function () { controller.abort(); }, { once: true });
- }
- active.add(controller);
- var flags = {};
- var attempts = 0;
- var recoveries = 0;
- var state = null;
- var started = Date.now();
- try {
- for (;;) {
- var built = adapter.build(req, key, flags);
- var res;
- try {
- res = await send(built, controller.signal);
- } catch (e) {
- if (e.name === "AbortError" || controller.signal.aborted) throw e;
- if (attempts < MAX_RETRIES) {
- attempts++;
- await wait(800 * attempts, controller.signal);
- continue;
- }
- throw providerError(req.provider, "ai.err.network", { message: e.message });
- }
- if (!res.ok) {
- var err = await httpError(req.provider, res);
- if (res.status === 400 && recoveries < MAX_RECOVERIES) {
- var flag = adapter.recover(err.detail, flags, req);
- if (flag) {
- flags[flag] = true;
- recoveries++;
- continue;
- }
- }
- if (err.retryable && attempts < MAX_RETRIES) {
- attempts++;
- await wait(err.retryAfter || 1000 * Math.pow(2, attempts), controller.signal);
- continue;
- }
- throw err;
- }
- state = adapter.start(req, flags);
- state.handlers = handlers || {};
- await readSSE(res, function (name, data) { adapter.event(state, name, data); });
- var out = adapter.finish(state);
- var model = out.model || req.model;
- await record(req, model, out.usage, out.cost);
- state = null;
- return {
- provider: req.provider,
- model: model,
- requestedModel: req.model,
- text: out.text,
- toolCalls: out.toolCalls,
- stopReason: out.stopReason,
- refusal: out.refusal || null,
- usage: out.usage,
- cost: typeof out.cost === "number" ? out.cost : ai.budget.price(ai.findModel(req.provider, model) || row, out.usage).cost,
- costKnown: typeof out.cost === "number" || ai.budget.price(ai.findModel(req.provider, model) || row, out.usage).known,
- ms: Date.now() - started,
- flags: Object.keys(flags),
- message: neutralMessage(req.provider, req.provider === "gemini" ? geminiModel(req.model) : req.model, out)
- };
- }
- } catch (e) {
- var partialCost = 0;
- if (state) {
- var usage = Object.assign(emptyUsage(), adapter.partial(state));
- var produced = state.text || (state.blocks || []).filter(Boolean).map(function (b) { return (b.text || "") + (b.thinking || ""); }).join("");
- if (!usage.output) usage.output = estimateOutputFromText(produced);
- if (!usage.input) usage.input = estimateInput(req);
- await record(req, state.model || req.model, usage, state.cost);
- partialCost = typeof state.cost === "number" ? state.cost : ai.budget.price(ai.findModel(req.provider, state.model || req.model) || row, usage).cost;
- }
- if (e.name === "AbortError" || controller.signal.aborted) {
- var ab = new DOMException(t("ai.err.aborted"), "AbortError");
- ab.partialCost = partialCost;
- throw ab;
- }
- e.partialCost = partialCost;
- throw e;
- } finally {
- active.delete(controller);
- }
- },
-
- test: async function (provider) {
- var row = ai.models().find(function (m) { return m.provider === provider && m.model; });
- var model = row ? row.model : ai.get("ghost.provider") === provider ? ai.get("ghost.model") : "";
- if (!model) throw providerError(provider, "ai.err.no_model");
- var result = await providers.stream({
- provider: provider,
- model: model,
- row: row || null,
- kind: "test",
- lite: true,
- cache: false,
- effort: "low",
- maxTokens: 512,
- expectedOutput: 20,
- system: [{ text: "Reply with the single word OK." }],
- messages: [{ role: "user", content: [{ type: "text", text: "OK?" }] }]
- });
- return result;
- },
-
- abortAll: function () {
- active.forEach(function (c) { c.abort(); });
- active.clear();
- },
-
- busy: function () {
- return active.size > 0;
- }
- });
-
- A.on("ai-abort", function () { providers.abortAll(); });
- })();
-