diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index d1bb805a0..22d4b6952 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -7125,7 +7125,7 @@ function renderAdd() { if (!adding) return editing && typeof editing === "object" ? renderEditor(null, editing.preset) : null; const head = el("div", "row-head"); head.append(el("span", "label", t(providers.providers.length ? "Add a provider" : "Add your first provider")), el("span", "grow")); - const q = input(presetQuery, t("Find a vendor…")); + const q = input(presetQuery, t("Find a vendor, or paste a URL and key…")); q.className = "find"; // Escape empties the search, then closes the sheet; it never hides the tray q.onkeydown = (e) => { @@ -7148,11 +7148,7 @@ function renderAdd() { editing = { custom: true }; draft = d; presetQuery = ""; renderProviders(); // the site's own icon, when it has one; the draft may be gone by then - api("icons/favicon", { url: c.base, name }).then((r) => { - if (draft !== d || !r?.icon) return; - d.icon = r.icon; - renderProviders(true); - }).catch(() => {}); + api("icons/favicon", { url: c.base, name }).then((r) => draft === d && r?.icon && (d.icon = r.icon, renderProviders(true))).catch(() => {}); }; const c = el("button", "text custom" + (editing?.custom ? " on" : "")); c.append(svg(PLUS, 11, 1.8), t("Custom provider")); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 89ca16f35..e1f56ff82 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1974,7 +1974,7 @@ const I18N = { "+ Add provider": "+ 添加供应商", "Add a provider": "添加供应商", "Add your first provider": "添加第一个供应商", - "Find a vendor…": "查找供应商…", + "Find a vendor, or paste a URL and key…": "查找供应商,或粘贴地址和密钥…", "Find a model…": "查找模型…", "Words match a model's id, name, provider or a group's models": "按模型 ID、名称、供应商或模型组里的模型查找", "Reasoning: {levels}": "推理强度:{levels}", @@ -7168,7 +7168,7 @@ const I18N = { "+ Add provider": "+ 新增供應商", "Add a provider": "新增供應商", "Add your first provider": "新增第一個供應商", - "Find a vendor…": "查詢供應商…", + "Find a vendor, or paste a URL and key…": "查詢供應商,或貼上位址和金鑰…", "Find a model…": "查詢模型…", "Words match a model's id, name, provider or a group's models": "按模型 ID、名稱、供應商或模型組裡的模型查詢", "Reasoning: {levels}": "推理強度:{levels}", @@ -12336,7 +12336,7 @@ const I18N = { "+ Add provider": "+ プロバイダを追加", "Add a provider": "プロバイダを追加", "Add your first provider": "最初のプロバイダを追加", - "Find a vendor…": "ベンダーを検索…", + "Find a vendor, or paste a URL and key…": "ベンダーを検索、または URL とキーを貼り付け…", "Find a model…": "モデルを検索…", "Words match a model's id, name, provider or a group's models": "モデルの ID、名前、プロバイダ、またはグループのモデルに一致する語で検索します", "Reasoning: {levels}": "推論:{levels}", @@ -17535,7 +17535,7 @@ const I18N = { "+ Add provider": "+ Anbieter hinzufügen", "Add a provider": "Anbieter hinzufügen", "Add your first provider": "Ersten Anbieter hinzufügen", - "Find a vendor…": "Anbieter suchen…", + "Find a vendor, or paste a URL and key…": "Anbieter suchen oder URL und Schlüssel einfügen…", "Find a model…": "Modell suchen…", "Words match a model's id, name, provider or a group's models": "Suchbegriffe passen auf ID, Name oder Anbieter eines Modells oder auf die Modelle einer Gruppe", "Reasoning: {levels}": "Reasoning: {levels}", diff --git a/internal/gui/assets/pasteread.js b/internal/gui/assets/pasteread.js index b5d4a8ca6..347e88940 100644 --- a/internal/gui/assets/pasteread.js +++ b/internal/gui/assets/pasteread.js @@ -104,26 +104,42 @@ window.envOf = function envOf(text) { put(m[1], q ? q[2] : m[2].replace(/\s+#.*$/, "")); } } - const base = /^(ANTHROPIC|OPENAI|GEMINI|GOOGLE_GEMINI)_(?:BASE_URL|API_BASE|API_URL|BASE|ENDPOINT)$/i; - const keyOf = /^(ANTHROPIC|OPENAI|GEMINI|GOOGLE)_(?:AUTH_TOKEN|API_KEY)$/i; - const modelOf = /^(ANTHROPIC|OPENAI|GEMINI)_MODEL$/i; - const apiOf = (name) => /^ANTHROPIC/i.test(name) ? "anthropic" : /^OPENAI/i.test(name) ? "openai" : "gemini"; + // a vendor's own names say no API (DEEPSEEK_BASE_URL, MY_RELAY_API_KEY, + // a bare BASE_URL): the URL says it, else it is OpenAI's chat + const base = /^(?:(\w+?)_)?(?:BASE_URL|API_BASE|API_URL|API_BASE_URL|BASE|ENDPOINT|URL|HOST|API_HOST)$/i; + const keyOf = /^(?:(\w+?)_)?(?:AUTH_TOKEN|API_KEY|API_TOKEN|ACCESS_TOKEN|KEY|TOKEN|SECRET_KEY|APIKEY)$/i; + const modelOf = /^(?:(\w+?)_)?MODEL$/i; + const named = /^(ANTHROPIC|CLAUDE|OPENAI|GEMINI|GOOGLE_GEMINI|GOOGLE)$/i; + const apiOf = (prefix, u) => /^(ANTHROPIC|CLAUDE)$/i.test(prefix) ? "anthropic" : /^OPENAI$/i.test(prefix) ? "openai" : /^(GEMINI|GOOGLE_GEMINI|GOOGLE)$/i.test(prefix) ? "gemini" : urlAPI(u); const out = { url: "", api: "", base: "", bases: [], urlHole: "", key: "", placeholder: "", model: "", name: "" }; - for (const [k, v] of Object.entries(vars)) { - if (base.test(k)) { - const api = apiOf(k); + // the names that say their API first, so OPENAI_BASE_URL wins over a URL + const prefix = (k) => (base.exec(k) || keyOf.exec(k) || [])[1] || ""; + const order = Object.entries(vars).sort(([a], [b]) => named.test(prefix(b)) - named.test(prefix(a))); + let seen = 0; + for (const [k, v] of order) { + let m; + if ((m = base.exec(k)) && !/PROXY$/i.test(k)) { + const known = named.test(m[1] || ""); + // a vendor's own name is read only for a web address: DATABASE_URL isn't one + if (!known && !/^https?:\/\//i.test(v)) continue; + seen++; // a host written without its scheme is https const u = /^[a-z][a-z0-9+.-]*:\/\//i.test(v) ? v : /^[^\s/]+\.[^\s/]+|^localhost\b/i.test(v) ? "https://" + v : ""; + const api = apiOf(m[1] || "", u); if (!u || out.bases.some(([a]) => a === api)) continue; // …/v1/chat/completions given whole is cut back to the base const cut = u.replace(/\/+$/, "").replace(/\/(?:chat\/completions|messages|responses)$/i, ""); out.bases.push([api, respellURL(cut, api)]); - } else if (keyOf.test(k)) { + } else if ((m = keyOf.exec(k)) && !/^(GITHUB|GH|NPM|AWS|HF|HUGGINGFACE|SLACK|DISCORD)$/i.test(m[1] || "")) { + seen++; if (out.key || out.placeholder) continue; - if (/^\$|^%\w+%$|^<.*>$|^\{\{.*\}\}$|^\[.*\]$|your[_-]?|api[_-]?key|x{6,}|\.\.\.|…/i.test(v)) out.placeholder = v; + if (standIn(v)) out.placeholder = v; else out.key = v; } else if (modelOf.test(k) && !out.model) out.model = v; } + // no URL in the names: the lines may still give one plainly + if (!out.bases.length) { const p = plainOf(body); if (p) return p; } + if (!seen) return null; if (!out.bases.length && !out.key && !out.placeholder) return null; if (out.bases.length) { [out.api, out.base] = out.bases[0]; @@ -134,6 +150,42 @@ window.envOf = function envOf(text) { return out; }; +// standIn: a key a page gives only to stand for the reader's own +const standIn = (v) => /^\$|^%\w+%$|^<.*>$|^\{\{.*\}\}$|^\[.*\]$|your[_-]?|api[_-]?key|x{6,}|\.\.\.|…/i.test(v); + +// urlAPI: the API a base URL with nothing else to say it serves — +// Anthropic's for a path naming it (…/anthropic, /claude), else OpenAI's chat +const urlAPI = (u) => /\/(anthropic|claude)(\/|$)/i.test(String(u).replace(/^\w+:\/\/[^/]+/, "")) ? "anthropic" : "openai"; + +// plainOf reads a base URL and a key given as plain lines, as a relay's +// page or a chat hands them over: "Base URL: https://…" over "Key: sk-…", +// or the two on one line. Both are needed, or it is no setup: a URL alone +// is a search, a key alone is a key. It gives what envOf does. +function plainOf(text) { + const s = String(text || ""); + if (s.length > 4000 || /^\s*curl\b/i.test(s)) return null; + const um = /https?:\/\/[^\s"'<>,。;、]+/i.exec(s); + if (!um) return null; + const u = um[0].replace(/[),.;:]+$/, ""); + const rest = s.slice(0, um.index) + " " + s.slice(um.index + um[0].length); + // a labelled key first (key, token, 密钥, 令牌), then a word that looks like one + const labelled = /(?:key|token|secret|密钥|令牌|秘钥)\s*[::=]?\s*["'`]?([A-Za-z0-9][\w.\-~+/=]{11,})/i.exec(rest); + let key = labelled?.[1] || ""; + if (!key) { + for (const w of rest.split(/[\s"'`,,;;|]+/)) { + const x = w.replace(/^[^\w]+|[^\w=]+$/g, ""); + if (/^(sk|ak|pk|rk|cr|ms|tp|fk|key)[-_]/i.test(x) && x.length >= 12 || /^[A-Za-z0-9][\w.\-]{31,}$/.test(x) && /\d/.test(x) && /[a-z]/i.test(x)) { key = x; break; } + } + } + if (!key) return null; + const cut = u.replace(/\/+$/, "").replace(/\/(?:chat\/completions|messages|responses)$/i, ""); + const api = urlAPI(cut); + const base = respellURL(cut, api); + const out = { url: base, api, base, bases: [[api, base]], urlHole: "", key: "", placeholder: "", model: "", name: siteName(base) }; + if (standIn(key)) out.placeholder = key; else out.key = key; + return out; +} + // siteName is what to call the provider at a URL: the name in its host, // api.moonshot.cn → Moonshot, open.bigmodel.cn → Bigmodel; an address // stays as it is. diff --git a/internal/gui/tests/provider-env-paste.test.cjs b/internal/gui/tests/provider-env-paste.test.cjs index 3e9bcbc21..9bb0a2c51 100644 --- a/internal/gui/tests/provider-env-paste.test.cjs +++ b/internal/gui/tests/provider-env-paste.test.cjs @@ -45,8 +45,8 @@ function serve(lang, posts) { } const words = { - en: { add: "Add", note: "Filled in from the pasted text: Base URL (Anthropic compatible) · API key." }, - zh: { add: "添加", note: "已从粘贴的文本填入:API 地址 (Anthropic 兼容) · API 密钥。" }, + en: { add: "Add", find: "Find a vendor, or paste a URL and key…", note: "Filled in from the pasted text: Base URL (Anthropic compatible) · API key." }, + zh: { add: "添加", find: "查找供应商,或粘贴地址和密钥…", note: "已从粘贴的文本填入:API 地址 (Anthropic 兼容) · API 密钥。" }, }; const launch = (engine) => engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }); @@ -78,6 +78,26 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", for (const s of ["", "sk-a\nsk-b", "https://api.moonshot.cn/v1", "PATH=/usr/bin\nHOME=/root", "export FOO=bar"]) { assert.equal(await page.evaluate((x) => envOf(x), s), null, JSON.stringify(s)); } + // a vendor's own names, a bare BASE_URL, JSON's snake_case and plain + // lines (WJaunita45604's XXX_BASE_URL): the URL says the API + const more = { + [`export XXX_BASE_URL="https://relay.foo.com/anthropic"\nexport XXX_AUTH_TOKEN="${own}"`]: ["anthropic", "https://relay.foo.com/anthropic", "Foo"], + [`export DEEPSEEK_BASE_URL=https://api.deepseek.com\nexport DEEPSEEK_API_KEY=${own}`]: ["openai", "https://api.deepseek.com/v1", "Deepseek"], + [`BASE_URL=https://api.relay.io/v1\nAPI_KEY=${own}`]: ["openai", "https://api.relay.io/v1", "Relay"], + [JSON.stringify({ base_url: "https://api.relay.io/v1", api_key: own })]: ["openai", "https://api.relay.io/v1", "Relay"], + [`Base URL: https://api.relay.io/v1\nAPI Key: ${own}`]: ["openai", "https://api.relay.io/v1", "Relay"], + [`地址:https://api.relay.cn/v1/chat/completions\n密钥:${own}`]: ["openai", "https://api.relay.cn/v1", "Relay"], + [`https://api.relay.io/claude ${own}`]: ["anthropic", "https://api.relay.io/claude", "Relay"], + }; + for (const [text, [api, base, name]] of Object.entries(more)) { + const c = await page.evaluate((s) => envOf(s), text); + assert.deepEqual([c?.api, c?.base, c?.key, c?.name], [api, base, own, name], text); + } + // a URL whose name says no API is read only as a web address; another + // service's token is no provider's key + for (const s of ["DATABASE_URL=postgres://db/x\nGITHUB_TOKEN=ghp_0123456789abcdef", "HTTPS_PROXY=http://127.0.0.1:7890", "see https://example.com for docs"]) { + assert.equal(await page.evaluate((x) => envOf(x), s), null, JSON.stringify(s)); + } assert.deepEqual(await page.evaluate(() => ["https://open.bigmodel.cn/api/paas/v4", "https://api.example.co.uk/v1", "http://127.0.0.1:8888/v1"].map(siteName)), ["Bigmodel", "Example", "127.0.0.1"]); }); @@ -105,6 +125,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.goto("http://magpie.test/?view=providers"); await page.locator("#addProvider").click(); + // the box says it takes a pasted URL and key + assert.equal(await page.locator("#addSheet .find").getAttribute("placeholder"), w.find); // text that isn't env lines is typed as before assert.equal(await paste(page.locator("#addSheet .find"), "moonshot"), false); assert.equal(await paste(page.locator("#addSheet .find"), forms.export), true);