Files
Coldsmile_7 c340aec110
CI / test (push) Canceled after 0s
release: dsh-infstarapi 0.2.0
2026-11-26 08:24:56 +08:00

2283 lines
101 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
window.__ModuleLoader__.load({
id: "dsh-infstarapi",
factory: (require) => {
var module = { exports: {} };
var exports = module.exports;
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
let react = require("react");
react = __toESM(react, 1);
let react_jsx_runtime = require("react/jsx-runtime");
//#region src/client-copy.js
/**
* The settings panel's copy, in both languages DSH ships.
*
* @module dsh-geek2api/client-copy
*/
const zh = {
nav: "InfStarAPI",
intro: "填入 InfStarAPI 的 API Key 即可使用内置模型路由。多个 Key 按顺序使用:余额用尽或失效时自动切到下一个;某个 Key 的分组用不了所选模型时,自动改用能用的 Key。多个接口地址可配置,故障时自动切换。",
accountsTitle: "账户与 Key",
refresh: "刷新",
refreshing: "刷新中…",
totalRemaining: "合计剩余",
totalUsed: "合计已用",
totalLimit: "合计额度",
totalPartial: "有 {count} 个 Key 未读到余额,未计入合计。",
totalStale: "其中 {count} 个 Key 本次读取失败,显示的是上次读到的余额。",
totalShared: "{count} 个 Key 与其他 Key 共用同一个钱包或订阅,只计一次。",
totalCapped: "{count} 个 Key 设有自己的限额,它们花的是账户钱包,限额不计入合计。",
staleNote: "上次读取于 {time},本次读取失败:{error}",
empty: "还没有 Key。添加一个即可在模型选择器里看到 InfStarAPI 的模型。",
keysHint: "按顺序使用:当前 Key 不可用时自动切到下一个;「切到此 Key」指定优先使用的 Key。",
keyActive: "使用中",
keyDisabled: "已停用",
keySkipped: "余额不足,暂时跳过",
keyUse: "切到此 Key",
keyEnable: "重新启用",
keyRemove: "删除",
keyRename: "重命名",
keyRenameSave: "保存",
keyRenameCancel: "取消",
keyRenamePlaceholder: "新的备注名",
keyUnlimited: "不限额度",
keyNoBalance: "余额未知",
keyRemaining: "剩余",
keyUsed: "已用",
accountLimit: "额度",
keyName: "Key 名称",
keyNameUnknown: "",
keyToday: "今日",
planWallet: "钱包余额(同账户的 Key 共用)",
planSubscription: "订阅:{name}",
planQuota: "Key 限额(从账户钱包扣费)",
planSubscriptionInactive: "订阅:{name}(未开通或已过期)",
keyCapRemaining: "Key 剩余限额",
keyWindow: "{window} 窗口 {used}/{limit}",
keyExpires: "{date} 到期",
resetMonthly: "每月重置",
resetWeekly: "每周重置",
resetDaily: "每日重置",
loadFailed: "读取失败",
removeAll: "清空全部",
addTitle: "添加 Key",
addKeyPlaceholder: "粘贴 API Key",
addLabelPlaceholder: "备注(可选)",
add: "添加",
notWritable: "当前 profile 不允许写入设置,这些选项暂时不能修改。",
error: "读取 InfStarAPI 状态失败",
groupsTitle: "分组",
groupsExtra: "另有 {count} 个模型不在内置列表中",
groupsChecking: "正在读取分组…",
groupsUnknown: "分组未读到",
groupsRejected: "Key 被网关拒绝",
groupsReach: "可用",
groupsMiss: "不可用",
groupsPartial: "部分",
groupsStale: "分组为上次读取的结果",
contextCap: "该分组单次上下文上限 {tokens},会提前自动压缩",
keyExpiresAt: "{when} 到期",
keyExpired: "已到期",
dailyKeyExpiresIn: "免费日卡 · {when} 到期(还剩 {hours} 小时 {minutes} 分)",
dailyKeyRenewOpen: "免费日卡 · {when} 到期,现在就能领下一把,两把同时有效不中断",
dailyKeyExpired: "免费日卡已到期,领一把新的粘贴到这里",
dailyKeyClaim: "去领取 →",
modelsTitle: "显示的模型",
modelsIntro: "切换模型时只显示已勾选的 InfStarAPI 模型,默认全选。修改后立即生效;已有会话仍可继续使用原模型。",
modelsChecking: "正在读取模型设置…",
modelsFailed: "模型设置读取或保存失败",
modelsAll: "全选",
modelsNone: "全不选",
modelsCount: "已选 {count} / {total}",
modelsEmpty: "未勾选任何模型,切换列表将隐藏 InfStarAPI 的模型。",
customTitle: "自定义模型({count})",
customIntro: "内置列表里没有的模型,可以按模型 ID 自己添加:填 InfStarAPI 上的模型名,选它走的协议。添加后立即出现在模型选择器里,和内置模型一样使用多 Key 轮换和多入口切换。能不能用取决于 Key 所在分组,以「账户与 Key」里「自定义」一栏的 ✓ / ✕ 为准。",
customChip: "自定义",
customFamily: "自定义",
customAddTitle: "添加模型",
customIdPlaceholder: "模型 ID,例如 qwen3-max",
customNamePlaceholder: "显示名称(可选)",
customProtocol: "协议",
customProtocolHint: "Claude 系选 Messages;GPT、Grok 选 Responses;其他大多数模型选 Chat Completions。",
protocolCompletions: "Chat Completions",
protocolResponses: "Responses",
protocolMessages: "Messages",
customCapabilities: "能力",
customReasoning: "推理",
customImage: "可带图",
customLimits: "上下文 / 输出",
customContextPlaceholder: "上下文窗口,默认 128000",
customOutputPlaceholder: "最大输出,默认 32000",
customWindow: "上下文 {context} · 输出 {output}",
customReasoningHint: "勾选「推理」后提供 off / low / medium / high 档位;不勾选则不发送推理参数。",
customAdd: "添加",
customRemove: "删除",
customFull: "最多添加 {count} 个自定义模型。",
hostsTitle: "接口地址",
hostsIntro: "所有请求按测速结果选用最快的地址;某个地址连不上会暂时跳过,自动改用下一个。",
hostsProbe: "重新测速",
hostsProbing: "测速中…",
hostsCurrent: "当前",
hostsDown: "不可达",
hostsCooling: "暂时跳过",
hostsUnprobed: "未测速",
hostsEdit: "编辑地址列表",
hostsEditHint: "每行一个地址(只取域名部分,必须是 https),按优先顺序排列。要恢复内置列表请点「恢复默认」。",
hostsSave: "保存",
hostsReset: "恢复默认",
composerLabel: "InfStarAPI 剩余额度",
composerNoKey: "无可用 Key",
composerUnread: "余额读取失败",
composerStale: "上次读取于 {time},本次读取失败",
cliTitle: "Claude Code CLI",
cliChecking: "正在检测本机的 Claude Code CLI…",
cliInstalled: "已安装",
cliVersion: "版本",
cliPath: "位置",
cliRecheck: "重新检测",
cliMissing: "未检测到 Claude Code CLI",
cliMissingHint: "只有把「Claude 运行方式」设为「本机 Claude Code CLI」,或使用 claude_code 委派工具时才需要安装。默认的 HTTP 方式不需要 CLI。",
claudeRuntimeTitle: "Claude 运行方式",
claudeRuntimeHttp: "HTTP 直连(推荐)",
claudeRuntimeHttpHint: "Claude 模型直接调用 InfStarAPI 的 Messages 接口,使用 DSH 自己的工具、权限和计划模式。",
claudeRuntimeCli: "本机 Claude Code CLI",
claudeRuntimeCliHint: "由本机官方 Claude Code CLI 执行,使用 CLI 自己的工具;适合 Key 所在分组只允许官方 CLI 的情况。",
cliConfiguredMissing: "设置里指定的 CLI 路径不存在:{path}",
cliBroken: "找到了 CLI,但无法运行",
cliInstall: "安装 Claude Code CLI",
cliReinstall: "重新安装",
cliInstalling: "正在安装…(通常需要一两分钟,请勿关闭 DSH)",
cliInstallCommand: "将在本机执行:{command}(需要 Node.js 18 或更高版本)",
cliInstallSucceeded: "安装完成。",
cliInstallFailed: "安装失败",
cliNpmMissing: "没有找到 npm。请先从 https://nodejs.org 安装 Node.js(18 或更高版本),然后再点安装。",
cliPermission: "npm 没有权限写入全局目录。请在终端执行 sudo {command},或把 npm 的全局目录改到用户目录后重试。",
cliPermissionWindows: "npm 没有权限写入全局目录。请以管理员身份打开终端执行 {command},然后点「重新检测」。",
cliNetwork: "下载失败,请检查网络或 npm 镜像设置后重试。",
cliTimeout: "安装超时,请检查网络后重试。",
cliNotFoundAfterInstall: "npm 显示安装完成,但仍找不到 claude 命令。请在终端执行 claude --version 确认,然后点「重新检测」。",
cliWindowsNote: "Windows 上 Claude Code 还需要 Git for Windows(https://git-scm.com/downloads/win)。",
versionTitle: "插件版本",
versionCurrent: "当前版本",
versionLatest: "最新版本",
versionCheck: "检查更新",
versionChecking: "正在检查更新…",
versionFailed: "无法检查最新版本。",
versionUpToDate: "已是最新版本",
versionAvailable: "发现新版本 v{version}",
versionLinked: "当前是本地开发安装,请在插件仓库拉取代码并重新构建。",
versionManual: "无法在这里自动更新。请到 GitHub Releases 下载新版本,在桌面应用的插件页重新安装。",
versionNotes: "更新说明",
versionUpdate: "更新插件",
versionUpdating: "正在更新…",
versionUpdateFailed: "更新失败,请重试,或在插件页重新安装。",
versionUpdated: "已更新到 v{version}。",
versionUpdatedHint: "新版本需要完全退出并重新打开桌面应用才会生效;只刷新页面不会重载 Host 里的插件。",
versionRestart: "如何重启",
versionRestartHint: "插件无法安全地重启桌面应用。请完全退出 DSH,再重新打开。",
versionRefresh: "刷新界面",
versionLater: "稍后",
searchTitle: "网页搜索",
searchScope: "DSH 全局设置",
searchIntro: "DSH 的 web_search 和 Claude CLI 的 MCP 搜索可使用这里选择的 Claude/GPT 后端。每次搜索是独立的模型调用,用插件保存的 Key 计费。",
searchCliHint: "Claude CLI 始终通过 MCP 使用这里的搜索后端,原生 WebSearch 已禁用。下面的路由选项只控制 DSH 全局搜索,不影响 CLI。",
searchChecking: "正在读取搜索设置…",
searchLoadFailed: "搜索设置读取或保存失败",
searchModeTitle: "DSH 路由",
searchModeDefault: "不接管",
searchModeDefaultHint: "不改动 DSH 的搜索路由(默认)。切回此项会移除本插件写入 profile 的搜索补丁。",
searchModeAuto: "按模型",
searchModeAutoHint: "InfStarAPI 模型用 InfStarAPI 搜索;其他模型仍走原来的搜索(DSH 默认搜索,或其他插件的设置)。",
searchModeInfstarapi: "始终 InfStarAPI",
searchModeInfstarapiHint: "原本由 DSH 默认搜索处理的请求都改走 InfStarAPI。Codex、Kimi 等订阅插件接管的模型仍按它们自己的设置。",
searchBackendTitle: "搜索后端",
searchBackendClaude: "Claude",
searchBackendClaudeHint: "{model}:每次搜索约 1 万输入 token,结果带出处;需要有能用 Claude 的 Key。",
searchBackendGpt: "GPT",
searchBackendGptHint: "{model}:结果通常更新、更准,但每次搜索约 2–3 万输入 token;需要有能用 GPT 的 Key。",
searchEffective: "当前生效:基础搜索 {base} · 运行时 {runtime}",
searchPatchNote: "「按模型」和「始终」会在本 profile 的 cordis.patch.yml 里写入一段带标记的 web 配置,热加载生效,无需重启。卸载插件前请先切回「不接管」。",
searchApplyFailed: "写入搜索补丁失败:{error}",
searchForeign: "检测到 {names} 订阅插件:它们接管的模型仍按各自的搜索设置,其余请求才会到达这里的选择。",
searchOverridden: "基础搜索现在是 {base},不是 InfStarAPI:可能还在热加载,或被其他插件的补丁覆盖。",
searchUnavailable: "当前运行环境没有 DSH 网页搜索服务,全局路由暂不生效;Claude CLI 的 MCP 搜索不受影响。",
searchNotWritable: "当前 profile 不允许写入设置。",
searchUnknown: "未知"
};
const en = {
nav: "InfStarAPI",
modelsTitle: "Visible models",
modelsIntro: "Only selected InfStarAPI models appear when switching models. All are selected by default. Changes apply immediately; existing sessions can keep their current model.",
modelsChecking: "Reading model settings…",
modelsFailed: "Could not read or save model settings",
modelsAll: "Select all",
modelsNone: "Select none",
modelsCount: "{count} / {total} selected",
modelsEmpty: "No models selected. InfStarAPI models are hidden from the picker.",
customTitle: "Custom models ({count})",
customIntro: "Add a model the built-in list lacks by its id: the model name on InfStarAPI, and the protocol it is served over. It appears in the model picker at once and uses the same key rotation and endpoint failover as the built-in models. Whether a key can use it depends on the key’s groups; see the ✓ / ✕ under “Custom” in Accounts and keys.",
customChip: "Custom",
customFamily: "Custom",
customAddTitle: "Add a model",
customIdPlaceholder: "Model id, e.g. qwen3-max",
customNamePlaceholder: "Display name (optional)",
customProtocol: "Protocol",
customProtocolHint: "Claude models: Messages. GPT and Grok: Responses. Most other models: Chat Completions.",
protocolCompletions: "Chat Completions",
protocolResponses: "Responses",
protocolMessages: "Messages",
customCapabilities: "Capabilities",
customReasoning: "Reasoning",
customImage: "Images",
customLimits: "Context / output",
customContextPlaceholder: "Context window, default 128000",
customOutputPlaceholder: "Max output, default 32000",
customWindow: "context {context} · output {output}",
customReasoningHint: "With Reasoning, the off / low / medium / high efforts are offered; without it, no reasoning parameter is sent.",
customAdd: "Add",
customRemove: "Remove",
customFull: "At most {count} custom models.",
intro: "Paste an InfStarAPI API key to use the built-in model route. Keys are used in order: an exhausted or rejected key hands over to the next one, and a key that cannot reach the selected model is passed over for one that can. Several endpoints are measured and fail over automatically.",
accountsTitle: "Accounts and keys",
refresh: "Refresh",
refreshing: "Refreshing…",
totalRemaining: "Total remaining",
totalUsed: "Total used",
totalLimit: "Total limit",
totalPartial: "{count} key(s) could not be read and are not counted here.",
totalStale: "{count} of these keys failed this read and show their last read balance.",
totalShared: "{count} key(s) share a wallet or subscription with another key and are counted once.",
totalCapped: "{count} key(s) have their own cap; they spend the account wallet, so caps are not added to the total.",
staleNote: "Last read at {time}; this read failed: {error}",
empty: "No keys yet. Add one and the InfStarAPI models appear in the model picker.",
keysHint: "Used in order: when the active key cannot serve a request, the next one takes over. “Use this key” picks the preferred key.",
keyActive: "Active",
keyDisabled: "Disabled",
keySkipped: "Out of balance, skipped for now",
keyUse: "Use this key",
keyEnable: "Re-enable",
keyRemove: "Remove",
keyRename: "Rename",
keyRenameSave: "Save",
keyRenameCancel: "Cancel",
keyRenamePlaceholder: "New name",
keyUnlimited: "No quota limit",
keyNoBalance: "Balance unknown",
keyRemaining: "Remaining",
keyUsed: "Used",
accountLimit: "Limit",
keyName: "Key name",
keyNameUnknown: "",
keyToday: "Today",
planWallet: "Wallet (shared by the account’s keys)",
planSubscription: "Subscription: {name}",
planQuota: "Key quota (spends the account wallet)",
planSubscriptionInactive: "Subscription: {name} (not active)",
keyCapRemaining: "Cap left",
keyWindow: "{window} window {used}/{limit}",
keyExpires: "expires {date}",
resetMonthly: "resets monthly",
resetWeekly: "resets weekly",
resetDaily: "resets daily",
loadFailed: "Read failed",
removeAll: "Remove all",
addTitle: "Add a key",
addKeyPlaceholder: "Paste API key",
addLabelPlaceholder: "Label (optional)",
add: "Add",
notWritable: "This profile does not allow settings writes; these options cannot be changed here.",
error: "Could not read InfStarAPI status",
groupsTitle: "Groups",
groupsExtra: "{count} more model(s) outside the built-in list",
groupsChecking: "Reading groups…",
groupsUnknown: "Groups not read",
groupsRejected: "Key rejected by the gateway",
groupsReach: "Reaches",
groupsMiss: "Not",
groupsPartial: "partly",
groupsStale: "groups from the last read",
contextCap: "This group caps the context at {tokens} per request; sessions compact early",
keyExpiresAt: "Expires {when}",
keyExpired: "Expired",
dailyKeyExpiresIn: "Free daily key · expires {when} ({hours}h {minutes}m left)",
dailyKeyRenewOpen: "Free daily key · expires {when}; claim the next one now, both stay valid",
dailyKeyExpired: "Free daily key expired; claim a new one and paste it here",
dailyKeyClaim: "Claim →",
hostsTitle: "Endpoints",
hostsIntro: "Every request uses the fastest endpoint by the last measurement; an endpoint that cannot be reached is skipped for a while and the next one serves.",
hostsProbe: "Measure again",
hostsProbing: "Measuring…",
hostsCurrent: "current",
hostsDown: "unreachable",
hostsCooling: "skipped for now",
hostsUnprobed: "not measured",
hostsEdit: "Edit endpoint list",
hostsEditHint: "One endpoint per line (origin only, https), in order of preference. Use Restore defaults to go back to the built-in list.",
hostsSave: "Save",
hostsReset: "Restore defaults",
composerLabel: "InfStarAPI remaining balance",
composerNoKey: "No usable key",
composerUnread: "Balance unavailable",
composerStale: "last read at {time}; this read failed",
cliTitle: "Claude Code CLI",
cliChecking: "Checking this device for the Claude Code CLI…",
cliInstalled: "Installed",
cliVersion: "Version",
cliPath: "Location",
cliRecheck: "Check again",
cliMissing: "Claude Code CLI not found",
cliMissingHint: "Only needed when the Claude runtime is set to the local Claude Code CLI, or for the claude_code delegation tool. The default HTTP runtime needs no CLI.",
claudeRuntimeTitle: "Claude runtime",
claudeRuntimeHttp: "HTTP (recommended)",
claudeRuntimeHttpHint: "Claude models call InfStarAPI’s Messages API directly and use DSH’s own tools, permissions, and plan mode.",
claudeRuntimeCli: "Local Claude Code CLI",
claudeRuntimeCliHint: "The local official Claude Code CLI runs the turn with its own tools; use this when the key’s group only serves the official CLI.",
cliConfiguredMissing: "The CLI path set in settings does not exist: {path}",
cliBroken: "The CLI was found but could not run",
cliInstall: "Install Claude Code CLI",
cliReinstall: "Reinstall",
cliInstalling: "Installing… (usually a minute or two; keep DSH open)",
cliInstallCommand: "Runs on this device: {command} (requires Node.js 18 or later)",
cliInstallSucceeded: "Installed.",
cliInstallFailed: "Install failed",
cliNpmMissing: "npm was not found. Install Node.js 18 or later from https://nodejs.org, then click Install again.",
cliPermission: "npm cannot write its global directory. Run sudo {command} in a terminal, or point npm’s global prefix at a folder you own, then retry.",
cliPermissionWindows: "npm cannot write its global directory. Open a terminal as administrator, run {command}, then click Check again.",
cliNetwork: "The download failed. Check your network or npm registry settings and retry.",
cliTimeout: "The install timed out. Check your network and retry.",
cliNotFoundAfterInstall: "npm reported success, but the claude command still cannot be found. Run claude --version in a terminal, then click Check again.",
cliWindowsNote: "On Windows, Claude Code also needs Git for Windows (https://git-scm.com/downloads/win).",
versionTitle: "Plugin version",
versionCurrent: "Current version",
versionLatest: "Latest version",
versionCheck: "Check for updates",
versionChecking: "Checking for updates…",
versionFailed: "Could not check the latest version.",
versionUpToDate: "Up to date",
versionAvailable: "v{version} is available",
versionLinked: "Installed from a local checkout. Pull and rebuild the plugin repository instead.",
versionManual: "This install cannot update itself. Download the new version from GitHub Releases and reinstall it from the Plugins page.",
versionNotes: "Release notes",
versionUpdate: "Update plugin",
versionUpdating: "Updating…",
versionUpdateFailed: "The update failed. Try again, or reinstall from the Plugins page.",
versionUpdated: "Updated to v{version}.",
versionUpdatedHint: "Quit and reopen the desktop application. Refreshing the page does not reload the plugin inside the Host.",
versionRestart: "How to restart",
versionRestartHint: "The plugin cannot safely restart the desktop application. Quit DSH completely, then open it again.",
versionRefresh: "Refresh page",
versionLater: "Later",
searchTitle: "Web search",
searchScope: "DSH-wide setting",
searchIntro: "DSH’s web_search and Claude CLI’s MCP search can use the Claude/GPT backend selected here. Each search is a separate model call billed to the plugin-stored keys.",
searchCliHint: "Claude CLI always uses this backend through MCP; native WebSearch is disabled. The routing options below only control DSH-wide search, not CLI search.",
searchChecking: "Reading the search preference…",
searchLoadFailed: "Could not read or save the search preference",
searchModeTitle: "DSH routing",
searchModeDefault: "Off",
searchModeDefaultHint: "Leave DSH search routing untouched (the default). Switching back here removes the search patch this plugin wrote into the profile.",
searchModeAuto: "By model",
searchModeAutoHint: "InfStarAPI models search through InfStarAPI; other models keep the search they had (DSH’s default, or another plugin’s choice).",
searchModeInfstarapi: "Always InfStarAPI",
searchModeInfstarapiHint: "Every request DSH’s default search would have served goes through InfStarAPI. Models another subscription plugin (Codex, Kimi) routes keep that plugin’s choice.",
searchBackendTitle: "Search backend",
searchBackendClaude: "Claude",
searchBackendClaudeHint: "{model}: about 10K input tokens per search, with sources; needs a key that can use Claude.",
searchBackendGpt: "GPT",
searchBackendGptHint: "{model}: usually fresher and more accurate results, about 20–30K input tokens per search; needs a key that can use GPT.",
searchEffective: "In effect: base search {base} · runtime {runtime}",
searchPatchNote: "By model and Always write a marked web entry into this profile’s cordis.patch.yml; it hot-applies, no restart needed. Switch back to Off before uninstalling the plugin.",
searchApplyFailed: "Could not write the search patch: {error}",
searchForeign: "{names} subscription plugin detected: the models it routes keep its own search choice; only the other requests reach the choice made here.",
searchOverridden: "The base search is {base}, not InfStarAPI: the reload may still be running, or another plugin’s patch overrides it.",
searchUnavailable: "This runtime has no DSH web search service; global routing has no effect. Claude CLI’s MCP search is unaffected.",
searchNotWritable: "This profile does not allow settings writes.",
searchUnknown: "unknown"
};
//#endregion
//#region src/client-style.js
/**
* The settings panel's stylesheet, built only from DSH design tokens so it
* follows the host theme (light and dark) and matches the host's own settings
* pages: settings cards, hairline-divided rows, 0.5px tags, layer-1 inputs.
* Fallbacks cover hosts that predate the settings-card tokens.
*
* @module dsh-geek2api/client-style
*/
const STYLE = `
.pkc{display:flex;flex-direction:column;gap:16px;color:var(--dsw-alias-label-primary);font-size:14px;line-height:22px}
.pkc-intro{margin:0;color:var(--dsw-alias-label-tertiary)}
.pkc-card{display:flex;flex-direction:column;gap:14px;padding:16px 18px;border:.5px solid var(--dsw-alias-settings-card-stroke,var(--dsw-alias-border-l4,rgba(127,127,127,.3)));border-radius:var(--dsw-radius-xl,20px);background:var(--dsw-alias-settings-card-fill,var(--dsw-alias-bg-layer-2))}
.pkc-head{display:flex;align-items:center;justify-content:space-between;gap:12px;min-height:28px}
.pkc-title{display:flex;align-items:center;gap:8px;margin:0;font-size:15px;font-weight:600;line-height:22px}
.pkc-note{margin:0;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
.pkc-warn{margin:0;color:var(--dsw-alias-state-warn-label,#dd8629);font-size:12px;line-height:18px}
.pkc-error{margin:0;color:var(--dsw-alias-state-error-primary,#ec1313);font-size:12px;line-height:18px}
.pkc-label{color:var(--dsw-alias-label-secondary);font-size:12px;font-weight:500;line-height:18px}
.pkc-mono{font-family:var(--ds-font-family-code,ui-monospace,SFMono-Regular,Menlo,Consolas,monospace);font-size:12px;word-break:break-all}
.pkc-detail{margin:0;padding:8px 10px;border-radius:var(--dsw-radius-sm,8px);background:var(--dsw-alias-markdown-code-block);color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px;white-space:pre-wrap;word-break:break-all;max-height:160px;overflow:auto}
.pkc-btn{box-sizing:border-box;display:inline-flex;flex:none;align-items:center;justify-content:center;gap:4px;height:28px;padding:0 10px;border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-sm,8px);background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;line-height:18px;white-space:nowrap;cursor:pointer}
.pkc-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}
.pkc-btn:active:not(:disabled){background:var(--dsw-alias-interactive-bg-active)}
.pkc-btn:disabled{opacity:.4;cursor:not-allowed}
.pkc-btn[data-size=md]{height:32px;padding:0 14px;border-radius:var(--dsw-radius-md,12px);font-size:13px}
.pkc-btn[data-variant=primary]{border-color:transparent;background:var(--dsw-alias-button-primary-fill);color:var(--dsw-alias-label-primary-foreground)}
.pkc-btn[data-variant=primary]:hover:not(:disabled){background:var(--dsw-alias-button-primary-hover)}
.pkc-btn[data-variant=ghost]{border-color:transparent;color:var(--dsw-alias-label-secondary)}
.pkc-btn[data-variant=danger]{border-color:transparent;color:var(--dsw-alias-state-error-primary)}
.pkc-btn[data-variant=danger]:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover-danger)}
.pkc-input{box-sizing:border-box;flex:1 1 200px;min-width:0;height:32px;padding:0 10px;border:.5px solid var(--dsw-alias-border-l4);border-radius:var(--dsw-radius-md,12px);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;outline:none}
.pkc-input:focus{border-color:var(--dsw-alias-state-business-primary)}
.pkc-input::placeholder{color:var(--dsw-alias-label-caption)}
.pkc-input:disabled{opacity:.5}
.pkc-link{color:var(--dsw-alias-state-business-primary);font-size:12px;text-decoration:none}
.pkc-link:hover{text-decoration:underline}
.pkc-textarea{display:block;width:100%;height:auto;min-height:96px;padding:8px 10px;line-height:1.6;resize:vertical;white-space:pre;overflow-x:auto}
.pkc-form{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
.pkc-chip{flex:none;padding:0 8px;border-radius:999px;font-size:11px;font-weight:500;line-height:18px;white-space:nowrap}
.pkc-chip[data-tone=success]{background:var(--dsw-alias-state-success-tertiary);color:var(--dsw-alias-state-success-primary)}
.pkc-chip[data-tone=danger]{background:var(--dsw-alias-interactive-bg-hover-danger);color:var(--dsw-alias-state-error-primary)}
.pkc-chip[data-tone=info]{background:var(--dsw-alias-state-business-tertiary);color:var(--dsw-alias-state-business-primary)}
.pkc-chip[data-tone=neutral]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}
.pkc-tag{flex:none;padding:0 6px;border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-xs,4px);color:var(--dsw-alias-label-secondary);font-family:var(--ds-font-family-code,ui-monospace,SFMono-Regular,Menlo,Consolas,monospace);font-size:11px;line-height:18px;cursor:default}
.pkc-dot{flex:none;width:8px;height:8px;border-radius:50%;background:var(--dsw-alias-state-idle-primary)}
.pkc-dot[data-tone=success]{background:var(--dsw-alias-state-success-primary)}
.pkc-dot[data-tone=warn]{background:var(--dsw-alias-state-warn-primary)}
.pkc-dot[data-tone=danger]{background:var(--dsw-alias-state-error-primary)}
.pkc-stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}
.pkc-stat{display:flex;flex-direction:column;gap:2px;padding:10px 12px;border-radius:var(--dsw-radius-md,12px);background:var(--dsw-alias-interactive-bg-hover)}
.pkc-stat-label{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
.pkc-stat-value{font-size:20px;font-weight:600;line-height:28px;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.pkc-list{display:flex;flex-direction:column}
.pkc-row{display:flex;flex-direction:column;gap:8px;padding:12px 0;border-top:.5px solid var(--dsw-alias-border-l2)}
.pkc-row:first-child{border-top:0;padding-top:2px}
.pkc-row-top{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:8px 12px}
.pkc-row-name{display:flex;flex-wrap:wrap;align-items:center;gap:8px;min-width:0;font-weight:500}
.pkc-row-name>.pkc-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.pkc-actions{display:flex;flex-wrap:wrap;gap:4px}
.pkc-meta{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px;font-variant-numeric:tabular-nums}
.pkc-figures{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 16px;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
.pkc-figures b{margin-left:4px;color:var(--dsw-alias-label-primary);font-size:13px;font-weight:600;font-variant-numeric:tabular-nums}
.pkc-bar{height:4px;overflow:hidden;border-radius:999px;background:var(--dsw-alias-interactive-bg-active)}
.pkc-bar>span{display:block;height:100%;border-radius:inherit;background:var(--dsw-alias-state-success-primary)}
.pkc-bar[data-level=warn]>span{background:var(--dsw-alias-state-warn-primary)}
.pkc-bar[data-level=low]>span{background:var(--dsw-alias-state-error-primary)}
.pkc-groups{display:flex;flex-wrap:wrap;align-items:center;gap:6px 6px}
.pkc-groups>.pkc-label{margin-right:2px}
.pkc-reach{display:flex;flex-wrap:wrap;align-items:center;gap:4px 12px;font-size:12px;line-height:18px}
.pkc-reach>span{display:inline-flex;align-items:center;gap:4px;cursor:default}
.pkc-reach>span[data-state=ok]{color:var(--dsw-alias-state-success-primary)}
.pkc-reach>span[data-state=partial]{color:var(--dsw-alias-state-warn-label,#dd8629)}
.pkc-reach>span[data-state=no]{color:var(--dsw-alias-label-caption);text-decoration:line-through}
.pkc-add{display:flex;flex-direction:column;gap:8px;padding-top:14px;border-top:.5px solid var(--dsw-alias-border-l2)}
.pkc-models{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin:0;padding:0;min-width:0;border:0}
.pkc-model{display:flex;align-items:center;gap:10px;min-width:0;padding:10px 12px;border-radius:var(--dsw-radius-md,12px);background:var(--dsw-alias-interactive-bg-hover);cursor:pointer}
.pkc-model>input{flex:none;width:16px;height:16px;margin:0;accent-color:var(--dsw-alias-state-business-primary)}
.pkc-model>span{display:flex;flex-direction:column;min-width:0;gap:2px}
.pkc-model b{font-size:13px;font-weight:500}
.pkc-models:disabled .pkc-model{opacity:.5;cursor:not-allowed}
.pkc-model b>.pkc-chip{margin-left:6px;vertical-align:1px}
.pkc-check{display:inline-flex;align-items:center;gap:6px;font-size:13px;cursor:pointer}
.pkc-check>input{flex:none;width:16px;height:16px;margin:0;accent-color:var(--dsw-alias-state-business-primary)}
.pkc-setting{display:grid;grid-template-columns:112px minmax(0,1fr);gap:6px 16px;align-items:start}
.pkc-setting>.pkc-label{padding-top:5px}
.pkc-setting>div{display:flex;flex-direction:column;gap:6px;min-width:0}
.pkc-seg{display:inline-flex;flex-wrap:wrap;align-self:flex-start;gap:2px;max-width:100%;padding:2px;border-radius:var(--dsw-radius-md,12px);background:var(--dsw-alias-interactive-bg-hover)}
.pkc-seg>button{height:28px;padding:0 12px;border:0;border-radius:calc(var(--dsw-radius-md,12px) - 2px);background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;line-height:18px;cursor:pointer}
.pkc-seg>button:hover:not(:disabled):not([aria-checked=true]){color:var(--dsw-alias-label-primary)}
.pkc-seg>button[aria-checked=true]{background:var(--dsw-alias-button-elevated-fill);color:var(--dsw-alias-label-primary);font-weight:500;box-shadow:var(--dsw-shadow-lv1)}
.pkc-seg>button:disabled{cursor:not-allowed;opacity:.5}
.pkc-status{display:flex;flex-wrap:wrap;align-items:center;gap:6px 8px;font-size:13px}
.pkc-status>b{font-weight:600;font-variant-numeric:tabular-nums}
.pkc-callout{display:flex;flex-direction:column;gap:10px;padding:12px 14px;border-radius:var(--dsw-radius-md,12px);background:var(--dsw-alias-state-warn-tertiary)}
.pkc-callout[data-tone=info]{background:var(--dsw-alias-state-business-tertiary)}
.pkc-callout>.pkc-title{font-size:13px}
.pkc-split{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:10px}
.pkc-advanced>summary{width:fit-content;padding:2px 4px;margin-left:-4px;border-radius:var(--dsw-radius-sm,8px);color:var(--dsw-alias-label-secondary);font-size:12px;font-weight:500;line-height:18px;cursor:pointer}
.pkc-advanced>summary:hover{background:var(--dsw-alias-interactive-bg-hover)}
.pkc-advanced[open]>summary{margin-bottom:10px}
.pkc-field{display:flex;flex-direction:column;gap:4px;margin-bottom:10px}
.pkc-composer{display:inline-flex;flex:0 0 auto;align-items:center;box-sizing:border-box;height:28px;color:var(--dsw-alias-label-secondary);font-size:12px;font-weight:500;line-height:20px;font-variant-numeric:tabular-nums;white-space:nowrap;user-select:none}
@media (max-width:640px){
.pkc-stats{grid-template-columns:1fr}
.pkc-setting{grid-template-columns:1fr}
.pkc-models{grid-template-columns:1fr}
.pkc-setting>.pkc-label{padding-top:0}
}
`;
//#endregion
//#region src/totals.js
/**
* Totals across the keys a balance read returned.
*
* In sub2api money belongs to the account, not the key:
* - every wallet key of one account spends the same wallet, counted once —
* the same wallet when the gateway names the same account (`accountRef`)
* or, when it names none, when the balances agree to the micro-dollar;
* - a subscription belongs to the user and its group, so keys on the same
* plan count it once;
* - a key quota is a cap on top of the wallet, not money of its own, so it
* is left out of the sums and reported as `capped`.
*
* @module dsh-geek2api/totals
*/
const amount = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
/** Which pool of money a row draws on; rows with the same pool count once. */
function poolOf(row, usage) {
if (usage.mode === "subscription") return `subscription:${usage.planName ?? row?.id}`;
if (usage.mode !== "wallet") return `key:${row?.id}`;
if (typeof usage.accountRef === "string") return `account:${usage.accountRef}`;
const remaining = amount(usage.availableUsd);
return remaining === void 0 ? `key:${row?.id}` : `wallet:${remaining.toFixed(6)}`;
}
/**
* Add up the balance rows the host returned.
* @param rows - the `keys` array of a balance projection.
* @returns summed amounts plus the conditions that make a sum incomplete:
* keys whose read failed, keys with no limit at all, rows folded into a
* pool already counted, and key caps left out of the sum.
*/
function sumBalances(rows) {
const total = {
keys: 0,
counted: 0,
unread: 0,
unlimited: 0,
shared: 0,
capped: 0,
remainingUsd: 0,
usedUsd: 0,
limitUsd: 0
};
const seen = /* @__PURE__ */ new Set();
for (const row of Array.isArray(rows) ? rows : []) {
total.keys += 1;
const usage = row?.usage;
if (usage === void 0) {
total.unread += 1;
continue;
}
total.counted += 1;
if (usage.mode === "quota") {
total.capped += 1;
continue;
}
const pool = poolOf(row, usage);
if (seen.has(pool)) {
total.shared += 1;
continue;
}
seen.add(pool);
if (usage.unlimitedQuota === true) {
total.unlimited += 1;
continue;
}
const remaining = amount(usage.availableUsd);
const used = amount(usage.usedUsd);
const limit = amount(usage.limitUsd);
if (remaining !== void 0) total.remainingUsd += remaining;
if (used !== void 0) total.usedUsd += used;
if (limit !== void 0) total.limitUsd += limit;
}
return total;
}
//#endregion
//#region src/client.jsx
/**
* Browser half: the InfStarAPI settings page and the composer balance chip.
*
* Every number here comes from the host over the plugin's own loopback RPC
* channel; no key material crosses it, and each read is a bounded projection
* the host built.
*
* @module dsh-infstarapi/client
*/
const NS = "settings.infstarapi";
const PROVIDER = "infstarapi";
const CHANNEL = "/infstarapi";
const REFRESH_MS = 6e4;
const INSTALL_POLL_MS = 2e3;
/** How long after a search change the panel re-reads what DSH applied (the patch hot-reloads). */
const SEARCH_SETTLE_MS = 1500;
const OWN_SEARCH_IDS = {
auto: "infstarapi-auto",
infstarapi: "infstarapi"
};
const FOREIGN_NAMES = {
codex: "Codex",
kimi: "Kimi"
};
/** The catalog's models by family, for the "reaches" line under each key. */
const MODEL_FAMILIES = [["GPT", [
"gpt-6.1-sol",
"gpt-6.2-sol",
"gpt-6.2-astra"
]], ["DeepSeek", ["deepseek-v4.1-flash", "deepseek-v4-pro"]]];
/**
* The one way this bundle talks to the host. The transport drops an
* `undefined` payload and the channel's envelope requires the field, so every
* call carries an object.
*/
function channelCaller(rpc) {
return (endpoint, payload = {}) => rpc.call(CHANNEL, endpoint, payload).then((response) => {
if (!response?.ok) throw new Error(response?.error?.message ?? "InfStarAPI RPC failed");
return response.value;
});
}
const useCaller = (rpc) => react.useMemo(() => channelCaller(rpc), [rpc]);
/** Substitute `{name}` placeholders in a copy string. */
const fill = (text, values) => text.replace(/\{(\w+)\}/gu, (match, name) => values[name] === void 0 ? match : String(values[name]));
function formatUsd(value) {
if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
try {
return new Intl.NumberFormat(void 0, {
style: "currency",
currency: "USD"
}).format(value);
} catch {
return `$${value.toFixed(2)}`;
}
}
/** The clock time of an epoch-millisecond reading, for a "last read at" note. */
function readTime(ms) {
if (typeof ms !== "number" || !Number.isFinite(ms)) return "—";
try {
return new Date(ms).toLocaleTimeString(void 0, {
hour: "2-digit",
minute: "2-digit"
});
} catch {
return new Date(ms).toISOString().slice(11, 16);
}
}
function clearMessage(error) {
const text = typeof error?.message === "string" && error.message.length > 0 ? error.message : String(error);
return text.length > 200 ? text.slice(0, 200) : text;
}
const RESET_KEYS = {
monthly: "resetMonthly",
weekly: "resetWeekly",
daily: "resetDaily"
};
/** What a key draws on: the shared wallet, a subscription plan, or its own quota. */
function planLabel(usage, t) {
if (usage?.mode === "wallet") return t("planWallet");
if (usage?.mode === "subscription" && usage.inactive === true) return fill(t("planSubscriptionInactive"), { name: usage.planName ?? "" });
if (usage?.mode === "subscription") return fill(t("planSubscription"), { name: usage.planName ?? "" });
if (usage?.mode === "quota") return t("planQuota");
}
const resetLabel = (period, t) => RESET_KEYS[period] === void 0 ? void 0 : t(RESET_KEYS[period]);
/** Active key's usage row, preferring the key the ring currently points at. */
function activeUsage(balance) {
if (balance === void 0) return void 0;
return balance.keys?.find((entry) => entry.id === balance.activeId) ?? balance.keys?.[0];
}
/** How much of a key's limit is left, for its bar; undefined without a limit. */
function remainingShare(usage) {
if (usage?.unlimitedQuota === true || typeof usage?.limitUsd !== "number" || usage.limitUsd <= 0) return void 0;
if (typeof usage.availableUsd !== "number") return void 0;
return Math.max(0, Math.min(1, usage.availableUsd / usage.limitUsd));
}
const BUILT_IN_IDS = new Set(MODEL_FAMILIES.flatMap(([, models]) => models));
/**
* Which catalog families a key reaches, from its per-model coverage. Models
* the user added by id form one more family of their own.
*/
function reachOf(coverage, customName) {
const custom = Object.keys(coverage ?? {}).filter((id) => !BUILT_IN_IDS.has(id));
return (custom.length === 0 ? MODEL_FAMILIES : [...MODEL_FAMILIES, [customName, custom]]).flatMap(([name, models]) => {
const known = models.filter((id) => typeof coverage?.[id] === "boolean");
if (known.length === 0) return [];
const reached = known.filter((id) => coverage[id] === true);
return [{
name,
state: reached.length === 0 ? "no" : reached.length === known.length ? "ok" : "partial",
reached,
missing: known.filter((id) => coverage[id] === false)
}];
});
}
function Card({ title, aside, children }) {
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
className: "pkc-card",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("header", {
className: "pkc-head",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h3", {
className: "pkc-title",
children: title
}), aside]
}), children]
});
}
function Button({ variant, size, children, ...rest }) {
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
type: "button",
className: "pkc-btn",
"data-variant": variant,
"data-size": size,
...rest,
children
});
}
function Segmented({ label, options, value, disabled, onChange }) {
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "pkc-seg",
role: "radiogroup",
"aria-label": label,
children: options.map((option) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
type: "button",
role: "radio",
"aria-checked": value === option.value,
disabled,
onClick: () => value !== option.value && onChange(option.value),
children: option.label
}, option.value))
});
}
/** A key's groups and what they reach. */
function KeyGroups({ group, descriptions, loading, t }) {
if (group === void 0) return loading ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: t("groupsChecking")
}) : null;
if (group.rejected === true) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-error",
children: t("groupsRejected")
});
const reach = reachOf(group.coverage, t("customFamily"));
const names = Array.isArray(group.groups) ? group.groups : [];
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-groups",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-label",
children: t("groupsTitle")
}), names.length === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: group.error === void 0 ? "—" : `${t("groupsUnknown")}: ${group.error}`
}) : names.map((name) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-tag",
title: descriptions?.[name] ?? name,
children: name
}, name))]
}),
reach.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "pkc-reach",
children: reach.map((family) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
"data-state": family.state,
title: [...family.reached.map((id) => `✓ ${id}`), ...family.missing.map((id) => `✗ ${id}`)].join("\n"),
children: [
family.state === "ok" ? "✓" : family.state === "partial" ? "◐" : "✕",
" ",
family.name,
family.state === "partial" && ` (${t("groupsPartial")})`
]
}, family.name))
}),
group.extraModels > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: fill(t("groupsExtra"), { count: group.extraModels })
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(KeyContextCap, {
windows: group.contextWindows,
t
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(KeyLifetime, {
lifetime: group.lifetime,
t
}),
group.stale !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: t("groupsStale")
})
] });
}
/** Where the free daily key is claimed again. */
const FREE_DAILY_SITE = "https://sub.infstar.org";
const compactTokens = (value) => value >= 1e3 ? `${Math.round(value / 1e3)}K` : String(value);
/** The per-request context cap the key's group enforces (the free DeepSeek group: 200K). */
function KeyContextCap({ windows, t }) {
if (windows === void 0 || windows === null) return null;
const values = [...new Set(Object.values(windows).filter((value) => Number.isInteger(value)))];
if (values.length === 0) return null;
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: fill(t("contextCap"), { tokens: values.map(compactTokens).join(" / ") })
});
}
/** When the key expires; a daily free key also links to the page that issues the next one. */
function KeyLifetime({ lifetime, t }) {
if (lifetime === void 0 || lifetime === null || !Number.isFinite(lifetime.expiresAt)) return null;
const left = lifetime.expiresAt - Date.now();
const at = new Date(lifetime.expiresAt);
const pad = (value) => String(value).padStart(2, "0");
const when = `${pad(at.getMonth() + 1)}-${pad(at.getDate())} ${pad(at.getHours())}:${pad(at.getMinutes())}`;
const hours = Math.max(0, Math.floor(left / 36e5));
const minutes = Math.max(0, Math.floor(left % 36e5 / 6e4));
if (lifetime.daily !== true) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: left > 0 ? fill(t("keyExpiresAt"), { when }) : t("keyExpired")
});
const renewOpen = left <= (lifetime.renewWindowHours ?? 2) * 36e5;
const href = `${FREE_DAILY_SITE}${lifetime.renewPath ?? "/free-ds"}`;
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
className: left <= 0 || renewOpen ? "pkc-error" : "pkc-meta",
children: [
left <= 0 ? t("dailyKeyExpired") : fill(renewOpen ? t("dailyKeyRenewOpen") : t("dailyKeyExpiresIn"), {
when,
hours,
minutes
}),
" ",
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
href,
target: "_blank",
rel: "noreferrer noopener",
children: t("dailyKeyClaim")
})
]
});
}
function KeyRow({ entry, row, group, descriptions, groupsLoading, busy, renaming, onRename, onAction, skippedUntil, t }) {
const usage = row?.usage;
const share = remainingShare(usage);
const remainingLabel = usage?.mode === "quota" ? t("keyCapRemaining") : t("keyRemaining");
const figures = [
usage?.unlimitedQuota === true ? [remainingLabel, t("keyUnlimited")] : usage?.availableUsd === void 0 ? void 0 : [remainingLabel, formatUsd(usage.availableUsd)],
usage?.usedUsd === void 0 ? void 0 : [t("keyUsed"), formatUsd(usage.usedUsd)],
usage?.limitUsd === void 0 ? void 0 : [t("accountLimit"), formatUsd(usage.limitUsd)]
].filter(Boolean);
const meta = [
planLabel(usage, t),
usage?.keyName === void 0 ? void 0 : `${t("keyName")} ${usage.keyName}`,
resetLabel(usage?.resetPeriod, t),
usage?.todayUsd === void 0 ? void 0 : `${t("keyToday")} ${formatUsd(usage.todayUsd)}`,
usage?.expiresAt === void 0 ? void 0 : fill(t("keyExpires"), { date: new Date(usage.expiresAt).toLocaleDateString() }),
...Array.isArray(usage?.rateLimits) ? usage.rateLimits.map((window) => fill(t("keyWindow"), {
window: window.window,
used: formatUsd(window.usedUsd) ?? "?",
limit: formatUsd(window.limitUsd) ?? "?"
})) : []
].filter(Boolean).join(" · ");
const editing = renaming?.id === entry.id;
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-row",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-row-top",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
className: "pkc-row-name",
children: [
editing ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("form", {
className: "pkc-form",
onSubmit: (event) => {
event.preventDefault();
onRename.submit();
},
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
className: "pkc-input",
type: "text",
maxLength: 60,
autoFocus: true,
placeholder: t("keyRenamePlaceholder"),
value: renaming.label,
onChange: (event) => onRename.change(event.target.value),
onKeyDown: (event) => event.key === "Escape" && onRename.cancel()
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
type: "submit",
variant: "primary",
disabled: busy || renaming.label.trim() === "",
children: t("keyRenameSave")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
variant: "ghost",
onClick: onRename.cancel,
children: t("keyRenameCancel")
})
]
}) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-name",
children: entry.label
}),
entry.active && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-chip",
"data-tone": "success",
children: t("keyActive")
}),
!entry.disabled && skippedUntil !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-chip",
"data-tone": "warn",
children: t("keySkipped")
}),
entry.disabled && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-chip",
"data-tone": "danger",
children: entry.disabledReason ? `${t("keyDisabled")} · ${entry.disabledReason}` : t("keyDisabled")
})
]
}), !editing && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
className: "pkc-actions",
children: [
!entry.active && !entry.disabled && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
disabled: busy,
onClick: () => onAction("keys/select", { id: entry.id }),
children: t("keyUse")
}),
entry.disabled && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
disabled: busy,
onClick: () => onAction("keys/enable", { id: entry.id }),
children: t("keyEnable")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
variant: "ghost",
disabled: busy,
onClick: () => onRename.start(entry),
children: t("keyRename")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
variant: "danger",
disabled: busy,
onClick: () => onAction("keys/remove", { id: entry.id }),
children: t("keyRemove")
})
]
})]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: meta
}),
figures.length > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "pkc-figures",
children: figures.map(([label, value]) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [label, /* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: value })] }, label))
}) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: row?.error === void 0 ? t("keyNoBalance") : `${t("loadFailed")}: ${row.error}`
}),
share !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "pkc-bar",
"data-level": share < .1 ? "low" : share < .3 ? "warn" : "ok",
role: "presentation",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { style: { width: `${Math.round(share * 100)}%` } })
}),
row?.stale !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-warn",
children: fill(t("staleNote"), {
time: readTime(row.stale.fetchedAt),
error: row.stale.error ?? ""
})
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(KeyGroups, {
group,
descriptions,
loading: groupsLoading,
t
})
]
});
}
function AccountsCard({ call, t }) {
const [status, setStatus] = react.useState();
const [balance, setBalance] = react.useState();
const [groups, setGroups] = react.useState();
const [groupsLoading, setGroupsLoading] = react.useState(true);
const [busy, setBusy] = react.useState(false);
const [error, setError] = react.useState();
const [draft, setDraft] = react.useState({
key: "",
label: ""
});
const [renaming, setRenaming] = react.useState();
const generation = react.useRef(0);
const readGroups = react.useCallback((force = false) => {
setGroupsLoading(true);
return call("groups", { force }).then(setGroups).catch(() => void 0).finally(() => setGroupsLoading(false));
}, [call]);
const load = react.useCallback((force = false) => {
const current = ++generation.current;
setBusy(true);
setError(void 0);
readGroups(force);
return Promise.all([call("status"), call("balance", { force })]).then(([nextStatus, nextBalance]) => {
if (generation.current !== current) return;
setStatus(nextStatus);
setBalance(nextBalance);
}).catch((failure) => {
if (generation.current === current) setError(clearMessage(failure));
}).finally(() => {
if (generation.current === current) setBusy(false);
});
}, [call, readGroups]);
react.useEffect(() => {
load(false);
return () => {
generation.current += 1;
};
}, [load]);
const mutate = (endpoint, payload) => {
setBusy(true);
setError(void 0);
return call(endpoint, payload).then((nextStatus) => {
setStatus(nextStatus);
readGroups(false);
return call("balance", { force: true });
}).then(setBalance).catch((failure) => setError(clearMessage(failure))).finally(() => setBusy(false));
};
const addKey = (event) => {
event.preventDefault();
if (draft.key.trim() === "") return;
mutate("keys/add", {
key: draft.key,
label: draft.label
}).then(() => setDraft({
key: "",
label: ""
}));
};
const rename = {
start: (entry) => setRenaming({
id: entry.id,
label: entry.label
}),
change: (label) => setRenaming((current) => ({
...current,
label
})),
cancel: () => setRenaming(void 0),
submit: () => {
if (renaming === void 0 || renaming.label.trim() === "") return;
mutate("keys/rename", {
id: renaming.id,
label: renaming.label
}).then(() => setRenaming(void 0));
}
};
const keys = status?.keys ?? [];
const rows = balance?.keys ?? [];
const totals = sumBalances(rows);
const staleCount = rows.filter((row) => row.stale !== void 0).length;
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Card, {
title: t("accountsTitle"),
aside: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
className: "pkc-actions",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
disabled: busy,
onClick: () => load(true),
children: busy ? t("refreshing") : t("refresh")
}), keys.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
variant: "danger",
disabled: busy,
onClick: () => mutate("keys/remove-all", {}),
children: t("removeAll")
})]
}),
children: [
keys.length === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("empty")
}) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-stats",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-stat",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-stat-label",
children: t("totalRemaining")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
className: "pkc-stat-value",
children: [totals.counted === 0 ? "—" : formatUsd(totals.remainingUsd) ?? "—", totals.unlimited > 0 && ` + ${t("keyUnlimited")}`]
})]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-stat",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-stat-label",
children: t("totalUsed")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-stat-value",
children: totals.counted === 0 ? "—" : formatUsd(totals.usedUsd) ?? "—"
})]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-stat",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-stat-label",
children: t("totalLimit")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-stat-value",
children: totals.counted === 0 ? "—" : totals.unlimited > 0 ? t("keyUnlimited") : formatUsd(totals.limitUsd) ?? "—"
})]
})
]
}),
(totals.unread > 0 || staleCount > 0 || totals.shared > 0 || totals.capped > 0) && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: [
totals.shared > 0 ? fill(t("totalShared"), { count: totals.shared }) : void 0,
totals.capped > 0 ? fill(t("totalCapped"), { count: totals.capped }) : void 0,
totals.unread > 0 ? fill(t("totalPartial"), { count: totals.unread }) : void 0,
staleCount > 0 ? fill(t("totalStale"), { count: staleCount }) : void 0
].filter(Boolean).join(" ")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "pkc-list",
children: keys.map((entry) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(KeyRow, {
entry,
row: rows.find((row) => row.id === entry.id),
group: groups?.keys?.find((group) => group.id === entry.id),
descriptions: groups?.descriptions,
groupsLoading,
busy,
renaming,
onRename: rename,
onAction: mutate,
skippedUntil: status?.skipped?.[entry.id],
t
}, entry.id))
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("keysHint")
})
] }),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("form", {
className: "pkc-add",
onSubmit: addKey,
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-label",
children: t("addTitle")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-form",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
className: "pkc-input",
type: "password",
autoComplete: "off",
placeholder: t("addKeyPlaceholder"),
value: draft.key,
onChange: (event) => setDraft((current) => ({
...current,
key: event.target.value
}))
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
className: "pkc-input",
type: "text",
placeholder: t("addLabelPlaceholder"),
value: draft.label,
onChange: (event) => setDraft((current) => ({
...current,
label: event.target.value
}))
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
type: "submit",
variant: "primary",
size: "md",
disabled: busy || draft.key.trim() === "",
children: t("add")
})
]
})]
}),
status !== void 0 && status.writable !== true && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("notWritable")
}),
error !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-error",
role: "alert",
children: `${t("error")}: ${error}`
})
]
});
}
/** The entry points, their measured latency, and an editor for the list. */
function HostsCard({ call, t }) {
const [status, setStatus] = react.useState();
const [busy, setBusy] = react.useState(false);
const [error, setError] = react.useState();
const [draft, setDraft] = react.useState();
const [editing, setEditing] = react.useState(false);
const run = react.useCallback((endpoint, payload) => {
setBusy(true);
setError(void 0);
return call(endpoint, payload).then((next) => {
setStatus(next);
return next;
}).catch((failure) => {
setError(clearMessage(failure));
}).finally(() => setBusy(false));
}, [call]);
react.useEffect(() => {
run("hosts/probe", {});
}, [run]);
const hosts = Array.isArray(status?.hosts) ? status.hosts : [];
const listText = (list) => Array.isArray(list) ? list.map((entry) => entry.host).join("\n") : "";
react.useEffect(() => {
if (editing && draft === void 0 && hosts.length > 0) setDraft(listText(hosts));
}, [
editing,
draft,
hosts
]);
const save = (list) => run("hosts/update", { apiHosts: list }).then((next) => {
if (next !== void 0) setDraft(listText(next.hosts));
});
const draftHosts = (draft ?? "").split(/\s+/u).filter(Boolean);
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Card, {
title: t("hostsTitle"),
aside: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
disabled: busy,
onClick: () => run("hosts/probe", {}),
children: busy ? t("hostsProbing") : t("hostsProbe")
}),
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("hostsIntro")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "pkc-list",
children: hosts.map((entry) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-status",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-dot",
"data-tone": entry.coolingUntil !== void 0 ? "danger" : entry.latencyMs !== void 0 ? "success" : "warn"
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-mono",
children: entry.host
}),
entry.current && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-chip",
"data-tone": "success",
children: t("hostsCurrent")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: entry.coolingUntil !== void 0 ? t("hostsCooling") : entry.latencyMs !== void 0 ? `${entry.latencyMs} ms` : entry.probed === false ? t("hostsUnprobed") : t("hostsDown")
})
]
}, entry.host))
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("details", {
className: "pkc-advanced",
onToggle: (event) => setEditing(event.currentTarget.open),
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("summary", { children: t("hostsEdit") }),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("hostsEditHint")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("textarea", {
className: "pkc-input pkc-textarea pkc-mono",
rows: Math.max(4, hosts.length + 1),
disabled: status?.writable !== true || busy,
value: draft ?? "",
onChange: (event) => setDraft(event.target.value)
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-split",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
variant: "primary",
disabled: status?.writable !== true || busy || draftHosts.length === 0,
onClick: () => save(draftHosts),
children: t("hostsSave")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
variant: "ghost",
disabled: status?.writable !== true || busy,
onClick: () => save([]),
children: t("hostsReset")
})]
})
]
}),
status !== void 0 && status.writable !== true && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("notWritable")
}),
error !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-error",
role: "alert",
children: `${t("error")}: ${error}`
})
]
});
}
const PROTOCOL_KEYS = {
"openai-completions": "protocolCompletions",
"openai-responses": "protocolResponses",
"anthropic-messages": "protocolMessages"
};
const EMPTY_CUSTOM = {
id: "",
name: "",
api: "openai-completions",
reasoning: false,
image: false,
contextWindow: "",
maxTokens: ""
};
/** One user-added model: its protocol and capabilities, and a remove button. */
function CustomModelRow({ model, disabled, onRemove, t }) {
const facts = [
t(PROTOCOL_KEYS[model.api] ?? "protocolCompletions"),
model.reasoning ? t("customReasoning") : void 0,
model.image ? t("customImage") : void 0,
fill(t("customWindow"), {
context: model.contextWindow.toLocaleString(),
output: model.maxTokens.toLocaleString()
})
].filter(Boolean).join(" · ");
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-row",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-row-top",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
className: "pkc-row-name",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-name",
children: model.name === "" ? model.id : model.name
}), model.name !== "" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta pkc-mono",
children: model.id
})]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-actions",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
variant: "danger",
disabled,
onClick: onRemove,
children: t("customRemove")
})
})]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: facts
})]
});
}
/** The form that adds a model by id. */
function CustomModelForm({ disabled, onAdd, t }) {
const [draft, setDraft] = react.useState(EMPTY_CUSTOM);
const set = (patch) => setDraft((current) => ({
...current,
...patch
}));
const submit = (event) => {
event.preventDefault();
if (disabled || draft.id.trim() === "") return;
onAdd({
id: draft.id.trim(),
name: draft.name.trim(),
api: draft.api,
reasoning: draft.reasoning,
image: draft.image,
...draft.contextWindow.trim() === "" ? {} : { contextWindow: Number(draft.contextWindow) },
...draft.maxTokens.trim() === "" ? {} : { maxTokens: Number(draft.maxTokens) }
}).then((saved) => {
if (saved) setDraft(EMPTY_CUSTOM);
});
};
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("form", {
className: "pkc-add",
onSubmit: submit,
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-label",
children: t("customAddTitle")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-form",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
className: "pkc-input pkc-mono",
type: "text",
maxLength: 128,
spellCheck: false,
autoComplete: "off",
placeholder: t("customIdPlaceholder"),
disabled,
value: draft.id,
onChange: (event) => set({ id: event.target.value })
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
className: "pkc-input",
type: "text",
maxLength: 64,
placeholder: t("customNamePlaceholder"),
disabled,
value: draft.name,
onChange: (event) => set({ name: event.target.value })
})]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-setting",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-label",
children: t("customProtocol")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Segmented, {
label: t("customProtocol"),
options: Object.keys(PROTOCOL_KEYS).map((value) => ({
value,
label: t(PROTOCOL_KEYS[value])
})),
value: draft.api,
disabled,
onChange: (api) => set({ api })
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("customProtocolHint")
})] }),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-label",
children: t("customCapabilities")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-form",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
className: "pkc-check",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
type: "checkbox",
disabled,
checked: draft.reasoning,
onChange: (event) => set({ reasoning: event.target.checked })
}), t("customReasoning")]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
className: "pkc-check",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
type: "checkbox",
disabled,
checked: draft.image,
onChange: (event) => set({ image: event.target.checked })
}), t("customImage")]
})]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-label",
children: t("customLimits")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-form",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
className: "pkc-input",
type: "number",
min: 1e3,
step: 1e3,
placeholder: t("customContextPlaceholder"),
disabled,
value: draft.contextWindow,
onChange: (event) => set({ contextWindow: event.target.value })
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
className: "pkc-input",
type: "number",
min: 1,
step: 1e3,
placeholder: t("customOutputPlaceholder"),
disabled,
value: draft.maxTokens,
onChange: (event) => set({ maxTokens: event.target.value })
})]
})
]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-split",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("customReasoningHint")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
type: "submit",
variant: "primary",
disabled: disabled || draft.id.trim() === "",
children: t("customAdd")
})]
})
]
});
}
function ModelsCard({ call, t }) {
const [state, setState] = react.useState();
const [busy, setBusy] = react.useState(false);
const [error, setError] = react.useState();
react.useEffect(() => {
let live = true;
call("models/status").then((value) => {
if (live) setState(value);
}).catch((failure) => {
if (live) setError(clearMessage(failure));
});
return () => {
live = false;
};
}, [call]);
const models = state?.models ?? [];
const custom = Array.isArray(state?.customModels) ? state.customModels : [];
const selectedIds = models.filter((model) => model.selected).map((model) => model.id);
const disabled = busy || state?.writable !== true;
/** Run one write; resolves true when it was saved. */
const write = (endpoint, payload) => {
if (disabled) return Promise.resolve(false);
setBusy(true);
setError(void 0);
return call(endpoint, payload).then((next) => {
setState(next);
return true;
}).catch((failure) => {
setError(clearMessage(failure));
return false;
}).finally(() => setBusy(false));
};
const update = (ids) => void write("models/update", { selectedIds: ids });
const saveCustom = (list) => write("models/custom/update", { customModels: list });
const full = custom.length >= (state?.maxCustomModels ?? Infinity);
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Card, {
title: t("modelsTitle"),
aside: state !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: fill(t("modelsCount"), {
count: selectedIds.length,
total: models.length
})
}),
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("modelsIntro")
}),
state === void 0 && error === void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
role: "status",
children: t("modelsChecking")
}),
state !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-actions",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
disabled: disabled || selectedIds.length === models.length,
onClick: () => update(models.map((model) => model.id)),
children: t("modelsAll")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
disabled: disabled || selectedIds.length === 0,
onClick: () => update([]),
children: t("modelsNone")
})]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("fieldset", {
className: "pkc-models",
"aria-label": t("modelsTitle"),
disabled,
children: models.map((model) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
className: "pkc-model",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
type: "checkbox",
checked: model.selected,
onChange: (event) => update(event.target.checked ? [...selectedIds, model.id] : selectedIds.filter((id) => id !== model.id))
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("b", { children: [model.name, model.custom === true && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-chip",
"data-tone": "info",
children: t("customChip")
})] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta pkc-mono",
children: model.id
})] })]
}, model.id))
}),
selectedIds.length === 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("modelsEmpty")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("details", {
className: "pkc-advanced",
open: custom.length > 0 ? true : void 0,
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("summary", { children: fill(t("customTitle"), { count: custom.length }) }),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("customIntro")
}),
custom.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "pkc-list",
children: custom.map((model) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CustomModelRow, {
model,
disabled,
onRemove: () => void saveCustom(custom.filter((entry) => entry.id !== model.id)),
t
}, model.id))
}),
full ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: fill(t("customFull"), { count: state.maxCustomModels })
}) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CustomModelForm, {
disabled,
onAdd: (entry) => saveCustom([...custom, entry]),
t
})
]
}),
state.writable !== true && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("searchNotWritable")
})
] }),
error !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-error",
role: "alert",
children: `${t("modelsFailed")}: ${error}`
})
]
});
}
/** Web search routing and backend, written through the host. */
function SearchCard({ call, t }) {
const [state, setState] = react.useState();
const [busy, setBusy] = react.useState(false);
const [error, setError] = react.useState();
const generation = react.useRef(0);
const read = react.useCallback(() => {
const current = ++generation.current;
return call("search/status").then((value) => {
if (generation.current === current) setState(value);
}).catch((failure) => {
if (generation.current === current) setError(clearMessage(failure));
});
}, [call]);
react.useEffect(() => {
read();
return () => {
generation.current += 1;
};
}, [read]);
const update = (patch) => {
if (busy || state?.writable !== true) return;
setBusy(true);
setError(void 0);
call("search/update", patch).then((value) => {
setState(value);
window.setTimeout(() => {
read();
}, SEARCH_SETTLE_MS);
}).catch((failure) => setError(clearMessage(failure))).finally(() => setBusy(false));
};
const mode = state?.searchProvider;
const backend = state?.searchBackend;
const models = state?.models ?? {};
const base = state?.effective?.base;
const runtime = state?.effective?.runtime;
const foreign = Object.entries(state?.foreign ?? {}).filter(([, present]) => present).map(([name]) => FOREIGN_NAMES[name] ?? name);
const expected = OWN_SEARCH_IDS[mode];
const overridden = expected !== void 0 && state?.applied?.state === "applied" && base !== void 0 && base !== expected;
const disabled = busy || state?.writable !== true;
const modeHint = {
default: "searchModeDefaultHint",
auto: "searchModeAutoHint",
infstarapi: "searchModeInfstarapiHint"
}[mode];
const backendHint = backend === "gpt" ? fill(t("searchBackendGptHint"), { model: models.gpt ?? "gpt-6.1-sol" }) : fill(t("searchBackendClaudeHint"), { model: models.claude ?? "claude-haiku-4-5-20251001" });
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Card, {
title: t("searchTitle"),
aside: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-chip",
"data-tone": "neutral",
children: t("searchScope")
}),
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("searchIntro")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("searchCliHint")
}),
state === void 0 && error === void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
role: "status",
children: t("searchChecking")
}),
state !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-setting",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-label",
children: t("searchModeTitle")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Segmented, {
label: t("searchModeTitle"),
value: mode,
disabled,
onChange: (value) => update({ searchProvider: value }),
options: [
{
value: "default",
label: t("searchModeDefault")
},
{
value: "auto",
label: t("searchModeAuto")
},
{
value: "infstarapi",
label: t("searchModeInfstarapi")
}
]
}), modeHint !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t(modeHint)
})] })]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-setting",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-label",
children: t("searchBackendTitle")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Segmented, {
label: t("searchBackendTitle"),
value: backend,
disabled,
onChange: (value) => update({ searchBackend: value }),
options: [{
value: "gpt",
label: t("searchBackendGpt")
}]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: backendHint
})] })]
}),
state.available === true && (base !== void 0 || runtime !== void 0) && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-status",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-dot",
"data-tone": overridden ? "warn" : expected !== void 0 && base === expected ? "success" : void 0
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: fill(t("searchEffective"), {
base: base ?? t("searchUnknown"),
runtime: runtime ?? base ?? t("searchUnknown")
})
})]
}),
overridden && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-warn",
children: fill(t("searchOverridden"), { base })
}),
foreign.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: fill(t("searchForeign"), { names: foreign.join(" / ") })
}),
state.applied?.state === "failed" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-error",
role: "alert",
children: fill(t("searchApplyFailed"), { error: state.applied.error ?? "" })
}),
state.available !== true && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("searchUnavailable")
}),
state.writable !== true && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("searchNotWritable")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("searchPatchNote")
})
] }),
error !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-error",
role: "alert",
children: `${t("searchLoadFailed")}: ${error}`
})
]
});
}
const INSTALL_FAILURES = {
"npm-missing": () => "cliNpmMissing",
permission: (cli) => cli.platform === "win32" ? "cliPermissionWindows" : "cliPermission",
network: () => "cliNetwork",
timeout: () => "cliTimeout",
"not-found-after-install": () => "cliNotFoundAfterInstall"
};
/** The sentence explaining a failed install, by the code the host classified. */
function installFailure(cli, t) {
const key = INSTALL_FAILURES[cli.install?.code]?.(cli);
return key === void 0 ? void 0 : fill(t(key), { command: cli.command ?? "" });
}
/**
* Whether this device has the Claude Code CLI, which version, and — when it
* has none — a button that installs it with npm.
*/
function ClaudeCliCard({ call, t }) {
const [cli, setCli] = react.useState();
const [checking, setChecking] = react.useState(false);
const [error, setError] = react.useState();
const [runtime, setRuntime] = react.useState();
const [runtimeWritable, setRuntimeWritable] = react.useState(false);
react.useEffect(() => {
call("status").then((value) => {
setRuntime(value?.claudeRuntime ?? "http");
setRuntimeWritable(value?.writable === true);
}).catch(() => void 0);
}, [call]);
const changeRuntime = (next) => {
setError(void 0);
call("claude-runtime/update", { runtime: next }).then((value) => setRuntime(value?.claudeRuntime ?? next)).catch((failure) => setError(clearMessage(failure)));
};
const check = react.useCallback((force = false) => {
setChecking(true);
setError(void 0);
return call("claude-cli/status", { force }).then(setCli).catch((failure) => setError(clearMessage(failure))).finally(() => setChecking(false));
}, [call]);
react.useEffect(() => {
check(false);
}, [check]);
const running = cli?.install?.state === "running";
react.useEffect(() => {
if (!running) return void 0;
let live = true;
const timer = window.setInterval(() => {
call("claude-cli/status").then((value) => {
if (live) setCli(value);
}).catch(() => void 0);
}, INSTALL_POLL_MS);
return () => {
live = false;
window.clearInterval(timer);
};
}, [call, running]);
const install = () => {
setError(void 0);
call("claude-cli/install").then(setCli).catch((failure) => setError(clearMessage(failure)));
};
const usable = cli?.installed === true && cli.version !== void 0;
const failed = cli?.install?.state === "failed";
const failure = cli === void 0 ? void 0 : installFailure(cli, t);
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Card, {
title: t("cliTitle"),
aside: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
disabled: checking || running,
onClick: () => check(true),
children: checking ? t("refreshing") : t("cliRecheck")
}),
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-field",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-label",
children: t("claudeRuntimeTitle")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Segmented, {
label: t("claudeRuntimeTitle"),
value: runtime,
disabled: !runtimeWritable || runtime === void 0,
options: [{
value: "http",
label: t("claudeRuntimeHttp")
}, {
value: "cli",
label: t("claudeRuntimeCli")
}],
onChange: changeRuntime
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: runtime === "cli" ? t("claudeRuntimeCliHint") : t("claudeRuntimeHttpHint")
})
]
}),
cli === void 0 && error === void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("cliChecking")
}),
usable && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-status",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-dot",
"data-tone": "success"
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("cliInstalled") }),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: `${t("cliVersion")} ${cli.version}` })
]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
className: "pkc-meta",
children: [
t("cliPath"),
" ",
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-mono",
children: cli.path
})
]
}),
cli.install?.state === "succeeded" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("cliInstallSucceeded")
})
] }),
cli !== void 0 && !usable && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-callout",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-status",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-dot",
"data-tone": cli.installed ? "danger" : "warn"
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: cli.installed ? t("cliBroken") : t("cliMissing") })]
}),
cli.installed && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
className: "pkc-meta",
children: [
t("cliPath"),
" ",
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-mono",
children: cli.path
})
]
}), cli.error !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
className: "pkc-detail",
children: cli.error
})] }),
cli.configuredPath !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: fill(t("cliConfiguredMissing"), { path: cli.configuredPath })
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("cliMissingHint")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "pkc-split",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
variant: "primary",
size: "md",
disabled: running || checking,
onClick: install,
children: running ? t("cliInstalling") : cli.installed ? t("cliReinstall") : t("cliInstall")
})
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", {
className: "pkc-note",
children: [fill(t("cliInstallCommand"), { command: cli.command ?? "" }), cli.platform === "win32" && ` ${t("cliWindowsNote")}`]
})
]
}),
failed && !usable && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-error",
children: failure === void 0 ? t("cliInstallFailed") : `${t("cliInstallFailed")} · ${failure}`
}), cli.install.detail !== void 0 && cli.install.detail !== "" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
className: "pkc-detail",
children: cli.install.detail
})] }),
error !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-error",
children: `${t("error")}: ${error}`
})
]
});
}
function VersionCard({ call, t }) {
const [info, setInfo] = react.useState();
const [loading, setLoading] = react.useState(true);
const [error, setError] = react.useState(false);
const [updating, setUpdating] = react.useState(false);
const [updateFailed, setUpdateFailed] = react.useState(false);
const [updated, setUpdated] = react.useState();
const [restartHint, setRestartHint] = react.useState(false);
const generation = react.useRef(0);
const load = (force) => {
const current = ++generation.current;
setLoading(true);
setError(false);
call("plugin/version", { force }).then((value) => {
if (generation.current === current) setInfo(value);
}).catch(() => {
if (generation.current === current) setError(true);
}).finally(() => {
if (generation.current === current) setLoading(false);
});
};
react.useEffect(() => {
load(false);
return () => {
generation.current += 1;
};
}, []);
const update = () => {
setUpdating(true);
setUpdateFailed(false);
call("plugin/update").then((value) => {
setUpdated(value);
setRestartHint(false);
}).catch(() => setUpdateFailed(true)).finally(() => setUpdating(false));
};
const installKind = info?.install?.kind;
const showStatus = info !== void 0 && updated === void 0;
const canUpdate = showStatus && info.updateAvailable && (info.updatable === true || info.updatable === void 0 && installKind === "npm");
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Card, {
title: t("versionTitle"),
aside: updated === void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
className: "pkc-actions",
children: [canUpdate && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
variant: "primary",
disabled: updating,
onClick: update,
children: updating ? t("versionUpdating") : t("versionUpdate")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
disabled: loading || updating,
onClick: () => load(true),
children: loading ? t("versionChecking") : t("versionCheck")
})]
}),
children: [
loading && info === void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
role: "status",
children: t("versionChecking")
}),
error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-error",
role: "alert",
children: t("versionFailed")
}),
showStatus && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-status",
role: "status",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-dot",
"data-tone": info.updateAvailable ? "warn" : "success"
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: `v${info.current}` }),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
className: "pkc-meta",
children: [info.updateAvailable ? fill(t("versionAvailable"), { version: info.latest }) : t("versionUpToDate"), info.updateAvailable && ` · ${t("versionLatest")} v${info.latest}`]
}),
info.releaseUrl !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
className: "pkc-link",
href: info.releaseUrl,
target: "_blank",
rel: "noreferrer noopener",
children: t("versionNotes")
})
]
}),
showStatus && installKind === "link" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("versionLinked")
}),
showStatus && info.updateAvailable && !canUpdate && installKind !== "link" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("versionManual")
}),
updateFailed && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-error",
role: "alert",
children: t("versionUpdateFailed")
}),
updated !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-callout",
"data-tone": "info",
role: "status",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", {
className: "pkc-title",
children: fill(t("versionUpdated"), { version: updated.version })
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("versionUpdatedHint")
}),
restartHint && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("versionRestartHint")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-actions",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
variant: "primary",
onClick: () => window.location.reload(),
children: t("versionRefresh")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
onClick: () => setRestartHint(true),
children: t("versionRestart")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
variant: "ghost",
onClick: () => setUpdated(void 0),
children: t("versionLater")
})
]
})
]
})
]
});
}
function InfStarAPISection({ rpc, t }) {
const call = useCaller(rpc);
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-intro",
children: t("intro")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(AccountsCard, {
call,
t
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(HostsCard, {
call,
t
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(ModelsCard, {
call,
t
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(SearchCard, {
call,
t
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(ClaudeCliCard, {
call,
t
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(VersionCard, {
call,
t
})
]
});
}
function InfStarAPIComposerQuota({ rpc, t, directory }) {
const call = useCaller(rpc);
const enabled = react.useSyncExternalStore((listener) => directory.subscribe(listener), () => directory.getSnapshot())?.current?.provider === PROVIDER;
const [balance, setBalance] = react.useState();
react.useEffect(() => {
if (!enabled) {
setBalance(void 0);
return;
}
let live = true;
const tick = () => {
call("balance").then((value) => {
if (live) setBalance(value);
}).catch(() => {
if (live) setBalance(void 0);
});
};
tick();
const timer = window.setInterval(tick, REFRESH_MS);
return () => {
live = false;
window.clearInterval(timer);
};
}, [call, enabled]);
if (!enabled || balance === void 0) return null;
const row = activeUsage(balance);
const usage = row?.usage;
const display = usage?.unlimitedQuota === true ? t("keyUnlimited") : formatUsd(usage?.availableUsd) ?? (row?.error === void 0 ? t("composerNoKey") : t("composerUnread"));
const stale = row?.stale !== void 0 && usage !== void 0;
const label = stale ? `${t("composerLabel")}: ${display}(${fill(t("composerStale"), { time: readTime(row.stale.fetchedAt) })})` : `${t("composerLabel")}: ${display}`;
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-composer",
role: "status",
"aria-label": label,
title: label,
children: stale ? `≈${display}` : display
});
}
const inject = [
"slots",
"locale",
"connection",
"modelDirectories"
];
function apply(ctx) {
ctx.effect(() => ctx.locale.register(NS, {
zh,
en
}), "infstarapi: copy");
ctx.effect(() => {
const tag = document.createElement("style");
tag.dataset.plugin = "dsh-infstarapi";
tag.textContent = STYLE;
document.head.append(tag);
return () => tag.remove();
}, "infstarapi: style");
const connection = ctx.get("connection");
const t = ctx.locale.bind(NS);
ctx.slots.inject("settings.section", () => ctx.slots.register({
name: "settings.section",
id: "infstarapi",
order: 17,
label: () => t("nav"),
locale: NS,
inject: () => ({
rpc: connection.rpc,
t
})
}, InfStarAPISection));
ctx.slots.inject("conversation.input.right", () => ctx.slots.register({
name: "conversation.input.right",
id: "infstarapi-balance",
order: 17,
locale: NS,
inject: (sessionId) => ({
rpc: connection.rpc,
t,
directory: ctx.modelDirectories.directoryFor(sessionId).store
})
}, InfStarAPIComposerQuota));
}
//#endregion
exports.apply = apply;
exports.inject = inject;
return module.exports;
}
});
//# sourceMappingURL=client.js.map