v1.5.0
AtheraStudio Code
- (function () {
- "use strict";
-
- var A = window.Athera;
- var util = A.util;
- var ai = A.ai;
- var t = ai.t;
-
- var GEOMETRY_KEY = "ai.window";
- var MIN_W = 380;
- var MIN_H = 360;
- var COMPACT_W = 600;
-
- var sections = [];
- var win = null;
- var nav = null;
- var content = null;
- var chip = null;
- var current = null;
- var renderSeq = 0;
- var geom = A.store.get(GEOMETRY_KEY, null);
- var dock = { on: !!(geom && geom.docked), w: (geom && geom.dockW) || 420 };
- var reopen = !!(geom && geom.open);
- var lastSection = geom && geom.section || null;
- var wantsFocus = true;
- var dockBtn = null;
-
- function clamp(v, min, max) {
- return Math.max(min, Math.min(max, v));
- }
-
- function defaultGeometry() {
- var w = Math.min(680, window.innerWidth - 32);
- var h = Math.min(760, window.innerHeight - 96);
- return { x: window.innerWidth - w - 16, y: 56, w: w, h: h };
- }
-
- function fitGeometry(g) {
- var vw = window.innerWidth, vh = window.innerHeight;
- var minW = Math.min(MIN_W, vw - 16), minH = Math.min(MIN_H, vh - 16);
- var w = clamp(Math.round(g.w), minW, vw - 16);
- var h = clamp(Math.round(g.h), minH, vh - 16);
- return { x: clamp(Math.round(g.x), 8, vw - w - 8), y: clamp(Math.round(g.y), 8, vh - h - 8), w: w, h: h };
- }
-
- function applyGeometry(save) {
- geom = fitGeometry(geom || defaultGeometry());
- dock.w = clamp(Math.round(dock.w), 320, Math.max(320, Math.round(window.innerWidth * 0.6)));
- win.classList.toggle("is-docked", dock.on);
- if (dock.on) {
- win.style.left = "";
- win.style.top = "";
- win.style.height = "";
- win.style.width = dock.w + "px";
- document.documentElement.style.setProperty("--ath-ai-dock-w", dock.w + "px");
- } else {
- win.style.left = geom.x + "px";
- win.style.top = geom.y + "px";
- win.style.width = geom.w + "px";
- win.style.height = geom.h + "px";
- }
- win.classList.toggle("is-compact", (dock.on ? dock.w : geom.w) < COMPACT_W);
- syncDock();
- if (save) A.store.set(GEOMETRY_KEY, Object.assign({ section: current ? current.id : lastSection, docked: dock.on, dockW: dock.w, open: !!win && !win.hidden }, geom));
- }
-
- function syncDock() {
- var on = dock.on && !!win && !win.hidden;
- if (dockBtn) {
- var label = t(dock.on ? "ai.window.undock" : "ai.window.dock");
- dockBtn.title = label;
- dockBtn.setAttribute("aria-label", label);
- dockBtn.setAttribute("aria-pressed", dock.on ? "true" : "false");
- }
- if (document.body.classList.contains("ath-ai-docked") === on) return;
- document.body.classList.toggle("ath-ai-docked", on);
- if (A.editor && A.editor.view) A.editor.view.requestMeasure();
- }
-
- function el(tag, attrs, children) {
- return util.el(tag, attrs, children);
- }
-
- function iconButton(icon, label, onClick, cls) {
- return el("button", {
- type: "button",
- class: cls || "ath-icon-btn",
- title: label,
- "aria-label": label,
- html: A.icon(icon),
- onclick: onClick
- });
- }
-
- function button(label, kind, onClick, icon) {
- return el("button", {
- type: "button",
- class: "orb-btn orb-btn-sm orb-btn-" + (kind || "secondary"),
- html: (icon ? A.icon(icon) : "") + "<span>" + util.esc(label) + "</span>",
- onclick: onClick
- });
- }
-
- function alertBox(tone, title, text, extra) {
- return el("div", { class: "orb-alert orb-alert-" + tone + " ath-ai-alert" }, [
- el("div", { class: "orb-alert-body" }, [
- title ? el("div", { class: "orb-alert-title" }, title) : null,
- text ? el("div", { class: "orb-alert-text" }, text) : null
- ].concat(extra || []))
- ]);
- }
-
- function row(label, control, hint) {
- return el("div", { class: "ath-set-row ath-ai-row" }, [
- el("div", { class: "ath-set-label" }, [el("span", {}, label), hint ? el("small", {}, hint) : null]),
- el("div", { class: "ath-set-control" }, control)
- ]);
- }
-
- function heading(text) {
- return el("h3", { class: "ath-ai-subhead" }, text);
- }
-
- function hint(text) {
- return el("p", { class: "ath-set-hint" }, text);
- }
-
- function fail(e) {
- if (e && e.name === "AbortError") return;
- console.error(e);
- A.ui.toast(e && e.message ? e.message : String(e), "danger");
- }
-
- function bindSwitch(path, onChange) {
- var input = el("input", { type: "checkbox", "data-ai-path": path });
- input.checked = !!ai.get(path);
- input.addEventListener("change", function () {
- if (onChange) Promise.resolve(onChange(input.checked, input)).catch(fail);
- else ai.set(path, input.checked);
- });
- return el("label", { class: "orb-switch" }, [input, el("span", { class: "orb-switch-track" })]);
- }
-
- function bindSelect(path, options) {
- var value = String(ai.get(path));
- var select = el("select", { class: "orb-select", "data-ai-path": path }, options.map(function (o) {
- return el("option", { value: o[0], selected: String(o[0]) === value }, o[1]);
- }));
- select.addEventListener("change", function () { ai.set(path, select.value); });
- return select;
- }
-
- function bindNumber(path, step, suffix) {
- var lim = ai.limits(path) || [0, 1e9];
- var input = el("input", { type: "number", class: "orb-input ath-ai-number", min: lim[0], max: lim[1], step: step || 1, value: ai.get(path), "data-ai-path": path });
- input.addEventListener("change", function () {
- if (input.value === "" || !ai.set(path, Number(input.value))) input.value = ai.get(path);
- else input.value = ai.get(path);
- });
- return suffix ? el("div", { class: "ath-ai-unit" }, [input, el("span", {}, suffix)]) : input;
- }
-
- function bindText(path, attrs) {
- var input = el("input", Object.assign({ type: "text", class: "orb-input", spellcheck: "false", autocomplete: "off", value: ai.get(path), "data-ai-path": path }, attrs || {}));
- input.addEventListener("change", function () {
- if (!ai.set(path, input.value)) input.value = ai.get(path);
- });
- return input;
- }
-
- function bindArea(path, rows, max, mono) {
- var area = el("textarea", { class: "orb-textarea ath-ai-area" + (mono ? " orb-mono" : ""), rows: rows, spellcheck: mono ? "false" : "true", maxlength: max || null, "data-ai-path": path });
- area.value = ai.get(path);
- var counter = max ? el("div", { class: "ath-ai-counter" }) : null;
- function count() {
- if (counter) counter.textContent = t("ai.common.chars", { n: area.value.length, max: max });
- }
- var save = util.debounce(function () { ai.set(path, area.value); }, 400);
- area.addEventListener("input", function () { count(); save(); });
- area.addEventListener("blur", function () { ai.set(path, area.value); });
- count();
- return el("div", { class: "ath-ai-area-wrap" }, [area, counter]);
- }
-
- function bindRange(path, step, format) {
- var lim = ai.limits(path);
- var out = el("span", { class: "ath-range-value" }, format(ai.get(path)));
- var input = el("input", { type: "range", class: "orb-range", min: lim[0], max: lim[1], step: step, value: ai.get(path), "data-ai-path": path });
- input.addEventListener("input", function () {
- out.textContent = format(Number(input.value));
- ai.set(path, Number(input.value));
- });
- return el("div", { class: "ath-range" }, [input, out]);
- }
-
- function masterSwitch() {
- return bindSwitch("enabled", function (on, input) {
- if (!on) {
- ai.disable();
- return;
- }
- return ai.enable().then(function (ok) { input.checked = ok; });
- });
- }
-
- function permRow(perm) {
- return row(t("ai.perm." + perm), bindSwitch("perms." + perm), t("ai.perm." + perm + "_hint"));
- }
-
- function syncControls() {
- if (!win) return;
- win.querySelectorAll("[data-ai-path]").forEach(function (n) {
- var path = n.getAttribute("data-ai-path");
- var v = path === "enabled" ? ai.enabled() : ai.get(path);
- if (n.type === "checkbox") n.checked = !!v;
- else if (n !== document.activeElement) n.value = v == null ? "" : v;
- });
- }
-
- function updateChip() {
- if (!chip) return;
- ai.budget.month().then(function (m) {
- var limit = ai.get("budget.monthly");
- chip.textContent = limit > 0
- ? t("ai.chip.spend_limit", { spent: ai.budget.format(m.cost), limit: ai.budget.format(limit) })
- : t("ai.chip.spend", { spent: ai.budget.format(m.cost) });
- chip.classList.toggle("is-over", limit > 0 && m.cost >= limit * 0.9);
- });
- }
-
- function updateMenu() {
- var label = document.getElementById("ai-toggle-label");
- if (label) {
- label.setAttribute("data-ai-i18n", ai.enabled() ? "ai.menu.disable" : "ai.menu.enable");
- label.textContent = t(label.getAttribute("data-ai-i18n"));
- }
- document.body.classList.toggle("ath-ai-on", ai.enabled());
- }
-
- function renderNav() {
- if (!nav) return;
- nav.innerHTML = "";
- sections.filter(function (s) { return !s.hidden || !s.hidden(); }).forEach(function (s) {
- var label = t(s.label);
- var b = el("button", {
- type: "button",
- class: "ath-ai-nav-item" + (current && current.id === s.id ? " is-active" : ""),
- role: "tab",
- "aria-selected": current && current.id === s.id ? "true" : "false",
- title: label,
- html: A.icon(s.icon) + "<span>" + util.esc(label) + "</span>",
- onclick: function () { wantsFocus = true; show(s.id); }
- });
- nav.appendChild(b);
- });
- }
-
- function show(id) {
- var def = sections.find(function (s) { return s.id === id; }) || sections[0];
- if (!def) return;
- current = def;
- lastSection = def.id;
- renderNav();
- renderCurrent();
- applyGeometry(true);
- }
-
- function renderCurrent() {
- if (!content || !current) return;
- var seq = ++renderSeq;
- var scroll = content.scrollTop;
- var keep = content.getAttribute("data-section") === current.id;
- var full = !!current.full;
- var box = el("div", { class: full ? "ath-ai-section is-full" : "ath-ai-section ath-settings" });
- var head = full ? null : el("h2", { class: "ath-ai-section-title" }, t(current.label));
- Promise.resolve().then(function () { return current.render(box); }).then(function () {
- if (seq !== renderSeq) return;
- content.innerHTML = "";
- content.setAttribute("data-section", current.id);
- content.classList.toggle("is-full", full);
- if (head) content.appendChild(head);
- content.appendChild(box);
- content.scrollTop = keep ? scroll : 0;
- }).catch(function (e) {
- if (seq !== renderSeq) return;
- content.innerHTML = "";
- content.appendChild(alertBox("danger", t("ai.common.error"), e && e.message ? e.message : String(e)));
- });
- }
-
- function editingInside() {
- var a = document.activeElement;
- return !!content && content.contains(a) && /^(INPUT|TEXTAREA|SELECT)$/.test(a.tagName) && a.type !== "checkbox";
- }
-
- function startPointer(e, onMove, onEnd) {
- if (e.button !== 0) return;
- e.preventDefault();
- var target = e.currentTarget;
- target.setPointerCapture(e.pointerId);
- document.body.classList.add("ath-resizing");
- var sx = e.clientX, sy = e.clientY, start = Object.assign({ dockW: dock.w }, geom);
- function move(ev) { onMove(ev.clientX - sx, ev.clientY - sy, start); applyGeometry(false); }
- function up() {
- target.removeEventListener("pointermove", move);
- target.removeEventListener("pointerup", up);
- target.removeEventListener("pointercancel", up);
- document.body.classList.remove("ath-resizing");
- applyGeometry(true);
- if (onEnd) onEnd();
- }
- target.addEventListener("pointermove", move);
- target.addEventListener("pointerup", up);
- target.addEventListener("pointercancel", up);
- }
-
- function resizeHandle(dir) {
- var h = el("div", { class: "ath-ai-resize ath-ai-resize-" + dir, "aria-hidden": "true" });
- h.addEventListener("pointerdown", function (e) {
- startPointer(e, function (dx, dy, s) {
- var minW = Math.min(MIN_W, window.innerWidth - 16);
- var minH = Math.min(MIN_H, window.innerHeight - 16);
- if (dir.indexOf("e") >= 0) geom.w = Math.max(minW, s.w + dx);
- if (dock.on) {
- if (dir === "w") dock.w = s.dockW - dx;
- return;
- }
- if (dir.indexOf("w") >= 0) {
- var w = Math.max(minW, s.w - dx);
- geom.x = s.x + (s.w - w);
- geom.w = w;
- }
- if (dir.indexOf("s") >= 0) geom.h = Math.max(minH, s.h + dy);
- });
- });
- return h;
- }
-
- function build() {
- var title = el("span", { class: "ath-ai-title", id: "ath-ai-title" });
- chip = el("button", { type: "button", class: "ath-ai-chip", onclick: function () { show("model"); } });
- var head = el("header", { class: "ath-ai-head" }, [
- el("span", { class: "ath-ai-logo", html: A.icon("sparkles") }),
- title,
- chip,
- el("span", { class: "ath-ai-spacer" }),
- el("span", { class: "ath-ai-master", "data-ai-i18n-title": "ai.window.master" }, masterSwitch()),
- (dockBtn = iconButton("sidebar", t("ai.window.dock"), function () { aiUi.setDocked(!dock.on); })),
- iconButton("x", A.t("common.close"), function () { aiUi.close(); })
- ]);
- head.addEventListener("pointerdown", function (e) {
- if (dock.on || e.target.closest("button, input, label, select, a")) return;
- startPointer(e, function (dx, dy, s) { geom.x = s.x + dx; geom.y = s.y + dy; });
- });
- head.addEventListener("dblclick", function (e) {
- if (dock.on || e.target.closest("button, input, label, select, a")) return;
- geom = defaultGeometry();
- applyGeometry(true);
- });
- nav = el("nav", { class: "ath-ai-nav", role: "tablist", "data-ai-i18n-title": "ai.window.sections" });
- content = el("div", { class: "ath-ai-content", role: "tabpanel" });
- win = el("div", { class: "ath-ai-window", role: "dialog", "aria-modal": "false", "aria-labelledby": "ath-ai-title", tabindex: "-1", hidden: true }, [
- head,
- el("div", { class: "ath-ai-body" }, [nav, content]),
- resizeHandle("w"), resizeHandle("e"), resizeHandle("s"), resizeHandle("sw"), resizeHandle("se")
- ]);
- win.addEventListener("keydown", function (e) {
- if (e.key !== "Escape" || /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName)) return;
- e.preventDefault();
- e.stopPropagation();
- aiUi.close();
- });
- document.body.appendChild(win);
- updateTitle();
- }
-
- function updateTitle() {
- if (!win) return;
- win.querySelector(".ath-ai-title").textContent = ai.name();
- ai.applyLabels(win);
- }
-
- var aiUi = (A.aiUi = {
- section: function (def) {
- sections = sections.filter(function (s) { return s.id !== def.id; });
- sections.push(def);
- sections.sort(function (a, b) { return a.order - b.order; });
- if (win && !win.hidden) renderNav();
- },
-
- open: function (id, opts) {
- if (!win) build();
- var opening = win.hidden;
- win.hidden = false;
- if (opening) {
- applyGeometry(false);
- updateChip();
- }
- wantsFocus = !opts || opts.focus !== false;
- if (id || !current) show(id || lastSection || sections[0].id);
- else if (opening) renderCurrent();
- applyGeometry(true);
- if (!opts || opts.focus !== false) win.focus({ preventScroll: true });
- A.emit("ai-window", true);
- },
-
- close: function () {
- if (!win || win.hidden) return;
- win.hidden = true;
- applyGeometry(true);
- A.emit("ai-window", false);
- var focusTarget = A.tabs && A.tabs.active && A.tabs.active.kind === "text" ? A.editor.view : null;
- if (focusTarget) focusTarget.focus();
- },
-
- toggle: function () {
- if (win && !win.hidden && win.contains(document.activeElement)) aiUi.close();
- else aiUi.open();
- },
-
- isOpen: function () {
- return !!win && !win.hidden;
- },
-
- wantsFocus: function () {
- return wantsFocus;
- },
-
- isDocked: function () {
- return dock.on;
- },
-
- setDocked: function (on) {
- dock.on = !!on;
- if (!win) build();
- if (win.hidden) aiUi.open();
- else applyGeometry(true);
- applyGeometry(true);
- if (current && current.id === "overview" && !editingInside()) renderCurrent();
- },
-
- current: function () {
- return current ? current.id : null;
- },
-
- refresh: function () {
- if (aiUi.isOpen() && !editingInside()) renderCurrent();
- },
-
- el: el,
- row: row,
- heading: heading,
- hint: hint,
- alert: alertBox,
- button: button,
- iconButton: iconButton,
- bindSwitch: bindSwitch,
- bindSelect: bindSelect,
- bindNumber: bindNumber,
- bindText: bindText,
- bindArea: bindArea,
- bindRange: bindRange,
- permRow: permRow,
- fail: fail,
-
- init: function () {
- ai.applyLabels(document);
- updateMenu();
- window.addEventListener("resize", util.debounce(function () { if (aiUi.isOpen()) applyGeometry(true); }, 150));
- if (reopen) setTimeout(function () { aiUi.open(null, { focus: false }); }, 0);
- }
- });
-
- A.on("ai-config", function (path) {
- if (path === "enabled" || path === "consent") updateMenu();
- syncControls();
- if (/^budget\./.test(path)) updateChip();
- if (current && current.live && current.live(path) && !editingInside()) renderCurrent();
- });
- A.on("ai-usage", function () {
- updateChip();
- if (current && current.id === "model" && aiUi.isOpen()) refreshLive();
- });
- A.on("ai-keys", function () { if (current && (current.id === "keys" || current.id === "overview" || current.id === "network")) aiUi.refresh(); });
- A.on("ai-name", function () { updateTitle(); renderNav(); aiUi.refresh(); });
- A.on("lang", function () { updateMenu(); updateTitle(); renderNav(); if (aiUi.isOpen()) renderCurrent(); updateChip(); });
-
- var liveBox = null;
-
- function refreshLive() {
- if (!liveBox || !document.contains(liveBox)) return;
- renderLive(liveBox);
- }
-
- async function renderLive(box) {
- var m = await ai.budget.month();
- var blocked = await ai.budget.blocked();
- var limit = ai.get("budget.monthly");
- var s = ai.budget.session();
- box.innerHTML = "";
- var ratio = limit > 0 ? Math.min(1, m.cost / limit) : 0;
- box.appendChild(el("div", { class: "ath-ai-spend" }, [
- el("div", { class: "ath-ai-spend-main" }, [
- el("strong", {}, ai.budget.format(m.cost)),
- el("span", {}, limit > 0 ? t("ai.budget.of_limit", { limit: ai.budget.format(limit) }) : t("ai.budget.no_limit"))
- ]),
- limit > 0 ? el("div", { class: "orb-progress ath-ai-progress" + (ratio >= 0.9 ? " is-over" : "") }, [
- el("div", { class: "orb-progress-bar", style: "width:" + (ratio * 100).toFixed(1) + "%" })
- ]) : null,
- el("div", { class: "ath-ai-stats" }, [
- el("span", {}, t("ai.budget.requests", { n: m.requests })),
- el("span", {}, t("ai.budget.cache_rate", { rate: ai.budget.percent(ai.budget.cacheHitRate(m)) })),
- el("span", {}, t("ai.budget.searches", { n: m.searches })),
- el("span", {}, t("ai.budget.session", { cost: ai.budget.format(s.cost) }))
- ])
- ]));
- if (m.unpriced) box.appendChild(alertBox("warning", null, t("ai.budget.unpriced", { n: m.unpriced })));
- if (blocked) {
- box.appendChild(alertBox("danger", t("ai.budget.blocked_title"), t("ai.budget.blocked_text", { month: blocked.month }), [
- el("div", { class: "ath-ai-actions" }, [button(t("ai.budget.unblock"), "secondary", function () { ai.budget.unblock().catch(fail); })])
- ]));
- }
- box.appendChild(el("div", { class: "ath-ai-actions" }, [
- button(t("ai.budget.clear"), "ghost", async function () {
- if (await A.ui.confirm(t("ai.budget.clear"), t("ai.budget.clear_confirm"), A.t("common.delete"), true)) ai.budget.clear().catch(fail);
- }, "trash")
- ]));
- }
-
- function modelTable() {
- var rows = ai.models();
- var wrap = el("div", { class: "ath-ai-table-wrap" });
- var save = util.debounce(function () { ai.setModels(rows); }, 400);
- var roleOptions = [["", t("ai.models.role_none")]].concat(ai.ROLES.map(function (r) { return [r, t("ai.role." + r)]; }));
-
- function priceInput(r, f) {
- var input = el("input", {
- type: "number",
- class: "orb-input ath-ai-price",
- min: "0",
- step: "any",
- placeholder: "?",
- value: r[f] == null ? "" : r[f],
- "aria-label": t("ai.models.col_" + f)
- });
- input.addEventListener("change", function () {
- var n = input.value === "" ? null : Number(input.value);
- r[f] = n != null && isFinite(n) && n >= 0 ? n : null;
- input.value = r[f] == null ? "" : r[f];
- save();
- mark();
- });
- return input;
- }
-
- var tbody = el("tbody");
-
- function mark() {
- Array.prototype.forEach.call(tbody.children, function (tr, i) {
- var r = rows[i];
- var unpriced = !!r.model && (r.input == null || r.output == null);
- tr.classList.toggle("is-unpriced", unpriced);
- tr.title = unpriced ? t("ai.models.unpriced") : "";
- });
- }
-
- function draw() {
- tbody.innerHTML = "";
- rows.forEach(function (r, i) {
- var provider = el("select", { class: "orb-select ath-ai-cell-select", "aria-label": t("ai.models.col_provider") }, ai.PROVIDERS.map(function (p) {
- return el("option", { value: p, selected: p === r.provider }, ai.providerLabel(p));
- }));
- provider.addEventListener("change", function () { r.provider = provider.value; save(); });
- var model = el("input", { type: "text", class: "orb-input orb-mono ath-ai-model-id", value: r.model, spellcheck: "false", autocomplete: "off", placeholder: t("ai.models.model_ph"), "aria-label": t("ai.models.col_model") });
- model.addEventListener("change", function () { r.model = model.value.trim(); save(); mark(); });
- var role = el("select", { class: "orb-select ath-ai-cell-select", "aria-label": t("ai.models.col_role") }, roleOptions.map(function (o) {
- return el("option", { value: o[0], selected: o[0] === r.role }, o[1]);
- }));
- role.addEventListener("change", function () { r.role = role.value; save(); });
- var vision = el("input", { type: "checkbox", "aria-label": t("ai.models.col_vision") });
- vision.checked = !!r.vision;
- vision.addEventListener("change", function () { r.vision = vision.checked; save(); });
- var del = iconButton("trash", t("ai.models.remove"), function () {
- rows.splice(i, 1);
- ai.setModels(rows);
- draw();
- });
- tbody.appendChild(el("tr", {}, [
- el("td", {}, provider),
- el("td", {}, model),
- el("td", {}, role),
- el("td", { class: "ath-ai-center" }, el("label", { class: "orb-checkbox" }, vision)),
- el("td", {}, priceInput(r, "input")),
- el("td", {}, priceInput(r, "output")),
- el("td", {}, priceInput(r, "cacheRead")),
- el("td", {}, priceInput(r, "cacheWrite")),
- el("td", {}, priceInput(r, "search")),
- el("td", {}, del)
- ]));
- });
- mark();
- }
-
- var cols = ["provider", "model", "role", "vision", "input", "output", "cacheRead", "cacheWrite", "search", ""];
- var table = el("table", { class: "orb-table ath-ai-models" }, [
- el("thead", {}, el("tr", {}, cols.map(function (c) {
- return el("th", { title: c ? t("ai.models.col_" + c + "_hint") : null }, c ? t("ai.models.col_" + c) : "");
- }))),
- tbody
- ]);
- draw();
- wrap.appendChild(table);
- return el("div", {}, [
- wrap,
- el("div", { class: "ath-ai-actions" }, [
- button(t("ai.models.add"), "secondary", function () {
- rows.push(ai.blankModel(ai.get("mode") === "auto" ? "openai" : ai.get("mode")));
- ai.setModels(rows);
- draw();
- var last = tbody.lastElementChild && tbody.lastElementChild.querySelector(".ath-ai-model-id");
- if (last) last.focus();
- }, "plus"),
- button(t("ai.models.reset"), "ghost", async function () {
- if (!(await A.ui.confirm(t("ai.models.reset"), t("ai.models.reset_confirm"), t("ai.models.reset"), true))) return;
- ai.resetModels();
- rows = ai.models();
- draw();
- }, "undo")
- ])
- ]);
- }
-
- function routerProbe() {
- var input = el("textarea", { class: "orb-textarea ath-ai-area", rows: 2, placeholder: t("ai.router.probe_ph"), "aria-label": t("ai.router.probe") });
- var out = el("div", { class: "ath-ai-probe-out", "aria-live": "polite" });
- function run() {
- var parsed = ai.router.parseOverride(input.value);
- if (!parsed.text.trim()) { out.textContent = ""; return; }
- ai.router.decide({ text: parsed.text, contextTokens: ai.budget.tokens(parsed.text) + 3000 }, parsed.override).then(function (d) {
- var est = ai.router.estimate(d, { input: ai.budget.tokens(parsed.text) + 3000 });
- out.innerHTML = "";
- out.appendChild(el("div", {}, ai.router.describe(d)));
- out.appendChild(el("small", {}, t("ai.router.estimate", {
- cost: est.known ? ai.budget.format(est.cost) : t("ai.common.unknown"),
- effort: d.effort
- })));
- }).catch(function (e) {
- out.innerHTML = "";
- out.appendChild(el("div", { class: "is-error" }, e.message));
- });
- }
- input.addEventListener("input", util.debounce(run, 300));
- return el("div", { class: "ath-ai-probe-wrap" }, [
- heading(t("ai.router.probe")),
- hint(t("ai.router.probe_hint")),
- input,
- out
- ]);
- }
-
- function engineRow(id) {
- var engine = ai.search.ENGINES[id];
- var status = ai.keys.statusSync();
- var info = status.providers["search:" + id];
- var path = "search.engines." + id;
- var relayReady = !!ai.relayUrl();
- var reach = engine.direct ? t("ai.search.direct") : relayReady ? t("ai.search.via_relay") : t("ai.search.needs_relay");
- var input = el("input", { type: "password", class: "orb-input orb-mono", autocomplete: "off", spellcheck: "false", placeholder: t(info ? "ai.keys.replace_ph" : "ai.keys.paste_ph"), "aria-label": t("ai.keys.input_label", { provider: engine.label }) });
- function saveKey() {
- if (!input.value.trim()) return;
- ai.keys.set("search:" + id, input.value).then(function () {
- input.value = "";
- A.ui.toast(t("ai.keys.saved_toast", { provider: engine.label }), "success");
- }).catch(fail);
- }
- input.addEventListener("keydown", function (e) { if (e.key === "Enter") { e.preventDefault(); saveKey(); } });
- var fee = cfgFee(id);
- var feeInput = el("input", { type: "number", class: "orb-input ath-ai-number ath-ai-fee", min: "0", step: "any", placeholder: "?", value: fee == null ? "" : fee, "aria-label": t("ai.search.fee"), title: t("ai.search.fee_hint") });
- feeInput.addEventListener("change", function () {
- var v = feeInput.value === "" ? null : Number(feeInput.value);
- if (!ai.set(path + ".fee", v != null && isFinite(v) && v >= 0 ? v : null)) feeInput.value = cfgFee(id) == null ? "" : cfgFee(id);
- });
- var testBtn = info ? button(t("ai.keys.test"), "secondary", function () {
- if (!ai.enabled()) return A.ui.toast(t("ai.err.disabled"), "info");
- testBtn.disabled = true;
- ai.search.test(id).then(function (r) {
- A.ui.toast(t("ai.search.test_ok", { engine: engine.label, n: r.n, ms: r.ms }), "success");
- }).catch(fail).then(function () { testBtn.disabled = false; });
- }) : null;
- var toggle = bindSwitch(path + ".on");
- if (!engine.direct && !relayReady) toggle.querySelector("input").disabled = true;
- var controls = el("div", { class: "ath-ai-engine" }, [
- el("div", { class: "ath-ai-key-control" }, [
- input,
- button(A.t("common.save"), "primary", saveKey),
- testBtn,
- info ? iconButton("trash", t("ai.keys.remove", { provider: engine.label }), async function () {
- if (await A.ui.confirm(t("ai.keys.remove", { provider: engine.label }), t("ai.keys.remove_confirm", { provider: engine.label }), A.t("common.delete"), true)) {
- ai.keys.remove("search:" + id).catch(fail);
- }
- }) : null
- ]),
- el("label", { class: "ath-ai-fee-row" }, [el("span", {}, t("ai.search.fee")), feeInput, el("span", {}, "USD")])
- ]);
- var head = el("span", { class: "ath-ai-engine-head" }, [
- el("span", { class: "ath-ai-engine-name" }, [
- el("span", {}, engine.label),
- engine.direct ? null : el("span", { class: "orb-badge orb-tone-warning ath-ai-relay-badge", title: t("ai.relay.badge_title") }, t("ai.relay.badge"))
- ]),
- toggle
- ]);
- var desc = engine.host + " · " + reach + " · " + (info ? t("ai.keys.saved", { hint: info.hint }) : t("ai.keys.missing")) + (engine.scrape ? " · " + t("ai.search.scrape_note") : "");
- var r = row(head, controls, desc);
- r.classList.add("is-stacked", "ath-ai-engine-row");
- if (!engine.direct && !relayReady) r.classList.add("is-disabled");
- return r;
- }
-
- function cfgFee(id) {
- var v = ai.get("search.engines." + id + ".fee");
- return typeof v === "number" ? v : null;
- }
-
- function keyRow(p, status) {
- var info = status.providers[p];
- var input = el("input", {
- type: "password",
- class: "orb-input orb-mono",
- autocomplete: "off",
- spellcheck: "false",
- placeholder: t(info ? "ai.keys.replace_ph" : "ai.keys.paste_ph"),
- "aria-label": t("ai.keys.input_label", { provider: ai.providerLabel(p) })
- });
- function saveKey() {
- if (!input.value.trim()) return;
- ai.keys.set(p, input.value).then(function () {
- input.value = "";
- A.ui.toast(t("ai.keys.saved_toast", { provider: ai.providerLabel(p) }), "success");
- }).catch(fail);
- }
- input.addEventListener("keydown", function (e) { if (e.key === "Enter") { e.preventDefault(); saveKey(); } });
- var testBtn = info ? button(t("ai.keys.test"), "secondary", function () {
- if (!ai.enabled()) return A.ui.toast(t("ai.err.disabled"), "info");
- testBtn.disabled = true;
- ai.providers.test(p).then(function (r) {
- A.ui.toast(t("ai.keys.test_ok", {
- provider: ai.providerLabel(p),
- model: r.model,
- ms: r.ms,
- cost: r.costKnown ? ai.budget.format(r.cost) : t("ai.common.unknown")
- }), "success");
- }).catch(fail).then(function () { testBtn.disabled = false; });
- }) : null;
- var controls = el("div", { class: "ath-ai-key-control" }, [
- input,
- button(A.t("common.save"), "primary", saveKey),
- testBtn,
- info ? iconButton("trash", t("ai.keys.remove", { provider: ai.providerLabel(p) }), async function () {
- if (await A.ui.confirm(t("ai.keys.remove", { provider: ai.providerLabel(p) }), t("ai.keys.remove_confirm", { provider: ai.providerLabel(p) }), A.t("common.delete"), true)) {
- ai.keys.remove(p).catch(fail);
- }
- }) : null
- ]);
- var desc = t("ai.keys.goes_to", { host: ai.PROVIDER_HOSTS[p] }) + (info ? " " + t("ai.keys.saved", { hint: info.hint }) : " " + t("ai.keys.missing"));
- var r = row(ai.providerLabel(p), controls, desc);
- r.classList.add("is-stacked");
- return r;
- }
-
- function passwordPair(onSubmit, label) {
- var a = el("input", { type: "password", class: "orb-input", autocomplete: "new-password", placeholder: t("ai.keys.pass_new"), "aria-label": t("ai.keys.pass_new") });
- var b = el("input", { type: "password", class: "orb-input", autocomplete: "new-password", placeholder: t("ai.keys.pass_repeat"), "aria-label": t("ai.keys.pass_repeat") });
- var go = button(label, "primary", function () {
- if (a.value !== b.value) return A.ui.toast(t("ai.keys.pass_mismatch"), "warning");
- go.disabled = true;
- onSubmit(a.value).then(function () {
- a.value = b.value = "";
- }).catch(fail).then(function () { go.disabled = false; });
- }, "lock");
- return el("div", { class: "ath-ai-pass" }, [a, b, go]);
- }
-
- aiUi.section({
- id: "overview",
- order: 10,
- icon: "sparkles",
- label: "ai.sec.overview",
- live: function (path) { return path === "enabled" || path === "consent" || path === "relay.on"; },
- render: async function (box) {
- var on = ai.enabled();
- var status = await ai.keys.status();
- var keyCount = Object.keys(status.providers).length;
- var month = await ai.budget.month();
- var limit = ai.get("budget.monthly");
- box.appendChild(on
- ? alertBox("success", t("ai.ov.on_title"), t("ai.ov.on_text"))
- : alertBox("info", t("ai.ov.off_title"), t("ai.ov.off_text"), [
- el("div", { class: "ath-ai-actions" }, [button(t("ai.ov.enable"), "primary", function () { ai.enable().catch(fail); }, "power")])
- ]));
- box.appendChild(row(t("ai.ov.master"), masterSwitch(), t("ai.ov.master_hint")));
-
- var nameInput = el("input", { type: "text", class: "orb-input", maxlength: ai.NAME_MAX, value: ai.name(), placeholder: ai.DEFAULT_NAME, spellcheck: "false", autocomplete: "off" });
- nameInput.addEventListener("change", function () { nameInput.value = ai.setName(nameInput.value); });
- box.appendChild(row(t("ai.ov.name"), nameInput, t("ai.ov.name_hint", { max: ai.NAME_MAX })));
-
- var modeSelect = el("select", { class: "orb-select" }, [
- el("option", { value: "float", selected: !dock.on }, t("ai.window.mode_float")),
- el("option", { value: "dock", selected: dock.on }, t("ai.window.mode_dock"))
- ]);
- modeSelect.addEventListener("change", function () { aiUi.setDocked(modeSelect.value === "dock"); });
- box.appendChild(row(t("ai.window.mode"), modeSelect, t("ai.window.mode_hint")));
-
- box.appendChild(row(t("ai.ov.keys"), button(t("ai.ov.keys_manage"), "secondary", function () { show("keys"); }, "key"),
- status.locked ? t("ai.ov.keys_locked") : keyCount ? t("ai.ov.keys_count", { n: keyCount }) : t("ai.ov.keys_none")));
- box.appendChild(row(t("ai.ov.spend"), button(t("ai.ov.spend_manage"), "secondary", function () { show("model"); }, "coins"),
- limit > 0 ? t("ai.ov.spend_limit", { spent: ai.budget.format(month.cost), limit: ai.budget.format(limit) }) : t("ai.ov.spend_nolimit", { spent: ai.budget.format(month.cost) })));
-
- box.appendChild(row(t("ai.ov.relay"), button(t("ai.relay.setup"), "secondary", function () { show("relay"); }, "globe"),
- ai.relayUrl() ? t("ai.ov.relay_on", { url: ai.relayUrl() }) : t("ai.ov.relay_off")));
-
- box.appendChild(heading(t("ai.conv.head")));
- box.appendChild(row(t("ai.conv.sync"), bindSwitch("conversation.sync"), t("ai.conv.sync_hint")));
- box.appendChild(row(t("ai.conv.keep"), bindNumber("conversation.keep", 1), t("ai.conv.keep_hint")));
- box.appendChild(row(t("ai.conv.compact"), bindNumber("conversation.compactAt", 1000, t("ai.conv.chars")), t("ai.conv.compact_hint")));
-
- box.appendChild(heading(t("ai.ov.privacy_head")));
- if (ai.consented()) {
- var when = new Date(ai.consentDate());
- box.appendChild(row(t("ai.ov.consent"), button(t("ai.ov.consent_revoke"), "ghost", async function () {
- if (await A.ui.confirm(t("ai.ov.consent_revoke"), t("ai.ov.consent_revoke_confirm"), t("ai.ov.consent_revoke"), true)) ai.revokeConsent();
- }), t("ai.ov.consent_at", { date: isNaN(when) ? "" : when.toLocaleString(document.documentElement.lang || undefined) })));
- } else {
- box.appendChild(hint(t("ai.ov.consent_none")));
- }
- box.appendChild(hint(t("ai.ov.api_only")));
- }
- });
-
- aiUi.section({
- id: "instructions",
- order: 30,
- icon: "pencil",
- label: "ai.sec.instructions",
- render: async function (box) {
- box.appendChild(hint(t("ai.ins.intro")));
- box.appendChild(heading(t("ai.ins.global")));
- box.appendChild(bindArea("instructions", 10, ai.INSTRUCTIONS_MAX, false));
- box.appendChild(heading(t("ai.ins.project")));
- if (!A.fs.provider) {
- box.appendChild(hint(t("ai.priv.no_folder")));
- } else {
- var projectText = await ai.private.read("instructions.md");
- box.appendChild(hint(t(projectText != null ? "ai.ins.project_on" : "ai.ins.project_off")));
- if (projectText != null && projectText.trim()) {
- box.appendChild(el("pre", { class: "ath-ai-snippet orb-mono" }, projectText.trim().split("\n").slice(0, 12).join("\n")));
- }
- box.appendChild(el("div", { class: "ath-ai-actions" }, [button(t(projectText != null ? "ai.priv.open" : "ai.priv.create"), projectText != null ? "secondary" : "primary", function () {
- openPrivateFile("instructions.md").then(function () { aiUi.refresh(); }).catch(fail);
- }, projectText != null ? "file" : "filePlus")]));
- }
- box.appendChild(hint(t("ai.ins.precedence")));
- }
- });
-
- function privateEditor(name) {
- return ai.private.read(name).then(function (text) {
- var area = el("textarea", { class: "orb-textarea ath-ai-area orb-mono", rows: 18, spellcheck: "false" });
- area.value = text == null ? ai.private.template(name) : text;
- return A.ui.dialog({
- title: ai.private.path(name),
- size: "lg",
- body: el("div", {}, [hint(t("ai.priv.memory_editor")), area]),
- actions: [
- { label: A.t("common.cancel"), value: null, kind: "ghost" },
- { label: A.t("common.save"), value: "save", kind: "primary" }
- ]
- }).then(function (r) {
- if (r === "save") return ai.private.write(name, area.value).then(function () { A.ui.toast(t("ai.priv.saved", { name: name }), "success"); });
- });
- });
- }
-
- async function openPrivateFile(name) {
- if (ai.private.memoryMode()) return privateEditor(name);
- if (!(await ai.private.create(name))) return;
- await A.tabs.openPath(ai.private.path(name));
- }
-
- async function openPrivateDir(dir) {
- if (!(await ai.private.createDir(dir))) return;
- if (ai.private.memoryMode()) return A.ui.toast(t("ai.priv.memory_dir"), "info");
- if (document.body.classList.contains("ath-no-sidebar")) A.commands.toggleSidebar();
- await A.explorer.reveal(ai.private.path(dir));
- }
-
- aiUi.section({
- id: "private",
- order: 40,
- icon: "folder",
- label: "ai.sec.private",
- render: async function (box) {
- var st = await ai.private.status();
- if (!st.folder) {
- box.appendChild(alertBox("info", null, t("ai.priv.no_folder")));
- return;
- }
- box.appendChild(hint(t("ai.priv.intro")));
- if (st.memory) box.appendChild(alertBox("warning", t("ai.priv.memory_title"), t("ai.priv.memory_text")));
- ai.private.FILES.forEach(function (name) {
- var exists = st.files[name];
- var b = button(t(exists ? "ai.priv.open" : "ai.priv.create"), exists ? "secondary" : "primary", function () {
- openPrivateFile(name).then(function () { aiUi.refresh(); }).catch(fail);
- }, exists ? "file" : "filePlus");
- box.appendChild(row(name, b, t("ai.priv.desc_" + name.replace(/\.md$/, "").toLowerCase())));
- });
- box.appendChild(heading(t("ai.priv.folders")));
- ai.private.DIRS.forEach(function (dir) {
- box.appendChild(row(dir + "/", button(t("ai.priv.open_dir"), "secondary", function () {
- openPrivateDir(dir).then(function () { aiUi.refresh(); }).catch(fail);
- }, "folderOpen"), t("ai.priv.desc_" + dir)));
- });
- if (!st.memory) {
- box.appendChild(el("div", { class: "ath-ai-actions" }, [button(t("ai.priv.gitignore"), "ghost", function () {
- ai.private.addToGitignore().then(function (added) {
- A.ui.toast(t(added ? "ai.priv.gitignore_added" : "ai.priv.gitignore_present"), added ? "success" : "info");
- }).catch(fail);
- }, "shield")]));
- box.appendChild(hint(t("ai.priv.safety")));
- }
- }
- });
-
- aiUi.section({
- id: "changes",
- order: 45,
- icon: "undo",
- label: "ai.sec.changes",
- render: async function (box) {
- if (!A.fs.provider) {
- box.appendChild(alertBox("info", null, t("ai.priv.no_folder")));
- return;
- }
- var list = await ai.tools.snapshots();
- box.appendChild(hint(t(ai.get("snapshots") ? "ai.changes.intro" : "ai.changes.off")));
- if (!list.length) {
- box.appendChild(el("p", { class: "ath-set-empty" }, t("ai.changes.empty")));
- return;
- }
- var wrap = el("div", { class: "ath-ai-changes" });
- list.forEach(function (rec) {
- var when = new Date(rec.at).toLocaleString(document.documentElement.lang || undefined);
- var actions = el("div", { class: "ath-ai-change-actions" }, [
- rec.op === "move" ? null : iconButton("eye", t("ai.changes.show_diff"), function () {
- A.ui.dialog({
- title: t("ai.change.op_" + rec.op, { path: rec.path, to: rec.to || "" }),
- size: "lg",
- body: ai.tools.diffView(rec.before, rec.after),
- actions: [{ label: A.t("common.close"), value: null, kind: "secondary" }]
- });
- }),
- rec.undone ? null : iconButton("undo", t("ai.change.undo"), function () {
- ai.tools.undo(rec.id).then(function () { aiUi.refresh(); }).catch(fail);
- })
- ]);
- wrap.appendChild(el("div", { class: "ath-ai-change" + (rec.undone ? " is-undone" : "") }, [
- el("div", { class: "ath-ai-change-main" }, [
- el("span", { class: "ath-ai-change-op" }, t("ai.change.op_" + rec.op, { path: rec.path, to: rec.to || "" })),
- el("small", {}, when + (rec.undone ? " · " + t("ai.changes.undone_tag") : ""))
- ]),
- actions
- ]));
- });
- box.appendChild(wrap);
- box.appendChild(el("div", { class: "ath-ai-actions" }, [button(t("ai.changes.clear"), "ghost", async function () {
- if (await A.ui.confirm(t("ai.changes.clear"), t("ai.changes.clear_confirm"), A.t("common.delete"), true)) {
- ai.tools.clearSnapshots().then(function () { aiUi.refresh(); }).catch(fail);
- }
- }, "trash")]));
- }
- });
-
- aiUi.section({
- id: "recipes",
- order: 47,
- icon: "code",
- label: "ai.sec.recipes",
- render: async function (box) {
- box.appendChild(hint(t("ai.recipes.intro")));
- box.appendChild(heading(t("ai.recipes.builtin")));
- var builtin = el("div", { class: "ath-ai-cmd-list" });
- ai.commands.ORDER.forEach(function (name) {
- builtin.appendChild(el("div", { class: "ath-ai-cmd" }, [el("code", {}, "/" + name), el("span", {}, t("ai.cmd.desc_" + name))]));
- });
- box.appendChild(builtin);
- box.appendChild(heading(t("ai.recipes.own")));
- if (!A.fs.provider) {
- box.appendChild(hint(t("ai.priv.no_folder")));
- return;
- }
- var recipes = await ai.commands.loadRecipes(true);
- if (!recipes.length) box.appendChild(el("p", { class: "ath-set-empty" }, t("ai.recipes.empty")));
- recipes.forEach(function (r) {
- var rel = r.path.replace(/^\.private\//, "");
- box.appendChild(row(el("code", {}, "/" + r.name), el("div", { class: "ath-ai-actions" }, [
- button(t("ai.priv.open"), "secondary", function () { openPrivateFile(rel).catch(fail); }, "file"),
- iconButton("trash", A.t("common.delete"), async function () {
- if (!(await A.ui.confirm(A.t("common.delete"), t("ai.recipes.delete_confirm", { name: r.name }), A.t("common.delete"), true))) return;
- await ai.tools.io.remove(r.path);
- A.emit("files-changed");
- aiUi.refresh();
- })
- ]), (r.description || "") + (r.tier ? " · " + t("ai.role." + r.tier) : "")));
- });
- box.appendChild(el("div", { class: "ath-ai-actions" }, [button(t("ai.recipes.new"), "primary", async function () {
- var name = await A.ui.prompt(t("ai.recipes.new"), t("ai.recipes.name_label"), "", A.t("common.create"));
- if (!name) return;
- try {
- var path = await ai.commands.createRecipe(name);
- if (path) await openPrivateFile(path.replace(/^\.private\//, ""));
- aiUi.refresh();
- } catch (e) {
- fail(e);
- }
- }, "plus")]));
- box.appendChild(hint(t("ai.recipes.format")));
- }
- });
-
- A.on("ai-changes", function () { if (current && current.id === "changes") aiUi.refresh(); });
- A.on("workspace", function () { if (current && (current.id === "private" || current.id === "changes")) aiUi.refresh(); });
-
- aiUi.section({
- id: "keys",
- order: 50,
- icon: "key",
- label: "ai.sec.keys",
- render: async function (box) {
- var status = await ai.keys.status();
- if (!status.crypto) {
- box.appendChild(alertBox("danger", t("ai.keys.no_crypto_title"), A.t("ai.keys.no_crypto")));
- return;
- }
- if (status.locked) {
- var pass = el("input", { type: "password", class: "orb-input", autocomplete: "current-password", placeholder: t("ai.keys.pass_enter"), "aria-label": t("ai.keys.pass_enter") });
- var unlock = function () {
- ai.keys.unlock(pass.value).then(function (ok) {
- if (!ok) {
- pass.value = "";
- pass.focus();
- A.ui.toast(t("ai.keys.pass_wrong"), "danger");
- }
- }).catch(fail);
- };
- pass.addEventListener("keydown", function (e) { if (e.key === "Enter") { e.preventDefault(); unlock(); } });
- box.appendChild(alertBox("info", t("ai.keys.locked_title"), t("ai.keys.locked_text"), [
- el("div", { class: "ath-ai-pass" }, [pass, button(t("ai.keys.unlock"), "primary", unlock, "lock")])
- ]));
- box.appendChild(hint(t("ai.keys.forgot_hint")));
- box.appendChild(el("div", { class: "ath-ai-actions" }, [button(t("ai.keys.wipe"), "danger", async function () {
- if (await A.ui.confirm(t("ai.keys.wipe"), t("ai.keys.wipe_confirm"), t("ai.keys.wipe"), true)) ai.keys.wipe().catch(fail);
- }, "trash")]));
- return;
- }
- box.appendChild(status.mode === "passphrase"
- ? alertBox("success", t("ai.keys.pass_title"), t("ai.keys.pass_text"))
- : alertBox("warning", t("ai.keys.device_title"), t("ai.keys.device_text")));
- ai.PROVIDERS.forEach(function (p) { box.appendChild(keyRow(p, status)); });
- box.appendChild(hint(t("ai.keys.only_provider")));
- if (ai.relayUrl()) box.appendChild(alertBox("warning", null, t("ai.keys.via_relay")));
-
- box.appendChild(heading(t("ai.keys.pass_head")));
- if (status.mode === "passphrase") {
- box.appendChild(el("div", { class: "ath-ai-actions" }, [
- button(t("ai.keys.lock_now"), "secondary", function () { ai.keys.lock(); }, "lock"),
- button(t("ai.keys.pass_remove"), "ghost", async function () {
- if (await A.ui.confirm(t("ai.keys.pass_remove"), t("ai.keys.pass_remove_confirm"), t("ai.keys.pass_remove"), true)) {
- ai.keys.clearPassphrase().then(function () { A.ui.toast(t("ai.keys.pass_removed"), "success"); }).catch(fail);
- }
- })
- ]));
- box.appendChild(hint(t("ai.keys.pass_change")));
- box.appendChild(passwordPair(function (v) {
- return ai.keys.setPassphrase(v).then(function () { A.ui.toast(t("ai.keys.pass_set"), "success"); });
- }, t("ai.keys.pass_change_btn")));
- } else {
- box.appendChild(hint(t("ai.keys.pass_intro", { n: ai.PASSPHRASE_MIN })));
- box.appendChild(passwordPair(function (v) {
- return ai.keys.setPassphrase(v).then(function () { A.ui.toast(t("ai.keys.pass_set"), "success"); });
- }, t("ai.keys.pass_set_btn")));
- }
- }
- });
-
- aiUi.section({
- id: "model",
- order: 60,
- icon: "coins",
- label: "ai.sec.model",
- live: function (path) { return path === "budget.monthly"; },
- render: function (box) {
- box.appendChild(row(t("ai.model.mode"), bindSelect("mode", ai.MODES.map(function (m) {
- return [m, m === "auto" ? t("ai.model.mode_auto") : ai.providerLabel(m)];
- })), t("ai.model.mode_hint")));
- box.appendChild(row(t("ai.model.efficiency"), bindSelect("efficiency", ai.EFFICIENCY.map(function (e) {
- return [e, t("ai.eff." + e)];
- })), t("ai.model.efficiency_hint")));
- box.appendChild(row(t("ai.model.cheap"), bindSwitch("cheap"), t("ai.model.cheap_hint")));
-
- box.appendChild(heading(t("ai.budget.head")));
- liveBox = el("div", { class: "ath-ai-live" });
- box.appendChild(liveBox);
- renderLive(liveBox).catch(fail);
- box.appendChild(row(t("ai.budget.monthly"), bindNumber("budget.monthly", 0.5, "USD"), t("ai.budget.monthly_hint")));
- box.appendChild(row(t("ai.budget.per_request"), bindNumber("budget.perRequest", 0.01, "USD"), t("ai.budget.per_request_hint")));
- box.appendChild(row(t("ai.budget.iterations"), bindNumber("budget.iterations", 1), t("ai.budget.iterations_hint")));
- box.appendChild(row(t("ai.budget.auto_reload"), bindSwitch("budget.autoReload"), t("ai.budget.auto_reload_hint")));
-
- box.appendChild(heading(t("ai.models.head")));
- box.appendChild(hint(t("ai.models.intro")));
- box.appendChild(modelTable());
- box.appendChild(hint(t("ai.models.price_note")));
- box.appendChild(routerProbe());
- }
- });
-
- aiUi.section({
- id: "autocomplete",
- order: 70,
- icon: "type",
- label: "ai.sec.autocomplete",
- render: function (box) {
- box.appendChild(permRow("ghost"));
- box.appendChild(row(t("ai.ghost.provider"), bindSelect("ghost.provider", ai.PROVIDERS.map(function (p) { return [p, ai.providerLabel(p)]; }))));
- box.appendChild(row(t("ai.ghost.model"), bindText("ghost.model", { class: "orb-input orb-mono" }), t("ai.ghost.model_hint")));
- box.appendChild(row(t("ai.ghost.debounce"), bindRange("ghost.debounce", 25, function (v) { return t("ai.common.ms", { n: v }); }), t("ai.ghost.debounce_hint")));
- box.appendChild(row(t("ai.ghost.max_tokens"), bindNumber("ghost.maxTokens", 8), t("ai.ghost.max_tokens_hint")));
- box.appendChild(hint(t("ai.ghost.tab_hint")));
- }
- });
-
- aiUi.section({
- id: "network",
- order: 80,
- icon: "globe",
- label: "ai.sec.network",
- live: function (path) { return path === "search.mode" || path === "relay.on" || /^search\.engines\.[a-z0-9]+\.on$/.test(path); },
- render: async function (box) {
- box.appendChild(permRow("web"));
- box.appendChild(permRow("crawler"));
- box.appendChild(alertBox("info", null, t("ai.net.cors")));
- await ai.keys.status();
- box.appendChild(heading(t("ai.search.head")));
- box.appendChild(hint(t("ai.search.intro")));
- box.appendChild(row(t("ai.search.mode"), bindSelect("search.mode", [
- ["model", t("ai.search.mode_model")], ["api", t("ai.search.mode_api")], ["both", t("ai.search.mode_both")]
- ]), t("ai.search.mode_hint")));
- box.appendChild(row(t("ai.search.results"), bindNumber("search.results", 1), t("ai.search.results_hint")));
- box.appendChild(row(t("ai.search.news"), bindSwitch("search.news"), t("ai.search.news_hint")));
- box.appendChild(row(t("ai.search.safe"), bindSwitch("search.safe"), t("ai.search.safe_hint")));
- if (!ai.relayUrl()) {
- box.appendChild(alertBox("info", null, t("ai.relay.engines_note"), [
- el("div", { class: "ath-ai-actions" }, [button(t("ai.relay.setup"), "secondary", function () { show("relay"); }, "globe")])
- ]));
- }
- ai.search.ORDER.forEach(function (id) { box.appendChild(engineRow(id)); });
- box.appendChild(hint(t("ai.search.keys_note")));
- box.appendChild(alertBox("warning", null, t("ai.search.retired")));
- box.appendChild(heading(t("ai.net.allow")));
- box.appendChild(bindArea("network.allow", 4, 5000, true));
- box.appendChild(hint(t("ai.net.allow_hint")));
- box.appendChild(heading(t("ai.net.deny")));
- box.appendChild(bindArea("network.deny", 4, 5000, true));
- box.appendChild(hint(t("ai.net.deny_hint")));
- }
- });
-
- aiUi.section({
- id: "preview",
- order: 90,
- icon: "eye",
- label: "ai.sec.preview",
- render: function (box) {
- box.appendChild(permRow("preview"));
- box.appendChild(permRow("screenshot"));
- box.appendChild(row(t("ai.pv.approval"), bindSelect("preview.approval", [["ask", t("ai.approval.ask")], ["auto", t("ai.pv.auto")]]), t("ai.pv.approval_hint")));
- box.appendChild(row(t("ai.pv.auto_fix"), bindSwitch("preview.autoFix"), t("ai.pv.auto_fix_hint")));
- box.appendChild(row(t("ai.pv.max_fix"), bindNumber("preview.maxFix", 1), t("ai.pv.max_fix_hint")));
- box.appendChild(heading(t("ai.pv.viewports")));
- box.appendChild(row(t("ai.pv.mobile"), bindNumber("preview.mobile", 1, "px")));
- box.appendChild(row(t("ai.pv.tablet"), bindNumber("preview.tablet", 1, "px")));
- box.appendChild(row(t("ai.pv.desktop"), bindNumber("preview.desktop", 1, "px")));
- box.appendChild(row(t("ai.pv.shot_width"), bindNumber("preview.shotWidth", 16, "px"), t("ai.pv.shot_width_hint")));
- box.appendChild(alertBox("info", t("ai.pv.limits_title"), t("ai.pv.limits_text")));
- box.appendChild(heading(t("ai.pv.tools_head")));
- box.appendChild(hint(t("ai.pv.tools_hint")));
- box.appendChild(el("div", { class: "ath-ai-actions" }, [
- button(t("ai.viewer.pick"), "secondary", function () { A.commands.aiPick(); }, "target"),
- button(t("ai.viewer.audit"), "secondary", function () { Promise.resolve(A.commands.aiAudit()).catch(fail); }, "layout")
- ]));
- }
- });
-
- aiUi.section({
- id: "permissions",
- order: 100,
- icon: "shield",
- label: "ai.sec.permissions",
- live: function (path) { return path === "enabled"; },
- render: function (box) {
- box.appendChild(ai.enabled()
- ? alertBox("success", null, t("ai.perm.master_on"))
- : alertBox("info", null, t("ai.perm.master_off")));
- box.appendChild(row(t("ai.ov.master"), masterSwitch(), t("ai.ov.master_hint")));
- box.appendChild(heading(t("ai.perm.head")));
- ai.PERMS.forEach(function (p) { box.appendChild(permRow(p)); });
- box.appendChild(heading(t("ai.approval.head")));
- box.appendChild(row(t("ai.approval.mode"), bindSelect("approval", [["ask", t("ai.approval.ask")], ["auto", t("ai.approval.auto")]]), t("ai.approval.mode_hint")));
- box.appendChild(row(t("ai.approval.diff"), bindSwitch("diff"), t("ai.approval.diff_hint")));
- box.appendChild(row(t("ai.approval.snapshots"), bindSwitch("snapshots"), t("ai.approval.snapshots_hint")));
- box.appendChild(hint(t("ai.approval.always")));
- box.appendChild(heading(t("ai.priv.head")));
- box.appendChild(row(t("ai.priv.index"), bindSwitch("privateIndex"), t("ai.priv.index_hint")));
- }
- });
-
- aiUi.section({
- id: "exclusions",
- order: 110,
- icon: "ban",
- label: "ai.sec.exclusions",
- render: function (box) {
- box.appendChild(hint(t("ai.exc.intro")));
- box.appendChild(bindArea("exclusions", 12, 20000, true));
- box.appendChild(el("div", { class: "ath-ai-actions" }, [button(t("ai.exc.reset"), "ghost", function () {
- ai.set("exclusions", ai.DEFAULT_EXCLUSIONS);
- renderCurrent();
- }, "undo")]));
- var probe = el("input", { type: "text", class: "orb-input orb-mono", spellcheck: "false", autocomplete: "off", placeholder: t("ai.exc.test_ph") });
- var result = el("small", { class: "ath-ai-probe", "aria-live": "polite" });
- probe.addEventListener("input", function () {
- var p = probe.value.trim();
- result.textContent = !p ? "" : ai.isExcluded(p) ? t("ai.exc.test_yes") : t("ai.exc.test_no");
- result.classList.toggle("is-excluded", !!p && ai.isExcluded(p));
- });
- box.appendChild(row(t("ai.exc.test"), el("div", { class: "ath-ai-probe-box" }, [probe, result])));
- box.appendChild(hint(ai.t("ai.exc.redact_link")));
- }
- });
-
- aiUi.section({
- id: "relay",
- order: 85,
- icon: "globe",
- label: "ai.sec.relay",
- live: function (path) { return path === "relay.on" || path === "relay.hash"; },
- render: async function (box) {
- var R = ai.relay;
- box.appendChild(hint(ai.t("ai.relay.intro")));
- box.appendChild(el("ul", { class: "ath-ai-consent-list" }, [t("ai.relay.needs_search"), t("ai.relay.needs_pages"), ai.t("ai.relay.never_ai")].map(function (s) { return el("li", {}, s); })));
- if (ai.relayUrl()) box.appendChild(alertBox("success", null, t("ai.relay.active", { url: ai.relayUrl() })));
-
- box.appendChild(heading(t("ai.relay.step_key")));
- var hash = R.hash();
- var hasKey = false;
- try { hasKey = await R.hasKey(); } catch (e) { hasKey = false; }
- var ready = hasKey && !!hash;
- box.appendChild(row(t("ai.relay.key"), el("div", { class: "ath-ai-key-control" }, [
- button(ready ? t("ai.relay.new_key") : t("ai.relay.create_key"), ready ? "ghost" : "primary", async function () {
- if (ready && !(await A.ui.confirm(t("ai.relay.new_key"), t("ai.relay.new_key_confirm"), t("ai.relay.new_key"), true))) return;
- await R.newKey();
- A.ui.toast(t("ai.relay.key_created"), "success");
- renderCurrent();
- }, "key"),
- ready ? iconButton("copy", t("ai.relay.copy_hash"), function () {
- A.ui.copyText(hash).then(function () { A.ui.toast(t("ai.relay.hash_copied"), "success"); });
- }) : null
- ]), ready ? t("ai.relay.key_hint", { hash: hash.slice(0, 12) + "…" + hash.slice(-6) }) : t("ai.relay.key_none")));
-
- box.appendChild(heading(t("ai.relay.step_files")));
- box.appendChild(row(t("ai.relay.pages"), bindSwitch("relay.pages"), t("ai.relay.pages_hint")));
- box.appendChild(el("div", { class: "ath-ai-actions ath-ai-relay-files" }, [
- R.canSave() ? button(t("ai.relay.save_folder"), "primary", async function () {
- try {
- var r = await R.saveToFolder();
- A.ui.toast(t("ai.relay.saved", { folder: r.folder }), "success");
- if (r.htaccess !== ".htaccess") A.ui.toast(t("ai.relay.saved_htaccess_txt"), "warning");
- renderCurrent();
- } catch (e) {
- if (e && e.name !== "AbortError") fail(e);
- }
- }, "folder") : null,
- button(t("ai.relay.download_php"), "secondary", function () { R.download("php").catch(fail); }, "download"),
- button(t("ai.relay.download_htaccess"), "secondary", function () { R.download("htaccess").catch(fail); }, "download")
- ]));
- box.appendChild(hint(t("ai.relay.files_hint")));
- var cmd = "php -S 127.0.0.1:8787 relay.php";
- box.appendChild(el("div", { class: "ath-ai-relay-how" }, [
- el("div", {}, [
- el("h4", {}, t("ai.relay.how_host")),
- el("ol", {}, [t("ai.relay.host_1", { folder: R.FOLDER }), t("ai.relay.host_2"), t("ai.relay.host_3", { folder: R.FOLDER })].map(function (s) { return el("li", {}, s); })),
- el("p", { class: "ath-set-hint" }, t("ai.relay.host_req"))
- ]),
- el("div", {}, [
- el("h4", {}, t("ai.relay.how_local")),
- el("ol", {}, [
- el("li", {}, [t("ai.relay.local_1"), el("div", { class: "ath-ai-relay-cmd" }, [el("code", {}, cmd), iconButton("copy", t("ai.relay.copy_cmd"), function () {
- A.ui.copyText(cmd).then(function () { A.ui.toast(t("ai.chat.copied"), "success"); });
- })])]),
- el("li", {}, t("ai.relay.local_2"))
- ]),
- el("p", { class: "ath-set-hint" }, t("ai.relay.local_req"))
- ])
- ]));
-
- box.appendChild(heading(t("ai.relay.step_connect")));
- var urlInput = bindText("relay.url", { type: "url", placeholder: "https://twojastrona.pl/" + R.FOLDER + "/relay.php", class: "orb-input orb-mono" });
- urlInput.addEventListener("change", function () {
- if (ai.get("relay.on") && !ai.validRelay(urlInput.value)) {
- ai.set("relay.on", false);
- A.ui.toast(t("ai.ov.relay_invalid"), "warning");
- }
- });
- box.appendChild(row(t("ai.relay.url"), urlInput, t("ai.relay.url_hint")));
- var result = el("p", { class: "ath-ai-relay-result", "aria-live": "polite" });
- var testBtn = button(t("ai.relay.test"), "primary", async function () {
- ai.set("relay.url", urlInput.value);
- testBtn.disabled = true;
- result.className = "ath-ai-relay-result";
- result.textContent = t("ai.relay.testing");
- try {
- var r = await R.test(urlInput.value);
- result.classList.add("is-ok");
- result.textContent = t("ai.relay.test_ok", { php: r.php || "?", pages: r.pages ? t("ai.relay.pages_on") : t("ai.relay.pages_off") }) + (r.outdated ? " " + t("ai.relay.outdated") : "");
- if (!ai.get("relay.on")) {
- ai.set("relay.on", true);
- A.ui.toast(t("ai.relay.enabled"), "success");
- }
- } catch (e) {
- result.classList.add("is-error");
- result.textContent = e.message;
- } finally {
- testBtn.disabled = false;
- }
- }, "check");
- box.appendChild(row(t("ai.relay.check"), el("div", { class: "ath-ai-probe-box" }, [testBtn, result])));
- box.appendChild(row(t("ai.relay.use"), bindSwitch("relay.on", function (v, input) {
- if (v && !ai.validRelay(ai.get("relay.url"))) {
- input.checked = false;
- return A.ui.toast(t("ai.ov.relay_invalid"), "warning");
- }
- ai.set("relay.on", v);
- }), t("ai.relay.use_hint")));
- }
- });
-
- aiUi.section({
- id: "privacy",
- order: 105,
- icon: "shield",
- label: "ai.sec.privacy",
- render: function (box) {
- var R = ai.redact;
- box.appendChild(hint(ai.t("ai.redact.intro")));
- box.appendChild(row(t("ai.redact.on"), bindSwitch("redact.on", function (on) {
- ai.set("redact.on", on);
- renderCurrent();
- }), ai.t("ai.redact.on_hint")));
- if (!ai.get("redact.on")) box.appendChild(alertBox("warning", null, ai.t("ai.redact.off_warning")));
- box.appendChild(row(t("ai.redact.secrets"), bindSwitch("redact.secrets"), t("ai.redact.secrets_hint")));
- box.appendChild(row(t("ai.redact.personal"), bindSwitch("redact.personal"), t("ai.redact.personal_hint")));
- box.appendChild(hint(ai.t("ai.redact.images")));
-
- box.appendChild(heading(t("ai.redact.session_head")));
- var items = R.session();
- if (!items.length) box.appendChild(hint(t("ai.redact.session_empty")));
- else {
- box.appendChild(el("ul", { class: "ath-ai-redact-list" }, items.map(function (it) {
- return el("li", {}, [
- el("span", { class: "ath-ai-secret" }, "«" + it.id + (it.label ? ": " + it.label : "") + "»"),
- el("code", {}, it.sample),
- el("small", {}, it.where.join(", ")),
- button(t("ai.redact.not_secret"), "ghost", function () {
- R.allow(it.id);
- A.ui.toast(t("ai.redact.allowed", { id: it.id }), "success");
- renderCurrent();
- })
- ]);
- })));
- }
- var allowed = R.allowedCount();
- box.appendChild(row(t("ai.redact.exceptions"), allowed ? button(t("ai.redact.clear_exceptions"), "ghost", function () {
- R.clearAllowed();
- renderCurrent();
- }, "undo") : el("span", { class: "orb-text-muted" }, t("ai.redact.no_exceptions")), t("ai.redact.exceptions_hint", { n: allowed })));
-
- box.appendChild(heading(t("ai.redact.test_head")));
- var file = el("input", { type: "text", class: "orb-input orb-mono", spellcheck: "false", autocomplete: "off", placeholder: t("ai.redact.test_file_ph") });
- var area = el("textarea", { class: "orb-textarea orb-mono ath-ai-area", rows: 6, spellcheck: "false", placeholder: t("ai.redact.test_ph") });
- var out = el("div", { class: "ath-ai-redact-out", "aria-live": "polite" });
- var run = util.debounce(function () {
- out.textContent = "";
- if (!area.value.trim()) return;
- var r = R.test(area.value, file.value.trim());
- out.appendChild(el("p", { class: "ath-ai-redact-sum" }, r.found.length ? t("ai.redact.test_found", { list: R.summary(r.found) }) : t("ai.redact.test_none")));
- out.appendChild(el("pre", {}, r.parts.map(function (p) {
- return p.kind ? el("mark", { class: "ath-ai-redact-hit", title: t("ai.redact.kind_" + p.kind) + (p.label ? ": " + p.label : "") }, p.text) : document.createTextNode(p.text);
- })));
- }, 200);
- area.addEventListener("input", run);
- file.addEventListener("input", run);
- box.appendChild(row(t("ai.redact.test_file"), file));
- box.appendChild(area);
- box.appendChild(out);
- }
- });
- })();
-