@bitkyc08/opencodex 2.7.19 → 2.7.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ko.md +2 -1
- package/README.md +2 -1
- package/README.zh-CN.md +2 -1
- package/gui/dist/assets/{index-D8ODGlXj.js → index-BH-RbAg4.js} +2 -2
- package/gui/dist/assets/index-BpqkH5f_.css +1 -0
- package/gui/dist/index.html +2 -2
- package/package.json +13 -3
- package/src/adapters/cursor/native-exec-desktop.ts +10 -3
- package/src/claude/inbound.ts +3 -1
- package/src/cli/claude.ts +21 -2
- package/src/cli/v2.ts +21 -5
- package/src/codex/project-config-warnings.ts +18 -6
- package/src/lib/win-exec.ts +105 -0
- package/src/server/management-api.ts +4 -3
- package/gui/dist/assets/index-DbIT5GLo.css +0 -1
|
@@ -30,11 +30,11 @@ v1: 经典单线程代理。所有模型使用 v1 协作界面。
|
|
|
30
30
|
base: 上游默认值 — sol/terra 使用 v2,luna 使用 v1,其余跟随 codex 功能标志。
|
|
31
31
|
v2: 多线程代理(spawn_agent)。所有模型使用 v2 协作界面。
|
|
32
32
|
|
|
33
|
-
更改在新会话中生效。`,"models.v2DocsLink":`v1 / v2 是什么?`,"dash.multiAgent":`子代理`,"models.v2Conflict":`[agents] max_threads 仍存在 — codex 将拒绝启动,请从 config.toml 移除`,"models.v2Applied":`multi_agent_v2 已更新 — 新会话生效(重启 Codex 应用以刷新选择器)`,"models.v2ThreadsLabel":`最大线程`,"models.v2ThreadsDefault":`默认 (4)`,"models.v2ThreadsApplied":`线程上限已更新 — 新会话生效`,"models.v2ThreadsInvalid":`线程上限必须为 >= 1 的整数`,"models.v2ThreadsApply":`应用`,"models.capValue":`限制 {value}`,"models.contextCappedValue":`{value} 限制`,"models.setAll":`全部设置`,"models.custom":`自定义…`,"models.customApply":`应用`,"models.customPlaceholder":`令牌 (例如 420000)`,"models.applied":`已应用 — 将在下一个 Codex 回合生效。`,"models.saveFailed":`保存失败`,"models.networkError":`网络错误 — 代理在运行吗?`,"models.loadFail":`加载模型失败 — 代理在运行吗?`,"models.noRouted":`没有已路由的模型`,"models.noRoutedHint":`请先登录提供方或添加一个。`,"models.loading":`加载中…`,"models.search":`搜索模型…`,"models.showMore":`再显示 {n} 个`,"models.allowlistLabel":`仅所选`,"models.allowlistHint":`仅勾选的模型进入目录(留空 = 全部)。适用于暴露成千上万模型的提供商。`,"models.selectedCount":`已选 {n} 个`,"models.orderHint":`选择器顺序:Subagents 中的选择(按所选顺序)→ 其余已路由模型(依次按提供方、模型 ID 字母排序)→ 原生模型。可见性开关仅用于筛选,不会改变此顺序。`,"sub.subtitle":`Codex 的 {cmd} 仅将优先级最高的前 5 个模型作为覆盖项公开。在此最多选择 5 个 — 原生 gpt 或已路由模型 — opencodex 会设置它们的目录优先级,使其正好排在前面。其他模型仍可按确切名称调用;此设置仅控制显示项。`,"sub.featured":`精选`,"sub.orderHint":`此处所选并显示的顺序决定 Codex 模型选择器顶部第 1–5 位,以及 {cmd} 的默认模型候选。`,"sub.noneSelected":`未选择 — 请从下方列表选择。`,"sub.models":`模型`,"sub.search":`搜索模型(原生 gpt + 已路由)…`,"sub.noModels":`没有模型 — 请先登录提供方或添加一个。`,"sub.saved":`已保存 {n} 个模型。启动新的 Codex 会话(或运行 {cmd})以将它们作为 spawn_agent 覆盖项查看。`,"sub.saveFailed":`保存失败`,"sub.networkError":`网络错误 — 代理在运行吗?`,"sub.loadFail":`加载模型失败 — 代理在运行吗?`,"sub.loading":`加载中…`,"sub.moveUp":`上移 {m}`,"sub.moveDown":`下移 {m}`,"sub.removeAria":`移除 {m}`,"logs.title":`请求日志`,"logs.subtitle":`经过本地 opencodex 代理的最近请求,最新在前。`,"logs.autoRefresh":`自动刷新`,"logs.noRequests":`暂无请求。`,"logs.filter.surface.label":`界面`,"logs.filter.surface.all":`全部`,"logs.filter.surface.claude":`Claude`,"logs.filter.surface.codex":`Codex`,"logs.badge.claude":`Claude`,"logs.col.time":`时间`,"logs.col.request":`请求`,"logs.col.model":`模型`,"logs.col.effort":`推理强度`,"logs.col.provider":`提供方`,"logs.col.status":`状态`,"logs.col.tokens":`Token 数`,"logs.col.error":`错误`,"logs.col.upstreamReason":`上游原因`,"logs.col.duration":`耗时`,"logs.tokens.reported":`已上报`,"logs.tokens.unreported":`未上报`,"logs.tokens.unsupported":`不支持`,"logs.tokens.estimated":`估算`,"logs.tokens.input":`输入`,"logs.tokens.output":`输出`,"logs.tokens.cacheRead":`缓存命中 (c)`,"logs.tokens.cacheWrite":`缓存写入 (w)`,"logs.tokens.reasoning":`推理`,"logs.tokens.noCache":`无缓存数据`,"logs.tokens.noCacheNote":`该提供商不报告缓存 token 数`,"logs.tokens.estimatedNote":`估算值(提供商不报告精确用量)`,"logs.details":`查看详情`,"logs.detailTitle":`请求详情`,"logs.detailRaw":`原始日志`,"debug.title":`调试`,"debug.subtitle":`可选的 provider transport 与 usage 提取诊断。请求错误和 502 在 Logs 页面。`,"debug.debug":`Provider debug`,"debug.usage":`Usage 提取`,"debug.injection":`注入日志`,"debug.claude":`Claude 入站`,"debug.claudeInbound.title":`Claude 入站请求`,"debug.claudeInbound.sub":`显示 Claude Code/Desktop 实际发送的内容(thinking、effort、metadata)— 不保存提示词原文。`,"debug.claudeInbound.empty":`尚未捕获任何请求。开启后从 Claude 发送一条消息试试。`,"debug.claudeInbound.time":`时间`,"debug.claudeInbound.endpoint":`端点`,"debug.claudeInbound.model":`模型`,"debug.claudeInbound.none":`无`,"debug.reset":`清除运行时覆盖`,"debug.refresh":`刷新`,"debug.follow":`跟随滚动`,"debug.streamProvider":`Provider`,"debug.streamUsage":`Usage`,"debug.streamInjection":`Injection`,"debug.loading":`正在加载调试设置…`,"debug.emptyTitle":`调试日志已关闭`,"debug.empty":`请在上方卡片中开启 Provider debug 或 Usage extraction。通过代理发送请求后,诊断行会显示在这里。`,"debug.noLinesTitle":`等待诊断行`,"debug.noLines.provider":`提供商调试已开启,但仅记录传输异常(丢弃或格式错误的帧,以及 Cursor dial/retry 事件)。通过 Anthropic 等提供商的正常请求可能不会产生任何行。`,"debug.noLines.usage":`用量提取已开启但尚未捕获任何内容。请通过 Codex 发送请求,随后会显示在此处。`,"debug.noLines.injection":`注入日志已开启但尚未捕获任何内容。它记录协作和子代理回合中的多代理指导注入与 effort-cap 决策。`,"usage.title":`用量`,"usage.subtitle":`代理本地的 Token 用量统计。缺失的用量不会显示为零。`,"usage.loading":`正在加载用量数据…`,"usage.empty":`尚无用量记录。通过代理发送请求后将在此显示。`,"usage.range.all":`全部`,"usage.range.30d":`30 天`,"usage.range.7d":`7 天`,"usage.card.requests":`请求数`,"usage.card.measured":`已计量`,"usage.card.reported":`已上报`,"usage.card.totalTokens":`Token 总数`,"usage.card.cachedTokens":`缓存命中 Token`,"usage.card.cachedTokensHint":`从提供商缓存读取的提示 Token(命中)。缓存写入在下方单独显示。`,"usage.card.cacheWriteTokens":`缓存写入`,"usage.card.coverage":`覆盖率`,"usage.card.activeDays":`活跃天数`,"usage.section.heatmap":`每日活动`,"usage.section.models":`模型`,"usage.section.providers":`提供方`,"usage.section.coverage":`覆盖率明细`,"usage.coverage.measured":`已计量`,"usage.coverage.reported":`提供方上报`,"usage.coverage.estimated":`估算`,"usage.coverage.note":`已计量包含提供方上报和估算的 Token 数。未上报 / 不支持请求仅做计数,不会被算作 0 Token。`,"usage.search.models":`搜索模型…`,"usage.col.requests":`请求数`,"usage.col.measured":`已计量`,"usage.col.reported":`已上报`,"usage.col.tokens":`Token 数`,"usage.col.share":`占比`,"usage.heatmap.less":`少`,"usage.heatmap.more":`多`,"modal.addNamed":`添加:{label}`,"modal.add":`添加提供方`,"modal.search":`搜索提供方…`,"modal.logInWith":`使用 {label} 登录`,"modal.waitingBrowser":`等待浏览器…`,"modal.providerName":`提供方名称`,"modal.adapter":`适配器`,"modal.baseUrl":`Base URL`,"modal.defaultModel":`默认模型(可选)`,"modal.nameRequired":`提供方名称为必填项`,"modal.baseUrlRequired":`Base URL 为必填项`,"modal.networkError":`网络错误 — 代理在运行吗?`,"modal.loginFailStart":`登录启动失败`,"modal.waitingLogin":`等待浏览器登录…`,"modal.loggingIn":`登录中…`,"modal.loginTimeout":`登录超时 — 请重试。`,"nav.api":`API`,"nav.codexAuth":`Codex 认证`,"nav.openMenu":`打开菜单`,"nav.closeMenu":`关闭菜单`,"codexAuth.mainAccount":`主账号`,"codexAuth.appLogin":`应用登录`,"codexAuth.accountPool":`账号池`,"codexAuth.add":`添加`,"codexAuth.refreshQuota":`刷新额度`,"codexAuth.refreshingQuota":`刷新中...`,"codexAuth.quotaRefreshed":`额度已刷新`,"codexAuth.quotaRefreshFailed":`额度刷新失败`,"codexAuth.noPool":`尚未添加池账号。`,"codexAuth.weekly":`每周`,"codexAuth.fiveHour":`5h`,"codexAuth.monthly":`30天`,"codexAuth.resets":`重置`,"codexAuth.today":`今天`,"codexAuth.current":`当前`,"codexAuth.nextSession":`下次会话`,"codexAuth.switchTitle":`切换活跃账号?`,"codexAuth.switchDesc":`从下次 Codex 会话开始生效。当前会话保持现有账号。`,"codexAuth.cacheWarning":`切换账号会重置提示缓存。新会话从空缓存开始。`,"codexAuth.setAsNext":`设为下次会话`,"codexAuth.cancel":`取消`,"codexAuth.switchBack":`切换回主账号?`,"codexAuth.switchBackDesc":`下次 Codex 会话将使用应用登录账号。`,"codexAuth.autoSwitch":`超过 80% 时自动切换`,"codexAuth.autoSwitchDesc":`新会话会在相关额度窗口达到阈值时切换;Go/Free 只使用 30天`,"codexAuth.switched":`下次会话将使用 {email}`,"codexAuth.removeConfirm":`删除 {id}?`,"codexAuth.addTitle":`添加 Codex 账号`,"codexAuth.addIdLabel":`账号 ID(标识符)`,"codexAuth.addJsonLabel":`auth.json 内容`,"codexAuth.addHelp":`从另一台机器的 ~/.codex/auth.json 复制,或使用 codex-auth export。`,"codexAuth.importBtn":`导入`,"codexAuth.importInvalidJson":`无效的 JSON`,"codexAuth.importMissingTokens":`JSON 中缺少 access_token 或 refresh_token`,"codexAuth.importMissingId":`请输入账号 ID`,"codexAuth.accountAdded":`账号已添加到池中`,"codexAuth.addPickDesc":`使用另一个 ChatGPT 账号登录以添加到池中。`,"codexAuth.oauthLogin":`OAuth 登录`,"codexAuth.oauthDesc":`在浏览器中打开 ChatGPT 登录`,"codexAuth.importAuthJson":`导入 auth.json`,"codexAuth.importAuthJsonDesc":`从另一个 Codex 安装或 codex-auth 导出`,"codexAuth.back":`返回`,"codexAuth.oauthAlreadyInProgress":`登录已在进行中。请在浏览器中完成。`,"codexAuth.oauthWaiting":`等待浏览器中完成 ChatGPT 登录...`,"codexAuth.copyLoginLink":`复制登录链接`,"codexAuth.loginLinkCopied":`登录链接已复制`,"codexAuth.loginLinkCopyFailed":`无法复制登录链接。`,"codexAuth.oauthCancelled":`登录已取消。`,"codexAuth.needsReauth":`重新登录`,"codexAuth.tokenExpired":`令牌已过期 — 重新添加此账号以刷新`,"codexAuth.emailCollision":`此账号与您的主 Codex 登录相同。请使用其他账号。`,"codexAuth.resetCreditsTitle":`重置额度`,"codexAuth.resetCreditsAvailable":`您有 {count} 个可用重置额度。`,"codexAuth.resetCreditsDesc":`每个额度可立即重置您当前的小时和每周使用限制。`,"codexAuth.noResetCredits":`没有可用的重置额度。`,"codexAuth.earnCreditsHint":`额度每月自动发放,也可通过推荐计划获得。`,"codexAuth.creditsExpireNote":`额度在获得后 30 天过期。`,"codexAuth.useOneCredit":`使用 1 个额度`,"codexAuth.confirmResetTitle":`使用重置额度?`,"codexAuth.confirmResetDesc":`这将立即重置您当前的使用限制。剩余额度:{count} 个。`,"codexAuth.irreversible":`此操作不可撤销。`,"codexAuth.useCredit":`使用额度`,"codexAuth.redeeming":`重置中...`,"codexAuth.resetSuccess":`使用限制已重置!剩余额度:{remaining} 个。`,"codexAuth.resetNothingToReset":`当前没有需要重置的使用窗口。`,"codexAuth.resetNoCredit":`没有可用的重置额度。`,"codexAuth.resetError":`重置额度使用失败,请重试。`,"codexAuth.fifoNote":`最早获得的额度优先使用。`,"codexAuth.confirmWhichCredit":`将使用 {date} 获得的额度。`,"codexAuth.creditNext":`即将使用`,"codexAuth.creditLabel":`额度 #{n}`,"codexAuth.creditNextBadge":`NEXT`,"codexAuth.creditGranted":`获得 {date}`,"codexAuth.creditExpires":`过期 {date}(剩余 {days} 天)`,"api.title":`API 访问`,"api.subtitle":`使用生成的 API 密钥从外部应用访问 opencodex 代理。通过 {authHeader} 或 {altHeader} 请求头进行认证。`,"api.endpoint":`端点`,"api.endpointNote":`兼容 OpenAI Responses API 格式。`,"api.newKeyTitle":`已创建新密钥`,"api.newKeyNote":`请立即复制此密钥,它不会再次显示。`,"api.copy":`复制`,"api.copied":`已复制`,"api.dismiss":`关闭`,"api.generateTitle":`生成密钥`,"api.keyNamePlaceholder":`密钥名称(可选)`,"api.generate":`生成`,"api.generating":`创建中…`,"api.activeKeys":`活跃密钥({count})`,"api.noKeys":`还没有 API 密钥。请在上方生成一个。`,"api.colName":`名称`,"api.colKey":`密钥`,"api.colCreated":`创建时间`,"api.confirm":`确认`,"api.deleteAria":`删除 API 密钥`,"api.usageTitle":`使用示例`,"nav.claude":`Claude`,"claude.subtitle":`在 Claude Code 中使用 GPT、Gemini 等其他模型。`,"claude.enabledLabel":`Claude 连接`,"claude.enabledHint":`关闭后 Claude Code 无法使用此代理。`,"claude.authMode":`认证模式`,"claude.authModeHint":`Subscription 需要 Claude 账户,Proxy 无需 Anthropic 账户即可使用`,"claude.authModeSubscription":`Subscription(Claude 账户)`,"claude.authModeProxy":`Proxy(无需账户)`,"claude.systemEnv":`自动连接`,"claude.systemEnvDesc":`开启后,在任意终端运行 claude 会自动通过代理。`,"claude.systemEnvWarn":`⚠ 需要完全退出并重新打开终端应用才能生效。不推荐使用。`,"claude.fastMode":`Fast Mode (OpenAI)`,"claude.fastModeDesc":`控制 OpenAI 模型的推理速度。ON = 优先级(更快)。OFF = 默认速度。Auto = 透传客户端设置。`,"claude.fastAuto":`Auto`,"claude.fastOn":`ON`,"claude.fastOff":`OFF`,"claude.autoContext":`自动利用大上下文`,"claude.autoContextDesc":`决定 1M 标记的范围。开:所有超过 20 万 token 的模型(GPT 系列等)都有大上下文条目;关:仅真正的 1M 模型有。`,"claude.autoContextInert":`配置文件中存在旧式上下文大小值(maxContextTokens),此功能暂不生效。删除该值即可恢复。`,"claude.autoCompactWindow":`自动摘要触发点`,"claude.autoCompactDefault":`350k(默认)`,"claude.autoCompactWindowDesc":`对话达到该点时自动摘要旧内容。不会超过各模型自身上限,因此 200k 模型不受影响。`,"claude.autoCompactWindowWarn":`修改该值可能导致 GPT 模型异常——若超过模型真实上限,会在摘要触发前报错。`,"claude.injectAgents":`自动注册子代理`,"claude.injectAgentsDesc":`将“子代理”页选中的模型(以及当前默认模型)注册为 Claude Code 可派遣的代理(ocx-*)。从下一个会话开始生效。`,"claude.webSearchSidecar":`网页搜索附属服务覆盖`,"claude.webSearchSidecarHint":`仅对 Claude Code 请求覆盖主网页搜索附属服务设置。`,"claude.visionSidecar":`视觉附属服务覆盖`,"claude.visionSidecarHint":`仅对 Claude Code 请求覆盖主视觉附属服务设置。`,"claude.useMainSetting":`使用主设置`,"claude.sidecarModelPlaceholder":`主设置中的模型`,"claude.quickstart":`开始使用`,"claude.quickstartHint":`{cmd} 通过代理打开 Claude Code。你的 claude.ai 登录保持不变。`,"claude.manualEnv":`手动配置(高级)`,"claude.smallFastModel":`后台辅助模型`,"claude.smallFastModelHint":`Claude Code 用于对话摘要、主题识别等后台工作的模型。子代理的 haiku 别名也使用它。留空 = Claude 默认(Haiku)。`,"claude.slotUnset":`使用 Claude 默认值`,"claude.modelMap":`模型拦截`,"claude.modelMapHint":`拦截对特定模型的请求并重定向到你指定的模型。默认为空——添加规则后才生效。`,"claude.mapFrom":`原始模型(如 claude-sonnet-4-5)`,"claude.mapTo":`替换为(如 gemini/gemini-3-pro)`,"claude.addMapping":`添加规则`,"claude.removeMapping":`删除规则`,"claude.aliases":`可用模型`,"claude.aliasesHint":`Claude Code 的 /model 菜单中显示的模型列表。`,"claude.loading":`加载中…`,"claude.loadFail":`加载 Claude 设置失败`,"claude.saved":`已保存。`,"claude.saveFailed":`保存失败`,"claude.networkError":`网络错误 — 代理是否在运行?`,"claude.toggleAria":`切换 Claude 连接`,"claude.none":`无`}},ve=[{code:`en`,name:`English`,htmlLang:`en`},{code:`de`,name:`Deutsch`,htmlLang:`de`},{code:`ko`,name:`한국어`,htmlLang:`ko`},{code:`zh`,name:`中文`,htmlLang:`zh-CN`}],ye=`ocx-lang`;function be(){try{let e=localStorage.getItem(ye);if(e===`en`||e===`de`||e===`ko`||e===`zh`)return e}catch{}let e=typeof navigator<`u`?navigator.language.toLowerCase():`en`;return e.startsWith(`de`)?`de`:e.startsWith(`ko`)?`ko`:e.startsWith(`zh`)?`zh`:`en`}var xe=(0,_.createContext)(null);function Se(e,t){if(!t)return e;let n=e;for(let e of Object.keys(t))n=n.split(`{${e}}`).join(String(t[e]));return n}function Ce(){let e=(0,_.useContext)(xe);if(!e)throw Error(`useI18n must be used within LanguageProvider`);return e}function we(){return Ce().t}function Te({children:e}){let[t,n]=(0,_.useState)(be);return(0,_.useEffect)(()=>{let e=ve.find(e=>e.code===t)??ve[0];document.documentElement.lang=e.htmlLang;try{localStorage.setItem(`ocx-lang`,t)}catch{}},[t]),(0,S.jsx)(xe.Provider,{value:{locale:t,setLocale:n,t:(e,n)=>Se(_e[t][e]??ge[e]??e,n)},children:e})}function Ee({k:e,cmd:t,vars:n}){let{t:r}=Ce(),[i,a=``]=r(e,n).split(`{cmd}`);return(0,S.jsxs)(S.Fragment,{children:[i,(0,S.jsx)(`code`,{className:`chip`,children:t}),a]})}var De={ko:[{v:0x2386f26fc10000,s:`경`},{v:0xe8d4a51000,s:`조`},{v:1e8,s:`억`},{v:1e4,s:`만`}],zh:[{v:0x2386f26fc10000,s:`京`},{v:0xe8d4a51000,s:`兆`},{v:1e8,s:`亿`},{v:1e4,s:`万`}]};function Oe(e){return e.replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function ke(e,t){let n=De[t];if(n){for(let t of n)if(e>=t.v)return`${Oe((e/t.v).toFixed(1))}${t.s}`;return String(e)}return e<1e4?String(e):e<1e6?`${Oe((e/1e3).toFixed(1))}K`:e<1e9?`${Oe((e/1e6).toFixed(1))}M`:e<0xe8d4a51000?`${Oe((e/1e9).toFixed(1))}B`:`${Oe((e/0xe8d4a51000).toFixed(1))}T`}function Ae({on:e,onClick:t,disabled:n,label:r}){return(0,S.jsx)(`button`,{type:`button`,className:`switch${e?` on`:``}`,onClick:t,disabled:n,"aria-pressed":e,"aria-label":r??(e?`enabled`:`disabled`),children:(0,S.jsx)(`span`,{className:`knob`})})}function je({tone:e,children:t}){return(0,S.jsxs)(`div`,{className:`notice ${e===`ok`?`notice-ok`:`notice-err`}`,role:`status`,children:[e===`ok`?(0,S.jsx)(O,{}):(0,S.jsx)(j,{}),(0,S.jsx)(`span`,{children:t})]})}function Me({value:e,options:t,onChange:n,disabled:r,label:i,style:a,align:o,placement:s,dropdownStyle:c}){let[l,u]=(0,_.useState)(!1),d=(0,_.useRef)(null),f=t.find(t=>t.value===e);return(0,_.useEffect)(()=>{if(!l)return;let e=e=>{d.current&&!d.current.contains(e.target)&&u(!1)},t=e=>{e.key===`Escape`&&u(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[l]),(0,S.jsxs)(`div`,{ref:d,className:`custom-select`,style:{position:`relative`,display:`inline-block`,...a},children:[(0,S.jsxs)(`button`,{type:`button`,className:`select-trigger`,onClick:()=>!r&&u(e=>!e),disabled:r,"aria-haspopup":`listbox`,"aria-expanded":l,"aria-label":i,children:[(0,S.jsx)(`span`,{children:f?.label??e}),(0,S.jsx)(P,{style:{width:12,height:12,color:`var(--muted)`,transform:l?`rotate(90deg)`:`none`,transition:`transform .12s`}})]}),l&&(0,S.jsx)(`div`,{className:`select-dropdown${o===`right`?` select-dropdown-right`:``}${s===`right`?` select-dropdown-beside`:``}`,role:`listbox`,"aria-label":i,style:c,children:t.map(t=>(0,S.jsx)(`button`,{type:`button`,role:`option`,"aria-selected":t.value===e,className:`select-option${t.value===e?` active`:``}`,onClick:()=>{n(t.value),u(!1)},children:t.label},t.value))})]})}function Ne({icon:e,title:t,children:n,className:r,style:i}){return(0,S.jsxs)(`div`,{className:r?`empty ${r}`:`empty`,style:i,children:[e,(0,S.jsx)(`div`,{className:`title`,children:t}),n&&(0,S.jsx)(`div`,{style:{fontSize:13},children:n})]})}var Pe=[`low`,`medium`,`high`,`xhigh`],Fe=2,Ie=800;function Le(e){return e?.includes(`-preview.`)?`preview`:`latest`}function Re(e,t){switch(e){case`source_checkout`:return t(`dash.updateReason.source_checkout`);case`latest_unavailable`:return t(`dash.updateReason.latest_unavailable`);case`already_latest`:return t(`dash.updateReason.already_latest`);default:return t(`dash.updateReason.unknown`)}}function ze({apiBase:e}){let{locale:t,t:n}=Ce(),[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)([]),[s,c]=(0,_.useState)([]),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(null),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(!1),[x,C]=(0,_.useState)(!1),[w,T]=(0,_.useState)(!1),[ee,te]=(0,_.useState)(!1),[E,ne]=(0,_.useState)(!1),[re,D]=(0,_.useState)(`default`),[O,ae]=(0,_.useState)(!1),[A,M]=(0,_.useState)(!1),[se,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(``),[ce,I]=(0,_.useState)(``),[ue,de]=(0,_.useState)([]),[L,fe]=(0,_.useState)([]),[pe,R]=(0,_.useState)(!1),[me,he]=(0,_.useState)(``),[ge,_e]=(0,_.useState)(``),[ve,ye]=(0,_.useState)(!1),[be,xe]=(0,_.useState)(null),[Se,we]=(0,_.useState)(null),[Te,De]=(0,_.useState)([]),[Oe,Ae]=(0,_.useState)(!1),[je,ze]=(0,_.useState)(`latest`),[Be,Ve]=(0,_.useState)(!0),[He,Ue]=(0,_.useState)(!1),We=(0,_.useRef)(0),Ge=(0,_.useRef)(null),Ke=(0,_.useRef)(0),[qe,Je]=(0,_.useState)(null),[Ye,Xe]=(0,_.useState)(null),[Ze,Qe]=(0,_.useState)(null),[$e,et]=(0,_.useState)(!1),[tt,nt]=(0,_.useState)(!1);(0,_.useEffect)(()=>()=>{Ke.current+=1,Ge.current!==null&&(window.clearTimeout(Ge.current),Ge.current=null)},[]),(0,_.useEffect)(()=>{let t=async()=>{try{let[t,n,r,a,s,c]=await Promise.all([fetch(`${e}/healthz`),fetch(`${e}/api/providers`),fetch(`${e}/api/settings`),fetch(`${e}/api/sidecar-settings`),fetch(`${e}/api/shadow-call-settings`),fetch(`${e}/api/usage?range=30d`)]);i(await t.json()),o(await n.json()),u(await r.json()),f(await a.json());try{s.ok&&m(await s.json())}catch{m(null)}try{g(c.ok?await c.json():null)}catch{g(null)}nt(!1);try{let t=await fetch(`${e}/api/v2`);if(t.ok){let e=await t.json();e.multiAgentMode===`v1`||e.multiAgentMode===`v2`?D(e.multiAgentMode):D(`default`)}}catch{}try{let t=await fetch(`${e}/api/injection-model`);if(t.ok){let e=await t.json();F(e.model??``),I(e.effort??``),de(e.efforts??[]),fe(e.available??[])}}catch{}try{let t=await fetch(`${e}/api/effort-caps`);if(t.ok){let e=await t.json();he(e.effortCap??``),_e(e.subagentEffortCap??``)}}catch{}}catch{nt(!0)}};t();let n=setInterval(t,5e3);return()=>clearInterval(n)},[e]),(0,_.useEffect)(()=>{let t=async()=>{try{let t=await fetch(`${e}/api/diagnostics/project-config`);De((t.ok?await t.json():null)?.grouped??[])}catch{De([])}};t();let n=setInterval(()=>void t(),3e4);return()=>clearInterval(n)},[e]);let rt=(0,_.useCallback)(async()=>{T(!0);try{c(await(await fetch(`${e}/api/models`)).json())}catch{}finally{T(!1)}},[e]);(0,_.useEffect)(()=>{if(tt)return;let e=window.setTimeout(()=>{rt()},0);return()=>window.clearTimeout(e)},[tt,rt]),(0,_.useEffect)(()=>{if(!Ze?.id||!Ze.restart)return;let t=!1,n=Ze.latestVersion,r=async()=>{try{let n=await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(Ze.id)}`);if(n.ok){let e=await n.json();if(!t&&e.job&&(Qe(e.job),e.job.status===`failed`)){et(!1);return}}}catch{t||et(!0)}if(n)try{let r=await fetch(`${e}/healthz`,{cache:`no-store`});if(!r.ok)throw Error(`health failed`);let i=await r.json();!t&&i.version===n&&(et(!1),window.location.reload())}catch{t||et(!0)}};r();let i=setInterval(r,1500);return()=>{t=!0,clearInterval(i)}},[e,Ze?.id,Ze?.latestVersion,Ze?.restart]);let it=(0,_.useMemo)(()=>{let e={};for(let t of s)(e[t.provider]??=[]).push(t);return Object.entries(e).sort(([e],[t])=>e.localeCompare(t))},[s]);if(tt)return(0,S.jsx)(Ne,{style:{marginTop:40},icon:(0,S.jsx)(j,{}),title:(0,S.jsx)(`span`,{style:{color:`var(--red)`},children:n(`dash.cannotConnect`)}),children:(0,S.jsx)(Ee,{k:`dash.runStart`,cmd:`ocx start`})});let at=r?.status===`ok`,z=async t=>{if(!d||v)return;let n=(e,t)=>{let n={...e};return t?.model!==void 0&&(n.model=t.model),t?.backend===null?delete n.backend:t?.backend!==void 0&&(n.backend=t.backend),n},r={webSearch:n(d.webSearch,t.webSearch),vision:n(d.vision,t.vision)};y(!0),f(r);try{let n=await fetch(`${e}/api/sidecar-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok)throw Error(`save failed`);let r=await n.json();f({webSearch:r.webSearch,vision:r.vision})}catch{f(d)}finally{y(!1)}};async function ot(t){if(!(!p||x)){C(!0),m({...p,...t});try{await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}finally{C(!1)}}}let st=async t=>{if(!(O||re===t)){ae(!0);try{(await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:t})})).ok&&D(t)}catch{}finally{ae(!1)}}},ct=async()=>{if(!l||ee)return;let t=!l.codexAutoStart;te(!0),u({...l,codexAutoStart:t});try{let n=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({codexAutoStart:t})});if(!n.ok)throw Error(`save failed`);let r=await n.json();u(e=>e&&{...e,codexAutoStart:r.codexAutoStart})}catch{u(e=>e&&{...e,codexAutoStart:!t}),nt(!0)}finally{te(!1)}},lt=async()=>{if(!E){ne(!0),xe(null),we(null);try{let t=await fetch(`${e}/api/sync`,{method:`POST`}),n=await t.json();if(!t.ok)throw Error(`error`in n&&n.error?n.error:`sync failed`);xe(n);let r=n.projectConfigGrouped;r&&De(r)}catch(e){we(e instanceof Error?e.message:String(e))}finally{ne(!1)}}},ut=async(t,n=!1)=>{n&&(We.current=0),Ge.current!==null&&(window.clearTimeout(Ge.current),Ge.current=null);let r=++Ke.current;Ue(!0),Xe(null),Je(null);try{let n=await fetch(`${e}/api/update/check?tag=${t}`),i=await n.json();if(!n.ok)throw Error(`error`in i&&i.error?i.error:`update check failed`);if(r!==Ke.current)return;let a=i;if(Je(a),a.reason===`latest_unavailable`&&We.current<Fe){let e=++We.current;Ge.current=window.setTimeout(()=>{r===Ke.current&&(Ge.current=null,ut(t))},Ie*e);return}a.reason!==`latest_unavailable`&&(We.current=0),Ue(!1)}catch(e){if(r!==Ke.current)return;Xe(e instanceof Error?e.message:String(e)),Ue(!1)}},dt=()=>{Ke.current+=1,Ge.current!==null&&(window.clearTimeout(Ge.current),Ge.current=null),Ue(!1),Ae(!1)},ft=()=>{let e=Le(r?.version);ze(e),Ve(!0),Ae(!0),ut(e,!0)},pt=e=>{ze(e),ut(e,!0)},mt=async()=>{if(qe?.canUpdate){Xe(null);try{let t=await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:je,restart:Be})}),n=await t.json();if(!t.ok||!n.job)throw Error(n.error??`update failed to start`);Qe(n.job),et(!1),dt()}catch(e){Xe(e instanceof Error?e.message:String(e))}}},ht=e=>{switch(e){case`running`:return n(`dash.updateStatus.running`);case`restarting`:return n(`dash.updateStatus.restarting`);case`succeeded`:return n(`dash.updateStatus.succeeded`);case`failed`:return n(`dash.updateStatus.failed`)}};return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`page-head`,children:(0,S.jsx)(`h2`,{children:n(`nav.dashboard`)})}),(0,S.jsx)(`p`,{className:`page-sub`,children:n(`dash.subtitle`)}),(0,S.jsxs)(`div`,{className:`stat-row`,children:[(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsxs)(`div`,{className:`label`,style:{display:`flex`,alignItems:`center`,gap:6},children:[n(`dash.multiAgent`),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{width:24,height:24,minWidth:24,flex:`0 0 24px`,padding:0,borderRadius:999,color:`var(--muted)`},onClick:()=>M(!0),"aria-label":n(`dash.multiAgent`),"aria-haspopup":`dialog`,children:(0,S.jsx)(oe,{width:14,height:14,"aria-hidden":`true`})})]}),(0,S.jsx)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,S.jsx)(`div`,{role:`radiogroup`,"aria-label":n(`dash.multiAgent`),style:{display:`inline-flex`,borderRadius:999,background:`var(--surface-soft, var(--raised))`,padding:3,gap:2},children:[`v1`,`default`,`v2`].map(e=>(0,S.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":re===e,className:`btn btn-sm${re===e?` btn-primary`:` btn-ghost`}`,style:{borderRadius:999,minWidth:36,fontSize:11,padding:`5px 10px`,border:`none`,background:re===e?void 0:`transparent`,color:re===e?void 0:`var(--muted)`},disabled:O,onClick:()=>void st(e),children:e==="default"?`base`:e},e))})})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`label`,children:n(`dash.status`)}),(0,S.jsxs)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,gap:9,color:at?`var(--green)`:`var(--red)`},children:[(0,S.jsx)(`span`,{className:`dot ${at?`dot-green`:`dot-red`}`}),n(at?`dash.online`:`dash.offline`)]})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`label`,children:n(`dash.version`)}),(0,S.jsx)(`div`,{className:`value mono`,children:r?.version??`—`})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`label`,children:n(`dash.uptime`)}),(0,S.jsx)(`div`,{className:`value mono`,children:r?b(r.uptime,t):`—`})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`label`,children:n(`dash.providers`)}),(0,S.jsx)(`div`,{className:`value`,children:a.length})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`label`,children:n(`dash.tokens30d`)}),(0,S.jsx)(`div`,{className:`value mono`,children:h&&h.summary.requests>0?ke(h.summary.totalTokens,t):`—`}),h&&h.summary.requests>0&&(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:12,marginTop:2},children:n(`dash.coverage`).replace(`{pct}`,`${Math.round(h.summary.coverageRatio*100)}%`)})]})]}),Te.length>0&&(0,S.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,style:{marginBottom:24},role:`alert`,children:[(0,S.jsx)(j,{}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{style:{fontWeight:650},children:n(`dash.projectConfigTitle`)}),(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:13,marginTop:4},children:n(`dash.projectConfigHint`)}),(0,S.jsx)(`ul`,{style:{margin:`10px 0 0`,paddingLeft:18,fontSize:13},children:Te.map(e=>(0,S.jsxs)(`li`,{style:{marginBottom:8},children:[(0,S.jsx)(`code`,{children:e.path}),` — `,e.issues.join(`, `),(0,S.jsx)(`div`,{className:`muted`,style:{marginTop:2},children:e.bypass})]},e.path))})]})]}),re!==`v1`&&(0,S.jsx)(`div`,{className:`panel`,style:{marginBottom:24},children:(0,S.jsxs)(`div`,{className:`injection-head`,children:[(0,S.jsxs)(`span`,{className:`injection-label`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[n(`dash.effortCapLabel`),(0,S.jsxs)(`span`,{style:{position:`relative`,display:`inline-flex`},children:[(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{width:22,height:22,minWidth:22,padding:0,borderRadius:999,color:`var(--muted)`},onClick:()=>N(e=>!e),"aria-label":n(`dash.effortCapLabel`),"aria-expanded":se,"aria-haspopup":`dialog`,children:(0,S.jsx)(oe,{width:13,height:13,"aria-hidden":`true`})}),se&&(0,S.jsxs)(`div`,{role:`dialog`,className:`help-popup`,style:{position:`absolute`,top:`calc(100% + 8px)`,left:0,width:`min(360px, calc(100vw - 48px))`,padding:`12px 16px`,border:`1px solid var(--border)`,borderRadius:8,background:`var(--bg)`,boxShadow:`0 8px 24px rgba(0, 0, 0, 0.14)`,color:`var(--text)`,fontSize:13,fontWeight:400,lineHeight:1.5,zIndex:10},children:[(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,style:{position:`absolute`,top:4,right:4,width:24,height:24,minWidth:24},onClick:()=>N(!1),"aria-label":`Close`,children:(0,S.jsx)(ie,{width:14,height:14})}),(0,S.jsx)(`div`,{style:{paddingRight:16},children:n(`dash.effortCapHelp`)})]})]})]}),(0,S.jsx)(Me,{value:me,options:[{value:``,label:n(`dash.effortCapNone`)},...Pe.map(e=>({value:e,label:e}))],onChange:async t=>{if(!ve){ye(!0);try{let n=await fetch(`${e}/api/effort-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({effortCap:t||null})});if(n.ok){let e=await n.json();he(e.effortCap??``),_e(e.subagentEffortCap??``)}}catch{}finally{ye(!1)}}},disabled:ve,label:n(`dash.effortCapLabel`)}),(0,S.jsx)(Me,{value:ge,options:[{value:``,label:n(`dash.effortCapNone`)},...Pe.map(e=>({value:e,label:e}))],onChange:async t=>{if(!ve){ye(!0);try{let n=await fetch(`${e}/api/effort-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({subagentEffortCap:t||null})});if(n.ok){let e=await n.json();he(e.effortCap??``),_e(e.subagentEffortCap??``)}}catch{}finally{ye(!1)}}},disabled:ve,label:n(`dash.subagentEffortCapLabel`)})]})}),(0,S.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,S.jsxs)(`div`,{className:`injection-head`,children:[(0,S.jsx)(`span`,{className:`injection-label`,children:n(`dash.injectionLabel`)}),(0,S.jsx)(Me,{value:P,options:[{value:``,label:n(`dash.injectionNone`)},...L.map(e=>({value:e.namespaced,label:`${e.provider} / ${e.model}`}))],onChange:async t=>{if(!pe){R(!0);try{let n=await fetch(`${e}/api/injection-model`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({model:t||null,effort:ce||null})});if(n.ok){let e=await n.json();F(e.model??``),I(e.effort??``)}}catch{}finally{R(!1)}}},disabled:pe,label:n(`dash.injectionLabel`)}),P&&ue.length>0&&(0,S.jsx)(Me,{value:ce,options:[{value:``,label:n(`dash.injectionEffortNone`)},...ue.map(e=>({value:e,label:e}))],onChange:async t=>{if(!pe){R(!0);try{let n=await fetch(`${e}/api/injection-model`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({model:P||null,effort:t||null})});if(n.ok){let e=await n.json();F(e.model??``),I(e.effort??``)}}catch{}finally{R(!1)}}},disabled:pe,label:n(`dash.injectionEffortLabel`)}),P&&(0,S.jsx)(`span`,{className:`badge badge-green`,style:{fontSize:10},children:n(`dash.injectionActive`)})]}),(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:13,marginTop:6},children:n(`dash.injectionHint`)})]}),(0,S.jsxs)(`div`,{className:`panel maintenance-panel`,style:{marginBottom:24},children:[(0,S.jsxs)(`div`,{className:`spread maintenance-head`,children:[(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{style:{fontWeight:650},children:n(`dash.maintenance`)}),(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:13,marginTop:3},children:n(`dash.maintenanceHint`)})]}),(0,S.jsxs)(`div`,{className:`maintenance-actions`,children:[(0,S.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:lt,disabled:E,children:[(0,S.jsx)(k,{}),` `,n(E?`dash.syncing`:`dash.syncModels`)]}),(0,S.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:ft,disabled:He,children:[(0,S.jsx)(le,{}),` `,n(`dash.checkUpdate`)]})]})]}),be&&(0,S.jsxs)(`div`,{className:`notice notice-ok maintenance-notice`,role:`status`,children:[(0,S.jsx)(k,{}),(0,S.jsxs)(`span`,{children:[n(`dash.syncOk`,{count:be.added}),be.warning?` ${be.warning}`:``,be.staleAppServerHint?` ${n(`dash.syncStaleHint`)}`:``]})]}),Se&&(0,S.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`status`,children:[(0,S.jsx)(j,{}),(0,S.jsx)(`span`,{children:n(`dash.syncFailed`,{error:Se})})]}),Ze&&(0,S.jsxs)(`div`,{className:`notice ${Ze.status===`failed`?`notice-err`:`notice-ok`} maintenance-notice`,role:`status`,children:[Ze.status===`failed`?(0,S.jsx)(j,{}):(0,S.jsx)(k,{}),(0,S.jsxs)(`span`,{children:[ht(Ze.status),Ze.latestVersion?` ${Ze.currentVersion} -> ${Ze.latestVersion}.`:``,$e?` ${n(`dash.updateReconnecting`)}`:``,Ze.error?` ${Ze.error}`:``]})]})]}),(0,S.jsx)(`div`,{className:`panel`,style:{marginBottom:24},children:(0,S.jsxs)(`div`,{className:`spread`,children:[(0,S.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,S.jsx)(`div`,{style:{fontWeight:650},children:n(`dash.codexAutoStart`)}),(0,S.jsx)(`div`,{className:`muted setting-hint`,children:n(`dash.codexAutoStartHint`)})]}),(0,S.jsx)(`button`,{className:`switch ${l?.codexAutoStart??!0?`on`:``}`,onClick:ct,disabled:!l||ee,"aria-label":n(`dash.codexAutoStart`),"aria-pressed":l?.codexAutoStart??!0,children:(0,S.jsx)(`span`,{className:`knob`})})]})}),(0,S.jsx)(`div`,{className:`panel`,style:{marginBottom:12},children:(0,S.jsxs)(`div`,{className:`spread setting-row`,style:{alignItems:`flex-start`},children:[(0,S.jsxs)(`div`,{className:`setting-copy`,style:{flex:1},children:[(0,S.jsx)(`div`,{style:{fontWeight:650},children:n(`dash.webSearchSidecar`)}),(0,S.jsx)(`div`,{className:`muted setting-hint`,children:n(`dash.webSearchSidecarHint`)})]}),(0,S.jsx)(`div`,{className:`setting-controls`,children:(0,S.jsx)(Me,{value:d?.webSearch.model??`gpt-5.6-luna`,options:s.filter(e=>e.provider===`openai`||e.provider===`anthropic`).map(e=>({value:e.id,label:`${e.provider}/${e.id}`})),onChange:e=>{z({webSearch:{model:e,backend:s.find(t=>t.id===e)?.provider===`anthropic`?`anthropic`:`openai`}})},disabled:!d||v,label:n(`dash.sidecarModel`)})})]})}),(0,S.jsx)(`div`,{className:`panel`,style:{marginBottom:24},children:(0,S.jsxs)(`div`,{className:`spread setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-copy`,style:{flex:1},children:[(0,S.jsx)(`div`,{style:{fontWeight:650},children:n(`dash.visionSidecar`)}),(0,S.jsx)(`div`,{className:`muted setting-hint`,children:n(`dash.visionSidecarHint`)})]}),(0,S.jsx)(`div`,{className:`setting-controls`,children:(0,S.jsx)(Me,{value:d?.vision.model??`gpt-5.6-luna`,options:s.filter(e=>e.provider===`openai`||e.provider===`anthropic`).map(e=>({value:e.id,label:`${e.provider}/${e.id}`})),onChange:e=>{z({vision:{model:e,backend:s.find(t=>t.id===e)?.provider===`anthropic`?`anthropic`:`openai`}})},disabled:!d||v,label:n(`dash.sidecarModel`)})})]})}),(0,S.jsx)(`div`,{className:`panel`,style:{marginBottom:12},children:(0,S.jsxs)(`div`,{className:`spread setting-row`,style:{alignItems:`center`},children:[(0,S.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,S.jsx)(`span`,{style:{fontWeight:650},children:n(`dash.shadowCallIntercept`)}),(0,S.jsx)(`span`,{title:n(`dash.shadowCallTooltip`),style:{cursor:`help`,opacity:.5},children:`ⓘ`}),(0,S.jsx)(`code`,{className:`muted`,style:{fontSize:11},children:`⚠ 5.4-mini`})]}),(0,S.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8,alignItems:`center`},children:[(0,S.jsx)(`button`,{className:`switch ${p?.enabled?`on`:``}`,onClick:()=>ot({enabled:!p?.enabled}),disabled:!p||x,"aria-label":n(`dash.shadowCallIntercept`),"aria-pressed":p?.enabled??!1,children:(0,S.jsx)(`span`,{className:`knob`})}),(0,S.jsx)(Me,{value:p?.model??``,options:[{value:``,label:`—`},...s.map(e=>({value:e.id,label:`${e.provider}/${e.id}`}))],onChange:e=>{m(t=>t&&{...t,model:e}),ot({model:e})},disabled:!p||x||!p?.enabled,label:n(`dash.shadowCallModel`)})]})]})}),(0,S.jsxs)(`div`,{className:`h-section`,children:[n(`dash.activeProviders`),` `,(0,S.jsx)(`span`,{className:`count`,children:a.length})]}),a.length===0?(0,S.jsx)(Ne,{title:(0,S.jsx)(Ee,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,S.jsx)(`div`,{className:`tbl-wrap`,children:(0,S.jsxs)(`table`,{className:`tbl`,children:[(0,S.jsx)(`thead`,{children:(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`th`,{children:n(`dash.col.name`)}),(0,S.jsx)(`th`,{children:n(`dash.col.adapter`)}),(0,S.jsx)(`th`,{children:n(`dash.col.baseUrl`)}),(0,S.jsx)(`th`,{children:n(`dash.col.model`)})]})}),(0,S.jsx)(`tbody`,{children:a.map(e=>(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`td`,{style:{fontWeight:600},children:e.name}),(0,S.jsx)(`td`,{children:(0,S.jsx)(`span`,{className:`chip`,children:e.adapter})}),(0,S.jsx)(`td`,{className:`muted mono`,style:{fontSize:12},children:e.baseUrl}),(0,S.jsx)(`td`,{className:`muted`,children:e.defaultModel??`—`})]},e.name))})]})}),(0,S.jsxs)(`div`,{className:`h-section`,children:[n(`dash.availableModels`),` `,(0,S.jsx)(`span`,{className:`count`,children:s.length}),w&&(0,S.jsx)(`span`,{className:`spin`,style:{marginLeft:4}})]}),s.length===0&&!w?(0,S.jsx)(Ne,{title:n(`dash.noModels`)}):(0,S.jsx)(`div`,{className:`stack`,style:{gap:16},children:it.map(([e,t])=>(0,S.jsxs)(`div`,{className:`model-group`,children:[(0,S.jsxs)(`div`,{className:`model-group-head`,children:[e,(0,S.jsx)(`span`,{className:`count`,children:t.length})]}),(0,S.jsx)(`div`,{className:`model-grid`,children:t.map(e=>(0,S.jsx)(`div`,{className:`model-card`,children:(0,S.jsx)(`div`,{className:`id`,children:e.id})},`${e.provider}/${e.id}`))})]},e))}),Oe&&(0,S.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`update-title`,children:(0,S.jsxs)(`div`,{className:`modal-card`,children:[(0,S.jsxs)(`div`,{className:`modal-head`,children:[(0,S.jsx)(`h3`,{id:`update-title`,children:n(`dash.updateTitle`)}),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:dt,"aria-label":n(`common.cancel`),children:(0,S.jsx)(ie,{})})]}),(0,S.jsx)(`div`,{className:`modal-desc`,children:n(`dash.updateDesc`)}),(0,S.jsxs)(`div`,{className:`update-row`,children:[(0,S.jsx)(`label`,{className:`field-label`,htmlFor:`update-channel`,children:n(`dash.updateChannel`)}),(0,S.jsx)(Me,{value:je,options:[{value:`latest`,label:`latest`},{value:`preview`,label:`preview`}],onChange:e=>pt(e),disabled:He,label:n(`dash.updateChannel`)})]}),He&&(0,S.jsx)(Ne,{className:`update-empty`,icon:(0,S.jsx)(`span`,{className:`spin`}),title:n(`dash.updateChecking`)}),Ye&&(0,S.jsxs)(`div`,{className:`notice notice-err`,role:`status`,children:[(0,S.jsx)(j,{}),(0,S.jsx)(`span`,{children:Ye})]}),qe&&!He&&(0,S.jsxs)(`div`,{className:`update-box`,children:[(0,S.jsxs)(`div`,{className:`spread`,children:[(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:12},children:n(`dash.updateInstalled`)}),(0,S.jsx)(`div`,{className:`mono`,children:qe.currentVersion})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:12},children:n(`dash.updateLatest`)}),(0,S.jsx)(`div`,{className:`mono`,children:qe.latestVersion??`—`})]}),(0,S.jsx)(`span`,{className:`badge ${qe.updateAvailable?`badge-green`:`badge-muted`}`,children:qe.updateAvailable?n(`dash.updateAvailable`):n(`dash.updateCurrent`)})]}),(0,S.jsxs)(`div`,{className:`muted update-command`,children:[n(`dash.updateCommand`),` `,(0,S.jsx)(`code`,{className:`chip`,children:qe.command})]}),qe.reason===`source_checkout`&&(0,S.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,S.jsx)(j,{}),` `,n(`dash.updateSource`)]}),qe.reason===`latest_unavailable`&&(0,S.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,S.jsx)(j,{}),` `,n(`dash.updateUnavailable`),(0,S.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:He,onClick:()=>{ut(je,!0)},style:{marginLeft:12},children:[(0,S.jsx)(k,{}),` `,n(`dash.updateRetry`)]})]}),!qe.canUpdate&&qe.reason!==`latest_unavailable`&&qe.reason!==`source_checkout`&&(0,S.jsxs)(`div`,{className:`update-recheck`,children:[(0,S.jsx)(`span`,{className:`muted update-recheck-reason`,children:n(`dash.updateCannotAuto`,{reason:Re(qe.reason,n)})}),(0,S.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:He,onClick:()=>{ut(je,!0)},children:[(0,S.jsx)(k,{}),` `,n(He?`dash.updateChecking`:`dash.updateRecheck`)]})]}),qe.canUpdate&&(0,S.jsxs)(`div`,{className:`spread update-restart`,children:[(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{style:{fontWeight:600},children:n(`dash.updateRestart`)}),(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:12},children:n(`dash.updateRestartHint`)})]}),(0,S.jsx)(`button`,{type:`button`,className:`switch ${Be?`on`:``}`,onClick:()=>Ve(e=>!e),"aria-label":n(`dash.updateRestart`),"aria-pressed":Be,children:(0,S.jsx)(`span`,{className:`knob`})})]})]}),(0,S.jsxs)(`div`,{className:`modal-actions`,children:[(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:dt,children:n(`common.cancel`)}),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:mt,disabled:!qe?.canUpdate||He,children:n(`dash.runUpdate`)})]})]})}),A&&(0,S.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":n(`dash.multiAgent`),onClick:()=>M(!1),onKeyDown:e=>{e.key===`Escape`&&M(!1)},children:(0,S.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,S.jsxs)(`div`,{className:`modal-head`,children:[(0,S.jsx)(`h3`,{children:n(`dash.multiAgent`)}),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>M(!1),"aria-label":`Close`,children:(0,S.jsx)(ie,{})})]}),(0,S.jsx)(`div`,{className:`modal-desc`,style:{whiteSpace:`pre-line`,lineHeight:1.6},children:n(`models.v2Help`)}),(0,S.jsx)(`div`,{style:{marginTop:12},children:(0,S.jsx)(`a`,{href:`https://lidge-jun.github.io/opencodex/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{fontSize:13,color:`var(--accent)`},children:n(`models.v2DocsLink`)})}),(0,S.jsx)(`div`,{className:`modal-actions`,children:(0,S.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>M(!1),children:`OK`})})]})})]})}function Be(e){let t={adapter:e.adapter.trim(),baseUrl:e.baseUrl.trim()};return(e.authMode===`key`||e.authMode===`forward`)&&(t.authMode=e.authMode),e.authMode===`key`&&e.apiKey.trim()&&(t.apiKey=e.apiKey.trim()),e.defaultModel.trim()&&(t.defaultModel=e.defaultModel.trim()),t}var Ve=[{id:`custom`,label:`Custom provider`,adapter:`openai-chat`,baseUrl:``,auth:`key`}];function He({apiBase:e,existingNames:t,onClose:n,onAdded:r}){let[i,a]=(0,_.useState)(``),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(``),[m,h]=(0,_.useState)([]),g=we(),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(``),[C,w]=(0,_.useState)(``),[T,ee]=(0,_.useState)(!1),[te,E]=(0,_.useState)(``),[ne,re]=(0,_.useState)(!0),[D,O]=(0,_.useState)(Ve),ae=(0,_.useRef)(null),k=(0,_.useRef)(!0);(0,_.useEffect)(()=>{ae.current?.focus()},[]),(0,_.useEffect)(()=>()=>{k.current=!1},[]),(0,_.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,_.useEffect)(()=>{fetch(`${e}/api/oauth/providers`).then(e=>e.json()).then(e=>h(e.providers??[])).catch(()=>{})},[e]),(0,_.useEffect)(()=>{fetch(`${e}/api/provider-presets`).then(e=>e.json()).then(e=>{Array.isArray(e.providers)&&e.providers.length>0&&O(e.providers)}).catch(()=>{})},[e]);let A=(0,_.useMemo)(()=>{let e=i.trim().toLowerCase();return e?D.filter(t=>t.label.toLowerCase().includes(e)||t.id.toLowerCase().includes(e)):D},[i,D]),j=e=>{s(e),l({name:e.id===`custom`?``:e.id,adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,apiKey:``,defaultModel:e.defaultModel??``}),p(``),x(``)},oe=()=>{s(null),l(null),p(``),x(``)},M=async()=>{if(!c)return;let t=c.name.trim();if(!t){p(`Provider name is required`);return}if(!c.baseUrl.trim()){p(`Base URL is required`);return}let n=Be(c);d(!0),p(``);try{let i=await fetch(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t,provider:n})});if(!i.ok){p((await i.json().catch(()=>({}))).error||`Failed (${i.status})`);return}r(t)}catch{p(`Network error — is the proxy running?`)}finally{d(!1)}},se=async t=>{y(!0),x(``),w(``),E(``);try{let n=await fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t})}),i=await n.json();if(!k.current)return;if(!n.ok){x(i.error===`unknown oauth provider`?`OAuth login for this provider arrives in the next update — use an API key for now.`:i.error||`Login failed to start`);return}i.url?(window.open(i.url,`_blank`),x(`Waiting for browser login…`)):x(i.instructions||`Logging in…`);for(let n=0;n<100;n++){if(await new Promise(e=>setTimeout(e,2e3)),!k.current)return;let n=await fetch(`${e}/api/oauth/status?provider=${t}`).then(e=>e.json()).catch(()=>null);if(!k.current)return;if(n?.loggedIn){r(t);return}if(n?.error){x(`Login error: ${n.error}`);return}}x(`Login timed out — try again.`)}catch{k.current&&x(`Network error — is the proxy running?`)}finally{k.current&&y(!1)}},N=async t=>{let n=C.trim();if(!(!n||T)){ee(!0),E(``);try{let r=await fetch(`${e}/api/oauth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t,input:n})}),i=await r.json().catch(()=>({}));if(!k.current)return;if(!r.ok){re(!1),E(g(`prov.pasteFail`,{error:i.error||r.statusText}));return}w(``),re(!0),E(g(`prov.pasteOk`))}catch{k.current&&(re(!1),E(g(`prov.pasteFail`,{error:`network error`})))}finally{k.current&&ee(!1)}}},P=c?t.includes(c.name.trim())&&c.name.trim()!==``:!1,F=o?.id===`custom`,ce=c?.authMode===`local`;return(0,S.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Add provider`,className:`modal-overlay`,onClick:n,children:(0,S.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,S.jsxs)(`div`,{className:`modal-head`,children:[(0,S.jsx)(`h3`,{children:o?`Add: ${o.label}`:`Add provider`}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-icon`,"aria-label":`Close`,onClick:n,children:(0,S.jsx)(ie,{})})]}),o?c&&(o.auth===`oauth`&&c.authMode===`oauth`?(0,S.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:13},children:o.note??`Log in with your account — no API key needed.`}),m.includes(o.oauthProvider??``)?(0,S.jsxs)(`button`,{className:`btn btn-primary`,onClick:()=>se(o.oauthProvider),disabled:v,style:{width:`100%`,padding:`12px 16px`,fontSize:14},children:[(0,S.jsx)(ue,{}),v?`Waiting for browser…`:`Log in with ${o.label}`]}):(0,S.jsxs)(`div`,{style:{fontSize:13,color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:[`OAuth login for `,o.label,` arrives in the next update. Use an API key for now.`]}),b&&(0,S.jsx)(`div`,{style:{fontSize:12,color:/error|update|timed/.test(b)?`var(--amber)`:`var(--accent-hover)`},children:b}),v&&(0,S.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6},children:[(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:12},children:g(`prov.pasteRedirectHint`)}),(0,S.jsxs)(`div`,{style:{display:`flex`,gap:8},children:[(0,S.jsx)(`input`,{className:`input`,type:`text`,autoComplete:`off`,spellCheck:!1,value:C,onChange:e=>w(e.target.value),onKeyDown:e=>{e.key===`Enter`&&o.oauthProvider&&(e.preventDefault(),N(o.oauthProvider))},placeholder:g(`prov.pasteRedirect`),"aria-label":g(`prov.pasteRedirect`),disabled:T,style:{flex:1,fontSize:12}}),(0,S.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,disabled:T||!C.trim()||!o.oauthProvider,onClick:()=>o.oauthProvider&&void N(o.oauthProvider),children:g(T?`prov.pasteSubmitting`:`prov.pasteSubmit`)})]}),te&&(0,S.jsx)(`div`,{style:{fontSize:12,color:ne?`var(--accent-hover)`:`var(--amber)`},children:te})]}),(0,S.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,S.jsx)(`button`,{className:`link-btn`,onClick:()=>{l({...c,authMode:`key`}),x(``),w(``),E(``)},children:`Use an API key instead`}),(0,S.jsx)(`div`,{style:{flex:1}}),(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:oe,children:`Back`})]})]}):(0,S.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!F&&!ce&&!o.keyOptional&&o.note&&(0,S.jsxs)(`details`,{className:`setup-guide`,children:[(0,S.jsx)(`summary`,{children:`Setup guide`}),(0,S.jsxs)(`ol`,{style:{margin:`8px 0 0`,paddingLeft:18,fontSize:12,color:`var(--muted)`,lineHeight:1.7},children:[(0,S.jsxs)(`li`,{children:[`Go to `,(0,S.jsxs)(`a`,{href:o.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:[o.label,` dashboard`]}),` and copy your API key`]}),(0,S.jsx)(`li`,{children:`Paste it in the API key field below`}),(0,S.jsx)(`li`,{children:`Click Add provider — models are auto-discovered`})]}),o.note&&(0,S.jsx)(`div`,{style:{fontSize:12,color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:o.note})]}),(0,S.jsx)(Ue,{label:`Provider name`,children:(0,S.jsx)(`input`,{className:`input`,value:c.name,onChange:e=>l({...c,name:e.target.value}),placeholder:`e.g. openrouter`})}),P&&(0,S.jsxs)(`div`,{style:{fontSize:12,color:`var(--amber)`},children:[`Provider "`,c.name.trim(),`" exists and will be overwritten.`]}),(0,S.jsx)(Ue,{label:`Adapter`,children:(0,S.jsx)(`select`,{className:`input`,value:c.adapter,onChange:e=>l({...c,adapter:e.target.value}),children:[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`].map(e=>(0,S.jsx)(`option`,{value:e,children:e},e))})}),(0,S.jsx)(Ue,{label:`Base URL`,children:(0,S.jsx)(`input`,{className:`input`,value:c.baseUrl,onChange:e=>l({...c,baseUrl:e.target.value}),placeholder:`https://...`})}),c.authMode===`forward`?(0,S.jsxs)(`div`,{style:{fontSize:12,color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:[`No key needed — the proxy forwards your `,(0,S.jsx)(`code`,{className:`chip`,children:`codex login`}),` credentials to this provider.`]}):c.authMode===`local`?(0,S.jsx)(`div`,{style:{fontSize:12,color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`,lineHeight:1.55},children:`No API key is stored. This adds Cursor's static public model catalog for Codex, but live Cursor transport and native file/shell execution remain disabled until audited.`}):o.keyOptional?(0,S.jsxs)(`div`,{style:{fontSize:12,color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`,lineHeight:1.6},children:[(0,S.jsx)(`strong`,{children:`Free tier`}),` — `,o.note??`No API key required. Works out of the box.`]}):(0,S.jsxs)(S.Fragment,{children:[o.dashboardUrl&&(0,S.jsxs)(`a`,{href:o.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{fontSize:12,display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,S.jsx)(I,{style:{width:14,height:14}}),`Get your `,o.label,` API key`,(0,S.jsx)(le,{style:{width:13,height:13}})]}),(0,S.jsx)(Ue,{label:`API key`,children:(0,S.jsx)(`input`,{className:`input`,type:`password`,value:c.apiKey,onChange:e=>l({...c,apiKey:e.target.value}),placeholder:`sk-… (or $ENV_VAR)`})})]}),(0,S.jsx)(Ue,{label:`Default model (optional)`,children:(0,S.jsx)(`input`,{className:`input`,value:c.defaultModel,onChange:e=>l({...c,defaultModel:e.target.value}),placeholder:`e.g. gpt-5.5`})}),f&&(0,S.jsx)(`div`,{role:`alert`,style:{fontSize:13,color:`var(--red)`},children:f}),(0,S.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,S.jsx)(`button`,{className:`btn btn-primary`,onClick:M,disabled:u,children:u?`Adding…`:`Add provider`}),o.auth===`oauth`&&(0,S.jsx)(`button`,{className:`link-btn`,onClick:()=>{l({...c,authMode:`oauth`}),p(``)},children:`← Use OAuth login`}),(0,S.jsx)(`div`,{style:{flex:1}}),(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:oe,children:`Back`})]})]})):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`input`,{ref:ae,className:`input`,value:i,onChange:e=>a(e.target.value),placeholder:`Search providers…`}),(0,S.jsxs)(`div`,{style:{marginTop:12,maxHeight:360,overflowY:`auto`,display:`flex`,flexDirection:`column`,gap:6},children:[A.map(e=>(0,S.jsxs)(`button`,{className:`list-row`,onClick:()=>j(e),children:[(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`title`,children:e.label}),(0,S.jsxs)(`div`,{className:`sub`,children:[(0,S.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,S.jsxs)(`div`,{style:{display:`flex`,gap:4,alignItems:`center`,flexShrink:0},children:[e.keyOptional&&(0,S.jsx)(`span`,{className:`badge badge-green`,children:`Free`}),e.auth===`oauth`?(0,S.jsx)(`span`,{className:`badge badge-accent`,children:`OAuth`}):e.auth===`forward`?(0,S.jsx)(`span`,{className:`badge badge-green`,children:`Codex login`}):e.auth===`local`?(0,S.jsx)(`span`,{className:`badge badge-amber`,children:`Local`}):e.keyOptional?null:(0,S.jsx)(`span`,{className:`badge badge-muted`,children:`API key`})]})]},e.id)),A.length===0&&(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:13,padding:8},children:`No match.`})]})]})]})})}function Ue({label:e,children:t}){return(0,S.jsxs)(`label`,{style:{display:`block`},children:[(0,S.jsx)(`span`,{className:`field-label`,children:e}),t]})}function We(e){let t=e?.trim().toLowerCase();return t===`go`||t===`free`}function Ge(e,t){return!e||!We(t)?e:{...e.monthlyPercent===void 0?{}:{monthlyPercent:e.monthlyPercent},...e.monthlyResetAt===void 0?{}:{monthlyResetAt:e.monthlyResetAt},...e.resetCredits===void 0?{}:{resetCredits:e.resetCredits},updatedAt:e.updatedAt}}function Ke({quota:e,plan:t,threshold:n,t:r,className:i}){let a=Ge(e,t);if(!a)return null;let o=[typeof a.fiveHourPercent==`number`?{label:r(`codexAuth.fiveHour`),percent:a.fiveHourPercent,resetAt:a.fiveHourResetAt}:null,typeof a.weeklyPercent==`number`?{label:r(`codexAuth.weekly`),percent:a.weeklyPercent,resetAt:a.weeklyResetAt}:null,typeof a.monthlyPercent==`number`?{label:r(`codexAuth.monthly`),percent:a.monthlyPercent,resetAt:a.monthlyResetAt}:null,...a.customWindows??[]].filter(e=>e!==null);return o.length===0?null:(0,S.jsx)(`div`,{className:`quota-compact${i?` ${i}`:``}`,children:o.map((e,t)=>(0,S.jsx)(qe,{label:e.label,percent:e.percent,resetAt:e.resetAt,threshold:n,t:r},`${e.label}-${t}`))})}function qe({label:e,percent:t,resetAt:n,threshold:r,t:i}){let a=r>0&&t>=r?`bar-amber`:`bar-green`,o=Ye(n,i);return(0,S.jsxs)(`div`,{className:`quota-row`,children:[(0,S.jsx)(`span`,{className:`quota-label`,children:e}),(0,S.jsx)(`span`,{className:`quota-reset-label`,children:i(`codexAuth.resets`)}),(0,S.jsx)(`span`,{className:`quota-reset-day`,children:o.day}),(0,S.jsx)(`span`,{className:`quota-reset-time`,children:o.time}),(0,S.jsx)(`div`,{className:`bar`,children:(0,S.jsx)(`div`,{className:`bar-fill ${a}`,style:{width:`${Je(t)}%`}})}),(0,S.jsxs)(`span`,{className:`quota-val`,children:[Math.round(t),`%`]})]})}function Je(e){return Math.max(0,Math.min(100,Math.round(e)))}function Ye(e,t){if(typeof e!=`number`||!Number.isFinite(e))return{day:``,time:``};let n=e<1e10?e*1e3:e,r=new Date(n),i=new Date,a=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r);return r.getFullYear()===i.getFullYear()&&r.getMonth()===i.getMonth()&&r.getDate()===i.getDate()?{day:t(`codexAuth.today`),time:a}:{day:new Intl.DateTimeFormat(void 0,{month:`numeric`,day:`numeric`}).format(r),time:a}}var Xe={anthropic:`claude-color.svg`,"anthropic-apikey":`claude-color.svg`,"azure-openai":`openai.svg`,chatgpt:`openai.svg`,"cloudflare-ai-gateway":`cloudflare-ai-gateway-color.svg`,cursor:`cursor-color.svg`,deepseek:`deepseek-color.svg`,firepass:`firepass-color.svg`,fireworks:`fireworks-color.svg`,github:`github-copilot-color.svg`,"github-copilot":`copilot-color.svg`,"gitlab-duo":`gitlab-duo-color.svg`,google:`gemini-color.svg`,"google-antigravity":`antigravity-color.svg`,"google-vertex":`gemini-color.svg`,groq:`groq-color.svg`,huggingface:`huggingface-color.svg`,kimi:`kimi-color.svg`,"kimi-code":`kimi-color.svg`,kiro:`kiro-color.svg`,"lm-studio":`lm-studio-color.svg`,mistral:`mistral-color.svg`,moonshot:`moonshot-color.svg`,nvidia:`nvidia-color.svg`,ollama:`ollama-color.svg`,"ollama-cloud":`ollama-color.svg`,openai:`openai.svg`,"openai-apikey":`openai.svg`,"opencode-free":`opencode.svg`,"opencode-go":`opencode.svg`,"opencode-zen":`opencode.svg`,openrouter:`openrouter-color.svg`,qianfan:`qianfan-color.svg`,"qwen-portal":`qwen-portal-color.svg`,"vercel-ai-gateway":`vercel-ai-gateway-color.svg`,vllm:`vllm-color.svg`,xai:`grok-color.svg`,"mimo-free":`xiaomi-color.svg`,xiaomi:`xiaomi-color.svg`};function Ze(e){return Xe[e.toLowerCase()]}function Qe(e){let t=Ze(e);return t?`/provider-icons/${t}`:void 0}var $e={xai:`xAI (Grok)`,anthropic:`Anthropic (Claude)`,kimi:`Kimi (Moonshot)`},et=e=>$e[e]??e;function tt({apiBase:e}){let t=we(),[n,r]=(0,_.useState)(null),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(``),[u,d]=(0,_.useState)(``),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)([]),[g,v]=(0,_.useState)({}),[y,b]=(0,_.useState)({}),[x,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),[ee,te]=(0,_.useState)(``),[E,ne]=(0,_.useState)(!1),[re,D]=(0,_.useState)(``),[O,ie]=(0,_.useState)({}),[k,j]=(0,_.useState)({}),[oe,M]=(0,_.useState)({}),[se,N]=(0,_.useState)(null),[F,I]=(0,_.useState)(``),de=(0,_.useRef)(!0),L=(e,t)=>{d(e),p(t)};(0,_.useEffect)(()=>(de.current=!0,()=>{de.current=!1}),[]);let fe=(0,_.useCallback)(async()=>{try{let t=await(await fetch(`${e}/api/config`)).json();r(t),l(JSON.stringify(t,null,2))}catch{L(t(`prov.loadConfigFail`),!1)}},[e,t]),pe=(0,_.useCallback)(async()=>{try{let t=(await fetch(`${e}/api/oauth/providers`).then(e=>e.json())).providers??[];h(t);let n=await Promise.all(t.map(async t=>[t,await fetch(`${e}/api/oauth/status?provider=${t}`).then(e=>e.json()).catch(()=>({loggedIn:!1}))]));v(Object.fromEntries(n))}catch{}},[e]),R=(0,_.useCallback)(async(t=!1)=>{try{let n=await fetch(`${e}/api/provider-quotas${t?`?refresh=1`:``}`).then(e=>e.json());b(Object.fromEntries((n.reports??[]).map(e=>[e.provider,e])))}catch{b({})}},[e]),me=(0,_.useCallback)(async t=>{let n=await Promise.all(t.map(async t=>{let n=await fetch(`${e}/api/oauth/accounts?provider=${t}`).then(e=>e.json()).catch(()=>null);return[t,{activeAccountId:n?.activeAccountId??null,accounts:n?.accounts??[]}]}));ie(Object.fromEntries(n))},[e]),he=async(n,r)=>{if(r.active)return;let i=await fetch(`${e}/api/oauth/accounts/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:n,accountId:r.id})});i.ok?(L(t(`prov.accountSwitched`,{email:r.email??r.id}),!0),me(Object.keys(O)),pe(),R(!0)):L((await i.json().catch(()=>({}))).error||t(`prov.accountSwitchFail`),!1)},ge=(0,_.useCallback)(async t=>{let n=await Promise.all(t.map(async t=>[t,(await fetch(`${e}/api/providers/keys?name=${encodeURIComponent(t)}`).then(e=>e.json()).catch(()=>null))?.keys??[]]));M(Object.fromEntries(n))},[e]),_e=async(n,r)=>{if(r.active)return;let i=await fetch(`${e}/api/providers/keys/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:n,id:r.id})});i.ok?(L(t(`prov.keySwitched`,{key:r.label??r.masked}),!0),ge(Object.keys(oe)),R(!0)):L((await i.json().catch(()=>({}))).error||t(`prov.keySwitchFail`),!1)},ve=async(n,r)=>{window.confirm(t(`prov.keyRemoveConfirm`,{key:r.label??r.masked}))&&(await fetch(`${e}/api/providers/keys?name=${encodeURIComponent(n)}&id=${encodeURIComponent(r.id)}`,{method:`DELETE`})).ok&&(L(t(`prov.keyRemoved`,{key:r.label??r.masked}),!0),ge(Object.keys(oe)),fe(),R(!0))},ye=async n=>{let r=F.trim();if(!r)return;let i=await fetch(`${e}/api/providers/keys`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:n,key:r})});i.ok?(L(t(`prov.keyAdded`,{name:n}),!0),I(``),N(null),ge(Object.keys(oe).includes(n)?Object.keys(oe):[...Object.keys(oe),n]),fe(),R(!0)):L((await i.json().catch(()=>({}))).error||t(`prov.keyAddFail`),!1)},be=async(n,r)=>{window.confirm(t(`prov.accountRemoveConfirm`,{email:r.email??r.id}))&&(await fetch(`${e}/api/oauth/accounts?provider=${n}&id=${encodeURIComponent(r.id)}`,{method:`DELETE`})).ok&&(L(t(`prov.accountRemoved`,{email:r.email??r.id}),!0),me(Object.keys(O)),pe(),R(!0))};(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{fe(),pe(),R()},0);return()=>window.clearTimeout(e)},[fe,pe,R]);let xe=(0,_.useMemo)(()=>n?Object.entries(n.providers).filter(([,e])=>e.authMode===`oauth`).map(([e])=>e):[],[n]);(0,_.useEffect)(()=>{if(xe.length===0)return;let e=window.setTimeout(()=>{me(xe)},0);return()=>window.clearTimeout(e)},[me,xe]);let Se=(0,_.useMemo)(()=>n?Object.entries(n.providers).filter(([,e])=>e.hasApiKey&&e.authMode!==`oauth`&&e.authMode!==`forward`).map(([e])=>e):[],[n]);(0,_.useEffect)(()=>{if(Se.length===0)return;let e=window.setTimeout(()=>{ge(Se)},0);return()=>window.clearTimeout(e)},[ge,Se]);let Ce=async()=>{try{let n=JSON.parse(c);(await fetch(`${e}/api/config`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)})).ok?(L(t(`prov.saved`),!0),a(!1),fe(),R(!0)):L(t(`prov.saveFailed`),!1)}catch{L(t(`prov.invalidJson`),!1)}},Te=async(n,r=!1)=>{C(n),d(``),T(null),te(``),D(``);try{let i=await fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r?{provider:n,addAccount:!0}:{provider:n})}),a=await i.json();if(!i.ok){L(a.error||t(`prov.loginFailStart`,{provider:et(n)}),!1);return}(a.url||a.instructions)&&T({provider:n,url:a.url,instructions:a.instructions});let o=O[n]?.accounts.length??0;for(let i=0;i<150&&de.current;i++){await new Promise(e=>setTimeout(e,2e3));let i=await fetch(`${e}/api/oauth/status?provider=${n}`).then(e=>e.json()).catch(()=>null);if(i){if(r?(i.accounts?.length??0)>o||i.done===!0&&!i.error:i.loggedIn){v(e=>({...e,[n]:i})),L(t(`prov.loginOk`,{provider:et(n),cmd:`ocx sync`}),!0),T(null),te(``),D(``),fe(),me(Object.keys(O).includes(n)?Object.keys(O):[...Object.keys(O),n]),R(!0);break}if(i.error){v(e=>({...e,[n]:i})),L(t(`prov.loginError`,{provider:et(n),error:i.error}),!1),T(null);break}}}}catch{L(t(`prov.loginRequestFail`,{provider:et(n)}),!1)}finally{de.current&&C(null)}},Ee=async n=>{let r=ee.trim();if(!(!r||E)){ne(!0),D(``);try{let i=await fetch(`${e}/api/oauth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:n,input:r})}),a=await i.json().catch(()=>({}));if(!i.ok){D(t(`prov.pasteFail`,{error:a.error||i.statusText}));return}te(``),D(t(`prov.pasteOk`))}catch{D(t(`prov.pasteFail`,{error:`network error`}))}finally{de.current&&ne(!1)}}},De=async n=>{await fetch(`${e}/api/oauth/logout?provider=${n}`,{method:`POST`}).catch(()=>{}),v(e=>({...e,[n]:{loggedIn:!1}})),L(t(`prov.logoutOk`,{provider:et(n)}),!0),fe(),R(!0)},Oe=async n=>{window.confirm(t(`prov.removeConfirm`,{name:n}))&&((await fetch(`${e}/api/providers?name=${encodeURIComponent(n)}`,{method:`DELETE`})).ok?(L(t(`prov.removed`,{name:n}),!0),fe(),pe(),R(!0)):L(t(`prov.removeFail`,{name:n}),!1))},ke=async(n,r)=>{let i=await fetch(`${e}/api/providers?name=${encodeURIComponent(n)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({disabled:r})});if(i.ok){L(t(r?`prov.disabled`:`prov.enabled`,{name:n}),!0),fe(),pe(),R(!0);return}L((await i.json().catch(()=>({}))).error||t(r?`prov.disableFail`:`prov.enableFail`,{name:n}),!1)};if(!n)return(0,S.jsx)(`div`,{className:`muted`,children:t(`prov.loadingConfig`)});let Ae=Object.entries(n.providers).filter(([e,t])=>t.hasApiKey&&t.authMode!==`oauth`&&t.authMode!==`forward`&&!m.includes(e)).map(([e])=>e);return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{className:`page-head`,children:[(0,S.jsx)(`h2`,{children:t(`nav.providers`)}),(0,S.jsx)(`div`,{className:`row`,children:i?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`button`,{className:`btn btn-primary`,onClick:Ce,children:t(`common.save`)}),(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>{a(!1),l(JSON.stringify(n,null,2))},children:t(`common.cancel`)})]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`button`,{className:`btn btn-primary`,onClick:()=>s(!0),children:[(0,S.jsx)(ae,{}),t(`prov.add`)]}),(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>a(!0),children:t(`prov.editJson`)})]})})]}),(0,S.jsx)(`p`,{className:`page-sub`,children:t(`prov.subtitle`)}),u&&(0,S.jsx)(je,{tone:f?`ok`:`err`,children:u}),(0,S.jsxs)(`div`,{className:`panel panel-accent`,style:{marginBottom:18},children:[(0,S.jsxs)(`div`,{className:`row`,style:{marginBottom:14},children:[(0,S.jsx)(ue,{style:{width:16,height:16,color:`var(--accent)`}}),(0,S.jsx)(`span`,{style:{fontWeight:600},children:t(`prov.accountLogin`)})]}),(0,S.jsxs)(`div`,{className:`oauth-grid`,children:[m.length===0&&Ae.length===0&&(0,S.jsx)(`span`,{className:`muted`,style:{fontSize:13,gridColumn:`1 / -1`},children:t(`prov.noOauth`)}),m.map(e=>{let n=g[e]??{loggedIn:!1},r=x===e,i=Qe(e);return(0,S.jsxs)(`div`,{className:`oauth-row`,children:[(0,S.jsxs)(`span`,{className:`oauth-name`,title:et(e),children:[(0,S.jsx)(`span`,{className:`provider-icon provider-icon-sm`,children:i&&(0,S.jsx)(`img`,{src:i,alt:``,"aria-hidden":`true`})}),(0,S.jsx)(`span`,{className:`oauth-name-text`,children:e})]}),(0,S.jsxs)(`span`,{className:`oauth-status`,children:[(0,S.jsx)(`span`,{className:`dot ${n.loggedIn?`dot-green`:`dot-muted`}`}),n.loggedIn?(0,S.jsx)(`span`,{className:`oauth-email`,style:{color:`var(--green)`},children:n.email??t(`prov.loggedIn`)}):(0,S.jsx)(`span`,{className:`oauth-email muted`,children:t(`prov.notLoggedIn`)})]}),(0,S.jsx)(`span`,{className:`oauth-actions`,children:n.loggedIn?(0,S.jsx)(`button`,{className:`btn btn-ghost btn-sm`,onClick:()=>De(e),children:t(`prov.logout`)}):(0,S.jsx)(`button`,{className:`btn btn-primary btn-sm`,onClick:()=>Te(e),disabled:r,children:r?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`span`,{className:`spin`}),t(`prov.waitingBrowser`)]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(ue,{}),t(`prov.login`)]})})}),w?.provider===e&&(w.url||w.instructions||r)&&(0,S.jsxs)(`span`,{className:`oauth-login-hint muted`,children:[(0,S.jsxs)(`span`,{className:`oauth-login-hint-links`,children:[w.url&&(0,S.jsxs)(`a`,{href:w.url,target:`_blank`,rel:`noreferrer`,className:`link-btn`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,S.jsx)(le,{}),t(`prov.didntOpen`)]}),w.instructions&&(0,S.jsx)(`span`,{children:w.instructions})]}),(0,S.jsxs)(`span`,{className:`oauth-login-paste`,children:[(0,S.jsx)(`input`,{className:`input`,type:`text`,autoComplete:`off`,spellCheck:!1,value:ee,onChange:e=>te(e.target.value),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),Ee(e))},placeholder:t(`prov.pasteRedirect`),"aria-label":t(`prov.pasteRedirect`),disabled:E}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-sm`,type:`button`,disabled:E||!ee.trim(),onClick:()=>void Ee(e),children:t(E?`prov.pasteSubmitting`:`prov.pasteSubmit`)})]}),(0,S.jsx)(`span`,{style:{fontSize:11},children:re||t(`prov.pasteRedirectHint`)})]})]},e)}),Ae.map(e=>{let r=n?.providers[e],i=Qe(e),a=r?.keyOptional===!0&&!r?.hasApiKey;return(0,S.jsxs)(`div`,{className:`oauth-row`,children:[(0,S.jsxs)(`span`,{className:`oauth-name`,title:e,children:[(0,S.jsx)(`span`,{className:`provider-icon provider-icon-sm`,children:i&&(0,S.jsx)(`img`,{src:i,alt:``,"aria-hidden":`true`})}),(0,S.jsx)(`span`,{className:`oauth-name-text`,children:e})]}),(0,S.jsxs)(`span`,{className:`oauth-status`,children:[(0,S.jsx)(`span`,{className:`dot dot-green`}),(0,S.jsx)(`span`,{className:`oauth-email muted`,children:a?`free tier`:t(`prov.hasApiKey`)})]}),(0,S.jsx)(`span`,{className:`oauth-actions`,"aria-hidden":`true`})]},e)})]})]}),i?(0,S.jsx)(`textarea`,{className:`input`,value:c,onChange:e=>l(e.target.value),style:{height:400}}):(0,S.jsxs)(`div`,{className:`stack`,style:{gap:8},children:[(0,S.jsxs)(`div`,{className:`muted`,style:{fontSize:13,marginBottom:4},children:[t(`prov.port`),`: `,(0,S.jsx)(`code`,{className:`chip`,children:n.port}),` · `,t(`prov.default`),`: `,(0,S.jsx)(`code`,{className:`chip`,children:n.defaultProvider})]}),Object.entries(n.providers).map(([e,r])=>{let i=e===n.defaultProvider,a=r.disabled===!0,o=y[e]?.quota??null,s=Qe(e),c=r.authMode===`oauth`?O[e]:void 0,l=r.authMode!==`oauth`&&r.authMode!==`forward`&&r.hasApiKey?oe[e]??[]:[],u=!!c&&c.accounts.length>0||l.length>0,d=k[e]===!0,f=c?.accounts.length??l.length;return(0,S.jsxs)(`div`,{className:`card prov-card${a?` prov-card-disabled`:``}`,children:[(0,S.jsxs)(`div`,{className:`prov-card-main`,children:[(0,S.jsxs)(`div`,{className:`prov-card-info`,children:[s&&(0,S.jsx)(`span`,{className:`provider-icon`,children:(0,S.jsx)(`img`,{src:s,alt:``,"aria-hidden":`true`})}),(0,S.jsxs)(`div`,{className:`prov-card-copy`,children:[(0,S.jsxs)(`div`,{className:`prov-title`,children:[(0,S.jsx)(`span`,{style:{fontWeight:600},children:e}),i&&(0,S.jsx)(`span`,{className:`badge badge-primary`,children:t(`prov.defaultBadge`)}),a?(0,S.jsx)(`span`,{className:`badge badge-muted`,children:t(`prov.disabledBadge`)}):(0,S.jsx)(`span`,{className:`badge badge-green`,children:t(`prov.activeBadge`)}),r.authMode===`oauth`&&(0,S.jsx)(`span`,{className:`badge badge-accent`,children:`oauth`}),r.authMode===`forward`&&(0,S.jsx)(`span`,{className:`badge badge-amber`,children:`passthrough`}),r.keyOptional&&(0,S.jsx)(`span`,{className:`badge badge-green`,children:`Free`})]}),(0,S.jsxs)(`div`,{className:`muted prov-meta`,style:{fontSize:13},children:[(0,S.jsx)(`code`,{className:`chip`,children:r.adapter}),(0,S.jsx)(`span`,{children:r.baseUrl}),r.defaultModel&&(0,S.jsx)(`span`,{children:r.defaultModel}),r.hasApiKey&&(0,S.jsx)(`span`,{children:t(`prov.hasApiKey`)}),r.hasHeaders&&(0,S.jsx)(`span`,{children:t(`prov.hasHeaders`)})]}),r.note&&(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:12,marginTop:4,lineHeight:1.5},children:r.note})]})]}),(0,S.jsxs)(`div`,{className:`provider-actions`,children:[(0,S.jsxs)(`button`,{className:`btn ${a?`btn-primary`:`btn-ghost`} btn-sm`,onClick:()=>ke(e,!a),disabled:i,title:i?t(`prov.defaultCannotDisable`):void 0,"aria-label":t(a?`prov.enableAria`:`prov.disableAria`,{name:e}),children:[i?(0,S.jsx)(ue,{}):(0,S.jsx)(ce,{}),t(a?`prov.enable`:`prov.disable`)]}),(0,S.jsxs)(`button`,{className:`btn btn-danger btn-sm`,onClick:()=>Oe(e),"aria-label":t(`sub.removeAria`,{m:e}),children:[(0,S.jsx)(A,{}),t(`common.remove`)]})]})]}),o&&(0,S.jsx)(Ke,{quota:o,threshold:80,t,className:`provider-quota`}),u&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`button`,{className:`prov-accounts-toggle${d?` open`:``}`,onClick:()=>j(t=>({...t,[e]:!d})),"aria-expanded":d,"aria-label":t(`prov.accountsAria`,{name:e}),children:[t(`prov.accounts`,{n:String(f)}),(0,S.jsx)(`span`,{className:`chev`,children:(0,S.jsx)(P,{})})]}),d&&(0,S.jsxs)(`div`,{className:`prov-accounts-list`,children:[(c?.accounts??[]).map(n=>(0,S.jsxs)(`button`,{className:`prov-account-row${n.active?` active`:``}`,onClick:()=>he(e,n),title:n.active?void 0:t(`prov.accountSwitchTitle`),children:[(0,S.jsx)(`span`,{className:`dot ${n.needsReauth?`dot-amber`:n.active?`dot-green`:`dot-muted`}`}),(0,S.jsx)(`span`,{className:`prov-account-email`,children:n.email??t(`prov.accountNoLabel`,{id:n.id})}),n.needsReauth&&(0,S.jsx)(`span`,{className:`badge badge-amber`,children:t(`prov.accountReauth`)}),n.active&&(0,S.jsx)(`span`,{className:`badge badge-primary`,children:t(`prov.accountActive`)}),(0,S.jsx)(`span`,{className:`prov-account-remove`,role:`button`,"aria-label":t(`prov.accountRemoveAria`,{email:n.email??n.id}),onClick:t=>{t.stopPropagation(),be(e,n)},children:(0,S.jsx)(A,{style:{width:13,height:13}})})]},n.id)),l.map(n=>(0,S.jsxs)(`button`,{className:`prov-account-row${n.active?` active`:``}`,onClick:()=>_e(e,n),title:n.active?void 0:t(`prov.keySwitchTitle`),children:[(0,S.jsx)(`span`,{className:`dot ${n.active?`dot-green`:`dot-muted`}`}),(0,S.jsx)(`span`,{className:`prov-account-email mono`,children:n.label?`${n.label} · ${n.masked}`:n.masked}),n.active&&(0,S.jsx)(`span`,{className:`badge badge-primary`,children:t(`prov.accountActive`)}),(0,S.jsx)(`span`,{className:`prov-account-remove`,role:`button`,"aria-label":t(`prov.keyRemoveAria`,{key:n.label??n.masked}),onClick:t=>{t.stopPropagation(),ve(e,n)},children:(0,S.jsx)(A,{style:{width:13,height:13}})})]},n.id)),c?(0,S.jsx)(`button`,{className:`prov-account-row prov-account-add`,onClick:()=>Te(e,!0),disabled:x===e,children:x===e?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`span`,{className:`spin`}),t(`prov.waitingBrowser`)]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(ae,{style:{width:13,height:13}}),t(`prov.accountAdd`)]})}):se===e?(0,S.jsxs)(`div`,{className:`prov-account-row prov-account-keyform`,children:[(0,S.jsx)(`input`,{className:`input input-sm mono`,type:`password`,autoFocus:!0,placeholder:t(`prov.keyPlaceholder`),value:F,onChange:e=>I(e.target.value),onKeyDown:t=>{t.key===`Enter`&&ye(e),t.key===`Escape`&&(N(null),I(``))}}),(0,S.jsx)(`button`,{className:`btn btn-primary btn-sm`,onClick:()=>ye(e),disabled:!F.trim(),children:t(`common.save`)}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-sm`,onClick:()=>{N(null),I(``)},children:t(`common.cancel`)})]}):(0,S.jsxs)(`button`,{className:`prov-account-row prov-account-add`,onClick:()=>{N(e),I(``)},children:[(0,S.jsx)(ae,{style:{width:13,height:13}}),t(`prov.keyAdd`)]})]})]})]},e)})]}),o&&(0,S.jsx)(He,{apiBase:e,existingNames:Object.keys(n.providers),onClose:()=>s(!1),onAdded:e=>{s(!1),L(t(`prov.added`,{name:e,cmd:`ocx sync`}),!0),fe(),pe(),R(!0)}})]})}var nt={"gpt-5.6-sol":fe,"gpt-5.6-terra":me,"gpt-5.6-luna":pe},rt={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`,marginRight:4};function it(e){return e.slice(e.lastIndexOf(`/`)+1)}function at(e){return nt[e]??nt[it(e)]??null}function z(e){let t=at(e);return t?(0,_.createElement)(`span`,{style:{display:`inline-flex`,alignItems:`center`,gap:4}},(0,_.createElement)(t,{style:rt}),e):e}var ot=Array.from({length:18},(e,t)=>1e5+t*5e4),st=`custom`,ct=[4,8,16,32,64,128,256,500,1e3],lt=60;function ut(e){return!Number.isFinite(e)||e<=0?String(e):e%1e3==0?`${e/1e3}k`:e.toLocaleString()}function dt({apiBase:e}){let t=we(),[n,r]=(0,_.useState)([]),[i,a]=(0,_.useState)(new Set),[o,s]=(0,_.useState)({}),[c,l]=(0,_.useState)({}),[u,d]=(0,_.useState)({}),[f,p]=(0,_.useState)(35e4),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(()=>{try{let e=localStorage.getItem(`ocx-models-collapsed`);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}}),[x,C]=(0,_.useState)(``),[w,T]=(0,_.useState)(!1),[te,E]=(0,_.useState)(!0),[ne,re]=(0,_.useState)(!1),D=(0,_.useRef)(!1),[O,ie]=(0,_.useState)(null),[ae,k]=(0,_.useState)(!1),[A,j]=(0,_.useState)(``),M=(0,_.useRef)(!1),[se,N]=(0,_.useState)(``),[F,ce]=(0,_.useState)(!1),[le,I]=(0,_.useState)(!1),[ue,de]=(0,_.useState)(null),[L,fe]=(0,_.useState)(!1),pe=(0,_.useCallback)(async()=>{try{let t=await fetch(`${e}/api/shadow-call-settings`);t.ok&&de(await t.json())}catch{}},[e]),R=(0,_.useCallback)(async()=>{if(!M.current)try{let t=await fetch(`${e}/api/v2`);if(!t.ok||!(t.headers.get(`content-type`)??``).includes(`application/json`)){ie(null);return}let n=await t.json();typeof n.enabled==`boolean`&&ie({enabled:n.enabled,agentsMaxThreadsConflict:n.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof n.maxConcurrentThreadsPerSession==`number`?n.maxConcurrentThreadsPerSession:null,multiAgentMode:n.multiAgentMode===`v1`||n.multiAgentMode===`v2`?n.multiAgentMode:`default`})}catch{ie(null)}},[e]),me=(0,_.useCallback)(async()=>{try{let[t,n]=await Promise.all([fetch(`${e}/api/models`).then(e=>e.json()),fetch(`${e}/api/provider-context-caps`).then(e=>e.json())]);R(),pe(),r(t),a(new Set(t.filter(e=>e.disabled).map(e=>e.namespaced)));let i=typeof n.value==`number`&&Number.isFinite(n.value)&&n.value>0?n.value:typeof n.cap==`number`&&Number.isFinite(n.cap)&&n.cap>0?n.cap:void 0;i!==void 0&&p(i),d(n.caps??{})}catch{T(!1),C(t(`models.loadFail`))}finally{E(!1)}},[e,pe,R,t]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{me()},0),t=window.setInterval(()=>{D.current||me()},1e4);return()=>{window.clearTimeout(e),window.clearInterval(t)}},[me]);let he=(0,_.useMemo)(()=>{let e={};for(let t of n)(e[t.provider]??=[]).push(t);return Object.entries(e).sort(([e,t],[n,r])=>{let i=t.every(e=>e.native);return i===r.every(e=>e.native)?e.localeCompare(n):i?-1:1})},[n]),ge=async n=>{re(!0),D.current=!0,C(``);try{(await fetch(`${e}/api/disabled-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:[...n]})})).ok?(a(n),T(!0),C(t(`models.applied`))):(T(!1),C(t(`models.saveFailed`)))}catch{T(!1),C(t(`models.networkError`))}finally{re(!1),D.current=!1}},_e=e=>{let t=new Set(i);t.has(e)?t.delete(e):t.add(e),ge(t)},ve=async n=>{re(!0),D.current=!0,C(``);let r=u[n]!==f;try{let i=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:n,enabled:r})});i.ok?(d((await i.json()).caps??{}),T(!0),C(t(`models.capApplied`)),await me()):(T(!1),C(t(`models.capSaveFailed`)))}catch{T(!1),C(t(`models.networkError`))}finally{re(!1),D.current=!1}},ye=e=>{b(t=>{let n=new Set(t);n.has(e)?n.delete(e):n.add(e);try{localStorage.setItem(`ocx-models-collapsed`,JSON.stringify([...n]))}catch{}return n})},be=async n=>{re(!0),D.current=!0,C(``);try{let r=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(r.ok){let e=await r.json();typeof e.value==`number`&&Number.isFinite(e.value)&&e.value>0&&p(e.value),d(e.caps??{}),T(!0),C(t(`models.capApplied`)),await me()}else T(!1),C(t(`models.capSaveFailed`))}catch{T(!1),C(t(`models.networkError`))}finally{re(!1),D.current=!1}},xe=e=>{!Number.isFinite(e)||e<=0||be({value:Math.floor(e)})},Se=e=>{if(e===st){v(!0),h(String(f));return}v(!1);let t=Number(e);Number.isFinite(t)&&t>0&&t!==f&&xe(t)},Ce=()=>{let e=Number(m.replace(/[_,\s]/g,``));if(!Number.isFinite(e)||e<=0){T(!1),C(t(`models.capSaveFailed`));return}v(!1),xe(e)},Te=(0,_.useMemo)(()=>{let e=he.filter(([,e])=>!e.every(e=>e.native));return e.length>0&&e.every(([e])=>u[e]===f)},[he,u,f]),Ee=()=>{be({setAll:!Te})},De=async t=>{if(!(!ue||L)){fe(!0),de({...ue,...t});try{await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}finally{fe(!1)}}},Oe=async n=>{if(!(!O||M.current)&&O.multiAgentMode!==n){k(!0),M.current=!0,j(``),C(``);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:n})}),i=await r.json().catch(()=>null);r.ok&&i?(R(),T(!0),C(t(`models.v2Applied`)),j((i.warnings??[]).join(` `))):(T(!1),C(i?.error??t(`models.saveFailed`)))}catch{T(!1),C(t(`models.networkError`))}finally{k(!1),M.current=!1}}},ke=async n=>{if(!(!O||M.current)){if(!Number.isInteger(n)||n<1){T(!1),C(t(`models.v2ThreadsInvalid`));return}if(O.maxConcurrentThreadsPerSession!==n){k(!0),M.current=!0,j(``),C(``);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({maxConcurrentThreadsPerSession:n})}),i=await r.json().catch(()=>null);r.ok&&i&&typeof i.enabled==`boolean`?(ie({enabled:i.enabled,agentsMaxThreadsConflict:i.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof i.maxConcurrentThreadsPerSession==`number`?i.maxConcurrentThreadsPerSession:null,multiAgentMode:i.multiAgentMode===`v1`||i.multiAgentMode===`v2`?i.multiAgentMode:`default`}),T(!0),C(t(`models.v2ThreadsApplied`)),ce(!1)):(T(!1),C(i?.error??t(`models.saveFailed`)))}catch{T(!1),C(t(`models.networkError`))}finally{k(!1),M.current=!1}}}},Pe=e=>{if(e===st){ce(!0),N(String(O?.maxConcurrentThreadsPerSession??``));return}ce(!1),ke(Number(e))};return te?(0,S.jsxs)(`div`,{className:`row muted`,children:[(0,S.jsx)(`span`,{className:`spin`}),` `,t(`models.loading`)]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{className:`page-head`,children:[(0,S.jsx)(`h2`,{children:t(`nav.models`)}),(0,S.jsx)(`span`,{className:`muted mono`,style:{fontSize:12},children:t(`models.active`,{active:n.length-i.size,total:n.length})})]}),(0,S.jsx)(`p`,{className:`page-sub`,children:t(`models.subtitle`)}),x&&(0,S.jsx)(je,{tone:w?`ok`:`err`,children:x}),(0,S.jsxs)(`div`,{className:`row muted`,style:{gap:6,marginBottom:8,alignItems:`center`,fontSize:13},children:[(0,S.jsxs)(`span`,{title:t(`models.shadowCallInterceptHint`),style:{cursor:`help`},children:[t(`models.shadowCallIntercept`),` ⓘ`]}),(0,S.jsx)(`code`,{style:{fontSize:11,opacity:.6},children:`⚠ 5.4-mini →`}),(0,S.jsx)(Ae,{on:ue?.enabled??!1,onClick:()=>void De({enabled:!ue?.enabled}),disabled:!ue||L,label:t(`models.shadowCallIntercept`)}),(0,S.jsx)(Me,{value:ue?.model??``,options:[{value:``,label:`—`},...n.filter(e=>!i.has(e.id)&&!i.has(e.namespaced)).map(e=>({value:e.namespaced,label:e.namespaced}))],onChange:e=>{de(t=>t&&{...t,model:e}),De({model:e})},disabled:!ue||L||!ue.enabled,label:t(`models.shadowCallIntercept`)})]}),O&&(0,S.jsxs)(`div`,{className:`row`,style:{gap:8,marginBottom:8,flexWrap:`wrap`,alignItems:`center`},children:[(0,S.jsx)(`span`,{className:`muted`,style:{fontSize:13},children:t(`models.v2Label`)}),(0,S.jsx)(`div`,{className:`segmented`,role:`radiogroup`,"aria-label":t(`models.v2Label`),style:{display:`inline-flex`,borderRadius:999,background:`var(--surface-soft, var(--raised))`,padding:3,gap:2},children:[`v1`,`default`,`v2`].map(e=>(0,S.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(O.multiAgentMode??`default`)===e,className:`btn btn-sm${(O.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{borderRadius:999,minWidth:64,fontSize:12,padding:`5px 12px`,border:`none`,background:(O.multiAgentMode??`default`)===e?void 0:`transparent`,color:(O.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:ae,onClick:()=>void Oe(e),children:t(`models.v2Mode_${e}`)},e))}),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{width:24,height:24,minWidth:24,flex:`0 0 24px`,padding:0,borderRadius:999,color:`var(--muted)`},onClick:()=>I(!0),"aria-label":t(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,S.jsx)(oe,{width:14,height:14,"aria-hidden":`true`})}),O.enabled&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`span`,{className:`muted`,style:{fontSize:13,marginLeft:8},children:t(`models.v2ThreadsLabel`)}),(0,S.jsx)(Me,{value:F?st:O.maxConcurrentThreadsPerSession!==null&&O.maxConcurrentThreadsPerSession!==void 0?ct.includes(O.maxConcurrentThreadsPerSession)?String(O.maxConcurrentThreadsPerSession):st:``,options:[...O.maxConcurrentThreadsPerSession===null||O.maxConcurrentThreadsPerSession===void 0?[{value:``,label:t(`models.v2ThreadsDefault`)}]:[],...O.maxConcurrentThreadsPerSession!==null&&O.maxConcurrentThreadsPerSession!==void 0&&!ct.includes(O.maxConcurrentThreadsPerSession)&&!F?[{value:st,label:String(O.maxConcurrentThreadsPerSession)}]:[],...ct.map(e=>({value:String(e),label:String(e)})),{value:st,label:t(`models.custom`)}],onChange:e=>Pe(e),disabled:ae,label:t(`models.v2ThreadsLabel`)}),F&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:se,onChange:e=>N(e.target.value),onKeyDown:e=>{e.key===`Enter`&&ke(Number(se.replace(/[_,\s]/g,``)))},disabled:ae}),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:ae,onClick:()=>{ke(Number(se.replace(/[_,\s]/g,``)))},children:t(`models.v2ThreadsApply`)})]})]}),O.enabled&&O.agentsMaxThreadsConflict&&(0,S.jsx)(`span`,{className:`mono`,style:{fontSize:12,color:`var(--err, #e5484d)`},children:t(`models.v2Conflict`)}),A&&(0,S.jsx)(`span`,{className:`muted`,style:{fontSize:12},children:A})]}),(0,S.jsxs)(`div`,{className:`row`,style:{gap:8,marginBottom:8,flexWrap:`wrap`},children:[(0,S.jsx)(`span`,{className:`muted`,style:{fontSize:13},children:t(`models.contextCapLabel`)}),(0,S.jsx)(Me,{value:g?st:ot.includes(f)?String(f):st,options:[...!ot.includes(f)&&!g?[{value:String(f),label:ut(f)}]:[],...ot.map(e=>({value:String(e),label:ut(e)})),{value:st,label:t(`models.custom`)}],onChange:e=>Se(e),disabled:ne,label:t(`models.contextCapLabel`)}),g&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:t(`models.customPlaceholder`),value:m,onChange:e=>h(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Ce()},disabled:ne}),(0,S.jsx)(`button`,{onClick:Ce,disabled:ne,className:`btn btn-ghost btn-sm`,children:t(`models.customApply`)})]}),(0,S.jsx)(`div`,{style:{flex:1}}),(0,S.jsx)(Ae,{on:Te,onClick:Ee,disabled:ne,label:t(`models.setAll`)}),(0,S.jsx)(`span`,{className:`muted mono`,style:{fontSize:12},children:t(`models.setAll`)})]}),(0,S.jsxs)(`div`,{className:`row muted`,style:{alignItems:`flex-start`,gap:8,marginBottom:12,maxWidth:`80ch`,fontSize:12.5,lineHeight:1.5},children:[(0,S.jsx)(oe,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,S.jsx)(`span`,{children:t(`models.orderHint`)})]}),he.map(([e,n])=>{let r=y.has(e),a=n.filter(e=>!i.has(e.namespaced)).length,d=u[e]===f,p=n.every(e=>e.native),m=(o[e]??``).trim().toLowerCase(),h=m?n.filter(e=>e.id.toLowerCase().includes(m)):n,g=c[e]??lt,_=h.slice(0,g),v=h.length-_.length,b=n.every(e=>!i.has(e.namespaced)),x=n.every(e=>i.has(e.namespaced)),C=e=>{let t=new Set(i);for(let r of n)e?t.delete(r.namespaced):t.add(r.namespaced);ge(t)};return(0,S.jsxs)(`div`,{className:`card`,style:{marginBottom:8,overflow:`hidden`},children:[(0,S.jsxs)(`div`,{onClick:()=>ye(e),className:`row group-head${r?``:` open`}`,children:[(0,S.jsx)(P,{style:{width:14,height:14,color:`var(--muted)`,transform:r?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,S.jsx)(`span`,{style:{fontWeight:600,fontSize:14},children:e}),p&&(0,S.jsx)(`span`,{className:`muted mono`,style:{fontSize:11,padding:`1px 6px`,border:`1px solid var(--border)`,borderRadius:999},children:t(`models.nativeGroupLabel`)}),(0,S.jsx)(`span`,{className:`muted mono`,style:{fontSize:12},children:t(`models.active`,{active:a,total:n.length})}),(0,S.jsx)(`div`,{style:{flex:1}}),(0,S.jsxs)(`div`,{className:`row`,onClick:e=>e.stopPropagation(),style:{gap:6},children:[(0,S.jsx)(`button`,{className:`btn btn-ghost btn-sm`,disabled:ne||b,onClick:()=>C(!0),style:{fontSize:11,padding:`2px 8px`},children:t(`models.allOn`)}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-sm`,disabled:ne||x,onClick:()=>C(!1),style:{fontSize:11,padding:`2px 8px`},children:t(`models.allOff`)}),!p&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(Ae,{on:d,onClick:()=>ve(e),disabled:ne,label:t(`models.capValue`,{value:ut(f)})}),(0,S.jsx)(`span`,{className:`muted mono`,style:{fontSize:12},children:t(`models.capValue`,{value:ut(f)})})]})]})]}),!r&&(0,S.jsxs)(`div`,{style:{padding:`6px 12px`},children:[p&&(0,S.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`2px 0 6px`},children:t(`models.nativeHint`)}),n.length>lt/2&&(0,S.jsx)(`input`,{className:`input`,style:{width:`100%`,marginBottom:6},placeholder:t(`models.search`),value:o[e]??``,onChange:t=>s(n=>({...n,[e]:t.target.value}))}),_.map(e=>{let n=i.has(e.namespaced);return(0,S.jsxs)(`div`,{className:`row`,style:{padding:`5px 0`},children:[(0,S.jsx)(Ae,{on:!n,onClick:()=>_e(e.namespaced),disabled:ne,label:e.id}),(0,S.jsx)(`code`,{className:`mono`,style:{fontSize:13,color:n?`var(--faint)`:`var(--text)`,textDecoration:n?`line-through`:`none`},children:z(e.id)}),e.contextCapped&&(0,S.jsx)(`span`,{className:`muted mono`,style:{fontSize:11,padding:`1px 6px`,border:`1px solid var(--border)`,borderRadius:999},children:t(`models.contextCappedValue`,{value:ut(e.contextCap??f)})})]},e.namespaced)}),v>0&&(0,S.jsx)(`button`,{onClick:()=>l(t=>({...t,[e]:g+lt})),className:`btn btn-ghost btn-sm`,style:{marginTop:4},children:t(`models.showMore`,{n:v})})]})]},e)}),he.length===0&&(0,S.jsx)(Ne,{icon:(0,S.jsx)(ee,{}),title:t(`models.noRouted`),children:t(`models.noRoutedHint`)}),le&&(0,S.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":t(`models.v2Label`),onClick:()=>I(!1),onKeyDown:e=>{e.key===`Escape`&&I(!1)},children:(0,S.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,S.jsxs)(`div`,{className:`modal-head`,children:[(0,S.jsx)(`h3`,{children:t(`models.v2Label`)}),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>I(!1),"aria-label":`Close`,children:`×`})]}),(0,S.jsx)(`div`,{className:`modal-desc`,style:{whiteSpace:`pre-line`,lineHeight:1.6},children:t(`models.v2Help`)}),(0,S.jsx)(`div`,{style:{marginTop:12},children:(0,S.jsx)(`a`,{href:`https://lidge-jun.github.io/opencodex/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{fontSize:13,color:`var(--accent)`},children:t(`models.v2DocsLink`)})}),(0,S.jsx)(`div`,{className:`modal-actions`,children:(0,S.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>I(!1),children:`OK`})})]})})]})}function ft({apiBase:e}){let t=we(),[n,r]=(0,_.useState)([]),[i,a]=(0,_.useState)([]),[o,s]=(0,_.useState)(``),[c,l]=(0,_.useState)(``),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!0),m=(0,_.useCallback)(async()=>{try{let t=await fetch(`${e}/api/subagent-models`).then(e=>e.json()),n=t.available??[];r(n),a((t.chosen??[]).filter(e=>n.includes(e)))}catch{d(!1),l(t(`sub.loadFail`))}finally{p(!1)}},[e,t]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{m()},0);return()=>window.clearTimeout(e)},[m]);let h=e=>{l(``),a(t=>t.includes(e)?t.filter(t=>t!==e):t.length>=5?t:[...t,e])},g=(e,t)=>{a(n=>{let r=[...n],i=e+t;return i<0||i>=r.length?n:([r[e],r[i]]=[r[i],r[e]],r)})},v=async()=>{l(``);try{let n=await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:i})}),r=await n.json();d(n.ok),l(n.ok?t(`sub.saved`,{n:r.applied?.length??0,cmd:`ocx sync`}):r.error||t(`sub.saveFailed`))}catch{d(!1),l(t(`sub.networkError`))}},y=(0,_.useMemo)(()=>{let e=o.trim().toLowerCase();return n.filter(t=>!e||t.toLowerCase().includes(e))},[n,o]);return f?(0,S.jsx)(`div`,{className:`muted`,style:{padding:8},children:t(`sub.loading`)}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`page-head`,children:(0,S.jsx)(`h2`,{children:t(`nav.subagents`)})}),(0,S.jsx)(`p`,{className:`page-sub`,children:(0,S.jsx)(Ee,{k:`sub.subtitle`,cmd:`spawn_agent`})}),c&&(0,S.jsx)(je,{tone:u?`ok`:`err`,children:c}),(0,S.jsxs)(`div`,{className:`h-section`,children:[t(`sub.featured`),` `,(0,S.jsxs)(`span`,{className:`count`,children:[i.length,`/5`]})]}),(0,S.jsxs)(`div`,{className:`row muted`,style:{alignItems:`flex-start`,gap:8,margin:`-2px 0 10px`,maxWidth:`80ch`,fontSize:12.5,lineHeight:1.5},children:[(0,S.jsx)(oe,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,S.jsx)(`span`,{children:(0,S.jsx)(Ee,{k:`sub.orderHint`,cmd:`spawn_agent`})})]}),i.length===0?(0,S.jsx)(Ne,{title:t(`sub.noneSelected`)}):(0,S.jsx)(`div`,{className:`stack`,style:{gap:8},children:i.map((e,n)=>(0,S.jsxs)(`div`,{className:`card panel-accent row`,style:{padding:`8px 12px`,gap:10},children:[(0,S.jsx)(`span`,{className:`mono`,style:{width:18,color:`var(--accent)`,fontWeight:700},children:n+1}),(0,S.jsx)(`code`,{className:`mono`,style:{flex:1,color:`var(--text)`},children:z(e)}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>g(n,-1),disabled:n===0,"aria-label":t(`sub.moveUp`,{m:e}),children:(0,S.jsx)(se,{})}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>g(n,1),disabled:n===i.length-1,"aria-label":t(`sub.moveDown`,{m:e}),children:(0,S.jsx)(N,{})}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>h(e),"aria-label":t(`sub.removeAria`,{m:e}),style:{color:`var(--red)`},children:(0,S.jsx)(ie,{})})]},e))}),(0,S.jsx)(`div`,{style:{marginTop:14},children:(0,S.jsx)(`button`,{className:`btn btn-primary`,onClick:v,children:t(`common.save`)})}),(0,S.jsxs)(`div`,{className:`h-section`,children:[t(`sub.models`),` `,(0,S.jsx)(`span`,{className:`count`,children:y.length})]}),(0,S.jsxs)(`div`,{style:{position:`relative`,marginBottom:10},children:[(0,S.jsx)(M,{style:{position:`absolute`,left:11,top:`50%`,transform:`translateY(-50%)`,width:15,height:15,color:`var(--faint)`,pointerEvents:`none`}}),(0,S.jsx)(`input`,{className:`input`,value:o,onChange:e=>s(e.target.value),placeholder:t(`sub.search`),style:{paddingLeft:34}})]}),(0,S.jsxs)(`div`,{className:`stack`,style:{gap:6,maxHeight:360,overflowY:`auto`},children:[y.map(e=>{let t=i.includes(e),n=!t&&i.length>=5;return(0,S.jsxs)(`button`,{className:`card row`,onClick:()=>h(e),disabled:n,"aria-pressed":t,style:{padding:`9px 12px`,gap:10,width:`100%`,textAlign:`left`,cursor:n?`not-allowed`:`pointer`,opacity:n?.45:1,background:t?`var(--accent-soft)`:void 0,borderColor:t?`var(--accent-ring)`:void 0},children:[(0,S.jsx)(`span`,{style:{width:16,height:16,flexShrink:0,color:`var(--accent)`,display:`inline-flex`},children:t&&(0,S.jsx)(O,{style:{width:16,height:16}})}),(0,S.jsx)(te,{style:{width:15,height:15,color:`var(--faint)`,flexShrink:0}}),(0,S.jsx)(`code`,{className:`mono`,style:{color:`var(--text)`},children:z(e)})]},e)}),y.length===0&&(0,S.jsx)(Ne,{title:t(`sub.noModels`)})]})]})}var pt=m();function mt(e,t,n){let r=Array(e);return new Proxy(r,{get(r,i,a){if(typeof i==`string`){let a=i.charCodeAt(0);if(a>=48&&a<=57){let a=+i;if(Number.isInteger(a)&&a>=0&&a<e){let e=r[a];if(!e){let i=t[a*2];e=r[a]={index:a,key:n(a),start:i,size:t[a*2+1],end:i+t[a*2+1],lane:0}}return e}}if(i===`length`)return e}return Reflect.get(r,i,a)}})}function ht(e,t,n){let r=n.initialDeps??[],i,a=!0;function o(){let o=e();return o.length!==r.length||o.some((e,t)=>r[t]!==e)?(r=o,i=t(...o),n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(i),a=!1,i):i}return o.updateDeps=e=>{r=e},o}function gt(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var _t=(e,t)=>Math.abs(e-t)<1.01,vt=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},yt,bt=()=>{if(yt!==void 0)return yt;if(typeof navigator>`u`)return yt=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return yt=!0;let e=navigator.maxTouchPoints;return yt=navigator.platform===`MacIntel`&&e!==void 0&&e>0},xt=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},St=e=>e,Ct=e=>{let t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,r=Array(n);for(let e=0;e<n;e++)r[e]=t+e;return r},wt=(e,t)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let i=e=>{let{width:n,height:r}=e;t({width:Math.round(n),height:Math.round(r)})};if(i(xt(n)),!r.ResizeObserver)return()=>{};let a=new r.ResizeObserver(t=>{let r=()=>{let e=t[0];if(e?.borderBoxSize){let t=e.borderBoxSize[0];if(t){i({width:t.inlineSize,height:t.blockSize});return}}i(xt(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},Tt={passive:!0},Et=typeof window>`u`?!0:`onscrollend`in window,Dt=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&Et,o=0,s=a?null:vt(i,()=>t(o,!1),e.options.isScrollingResetDelay),c=e=>()=>{o=n(r),s?.(),t(o,e)},l=c(!0),u=c(!1);return r.addEventListener(`scroll`,l,Tt),a&&r.addEventListener(`scrollend`,u,Tt),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},Ot=(e,t)=>Dt(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),kt=(e,t,n)=>{if(n.options.useCachedMeasurements){let t=n.indexFromElement(e),r=n.options.getItemKey(t);return n.itemSizeCache.get(r)??n.options.estimateSize(t)}if(t?.borderBoxSize){let e=t.borderBoxSize[0];if(e)return Math.round(e[n.options.horizontal?`inlineSize`:`blockSize`])}if(!t){let t=n.indexFromElement(e),r=n.options.getItemKey(t),i=n.itemSizeCache.get(r);if(i!==void 0)return i}return e[n.options.horizontal?`offsetWidth`:`offsetHeight`]},At=(e,{adjustments:t=0,behavior:n},r)=>{var i,a;(a=(i=r.scrollElement)?.scrollTo)==null||a.call(i,{[r.options.horizontal?`left`:`top`]:e+t,behavior:n})},jt=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var e;return((e=this.targetWindow?.performance)?.now)?.call(e)??Date.now()},this.observer=(()=>{let e=null,t=()=>e||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:e=new this.targetWindow.ResizeObserver(e=>{e.forEach(e=>{let t=()=>{let t=e.target,n=this.indexFromElement(t);if(!t.isConnected){this.observer.unobserve(t);for(let[e,n]of this.elementsCache)if(n===t){this.elementsCache.delete(e);break}return}this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,e,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(t):t()})}));return{disconnect:()=>{var n;(n=t())==null||n.disconnect(),e=null},observe:e=>t()?.observe(e,{box:`border-box`}),unobserve:e=>t()?.unobserve(e)}})(),this.range=null,this.setOptions=e=>{let t={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:St,rangeExtractor:Ct,onChange:()=>{},measureElement:kt,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:`data-index`,initialMeasurementsCache:[],lanes:1,anchorTo:`start`,followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:`estimate`,useCachedMeasurements:!1};for(let n in e){let r=e[n];r!==void 0&&(t[n]=r)}let n=this.options,r=null,i=null,a=!1;if(n!==void 0&&n.enabled&&t.enabled&&t.anchorTo===`end`&&this.scrollElement!==null){let e=n.count,o=t.count,s=this.getMeasurements(),c=e>0?s[0]?.key??n.getItemKey(0):null,l=e>0?s[e-1]?.key??n.getItemKey(e-1):null;if(o!==e||e>0&&o>0&&(t.getItemKey(0)!==c||t.getItemKey(o-1)!==l)){a=!0;let c=e>0?this.getVirtualItemForOffset(this.getScrollOffset())??s[0]:null;c&&(r=[c.key,this.getScrollOffset()-c.start]);let u=t.followOnAppend===!0?`auto`:t.followOnAppend||null;u&&o>e&&this.isAtEnd(n.scrollEndThreshold)&&(e===0||t.getItemKey(o-1)!==l)&&(i=u)}}this.options=t,a&&(this.pendingMin=0,this.itemSizeCacheVersion++);let o=!1,s=0;if(r&&this.scrollOffset!==null){let[e,t]=r,n=this.getMeasurements(),{count:i,getItemKey:a}=this.options,c=0;for(;c<i&&a(c)!==e;)c++;if(c<i){let e=n[c];if(e){let n=e.start+t;n!==this.scrollOffset&&(s=n-this.scrollOffset,this.scrollOffset=n,o=!0)}}}(o||i)&&(this.pendingScrollAnchor=[o?r[0]:null,o?r[1]:0,i,s])},this.notify=e=>{var t,n;(n=(t=this.options).onChange)==null||n.call(t,this,e)},this.maybeNotify=ht(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),e=>{this.notify(e)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(e=>e()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{let e=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==e){if(this.cleanup(),!e){this.maybeNotify();return}if(this.scrollElement=e,this.scrollElement&&`ownerDocument`in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=this.scrollElement?.window??null,this.elementsCache.forEach(e=>{this.observer.observe(e)}),this.unsubs.push(this.options.observeElementRect(this,e=>{this.scrollRect=e,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(e,t)=>{if(t&&this._intendedScrollOffset===null&&e===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(e-this._intendedScrollOffset)<1.5&&(e=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;let n=this.getScrollOffset();this.scrollDirection=t?n===e?this.scrollDirection:n<e?`forward`:`backward`:null,this.scrollOffset=e,this.isScrolling=t,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),`addEventListener`in this.scrollElement){let e=this.scrollElement,t=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},n=()=>{this._iosTouching=!1,!(!bt()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,Tt),e.addEventListener(`touchend`,n,Tt),this.unsubs.push(()=>{e.removeEventListener(`touchstart`,t),e.removeEventListener(`touchend`,n),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}let t=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,t&&this.scrollElement&&this.options.enabled){let[e,n,r,i]=t;e!==null&&!r&&(bt()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?i!==0&&(this._iosDeferredAdjustment+=i):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),r&&this.scrollToEnd({behavior:r})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;let e=this.getScrollOffset(),t=this.getMaxScrollOffset();if(e<0||e>t)return;let n=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(e,{adjustments:this.scrollAdjustments+=n,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?`width`:`height`]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset==`function`?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(e,t)=>{let n=new Map,r=new Map;for(let i=t-1;i>=0;i--){let t=e[i];if(n.has(t.lane))continue;let a=r.get(t.lane);if(a==null||t.end>a.end?r.set(t.lane,t):t.end<a.end&&n.set(t.lane,!0),n.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((e,t)=>e.end===t.end?e.index-t.index:e.end-t.end)[0]:void 0},this.getMeasurementOptions=ht(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(e,t,n,r,i,a,o)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMin=null,{count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o}),{key:!1}),this.getMeasurements=ht(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o},s)=>{let c=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>e)for(let t of this.laneAssignments.keys())t>=e&&this.laneAssignments.delete(t);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(e=>{this.itemSizeCache.set(e.key,e.size)}));let l=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1),a===1){let i=this.options.gap,a=e*2,o=this._flatMeasurements;if(!o||o.length<a){let e=new Float64Array(a);o&&l>0&&e.set(o.subarray(0,l*2)),o=e,this._flatMeasurements=o}let s;if(l===0)s=t+n;else{let e=l-1;s=o[e*2]+o[e*2+1]+i}for(let t=l;t<e;t++){let e=r(t),n=c.get(e),a=typeof n==`number`?n:this.options.estimateSize(t);o[t*2]=s,o[t*2+1]=a,s+=a+i}let u=mt(e,o,r);return this.measurementsCache=u,u}let u=this.measurementsCache.slice(0,l),d=Array(a).fill(void 0);for(let e=0;e<l;e++){let t=u[e];t&&(d[t.lane]=e)}for(let i=l;i<e;i++){let e=r(i),a=this.laneAssignments.get(i),s,l,f=o===`estimate`||c.has(e);if(a!==void 0&&this.options.lanes>1){s=a;let e=d[s],r=e===void 0?void 0:u[e];l=r?r.end+this.options.gap:t+n}else{let e=this.options.lanes===1?u[i-1]:this.getFurthestMeasurement(u,i);l=e?e.end+this.options.gap:t+n,s=e?e.lane:i%this.options.lanes,this.options.lanes>1&&f&&this.laneAssignments.set(i,s)}let p=c.get(e),m=typeof p==`number`?p:this.options.estimateSize(i),h=l+m;u[i]={index:i,start:l,size:m,end:h,key:e,lane:s},d[s]=i}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=ht(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>e.length===0||t===0?(this.range=null,null):(this.range=Pt(e,t,n,r,r===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=ht(()=>{let e=null,t=null,n=this.calculateRange();return n&&(e=n.startIndex,t=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,e,t]),[this.options.rangeExtractor,this.options.overscan,this.options.count,e,t]},(e,t,n,r,i)=>r===null||i===null?[]:e({startIndex:r,endIndex:i,overscan:t,count:n}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=e=>{let t=this.options.indexAttribute,n=e.getAttribute(t);return n?parseInt(n,10):(console.warn(`Missing attribute name '${t}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=e=>{if(!this.scrollState||this.scrollState.behavior!==`smooth`)return!0;let t=this.scrollState.index??this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index;if(t!==void 0&&this.range){let n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),r=Math.max(0,t-n),i=Math.min(this.options.count-1,t+n);return e>=r&&e<=i}return!0},this.measureElement=e=>{if(!e){this.elementsCache.forEach((e,t)=>{e.isConnected||(this.observer.unobserve(e),this.elementsCache.delete(t))});return}let t=this.indexFromElement(e),n=this.options.getItemKey(t),r=this.elementsCache.get(n);r!==e&&(r&&this.observer.unobserve(r),this.observer.observe(e),this.elementsCache.set(n,e)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(t)&&this.resizeItem(t,this.options.measureElement(e,void 0,this))},this.resizeItem=(e,t)=>{if(e<0||e>=this.options.count)return;let n,r,i,a=this._flatMeasurements;if(this.options.lanes===1&&a!==null)i=this.options.getItemKey(e),r=a[e*2],n=a[e*2+1];else{let t=this.measurementsCache[e];if(!t)return;i=t.key,r=t.start,n=t.size}let o=t-(this.itemSizeCache.get(i)??n);if(o!==0){let a=this.options.anchorTo===`end`&&this.scrollState?.behavior!==`smooth`&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,s=a?this.getTotalSize():0,c=this.scrollState?.behavior!==`smooth`&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?r<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(i)||this.scrollDirection!==`backward`):this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[e]??{index:e,key:i,start:r,size:n,end:r+n,lane:0},o,this));(this.pendingMin===null||e<this.pendingMin)&&(this.pendingMin=e),this.itemSizeCache.set(i,t),this.itemSizeCacheVersion++,a?this.applyScrollAdjustment(this.getTotalSize()-s):c&&this.applyScrollAdjustment(o),this.notify(!1)}},this.getVirtualItems=ht(()=>[this.getVirtualIndexes(),this.getMeasurements()],(e,t)=>{let n=[];for(let r=0,i=e.length;r<i;r++){let i=t[e[r]];n.push(i)}return n},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=e=>{let t=this.getMeasurements();if(t.length===0)return;let n=this._flatMeasurements,r=this.options.lanes===1&&n!=null;return gt(t[Mt(0,t.length-1,r?e=>n[e*2]:e=>gt(t[e]).start,e)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if(`scrollHeight`in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{let e=this.scrollElement.document.documentElement;return this.options.horizontal?e.scrollWidth-this.scrollElement.innerWidth:e.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(e=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=e,this.getOffsetForAlignment=(e,t,n=0)=>{if(!this.scrollElement)return 0;let r=this.getSize(),i=this.getScrollOffset();t===`auto`&&(t=e>=i+r?`end`:`start`),t===`center`?e+=(n-r)/2:t===`end`&&(e-=r);let a=this.getMaxScrollOffset();return Math.max(Math.min(a,e),0)},this.getOffsetForIndex=(e,t=`auto`)=>{e=Math.max(0,Math.min(e,this.options.count-1));let n=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[e];if(!i)return;if(t===`auto`)if(i.end>=r+n-this.options.scrollPaddingEnd)t=`end`;else if(i.start<=r+this.options.scrollPaddingStart)t=`start`;else return[r,t];if(t===`end`&&e===this.options.count-1)return[this.getMaxScrollOffset(),t];let a=t===`end`?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,t,i.size),t]},this.scrollToOffset=(e,{align:t=`start`,behavior:n=`auto`}={})=>{let r=this.getOffsetForAlignment(e,t),i=this.now();this.scrollState={index:null,align:t,behavior:n,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToIndex=(e,{align:t=`auto`,behavior:n=`auto`}={})=>{e=Math.max(0,Math.min(e,this.options.count-1));let r=this.getOffsetForIndex(e,t);if(!r)return;let[i,a]=r,o=this.now();this.scrollState={index:e,align:a,behavior:n,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollBy=(e,{behavior:t=`auto`}={})=>{let n=this.getScrollOffset()+e,r=this.now();this.scrollState={index:null,align:`start`,behavior:t,startedAt:r,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:t}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:e=`auto`}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:`end`,behavior:e});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:e})},this.getTotalSize=()=>{let e=this.getMeasurements(),t;if(e.length===0)t=this.options.paddingStart;else if(this.options.lanes===1){let n=e.length-1,r=this._flatMeasurements;t=r==null?e[n]?.end??0:r[n*2]+r[n*2+1]}else{let n=Array(this.options.lanes).fill(null),r=e.length-1;for(;r>=0&&n.some(e=>e===null);){let t=e[r];n[t.lane]===null&&(n[t.lane]=t.end),r--}t=Math.max(...n.filter(e=>e!==null))}return Math.max(t-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{let e=[];if(this.itemSizeCache.size===0)return e;let t=this.getMeasurements();for(let n of t)n&&this.itemSizeCache.has(n.key)&&e.push({index:n.index,key:n.key,start:n.start,size:n.size,end:n.end,lane:n.lane});return e},this._scrollToOffset=(e,{adjustments:t,behavior:n})=>{this._intendedScrollOffset=e+(t??0),this.options.scrollToFn(e,{behavior:n,adjustments:t},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(e)}applyScrollAdjustment(e,t){e!==0&&(bt()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=e:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=e,behavior:t}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId??=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()})}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}let e=this.scrollState.index==null?void 0:this.getOffsetForIndex(this.scrollState.index,this.scrollState.align),t=e?e[0]:this.scrollState.lastTargetOffset,n=t!==this.scrollState.lastTargetOffset;if(!n&&_t(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=1){this.getScrollOffset()!==t&&this._scrollToOffset(t,{adjustments:void 0,behavior:`auto`}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,n){let e=this.getSize()||600,n=Math.abs(t-this.getScrollOffset()),r=this.scrollState.behavior===`smooth`&&n>e;this.scrollState.lastTargetOffset=t,r||(this.scrollState.behavior=`auto`),this._scrollToOffset(t,{adjustments:void 0,behavior:r?`smooth`:`auto`})}this.scheduleScrollReconcile()}},Mt=(e,t,n,r)=>{for(;e<=t;){let i=(e+t)/2|0,a=n(i);if(a<r)e=i+1;else if(a>r)t=i-1;else return i}return e>0?e-1:0};function Nt(e,t,n){let r=0;for(;r<=t;){let i=(r+t)/2|0,a=e[i*2];if(a<n)r=i+1;else if(a>n)t=i-1;else return i}return r>0?r-1:0}function Pt(e,t,n,r,i){let a=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:a};if(r===1&&i!==null){let e=Nt(i,a,n),r=e,o=n+t;for(;r<a&&i[r*2]+i[r*2+1]<o;)r++;return{startIndex:e,endIndex:r}}let o=Mt(0,a,t=>e[t].start,n),s=o;if(r===1)for(;s<a&&e[s].end<n+t;)s++;else if(r>1){let i=Array(r).fill(0);for(;s<a&&i.some(e=>e<n+t);){let t=e[s];i[t.lane]=t.end,s++}let c=Array(r).fill(n+t);for(;o>=0&&c.some(e=>e>=n);){let t=e[o];c[t.lane]=t.start,o--}o=Math.max(0,o-o%r),s=Math.min(a,s+(r-1-s%r))}return{startIndex:o,endIndex:s}}var Ft=typeof document<`u`?_.useLayoutEffect:_.useEffect;function It({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n=`transform`,...r}){let i=_.useReducer(e=>e+1,0)[1],a=_.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});a.current.enabled=t,a.current.mode=n;let o=e=>{let t=a.current;if(!t.enabled||!t.container)return;let n=e.getTotalSize();if(n!==t.lastSize){t.lastSize=n;let r=e.options.horizontal?`width`:`height`;t.container.style[r]=`${n}px`}let r=!!e.options.horizontal,i=t.mode===`transform`,o=r?`left`:`top`,s=e.options.scrollMargin,c=e.getVirtualItems();for(let n of c){let a=n.start-s,c=e.elementsCache.get(n.key);c&&t.lastPositions.get(c)!==a&&(t.lastPositions.set(c,a),i?c.style.transform=r?`translate3d(${a}px, 0, 0)`:`translate3d(0, ${a}px, 0)`:c.style[o]=`${a}px`)}},s={...r,onChange:(t,n)=>{var s;let c=a.current,l=!0;if(c.enabled){o(t);let e=t.range,n=c.prevRange;l=!n||n.isScrolling!==t.isScrolling||n.startIndex!==e?.startIndex||n.endIndex!==e?.endIndex,l&&(c.prevRange=e?{startIndex:e.startIndex,endIndex:e.endIndex,isScrolling:t.isScrolling}:null)}l&&(e&&n?(0,pt.flushSync)(i):i()),(s=r.onChange)==null||s.call(r,t,n)}},[c]=_.useState(()=>{let e=new jt(s);return Object.assign(e,{containerRef:t=>{let n=a.current;if(n.container=t,n.lastSize=null,t&&n.enabled){let r=e.getTotalSize();n.lastSize=r;let i=e.options.horizontal?`width`:`height`;t.style[i]=`${r}px`}}})});return c.setOptions(s),Ft(()=>c._didMount(),[]),Ft(()=>c._willUpdate()),Ft(()=>{o(c)}),c}function Lt(e){return It({observeElementRect:wt,observeElementOffset:Ot,scrollToFn:At,...e})}var Rt={400:{en:{label:`Bad request`,description:`The proxy could not understand the request. Check the model, message shape, headers, and JSON body before retrying.`},ko:{label:`잘못된 요청`,description:`프록시가 요청을 이해할 수 없습니다. 재시도 전에 모델, 메시지 형식, 헤더, JSON 본문을 확인해야 합니다.`},zh:{label:`错误请求`,description:`代理无法理解该请求。重试前请检查模型、消息结构、标头和 JSON 正文。`},de:{label:`Ungültige Anfrage`,description:`Der Proxy konnte die Anfrage nicht verstehen. Prüfe Modell, Nachrichtenformat, Header und JSON-Body vor einem erneuten Versuch.`}},401:{en:{label:`Unauthorized`,description:`Credentials are missing, expired, or invalid. Re-login or refresh the account/provider credentials used by opencodex.`},ko:{label:`인증 필요`,description:`자격 증명이 없거나 만료되었거나 유효하지 않습니다. opencodex에서 사용하는 계정 또는 제공자 자격 증명을 다시 로그인하거나 갱신해야 합니다.`},zh:{label:`未授权`,description:`凭据缺失、已过期或无效。请重新登录,或刷新 opencodex 使用的账号/提供商凭据。`},de:{label:`Nicht autorisiert`,description:`Anmeldedaten fehlen, sind abgelaufen oder ungültig. Melde dich erneut an oder aktualisiere die von opencodex genutzten Konto-/Anbieter-Zugangsdaten.`}},402:{en:{label:`Payment required`,description:`The upstream provider rejected the request because billing, credits, or plan access is not available. Add credits, update billing, or switch provider.`},ko:{label:`결제 필요`,description:`청구, 크레딧, 플랜 접근 권한 문제로 업스트림 제공자가 요청을 거부했습니다. 크레딧 추가, 결제 정보 갱신, 제공자 전환이 필요합니다.`},zh:{label:`需要付款`,description:`上游提供商因账单、额度或套餐权限不可用而拒绝了请求。请充值、更新账单信息或切换提供商。`},de:{label:`Zahlung erforderlich`,description:`Der Upstream-Anbieter hat die Anfrage abgelehnt, weil Abrechnung, Guthaben oder Planzugriff nicht verfügbar ist. Guthaben aufladen, Abrechnung aktualisieren oder Anbieter wechseln.`}},403:{en:{label:`Forbidden`,description:`The account is authenticated but not allowed to use this model or operation. Check provider permissions, org access, and policy restrictions.`},ko:{label:`권한 없음`,description:`계정 인증은 되었지만 이 모델 또는 작업을 사용할 권한이 없습니다. 제공자 권한, 조직 접근, 정책 제한을 확인해야 합니다.`},zh:{label:`禁止访问`,description:`账号已认证,但无权使用此模型或操作。请检查提供商权限、组织访问权限和策略限制。`},de:{label:`Verboten`,description:`Das Konto ist authentifiziert, darf dieses Modell oder diese Operation aber nicht nutzen. Prüfe Anbieterberechtigungen, Organisationszugriff und Richtlinien.`}},404:{en:{label:`Not found`,description:`The requested route, model, account, or upstream resource was not found. Verify the model name and opencodex provider configuration.`},ko:{label:`찾을 수 없음`,description:`요청한 경로, 모델, 계정 또는 업스트림 리소스를 찾을 수 없습니다. 모델 이름과 opencodex 제공자 설정을 확인해야 합니다.`},zh:{label:`未找到`,description:`找不到请求的路由、模型、账号或上游资源。请确认模型名称和 opencodex 提供商配置。`},de:{label:`Nicht gefunden`,description:`Die angeforderte Route, das Modell, das Konto oder die Upstream-Ressource wurde nicht gefunden. Prüfe Modellname und opencodex-Anbieterkonfiguration.`}},408:{en:{label:`Request timeout`,description:`The request took too long before the proxy or upstream provider could complete it. Retry with a smaller request or a different provider.`},ko:{label:`요청 시간 초과`,description:`프록시 또는 업스트림 제공자가 요청을 완료하기 전에 시간이 초과되었습니다. 더 작은 요청으로 재시도하거나 다른 제공자로 전환해야 합니다.`},zh:{label:`请求超时`,description:`代理或上游提供商未能在限定时间内完成请求。请缩小请求后重试,或切换提供商。`},de:{label:`Anfrage-Timeout`,description:`Die Anfrage dauerte zu lange, bevor Proxy oder Upstream-Anbieter sie abschließen konnten. Mit kleinerer Anfrage oder anderem Anbieter erneut versuchen.`}},409:{en:{label:`Conflict`,description:`The request conflicts with the current account, session, or provider state. Refresh the session or retry after the active operation finishes.`},ko:{label:`상태 충돌`,description:`요청이 현재 계정, 세션 또는 제공자 상태와 충돌합니다. 세션을 갱신하거나 진행 중인 작업이 끝난 뒤 재시도해야 합니다.`},zh:{label:`状态冲突`,description:`请求与当前账号、会话或提供商状态冲突。请刷新会话,或等待当前操作完成后重试。`},de:{label:`Konflikt`,description:`Die Anfrage kollidiert mit dem aktuellen Konto-, Sitzungs- oder Anbieterstatus. Sitzung aktualisieren oder nach Abschluss der laufenden Operation erneut versuchen.`}},413:{en:{label:`Request too large`,description:`The prompt, attachments, or generated payload exceeds a proxy or upstream limit. Reduce tokens, file size, or conversation history.`},ko:{label:`요청 과대`,description:`프롬프트, 첨부 파일 또는 생성 페이로드가 프록시나 업스트림 한도를 초과했습니다. 토큰, 파일 크기, 대화 기록을 줄여야 합니다.`},zh:{label:`请求过大`,description:`提示、附件或生成的负载超过了代理或上游限制。请减少 token、文件大小或对话历史。`},de:{label:`Anfrage zu groß`,description:`Prompt, Anhänge oder generierte Nutzlast überschreiten ein Proxy- oder Upstream-Limit. Tokens, Dateigröße oder Verlauf reduzieren.`}},422:{en:{label:`Invalid content`,description:`The provider accepted the request format but rejected its contents. Check model options, tool definitions, message roles, and unsupported fields.`},ko:{label:`내용 검증 실패`,description:`제공자가 요청 형식은 받았지만 내용을 거부했습니다. 모델 옵션, 도구 정의, 메시지 역할, 지원되지 않는 필드를 확인해야 합니다.`},zh:{label:`内容无效`,description:`提供商接受了请求格式,但拒绝了其中的内容。请检查模型选项、工具定义、消息角色和不支持的字段。`},de:{label:`Ungültiger Inhalt`,description:`Der Anbieter akzeptierte das Anfrageformat, lehnte den Inhalt aber ab. Prüfe Modelloptionen, Tool-Definitionen, Nachrichtenrollen und nicht unterstützte Felder.`}},424:{en:{label:`Provider dependency failed`,description:`A required upstream dependency failed while opencodex was routing the request. Retry later or switch to another configured provider.`},ko:{label:`제공자 의존성 실패`,description:`opencodex가 요청을 라우팅하는 동안 필요한 업스트림 의존성이 실패했습니다. 나중에 재시도하거나 다른 설정된 제공자로 전환해야 합니다.`},zh:{label:`提供商依赖失败`,description:`opencodex 路由请求时,必需的上游依赖失败。请稍后重试,或切换到另一个已配置的提供商。`},de:{label:`Anbieter-Abhängigkeit fehlgeschlagen`,description:`Eine erforderliche Upstream-Abhängigkeit ist fehlgeschlagen, während opencodex die Anfrage geroutet hat. Später erneut versuchen oder zu einem anderen Anbieter wechseln.`}},429:{en:{label:`Rate limited`,description:`The upstream provider rate or quota limit has been reached. Wait for the quota window to reset or switch account/provider.`},ko:{label:`한도 초과`,description:`업스트림 제공자의 속도 또는 할당량 한도에 도달했습니다. 한도 창이 초기화될 때까지 기다리거나 계정/제공자를 전환해야 합니다.`},zh:{label:`限流`,description:`已达到上游提供商的速率或额度限制。请等待额度窗口重置,或切换账号/提供商。`},de:{label:`Ratenlimit erreicht`,description:`Das Raten- oder Kontingentlimit des Upstream-Anbieters ist erreicht. Auf Reset des Kontingentfensters warten oder Konto/Anbieter wechseln.`}},499:{en:{label:`Client closed request`,description:`The client disconnected or canceled the request before opencodex finished routing it. Retry if the cancellation was accidental.`},ko:{label:`클라이언트 취소`,description:`opencodex가 라우팅을 끝내기 전에 클라이언트 연결이 끊기거나 요청이 취소되었습니다. 의도한 취소가 아니면 다시 시도해야 합니다.`},zh:{label:`客户端已取消`,description:`opencodex 完成路由前,客户端已断开连接或取消请求。如果不是有意取消,请重试。`},de:{label:`Client hat Anfrage geschlossen`,description:`Der Client hat die Verbindung getrennt oder die Anfrage abgebrochen, bevor opencodex das Routing abgeschlossen hat. Bei versehentlichem Abbruch erneut versuchen.`}},500:{en:{label:`Proxy error`,description:`opencodex hit an internal error while handling the request. Retry once, then check proxy logs if it repeats.`},ko:{label:`프록시 오류`,description:`opencodex가 요청을 처리하는 동안 내부 오류가 발생했습니다. 한 번 재시도하고 반복되면 프록시 로그를 확인해야 합니다.`},zh:{label:`代理错误`,description:`opencodex 处理请求时发生内部错误。请先重试一次;如果重复出现,请检查代理日志。`},de:{label:`Proxy-Fehler`,description:`opencodex ist bei der Anfragebearbeitung auf einen internen Fehler gestoßen. Einmal erneut versuchen, bei Wiederholung Proxy-Logs prüfen.`}},502:{en:{label:`Bad upstream response`,description:`The upstream provider returned an invalid or failed response through the proxy. Retry or route the request to another provider.`},ko:{label:`업스트림 응답 오류`,description:`업스트림 제공자가 프록시를 통해 유효하지 않거나 실패한 응답을 반환했습니다. 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{label:`上游响应错误`,description:`上游提供商通过代理返回了无效或失败的响应。请重试,或将请求路由到其他提供商。`},de:{label:`Ungültige Upstream-Antwort`,description:`Der Upstream-Anbieter lieferte über den Proxy eine ungültige oder fehlgeschlagene Antwort. Erneut versuchen oder zu einem anderen Anbieter routen.`}},503:{en:{label:`Provider unavailable`,description:`The proxy or upstream provider is temporarily unavailable or overloaded. Wait briefly, then retry or switch provider.`},ko:{label:`제공자 사용 불가`,description:`프록시 또는 업스트림 제공자가 일시적으로 사용할 수 없거나 과부하 상태입니다. 잠시 기다린 뒤 재시도하거나 제공자를 전환해야 합니다.`},zh:{label:`提供商不可用`,description:`代理或上游提供商暂时不可用或过载。请稍后重试,或切换提供商。`},de:{label:`Anbieter nicht verfügbar`,description:`Proxy oder Upstream-Anbieter ist vorübergehend nicht verfügbar oder überlastet. Kurz warten, dann erneut versuchen oder Anbieter wechseln.`}},504:{en:{label:`Upstream timeout`,description:`The upstream provider did not respond before the proxy timeout. Retry with a smaller request or choose a faster provider.`},ko:{label:`업스트림 시간 초과`,description:`프록시 시간 제한 전에 업스트림 제공자가 응답하지 않았습니다. 더 작은 요청으로 재시도하거나 더 빠른 제공자를 선택해야 합니다.`},zh:{label:`上游超时`,description:`上游提供商未在代理超时前响应。请缩小请求后重试,或选择响应更快的提供商。`},de:{label:`Upstream-Timeout`,description:`Der Upstream-Anbieter antwortete nicht vor dem Proxy-Timeout. Mit kleinerer Anfrage erneut versuchen oder schnelleren Anbieter wählen.`}},529:{en:{label:`Provider overloaded`,description:`The upstream provider is overloaded or capacity-limited. Wait and retry, or switch to another account/provider.`},ko:{label:`제공자 과부하`,description:`업스트림 제공자가 과부하 상태이거나 처리 용량이 제한되었습니다. 기다렸다가 재시도하거나 다른 계정/제공자로 전환해야 합니다.`},zh:{label:`提供商过载`,description:`上游提供商过载或容量受限。请等待后重试,或切换到其他账号/提供商。`},de:{label:`Anbieter überlastet`,description:`Der Upstream-Anbieter ist überlastet oder kapazitätsbegrenzt. Warten und erneut versuchen oder anderes Konto/Anbieter nutzen.`}}},zt={client:{en:{label:`Request error`,description:`The proxy or upstream provider rejected the request. Check the request shape, credentials, model name, and provider configuration.`},ko:{label:`요청 오류`,description:`프록시 또는 업스트림 제공자가 요청을 거부했습니다. 요청 형식, 자격 증명, 모델 이름, 제공자 설정을 확인해야 합니다.`},zh:{label:`请求错误`,description:`代理或上游提供商拒绝了该请求。请检查请求结构、凭据、模型名称和提供商配置。`},de:{label:`Anfragefehler`,description:`Der Proxy oder Upstream-Anbieter hat die Anfrage abgelehnt. Prüfe Anfrageformat, Anmeldedaten, Modellname und Anbieterkonfiguration.`}},server:{en:{label:`Server or upstream error`,description:`opencodex or an upstream provider failed while processing the request. Retry later or route the request to another provider.`},ko:{label:`서버 또는 업스트림 오류`,description:`opencodex 또는 업스트림 제공자가 요청 처리 중 실패했습니다. 나중에 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{label:`服务器或上游错误`,description:`opencodex 或上游提供商处理请求时失败。请稍后重试,或将请求路由到其他提供商。`},de:{label:`Server- oder Upstream-Fehler`,description:`opencodex oder ein Upstream-Anbieter ist bei der Anfragebearbeitung fehlgeschlagen. Später erneut versuchen oder zu einem anderen Anbieter routen.`}}};function Bt(e){return e===`de`||e===`ko`||e===`zh`?e:`en`}function Vt(e,t){if(e<400)return null;let n=Bt(t);return(Rt[Math.trunc(e)]??(e<500?zt.client:zt.server))[n]}function Ht(e,t){if(!e.usage)return;let n=Wt(e),r=[`${t(`logs.tokens.input`)}=${e.usage.inputTokens}`,`${t(`logs.tokens.output`)}=${e.usage.outputTokens}`];return n.read!==void 0&&r.push(`${t(`logs.tokens.cacheRead`)}=${n.read}`),n.write!==void 0&&r.push(`${t(`logs.tokens.cacheWrite`)}=${n.write}`),typeof e.usage.reasoningOutputTokens==`number`&&r.push(`${t(`logs.tokens.reasoning`)}=${e.usage.reasoningOutputTokens}`),e.usageStatus===`estimated`&&r.push(t(`logs.tokens.estimatedNote`)),e.usageStatus===`estimated`&&n.read===void 0&&n.write===void 0&&r.push(t(`logs.tokens.noCacheNote`)),r.join(` · `)}function Ut(e){if(!e.usage)return typeof e.totalTokens==`number`?e.totalTokens:void 0;let t=e.usage.inputTokens+e.usage.outputTokens,n=e.usage.totalTokens??e.totalTokens;return typeof n==`number`?Math.max(n,t):t}function Wt(e){let t=e.usage;if(!t)return{};let n=typeof t.cacheCreationInputTokens==`number`?t.cacheCreationInputTokens:void 0;return{read:typeof t.cacheReadInputTokens==`number`?t.cacheReadInputTokens:typeof t.cachedInputTokens==`number`&&n!==void 0?Math.max(0,t.cachedInputTokens-n):t.cachedInputTokens,write:n}}function Gt(e){if(e.requestedSpeedLabel)return e.requestedSpeedLabel;if(e.modelSupportsServiceTier&&e.configuredSpeedLabel)return e.configuredSpeedLabel}function Kt(e){return[`model=${e.model}`,e.resolvedModel?`resolved=${e.resolvedModel}`:void 0,e.requestedServiceTier?`requestedTier=${e.requestedServiceTier}`:void 0,e.configuredServiceTier?`configuredTier=${e.configuredServiceTier}`:void 0,e.responseServiceTier?`responseTier=${e.responseServiceTier}`:void 0,e.modelSupportsServiceTier===void 0?void 0:`supportsTier=${e.modelSupportsServiceTier}`].filter(Boolean).join(` · `)}function qt({apiBase:e}){let{t,locale:n}=Ce(),[r,i]=(0,_.useState)([]),[a,o]=(0,_.useState)(!0),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(`all`),d=(0,_.useRef)(null),f=ve.find(e=>e.code===n)?.htmlLang;(0,_.useEffect)(()=>{let t=async()=>{try{i(await(await fetch(`${e}/api/logs`)).json())}catch{}};if(t(),!a)return;let n=setInterval(t,2e3);return()=>clearInterval(n)},[e,a]);let p=e=>e>=200&&e<300?`var(--green)`:e>=400?`var(--red)`:`var(--amber)`,m=s?Vt(s.status,n):null,h=r.filter(e=>l===`all`||(l===`claude`?e.surface===`claude`:e.surface!==`claude`)),g=Lt({count:h.length,getScrollElement:()=>d.current,estimateSize:()=>44,overscan:15}),v=g.getVirtualItems(),y=v.length>0?v[0].start:0,b=v.length>0?g.getTotalSize()-v[v.length-1].end:0;return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{className:`page-head`,children:[(0,S.jsx)(`h2`,{children:t(`logs.title`)}),(0,S.jsxs)(`label`,{className:`muted`,style:{fontSize:13,cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,S.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked)}),t(`logs.autoRefresh`)]})]}),(0,S.jsx)(`p`,{className:`page-sub`,children:t(`logs.subtitle`)}),(0,S.jsxs)(`div`,{className:`row`,style:{gap:8,marginBottom:12,alignItems:`center`},children:[(0,S.jsx)(`span`,{className:`muted`,style:{fontSize:13},children:t(`logs.filter.surface.label`)}),(0,S.jsx)(`div`,{className:`segmented`,role:`radiogroup`,"aria-label":t(`logs.filter.surface.label`),style:{display:`inline-flex`,borderRadius:999,background:`var(--surface-soft, var(--raised))`,padding:3,gap:2},children:[`all`,`claude`,`codex`].map(e=>(0,S.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":l===e,className:`btn btn-sm${l===e?` btn-primary`:` btn-ghost`}`,style:{borderRadius:999,minWidth:64,fontSize:12,padding:`5px 12px`,border:`none`,background:l===e?void 0:`transparent`,color:l===e?void 0:`var(--muted)`},onClick:()=>u(e),children:t(`logs.filter.surface.${e}`)},e))})]}),h.length===0?(0,S.jsx)(Ne,{title:t(`logs.noRequests`)}):(0,S.jsx)(`div`,{ref:d,className:`tbl-wrap`,style:{overflowY:`auto`,maxHeight:`calc(100vh - 260px)`},children:(0,S.jsxs)(`table`,{className:`tbl`,children:[(0,S.jsx)(`thead`,{style:{position:`sticky`,top:0,zIndex:1,background:`var(--surface)`},children:(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`th`,{children:t(`logs.col.time`)}),(0,S.jsx)(`th`,{className:`num log-col-tokens`,children:t(`logs.col.tokens`)}),(0,S.jsx)(`th`,{className:`log-col-model`,children:t(`logs.col.model`)}),(0,S.jsx)(`th`,{children:t(`logs.col.effort`)}),(0,S.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,S.jsx)(`th`,{children:t(`logs.col.status`)}),(0,S.jsx)(`th`,{children:t(`logs.col.request`)}),(0,S.jsx)(`th`,{className:`num`,children:t(`logs.col.duration`)})]})}),(0,S.jsxs)(`tbody`,{children:[y>0&&(0,S.jsx)(`tr`,{children:(0,S.jsx)(`td`,{colSpan:8,style:{height:y,padding:0,border:0}})}),v.map(e=>{let r=h[h.length-1-e.index];return(0,S.jsxs)(`tr`,{"data-index":e.index,ref:g.measureElement,children:[(0,S.jsx)(`td`,{className:`muted mono`,children:new Date(r.timestamp).toLocaleTimeString(f)}),(0,S.jsx)(`td`,{className:`num mono log-col-tokens`,title:Ht(r,t),children:(()=>{let e=Ut(r),{read:i,write:a}=Wt(r);return e===void 0?(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.tokens.${r.usageStatus??`unreported`}`)}):(0,S.jsxs)(`span`,{style:{display:`inline-flex`,flexDirection:`column`,alignItems:`flex-end`,gap:2},children:[(0,S.jsxs)(`span`,{children:[r.usageStatus===`estimated`?`~`:``,ke(e,n)]}),i!==void 0&&i>0&&(0,S.jsxs)(`span`,{className:`muted`,style:{fontSize:11,lineHeight:1},children:[`c `,ke(i,n)]}),a!==void 0&&a>0&&(0,S.jsxs)(`span`,{className:`muted`,style:{fontSize:11,lineHeight:1},children:[`w `,ke(a,n)]}),r.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,S.jsx)(`span`,{className:`muted`,style:{fontSize:11,lineHeight:1},children:t(`logs.tokens.noCache`)})]})})()}),(0,S.jsx)(`td`,{className:`mono log-col-model`,title:Kt(r),children:(0,S.jsxs)(`span`,{style:{display:`inline-flex`,alignItems:`center`,gap:6,flexWrap:`wrap`},children:[(0,S.jsx)(`span`,{children:z(r.resolvedModel??r.model)}),r.surface===`claude`&&(0,S.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.claude`)}),Gt(r)&&(0,S.jsx)(`span`,{className:`badge badge-amber`,children:Gt(r)})]})}),(0,S.jsx)(`td`,{className:`mono`,children:r.requestedEffort??`-`}),(0,S.jsx)(`td`,{className:`muted`,children:r.provider}),(0,S.jsx)(`td`,{children:(0,S.jsxs)(`span`,{className:`log-status-cell`,children:[(0,S.jsx)(`span`,{className:`mono`,style:{color:p(r.status),fontWeight:600},children:r.status}),r.status>=400&&(0,S.jsx)(`button`,{type:`button`,className:`log-detail-btn`,onClick:()=>c(r),children:t(`logs.details`)})]})}),(0,S.jsx)(`td`,{className:`muted mono`,children:(0,S.jsx)(`span`,{className:`log-reqid`,title:r.requestId,children:r.requestId??`-`})}),(0,S.jsxs)(`td`,{className:`num`,children:[r.durationMs,`ms`]})]},r.requestId??`${r.timestamp}-${e.index}`)}),b>0&&(0,S.jsx)(`tr`,{children:(0,S.jsx)(`td`,{colSpan:8,style:{height:b,padding:0,border:0}})})]})]})}),s&&(0,S.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":t(`logs.detailTitle`),className:`modal-overlay`,onClick:()=>c(null),children:(0,S.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,S.jsxs)(`div`,{className:`modal-head`,children:[(0,S.jsxs)(`h3`,{children:[(0,S.jsx)(`span`,{className:`mono`,style:{color:p(s.status)},children:s.status}),m&&(0,S.jsx)(`span`,{style:{marginLeft:8},children:m.label})]}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-sm`,onClick:()=>c(null),"aria-label":t(`common.cancel`),children:(0,S.jsx)(ie,{})})]}),m&&(0,S.jsx)(`p`,{className:`modal-desc`,children:m.description}),(0,S.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.col.time`)}),(0,S.jsx)(`span`,{className:`mono`,children:new Date(s.timestamp).toLocaleString(f)}),(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.col.request`)}),(0,S.jsx)(`span`,{className:`mono log-detail-break`,children:s.requestId??`-`}),(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.col.model`)}),(0,S.jsx)(`span`,{className:`mono`,children:z(s.resolvedModel??s.model)}),(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.col.provider`)}),(0,S.jsx)(`span`,{children:s.provider}),s.errorCode&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.col.error`)}),(0,S.jsx)(`span`,{className:`mono`,children:s.errorCode})]}),s.upstreamError&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.col.upstreamReason`)}),(0,S.jsx)(`span`,{className:`mono log-detail-break`,children:s.upstreamError})]}),(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.col.duration`)}),(0,S.jsxs)(`span`,{className:`mono`,children:[s.durationMs,`ms`]})]}),(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:12,margin:`12px 0 6px`},children:t(`logs.detailRaw`)}),(0,S.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(s,null,2)})]})})]})}var Jt=[`provider`,`usage`,`injection`],Yt=e=>e>0?`[${new Date(e).toLocaleTimeString()}] `:``;function Xt({apiBase:e}){let{t}=Ce(),[n,r]=(0,_.useState)(null),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(`provider`),[c,l]=(0,_.useState)([]),[u,d]=(0,_.useState)(!0),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)([]),g=(0,_.useRef)(0),v=(0,_.useRef)(null),y=Lt({count:c.length,getScrollElement:()=>v.current,estimateSize:()=>20,overscan:30,getItemKey:e=>c[e].seq});(0,_.useEffect)(()=>{let t=async()=>{try{let t=await fetch(`${e}/api/debug`);t.ok&&r(await t.json())}catch{}};t();let n=setInterval(()=>void t(),2e3);return()=>clearInterval(n)},[e]);let b=(0,_.useCallback)(e=>e===`provider`?!!n?.enabled:e===`usage`?!!n?.usage:!!n?.injection,[n]);(0,_.useEffect)(()=>{if(!n||b(o))return;let e=Jt.find(b);if(!e)return;let t=window.setTimeout(()=>s(e),0);return()=>window.clearTimeout(t)},[n,o,b]);let x=b(o),C=o===`provider`?`${e}/api/debug/logs`:o===`usage`?`${e}/api/debug/usage-logs`:`${e}/api/debug/injection-logs`,w=(0,_.useCallback)(async e=>{if(!x){l([]),g.current=0;return}p(!0);try{let t=new URLSearchParams({limit:`500`});!e&&g.current>0&&t.set(`after`,String(g.current));let n=await fetch(`${C}?${t}`);if(!n.ok)return;let r=await n.json();if(r.length===0)return;l(t=>(e?r:[...t,...r]).slice(-2e3)),g.current=r[r.length-1].seq}catch{}finally{p(!1)}},[C,x]);(0,_.useEffect)(()=>{g.current=0;let e=window.setTimeout(()=>{l([]),w(!0)},0);return()=>window.clearTimeout(e)},[o,x,w]),(0,_.useEffect)(()=>{if(!u||!x)return;let e=setInterval(()=>void w(!1),1e3);return()=>clearInterval(e)},[u,x,w]),(0,_.useEffect)(()=>{u&&c.length>0&&y.scrollToIndex(c.length-1,{align:`end`})},[c,u,y]),(0,_.useEffect)(()=>{if(!n?.claude){h([]);return}let t=async()=>{try{let t=await fetch(`${e}/api/claude/inbound-debug`);if(t.ok){let e=await t.json();h(Array.isArray(e.entries)?e.entries:[])}}catch{}};t();let r=setInterval(()=>void t(),2e3);return()=>clearInterval(r)},[e,n?.claude]);let T=async(t,n)=>{a(!0);try{let i=await fetch(`${e}/api/debug`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({[t]:n})});i.ok&&r(await i.json())}catch{}finally{a(!1)}},ee=async()=>{a(!0);try{let t=await fetch(`${e}/api/debug`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({reset:!0})});t.ok&&r(await t.json())}catch{}finally{a(!1)}};return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{className:`page-head`,children:[(0,S.jsx)(`h2`,{children:t(`debug.title`)}),(0,S.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:12},children:[(0,S.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:f||!x,onClick:()=>void w(!0),children:[(0,S.jsx)(k,{}),` `,t(`debug.refresh`)]}),(0,S.jsxs)(`label`,{className:`muted`,style:{fontSize:13,cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,S.jsx)(`input`,{type:`checkbox`,checked:u,onChange:e=>d(e.target.checked)}),t(`debug.follow`)]})]})]}),(0,S.jsx)(`p`,{className:`page-sub`,children:t(`debug.subtitle`)}),n?(0,S.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,S.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,S.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:16},children:[`debug`,`usage`,`injection`,`claude`].map(e=>{let r=e===`debug`?n.enabled:e===`usage`?n.usage:e===`injection`?n.injection:n.claude;return(0,S.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:10,minWidth:220},children:[(0,S.jsx)(Ae,{on:r,disabled:i,label:t(`debug.${e}`),onClick:()=>void T(e,!r)}),(0,S.jsx)(`span`,{style:{fontSize:13},children:t(`debug.${e}`)})]},e)})}),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:i,onClick:()=>void ee(),children:t(`debug.reset`)})]}),(n.enabled||n.usage||n.injection)&&(0,S.jsxs)(`div`,{style:{display:`inline-flex`,gap:6,marginTop:12},children:[n.enabled&&(0,S.jsx)(`button`,{type:`button`,className:`btn btn-sm${o===`provider`?` btn-primary`:` btn-ghost`}`,onClick:()=>s(`provider`),children:t(`debug.streamProvider`)}),n.usage&&(0,S.jsx)(`button`,{type:`button`,className:`btn btn-sm${o===`usage`?` btn-primary`:` btn-ghost`}`,onClick:()=>s(`usage`),children:t(`debug.streamUsage`)}),n.injection&&(0,S.jsx)(`button`,{type:`button`,className:`btn btn-sm${o===`injection`?` btn-primary`:` btn-ghost`}`,onClick:()=>s(`injection`),children:t(`debug.streamInjection`)})]})]}):(0,S.jsx)(`div`,{className:`empty`,children:t(`debug.loading`)}),n?.claude&&(0,S.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,S.jsx)(`div`,{style:{fontWeight:600,marginBottom:4},children:t(`debug.claudeInbound.title`)}),(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:13,marginBottom:10},children:t(`debug.claudeInbound.sub`)}),m.length===0?(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:13},children:t(`debug.claudeInbound.empty`)}):(0,S.jsx)(`div`,{style:{overflowX:`auto`},children:(0,S.jsxs)(`table`,{className:`table`,style:{fontSize:12},children:[(0,S.jsx)(`thead`,{children:(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,S.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,S.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,S.jsx)(`th`,{children:`thinking`}),(0,S.jsx)(`th`,{children:`effort`}),(0,S.jsx)(`th`,{children:`beta`}),(0,S.jsx)(`th`,{children:`metadata`}),(0,S.jsx)(`th`,{children:`system`})]})}),(0,S.jsx)(`tbody`,{children:m.map((e,n)=>(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`td`,{className:`muted mono`,children:new Date(e.at).toLocaleTimeString()}),(0,S.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,S.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,S.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,S.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,S.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,S.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,S.jsx)(`td`,{className:`mono`,title:e.anthropicBeta,style:{maxWidth:160,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.anthropicBeta??`-`}),(0,S.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,S.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},`${e.at}-${n}`))})]})})]}),n&&!x?(0,S.jsxs)(`div`,{className:`empty`,children:[(0,S.jsx)(`div`,{style:{fontWeight:600,marginBottom:6},children:t(`debug.emptyTitle`)}),(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:13,maxWidth:560,marginInline:`auto`},children:t(`debug.empty`)})]}):n&&x&&c.length===0?(0,S.jsxs)(`div`,{className:`empty`,children:[(0,S.jsx)(`div`,{style:{fontWeight:600,marginBottom:6},children:t(`debug.noLinesTitle`)}),(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:13,maxWidth:560,marginInline:`auto`},children:t(`debug.noLines.${o}`)})]}):n&&x?(0,S.jsx)(`div`,{ref:v,className:`log-detail-json`,style:{maxHeight:`calc(100vh - 280px)`,overflow:`auto`},children:(0,S.jsx)(`div`,{style:{position:`relative`,height:y.getTotalSize(),width:`100%`},children:y.getVirtualItems().map(e=>(0,S.jsx)(`div`,{ref:y.measureElement,"data-index":e.index,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${e.start}px)`},children:`${Yt(c[e.index].at)}${c[e.index].line}`},e.key))})}):null]})}function Zt(e){return`${Math.round(e*100)}%`}function Qt(e,t){let n=`${t}/${e}`,r=0;for(let e=0;e<n.length;e++)r=r*31+n.charCodeAt(e)>>>0;return`hsl(${r%360} 55% 55%)`}function $t(e){let t=new Map(e.map(e=>[e.date,e])),n=[],r=new Date;r.setHours(0,0,0,0),r.setDate(r.getDate()-6);for(let e=0;e<7;e++){let e=`${r.getFullYear()}-${String(r.getMonth()+1).padStart(2,`0`)}-${String(r.getDate()).padStart(2,`0`)}`,i=t.get(e);n.push({date:e,requests:i?.requests??0,measuredRequests:i?.measuredRequests??0,reportedRequests:i?.reportedRequests??0,totalTokens:i?.totalTokens??0,models:i?.models??[]}),r.setDate(r.getDate()+1)}return n}function en(e){let t=e.filter(e=>e>0).sort((e,t)=>e-t);if(t.length===0)return[0,0,0,0];let n=e=>t[Math.min(t.length-1,Math.floor(e*t.length))];return[n(.25),n(.5),n(.75),n(.95)]}function tn(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function nn(e){let t=en(e.map(e=>e.totalTokens)),n=new Map(e.map(e=>[e.date,e])),r=new Date;r.setHours(0,0,0,0);let i=new Date(r);i.setDate(i.getDate()-364),i.setDate(i.getDate()-i.getDay());let a=[],o=[],s=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],c=-4,l=-1,u=[],d=new Date(i);for(;d<=r;){let e=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,`0`)}-${String(d.getDate()).padStart(2,`0`)}`,r=d.getMonth();d.getDay()===0&&r!==l&&a.length-c>=4&&(o.push({label:s[r],col:a.length}),c=a.length,l=r);let i=n.get(e);u.push({date:e,requests:i?.requests??0,totalTokens:i?.totalTokens??0,level:i?tn(i.totalTokens,t):0,dayOfWeek:d.getDay()}),d.getDay()===6&&(a.push(u),u=[]),d.setDate(d.getDate()+1)}if(u.length>0){for(;u.length<7;)u.push({date:``,requests:0,totalTokens:0,level:0,dayOfWeek:u.length});a.push(u)}return{weeks:a,months:o,buckets:t}}function rn({apiBase:e}){let{t,locale:n}=Ce(),[r,i]=(0,_.useState)(`30d`),[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(!0),[l,u]=(0,_.useState)(``),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(null),h=(0,_.useCallback)(async(t,n)=>{c(!0);try{let r=await fetch(`${e}/api/usage?range=${t}`,{signal:n});if(!r.ok)throw Error(`fetch failed`);let i=await r.json();if(n.aborted)return;o(i)}catch{if(n.aborted)return;o(null)}finally{n.aborted||c(!1)}},[e]);(0,_.useEffect)(()=>{let e=new AbortController,t=window.setTimeout(()=>{h(r,e.signal)},0);return()=>{window.clearTimeout(t),e.abort()}},[h,r]);let g=(0,_.useMemo)(()=>nn(a?.days??[]),[a?.days]),v=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=v.current;if(!e)return;let t=()=>{e.scrollLeft=e.scrollWidth};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[g,r,s]);let y=(0,_.useMemo)(()=>$t(a?.days??[]),[a?.days]),b=(0,_.useMemo)(()=>(a?.days??[]).filter(e=>e.requests>0).length,[a?.days]),x=(0,_.useMemo)(()=>{let e=l.trim().toLowerCase(),t=[...a?.models??[]].sort((e,t)=>t.totalTokens-e.totalTokens);return e?t.filter(t=>t.model.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)||(t.resolvedModel??``).toLowerCase().includes(e)).slice(0,100):t.slice(0,100)},[a?.models,l]),C=(0,_.useMemo)(()=>[...a?.providers??[]].sort((e,t)=>t.totalTokens-e.totalTokens),[a?.providers]);return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{className:`page-head`,children:[(0,S.jsx)(`h2`,{children:t(`usage.title`)}),(0,S.jsx)(`div`,{className:`usage-range`,role:`group`,"aria-label":t(`usage.title`),children:[`all`,`30d`,`7d`].map(e=>(0,S.jsx)(`button`,{type:`button`,className:`usage-range-btn${r===e?` active`:``}`,onClick:()=>i(e),children:t(`usage.range.${e}`)},e))})]}),(0,S.jsx)(`p`,{className:`page-sub`,children:t(`usage.subtitle`)}),s&&!a?(0,S.jsx)(Ne,{title:t(`usage.loading`)}):!a||a.summary.requests===0?(0,S.jsx)(Ne,{title:t(`usage.empty`)}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.card.requests`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:a.summary.requests})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.card.measured`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:a.summary.measuredRequests})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.card.totalTokens`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:ke(a.summary.totalTokens,n)})]}),(0,S.jsxs)(`div`,{className:`stat`,title:t(`usage.card.cachedTokensHint`),children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.card.cachedTokens`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:ke(a.summary.cacheReadInputTokens??a.summary.cachedInputTokens,n)}),(a.summary.cacheCreationInputTokens??0)>0&&(0,S.jsxs)(`div`,{className:`muted`,style:{fontSize:11},children:[t(`usage.card.cacheWriteTokens`),`: `,ke(a.summary.cacheCreationInputTokens??0,n)]})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.card.coverage`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:Zt(a.summary.coverageRatio)})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.card.activeDays`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:b})]})]}),(0,S.jsxs)(`section`,{className:`panel`,style:{marginTop:16},children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`usage.section.heatmap`)}),r===`7d`?(0,S.jsx)(`div`,{className:`daybars`,children:y.map((e,t)=>{let r=Math.max(1,...y.map(e=>e.totalTokens)),i=Math.round(e.totalTokens/r*100),a=e.date.slice(5);return(0,S.jsxs)(`div`,{className:`daybar`,onMouseEnter:()=>f(t),onMouseLeave:()=>f(e=>e===t?null:e),children:[(0,S.jsx)(`div`,{className:`daybar-track`,children:(0,S.jsxs)(`div`,{className:`daybar-stack`,style:{height:`${i}%`},children:[e.models.map(e=>(0,S.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:e.totalTokens,background:Qt(e.model,e.provider)}},`${e.provider}/${e.model}`)),e.models.length===0&&e.totalTokens>0&&(0,S.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:1,background:`var(--green)`}})]})}),d===t&&e.totalTokens>0&&(0,S.jsxs)(`div`,{className:`daybar-tip`,children:[(0,S.jsx)(`div`,{className:`daybar-tip-date`,children:e.date}),e.models.slice(0,8).map(e=>(0,S.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,S.jsx)(`span`,{className:`daybar-tip-swatch`,style:{background:Qt(e.model,e.provider)}}),(0,S.jsx)(`span`,{className:`daybar-tip-name`,children:z(e.model)}),(0,S.jsx)(`span`,{className:`daybar-tip-val`,children:ke(e.totalTokens,n)})]},`${e.provider}/${e.model}`))]}),(0,S.jsx)(`span`,{className:`daybar-count`,children:ke(e.totalTokens,n)}),(0,S.jsx)(`span`,{className:`daybar-label muted`,children:a})]},t)})}):(0,S.jsxs)(`div`,{className:`heatmap`,ref:v,children:[(0,S.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${g.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,S.jsx)(`span`,{className:`heatmap-day-spacer`}),g.months.map((e,t)=>(0,S.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:e.label},t))]}),(0,S.jsxs)(`div`,{className:`heatmap-body`,children:[(0,S.jsxs)(`div`,{className:`heatmap-days`,children:[(0,S.jsx)(`span`,{}),(0,S.jsx)(`span`,{children:`Mon`}),(0,S.jsx)(`span`,{}),(0,S.jsx)(`span`,{children:`Wed`}),(0,S.jsx)(`span`,{}),(0,S.jsx)(`span`,{children:`Fri`}),(0,S.jsx)(`span`,{})]}),(0,S.jsx)(`div`,{className:`heatmap-grid`,style:{gridTemplateColumns:`repeat(${g.weeks.length}, var(--hm-cell))`},children:g.weeks.map((e,t)=>(0,S.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,n)=>(0,S.jsx)(`div`,{className:`heatmap-cell heatmap-cell-${e.level}`,onMouseEnter:r=>{if(!e.date)return;let i=r.target.getBoundingClientRect();m({wi:t,di:n,x:i.left+i.width/2,y:i.top})},onMouseLeave:()=>m(e=>e?.wi===t&&e?.di===n?null:e)},`${t}-${n}`))},t))})]}),p&&(()=>{let e=g.weeks[p.wi]?.[p.di];return e?.date?(0,S.jsxs)(`div`,{className:`heatmap-tip`,style:{left:p.x,top:p.y},children:[(0,S.jsx)(`div`,{className:`heatmap-tip-date`,children:e.date}),(0,S.jsxs)(`div`,{className:`heatmap-tip-val`,children:[ke(e.totalTokens,n),` tokens`]}),(0,S.jsxs)(`div`,{className:`heatmap-tip-req muted`,children:[e.requests,` requests`]})]}):null})(),(0,S.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,S.jsx)(`span`,{children:t(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,S.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,S.jsx)(`span`,{children:t(`usage.heatmap.more`)})]})]})]}),(0,S.jsxs)(`section`,{className:`panel`,style:{marginTop:16},children:[(0,S.jsxs)(`div`,{className:`panel-head`,children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`usage.section.models`)}),(0,S.jsx)(`input`,{className:`input`,placeholder:t(`usage.search.models`),value:l,onChange:e=>u(e.target.value)})]}),(0,S.jsx)(`div`,{className:`tbl-wrap usage-scroll`,children:(0,S.jsxs)(`table`,{className:`tbl`,children:[(0,S.jsx)(`thead`,{children:(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`th`,{children:t(`logs.col.model`)}),(0,S.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,S.jsx)(`th`,{className:`num`,children:t(`usage.col.requests`)}),(0,S.jsx)(`th`,{className:`num`,children:t(`usage.col.measured`)}),(0,S.jsx)(`th`,{className:`num`,children:t(`usage.col.tokens`)}),(0,S.jsx)(`th`,{children:t(`usage.col.share`)})]})}),(0,S.jsx)(`tbody`,{children:x.map(e=>(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`td`,{className:`mono`,children:z(e.resolvedModel??e.model)}),(0,S.jsx)(`td`,{className:`muted`,children:e.provider}),(0,S.jsx)(`td`,{className:`num`,children:e.requests}),(0,S.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,S.jsx)(`td`,{className:`num mono`,children:ke(e.totalTokens,n)}),(0,S.jsx)(`td`,{children:(0,S.jsx)(`div`,{className:`usage-bar`,children:(0,S.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},`${e.provider}/${e.model}/${e.resolvedModel??``}`))})]})})]}),(0,S.jsxs)(`section`,{className:`panel`,style:{marginTop:16},children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`usage.section.providers`)}),(0,S.jsx)(`div`,{className:`tbl-wrap usage-scroll`,children:(0,S.jsxs)(`table`,{className:`tbl`,children:[(0,S.jsx)(`thead`,{children:(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,S.jsx)(`th`,{className:`num`,children:t(`usage.col.requests`)}),(0,S.jsx)(`th`,{className:`num`,children:t(`usage.col.measured`)}),(0,S.jsx)(`th`,{className:`num`,children:t(`usage.col.tokens`)}),(0,S.jsx)(`th`,{children:t(`usage.col.share`)})]})}),(0,S.jsx)(`tbody`,{children:C.map(e=>(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`td`,{className:`mono`,children:e.provider}),(0,S.jsx)(`td`,{className:`num`,children:e.requests}),(0,S.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,S.jsx)(`td`,{className:`num mono`,children:ke(e.totalTokens,n)}),(0,S.jsx)(`td`,{children:(0,S.jsx)(`div`,{className:`usage-bar`,children:(0,S.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},e.provider))})]})})]}),(0,S.jsxs)(`section`,{className:`panel`,style:{marginTop:16},children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`usage.section.coverage`)}),(0,S.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.measured`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:a.summary.measuredRequests})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.reported`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:a.summary.reportedRequests})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.estimated`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:a.summary.estimatedRequests})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unreported`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:a.summary.unreportedRequests})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unsupported`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:a.summary.unsupportedRequests})]})]}),(0,S.jsx)(`p`,{className:`muted`,style:{marginTop:12,fontSize:13},children:t(`usage.coverage.note`)})]})]})]})}function an({apiBase:e,onClose:t,onAdded:n}){let r=we(),i=(0,_.useRef)(!0),a=(0,_.useRef)(null),o=(0,_.useRef)(null),s=(0,_.useRef)(null),c=(0,_.useRef)(null);(0,_.useEffect)(()=>()=>{i.current=!1,a.current&&=(clearInterval(a.current),null),o.current&&=(clearTimeout(o.current),null)},[]);let[l,u]=(0,_.useState)(`pick`),[d,f]=(0,_.useState)(``),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(!1),b=()=>{a.current&&=(clearInterval(a.current),null),o.current&&=(clearTimeout(o.current),null)},x=async()=>{let t=s.current;s.current=null,c.current=null,g(``),b(),t&&await fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:t})}).catch(()=>{})},C=()=>{l===`oauth-waiting`&&x(),t()};return(0,_.useEffect)(()=>{let e=e=>{e.key===`Escape`&&C()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)}),(0,S.jsx)(`div`,{className:`modal-overlay`,onClick:C,children:(0,S.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:440},children:[l===`pick`&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`h3`,{style:{marginBottom:4},children:r(`codexAuth.addTitle`)}),(0,S.jsx)(`p`,{className:`modal-desc`,children:r(`codexAuth.addPickDesc`)}),(0,S.jsx)(`label`,{className:`field-label`,children:r(`codexAuth.addIdLabel`)}),(0,S.jsx)(`input`,{className:`input`,placeholder:`codex-work, codex-alt, team...`,value:d,onChange:e=>f(e.target.value),style:{marginBottom:12}}),(0,S.jsx)(`button`,{className:`list-row`,onClick:async()=>{m(``);try{let l=d.trim(),f=await fetch(`${e}/api/codex-auth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(l?{id:l}:{})}),p=await f.json();if(f.status===409){m(r(`codexAuth.oauthAlreadyInProgress`));return}if(p.url){s.current=p.flowId??null,g(p.url),c.current=window.open(p.url,`_blank`),c.current&&(c.current.opener=null),u(`oauth-waiting`),b();let d=p.flowId??``,f=d?`${e}/api/codex-auth/login-status?flowId=${encodeURIComponent(d)}${l?`&accountId=${encodeURIComponent(l)}`:``}`:`${e}/api/codex-auth/login-status`;a.current=setInterval(async()=>{try{let e=await fetch(f).then(e=>e.json());e.status===`done`?(b(),s.current=null,c.current=null,n(),t()):e.status===`error`||e.status===`expired`?(b(),s.current=null,c.current=null,i.current&&(u(`pick`),m(e.error??`Login failed`))):c.current?.closed&&(await x(),i.current&&(u(`pick`),m(r(`codexAuth.oauthCancelled`))))}catch{}},2e3),o.current=setTimeout(()=>{a.current&&(x(),i.current&&(u(`pick`),m(r(`modal.loginTimeout`))))},3e5)}p.error&&!p.url&&m(p.error)}catch(e){m(String(e))}},style:{marginBottom:8},children:(0,S.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,S.jsx)(me,{width:20}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`title`,children:r(`codexAuth.oauthLogin`)}),(0,S.jsx)(`div`,{className:`sub`,children:r(`codexAuth.oauthDesc`)})]})]})}),p&&(0,S.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:p}),(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:C,style:{width:`100%`},children:r(`codexAuth.cancel`)})]}),l===`oauth-waiting`&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`h3`,{style:{marginBottom:4},children:r(`codexAuth.oauthLogin`)}),(0,S.jsx)(`p`,{className:`modal-desc`,children:r(`codexAuth.oauthWaiting`)}),(0,S.jsxs)(`button`,{className:`btn btn-ghost`,onClick:async()=>{if(h)try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(h);else{let e=document.createElement(`textarea`);e.value=h,e.style.position=`fixed`,e.style.opacity=`0`,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e)}y(!0),setTimeout(()=>{i.current&&y(!1)},2500)}catch{m(r(`codexAuth.loginLinkCopyFailed`))}},disabled:!h,style:{width:`100%`,justifyContent:`center`,marginTop:12},children:[(0,S.jsx)(L,{width:14}),` `,r(v?`codexAuth.loginLinkCopied`:`codexAuth.copyLoginLink`)]}),p&&(0,S.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:p}),(0,S.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,S.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:C,style:{width:`100%`},children:r(`codexAuth.cancel`)})]})]})})}function on({apiBase:e}){let t=we(),[n,r]=(0,_.useState)([]),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(80),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(``),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(!1),[x,C]=(0,_.useState)(!1),[w,T]=(0,_.useState)(null),[ee,te]=(0,_.useState)(!1),E=(0,_.useCallback)(async(t=!1)=>{try{let[n,i]=await Promise.all([fetch(`${e}/api/codex-auth/accounts${t?`?refresh=1`:``}`).then(e=>e.json()),fetch(`${e}/api/codex-auth/active`).then(e=>e.json())]);return r(n.accounts??[]),a(i.activeCodexAccountId??null),s(i.autoSwitchThreshold??80),!0}catch{return!1}},[e]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{E()},0),t=window.setInterval(()=>{E()},3e4);return()=>{window.clearTimeout(e),window.clearInterval(t)}},[E]);let ne=async r=>{await fetch(`${e}/api/codex-auth/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:r})}),a(r),l(null),p(t(`codexAuth.switched`,{email:r&&r!==`__main__`?n.find(e=>e.id===r)?.email??r:`main`})),setTimeout(()=>p(``),5e3)},re=async n=>{window.confirm(t(`codexAuth.removeConfirm`,{id:n}))&&(await fetch(`${e}/api/codex-auth/accounts?id=${n}`,{method:`DELETE`}),E())},D=async()=>{let t=o>0?0:80;await fetch(`${e}/api/codex-auth/auto-switch`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({threshold:t})}),s(t)},O=async()=>{h(!0);try{p(t(await E(!0)?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`)),setTimeout(()=>p(``),5e3)}finally{h(!1)}},A=async t=>{v(t),b(!1),T(null),te(!0);try{let n=await fetch(`${e}/api/codex-auth/reset-credits?accountId=${encodeURIComponent(t.id)}`);n.ok&&T(((await n.json()).credits??[]).sort((e,t)=>new Date(e.granted_at).getTime()-new Date(t.granted_at).getTime()))}catch{}finally{te(!1)}},oe=async n=>{C(!0);try{let r=await fetch(`${e}/api/codex-auth/reset-credits/consume`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:n})});if(!r.ok){alert(t(`codexAuth.resetError`));return}let i=await r.json();if(i.code===`reset`||i.code===`already_redeemed`){let e=g?.quota?.resetCredits??1;v(null),b(!1),await E(!0),p(t(`codexAuth.resetSuccess`,{remaining:String(Math.max(0,e-1))})),setTimeout(()=>p(``),5e3)}else i.code===`nothing_to_reset`?alert(t(`codexAuth.resetNothingToReset`)):i.code===`no_credit`?alert(t(`codexAuth.resetNoCredit`)):alert(t(`codexAuth.resetError`))}catch{alert(t(`codexAuth.resetError`))}finally{C(!1)}},M=n.find(e=>e.isMain),se=n.filter(e=>!e.isMain),N=e=>i===e,P=!i||i===`__main__`;return(0,S.jsxs)(`div`,{children:[(0,S.jsxs)(`div`,{className:`page-head`,children:[(0,S.jsx)(`h2`,{className:`page-title`,children:t(`nav.codexAuth`)}),(0,S.jsxs)(`button`,{className:`btn btn-sm btn-ghost`,onClick:O,disabled:m,children:[(0,S.jsx)(k,{width:14}),` `,t(m?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]}),f&&(0,S.jsx)(je,{tone:`ok`,children:f}),(0,S.jsxs)(`div`,{className:`card ${P?`card-active`:``}`,onClick:()=>P?void 0:l({id:`__main__`,email:M?.email??`Codex App`,plan:M?.plan,isMain:!0,hasCredential:!0,quota:M?.quota??null}),style:{cursor:P?`default`:`pointer`,marginBottom:12},children:[(0,S.jsxs)(`div`,{className:`card-head`,children:[(0,S.jsx)(`span`,{className:`dot dot-green`}),(0,S.jsx)(`strong`,{children:t(`codexAuth.mainAccount`)}),(0,S.jsxs)(`span`,{className:`card-badges`,children:[M&&(0,S.jsx)(un,{account:{...M,id:`__main__`},onClick:()=>A({...M,id:`__main__`})}),(0,S.jsx)(`span`,{className:`badge ${P?`badge-primary`:`badge-muted`}`,children:t(P?`codexAuth.nextSession`:`codexAuth.current`)})]}),(0,S.jsxs)(`span`,{className:`card-right`,children:[(0,S.jsx)(ue,{width:14}),` `,t(`codexAuth.appLogin`)]})]}),(0,S.jsxs)(`div`,{className:`card-sub`,children:[M?.email??`Codex App login`,M?.plan?` · ${M.plan}`:``]}),M?.quota&&(0,S.jsx)(Ke,{quota:M.quota,plan:M.plan,threshold:o,t})]}),(0,S.jsxs)(`div`,{className:`section-sep`,children:[(0,S.jsx)(`span`,{className:`section-label`,children:t(`codexAuth.accountPool`)}),(0,S.jsx)(`div`,{className:`sep-line`}),(0,S.jsxs)(`button`,{className:`btn btn-sm btn-ghost`,onClick:()=>d(!0),children:[(0,S.jsx)(ae,{width:14}),` `,t(`codexAuth.add`)]})]}),se.length===0&&(0,S.jsx)(Ne,{title:t(`codexAuth.noPool`)}),se.map(e=>(0,S.jsxs)(`div`,{className:`card ${N(e.id)?`card-active`:``}`,onClick:()=>!e.needsReauth&&l(e),style:{cursor:e.needsReauth?`default`:`pointer`,marginBottom:8},children:[(0,S.jsxs)(`div`,{className:`card-head`,children:[(0,S.jsx)(`span`,{className:`dot ${e.needsReauth?`dot-amber`:N(e.id)?`dot-blue`:`dot-muted`}`}),(0,S.jsx)(`strong`,{children:e.email}),(0,S.jsxs)(`span`,{className:`card-badges`,children:[e.plan&&(0,S.jsx)(`span`,{className:`badge badge-green`,children:e.plan}),(0,S.jsx)(un,{account:e,onClick:()=>A(e)}),e.needsReauth&&(0,S.jsx)(`span`,{className:`badge badge-amber`,children:t(`codexAuth.needsReauth`)}),N(e.id)&&!e.needsReauth&&(0,S.jsx)(`span`,{className:`badge badge-primary`,children:t(`codexAuth.nextSession`)})]}),(0,S.jsx)(`button`,{className:`btn-icon btn-icon-danger card-right`,"aria-label":t(`common.remove`),onClick:t=>{t.stopPropagation(),re(e.id)},children:(0,S.jsx)(ie,{width:14})})]}),e.needsReauth?(0,S.jsx)(`div`,{className:`card-sub faint`,children:t(`codexAuth.tokenExpired`)}):(0,S.jsx)(Ke,{quota:e.quota,plan:e.plan,threshold:o,t})]},e.id)),(0,S.jsxs)(`div`,{className:`card card-row`,style:{marginTop:16},children:[(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`strong`,{children:t(`codexAuth.autoSwitch`)}),(0,S.jsx)(`div`,{className:`card-sub`,children:t(`codexAuth.autoSwitchDesc`)})]}),(0,S.jsx)(`button`,{className:`toggle ${o>0?`on`:``}`,onClick:D,"aria-pressed":o>0,"aria-label":t(`codexAuth.autoSwitch`),title:t(`codexAuth.autoSwitch`),children:(0,S.jsx)(`span`,{className:`toggle-knob`})})]}),c&&(0,S.jsx)(`div`,{className:`modal-overlay`,onClick:()=>l(null),children:(0,S.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,S.jsx)(`h3`,{children:c.id===`__main__`?t(`codexAuth.switchBack`):t(`codexAuth.switchTitle`)}),(0,S.jsx)(`p`,{className:`modal-desc`,children:c.id===`__main__`?t(`codexAuth.switchBackDesc`):t(`codexAuth.switchDesc`)}),(0,S.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,S.jsx)(`strong`,{children:c.id===`__main__`?M?.email:c.email}),c.plan&&(0,S.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:c.plan})]}),c.id!==`__main__`&&(0,S.jsxs)(`div`,{className:`notice-warn`,children:[(0,S.jsx)(j,{width:14}),` `,t(`codexAuth.cacheWarning`)]}),(0,S.jsxs)(`div`,{className:`modal-actions`,children:[(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>l(null),children:t(`codexAuth.cancel`)}),(0,S.jsx)(`button`,{className:`btn btn-primary`,onClick:()=>ne(c.id===`__main__`?`__main__`:c.id),children:t(`codexAuth.setAsNext`)})]})]})}),g&&(0,S.jsx)(`div`,{className:`modal-overlay`,onClick:()=>{v(null),b(!1),T(null)},children:(0,S.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:y?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,S.jsx)(`div`,{className:`confirm-icon`,children:(0,S.jsx)(j,{width:22})}),(0,S.jsx)(`h3`,{children:t(`codexAuth.confirmResetTitle`)}),(0,S.jsx)(`p`,{className:`modal-desc`,children:t(`codexAuth.confirmResetDesc`,{count:String(g.quota?.resetCredits??0)})}),w&&w[0]&&(0,S.jsx)(`p`,{className:`faint`,style:{fontSize:12},children:t(`codexAuth.confirmWhichCredit`,{date:sn(w[0].granted_at)})}),(0,S.jsx)(`p`,{className:`faint`,style:{fontSize:12},children:t(`codexAuth.irreversible`)})]}),(0,S.jsxs)(`div`,{className:`modal-actions`,children:[(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>b(!1),children:t(`codexAuth.cancel`)}),(0,S.jsx)(`button`,{className:`btn btn-primary`,onClick:()=>oe(g.id),disabled:x,children:t(x?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`h3`,{children:[(0,S.jsx)(de,{width:16}),` `,t(`codexAuth.resetCreditsTitle`)]}),(0,S.jsxs)(`div`,{className:`card-sub`,children:[g.email,g.plan?` · ${g.plan}`:``]}),(0,S.jsx)(`div`,{style:{margin:`16px 0`},children:(g.quota?.resetCredits??0)>0?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`p`,{style:{marginBottom:12},children:t(`codexAuth.resetCreditsAvailable`,{count:String(g.quota?.resetCredits??0)})}),ee&&(0,S.jsx)(`p`,{className:`faint`,style:{fontSize:12},children:`Loading...`}),w&&w.length>0&&(0,S.jsx)(`div`,{className:`credit-list`,children:w.map((e,n)=>(0,S.jsx)(ln,{index:n,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:n===0,t},n))}),(0,S.jsx)(`button`,{className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:()=>b(!0),disabled:x,children:t(`codexAuth.useOneCredit`)}),(0,S.jsx)(`p`,{className:`card-sub`,style:{fontSize:11,marginTop:8,textAlign:`center`},children:t(`codexAuth.fifoNote`)})]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`p`,{className:`faint`,children:t(`codexAuth.noResetCredits`)}),(0,S.jsx)(`p`,{className:`modal-desc`,children:t(`codexAuth.earnCreditsHint`)})]})})]})})}),u&&(0,S.jsx)(an,{apiBase:e,onClose:()=>d(!1),onAdded:()=>{E(),p(t(`codexAuth.accountAdded`)),setTimeout(()=>p(``),5e3)}})]})}function sn(e){let t=new Date(e);return new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`}).format(t)}function cn(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function ln({index:e,grantedAt:t,expiresAt:n,isNext:r,t:i}){let a=cn(n),o=a<=7;return(0,S.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,S.jsxs)(`div`,{className:`credit-item-head`,children:[(0,S.jsx)(de,{width:13}),(0,S.jsx)(`span`,{className:`credit-item-label`,children:r?i(`codexAuth.creditNext`):i(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,S.jsx)(`span`,{className:`badge badge-amber`,style:{fontSize:10,padding:`1px 6px`},children:i(`codexAuth.creditNextBadge`)})]}),(0,S.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,S.jsx)(`span`,{children:i(`codexAuth.creditGranted`,{date:sn(t)})}),(0,S.jsx)(`span`,{className:o?`credit-urgent`:``,children:i(`codexAuth.creditExpires`,{date:sn(n),days:String(a)})})]})]})}function un({account:e,onClick:t}){let n=e.quota?.resetCredits;return n===void 0?null:(0,S.jsxs)(`button`,{type:`button`,className:`badge ${typeof n==`number`&&n>0?`badge-amber`:`badge-muted`} badge-clickable`,onClick:e=>{e.stopPropagation(),t()},"aria-label":`${n} reset credit(s)`,children:[(0,S.jsx)(de,{width:12}),n]})}function dn({apiBase:e}){let{t,locale:n}=Ce(),r=ve.find(e=>e.code===n)?.htmlLang,[i,a]=(0,_.useState)([]),[o,s]=(0,_.useState)(``),[c,l]=(0,_.useState)(``),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(null),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)(null),y=(0,_.useCallback)(async()=>{try{let t=await fetch(`${e}/api/keys`);if(t.ok){let e=await t.json();a(e.keys??[]),s(e.endpoint??``)}}catch{}},[e]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{y()},0);return()=>window.clearTimeout(e)},[y]);let b=o||`http://127.0.0.1:10100/v1/responses`,x=async()=>{d(!0);try{let t=await fetch(`${e}/api/keys`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:c||`default`})});t.ok&&(p((await t.json()).key),l(``),y())}finally{d(!1)}},C=async t=>{await fetch(`${e}/api/keys`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t})}),v(null),y()},w=()=>{f&&(navigator.clipboard.writeText(f),h(!0),setTimeout(()=>h(!1),2e3))},T=t(`api.subtitle`).split(/\{authHeader\}|\{altHeader\}/);return(0,S.jsxs)(`section`,{className:`api-page`,children:[(0,S.jsx)(`div`,{className:`page-head`,children:(0,S.jsx)(`h2`,{children:t(`api.title`)})}),(0,S.jsxs)(`p`,{className:`page-sub`,children:[T[0],(0,S.jsx)(`code`,{children:`Authorization: Bearer ocx_...`}),T[1],(0,S.jsx)(`code`,{children:`x-opencodex-api-key`}),T[2]]}),(0,S.jsxs)(`div`,{className:`panel api-panel`,children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`api.endpoint`)}),(0,S.jsx)(`code`,{className:`api-code api-code-inline`,children:b}),(0,S.jsx)(`p`,{className:`muted small`,children:t(`api.endpointNote`)})]}),f&&(0,S.jsxs)(`div`,{className:`panel api-panel panel-accent`,style:{marginTop:`1rem`},children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`api.newKeyTitle`)}),(0,S.jsx)(`p`,{className:`muted small`,children:t(`api.newKeyNote`)}),(0,S.jsxs)(`div`,{className:`api-form-row`,children:[(0,S.jsx)(`code`,{className:`api-code`,style:{flex:1,wordBreak:`break-all`},children:f}),(0,S.jsx)(`button`,{className:`btn btn-sm btn-ghost`,onClick:w,children:m?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(O,{}),` `,t(`api.copied`)]}):t(`api.copy`)})]}),(0,S.jsx)(`button`,{className:`btn btn-sm btn-ghost`,style:{alignSelf:`flex-start`},onClick:()=>p(null),children:t(`api.dismiss`)})]}),(0,S.jsxs)(`div`,{className:`panel api-panel`,style:{marginTop:`1rem`},children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`api.generateTitle`)}),(0,S.jsxs)(`div`,{className:`api-form-row`,children:[(0,S.jsx)(`input`,{type:`text`,placeholder:t(`api.keyNamePlaceholder`),value:c,onChange:e=>l(e.target.value),className:`input`}),(0,S.jsxs)(`button`,{className:`btn btn-primary`,onClick:x,disabled:u,children:[(0,S.jsx)(ae,{}),` `,t(u?`api.generating`:`api.generate`)]})]})]}),(0,S.jsxs)(`div`,{className:`panel api-panel`,style:{marginTop:`1rem`},children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`api.activeKeys`,{count:i.length})}),i.length===0?(0,S.jsx)(`p`,{className:`muted`,children:t(`api.noKeys`)}):(0,S.jsx)(`div`,{className:`tbl-wrap`,children:(0,S.jsxs)(`table`,{className:`tbl`,children:[(0,S.jsx)(`thead`,{children:(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`th`,{children:t(`api.colName`)}),(0,S.jsx)(`th`,{children:t(`api.colKey`)}),(0,S.jsx)(`th`,{children:t(`api.colCreated`)}),(0,S.jsx)(`th`,{})]})}),(0,S.jsx)(`tbody`,{children:i.map(e=>(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`td`,{children:e.name}),(0,S.jsx)(`td`,{children:(0,S.jsx)(`code`,{children:e.prefix})}),(0,S.jsx)(`td`,{children:new Date(e.createdAt).toLocaleDateString(r)}),(0,S.jsx)(`td`,{children:g===e.id?(0,S.jsxs)(`span`,{className:`api-actions`,children:[(0,S.jsx)(`button`,{className:`btn btn-sm btn-danger`,onClick:()=>C(e.id),children:t(`api.confirm`)}),(0,S.jsx)(`button`,{className:`btn btn-sm btn-ghost`,onClick:()=>v(null),children:t(`common.cancel`)})]}):(0,S.jsx)(`button`,{className:`btn btn-sm btn-ghost`,"aria-label":t(`api.deleteAria`),onClick:()=>v(e.id),children:(0,S.jsx)(ie,{})})})]},e.id))})]})})]}),(0,S.jsxs)(`div`,{className:`panel api-panel`,style:{marginTop:`1rem`},children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`api.usageTitle`)}),(0,S.jsx)(`pre`,{className:`api-code`,children:`curl ${b} \\
|
|
33
|
+
更改在新会话中生效。`,"models.v2DocsLink":`v1 / v2 是什么?`,"dash.multiAgent":`子代理`,"models.v2Conflict":`[agents] max_threads 仍存在 — codex 将拒绝启动,请从 config.toml 移除`,"models.v2Applied":`multi_agent_v2 已更新 — 新会话生效(重启 Codex 应用以刷新选择器)`,"models.v2ThreadsLabel":`最大线程`,"models.v2ThreadsDefault":`默认 (4)`,"models.v2ThreadsApplied":`线程上限已更新 — 新会话生效`,"models.v2ThreadsInvalid":`线程上限必须为 >= 1 的整数`,"models.v2ThreadsApply":`应用`,"models.capValue":`限制 {value}`,"models.contextCappedValue":`{value} 限制`,"models.setAll":`全部设置`,"models.custom":`自定义…`,"models.customApply":`应用`,"models.customPlaceholder":`令牌 (例如 420000)`,"models.applied":`已应用 — 将在下一个 Codex 回合生效。`,"models.saveFailed":`保存失败`,"models.networkError":`网络错误 — 代理在运行吗?`,"models.loadFail":`加载模型失败 — 代理在运行吗?`,"models.noRouted":`没有已路由的模型`,"models.noRoutedHint":`请先登录提供方或添加一个。`,"models.loading":`加载中…`,"models.search":`搜索模型…`,"models.showMore":`再显示 {n} 个`,"models.allowlistLabel":`仅所选`,"models.allowlistHint":`仅勾选的模型进入目录(留空 = 全部)。适用于暴露成千上万模型的提供商。`,"models.selectedCount":`已选 {n} 个`,"models.orderHint":`选择器顺序:Subagents 中的选择(按所选顺序)→ 其余已路由模型(依次按提供方、模型 ID 字母排序)→ 原生模型。可见性开关仅用于筛选,不会改变此顺序。`,"sub.subtitle":`Codex 的 {cmd} 仅将优先级最高的前 5 个模型作为覆盖项公开。在此最多选择 5 个 — 原生 gpt 或已路由模型 — opencodex 会设置它们的目录优先级,使其正好排在前面。其他模型仍可按确切名称调用;此设置仅控制显示项。`,"sub.featured":`精选`,"sub.orderHint":`此处所选并显示的顺序决定 Codex 模型选择器顶部第 1–5 位,以及 {cmd} 的默认模型候选。`,"sub.noneSelected":`未选择 — 请从下方列表选择。`,"sub.models":`模型`,"sub.search":`搜索模型(原生 gpt + 已路由)…`,"sub.noModels":`没有模型 — 请先登录提供方或添加一个。`,"sub.saved":`已保存 {n} 个模型。启动新的 Codex 会话(或运行 {cmd})以将它们作为 spawn_agent 覆盖项查看。`,"sub.saveFailed":`保存失败`,"sub.networkError":`网络错误 — 代理在运行吗?`,"sub.loadFail":`加载模型失败 — 代理在运行吗?`,"sub.loading":`加载中…`,"sub.moveUp":`上移 {m}`,"sub.moveDown":`下移 {m}`,"sub.removeAria":`移除 {m}`,"logs.title":`请求日志`,"logs.subtitle":`经过本地 opencodex 代理的最近请求,最新在前。`,"logs.autoRefresh":`自动刷新`,"logs.noRequests":`暂无请求。`,"logs.filter.surface.label":`界面`,"logs.filter.surface.all":`全部`,"logs.filter.surface.claude":`Claude`,"logs.filter.surface.codex":`Codex`,"logs.badge.claude":`Claude`,"logs.col.time":`时间`,"logs.col.request":`请求`,"logs.col.model":`模型`,"logs.col.effort":`推理强度`,"logs.col.provider":`提供方`,"logs.col.status":`状态`,"logs.col.tokens":`Token 数`,"logs.col.error":`错误`,"logs.col.upstreamReason":`上游原因`,"logs.col.duration":`耗时`,"logs.tokens.reported":`已上报`,"logs.tokens.unreported":`未上报`,"logs.tokens.unsupported":`不支持`,"logs.tokens.estimated":`估算`,"logs.tokens.input":`输入`,"logs.tokens.output":`输出`,"logs.tokens.cacheRead":`缓存命中 (c)`,"logs.tokens.cacheWrite":`缓存写入 (w)`,"logs.tokens.reasoning":`推理`,"logs.tokens.noCache":`无缓存数据`,"logs.tokens.noCacheNote":`该提供商不报告缓存 token 数`,"logs.tokens.estimatedNote":`估算值(提供商不报告精确用量)`,"logs.details":`查看详情`,"logs.detailTitle":`请求详情`,"logs.detailRaw":`原始日志`,"debug.title":`调试`,"debug.subtitle":`可选的 provider transport 与 usage 提取诊断。请求错误和 502 在 Logs 页面。`,"debug.debug":`Provider debug`,"debug.usage":`Usage 提取`,"debug.injection":`注入日志`,"debug.claude":`Claude 入站`,"debug.claudeInbound.title":`Claude 入站请求`,"debug.claudeInbound.sub":`显示 Claude Code/Desktop 实际发送的内容(thinking、effort、metadata)— 不保存提示词原文。`,"debug.claudeInbound.empty":`尚未捕获任何请求。开启后从 Claude 发送一条消息试试。`,"debug.claudeInbound.time":`时间`,"debug.claudeInbound.endpoint":`端点`,"debug.claudeInbound.model":`模型`,"debug.claudeInbound.none":`无`,"debug.reset":`清除运行时覆盖`,"debug.refresh":`刷新`,"debug.follow":`跟随滚动`,"debug.streamProvider":`Provider`,"debug.streamUsage":`Usage`,"debug.streamInjection":`Injection`,"debug.loading":`正在加载调试设置…`,"debug.emptyTitle":`调试日志已关闭`,"debug.empty":`请在上方卡片中开启 Provider debug 或 Usage extraction。通过代理发送请求后,诊断行会显示在这里。`,"debug.noLinesTitle":`等待诊断行`,"debug.noLines.provider":`提供商调试已开启,但仅记录传输异常(丢弃或格式错误的帧,以及 Cursor dial/retry 事件)。通过 Anthropic 等提供商的正常请求可能不会产生任何行。`,"debug.noLines.usage":`用量提取已开启但尚未捕获任何内容。请通过 Codex 发送请求,随后会显示在此处。`,"debug.noLines.injection":`注入日志已开启但尚未捕获任何内容。它记录协作和子代理回合中的多代理指导注入与 effort-cap 决策。`,"usage.title":`用量`,"usage.subtitle":`代理本地的 Token 用量统计。缺失的用量不会显示为零。`,"usage.loading":`正在加载用量数据…`,"usage.empty":`尚无用量记录。通过代理发送请求后将在此显示。`,"usage.range.all":`全部`,"usage.range.30d":`30 天`,"usage.range.7d":`7 天`,"usage.card.requests":`请求数`,"usage.card.measured":`已计量`,"usage.card.reported":`已上报`,"usage.card.totalTokens":`Token 总数`,"usage.card.cachedTokens":`缓存命中 Token`,"usage.card.cachedTokensHint":`从提供商缓存读取的提示 Token(命中)。缓存写入在下方单独显示。`,"usage.card.cacheWriteTokens":`缓存写入`,"usage.card.coverage":`覆盖率`,"usage.card.activeDays":`活跃天数`,"usage.section.heatmap":`每日活动`,"usage.section.models":`模型`,"usage.section.providers":`提供方`,"usage.section.coverage":`覆盖率明细`,"usage.coverage.measured":`已计量`,"usage.coverage.reported":`提供方上报`,"usage.coverage.estimated":`估算`,"usage.coverage.note":`已计量包含提供方上报和估算的 Token 数。未上报 / 不支持请求仅做计数,不会被算作 0 Token。`,"usage.search.models":`搜索模型…`,"usage.col.requests":`请求数`,"usage.col.measured":`已计量`,"usage.col.reported":`已上报`,"usage.col.tokens":`Token 数`,"usage.col.share":`占比`,"usage.heatmap.less":`少`,"usage.heatmap.more":`多`,"modal.addNamed":`添加:{label}`,"modal.add":`添加提供方`,"modal.search":`搜索提供方…`,"modal.logInWith":`使用 {label} 登录`,"modal.waitingBrowser":`等待浏览器…`,"modal.providerName":`提供方名称`,"modal.adapter":`适配器`,"modal.baseUrl":`Base URL`,"modal.defaultModel":`默认模型(可选)`,"modal.nameRequired":`提供方名称为必填项`,"modal.baseUrlRequired":`Base URL 为必填项`,"modal.networkError":`网络错误 — 代理在运行吗?`,"modal.loginFailStart":`登录启动失败`,"modal.waitingLogin":`等待浏览器登录…`,"modal.loggingIn":`登录中…`,"modal.loginTimeout":`登录超时 — 请重试。`,"nav.api":`API`,"nav.codexAuth":`Codex 认证`,"nav.openMenu":`打开菜单`,"nav.closeMenu":`关闭菜单`,"codexAuth.mainAccount":`主账号`,"codexAuth.appLogin":`应用登录`,"codexAuth.accountPool":`账号池`,"codexAuth.add":`添加`,"codexAuth.refreshQuota":`刷新额度`,"codexAuth.refreshingQuota":`刷新中...`,"codexAuth.quotaRefreshed":`额度已刷新`,"codexAuth.quotaRefreshFailed":`额度刷新失败`,"codexAuth.noPool":`尚未添加池账号。`,"codexAuth.weekly":`每周`,"codexAuth.fiveHour":`5h`,"codexAuth.monthly":`30天`,"codexAuth.resets":`重置`,"codexAuth.today":`今天`,"codexAuth.current":`当前`,"codexAuth.nextSession":`下次会话`,"codexAuth.switchTitle":`切换活跃账号?`,"codexAuth.switchDesc":`从下次 Codex 会话开始生效。当前会话保持现有账号。`,"codexAuth.cacheWarning":`切换账号会重置提示缓存。新会话从空缓存开始。`,"codexAuth.setAsNext":`设为下次会话`,"codexAuth.cancel":`取消`,"codexAuth.switchBack":`切换回主账号?`,"codexAuth.switchBackDesc":`下次 Codex 会话将使用应用登录账号。`,"codexAuth.autoSwitch":`超过 80% 时自动切换`,"codexAuth.autoSwitchDesc":`新会话会在相关额度窗口达到阈值时切换;Go/Free 只使用 30天`,"codexAuth.switched":`下次会话将使用 {email}`,"codexAuth.removeConfirm":`删除 {id}?`,"codexAuth.addTitle":`添加 Codex 账号`,"codexAuth.addIdLabel":`账号 ID(标识符)`,"codexAuth.addJsonLabel":`auth.json 内容`,"codexAuth.addHelp":`从另一台机器的 ~/.codex/auth.json 复制,或使用 codex-auth export。`,"codexAuth.importBtn":`导入`,"codexAuth.importInvalidJson":`无效的 JSON`,"codexAuth.importMissingTokens":`JSON 中缺少 access_token 或 refresh_token`,"codexAuth.importMissingId":`请输入账号 ID`,"codexAuth.accountAdded":`账号已添加到池中`,"codexAuth.addPickDesc":`使用另一个 ChatGPT 账号登录以添加到池中。`,"codexAuth.oauthLogin":`OAuth 登录`,"codexAuth.oauthDesc":`在浏览器中打开 ChatGPT 登录`,"codexAuth.importAuthJson":`导入 auth.json`,"codexAuth.importAuthJsonDesc":`从另一个 Codex 安装或 codex-auth 导出`,"codexAuth.back":`返回`,"codexAuth.oauthAlreadyInProgress":`登录已在进行中。请在浏览器中完成。`,"codexAuth.oauthWaiting":`等待浏览器中完成 ChatGPT 登录...`,"codexAuth.copyLoginLink":`复制登录链接`,"codexAuth.loginLinkCopied":`登录链接已复制`,"codexAuth.loginLinkCopyFailed":`无法复制登录链接。`,"codexAuth.oauthCancelled":`登录已取消。`,"codexAuth.needsReauth":`重新登录`,"codexAuth.tokenExpired":`令牌已过期 — 重新添加此账号以刷新`,"codexAuth.emailCollision":`此账号与您的主 Codex 登录相同。请使用其他账号。`,"codexAuth.resetCreditsTitle":`重置额度`,"codexAuth.resetCreditsAvailable":`您有 {count} 个可用重置额度。`,"codexAuth.resetCreditsDesc":`每个额度可立即重置您当前的小时和每周使用限制。`,"codexAuth.noResetCredits":`没有可用的重置额度。`,"codexAuth.earnCreditsHint":`额度每月自动发放,也可通过推荐计划获得。`,"codexAuth.creditsExpireNote":`额度在获得后 30 天过期。`,"codexAuth.useOneCredit":`使用 1 个额度`,"codexAuth.confirmResetTitle":`使用重置额度?`,"codexAuth.confirmResetDesc":`这将立即重置您当前的使用限制。剩余额度:{count} 个。`,"codexAuth.irreversible":`此操作不可撤销。`,"codexAuth.useCredit":`使用额度`,"codexAuth.redeeming":`重置中...`,"codexAuth.resetSuccess":`使用限制已重置!剩余额度:{remaining} 个。`,"codexAuth.resetNothingToReset":`当前没有需要重置的使用窗口。`,"codexAuth.resetNoCredit":`没有可用的重置额度。`,"codexAuth.resetError":`重置额度使用失败,请重试。`,"codexAuth.fifoNote":`最早获得的额度优先使用。`,"codexAuth.confirmWhichCredit":`将使用 {date} 获得的额度。`,"codexAuth.creditNext":`即将使用`,"codexAuth.creditLabel":`额度 #{n}`,"codexAuth.creditNextBadge":`NEXT`,"codexAuth.creditGranted":`获得 {date}`,"codexAuth.creditExpires":`过期 {date}(剩余 {days} 天)`,"api.title":`API 访问`,"api.subtitle":`使用生成的 API 密钥从外部应用访问 opencodex 代理。通过 {authHeader} 或 {altHeader} 请求头进行认证。`,"api.endpoint":`端点`,"api.endpointNote":`兼容 OpenAI Responses API 格式。`,"api.newKeyTitle":`已创建新密钥`,"api.newKeyNote":`请立即复制此密钥,它不会再次显示。`,"api.copy":`复制`,"api.copied":`已复制`,"api.dismiss":`关闭`,"api.generateTitle":`生成密钥`,"api.keyNamePlaceholder":`密钥名称(可选)`,"api.generate":`生成`,"api.generating":`创建中…`,"api.activeKeys":`活跃密钥({count})`,"api.noKeys":`还没有 API 密钥。请在上方生成一个。`,"api.colName":`名称`,"api.colKey":`密钥`,"api.colCreated":`创建时间`,"api.confirm":`确认`,"api.deleteAria":`删除 API 密钥`,"api.usageTitle":`使用示例`,"nav.claude":`Claude`,"claude.subtitle":`在 Claude Code 中使用 GPT、Gemini 等其他模型。`,"claude.enabledLabel":`Claude 连接`,"claude.enabledHint":`关闭后 Claude Code 无法使用此代理。`,"claude.authMode":`认证模式`,"claude.authModeHint":`Subscription 需要 Claude 账户,Proxy 无需 Anthropic 账户即可使用`,"claude.authModeSubscription":`Subscription(Claude 账户)`,"claude.authModeProxy":`Proxy(无需账户)`,"claude.systemEnv":`自动连接`,"claude.systemEnvDesc":`开启后,在任意终端运行 claude 会自动通过代理。`,"claude.systemEnvWarn":`⚠ 需要完全退出并重新打开终端应用才能生效。不推荐使用。`,"claude.fastMode":`Fast Mode (OpenAI)`,"claude.fastModeDesc":`控制 OpenAI 模型的推理速度。ON = 优先级(更快)。OFF = 默认速度。Auto = 透传客户端设置。`,"claude.fastAuto":`Auto`,"claude.fastOn":`ON`,"claude.fastOff":`OFF`,"claude.autoContext":`自动利用大上下文`,"claude.autoContextDesc":`决定 1M 标记的范围。开:所有超过 20 万 token 的模型(GPT 系列等)都有大上下文条目;关:仅真正的 1M 模型有。`,"claude.autoContextInert":`配置文件中存在旧式上下文大小值(maxContextTokens),此功能暂不生效。删除该值即可恢复。`,"claude.autoCompactWindow":`自动摘要触发点`,"claude.autoCompactDefault":`350k(默认)`,"claude.autoCompactWindowDesc":`对话达到该点时自动摘要旧内容。不会超过各模型自身上限,因此 200k 模型不受影响。`,"claude.autoCompactWindowWarn":`修改该值可能导致 GPT 模型异常——若超过模型真实上限,会在摘要触发前报错。`,"claude.injectAgents":`自动注册子代理`,"claude.injectAgentsDesc":`将“子代理”页选中的模型(以及当前默认模型)注册为 Claude Code 可派遣的代理(ocx-*)。从下一个会话开始生效。`,"claude.webSearchSidecar":`网页搜索附属服务覆盖`,"claude.webSearchSidecarHint":`仅对 Claude Code 请求覆盖主网页搜索附属服务设置。`,"claude.visionSidecar":`视觉附属服务覆盖`,"claude.visionSidecarHint":`仅对 Claude Code 请求覆盖主视觉附属服务设置。`,"claude.useMainSetting":`使用主设置`,"claude.sidecarModelPlaceholder":`主设置中的模型`,"claude.quickstart":`开始使用`,"claude.quickstartHint":`{cmd} 通过代理打开 Claude Code。你的 claude.ai 登录保持不变。`,"claude.manualEnv":`手动配置(高级)`,"claude.smallFastModel":`后台辅助模型`,"claude.smallFastModelHint":`Claude Code 用于对话摘要、主题识别等后台工作的模型。子代理的 haiku 别名也使用它。留空 = Claude 默认(Haiku)。`,"claude.slotUnset":`使用 Claude 默认值`,"claude.modelMap":`模型拦截`,"claude.modelMapHint":`拦截对特定模型的请求并重定向到你指定的模型。默认为空——添加规则后才生效。`,"claude.mapFrom":`原始模型(如 claude-sonnet-4-5)`,"claude.mapTo":`替换为(如 gemini/gemini-3-pro)`,"claude.addMapping":`添加规则`,"claude.removeMapping":`删除规则`,"claude.aliases":`可用模型`,"claude.aliasesHint":`Claude Code 的 /model 菜单中显示的模型列表。`,"claude.loading":`加载中…`,"claude.loadFail":`加载 Claude 设置失败`,"claude.saved":`已保存。`,"claude.saveFailed":`保存失败`,"claude.networkError":`网络错误 — 代理是否在运行?`,"claude.toggleAria":`切换 Claude 连接`,"claude.none":`无`}},ve=[{code:`en`,name:`English`,htmlLang:`en`},{code:`de`,name:`Deutsch`,htmlLang:`de`},{code:`ko`,name:`한국어`,htmlLang:`ko`},{code:`zh`,name:`中文`,htmlLang:`zh-CN`}],ye=`ocx-lang`;function be(){try{let e=localStorage.getItem(ye);if(e===`en`||e===`de`||e===`ko`||e===`zh`)return e}catch{}let e=typeof navigator<`u`?navigator.language.toLowerCase():`en`;return e.startsWith(`de`)?`de`:e.startsWith(`ko`)?`ko`:e.startsWith(`zh`)?`zh`:`en`}var xe=(0,_.createContext)(null);function Se(e,t){if(!t)return e;let n=e;for(let e of Object.keys(t))n=n.split(`{${e}}`).join(String(t[e]));return n}function Ce(){let e=(0,_.useContext)(xe);if(!e)throw Error(`useI18n must be used within LanguageProvider`);return e}function we(){return Ce().t}function Te({children:e}){let[t,n]=(0,_.useState)(be);return(0,_.useEffect)(()=>{let e=ve.find(e=>e.code===t)??ve[0];document.documentElement.lang=e.htmlLang;try{localStorage.setItem(`ocx-lang`,t)}catch{}},[t]),(0,S.jsx)(xe.Provider,{value:{locale:t,setLocale:n,t:(e,n)=>Se(_e[t][e]??ge[e]??e,n)},children:e})}function Ee({k:e,cmd:t,vars:n}){let{t:r}=Ce(),[i,a=``]=r(e,n).split(`{cmd}`);return(0,S.jsxs)(S.Fragment,{children:[i,(0,S.jsx)(`code`,{className:`chip`,children:t}),a]})}var De={ko:[{v:0x2386f26fc10000,s:`경`},{v:0xe8d4a51000,s:`조`},{v:1e8,s:`억`},{v:1e4,s:`만`}],zh:[{v:0x2386f26fc10000,s:`京`},{v:0xe8d4a51000,s:`兆`},{v:1e8,s:`亿`},{v:1e4,s:`万`}]};function Oe(e){return e.replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function ke(e,t){let n=De[t];if(n){for(let t of n)if(e>=t.v)return`${Oe((e/t.v).toFixed(1))}${t.s}`;return String(e)}return e<1e4?String(e):e<1e6?`${Oe((e/1e3).toFixed(1))}K`:e<1e9?`${Oe((e/1e6).toFixed(1))}M`:e<0xe8d4a51000?`${Oe((e/1e9).toFixed(1))}B`:`${Oe((e/0xe8d4a51000).toFixed(1))}T`}function Ae({on:e,onClick:t,disabled:n,label:r}){return(0,S.jsx)(`button`,{type:`button`,className:`switch${e?` on`:``}`,onClick:t,disabled:n,"aria-pressed":e,"aria-label":r??(e?`enabled`:`disabled`),children:(0,S.jsx)(`span`,{className:`knob`})})}function je({tone:e,children:t}){return(0,S.jsxs)(`div`,{className:`notice ${e===`ok`?`notice-ok`:`notice-err`}`,role:`status`,children:[e===`ok`?(0,S.jsx)(O,{}):(0,S.jsx)(j,{}),(0,S.jsx)(`span`,{children:t})]})}function Me({value:e,options:t,onChange:n,disabled:r,label:i,style:a,align:o,placement:s,dropdownStyle:c}){let[l,u]=(0,_.useState)(!1),d=(0,_.useRef)(null),f=t.find(t=>t.value===e);return(0,_.useEffect)(()=>{if(!l)return;let e=e=>{d.current&&!d.current.contains(e.target)&&u(!1)},t=e=>{e.key===`Escape`&&u(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[l]),(0,S.jsxs)(`div`,{ref:d,className:`custom-select`,style:{position:`relative`,display:`inline-block`,...a},children:[(0,S.jsxs)(`button`,{type:`button`,className:`select-trigger`,onClick:()=>!r&&u(e=>!e),disabled:r,"aria-haspopup":`listbox`,"aria-expanded":l,"aria-label":i,children:[(0,S.jsx)(`span`,{children:f?.label??e}),(0,S.jsx)(P,{style:{width:12,height:12,color:`var(--muted)`,transform:l?`rotate(90deg)`:`none`,transition:`transform .12s`}})]}),l&&(0,S.jsx)(`div`,{className:`select-dropdown${o===`right`?` select-dropdown-right`:``}${s===`right`?` select-dropdown-beside`:``}`,role:`listbox`,"aria-label":i,style:c,children:t.map(t=>(0,S.jsx)(`button`,{type:`button`,role:`option`,"aria-selected":t.value===e,className:`select-option${t.value===e?` active`:``}`,onClick:()=>{n(t.value),u(!1)},children:t.label},t.value))})]})}function Ne({icon:e,title:t,children:n,className:r,style:i}){return(0,S.jsxs)(`div`,{className:r?`empty ${r}`:`empty`,style:i,children:[e,(0,S.jsx)(`div`,{className:`title`,children:t}),n&&(0,S.jsx)(`div`,{className:`text-control`,children:n})]})}var Pe=[`low`,`medium`,`high`,`xhigh`],Fe=2,Ie=800;function Le(e){return e?.includes(`-preview.`)?`preview`:`latest`}function Re(e,t){switch(e){case`source_checkout`:return t(`dash.updateReason.source_checkout`);case`latest_unavailable`:return t(`dash.updateReason.latest_unavailable`);case`already_latest`:return t(`dash.updateReason.already_latest`);default:return t(`dash.updateReason.unknown`)}}function ze({apiBase:e}){let{locale:t,t:n}=Ce(),[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)([]),[s,c]=(0,_.useState)([]),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(null),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(!1),[x,C]=(0,_.useState)(!1),[w,T]=(0,_.useState)(!1),[ee,te]=(0,_.useState)(!1),[E,ne]=(0,_.useState)(!1),[re,D]=(0,_.useState)(`default`),[O,ae]=(0,_.useState)(!1),[A,M]=(0,_.useState)(!1),[se,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(``),[ce,I]=(0,_.useState)(``),[ue,de]=(0,_.useState)([]),[L,fe]=(0,_.useState)([]),[pe,R]=(0,_.useState)(!1),[me,he]=(0,_.useState)(``),[ge,_e]=(0,_.useState)(``),[ve,ye]=(0,_.useState)(!1),[be,xe]=(0,_.useState)(null),[Se,we]=(0,_.useState)(null),[Te,De]=(0,_.useState)([]),[Oe,Ae]=(0,_.useState)(!1),[je,ze]=(0,_.useState)(`latest`),[Be,Ve]=(0,_.useState)(!0),[He,Ue]=(0,_.useState)(!1),We=(0,_.useRef)(0),Ge=(0,_.useRef)(null),Ke=(0,_.useRef)(0),[qe,Je]=(0,_.useState)(null),[Ye,Xe]=(0,_.useState)(null),[Ze,Qe]=(0,_.useState)(null),[$e,et]=(0,_.useState)(!1),[tt,nt]=(0,_.useState)(!1);(0,_.useEffect)(()=>()=>{Ke.current+=1,Ge.current!==null&&(window.clearTimeout(Ge.current),Ge.current=null)},[]),(0,_.useEffect)(()=>{let t=async()=>{try{let[t,n,r,a,s,c]=await Promise.all([fetch(`${e}/healthz`),fetch(`${e}/api/providers`),fetch(`${e}/api/settings`),fetch(`${e}/api/sidecar-settings`),fetch(`${e}/api/shadow-call-settings`),fetch(`${e}/api/usage?range=30d`)]);i(await t.json()),o(await n.json()),u(await r.json()),f(await a.json());try{s.ok&&m(await s.json())}catch{m(null)}try{g(c.ok?await c.json():null)}catch{g(null)}nt(!1);try{let t=await fetch(`${e}/api/v2`);if(t.ok){let e=await t.json();e.multiAgentMode===`v1`||e.multiAgentMode===`v2`?D(e.multiAgentMode):D(`default`)}}catch{}try{let t=await fetch(`${e}/api/injection-model`);if(t.ok){let e=await t.json();F(e.model??``),I(e.effort??``),de(e.efforts??[]),fe(e.available??[])}}catch{}try{let t=await fetch(`${e}/api/effort-caps`);if(t.ok){let e=await t.json();he(e.effortCap??``),_e(e.subagentEffortCap??``)}}catch{}}catch{nt(!0)}};t();let n=setInterval(t,5e3);return()=>clearInterval(n)},[e]),(0,_.useEffect)(()=>{let t=async()=>{try{let t=await fetch(`${e}/api/diagnostics/project-config`);De((t.ok?await t.json():null)?.grouped??[])}catch{De([])}};t();let n=setInterval(()=>void t(),3e4);return()=>clearInterval(n)},[e]);let rt=(0,_.useCallback)(async()=>{T(!0);try{c(await(await fetch(`${e}/api/models`)).json())}catch{}finally{T(!1)}},[e]);(0,_.useEffect)(()=>{if(tt)return;let e=window.setTimeout(()=>{rt()},0);return()=>window.clearTimeout(e)},[tt,rt]),(0,_.useEffect)(()=>{if(!Ze?.id||!Ze.restart)return;let t=!1,n=Ze.latestVersion,r=async()=>{try{let n=await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(Ze.id)}`);if(n.ok){let e=await n.json();if(!t&&e.job&&(Qe(e.job),e.job.status===`failed`)){et(!1);return}}}catch{t||et(!0)}if(n)try{let r=await fetch(`${e}/healthz`,{cache:`no-store`});if(!r.ok)throw Error(`health failed`);let i=await r.json();!t&&i.version===n&&(et(!1),window.location.reload())}catch{t||et(!0)}};r();let i=setInterval(r,1500);return()=>{t=!0,clearInterval(i)}},[e,Ze?.id,Ze?.latestVersion,Ze?.restart]);let it=(0,_.useMemo)(()=>{let e={};for(let t of s)(e[t.provider]??=[]).push(t);return Object.entries(e).sort(([e],[t])=>e.localeCompare(t))},[s]);if(tt)return(0,S.jsx)(Ne,{style:{marginTop:40},icon:(0,S.jsx)(j,{}),title:(0,S.jsx)(`span`,{style:{color:`var(--red)`},children:n(`dash.cannotConnect`)}),children:(0,S.jsx)(Ee,{k:`dash.runStart`,cmd:`ocx start`})});let at=r?.status===`ok`,z=async t=>{if(!d||v)return;let n=(e,t)=>{let n={...e};return t?.model!==void 0&&(n.model=t.model),t?.backend===null?delete n.backend:t?.backend!==void 0&&(n.backend=t.backend),n},r={webSearch:n(d.webSearch,t.webSearch),vision:n(d.vision,t.vision)};y(!0),f(r);try{let n=await fetch(`${e}/api/sidecar-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok)throw Error(`save failed`);let r=await n.json();f({webSearch:r.webSearch,vision:r.vision})}catch{f(d)}finally{y(!1)}};async function ot(t){if(!(!p||x)){C(!0),m({...p,...t});try{await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}finally{C(!1)}}}let st=async t=>{if(!(O||re===t)){ae(!0);try{(await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:t})})).ok&&D(t)}catch{}finally{ae(!1)}}},ct=async()=>{if(!l||ee)return;let t=!l.codexAutoStart;te(!0),u({...l,codexAutoStart:t});try{let n=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({codexAutoStart:t})});if(!n.ok)throw Error(`save failed`);let r=await n.json();u(e=>e&&{...e,codexAutoStart:r.codexAutoStart})}catch{u(e=>e&&{...e,codexAutoStart:!t}),nt(!0)}finally{te(!1)}},lt=async()=>{if(!E){ne(!0),xe(null),we(null);try{let t=await fetch(`${e}/api/sync`,{method:`POST`}),n=await t.json();if(!t.ok)throw Error(`error`in n&&n.error?n.error:`sync failed`);xe(n);let r=n.projectConfigGrouped;r&&De(r)}catch(e){we(e instanceof Error?e.message:String(e))}finally{ne(!1)}}},ut=async(t,n=!1)=>{n&&(We.current=0),Ge.current!==null&&(window.clearTimeout(Ge.current),Ge.current=null);let r=++Ke.current;Ue(!0),Xe(null),Je(null);try{let n=await fetch(`${e}/api/update/check?tag=${t}`),i=await n.json();if(!n.ok)throw Error(`error`in i&&i.error?i.error:`update check failed`);if(r!==Ke.current)return;let a=i;if(Je(a),a.reason===`latest_unavailable`&&We.current<Fe){let e=++We.current;Ge.current=window.setTimeout(()=>{r===Ke.current&&(Ge.current=null,ut(t))},Ie*e);return}a.reason!==`latest_unavailable`&&(We.current=0),Ue(!1)}catch(e){if(r!==Ke.current)return;Xe(e instanceof Error?e.message:String(e)),Ue(!1)}},dt=()=>{Ke.current+=1,Ge.current!==null&&(window.clearTimeout(Ge.current),Ge.current=null),Ue(!1),Ae(!1)},ft=()=>{let e=Le(r?.version);ze(e),Ve(!0),Ae(!0),ut(e,!0)},pt=e=>{ze(e),ut(e,!0)},mt=async()=>{if(qe?.canUpdate){Xe(null);try{let t=await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:je,restart:Be})}),n=await t.json();if(!t.ok||!n.job)throw Error(n.error??`update failed to start`);Qe(n.job),et(!1),dt()}catch(e){Xe(e instanceof Error?e.message:String(e))}}},ht=e=>{switch(e){case`running`:return n(`dash.updateStatus.running`);case`restarting`:return n(`dash.updateStatus.restarting`);case`succeeded`:return n(`dash.updateStatus.succeeded`);case`failed`:return n(`dash.updateStatus.failed`)}};return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`page-head`,children:(0,S.jsx)(`h2`,{children:n(`nav.dashboard`)})}),(0,S.jsx)(`p`,{className:`page-sub`,children:n(`dash.subtitle`)}),(0,S.jsxs)(`div`,{className:`stat-row`,children:[(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsxs)(`div`,{className:`label`,style:{display:`flex`,alignItems:`center`,gap:6},children:[n(`dash.multiAgent`),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{width:24,height:24,minWidth:24,flex:`0 0 24px`,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},onClick:()=>M(!0),"aria-label":n(`dash.multiAgent`),"aria-haspopup":`dialog`,children:(0,S.jsx)(oe,{width:14,height:14,"aria-hidden":`true`})})]}),(0,S.jsx)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,S.jsx)(`div`,{role:`radiogroup`,"aria-label":n(`dash.multiAgent`),style:{display:`inline-flex`,borderRadius:`var(--radius-pill)`,background:`var(--surface-soft, var(--raised))`,padding:3,gap:2},children:[`v1`,`default`,`v2`].map(e=>(0,S.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":re===e,className:`btn btn-sm text-caption${re===e?` btn-primary`:` btn-ghost`}`,style:{borderRadius:`var(--radius-pill)`,minWidth:36,padding:`5px 10px`,border:`none`,background:re===e?void 0:`transparent`,color:re===e?void 0:`var(--muted)`},disabled:O,onClick:()=>void st(e),children:e==="default"?`base`:e},e))})})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`label`,children:n(`dash.status`)}),(0,S.jsxs)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,gap:9,color:at?`var(--green)`:`var(--red)`},children:[(0,S.jsx)(`span`,{className:`dot ${at?`dot-green`:`dot-red`}`}),n(at?`dash.online`:`dash.offline`)]})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`label`,children:n(`dash.version`)}),(0,S.jsx)(`div`,{className:`value mono`,children:r?.version??`—`})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`label`,children:n(`dash.uptime`)}),(0,S.jsx)(`div`,{className:`value mono`,children:r?b(r.uptime,t):`—`})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`label`,children:n(`dash.providers`)}),(0,S.jsx)(`div`,{className:`value`,children:a.length})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`label`,children:n(`dash.tokens30d`)}),(0,S.jsx)(`div`,{className:`value mono`,children:h&&h.summary.requests>0?ke(h.summary.totalTokens,t):`—`}),h&&h.summary.requests>0&&(0,S.jsx)(`div`,{className:`muted text-label`,style:{marginTop:2},children:n(`dash.coverage`).replace(`{pct}`,`${Math.round(h.summary.coverageRatio*100)}%`)})]})]}),Te.length>0&&(0,S.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,style:{marginBottom:24},role:`alert`,children:[(0,S.jsx)(j,{}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`font-semibold`,children:n(`dash.projectConfigTitle`)}),(0,S.jsx)(`div`,{className:`muted text-control`,style:{marginTop:4},children:n(`dash.projectConfigHint`)}),(0,S.jsx)(`ul`,{className:`text-control`,style:{margin:`10px 0 0`,paddingLeft:18},children:Te.map(e=>(0,S.jsxs)(`li`,{style:{marginBottom:8},children:[(0,S.jsx)(`code`,{children:e.path}),` — `,e.issues.join(`, `),(0,S.jsx)(`div`,{className:`muted`,style:{marginTop:2},children:e.bypass})]},e.path))})]})]}),re!==`v1`&&(0,S.jsx)(`div`,{className:`panel`,style:{marginBottom:24},children:(0,S.jsxs)(`div`,{className:`injection-head`,children:[(0,S.jsxs)(`span`,{className:`injection-label`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[n(`dash.effortCapLabel`),(0,S.jsxs)(`span`,{style:{position:`relative`,display:`inline-flex`},children:[(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{width:22,height:22,minWidth:22,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},onClick:()=>N(e=>!e),"aria-label":n(`dash.effortCapLabel`),"aria-expanded":se,"aria-haspopup":`dialog`,children:(0,S.jsx)(oe,{width:13,height:13,"aria-hidden":`true`})}),se&&(0,S.jsxs)(`div`,{role:`dialog`,className:`help-popup text-control font-regular leading-body`,style:{position:`absolute`,top:`calc(100% + 8px)`,left:0,width:`min(360px, calc(100vw - 48px))`,padding:`12px 16px`,border:`1px solid var(--border)`,borderRadius:`var(--radius-sm)`,background:`var(--bg)`,boxShadow:`0 8px 24px rgba(0, 0, 0, 0.14)`,color:`var(--text)`,zIndex:10},children:[(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,style:{position:`absolute`,top:4,right:4,width:24,height:24,minWidth:24},onClick:()=>N(!1),"aria-label":`Close`,children:(0,S.jsx)(ie,{width:14,height:14})}),(0,S.jsx)(`div`,{style:{paddingRight:16},children:n(`dash.effortCapHelp`)})]})]})]}),(0,S.jsx)(Me,{value:me,options:[{value:``,label:n(`dash.effortCapNone`)},...Pe.map(e=>({value:e,label:e}))],onChange:async t=>{if(!ve){ye(!0);try{let n=await fetch(`${e}/api/effort-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({effortCap:t||null})});if(n.ok){let e=await n.json();he(e.effortCap??``),_e(e.subagentEffortCap??``)}}catch{}finally{ye(!1)}}},disabled:ve,label:n(`dash.effortCapLabel`)}),(0,S.jsx)(Me,{value:ge,options:[{value:``,label:n(`dash.effortCapNone`)},...Pe.map(e=>({value:e,label:e}))],onChange:async t=>{if(!ve){ye(!0);try{let n=await fetch(`${e}/api/effort-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({subagentEffortCap:t||null})});if(n.ok){let e=await n.json();he(e.effortCap??``),_e(e.subagentEffortCap??``)}}catch{}finally{ye(!1)}}},disabled:ve,label:n(`dash.subagentEffortCapLabel`)})]})}),(0,S.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,S.jsxs)(`div`,{className:`injection-head`,children:[(0,S.jsx)(`span`,{className:`injection-label`,children:n(`dash.injectionLabel`)}),(0,S.jsx)(Me,{value:P,options:[{value:``,label:n(`dash.injectionNone`)},...L.map(e=>({value:e.namespaced,label:`${e.provider} / ${e.model}`}))],onChange:async t=>{if(!pe){R(!0);try{let n=await fetch(`${e}/api/injection-model`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({model:t||null,effort:ce||null})});if(n.ok){let e=await n.json();F(e.model??``),I(e.effort??``)}}catch{}finally{R(!1)}}},disabled:pe,label:n(`dash.injectionLabel`)}),P&&ue.length>0&&(0,S.jsx)(Me,{value:ce,options:[{value:``,label:n(`dash.injectionEffortNone`)},...ue.map(e=>({value:e,label:e}))],onChange:async t=>{if(!pe){R(!0);try{let n=await fetch(`${e}/api/injection-model`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({model:P||null,effort:t||null})});if(n.ok){let e=await n.json();F(e.model??``),I(e.effort??``)}}catch{}finally{R(!1)}}},disabled:pe,label:n(`dash.injectionEffortLabel`)}),P&&(0,S.jsx)(`span`,{className:`badge badge-green text-micro`,children:n(`dash.injectionActive`)})]}),(0,S.jsx)(`div`,{className:`muted text-control`,style:{marginTop:6},children:n(`dash.injectionHint`)})]}),(0,S.jsxs)(`div`,{className:`panel maintenance-panel`,style:{marginBottom:24},children:[(0,S.jsxs)(`div`,{className:`spread maintenance-head`,children:[(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`font-semibold`,children:n(`dash.maintenance`)}),(0,S.jsx)(`div`,{className:`muted text-control`,style:{marginTop:3},children:n(`dash.maintenanceHint`)})]}),(0,S.jsxs)(`div`,{className:`maintenance-actions`,children:[(0,S.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:lt,disabled:E,children:[(0,S.jsx)(k,{}),` `,n(E?`dash.syncing`:`dash.syncModels`)]}),(0,S.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:ft,disabled:He,children:[(0,S.jsx)(le,{}),` `,n(`dash.checkUpdate`)]})]})]}),be&&(0,S.jsxs)(`div`,{className:`notice notice-ok maintenance-notice`,role:`status`,children:[(0,S.jsx)(k,{}),(0,S.jsxs)(`span`,{children:[n(`dash.syncOk`,{count:be.added}),be.warning?` ${be.warning}`:``,be.staleAppServerHint?` ${n(`dash.syncStaleHint`)}`:``]})]}),Se&&(0,S.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`status`,children:[(0,S.jsx)(j,{}),(0,S.jsx)(`span`,{children:n(`dash.syncFailed`,{error:Se})})]}),Ze&&(0,S.jsxs)(`div`,{className:`notice ${Ze.status===`failed`?`notice-err`:`notice-ok`} maintenance-notice`,role:`status`,children:[Ze.status===`failed`?(0,S.jsx)(j,{}):(0,S.jsx)(k,{}),(0,S.jsxs)(`span`,{children:[ht(Ze.status),Ze.latestVersion?` ${Ze.currentVersion} -> ${Ze.latestVersion}.`:``,$e?` ${n(`dash.updateReconnecting`)}`:``,Ze.error?` ${Ze.error}`:``]})]})]}),(0,S.jsx)(`div`,{className:`panel`,style:{marginBottom:24},children:(0,S.jsxs)(`div`,{className:`spread`,children:[(0,S.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,S.jsx)(`div`,{className:`font-semibold`,children:n(`dash.codexAutoStart`)}),(0,S.jsx)(`div`,{className:`muted setting-hint`,children:n(`dash.codexAutoStartHint`)})]}),(0,S.jsx)(`button`,{className:`switch ${l?.codexAutoStart??!0?`on`:``}`,onClick:ct,disabled:!l||ee,"aria-label":n(`dash.codexAutoStart`),"aria-pressed":l?.codexAutoStart??!0,children:(0,S.jsx)(`span`,{className:`knob`})})]})}),(0,S.jsx)(`div`,{className:`panel`,style:{marginBottom:12},children:(0,S.jsxs)(`div`,{className:`spread setting-row`,style:{alignItems:`flex-start`},children:[(0,S.jsxs)(`div`,{className:`setting-copy`,style:{flex:1},children:[(0,S.jsx)(`div`,{className:`font-semibold`,children:n(`dash.webSearchSidecar`)}),(0,S.jsx)(`div`,{className:`muted setting-hint`,children:n(`dash.webSearchSidecarHint`)})]}),(0,S.jsx)(`div`,{className:`setting-controls`,children:(0,S.jsx)(Me,{value:d?.webSearch.model??`gpt-5.6-luna`,options:s.filter(e=>e.provider===`openai`||e.provider===`anthropic`).map(e=>({value:e.id,label:`${e.provider}/${e.id}`})),onChange:e=>{z({webSearch:{model:e,backend:s.find(t=>t.id===e)?.provider===`anthropic`?`anthropic`:`openai`}})},disabled:!d||v,label:n(`dash.sidecarModel`)})})]})}),(0,S.jsx)(`div`,{className:`panel`,style:{marginBottom:24},children:(0,S.jsxs)(`div`,{className:`spread setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-copy`,style:{flex:1},children:[(0,S.jsx)(`div`,{className:`font-semibold`,children:n(`dash.visionSidecar`)}),(0,S.jsx)(`div`,{className:`muted setting-hint`,children:n(`dash.visionSidecarHint`)})]}),(0,S.jsx)(`div`,{className:`setting-controls`,children:(0,S.jsx)(Me,{value:d?.vision.model??`gpt-5.6-luna`,options:s.filter(e=>e.provider===`openai`||e.provider===`anthropic`).map(e=>({value:e.id,label:`${e.provider}/${e.id}`})),onChange:e=>{z({vision:{model:e,backend:s.find(t=>t.id===e)?.provider===`anthropic`?`anthropic`:`openai`}})},disabled:!d||v,label:n(`dash.sidecarModel`)})})]})}),(0,S.jsx)(`div`,{className:`panel`,style:{marginBottom:12},children:(0,S.jsxs)(`div`,{className:`spread setting-row`,style:{alignItems:`center`},children:[(0,S.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,S.jsx)(`span`,{className:`font-semibold`,children:n(`dash.shadowCallIntercept`)}),(0,S.jsx)(`span`,{title:n(`dash.shadowCallTooltip`),style:{cursor:`help`,opacity:.5},children:`ⓘ`}),(0,S.jsx)(`code`,{className:`muted text-caption`,children:`⚠ 5.4-mini`})]}),(0,S.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8,alignItems:`center`},children:[(0,S.jsx)(`button`,{className:`switch ${p?.enabled?`on`:``}`,onClick:()=>ot({enabled:!p?.enabled}),disabled:!p||x,"aria-label":n(`dash.shadowCallIntercept`),"aria-pressed":p?.enabled??!1,children:(0,S.jsx)(`span`,{className:`knob`})}),(0,S.jsx)(Me,{value:p?.model??``,options:[{value:``,label:`—`},...s.map(e=>({value:e.id,label:`${e.provider}/${e.id}`}))],onChange:e=>{m(t=>t&&{...t,model:e}),ot({model:e})},disabled:!p||x||!p?.enabled,label:n(`dash.shadowCallModel`)})]})]})}),(0,S.jsxs)(`div`,{className:`h-section`,children:[n(`dash.activeProviders`),` `,(0,S.jsx)(`span`,{className:`count`,children:a.length})]}),a.length===0?(0,S.jsx)(Ne,{title:(0,S.jsx)(Ee,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,S.jsx)(`div`,{className:`tbl-wrap`,children:(0,S.jsxs)(`table`,{className:`tbl`,children:[(0,S.jsx)(`thead`,{children:(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`th`,{children:n(`dash.col.name`)}),(0,S.jsx)(`th`,{children:n(`dash.col.adapter`)}),(0,S.jsx)(`th`,{children:n(`dash.col.baseUrl`)}),(0,S.jsx)(`th`,{children:n(`dash.col.model`)})]})}),(0,S.jsx)(`tbody`,{children:a.map(e=>(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`td`,{className:`font-semibold`,children:e.name}),(0,S.jsx)(`td`,{children:(0,S.jsx)(`span`,{className:`chip`,children:e.adapter})}),(0,S.jsx)(`td`,{className:`muted mono text-label`,children:e.baseUrl}),(0,S.jsx)(`td`,{className:`muted`,children:e.defaultModel??`—`})]},e.name))})]})}),(0,S.jsxs)(`div`,{className:`h-section`,children:[n(`dash.availableModels`),` `,(0,S.jsx)(`span`,{className:`count`,children:s.length}),w&&(0,S.jsx)(`span`,{className:`spin`,style:{marginLeft:4}})]}),s.length===0&&!w?(0,S.jsx)(Ne,{title:n(`dash.noModels`)}):(0,S.jsx)(`div`,{className:`stack`,style:{gap:16},children:it.map(([e,t])=>(0,S.jsxs)(`div`,{className:`model-group`,children:[(0,S.jsxs)(`div`,{className:`model-group-head`,children:[e,(0,S.jsx)(`span`,{className:`count`,children:t.length})]}),(0,S.jsx)(`div`,{className:`model-grid`,children:t.map(e=>(0,S.jsx)(`div`,{className:`model-card`,children:(0,S.jsx)(`div`,{className:`id`,children:e.id})},`${e.provider}/${e.id}`))})]},e))}),Oe&&(0,S.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`update-title`,children:(0,S.jsxs)(`div`,{className:`modal-card`,children:[(0,S.jsxs)(`div`,{className:`modal-head`,children:[(0,S.jsx)(`h3`,{id:`update-title`,children:n(`dash.updateTitle`)}),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:dt,"aria-label":n(`common.cancel`),children:(0,S.jsx)(ie,{})})]}),(0,S.jsx)(`div`,{className:`modal-desc`,children:n(`dash.updateDesc`)}),(0,S.jsxs)(`div`,{className:`update-row`,children:[(0,S.jsx)(`label`,{className:`field-label`,htmlFor:`update-channel`,children:n(`dash.updateChannel`)}),(0,S.jsx)(Me,{value:je,options:[{value:`latest`,label:`latest`},{value:`preview`,label:`preview`}],onChange:e=>pt(e),disabled:He,label:n(`dash.updateChannel`)})]}),He&&(0,S.jsx)(Ne,{className:`update-empty`,icon:(0,S.jsx)(`span`,{className:`spin`}),title:n(`dash.updateChecking`)}),Ye&&(0,S.jsxs)(`div`,{className:`notice notice-err`,role:`status`,children:[(0,S.jsx)(j,{}),(0,S.jsx)(`span`,{children:Ye})]}),qe&&!He&&(0,S.jsxs)(`div`,{className:`update-box`,children:[(0,S.jsxs)(`div`,{className:`spread`,children:[(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`muted text-label`,children:n(`dash.updateInstalled`)}),(0,S.jsx)(`div`,{className:`mono`,children:qe.currentVersion})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`muted text-label`,children:n(`dash.updateLatest`)}),(0,S.jsx)(`div`,{className:`mono`,children:qe.latestVersion??`—`})]}),(0,S.jsx)(`span`,{className:`badge ${qe.updateAvailable?`badge-green`:`badge-muted`}`,children:qe.updateAvailable?n(`dash.updateAvailable`):n(`dash.updateCurrent`)})]}),(0,S.jsxs)(`div`,{className:`muted update-command`,children:[n(`dash.updateCommand`),` `,(0,S.jsx)(`code`,{className:`chip`,children:qe.command})]}),qe.reason===`source_checkout`&&(0,S.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,S.jsx)(j,{}),` `,n(`dash.updateSource`)]}),qe.reason===`latest_unavailable`&&(0,S.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,S.jsx)(j,{}),` `,n(`dash.updateUnavailable`),(0,S.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:He,onClick:()=>{ut(je,!0)},style:{marginLeft:12},children:[(0,S.jsx)(k,{}),` `,n(`dash.updateRetry`)]})]}),!qe.canUpdate&&qe.reason!==`latest_unavailable`&&qe.reason!==`source_checkout`&&(0,S.jsxs)(`div`,{className:`update-recheck`,children:[(0,S.jsx)(`span`,{className:`muted update-recheck-reason`,children:n(`dash.updateCannotAuto`,{reason:Re(qe.reason,n)})}),(0,S.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:He,onClick:()=>{ut(je,!0)},children:[(0,S.jsx)(k,{}),` `,n(He?`dash.updateChecking`:`dash.updateRecheck`)]})]}),qe.canUpdate&&(0,S.jsxs)(`div`,{className:`spread update-restart`,children:[(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`font-semibold`,children:n(`dash.updateRestart`)}),(0,S.jsx)(`div`,{className:`muted text-label`,children:n(`dash.updateRestartHint`)})]}),(0,S.jsx)(`button`,{type:`button`,className:`switch ${Be?`on`:``}`,onClick:()=>Ve(e=>!e),"aria-label":n(`dash.updateRestart`),"aria-pressed":Be,children:(0,S.jsx)(`span`,{className:`knob`})})]})]}),(0,S.jsxs)(`div`,{className:`modal-actions`,children:[(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:dt,children:n(`common.cancel`)}),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:mt,disabled:!qe?.canUpdate||He,children:n(`dash.runUpdate`)})]})]})}),A&&(0,S.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":n(`dash.multiAgent`),onClick:()=>M(!1),onKeyDown:e=>{e.key===`Escape`&&M(!1)},children:(0,S.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,S.jsxs)(`div`,{className:`modal-head`,children:[(0,S.jsx)(`h3`,{children:n(`dash.multiAgent`)}),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>M(!1),"aria-label":`Close`,children:(0,S.jsx)(ie,{})})]}),(0,S.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:n(`models.v2Help`)}),(0,S.jsx)(`div`,{style:{marginTop:12},children:(0,S.jsx)(`a`,{className:`text-control`,href:`https://lidge-jun.github.io/opencodex/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:n(`models.v2DocsLink`)})}),(0,S.jsx)(`div`,{className:`modal-actions`,children:(0,S.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>M(!1),children:`OK`})})]})})]})}function Be(e){let t={adapter:e.adapter.trim(),baseUrl:e.baseUrl.trim()};return(e.authMode===`key`||e.authMode===`forward`)&&(t.authMode=e.authMode),e.authMode===`key`&&e.apiKey.trim()&&(t.apiKey=e.apiKey.trim()),e.defaultModel.trim()&&(t.defaultModel=e.defaultModel.trim()),t}var Ve=[{id:`custom`,label:`Custom provider`,adapter:`openai-chat`,baseUrl:``,auth:`key`}];function He({apiBase:e,existingNames:t,onClose:n,onAdded:r}){let[i,a]=(0,_.useState)(``),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(``),[m,h]=(0,_.useState)([]),g=we(),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(``),[C,w]=(0,_.useState)(``),[T,ee]=(0,_.useState)(!1),[te,E]=(0,_.useState)(``),[ne,re]=(0,_.useState)(!0),[D,O]=(0,_.useState)(Ve),ae=(0,_.useRef)(null),k=(0,_.useRef)(!0);(0,_.useEffect)(()=>{ae.current?.focus()},[]),(0,_.useEffect)(()=>()=>{k.current=!1},[]),(0,_.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,_.useEffect)(()=>{fetch(`${e}/api/oauth/providers`).then(e=>e.json()).then(e=>h(e.providers??[])).catch(()=>{})},[e]),(0,_.useEffect)(()=>{fetch(`${e}/api/provider-presets`).then(e=>e.json()).then(e=>{Array.isArray(e.providers)&&e.providers.length>0&&O(e.providers)}).catch(()=>{})},[e]);let A=(0,_.useMemo)(()=>{let e=i.trim().toLowerCase();return e?D.filter(t=>t.label.toLowerCase().includes(e)||t.id.toLowerCase().includes(e)):D},[i,D]),j=e=>{s(e),l({name:e.id===`custom`?``:e.id,adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,apiKey:``,defaultModel:e.defaultModel??``}),p(``),x(``)},oe=()=>{s(null),l(null),p(``),x(``)},M=async()=>{if(!c)return;let t=c.name.trim();if(!t){p(`Provider name is required`);return}if(!c.baseUrl.trim()){p(`Base URL is required`);return}let n=Be(c);d(!0),p(``);try{let i=await fetch(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t,provider:n})});if(!i.ok){p((await i.json().catch(()=>({}))).error||`Failed (${i.status})`);return}r(t)}catch{p(`Network error — is the proxy running?`)}finally{d(!1)}},se=async t=>{y(!0),x(``),w(``),E(``);try{let n=await fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t})}),i=await n.json();if(!k.current)return;if(!n.ok){x(i.error===`unknown oauth provider`?`OAuth login for this provider arrives in the next update — use an API key for now.`:i.error||`Login failed to start`);return}i.url?(window.open(i.url,`_blank`),x(`Waiting for browser login…`)):x(i.instructions||`Logging in…`);for(let n=0;n<100;n++){if(await new Promise(e=>setTimeout(e,2e3)),!k.current)return;let n=await fetch(`${e}/api/oauth/status?provider=${t}`).then(e=>e.json()).catch(()=>null);if(!k.current)return;if(n?.loggedIn){r(t);return}if(n?.error){x(`Login error: ${n.error}`);return}}x(`Login timed out — try again.`)}catch{k.current&&x(`Network error — is the proxy running?`)}finally{k.current&&y(!1)}},N=async t=>{let n=C.trim();if(!(!n||T)){ee(!0),E(``);try{let r=await fetch(`${e}/api/oauth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t,input:n})}),i=await r.json().catch(()=>({}));if(!k.current)return;if(!r.ok){re(!1),E(g(`prov.pasteFail`,{error:i.error||r.statusText}));return}w(``),re(!0),E(g(`prov.pasteOk`))}catch{k.current&&(re(!1),E(g(`prov.pasteFail`,{error:`network error`})))}finally{k.current&&ee(!1)}}},P=c?t.includes(c.name.trim())&&c.name.trim()!==``:!1,F=o?.id===`custom`,ce=c?.authMode===`local`;return(0,S.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Add provider`,className:`modal-overlay`,onClick:n,children:(0,S.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,S.jsxs)(`div`,{className:`modal-head`,children:[(0,S.jsx)(`h3`,{children:o?`Add: ${o.label}`:`Add provider`}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-icon`,"aria-label":`Close`,onClick:n,children:(0,S.jsx)(ie,{})})]}),o?c&&(o.auth===`oauth`&&c.authMode===`oauth`?(0,S.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,S.jsx)(`div`,{className:`muted text-control`,children:o.note??`Log in with your account — no API key needed.`}),m.includes(o.oauthProvider??``)?(0,S.jsxs)(`button`,{className:`btn btn-primary`,onClick:()=>se(o.oauthProvider),disabled:v,style:{width:`100%`,padding:`12px 16px`},children:[(0,S.jsx)(ue,{}),v?`Waiting for browser…`:`Log in with ${o.label}`]}):(0,S.jsxs)(`div`,{className:`text-control`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:[`OAuth login for `,o.label,` arrives in the next update. Use an API key for now.`]}),b&&(0,S.jsx)(`div`,{className:`text-label`,style:{color:/error|update|timed/.test(b)?`var(--amber)`:`var(--accent-hover)`},children:b}),v&&(0,S.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6},children:[(0,S.jsx)(`div`,{className:`muted text-label`,children:g(`prov.pasteRedirectHint`)}),(0,S.jsxs)(`div`,{style:{display:`flex`,gap:8},children:[(0,S.jsx)(`input`,{type:`text`,autoComplete:`off`,spellCheck:!1,value:C,onChange:e=>w(e.target.value),onKeyDown:e=>{e.key===`Enter`&&o.oauthProvider&&(e.preventDefault(),N(o.oauthProvider))},placeholder:g(`prov.pasteRedirect`),"aria-label":g(`prov.pasteRedirect`),disabled:T,className:`input text-label`,style:{flex:1}}),(0,S.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,disabled:T||!C.trim()||!o.oauthProvider,onClick:()=>o.oauthProvider&&void N(o.oauthProvider),children:g(T?`prov.pasteSubmitting`:`prov.pasteSubmit`)})]}),te&&(0,S.jsx)(`div`,{className:`text-label`,style:{color:ne?`var(--accent-hover)`:`var(--amber)`},children:te})]}),(0,S.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,S.jsx)(`button`,{className:`link-btn`,onClick:()=>{l({...c,authMode:`key`}),x(``),w(``),E(``)},children:`Use an API key instead`}),(0,S.jsx)(`div`,{style:{flex:1}}),(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:oe,children:`Back`})]})]}):(0,S.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!F&&!ce&&!o.keyOptional&&o.note&&(0,S.jsxs)(`details`,{className:`setup-guide`,children:[(0,S.jsx)(`summary`,{children:`Setup guide`}),(0,S.jsxs)(`ol`,{className:`text-label leading-relaxed`,style:{margin:`8px 0 0`,paddingLeft:18,color:`var(--muted)`},children:[(0,S.jsxs)(`li`,{children:[`Go to `,(0,S.jsxs)(`a`,{href:o.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:[o.label,` dashboard`]}),` and copy your API key`]}),(0,S.jsx)(`li`,{children:`Paste it in the API key field below`}),(0,S.jsx)(`li`,{children:`Click Add provider — models are auto-discovered`})]}),o.note&&(0,S.jsx)(`div`,{className:`text-label`,style:{color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:o.note})]}),(0,S.jsx)(Ue,{label:`Provider name`,children:(0,S.jsx)(`input`,{className:`input`,value:c.name,onChange:e=>l({...c,name:e.target.value}),placeholder:`e.g. openrouter`})}),P&&(0,S.jsxs)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:[`Provider "`,c.name.trim(),`" exists and will be overwritten.`]}),(0,S.jsx)(Ue,{label:`Adapter`,children:(0,S.jsx)(`select`,{className:`input`,value:c.adapter,onChange:e=>l({...c,adapter:e.target.value}),children:[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`].map(e=>(0,S.jsx)(`option`,{value:e,children:e},e))})}),(0,S.jsx)(Ue,{label:`Base URL`,children:(0,S.jsx)(`input`,{className:`input`,value:c.baseUrl,onChange:e=>l({...c,baseUrl:e.target.value}),placeholder:`https://...`})}),c.authMode===`forward`?(0,S.jsxs)(`div`,{className:`text-label`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:[`No key needed — the proxy forwards your `,(0,S.jsx)(`code`,{className:`chip`,children:`codex login`}),` credentials to this provider.`]}):c.authMode===`local`?(0,S.jsx)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:`No API key is stored. This adds Cursor's static public model catalog for Codex, but live Cursor transport and native file/shell execution remain disabled until audited.`}):o.keyOptional?(0,S.jsxs)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:[(0,S.jsx)(`strong`,{children:`Free tier`}),` — `,o.note??`No API key required. Works out of the box.`]}):(0,S.jsxs)(S.Fragment,{children:[o.dashboardUrl&&(0,S.jsxs)(`a`,{className:`text-label`,href:o.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,S.jsx)(I,{style:{width:14,height:14}}),`Get your `,o.label,` API key`,(0,S.jsx)(le,{style:{width:13,height:13}})]}),(0,S.jsx)(Ue,{label:`API key`,children:(0,S.jsx)(`input`,{className:`input`,type:`password`,value:c.apiKey,onChange:e=>l({...c,apiKey:e.target.value}),placeholder:`sk-… (or $ENV_VAR)`})})]}),(0,S.jsx)(Ue,{label:`Default model (optional)`,children:(0,S.jsx)(`input`,{className:`input`,value:c.defaultModel,onChange:e=>l({...c,defaultModel:e.target.value}),placeholder:`e.g. gpt-5.5`})}),f&&(0,S.jsx)(`div`,{className:`text-control`,role:`alert`,style:{color:`var(--red)`},children:f}),(0,S.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,S.jsx)(`button`,{className:`btn btn-primary`,onClick:M,disabled:u,children:u?`Adding…`:`Add provider`}),o.auth===`oauth`&&(0,S.jsx)(`button`,{className:`link-btn`,onClick:()=>{l({...c,authMode:`oauth`}),p(``)},children:`← Use OAuth login`}),(0,S.jsx)(`div`,{style:{flex:1}}),(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:oe,children:`Back`})]})]})):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`input`,{ref:ae,className:`input`,value:i,onChange:e=>a(e.target.value),placeholder:`Search providers…`}),(0,S.jsxs)(`div`,{style:{marginTop:12,maxHeight:360,overflowY:`auto`,display:`flex`,flexDirection:`column`,gap:6},children:[A.map(e=>(0,S.jsxs)(`button`,{className:`list-row`,onClick:()=>j(e),children:[(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`title`,children:e.label}),(0,S.jsxs)(`div`,{className:`sub`,children:[(0,S.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,S.jsxs)(`div`,{style:{display:`flex`,gap:4,alignItems:`center`,flexShrink:0},children:[e.keyOptional&&(0,S.jsx)(`span`,{className:`badge badge-green`,children:`Free`}),e.auth===`oauth`?(0,S.jsx)(`span`,{className:`badge badge-accent`,children:`OAuth`}):e.auth===`forward`?(0,S.jsx)(`span`,{className:`badge badge-green`,children:`Codex login`}):e.auth===`local`?(0,S.jsx)(`span`,{className:`badge badge-amber`,children:`Local`}):e.keyOptional?null:(0,S.jsx)(`span`,{className:`badge badge-muted`,children:`API key`})]})]},e.id)),A.length===0&&(0,S.jsx)(`div`,{className:`muted text-control`,style:{padding:8},children:`No match.`})]})]})]})})}function Ue({label:e,children:t}){return(0,S.jsxs)(`label`,{style:{display:`block`},children:[(0,S.jsx)(`span`,{className:`field-label`,children:e}),t]})}function We(e){let t=e?.trim().toLowerCase();return t===`go`||t===`free`}function Ge(e,t){return!e||!We(t)?e:{...e.monthlyPercent===void 0?{}:{monthlyPercent:e.monthlyPercent},...e.monthlyResetAt===void 0?{}:{monthlyResetAt:e.monthlyResetAt},...e.resetCredits===void 0?{}:{resetCredits:e.resetCredits},updatedAt:e.updatedAt}}function Ke({quota:e,plan:t,threshold:n,t:r,className:i}){let a=Ge(e,t);if(!a)return null;let o=[typeof a.fiveHourPercent==`number`?{label:r(`codexAuth.fiveHour`),percent:a.fiveHourPercent,resetAt:a.fiveHourResetAt}:null,typeof a.weeklyPercent==`number`?{label:r(`codexAuth.weekly`),percent:a.weeklyPercent,resetAt:a.weeklyResetAt}:null,typeof a.monthlyPercent==`number`?{label:r(`codexAuth.monthly`),percent:a.monthlyPercent,resetAt:a.monthlyResetAt}:null,...a.customWindows??[]].filter(e=>e!==null);return o.length===0?null:(0,S.jsx)(`div`,{className:`quota-compact${i?` ${i}`:``}`,children:o.map((e,t)=>(0,S.jsx)(qe,{label:e.label,percent:e.percent,resetAt:e.resetAt,threshold:n,t:r},`${e.label}-${t}`))})}function qe({label:e,percent:t,resetAt:n,threshold:r,t:i}){let a=r>0&&t>=r?`bar-amber`:`bar-green`,o=Ye(n,i);return(0,S.jsxs)(`div`,{className:`quota-row`,children:[(0,S.jsx)(`span`,{className:`quota-label`,children:e}),(0,S.jsx)(`span`,{className:`quota-reset-label`,children:i(`codexAuth.resets`)}),(0,S.jsx)(`span`,{className:`quota-reset-day`,children:o.day}),(0,S.jsx)(`span`,{className:`quota-reset-time`,children:o.time}),(0,S.jsx)(`div`,{className:`bar`,children:(0,S.jsx)(`div`,{className:`bar-fill ${a}`,style:{width:`${Je(t)}%`}})}),(0,S.jsxs)(`span`,{className:`quota-val`,children:[Math.round(t),`%`]})]})}function Je(e){return Math.max(0,Math.min(100,Math.round(e)))}function Ye(e,t){if(typeof e!=`number`||!Number.isFinite(e))return{day:``,time:``};let n=e<1e10?e*1e3:e,r=new Date(n),i=new Date,a=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(r);return r.getFullYear()===i.getFullYear()&&r.getMonth()===i.getMonth()&&r.getDate()===i.getDate()?{day:t(`codexAuth.today`),time:a}:{day:new Intl.DateTimeFormat(void 0,{month:`numeric`,day:`numeric`}).format(r),time:a}}var Xe={anthropic:`claude-color.svg`,"anthropic-apikey":`claude-color.svg`,"azure-openai":`openai.svg`,chatgpt:`openai.svg`,"cloudflare-ai-gateway":`cloudflare-ai-gateway-color.svg`,cursor:`cursor-color.svg`,deepseek:`deepseek-color.svg`,firepass:`firepass-color.svg`,fireworks:`fireworks-color.svg`,github:`github-copilot-color.svg`,"github-copilot":`copilot-color.svg`,"gitlab-duo":`gitlab-duo-color.svg`,google:`gemini-color.svg`,"google-antigravity":`antigravity-color.svg`,"google-vertex":`gemini-color.svg`,groq:`groq-color.svg`,huggingface:`huggingface-color.svg`,kimi:`kimi-color.svg`,"kimi-code":`kimi-color.svg`,kiro:`kiro-color.svg`,"lm-studio":`lm-studio-color.svg`,mistral:`mistral-color.svg`,moonshot:`moonshot-color.svg`,nvidia:`nvidia-color.svg`,ollama:`ollama-color.svg`,"ollama-cloud":`ollama-color.svg`,openai:`openai.svg`,"openai-apikey":`openai.svg`,"opencode-free":`opencode.svg`,"opencode-go":`opencode.svg`,"opencode-zen":`opencode.svg`,openrouter:`openrouter-color.svg`,qianfan:`qianfan-color.svg`,"qwen-portal":`qwen-portal-color.svg`,"vercel-ai-gateway":`vercel-ai-gateway-color.svg`,vllm:`vllm-color.svg`,xai:`grok-color.svg`,"mimo-free":`xiaomi-color.svg`,xiaomi:`xiaomi-color.svg`};function Ze(e){return Xe[e.toLowerCase()]}function Qe(e){let t=Ze(e);return t?`/provider-icons/${t}`:void 0}var $e={xai:`xAI (Grok)`,anthropic:`Anthropic (Claude)`,kimi:`Kimi (Moonshot)`},et=e=>$e[e]??e;function tt({apiBase:e}){let t=we(),[n,r]=(0,_.useState)(null),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(``),[u,d]=(0,_.useState)(``),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)([]),[g,v]=(0,_.useState)({}),[y,b]=(0,_.useState)({}),[x,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),[ee,te]=(0,_.useState)(``),[E,ne]=(0,_.useState)(!1),[re,D]=(0,_.useState)(``),[O,ie]=(0,_.useState)({}),[k,j]=(0,_.useState)({}),[oe,M]=(0,_.useState)({}),[se,N]=(0,_.useState)(null),[F,I]=(0,_.useState)(``),de=(0,_.useRef)(!0),L=(e,t)=>{d(e),p(t)};(0,_.useEffect)(()=>(de.current=!0,()=>{de.current=!1}),[]);let fe=(0,_.useCallback)(async()=>{try{let t=await(await fetch(`${e}/api/config`)).json();r(t),l(JSON.stringify(t,null,2))}catch{L(t(`prov.loadConfigFail`),!1)}},[e,t]),pe=(0,_.useCallback)(async()=>{try{let t=(await fetch(`${e}/api/oauth/providers`).then(e=>e.json())).providers??[];h(t);let n=await Promise.all(t.map(async t=>[t,await fetch(`${e}/api/oauth/status?provider=${t}`).then(e=>e.json()).catch(()=>({loggedIn:!1}))]));v(Object.fromEntries(n))}catch{}},[e]),R=(0,_.useCallback)(async(t=!1)=>{try{let n=await fetch(`${e}/api/provider-quotas${t?`?refresh=1`:``}`).then(e=>e.json());b(Object.fromEntries((n.reports??[]).map(e=>[e.provider,e])))}catch{b({})}},[e]),me=(0,_.useCallback)(async t=>{let n=await Promise.all(t.map(async t=>{let n=await fetch(`${e}/api/oauth/accounts?provider=${t}`).then(e=>e.json()).catch(()=>null);return[t,{activeAccountId:n?.activeAccountId??null,accounts:n?.accounts??[]}]}));ie(Object.fromEntries(n))},[e]),he=async(n,r)=>{if(r.active)return;let i=await fetch(`${e}/api/oauth/accounts/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:n,accountId:r.id})});i.ok?(L(t(`prov.accountSwitched`,{email:r.email??r.id}),!0),me(Object.keys(O)),pe(),R(!0)):L((await i.json().catch(()=>({}))).error||t(`prov.accountSwitchFail`),!1)},ge=(0,_.useCallback)(async t=>{let n=await Promise.all(t.map(async t=>[t,(await fetch(`${e}/api/providers/keys?name=${encodeURIComponent(t)}`).then(e=>e.json()).catch(()=>null))?.keys??[]]));M(Object.fromEntries(n))},[e]),_e=async(n,r)=>{if(r.active)return;let i=await fetch(`${e}/api/providers/keys/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:n,id:r.id})});i.ok?(L(t(`prov.keySwitched`,{key:r.label??r.masked}),!0),ge(Object.keys(oe)),R(!0)):L((await i.json().catch(()=>({}))).error||t(`prov.keySwitchFail`),!1)},ve=async(n,r)=>{window.confirm(t(`prov.keyRemoveConfirm`,{key:r.label??r.masked}))&&(await fetch(`${e}/api/providers/keys?name=${encodeURIComponent(n)}&id=${encodeURIComponent(r.id)}`,{method:`DELETE`})).ok&&(L(t(`prov.keyRemoved`,{key:r.label??r.masked}),!0),ge(Object.keys(oe)),fe(),R(!0))},ye=async n=>{let r=F.trim();if(!r)return;let i=await fetch(`${e}/api/providers/keys`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:n,key:r})});i.ok?(L(t(`prov.keyAdded`,{name:n}),!0),I(``),N(null),ge(Object.keys(oe).includes(n)?Object.keys(oe):[...Object.keys(oe),n]),fe(),R(!0)):L((await i.json().catch(()=>({}))).error||t(`prov.keyAddFail`),!1)},be=async(n,r)=>{window.confirm(t(`prov.accountRemoveConfirm`,{email:r.email??r.id}))&&(await fetch(`${e}/api/oauth/accounts?provider=${n}&id=${encodeURIComponent(r.id)}`,{method:`DELETE`})).ok&&(L(t(`prov.accountRemoved`,{email:r.email??r.id}),!0),me(Object.keys(O)),pe(),R(!0))};(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{fe(),pe(),R()},0);return()=>window.clearTimeout(e)},[fe,pe,R]);let xe=(0,_.useMemo)(()=>n?Object.entries(n.providers).filter(([,e])=>e.authMode===`oauth`).map(([e])=>e):[],[n]);(0,_.useEffect)(()=>{if(xe.length===0)return;let e=window.setTimeout(()=>{me(xe)},0);return()=>window.clearTimeout(e)},[me,xe]);let Se=(0,_.useMemo)(()=>n?Object.entries(n.providers).filter(([,e])=>e.hasApiKey&&e.authMode!==`oauth`&&e.authMode!==`forward`).map(([e])=>e):[],[n]);(0,_.useEffect)(()=>{if(Se.length===0)return;let e=window.setTimeout(()=>{ge(Se)},0);return()=>window.clearTimeout(e)},[ge,Se]);let Ce=async()=>{try{let n=JSON.parse(c);(await fetch(`${e}/api/config`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)})).ok?(L(t(`prov.saved`),!0),a(!1),fe(),R(!0)):L(t(`prov.saveFailed`),!1)}catch{L(t(`prov.invalidJson`),!1)}},Te=async(n,r=!1)=>{C(n),d(``),T(null),te(``),D(``);try{let i=await fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r?{provider:n,addAccount:!0}:{provider:n})}),a=await i.json();if(!i.ok){L(a.error||t(`prov.loginFailStart`,{provider:et(n)}),!1);return}(a.url||a.instructions)&&T({provider:n,url:a.url,instructions:a.instructions});let o=O[n]?.accounts.length??0;for(let i=0;i<150&&de.current;i++){await new Promise(e=>setTimeout(e,2e3));let i=await fetch(`${e}/api/oauth/status?provider=${n}`).then(e=>e.json()).catch(()=>null);if(i){if(r?(i.accounts?.length??0)>o||i.done===!0&&!i.error:i.loggedIn){v(e=>({...e,[n]:i})),L(t(`prov.loginOk`,{provider:et(n),cmd:`ocx sync`}),!0),T(null),te(``),D(``),fe(),me(Object.keys(O).includes(n)?Object.keys(O):[...Object.keys(O),n]),R(!0);break}if(i.error){v(e=>({...e,[n]:i})),L(t(`prov.loginError`,{provider:et(n),error:i.error}),!1),T(null);break}}}}catch{L(t(`prov.loginRequestFail`,{provider:et(n)}),!1)}finally{de.current&&C(null)}},Ee=async n=>{let r=ee.trim();if(!(!r||E)){ne(!0),D(``);try{let i=await fetch(`${e}/api/oauth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:n,input:r})}),a=await i.json().catch(()=>({}));if(!i.ok){D(t(`prov.pasteFail`,{error:a.error||i.statusText}));return}te(``),D(t(`prov.pasteOk`))}catch{D(t(`prov.pasteFail`,{error:`network error`}))}finally{de.current&&ne(!1)}}},De=async n=>{await fetch(`${e}/api/oauth/logout?provider=${n}`,{method:`POST`}).catch(()=>{}),v(e=>({...e,[n]:{loggedIn:!1}})),L(t(`prov.logoutOk`,{provider:et(n)}),!0),fe(),R(!0)},Oe=async n=>{window.confirm(t(`prov.removeConfirm`,{name:n}))&&((await fetch(`${e}/api/providers?name=${encodeURIComponent(n)}`,{method:`DELETE`})).ok?(L(t(`prov.removed`,{name:n}),!0),fe(),pe(),R(!0)):L(t(`prov.removeFail`,{name:n}),!1))},ke=async(n,r)=>{let i=await fetch(`${e}/api/providers?name=${encodeURIComponent(n)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({disabled:r})});if(i.ok){L(t(r?`prov.disabled`:`prov.enabled`,{name:n}),!0),fe(),pe(),R(!0);return}L((await i.json().catch(()=>({}))).error||t(r?`prov.disableFail`:`prov.enableFail`,{name:n}),!1)};if(!n)return(0,S.jsx)(`div`,{className:`muted`,children:t(`prov.loadingConfig`)});let Ae=Object.entries(n.providers).filter(([e,t])=>t.hasApiKey&&t.authMode!==`oauth`&&t.authMode!==`forward`&&!m.includes(e)).map(([e])=>e);return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{className:`page-head`,children:[(0,S.jsx)(`h2`,{children:t(`nav.providers`)}),(0,S.jsx)(`div`,{className:`row`,children:i?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`button`,{className:`btn btn-primary`,onClick:Ce,children:t(`common.save`)}),(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>{a(!1),l(JSON.stringify(n,null,2))},children:t(`common.cancel`)})]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`button`,{className:`btn btn-primary`,onClick:()=>s(!0),children:[(0,S.jsx)(ae,{}),t(`prov.add`)]}),(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>a(!0),children:t(`prov.editJson`)})]})})]}),(0,S.jsx)(`p`,{className:`page-sub`,children:t(`prov.subtitle`)}),u&&(0,S.jsx)(je,{tone:f?`ok`:`err`,children:u}),(0,S.jsxs)(`div`,{className:`panel panel-accent`,style:{marginBottom:18},children:[(0,S.jsxs)(`div`,{className:`row`,style:{marginBottom:14},children:[(0,S.jsx)(ue,{style:{width:16,height:16,color:`var(--accent)`}}),(0,S.jsx)(`span`,{className:`font-semibold`,children:t(`prov.accountLogin`)})]}),(0,S.jsxs)(`div`,{className:`oauth-grid`,children:[m.length===0&&Ae.length===0&&(0,S.jsx)(`span`,{className:`muted text-control`,style:{gridColumn:`1 / -1`},children:t(`prov.noOauth`)}),m.map(e=>{let n=g[e]??{loggedIn:!1},r=x===e,i=Qe(e);return(0,S.jsxs)(`div`,{className:`oauth-row`,children:[(0,S.jsxs)(`span`,{className:`oauth-name`,title:et(e),children:[(0,S.jsx)(`span`,{className:`provider-icon provider-icon-sm`,children:i&&(0,S.jsx)(`img`,{src:i,alt:``,"aria-hidden":`true`})}),(0,S.jsx)(`span`,{className:`oauth-name-text`,children:e})]}),(0,S.jsxs)(`span`,{className:`oauth-status`,children:[(0,S.jsx)(`span`,{className:`dot ${n.loggedIn?`dot-green`:`dot-muted`}`}),n.loggedIn?(0,S.jsx)(`span`,{className:`oauth-email`,style:{color:`var(--green)`},children:n.email??t(`prov.loggedIn`)}):(0,S.jsx)(`span`,{className:`oauth-email muted`,children:t(`prov.notLoggedIn`)})]}),(0,S.jsx)(`span`,{className:`oauth-actions`,children:n.loggedIn?(0,S.jsx)(`button`,{className:`btn btn-ghost btn-sm`,onClick:()=>De(e),children:t(`prov.logout`)}):(0,S.jsx)(`button`,{className:`btn btn-primary btn-sm`,onClick:()=>Te(e),disabled:r,children:r?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`span`,{className:`spin`}),t(`prov.waitingBrowser`)]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(ue,{}),t(`prov.login`)]})})}),w?.provider===e&&(w.url||w.instructions||r)&&(0,S.jsxs)(`span`,{className:`oauth-login-hint muted`,children:[(0,S.jsxs)(`span`,{className:`oauth-login-hint-links`,children:[w.url&&(0,S.jsxs)(`a`,{href:w.url,target:`_blank`,rel:`noreferrer`,className:`link-btn`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,S.jsx)(le,{}),t(`prov.didntOpen`)]}),w.instructions&&(0,S.jsx)(`span`,{children:w.instructions})]}),(0,S.jsxs)(`span`,{className:`oauth-login-paste`,children:[(0,S.jsx)(`input`,{className:`input`,type:`text`,autoComplete:`off`,spellCheck:!1,value:ee,onChange:e=>te(e.target.value),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),Ee(e))},placeholder:t(`prov.pasteRedirect`),"aria-label":t(`prov.pasteRedirect`),disabled:E}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-sm`,type:`button`,disabled:E||!ee.trim(),onClick:()=>void Ee(e),children:t(E?`prov.pasteSubmitting`:`prov.pasteSubmit`)})]}),(0,S.jsx)(`span`,{className:`text-caption`,children:re||t(`prov.pasteRedirectHint`)})]})]},e)}),Ae.map(e=>{let r=n?.providers[e],i=Qe(e),a=r?.keyOptional===!0&&!r?.hasApiKey;return(0,S.jsxs)(`div`,{className:`oauth-row`,children:[(0,S.jsxs)(`span`,{className:`oauth-name`,title:e,children:[(0,S.jsx)(`span`,{className:`provider-icon provider-icon-sm`,children:i&&(0,S.jsx)(`img`,{src:i,alt:``,"aria-hidden":`true`})}),(0,S.jsx)(`span`,{className:`oauth-name-text`,children:e})]}),(0,S.jsxs)(`span`,{className:`oauth-status`,children:[(0,S.jsx)(`span`,{className:`dot dot-green`}),(0,S.jsx)(`span`,{className:`oauth-email muted`,children:a?`free tier`:t(`prov.hasApiKey`)})]}),(0,S.jsx)(`span`,{className:`oauth-actions`,"aria-hidden":`true`})]},e)})]})]}),i?(0,S.jsx)(`textarea`,{className:`input`,value:c,onChange:e=>l(e.target.value),style:{height:400}}):(0,S.jsxs)(`div`,{className:`stack`,style:{gap:8},children:[(0,S.jsxs)(`div`,{className:`muted text-control`,style:{marginBottom:4},children:[t(`prov.port`),`: `,(0,S.jsx)(`code`,{className:`chip`,children:n.port}),` · `,t(`prov.default`),`: `,(0,S.jsx)(`code`,{className:`chip`,children:n.defaultProvider})]}),Object.entries(n.providers).map(([e,r])=>{let i=e===n.defaultProvider,a=r.disabled===!0,o=y[e]?.quota??null,s=Qe(e),c=r.authMode===`oauth`?O[e]:void 0,l=r.authMode!==`oauth`&&r.authMode!==`forward`&&r.hasApiKey?oe[e]??[]:[],u=!!c&&c.accounts.length>0||l.length>0,d=k[e]===!0,f=c?.accounts.length??l.length;return(0,S.jsxs)(`div`,{className:`card prov-card${a?` prov-card-disabled`:``}`,children:[(0,S.jsxs)(`div`,{className:`prov-card-main`,children:[(0,S.jsxs)(`div`,{className:`prov-card-info`,children:[s&&(0,S.jsx)(`span`,{className:`provider-icon`,children:(0,S.jsx)(`img`,{src:s,alt:``,"aria-hidden":`true`})}),(0,S.jsxs)(`div`,{className:`prov-card-copy`,children:[(0,S.jsxs)(`div`,{className:`prov-title`,children:[(0,S.jsx)(`span`,{className:`font-semibold`,children:e}),i&&(0,S.jsx)(`span`,{className:`badge badge-primary`,children:t(`prov.defaultBadge`)}),a?(0,S.jsx)(`span`,{className:`badge badge-muted`,children:t(`prov.disabledBadge`)}):(0,S.jsx)(`span`,{className:`badge badge-green`,children:t(`prov.activeBadge`)}),r.authMode===`oauth`&&(0,S.jsx)(`span`,{className:`badge badge-accent`,children:`oauth`}),r.authMode===`forward`&&(0,S.jsx)(`span`,{className:`badge badge-amber`,children:`passthrough`}),r.keyOptional&&(0,S.jsx)(`span`,{className:`badge badge-green`,children:`Free`})]}),(0,S.jsxs)(`div`,{className:`muted prov-meta text-control`,children:[(0,S.jsx)(`code`,{className:`chip`,children:r.adapter}),(0,S.jsx)(`span`,{children:r.baseUrl}),r.defaultModel&&(0,S.jsx)(`span`,{children:r.defaultModel}),r.hasApiKey&&(0,S.jsx)(`span`,{children:t(`prov.hasApiKey`)}),r.hasHeaders&&(0,S.jsx)(`span`,{children:t(`prov.hasHeaders`)})]}),r.note&&(0,S.jsx)(`div`,{className:`muted text-label leading-body`,style:{marginTop:4},children:r.note})]})]}),(0,S.jsxs)(`div`,{className:`provider-actions`,children:[(0,S.jsxs)(`button`,{className:`btn ${a?`btn-primary`:`btn-ghost`} btn-sm`,onClick:()=>ke(e,!a),disabled:i,title:i?t(`prov.defaultCannotDisable`):void 0,"aria-label":t(a?`prov.enableAria`:`prov.disableAria`,{name:e}),children:[i?(0,S.jsx)(ue,{}):(0,S.jsx)(ce,{}),t(a?`prov.enable`:`prov.disable`)]}),(0,S.jsxs)(`button`,{className:`btn btn-danger btn-sm`,onClick:()=>Oe(e),"aria-label":t(`sub.removeAria`,{m:e}),children:[(0,S.jsx)(A,{}),t(`common.remove`)]})]})]}),o&&(0,S.jsx)(Ke,{quota:o,threshold:80,t,className:`provider-quota`}),u&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`button`,{className:`prov-accounts-toggle${d?` open`:``}`,onClick:()=>j(t=>({...t,[e]:!d})),"aria-expanded":d,"aria-label":t(`prov.accountsAria`,{name:e}),children:[t(`prov.accounts`,{n:String(f)}),(0,S.jsx)(`span`,{className:`chev`,children:(0,S.jsx)(P,{})})]}),d&&(0,S.jsxs)(`div`,{className:`prov-accounts-list`,children:[(c?.accounts??[]).map(n=>(0,S.jsxs)(`button`,{className:`prov-account-row${n.active?` active`:``}`,onClick:()=>he(e,n),title:n.active?void 0:t(`prov.accountSwitchTitle`),children:[(0,S.jsx)(`span`,{className:`dot ${n.needsReauth?`dot-amber`:n.active?`dot-green`:`dot-muted`}`}),(0,S.jsx)(`span`,{className:`prov-account-email`,children:n.email??t(`prov.accountNoLabel`,{id:n.id})}),n.needsReauth&&(0,S.jsx)(`span`,{className:`badge badge-amber`,children:t(`prov.accountReauth`)}),n.active&&(0,S.jsx)(`span`,{className:`badge badge-primary`,children:t(`prov.accountActive`)}),(0,S.jsx)(`span`,{className:`prov-account-remove`,role:`button`,"aria-label":t(`prov.accountRemoveAria`,{email:n.email??n.id}),onClick:t=>{t.stopPropagation(),be(e,n)},children:(0,S.jsx)(A,{style:{width:13,height:13}})})]},n.id)),l.map(n=>(0,S.jsxs)(`button`,{className:`prov-account-row${n.active?` active`:``}`,onClick:()=>_e(e,n),title:n.active?void 0:t(`prov.keySwitchTitle`),children:[(0,S.jsx)(`span`,{className:`dot ${n.active?`dot-green`:`dot-muted`}`}),(0,S.jsx)(`span`,{className:`prov-account-email mono`,children:n.label?`${n.label} · ${n.masked}`:n.masked}),n.active&&(0,S.jsx)(`span`,{className:`badge badge-primary`,children:t(`prov.accountActive`)}),(0,S.jsx)(`span`,{className:`prov-account-remove`,role:`button`,"aria-label":t(`prov.keyRemoveAria`,{key:n.label??n.masked}),onClick:t=>{t.stopPropagation(),ve(e,n)},children:(0,S.jsx)(A,{style:{width:13,height:13}})})]},n.id)),c?(0,S.jsx)(`button`,{className:`prov-account-row prov-account-add`,onClick:()=>Te(e,!0),disabled:x===e,children:x===e?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`span`,{className:`spin`}),t(`prov.waitingBrowser`)]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(ae,{style:{width:13,height:13}}),t(`prov.accountAdd`)]})}):se===e?(0,S.jsxs)(`div`,{className:`prov-account-row prov-account-keyform`,children:[(0,S.jsx)(`input`,{className:`input input-sm mono`,type:`password`,autoFocus:!0,placeholder:t(`prov.keyPlaceholder`),value:F,onChange:e=>I(e.target.value),onKeyDown:t=>{t.key===`Enter`&&ye(e),t.key===`Escape`&&(N(null),I(``))}}),(0,S.jsx)(`button`,{className:`btn btn-primary btn-sm`,onClick:()=>ye(e),disabled:!F.trim(),children:t(`common.save`)}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-sm`,onClick:()=>{N(null),I(``)},children:t(`common.cancel`)})]}):(0,S.jsxs)(`button`,{className:`prov-account-row prov-account-add`,onClick:()=>{N(e),I(``)},children:[(0,S.jsx)(ae,{style:{width:13,height:13}}),t(`prov.keyAdd`)]})]})]})]},e)})]}),o&&(0,S.jsx)(He,{apiBase:e,existingNames:Object.keys(n.providers),onClose:()=>s(!1),onAdded:e=>{s(!1),L(t(`prov.added`,{name:e,cmd:`ocx sync`}),!0),fe(),pe(),R(!0)}})]})}var nt={"gpt-5.6-sol":fe,"gpt-5.6-terra":me,"gpt-5.6-luna":pe},rt={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`,marginRight:4};function it(e){return e.slice(e.lastIndexOf(`/`)+1)}function at(e){return nt[e]??nt[it(e)]??null}function z(e){let t=at(e);return t?(0,_.createElement)(`span`,{style:{display:`inline-flex`,alignItems:`center`,gap:4}},(0,_.createElement)(t,{style:rt}),e):e}var ot=Array.from({length:18},(e,t)=>1e5+t*5e4),st=`custom`,ct=[4,8,16,32,64,128,256,500,1e3],lt=60;function ut(e){return!Number.isFinite(e)||e<=0?String(e):e%1e3==0?`${e/1e3}k`:e.toLocaleString()}function dt({apiBase:e}){let t=we(),[n,r]=(0,_.useState)([]),[i,a]=(0,_.useState)(new Set),[o,s]=(0,_.useState)({}),[c,l]=(0,_.useState)({}),[u,d]=(0,_.useState)({}),[f,p]=(0,_.useState)(35e4),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(()=>{try{let e=localStorage.getItem(`ocx-models-collapsed`);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}}),[x,C]=(0,_.useState)(``),[w,T]=(0,_.useState)(!1),[te,E]=(0,_.useState)(!0),[ne,re]=(0,_.useState)(!1),D=(0,_.useRef)(!1),[O,ie]=(0,_.useState)(null),[ae,k]=(0,_.useState)(!1),[A,j]=(0,_.useState)(``),M=(0,_.useRef)(!1),[se,N]=(0,_.useState)(``),[F,ce]=(0,_.useState)(!1),[le,I]=(0,_.useState)(!1),[ue,de]=(0,_.useState)(null),[L,fe]=(0,_.useState)(!1),pe=(0,_.useCallback)(async()=>{try{let t=await fetch(`${e}/api/shadow-call-settings`);t.ok&&de(await t.json())}catch{}},[e]),R=(0,_.useCallback)(async()=>{if(!M.current)try{let t=await fetch(`${e}/api/v2`);if(!t.ok||!(t.headers.get(`content-type`)??``).includes(`application/json`)){ie(null);return}let n=await t.json();typeof n.enabled==`boolean`&&ie({enabled:n.enabled,agentsMaxThreadsConflict:n.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof n.maxConcurrentThreadsPerSession==`number`?n.maxConcurrentThreadsPerSession:null,multiAgentMode:n.multiAgentMode===`v1`||n.multiAgentMode===`v2`?n.multiAgentMode:`default`})}catch{ie(null)}},[e]),me=(0,_.useCallback)(async()=>{try{let[t,n]=await Promise.all([fetch(`${e}/api/models`).then(e=>e.json()),fetch(`${e}/api/provider-context-caps`).then(e=>e.json())]);R(),pe(),r(t),a(new Set(t.filter(e=>e.disabled).map(e=>e.namespaced)));let i=typeof n.value==`number`&&Number.isFinite(n.value)&&n.value>0?n.value:typeof n.cap==`number`&&Number.isFinite(n.cap)&&n.cap>0?n.cap:void 0;i!==void 0&&p(i),d(n.caps??{})}catch{T(!1),C(t(`models.loadFail`))}finally{E(!1)}},[e,pe,R,t]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{me()},0),t=window.setInterval(()=>{D.current||me()},1e4);return()=>{window.clearTimeout(e),window.clearInterval(t)}},[me]);let he=(0,_.useMemo)(()=>{let e={};for(let t of n)(e[t.provider]??=[]).push(t);return Object.entries(e).sort(([e,t],[n,r])=>{let i=t.every(e=>e.native);return i===r.every(e=>e.native)?e.localeCompare(n):i?-1:1})},[n]),ge=async n=>{re(!0),D.current=!0,C(``);try{(await fetch(`${e}/api/disabled-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:[...n]})})).ok?(a(n),T(!0),C(t(`models.applied`))):(T(!1),C(t(`models.saveFailed`)))}catch{T(!1),C(t(`models.networkError`))}finally{re(!1),D.current=!1}},_e=e=>{let t=new Set(i);t.has(e)?t.delete(e):t.add(e),ge(t)},ve=async n=>{re(!0),D.current=!0,C(``);let r=u[n]!==f;try{let i=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:n,enabled:r})});i.ok?(d((await i.json()).caps??{}),T(!0),C(t(`models.capApplied`)),await me()):(T(!1),C(t(`models.capSaveFailed`)))}catch{T(!1),C(t(`models.networkError`))}finally{re(!1),D.current=!1}},ye=e=>{b(t=>{let n=new Set(t);n.has(e)?n.delete(e):n.add(e);try{localStorage.setItem(`ocx-models-collapsed`,JSON.stringify([...n]))}catch{}return n})},be=async n=>{re(!0),D.current=!0,C(``);try{let r=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(r.ok){let e=await r.json();typeof e.value==`number`&&Number.isFinite(e.value)&&e.value>0&&p(e.value),d(e.caps??{}),T(!0),C(t(`models.capApplied`)),await me()}else T(!1),C(t(`models.capSaveFailed`))}catch{T(!1),C(t(`models.networkError`))}finally{re(!1),D.current=!1}},xe=e=>{!Number.isFinite(e)||e<=0||be({value:Math.floor(e)})},Se=e=>{if(e===st){v(!0),h(String(f));return}v(!1);let t=Number(e);Number.isFinite(t)&&t>0&&t!==f&&xe(t)},Ce=()=>{let e=Number(m.replace(/[_,\s]/g,``));if(!Number.isFinite(e)||e<=0){T(!1),C(t(`models.capSaveFailed`));return}v(!1),xe(e)},Te=(0,_.useMemo)(()=>{let e=he.filter(([,e])=>!e.every(e=>e.native));return e.length>0&&e.every(([e])=>u[e]===f)},[he,u,f]),Ee=()=>{be({setAll:!Te})},De=async t=>{if(!(!ue||L)){fe(!0),de({...ue,...t});try{await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}finally{fe(!1)}}},Oe=async n=>{if(!(!O||M.current)&&O.multiAgentMode!==n){k(!0),M.current=!0,j(``),C(``);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:n})}),i=await r.json().catch(()=>null);r.ok&&i?(R(),T(!0),C(t(`models.v2Applied`)),j((i.warnings??[]).join(` `))):(T(!1),C(i?.error??t(`models.saveFailed`)))}catch{T(!1),C(t(`models.networkError`))}finally{k(!1),M.current=!1}}},ke=async n=>{if(!(!O||M.current)){if(!Number.isInteger(n)||n<1){T(!1),C(t(`models.v2ThreadsInvalid`));return}if(O.maxConcurrentThreadsPerSession!==n){k(!0),M.current=!0,j(``),C(``);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({maxConcurrentThreadsPerSession:n})}),i=await r.json().catch(()=>null);r.ok&&i&&typeof i.enabled==`boolean`?(ie({enabled:i.enabled,agentsMaxThreadsConflict:i.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof i.maxConcurrentThreadsPerSession==`number`?i.maxConcurrentThreadsPerSession:null,multiAgentMode:i.multiAgentMode===`v1`||i.multiAgentMode===`v2`?i.multiAgentMode:`default`}),T(!0),C(t(`models.v2ThreadsApplied`)),ce(!1)):(T(!1),C(i?.error??t(`models.saveFailed`)))}catch{T(!1),C(t(`models.networkError`))}finally{k(!1),M.current=!1}}}},Pe=e=>{if(e===st){ce(!0),N(String(O?.maxConcurrentThreadsPerSession??``));return}ce(!1),ke(Number(e))};return te?(0,S.jsxs)(`div`,{className:`row muted`,children:[(0,S.jsx)(`span`,{className:`spin`}),` `,t(`models.loading`)]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{className:`page-head`,children:[(0,S.jsx)(`h2`,{children:t(`nav.models`)}),(0,S.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.active`,{active:n.length-i.size,total:n.length})})]}),(0,S.jsx)(`p`,{className:`page-sub`,children:t(`models.subtitle`)}),x&&(0,S.jsx)(je,{tone:w?`ok`:`err`,children:x}),(0,S.jsxs)(`div`,{className:`row muted text-control`,style:{gap:6,marginBottom:8,alignItems:`center`},children:[(0,S.jsxs)(`span`,{title:t(`models.shadowCallInterceptHint`),style:{cursor:`help`},children:[t(`models.shadowCallIntercept`),` ⓘ`]}),(0,S.jsx)(`code`,{className:`text-caption`,style:{opacity:.6},children:`⚠ 5.4-mini →`}),(0,S.jsx)(Ae,{on:ue?.enabled??!1,onClick:()=>void De({enabled:!ue?.enabled}),disabled:!ue||L,label:t(`models.shadowCallIntercept`)}),(0,S.jsx)(Me,{value:ue?.model??``,options:[{value:``,label:`—`},...n.filter(e=>!i.has(e.id)&&!i.has(e.namespaced)).map(e=>({value:e.namespaced,label:e.namespaced}))],onChange:e=>{de(t=>t&&{...t,model:e}),De({model:e})},disabled:!ue||L||!ue.enabled,label:t(`models.shadowCallIntercept`)})]}),O&&(0,S.jsxs)(`div`,{className:`row`,style:{gap:8,marginBottom:8,flexWrap:`wrap`,alignItems:`center`},children:[(0,S.jsx)(`span`,{className:`muted text-control`,children:t(`models.v2Label`)}),(0,S.jsx)(`div`,{className:`segmented`,role:`radiogroup`,"aria-label":t(`models.v2Label`),style:{display:`inline-flex`,borderRadius:`var(--radius-pill)`,background:`var(--surface-soft, var(--raised))`,padding:3,gap:2},children:[`v1`,`default`,`v2`].map(e=>(0,S.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(O.multiAgentMode??`default`)===e,className:`btn btn-sm${(O.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{borderRadius:`var(--radius-pill)`,minWidth:64,padding:`5px 12px`,border:`none`,background:(O.multiAgentMode??`default`)===e?void 0:`transparent`,color:(O.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:ae,onClick:()=>void Oe(e),children:t(`models.v2Mode_${e}`)},e))}),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{width:24,height:24,minWidth:24,flex:`0 0 24px`,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},onClick:()=>I(!0),"aria-label":t(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,S.jsx)(oe,{width:14,height:14,"aria-hidden":`true`})}),O.enabled&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`span`,{className:`muted text-control`,style:{marginLeft:8},children:t(`models.v2ThreadsLabel`)}),(0,S.jsx)(Me,{value:F?st:O.maxConcurrentThreadsPerSession!==null&&O.maxConcurrentThreadsPerSession!==void 0?ct.includes(O.maxConcurrentThreadsPerSession)?String(O.maxConcurrentThreadsPerSession):st:``,options:[...O.maxConcurrentThreadsPerSession===null||O.maxConcurrentThreadsPerSession===void 0?[{value:``,label:t(`models.v2ThreadsDefault`)}]:[],...O.maxConcurrentThreadsPerSession!==null&&O.maxConcurrentThreadsPerSession!==void 0&&!ct.includes(O.maxConcurrentThreadsPerSession)&&!F?[{value:st,label:String(O.maxConcurrentThreadsPerSession)}]:[],...ct.map(e=>({value:String(e),label:String(e)})),{value:st,label:t(`models.custom`)}],onChange:e=>Pe(e),disabled:ae,label:t(`models.v2ThreadsLabel`)}),F&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:se,onChange:e=>N(e.target.value),onKeyDown:e=>{e.key===`Enter`&&ke(Number(se.replace(/[_,\s]/g,``)))},disabled:ae}),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:ae,onClick:()=>{ke(Number(se.replace(/[_,\s]/g,``)))},children:t(`models.v2ThreadsApply`)})]})]}),O.enabled&&O.agentsMaxThreadsConflict&&(0,S.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:t(`models.v2Conflict`)}),A&&(0,S.jsx)(`span`,{className:`muted text-label`,children:A})]}),(0,S.jsxs)(`div`,{className:`row`,style:{gap:8,marginBottom:8,flexWrap:`wrap`},children:[(0,S.jsx)(`span`,{className:`muted text-control`,children:t(`models.contextCapLabel`)}),(0,S.jsx)(Me,{value:g?st:ot.includes(f)?String(f):st,options:[...!ot.includes(f)&&!g?[{value:String(f),label:ut(f)}]:[],...ot.map(e=>({value:String(e),label:ut(e)})),{value:st,label:t(`models.custom`)}],onChange:e=>Se(e),disabled:ne,label:t(`models.contextCapLabel`)}),g&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:t(`models.customPlaceholder`),value:m,onChange:e=>h(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Ce()},disabled:ne}),(0,S.jsx)(`button`,{onClick:Ce,disabled:ne,className:`btn btn-ghost btn-sm`,children:t(`models.customApply`)})]}),(0,S.jsx)(`div`,{style:{flex:1}}),(0,S.jsx)(Ae,{on:Te,onClick:Ee,disabled:ne,label:t(`models.setAll`)}),(0,S.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.setAll`)})]}),(0,S.jsxs)(`div`,{className:`row muted text-label leading-body`,style:{alignItems:`flex-start`,gap:8,marginBottom:12,maxWidth:`80ch`},children:[(0,S.jsx)(oe,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,S.jsx)(`span`,{children:t(`models.orderHint`)})]}),he.map(([e,n])=>{let r=y.has(e),a=n.filter(e=>!i.has(e.namespaced)).length,d=u[e]===f,p=n.every(e=>e.native),m=(o[e]??``).trim().toLowerCase(),h=m?n.filter(e=>e.id.toLowerCase().includes(m)):n,g=c[e]??lt,_=h.slice(0,g),v=h.length-_.length,b=n.every(e=>!i.has(e.namespaced)),x=n.every(e=>i.has(e.namespaced)),C=e=>{let t=new Set(i);for(let r of n)e?t.delete(r.namespaced):t.add(r.namespaced);ge(t)};return(0,S.jsxs)(`div`,{className:`card`,style:{marginBottom:8,overflow:`hidden`},children:[(0,S.jsxs)(`div`,{onClick:()=>ye(e),className:`row group-head${r?``:` open`}`,children:[(0,S.jsx)(P,{style:{width:14,height:14,color:`var(--muted)`,transform:r?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,S.jsx)(`span`,{className:`text-body font-semibold`,children:e}),p&&(0,S.jsx)(`span`,{className:`muted mono text-caption`,style:{padding:`1px 6px`,border:`1px solid var(--border)`,borderRadius:`var(--radius-pill)`},children:t(`models.nativeGroupLabel`)}),(0,S.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.active`,{active:a,total:n.length})}),(0,S.jsx)(`div`,{style:{flex:1}}),(0,S.jsxs)(`div`,{className:`row`,onClick:e=>e.stopPropagation(),style:{gap:6},children:[(0,S.jsx)(`button`,{className:`btn btn-ghost btn-sm text-caption`,disabled:ne||b,onClick:()=>C(!0),style:{padding:`2px 8px`},children:t(`models.allOn`)}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-sm text-caption`,disabled:ne||x,onClick:()=>C(!1),style:{padding:`2px 8px`},children:t(`models.allOff`)}),!p&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(Ae,{on:d,onClick:()=>ve(e),disabled:ne,label:t(`models.capValue`,{value:ut(f)})}),(0,S.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.capValue`,{value:ut(f)})})]})]})]}),!r&&(0,S.jsxs)(`div`,{style:{padding:`6px 12px`},children:[p&&(0,S.jsx)(`p`,{className:`muted text-label`,style:{margin:`2px 0 6px`},children:t(`models.nativeHint`)}),n.length>lt/2&&(0,S.jsx)(`input`,{className:`input`,style:{width:`100%`,marginBottom:6},placeholder:t(`models.search`),value:o[e]??``,onChange:t=>s(n=>({...n,[e]:t.target.value}))}),_.map(e=>{let n=i.has(e.namespaced);return(0,S.jsxs)(`div`,{className:`row`,style:{padding:`5px 0`},children:[(0,S.jsx)(Ae,{on:!n,onClick:()=>_e(e.namespaced),disabled:ne,label:e.id}),(0,S.jsx)(`code`,{className:`mono text-control`,style:{color:n?`var(--faint)`:`var(--text)`,textDecoration:n?`line-through`:`none`},children:z(e.id)}),e.contextCapped&&(0,S.jsx)(`span`,{className:`muted mono text-caption`,style:{padding:`1px 6px`,border:`1px solid var(--border)`,borderRadius:`var(--radius-pill)`},children:t(`models.contextCappedValue`,{value:ut(e.contextCap??f)})})]},e.namespaced)}),v>0&&(0,S.jsx)(`button`,{onClick:()=>l(t=>({...t,[e]:g+lt})),className:`btn btn-ghost btn-sm`,style:{marginTop:4},children:t(`models.showMore`,{n:v})})]})]},e)}),he.length===0&&(0,S.jsx)(Ne,{icon:(0,S.jsx)(ee,{}),title:t(`models.noRouted`),children:t(`models.noRoutedHint`)}),le&&(0,S.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":t(`models.v2Label`),onClick:()=>I(!1),onKeyDown:e=>{e.key===`Escape`&&I(!1)},children:(0,S.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,S.jsxs)(`div`,{className:`modal-head`,children:[(0,S.jsx)(`h3`,{children:t(`models.v2Label`)}),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>I(!1),"aria-label":`Close`,children:`×`})]}),(0,S.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`models.v2Help`)}),(0,S.jsx)(`div`,{style:{marginTop:12},children:(0,S.jsx)(`a`,{className:`text-control`,href:`https://lidge-jun.github.io/opencodex/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:t(`models.v2DocsLink`)})}),(0,S.jsx)(`div`,{className:`modal-actions`,children:(0,S.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>I(!1),children:`OK`})})]})})]})}function ft({apiBase:e}){let t=we(),[n,r]=(0,_.useState)([]),[i,a]=(0,_.useState)([]),[o,s]=(0,_.useState)(``),[c,l]=(0,_.useState)(``),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!0),m=(0,_.useCallback)(async()=>{try{let t=await fetch(`${e}/api/subagent-models`).then(e=>e.json()),n=t.available??[];r(n),a((t.chosen??[]).filter(e=>n.includes(e)))}catch{d(!1),l(t(`sub.loadFail`))}finally{p(!1)}},[e,t]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{m()},0);return()=>window.clearTimeout(e)},[m]);let h=e=>{l(``),a(t=>t.includes(e)?t.filter(t=>t!==e):t.length>=5?t:[...t,e])},g=(e,t)=>{a(n=>{let r=[...n],i=e+t;return i<0||i>=r.length?n:([r[e],r[i]]=[r[i],r[e]],r)})},v=async()=>{l(``);try{let n=await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:i})}),r=await n.json();d(n.ok),l(n.ok?t(`sub.saved`,{n:r.applied?.length??0,cmd:`ocx sync`}):r.error||t(`sub.saveFailed`))}catch{d(!1),l(t(`sub.networkError`))}},y=(0,_.useMemo)(()=>{let e=o.trim().toLowerCase();return n.filter(t=>!e||t.toLowerCase().includes(e))},[n,o]);return f?(0,S.jsx)(`div`,{className:`muted`,style:{padding:8},children:t(`sub.loading`)}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`page-head`,children:(0,S.jsx)(`h2`,{children:t(`nav.subagents`)})}),(0,S.jsx)(`p`,{className:`page-sub`,children:(0,S.jsx)(Ee,{k:`sub.subtitle`,cmd:`spawn_agent`})}),c&&(0,S.jsx)(je,{tone:u?`ok`:`err`,children:c}),(0,S.jsxs)(`div`,{className:`h-section`,children:[t(`sub.featured`),` `,(0,S.jsxs)(`span`,{className:`count`,children:[i.length,`/5`]})]}),(0,S.jsxs)(`div`,{className:`row muted text-label leading-body`,style:{alignItems:`flex-start`,gap:8,margin:`-2px 0 10px`,maxWidth:`80ch`},children:[(0,S.jsx)(oe,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,S.jsx)(`span`,{children:(0,S.jsx)(Ee,{k:`sub.orderHint`,cmd:`spawn_agent`})})]}),i.length===0?(0,S.jsx)(Ne,{title:t(`sub.noneSelected`)}):(0,S.jsx)(`div`,{className:`stack`,style:{gap:8},children:i.map((e,n)=>(0,S.jsxs)(`div`,{className:`card panel-accent row`,style:{padding:`8px 12px`,gap:10},children:[(0,S.jsx)(`span`,{className:`mono font-bold`,style:{width:18,color:`var(--accent)`},children:n+1}),(0,S.jsx)(`code`,{className:`mono`,style:{flex:1,color:`var(--text)`},children:z(e)}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>g(n,-1),disabled:n===0,"aria-label":t(`sub.moveUp`,{m:e}),children:(0,S.jsx)(se,{})}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>g(n,1),disabled:n===i.length-1,"aria-label":t(`sub.moveDown`,{m:e}),children:(0,S.jsx)(N,{})}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>h(e),"aria-label":t(`sub.removeAria`,{m:e}),style:{color:`var(--red)`},children:(0,S.jsx)(ie,{})})]},e))}),(0,S.jsx)(`div`,{style:{marginTop:14},children:(0,S.jsx)(`button`,{className:`btn btn-primary`,onClick:v,children:t(`common.save`)})}),(0,S.jsxs)(`div`,{className:`h-section`,children:[t(`sub.models`),` `,(0,S.jsx)(`span`,{className:`count`,children:y.length})]}),(0,S.jsxs)(`div`,{style:{position:`relative`,marginBottom:10},children:[(0,S.jsx)(M,{style:{position:`absolute`,left:11,top:`50%`,transform:`translateY(-50%)`,width:15,height:15,color:`var(--faint)`,pointerEvents:`none`}}),(0,S.jsx)(`input`,{className:`input`,value:o,onChange:e=>s(e.target.value),placeholder:t(`sub.search`),style:{paddingLeft:34}})]}),(0,S.jsxs)(`div`,{className:`stack`,style:{gap:6,maxHeight:360,overflowY:`auto`},children:[y.map(e=>{let t=i.includes(e),n=!t&&i.length>=5;return(0,S.jsxs)(`button`,{className:`card row`,onClick:()=>h(e),disabled:n,"aria-pressed":t,style:{padding:`9px 12px`,gap:10,width:`100%`,textAlign:`left`,cursor:n?`not-allowed`:`pointer`,opacity:n?.45:1,background:t?`var(--accent-soft)`:void 0,borderColor:t?`var(--accent-ring)`:void 0},children:[(0,S.jsx)(`span`,{style:{width:16,height:16,flexShrink:0,color:`var(--accent)`,display:`inline-flex`},children:t&&(0,S.jsx)(O,{style:{width:16,height:16}})}),(0,S.jsx)(te,{style:{width:15,height:15,color:`var(--faint)`,flexShrink:0}}),(0,S.jsx)(`code`,{className:`mono`,style:{color:`var(--text)`},children:z(e)})]},e)}),y.length===0&&(0,S.jsx)(Ne,{title:t(`sub.noModels`)})]})]})}var pt=m();function mt(e,t,n){let r=Array(e);return new Proxy(r,{get(r,i,a){if(typeof i==`string`){let a=i.charCodeAt(0);if(a>=48&&a<=57){let a=+i;if(Number.isInteger(a)&&a>=0&&a<e){let e=r[a];if(!e){let i=t[a*2];e=r[a]={index:a,key:n(a),start:i,size:t[a*2+1],end:i+t[a*2+1],lane:0}}return e}}if(i===`length`)return e}return Reflect.get(r,i,a)}})}function ht(e,t,n){let r=n.initialDeps??[],i,a=!0;function o(){let o=e();return o.length!==r.length||o.some((e,t)=>r[t]!==e)?(r=o,i=t(...o),n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(i),a=!1,i):i}return o.updateDeps=e=>{r=e},o}function gt(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var _t=(e,t)=>Math.abs(e-t)<1.01,vt=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},yt,bt=()=>{if(yt!==void 0)return yt;if(typeof navigator>`u`)return yt=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return yt=!0;let e=navigator.maxTouchPoints;return yt=navigator.platform===`MacIntel`&&e!==void 0&&e>0},xt=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},St=e=>e,Ct=e=>{let t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,r=Array(n);for(let e=0;e<n;e++)r[e]=t+e;return r},wt=(e,t)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let i=e=>{let{width:n,height:r}=e;t({width:Math.round(n),height:Math.round(r)})};if(i(xt(n)),!r.ResizeObserver)return()=>{};let a=new r.ResizeObserver(t=>{let r=()=>{let e=t[0];if(e?.borderBoxSize){let t=e.borderBoxSize[0];if(t){i({width:t.inlineSize,height:t.blockSize});return}}i(xt(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},Tt={passive:!0},Et=typeof window>`u`?!0:`onscrollend`in window,Dt=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&Et,o=0,s=a?null:vt(i,()=>t(o,!1),e.options.isScrollingResetDelay),c=e=>()=>{o=n(r),s?.(),t(o,e)},l=c(!0),u=c(!1);return r.addEventListener(`scroll`,l,Tt),a&&r.addEventListener(`scrollend`,u,Tt),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},Ot=(e,t)=>Dt(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),kt=(e,t,n)=>{if(n.options.useCachedMeasurements){let t=n.indexFromElement(e),r=n.options.getItemKey(t);return n.itemSizeCache.get(r)??n.options.estimateSize(t)}if(t?.borderBoxSize){let e=t.borderBoxSize[0];if(e)return Math.round(e[n.options.horizontal?`inlineSize`:`blockSize`])}if(!t){let t=n.indexFromElement(e),r=n.options.getItemKey(t),i=n.itemSizeCache.get(r);if(i!==void 0)return i}return e[n.options.horizontal?`offsetWidth`:`offsetHeight`]},At=(e,{adjustments:t=0,behavior:n},r)=>{var i,a;(a=(i=r.scrollElement)?.scrollTo)==null||a.call(i,{[r.options.horizontal?`left`:`top`]:e+t,behavior:n})},jt=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var e;return((e=this.targetWindow?.performance)?.now)?.call(e)??Date.now()},this.observer=(()=>{let e=null,t=()=>e||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:e=new this.targetWindow.ResizeObserver(e=>{e.forEach(e=>{let t=()=>{let t=e.target,n=this.indexFromElement(t);if(!t.isConnected){this.observer.unobserve(t);for(let[e,n]of this.elementsCache)if(n===t){this.elementsCache.delete(e);break}return}this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,e,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(t):t()})}));return{disconnect:()=>{var n;(n=t())==null||n.disconnect(),e=null},observe:e=>t()?.observe(e,{box:`border-box`}),unobserve:e=>t()?.unobserve(e)}})(),this.range=null,this.setOptions=e=>{let t={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:St,rangeExtractor:Ct,onChange:()=>{},measureElement:kt,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:`data-index`,initialMeasurementsCache:[],lanes:1,anchorTo:`start`,followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:`estimate`,useCachedMeasurements:!1};for(let n in e){let r=e[n];r!==void 0&&(t[n]=r)}let n=this.options,r=null,i=null,a=!1;if(n!==void 0&&n.enabled&&t.enabled&&t.anchorTo===`end`&&this.scrollElement!==null){let e=n.count,o=t.count,s=this.getMeasurements(),c=e>0?s[0]?.key??n.getItemKey(0):null,l=e>0?s[e-1]?.key??n.getItemKey(e-1):null;if(o!==e||e>0&&o>0&&(t.getItemKey(0)!==c||t.getItemKey(o-1)!==l)){a=!0;let c=e>0?this.getVirtualItemForOffset(this.getScrollOffset())??s[0]:null;c&&(r=[c.key,this.getScrollOffset()-c.start]);let u=t.followOnAppend===!0?`auto`:t.followOnAppend||null;u&&o>e&&this.isAtEnd(n.scrollEndThreshold)&&(e===0||t.getItemKey(o-1)!==l)&&(i=u)}}this.options=t,a&&(this.pendingMin=0,this.itemSizeCacheVersion++);let o=!1,s=0;if(r&&this.scrollOffset!==null){let[e,t]=r,n=this.getMeasurements(),{count:i,getItemKey:a}=this.options,c=0;for(;c<i&&a(c)!==e;)c++;if(c<i){let e=n[c];if(e){let n=e.start+t;n!==this.scrollOffset&&(s=n-this.scrollOffset,this.scrollOffset=n,o=!0)}}}(o||i)&&(this.pendingScrollAnchor=[o?r[0]:null,o?r[1]:0,i,s])},this.notify=e=>{var t,n;(n=(t=this.options).onChange)==null||n.call(t,this,e)},this.maybeNotify=ht(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),e=>{this.notify(e)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(e=>e()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{let e=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==e){if(this.cleanup(),!e){this.maybeNotify();return}if(this.scrollElement=e,this.scrollElement&&`ownerDocument`in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=this.scrollElement?.window??null,this.elementsCache.forEach(e=>{this.observer.observe(e)}),this.unsubs.push(this.options.observeElementRect(this,e=>{this.scrollRect=e,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(e,t)=>{if(t&&this._intendedScrollOffset===null&&e===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(e-this._intendedScrollOffset)<1.5&&(e=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;let n=this.getScrollOffset();this.scrollDirection=t?n===e?this.scrollDirection:n<e?`forward`:`backward`:null,this.scrollOffset=e,this.isScrolling=t,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),`addEventListener`in this.scrollElement){let e=this.scrollElement,t=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},n=()=>{this._iosTouching=!1,!(!bt()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,Tt),e.addEventListener(`touchend`,n,Tt),this.unsubs.push(()=>{e.removeEventListener(`touchstart`,t),e.removeEventListener(`touchend`,n),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}let t=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,t&&this.scrollElement&&this.options.enabled){let[e,n,r,i]=t;e!==null&&!r&&(bt()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?i!==0&&(this._iosDeferredAdjustment+=i):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),r&&this.scrollToEnd({behavior:r})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;let e=this.getScrollOffset(),t=this.getMaxScrollOffset();if(e<0||e>t)return;let n=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(e,{adjustments:this.scrollAdjustments+=n,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?`width`:`height`]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset==`function`?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(e,t)=>{let n=new Map,r=new Map;for(let i=t-1;i>=0;i--){let t=e[i];if(n.has(t.lane))continue;let a=r.get(t.lane);if(a==null||t.end>a.end?r.set(t.lane,t):t.end<a.end&&n.set(t.lane,!0),n.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((e,t)=>e.end===t.end?e.index-t.index:e.end-t.end)[0]:void 0},this.getMeasurementOptions=ht(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(e,t,n,r,i,a,o)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMin=null,{count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o}),{key:!1}),this.getMeasurements=ht(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o},s)=>{let c=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>e)for(let t of this.laneAssignments.keys())t>=e&&this.laneAssignments.delete(t);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(e=>{this.itemSizeCache.set(e.key,e.size)}));let l=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1),a===1){let i=this.options.gap,a=e*2,o=this._flatMeasurements;if(!o||o.length<a){let e=new Float64Array(a);o&&l>0&&e.set(o.subarray(0,l*2)),o=e,this._flatMeasurements=o}let s;if(l===0)s=t+n;else{let e=l-1;s=o[e*2]+o[e*2+1]+i}for(let t=l;t<e;t++){let e=r(t),n=c.get(e),a=typeof n==`number`?n:this.options.estimateSize(t);o[t*2]=s,o[t*2+1]=a,s+=a+i}let u=mt(e,o,r);return this.measurementsCache=u,u}let u=this.measurementsCache.slice(0,l),d=Array(a).fill(void 0);for(let e=0;e<l;e++){let t=u[e];t&&(d[t.lane]=e)}for(let i=l;i<e;i++){let e=r(i),a=this.laneAssignments.get(i),s,l,f=o===`estimate`||c.has(e);if(a!==void 0&&this.options.lanes>1){s=a;let e=d[s],r=e===void 0?void 0:u[e];l=r?r.end+this.options.gap:t+n}else{let e=this.options.lanes===1?u[i-1]:this.getFurthestMeasurement(u,i);l=e?e.end+this.options.gap:t+n,s=e?e.lane:i%this.options.lanes,this.options.lanes>1&&f&&this.laneAssignments.set(i,s)}let p=c.get(e),m=typeof p==`number`?p:this.options.estimateSize(i),h=l+m;u[i]={index:i,start:l,size:m,end:h,key:e,lane:s},d[s]=i}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=ht(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>e.length===0||t===0?(this.range=null,null):(this.range=Pt(e,t,n,r,r===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=ht(()=>{let e=null,t=null,n=this.calculateRange();return n&&(e=n.startIndex,t=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,e,t]),[this.options.rangeExtractor,this.options.overscan,this.options.count,e,t]},(e,t,n,r,i)=>r===null||i===null?[]:e({startIndex:r,endIndex:i,overscan:t,count:n}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=e=>{let t=this.options.indexAttribute,n=e.getAttribute(t);return n?parseInt(n,10):(console.warn(`Missing attribute name '${t}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=e=>{if(!this.scrollState||this.scrollState.behavior!==`smooth`)return!0;let t=this.scrollState.index??this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index;if(t!==void 0&&this.range){let n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),r=Math.max(0,t-n),i=Math.min(this.options.count-1,t+n);return e>=r&&e<=i}return!0},this.measureElement=e=>{if(!e){this.elementsCache.forEach((e,t)=>{e.isConnected||(this.observer.unobserve(e),this.elementsCache.delete(t))});return}let t=this.indexFromElement(e),n=this.options.getItemKey(t),r=this.elementsCache.get(n);r!==e&&(r&&this.observer.unobserve(r),this.observer.observe(e),this.elementsCache.set(n,e)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(t)&&this.resizeItem(t,this.options.measureElement(e,void 0,this))},this.resizeItem=(e,t)=>{if(e<0||e>=this.options.count)return;let n,r,i,a=this._flatMeasurements;if(this.options.lanes===1&&a!==null)i=this.options.getItemKey(e),r=a[e*2],n=a[e*2+1];else{let t=this.measurementsCache[e];if(!t)return;i=t.key,r=t.start,n=t.size}let o=t-(this.itemSizeCache.get(i)??n);if(o!==0){let a=this.options.anchorTo===`end`&&this.scrollState?.behavior!==`smooth`&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,s=a?this.getTotalSize():0,c=this.scrollState?.behavior!==`smooth`&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?r<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(i)||this.scrollDirection!==`backward`):this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[e]??{index:e,key:i,start:r,size:n,end:r+n,lane:0},o,this));(this.pendingMin===null||e<this.pendingMin)&&(this.pendingMin=e),this.itemSizeCache.set(i,t),this.itemSizeCacheVersion++,a?this.applyScrollAdjustment(this.getTotalSize()-s):c&&this.applyScrollAdjustment(o),this.notify(!1)}},this.getVirtualItems=ht(()=>[this.getVirtualIndexes(),this.getMeasurements()],(e,t)=>{let n=[];for(let r=0,i=e.length;r<i;r++){let i=t[e[r]];n.push(i)}return n},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=e=>{let t=this.getMeasurements();if(t.length===0)return;let n=this._flatMeasurements,r=this.options.lanes===1&&n!=null;return gt(t[Mt(0,t.length-1,r?e=>n[e*2]:e=>gt(t[e]).start,e)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if(`scrollHeight`in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{let e=this.scrollElement.document.documentElement;return this.options.horizontal?e.scrollWidth-this.scrollElement.innerWidth:e.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(e=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=e,this.getOffsetForAlignment=(e,t,n=0)=>{if(!this.scrollElement)return 0;let r=this.getSize(),i=this.getScrollOffset();t===`auto`&&(t=e>=i+r?`end`:`start`),t===`center`?e+=(n-r)/2:t===`end`&&(e-=r);let a=this.getMaxScrollOffset();return Math.max(Math.min(a,e),0)},this.getOffsetForIndex=(e,t=`auto`)=>{e=Math.max(0,Math.min(e,this.options.count-1));let n=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[e];if(!i)return;if(t===`auto`)if(i.end>=r+n-this.options.scrollPaddingEnd)t=`end`;else if(i.start<=r+this.options.scrollPaddingStart)t=`start`;else return[r,t];if(t===`end`&&e===this.options.count-1)return[this.getMaxScrollOffset(),t];let a=t===`end`?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,t,i.size),t]},this.scrollToOffset=(e,{align:t=`start`,behavior:n=`auto`}={})=>{let r=this.getOffsetForAlignment(e,t),i=this.now();this.scrollState={index:null,align:t,behavior:n,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToIndex=(e,{align:t=`auto`,behavior:n=`auto`}={})=>{e=Math.max(0,Math.min(e,this.options.count-1));let r=this.getOffsetForIndex(e,t);if(!r)return;let[i,a]=r,o=this.now();this.scrollState={index:e,align:a,behavior:n,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollBy=(e,{behavior:t=`auto`}={})=>{let n=this.getScrollOffset()+e,r=this.now();this.scrollState={index:null,align:`start`,behavior:t,startedAt:r,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:t}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:e=`auto`}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:`end`,behavior:e});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:e})},this.getTotalSize=()=>{let e=this.getMeasurements(),t;if(e.length===0)t=this.options.paddingStart;else if(this.options.lanes===1){let n=e.length-1,r=this._flatMeasurements;t=r==null?e[n]?.end??0:r[n*2]+r[n*2+1]}else{let n=Array(this.options.lanes).fill(null),r=e.length-1;for(;r>=0&&n.some(e=>e===null);){let t=e[r];n[t.lane]===null&&(n[t.lane]=t.end),r--}t=Math.max(...n.filter(e=>e!==null))}return Math.max(t-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{let e=[];if(this.itemSizeCache.size===0)return e;let t=this.getMeasurements();for(let n of t)n&&this.itemSizeCache.has(n.key)&&e.push({index:n.index,key:n.key,start:n.start,size:n.size,end:n.end,lane:n.lane});return e},this._scrollToOffset=(e,{adjustments:t,behavior:n})=>{this._intendedScrollOffset=e+(t??0),this.options.scrollToFn(e,{behavior:n,adjustments:t},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(e)}applyScrollAdjustment(e,t){e!==0&&(bt()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=e:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=e,behavior:t}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId??=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()})}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}let e=this.scrollState.index==null?void 0:this.getOffsetForIndex(this.scrollState.index,this.scrollState.align),t=e?e[0]:this.scrollState.lastTargetOffset,n=t!==this.scrollState.lastTargetOffset;if(!n&&_t(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=1){this.getScrollOffset()!==t&&this._scrollToOffset(t,{adjustments:void 0,behavior:`auto`}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,n){let e=this.getSize()||600,n=Math.abs(t-this.getScrollOffset()),r=this.scrollState.behavior===`smooth`&&n>e;this.scrollState.lastTargetOffset=t,r||(this.scrollState.behavior=`auto`),this._scrollToOffset(t,{adjustments:void 0,behavior:r?`smooth`:`auto`})}this.scheduleScrollReconcile()}},Mt=(e,t,n,r)=>{for(;e<=t;){let i=(e+t)/2|0,a=n(i);if(a<r)e=i+1;else if(a>r)t=i-1;else return i}return e>0?e-1:0};function Nt(e,t,n){let r=0;for(;r<=t;){let i=(r+t)/2|0,a=e[i*2];if(a<n)r=i+1;else if(a>n)t=i-1;else return i}return r>0?r-1:0}function Pt(e,t,n,r,i){let a=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:a};if(r===1&&i!==null){let e=Nt(i,a,n),r=e,o=n+t;for(;r<a&&i[r*2]+i[r*2+1]<o;)r++;return{startIndex:e,endIndex:r}}let o=Mt(0,a,t=>e[t].start,n),s=o;if(r===1)for(;s<a&&e[s].end<n+t;)s++;else if(r>1){let i=Array(r).fill(0);for(;s<a&&i.some(e=>e<n+t);){let t=e[s];i[t.lane]=t.end,s++}let c=Array(r).fill(n+t);for(;o>=0&&c.some(e=>e>=n);){let t=e[o];c[t.lane]=t.start,o--}o=Math.max(0,o-o%r),s=Math.min(a,s+(r-1-s%r))}return{startIndex:o,endIndex:s}}var Ft=typeof document<`u`?_.useLayoutEffect:_.useEffect;function It({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n=`transform`,...r}){let i=_.useReducer(e=>e+1,0)[1],a=_.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});a.current.enabled=t,a.current.mode=n;let o=e=>{let t=a.current;if(!t.enabled||!t.container)return;let n=e.getTotalSize();if(n!==t.lastSize){t.lastSize=n;let r=e.options.horizontal?`width`:`height`;t.container.style[r]=`${n}px`}let r=!!e.options.horizontal,i=t.mode===`transform`,o=r?`left`:`top`,s=e.options.scrollMargin,c=e.getVirtualItems();for(let n of c){let a=n.start-s,c=e.elementsCache.get(n.key);c&&t.lastPositions.get(c)!==a&&(t.lastPositions.set(c,a),i?c.style.transform=r?`translate3d(${a}px, 0, 0)`:`translate3d(0, ${a}px, 0)`:c.style[o]=`${a}px`)}},s={...r,onChange:(t,n)=>{var s;let c=a.current,l=!0;if(c.enabled){o(t);let e=t.range,n=c.prevRange;l=!n||n.isScrolling!==t.isScrolling||n.startIndex!==e?.startIndex||n.endIndex!==e?.endIndex,l&&(c.prevRange=e?{startIndex:e.startIndex,endIndex:e.endIndex,isScrolling:t.isScrolling}:null)}l&&(e&&n?(0,pt.flushSync)(i):i()),(s=r.onChange)==null||s.call(r,t,n)}},[c]=_.useState(()=>{let e=new jt(s);return Object.assign(e,{containerRef:t=>{let n=a.current;if(n.container=t,n.lastSize=null,t&&n.enabled){let r=e.getTotalSize();n.lastSize=r;let i=e.options.horizontal?`width`:`height`;t.style[i]=`${r}px`}}})});return c.setOptions(s),Ft(()=>c._didMount(),[]),Ft(()=>c._willUpdate()),Ft(()=>{o(c)}),c}function Lt(e){return It({observeElementRect:wt,observeElementOffset:Ot,scrollToFn:At,...e})}var Rt={400:{en:{label:`Bad request`,description:`The proxy could not understand the request. Check the model, message shape, headers, and JSON body before retrying.`},ko:{label:`잘못된 요청`,description:`프록시가 요청을 이해할 수 없습니다. 재시도 전에 모델, 메시지 형식, 헤더, JSON 본문을 확인해야 합니다.`},zh:{label:`错误请求`,description:`代理无法理解该请求。重试前请检查模型、消息结构、标头和 JSON 正文。`},de:{label:`Ungültige Anfrage`,description:`Der Proxy konnte die Anfrage nicht verstehen. Prüfe Modell, Nachrichtenformat, Header und JSON-Body vor einem erneuten Versuch.`}},401:{en:{label:`Unauthorized`,description:`Credentials are missing, expired, or invalid. Re-login or refresh the account/provider credentials used by opencodex.`},ko:{label:`인증 필요`,description:`자격 증명이 없거나 만료되었거나 유효하지 않습니다. opencodex에서 사용하는 계정 또는 제공자 자격 증명을 다시 로그인하거나 갱신해야 합니다.`},zh:{label:`未授权`,description:`凭据缺失、已过期或无效。请重新登录,或刷新 opencodex 使用的账号/提供商凭据。`},de:{label:`Nicht autorisiert`,description:`Anmeldedaten fehlen, sind abgelaufen oder ungültig. Melde dich erneut an oder aktualisiere die von opencodex genutzten Konto-/Anbieter-Zugangsdaten.`}},402:{en:{label:`Payment required`,description:`The upstream provider rejected the request because billing, credits, or plan access is not available. Add credits, update billing, or switch provider.`},ko:{label:`결제 필요`,description:`청구, 크레딧, 플랜 접근 권한 문제로 업스트림 제공자가 요청을 거부했습니다. 크레딧 추가, 결제 정보 갱신, 제공자 전환이 필요합니다.`},zh:{label:`需要付款`,description:`上游提供商因账单、额度或套餐权限不可用而拒绝了请求。请充值、更新账单信息或切换提供商。`},de:{label:`Zahlung erforderlich`,description:`Der Upstream-Anbieter hat die Anfrage abgelehnt, weil Abrechnung, Guthaben oder Planzugriff nicht verfügbar ist. Guthaben aufladen, Abrechnung aktualisieren oder Anbieter wechseln.`}},403:{en:{label:`Forbidden`,description:`The account is authenticated but not allowed to use this model or operation. Check provider permissions, org access, and policy restrictions.`},ko:{label:`권한 없음`,description:`계정 인증은 되었지만 이 모델 또는 작업을 사용할 권한이 없습니다. 제공자 권한, 조직 접근, 정책 제한을 확인해야 합니다.`},zh:{label:`禁止访问`,description:`账号已认证,但无权使用此模型或操作。请检查提供商权限、组织访问权限和策略限制。`},de:{label:`Verboten`,description:`Das Konto ist authentifiziert, darf dieses Modell oder diese Operation aber nicht nutzen. Prüfe Anbieterberechtigungen, Organisationszugriff und Richtlinien.`}},404:{en:{label:`Not found`,description:`The requested route, model, account, or upstream resource was not found. Verify the model name and opencodex provider configuration.`},ko:{label:`찾을 수 없음`,description:`요청한 경로, 모델, 계정 또는 업스트림 리소스를 찾을 수 없습니다. 모델 이름과 opencodex 제공자 설정을 확인해야 합니다.`},zh:{label:`未找到`,description:`找不到请求的路由、模型、账号或上游资源。请确认模型名称和 opencodex 提供商配置。`},de:{label:`Nicht gefunden`,description:`Die angeforderte Route, das Modell, das Konto oder die Upstream-Ressource wurde nicht gefunden. Prüfe Modellname und opencodex-Anbieterkonfiguration.`}},408:{en:{label:`Request timeout`,description:`The request took too long before the proxy or upstream provider could complete it. Retry with a smaller request or a different provider.`},ko:{label:`요청 시간 초과`,description:`프록시 또는 업스트림 제공자가 요청을 완료하기 전에 시간이 초과되었습니다. 더 작은 요청으로 재시도하거나 다른 제공자로 전환해야 합니다.`},zh:{label:`请求超时`,description:`代理或上游提供商未能在限定时间内完成请求。请缩小请求后重试,或切换提供商。`},de:{label:`Anfrage-Timeout`,description:`Die Anfrage dauerte zu lange, bevor Proxy oder Upstream-Anbieter sie abschließen konnten. Mit kleinerer Anfrage oder anderem Anbieter erneut versuchen.`}},409:{en:{label:`Conflict`,description:`The request conflicts with the current account, session, or provider state. Refresh the session or retry after the active operation finishes.`},ko:{label:`상태 충돌`,description:`요청이 현재 계정, 세션 또는 제공자 상태와 충돌합니다. 세션을 갱신하거나 진행 중인 작업이 끝난 뒤 재시도해야 합니다.`},zh:{label:`状态冲突`,description:`请求与当前账号、会话或提供商状态冲突。请刷新会话,或等待当前操作完成后重试。`},de:{label:`Konflikt`,description:`Die Anfrage kollidiert mit dem aktuellen Konto-, Sitzungs- oder Anbieterstatus. Sitzung aktualisieren oder nach Abschluss der laufenden Operation erneut versuchen.`}},413:{en:{label:`Request too large`,description:`The prompt, attachments, or generated payload exceeds a proxy or upstream limit. Reduce tokens, file size, or conversation history.`},ko:{label:`요청 과대`,description:`프롬프트, 첨부 파일 또는 생성 페이로드가 프록시나 업스트림 한도를 초과했습니다. 토큰, 파일 크기, 대화 기록을 줄여야 합니다.`},zh:{label:`请求过大`,description:`提示、附件或生成的负载超过了代理或上游限制。请减少 token、文件大小或对话历史。`},de:{label:`Anfrage zu groß`,description:`Prompt, Anhänge oder generierte Nutzlast überschreiten ein Proxy- oder Upstream-Limit. Tokens, Dateigröße oder Verlauf reduzieren.`}},422:{en:{label:`Invalid content`,description:`The provider accepted the request format but rejected its contents. Check model options, tool definitions, message roles, and unsupported fields.`},ko:{label:`내용 검증 실패`,description:`제공자가 요청 형식은 받았지만 내용을 거부했습니다. 모델 옵션, 도구 정의, 메시지 역할, 지원되지 않는 필드를 확인해야 합니다.`},zh:{label:`内容无效`,description:`提供商接受了请求格式,但拒绝了其中的内容。请检查模型选项、工具定义、消息角色和不支持的字段。`},de:{label:`Ungültiger Inhalt`,description:`Der Anbieter akzeptierte das Anfrageformat, lehnte den Inhalt aber ab. Prüfe Modelloptionen, Tool-Definitionen, Nachrichtenrollen und nicht unterstützte Felder.`}},424:{en:{label:`Provider dependency failed`,description:`A required upstream dependency failed while opencodex was routing the request. Retry later or switch to another configured provider.`},ko:{label:`제공자 의존성 실패`,description:`opencodex가 요청을 라우팅하는 동안 필요한 업스트림 의존성이 실패했습니다. 나중에 재시도하거나 다른 설정된 제공자로 전환해야 합니다.`},zh:{label:`提供商依赖失败`,description:`opencodex 路由请求时,必需的上游依赖失败。请稍后重试,或切换到另一个已配置的提供商。`},de:{label:`Anbieter-Abhängigkeit fehlgeschlagen`,description:`Eine erforderliche Upstream-Abhängigkeit ist fehlgeschlagen, während opencodex die Anfrage geroutet hat. Später erneut versuchen oder zu einem anderen Anbieter wechseln.`}},429:{en:{label:`Rate limited`,description:`The upstream provider rate or quota limit has been reached. Wait for the quota window to reset or switch account/provider.`},ko:{label:`한도 초과`,description:`업스트림 제공자의 속도 또는 할당량 한도에 도달했습니다. 한도 창이 초기화될 때까지 기다리거나 계정/제공자를 전환해야 합니다.`},zh:{label:`限流`,description:`已达到上游提供商的速率或额度限制。请等待额度窗口重置,或切换账号/提供商。`},de:{label:`Ratenlimit erreicht`,description:`Das Raten- oder Kontingentlimit des Upstream-Anbieters ist erreicht. Auf Reset des Kontingentfensters warten oder Konto/Anbieter wechseln.`}},499:{en:{label:`Client closed request`,description:`The client disconnected or canceled the request before opencodex finished routing it. Retry if the cancellation was accidental.`},ko:{label:`클라이언트 취소`,description:`opencodex가 라우팅을 끝내기 전에 클라이언트 연결이 끊기거나 요청이 취소되었습니다. 의도한 취소가 아니면 다시 시도해야 합니다.`},zh:{label:`客户端已取消`,description:`opencodex 完成路由前,客户端已断开连接或取消请求。如果不是有意取消,请重试。`},de:{label:`Client hat Anfrage geschlossen`,description:`Der Client hat die Verbindung getrennt oder die Anfrage abgebrochen, bevor opencodex das Routing abgeschlossen hat. Bei versehentlichem Abbruch erneut versuchen.`}},500:{en:{label:`Proxy error`,description:`opencodex hit an internal error while handling the request. Retry once, then check proxy logs if it repeats.`},ko:{label:`프록시 오류`,description:`opencodex가 요청을 처리하는 동안 내부 오류가 발생했습니다. 한 번 재시도하고 반복되면 프록시 로그를 확인해야 합니다.`},zh:{label:`代理错误`,description:`opencodex 处理请求时发生内部错误。请先重试一次;如果重复出现,请检查代理日志。`},de:{label:`Proxy-Fehler`,description:`opencodex ist bei der Anfragebearbeitung auf einen internen Fehler gestoßen. Einmal erneut versuchen, bei Wiederholung Proxy-Logs prüfen.`}},502:{en:{label:`Bad upstream response`,description:`The upstream provider returned an invalid or failed response through the proxy. Retry or route the request to another provider.`},ko:{label:`업스트림 응답 오류`,description:`업스트림 제공자가 프록시를 통해 유효하지 않거나 실패한 응답을 반환했습니다. 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{label:`上游响应错误`,description:`上游提供商通过代理返回了无效或失败的响应。请重试,或将请求路由到其他提供商。`},de:{label:`Ungültige Upstream-Antwort`,description:`Der Upstream-Anbieter lieferte über den Proxy eine ungültige oder fehlgeschlagene Antwort. Erneut versuchen oder zu einem anderen Anbieter routen.`}},503:{en:{label:`Provider unavailable`,description:`The proxy or upstream provider is temporarily unavailable or overloaded. Wait briefly, then retry or switch provider.`},ko:{label:`제공자 사용 불가`,description:`프록시 또는 업스트림 제공자가 일시적으로 사용할 수 없거나 과부하 상태입니다. 잠시 기다린 뒤 재시도하거나 제공자를 전환해야 합니다.`},zh:{label:`提供商不可用`,description:`代理或上游提供商暂时不可用或过载。请稍后重试,或切换提供商。`},de:{label:`Anbieter nicht verfügbar`,description:`Proxy oder Upstream-Anbieter ist vorübergehend nicht verfügbar oder überlastet. Kurz warten, dann erneut versuchen oder Anbieter wechseln.`}},504:{en:{label:`Upstream timeout`,description:`The upstream provider did not respond before the proxy timeout. Retry with a smaller request or choose a faster provider.`},ko:{label:`업스트림 시간 초과`,description:`프록시 시간 제한 전에 업스트림 제공자가 응답하지 않았습니다. 더 작은 요청으로 재시도하거나 더 빠른 제공자를 선택해야 합니다.`},zh:{label:`上游超时`,description:`上游提供商未在代理超时前响应。请缩小请求后重试,或选择响应更快的提供商。`},de:{label:`Upstream-Timeout`,description:`Der Upstream-Anbieter antwortete nicht vor dem Proxy-Timeout. Mit kleinerer Anfrage erneut versuchen oder schnelleren Anbieter wählen.`}},529:{en:{label:`Provider overloaded`,description:`The upstream provider is overloaded or capacity-limited. Wait and retry, or switch to another account/provider.`},ko:{label:`제공자 과부하`,description:`업스트림 제공자가 과부하 상태이거나 처리 용량이 제한되었습니다. 기다렸다가 재시도하거나 다른 계정/제공자로 전환해야 합니다.`},zh:{label:`提供商过载`,description:`上游提供商过载或容量受限。请等待后重试,或切换到其他账号/提供商。`},de:{label:`Anbieter überlastet`,description:`Der Upstream-Anbieter ist überlastet oder kapazitätsbegrenzt. Warten und erneut versuchen oder anderes Konto/Anbieter nutzen.`}}},zt={client:{en:{label:`Request error`,description:`The proxy or upstream provider rejected the request. Check the request shape, credentials, model name, and provider configuration.`},ko:{label:`요청 오류`,description:`프록시 또는 업스트림 제공자가 요청을 거부했습니다. 요청 형식, 자격 증명, 모델 이름, 제공자 설정을 확인해야 합니다.`},zh:{label:`请求错误`,description:`代理或上游提供商拒绝了该请求。请检查请求结构、凭据、模型名称和提供商配置。`},de:{label:`Anfragefehler`,description:`Der Proxy oder Upstream-Anbieter hat die Anfrage abgelehnt. Prüfe Anfrageformat, Anmeldedaten, Modellname und Anbieterkonfiguration.`}},server:{en:{label:`Server or upstream error`,description:`opencodex or an upstream provider failed while processing the request. Retry later or route the request to another provider.`},ko:{label:`서버 또는 업스트림 오류`,description:`opencodex 또는 업스트림 제공자가 요청 처리 중 실패했습니다. 나중에 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{label:`服务器或上游错误`,description:`opencodex 或上游提供商处理请求时失败。请稍后重试,或将请求路由到其他提供商。`},de:{label:`Server- oder Upstream-Fehler`,description:`opencodex oder ein Upstream-Anbieter ist bei der Anfragebearbeitung fehlgeschlagen. Später erneut versuchen oder zu einem anderen Anbieter routen.`}}};function Bt(e){return e===`de`||e===`ko`||e===`zh`?e:`en`}function Vt(e,t){if(e<400)return null;let n=Bt(t);return(Rt[Math.trunc(e)]??(e<500?zt.client:zt.server))[n]}function Ht(e,t){if(!e.usage)return;let n=Wt(e),r=[`${t(`logs.tokens.input`)}=${e.usage.inputTokens}`,`${t(`logs.tokens.output`)}=${e.usage.outputTokens}`];return n.read!==void 0&&r.push(`${t(`logs.tokens.cacheRead`)}=${n.read}`),n.write!==void 0&&r.push(`${t(`logs.tokens.cacheWrite`)}=${n.write}`),typeof e.usage.reasoningOutputTokens==`number`&&r.push(`${t(`logs.tokens.reasoning`)}=${e.usage.reasoningOutputTokens}`),e.usageStatus===`estimated`&&r.push(t(`logs.tokens.estimatedNote`)),e.usageStatus===`estimated`&&n.read===void 0&&n.write===void 0&&r.push(t(`logs.tokens.noCacheNote`)),r.join(` · `)}function Ut(e){if(!e.usage)return typeof e.totalTokens==`number`?e.totalTokens:void 0;let t=e.usage.inputTokens+e.usage.outputTokens,n=e.usage.totalTokens??e.totalTokens;return typeof n==`number`?Math.max(n,t):t}function Wt(e){let t=e.usage;if(!t)return{};let n=typeof t.cacheCreationInputTokens==`number`?t.cacheCreationInputTokens:void 0;return{read:typeof t.cacheReadInputTokens==`number`?t.cacheReadInputTokens:typeof t.cachedInputTokens==`number`&&n!==void 0?Math.max(0,t.cachedInputTokens-n):t.cachedInputTokens,write:n}}function Gt(e){if(e.requestedSpeedLabel)return e.requestedSpeedLabel;if(e.modelSupportsServiceTier&&e.configuredSpeedLabel)return e.configuredSpeedLabel}function Kt(e){return[`model=${e.model}`,e.resolvedModel?`resolved=${e.resolvedModel}`:void 0,e.requestedServiceTier?`requestedTier=${e.requestedServiceTier}`:void 0,e.configuredServiceTier?`configuredTier=${e.configuredServiceTier}`:void 0,e.responseServiceTier?`responseTier=${e.responseServiceTier}`:void 0,e.modelSupportsServiceTier===void 0?void 0:`supportsTier=${e.modelSupportsServiceTier}`].filter(Boolean).join(` · `)}function qt({apiBase:e}){let{t,locale:n}=Ce(),[r,i]=(0,_.useState)([]),[a,o]=(0,_.useState)(!0),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(`all`),d=(0,_.useRef)(null),f=ve.find(e=>e.code===n)?.htmlLang;(0,_.useEffect)(()=>{let t=async()=>{try{i(await(await fetch(`${e}/api/logs`)).json())}catch{}};if(t(),!a)return;let n=setInterval(t,2e3);return()=>clearInterval(n)},[e,a]);let p=e=>e>=200&&e<300?`var(--green)`:e>=400?`var(--red)`:`var(--amber)`,m=s?Vt(s.status,n):null,h=r.filter(e=>l===`all`||(l===`claude`?e.surface===`claude`:e.surface!==`claude`)),g=Lt({count:h.length,getScrollElement:()=>d.current,estimateSize:()=>44,overscan:15}),v=g.getVirtualItems(),y=v.length>0?v[0].start:0,b=v.length>0?g.getTotalSize()-v[v.length-1].end:0;return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{className:`page-head`,children:[(0,S.jsx)(`h2`,{children:t(`logs.title`)}),(0,S.jsxs)(`label`,{className:`muted text-control`,style:{cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,S.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked)}),t(`logs.autoRefresh`)]})]}),(0,S.jsx)(`p`,{className:`page-sub`,children:t(`logs.subtitle`)}),(0,S.jsxs)(`div`,{className:`row`,style:{gap:8,marginBottom:12,alignItems:`center`},children:[(0,S.jsx)(`span`,{className:`muted text-control`,children:t(`logs.filter.surface.label`)}),(0,S.jsx)(`div`,{className:`segmented`,role:`radiogroup`,"aria-label":t(`logs.filter.surface.label`),style:{display:`inline-flex`,borderRadius:`var(--radius-pill)`,background:`var(--surface-soft, var(--raised))`,padding:3,gap:2},children:[`all`,`claude`,`codex`].map(e=>(0,S.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":l===e,className:`btn btn-sm${l===e?` btn-primary`:` btn-ghost`}`,style:{borderRadius:`var(--radius-pill)`,minWidth:64,padding:`5px 12px`,border:`none`,background:l===e?void 0:`transparent`,color:l===e?void 0:`var(--muted)`},onClick:()=>u(e),children:t(`logs.filter.surface.${e}`)},e))})]}),h.length===0?(0,S.jsx)(Ne,{title:t(`logs.noRequests`)}):(0,S.jsx)(`div`,{ref:d,className:`tbl-wrap`,style:{overflowY:`auto`,maxHeight:`calc(100vh - 260px)`},children:(0,S.jsxs)(`table`,{className:`tbl`,children:[(0,S.jsx)(`thead`,{style:{position:`sticky`,top:0,zIndex:1,background:`var(--surface)`},children:(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`th`,{children:t(`logs.col.time`)}),(0,S.jsx)(`th`,{className:`num log-col-tokens`,children:t(`logs.col.tokens`)}),(0,S.jsx)(`th`,{className:`log-col-model`,children:t(`logs.col.model`)}),(0,S.jsx)(`th`,{children:t(`logs.col.effort`)}),(0,S.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,S.jsx)(`th`,{children:t(`logs.col.status`)}),(0,S.jsx)(`th`,{children:t(`logs.col.request`)}),(0,S.jsx)(`th`,{className:`num`,children:t(`logs.col.duration`)})]})}),(0,S.jsxs)(`tbody`,{children:[y>0&&(0,S.jsx)(`tr`,{children:(0,S.jsx)(`td`,{colSpan:8,style:{height:y,padding:0,border:0}})}),v.map(e=>{let r=h[h.length-1-e.index];return(0,S.jsxs)(`tr`,{"data-index":e.index,ref:g.measureElement,children:[(0,S.jsx)(`td`,{className:`muted mono`,children:new Date(r.timestamp).toLocaleTimeString(f)}),(0,S.jsx)(`td`,{className:`num mono log-col-tokens`,title:Ht(r,t),children:(()=>{let e=Ut(r),{read:i,write:a}=Wt(r);return e===void 0?(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.tokens.${r.usageStatus??`unreported`}`)}):(0,S.jsxs)(`span`,{style:{display:`inline-flex`,flexDirection:`column`,alignItems:`flex-end`,gap:2},children:[(0,S.jsxs)(`span`,{children:[r.usageStatus===`estimated`?`~`:``,ke(e,n)]}),i!==void 0&&i>0&&(0,S.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`c `,ke(i,n)]}),a!==void 0&&a>0&&(0,S.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`w `,ke(a,n)]}),r.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,S.jsx)(`span`,{className:`muted text-caption leading-tight`,children:t(`logs.tokens.noCache`)})]})})()}),(0,S.jsx)(`td`,{className:`mono log-col-model`,title:Kt(r),children:(0,S.jsxs)(`span`,{style:{display:`inline-flex`,alignItems:`center`,gap:6,flexWrap:`wrap`},children:[(0,S.jsx)(`span`,{children:z(r.resolvedModel??r.model)}),r.surface===`claude`&&(0,S.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.claude`)}),Gt(r)&&(0,S.jsx)(`span`,{className:`badge badge-amber`,children:Gt(r)})]})}),(0,S.jsx)(`td`,{className:`mono`,children:r.requestedEffort??`-`}),(0,S.jsx)(`td`,{className:`muted`,children:r.provider}),(0,S.jsx)(`td`,{children:(0,S.jsxs)(`span`,{className:`log-status-cell`,children:[(0,S.jsx)(`span`,{className:`mono font-semibold`,style:{color:p(r.status)},children:r.status}),r.status>=400&&(0,S.jsx)(`button`,{type:`button`,className:`log-detail-btn`,onClick:()=>c(r),children:t(`logs.details`)})]})}),(0,S.jsx)(`td`,{className:`muted mono`,children:(0,S.jsx)(`span`,{className:`log-reqid`,title:r.requestId,children:r.requestId??`-`})}),(0,S.jsxs)(`td`,{className:`num`,children:[r.durationMs,`ms`]})]},r.requestId??`${r.timestamp}-${e.index}`)}),b>0&&(0,S.jsx)(`tr`,{children:(0,S.jsx)(`td`,{colSpan:8,style:{height:b,padding:0,border:0}})})]})]})}),s&&(0,S.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":t(`logs.detailTitle`),className:`modal-overlay`,onClick:()=>c(null),children:(0,S.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,S.jsxs)(`div`,{className:`modal-head`,children:[(0,S.jsxs)(`h3`,{children:[(0,S.jsx)(`span`,{className:`mono`,style:{color:p(s.status)},children:s.status}),m&&(0,S.jsx)(`span`,{style:{marginLeft:8},children:m.label})]}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-sm`,onClick:()=>c(null),"aria-label":t(`common.cancel`),children:(0,S.jsx)(ie,{})})]}),m&&(0,S.jsx)(`p`,{className:`modal-desc`,children:m.description}),(0,S.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.col.time`)}),(0,S.jsx)(`span`,{className:`mono`,children:new Date(s.timestamp).toLocaleString(f)}),(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.col.request`)}),(0,S.jsx)(`span`,{className:`mono log-detail-break`,children:s.requestId??`-`}),(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.col.model`)}),(0,S.jsx)(`span`,{className:`mono`,children:z(s.resolvedModel??s.model)}),(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.col.provider`)}),(0,S.jsx)(`span`,{children:s.provider}),s.errorCode&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.col.error`)}),(0,S.jsx)(`span`,{className:`mono`,children:s.errorCode})]}),s.upstreamError&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.col.upstreamReason`)}),(0,S.jsx)(`span`,{className:`mono log-detail-break`,children:s.upstreamError})]}),(0,S.jsx)(`span`,{className:`muted`,children:t(`logs.col.duration`)}),(0,S.jsxs)(`span`,{className:`mono`,children:[s.durationMs,`ms`]})]}),(0,S.jsx)(`div`,{className:`muted text-label`,style:{margin:`12px 0 6px`},children:t(`logs.detailRaw`)}),(0,S.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(s,null,2)})]})})]})}var Jt=[`provider`,`usage`,`injection`],Yt=e=>e>0?`[${new Date(e).toLocaleTimeString()}] `:``;function Xt({apiBase:e}){let{t}=Ce(),[n,r]=(0,_.useState)(null),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(`provider`),[c,l]=(0,_.useState)([]),[u,d]=(0,_.useState)(!0),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)([]),g=(0,_.useRef)(0),v=(0,_.useRef)(null),y=Lt({count:c.length,getScrollElement:()=>v.current,estimateSize:()=>20,overscan:30,getItemKey:e=>c[e].seq});(0,_.useEffect)(()=>{let t=async()=>{try{let t=await fetch(`${e}/api/debug`);t.ok&&r(await t.json())}catch{}};t();let n=setInterval(()=>void t(),2e3);return()=>clearInterval(n)},[e]);let b=(0,_.useCallback)(e=>e===`provider`?!!n?.enabled:e===`usage`?!!n?.usage:!!n?.injection,[n]);(0,_.useEffect)(()=>{if(!n||b(o))return;let e=Jt.find(b);if(!e)return;let t=window.setTimeout(()=>s(e),0);return()=>window.clearTimeout(t)},[n,o,b]);let x=b(o),C=o===`provider`?`${e}/api/debug/logs`:o===`usage`?`${e}/api/debug/usage-logs`:`${e}/api/debug/injection-logs`,w=(0,_.useCallback)(async e=>{if(!x){l([]),g.current=0;return}p(!0);try{let t=new URLSearchParams({limit:`500`});!e&&g.current>0&&t.set(`after`,String(g.current));let n=await fetch(`${C}?${t}`);if(!n.ok)return;let r=await n.json();if(r.length===0)return;l(t=>(e?r:[...t,...r]).slice(-2e3)),g.current=r[r.length-1].seq}catch{}finally{p(!1)}},[C,x]);(0,_.useEffect)(()=>{g.current=0;let e=window.setTimeout(()=>{l([]),w(!0)},0);return()=>window.clearTimeout(e)},[o,x,w]),(0,_.useEffect)(()=>{if(!u||!x)return;let e=setInterval(()=>void w(!1),1e3);return()=>clearInterval(e)},[u,x,w]),(0,_.useEffect)(()=>{u&&c.length>0&&y.scrollToIndex(c.length-1,{align:`end`})},[c,u,y]),(0,_.useEffect)(()=>{if(!n?.claude){h([]);return}let t=async()=>{try{let t=await fetch(`${e}/api/claude/inbound-debug`);if(t.ok){let e=await t.json();h(Array.isArray(e.entries)?e.entries:[])}}catch{}};t();let r=setInterval(()=>void t(),2e3);return()=>clearInterval(r)},[e,n?.claude]);let T=async(t,n)=>{a(!0);try{let i=await fetch(`${e}/api/debug`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({[t]:n})});i.ok&&r(await i.json())}catch{}finally{a(!1)}},ee=async()=>{a(!0);try{let t=await fetch(`${e}/api/debug`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({reset:!0})});t.ok&&r(await t.json())}catch{}finally{a(!1)}};return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{className:`page-head`,children:[(0,S.jsx)(`h2`,{children:t(`debug.title`)}),(0,S.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:12},children:[(0,S.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:f||!x,onClick:()=>void w(!0),children:[(0,S.jsx)(k,{}),` `,t(`debug.refresh`)]}),(0,S.jsxs)(`label`,{className:`muted text-control`,style:{cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,S.jsx)(`input`,{type:`checkbox`,checked:u,onChange:e=>d(e.target.checked)}),t(`debug.follow`)]})]})]}),(0,S.jsx)(`p`,{className:`page-sub`,children:t(`debug.subtitle`)}),n?(0,S.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,S.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,S.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:16},children:[`debug`,`usage`,`injection`,`claude`].map(e=>{let r=e===`debug`?n.enabled:e===`usage`?n.usage:e===`injection`?n.injection:n.claude;return(0,S.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:10,minWidth:220},children:[(0,S.jsx)(Ae,{on:r,disabled:i,label:t(`debug.${e}`),onClick:()=>void T(e,!r)}),(0,S.jsx)(`span`,{className:`text-control`,children:t(`debug.${e}`)})]},e)})}),(0,S.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:i,onClick:()=>void ee(),children:t(`debug.reset`)})]}),(n.enabled||n.usage||n.injection)&&(0,S.jsxs)(`div`,{style:{display:`inline-flex`,gap:6,marginTop:12},children:[n.enabled&&(0,S.jsx)(`button`,{type:`button`,className:`btn btn-sm${o===`provider`?` btn-primary`:` btn-ghost`}`,onClick:()=>s(`provider`),children:t(`debug.streamProvider`)}),n.usage&&(0,S.jsx)(`button`,{type:`button`,className:`btn btn-sm${o===`usage`?` btn-primary`:` btn-ghost`}`,onClick:()=>s(`usage`),children:t(`debug.streamUsage`)}),n.injection&&(0,S.jsx)(`button`,{type:`button`,className:`btn btn-sm${o===`injection`?` btn-primary`:` btn-ghost`}`,onClick:()=>s(`injection`),children:t(`debug.streamInjection`)})]})]}):(0,S.jsx)(`div`,{className:`empty`,children:t(`debug.loading`)}),n?.claude&&(0,S.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,S.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:4},children:t(`debug.claudeInbound.title`)}),(0,S.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:t(`debug.claudeInbound.sub`)}),m.length===0?(0,S.jsx)(`div`,{className:`muted text-control`,children:t(`debug.claudeInbound.empty`)}):(0,S.jsx)(`div`,{style:{overflowX:`auto`},children:(0,S.jsxs)(`table`,{className:`table text-label`,children:[(0,S.jsx)(`thead`,{children:(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,S.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,S.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,S.jsx)(`th`,{children:`thinking`}),(0,S.jsx)(`th`,{children:`effort`}),(0,S.jsx)(`th`,{children:`beta`}),(0,S.jsx)(`th`,{children:`metadata`}),(0,S.jsx)(`th`,{children:`system`})]})}),(0,S.jsx)(`tbody`,{children:m.map((e,n)=>(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`td`,{className:`muted mono`,children:new Date(e.at).toLocaleTimeString()}),(0,S.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,S.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,S.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,S.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,S.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,S.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,S.jsx)(`td`,{className:`mono`,title:e.anthropicBeta,style:{maxWidth:160,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.anthropicBeta??`-`}),(0,S.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,S.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},`${e.at}-${n}`))})]})})]}),n&&!x?(0,S.jsxs)(`div`,{className:`empty`,children:[(0,S.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:t(`debug.emptyTitle`)}),(0,S.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:t(`debug.empty`)})]}):n&&x&&c.length===0?(0,S.jsxs)(`div`,{className:`empty`,children:[(0,S.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:t(`debug.noLinesTitle`)}),(0,S.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:t(`debug.noLines.${o}`)})]}):n&&x?(0,S.jsx)(`div`,{ref:v,className:`log-detail-json`,style:{maxHeight:`calc(100vh - 280px)`,overflow:`auto`},children:(0,S.jsx)(`div`,{style:{position:`relative`,height:y.getTotalSize(),width:`100%`},children:y.getVirtualItems().map(e=>(0,S.jsx)(`div`,{ref:y.measureElement,"data-index":e.index,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${e.start}px)`},children:`${Yt(c[e.index].at)}${c[e.index].line}`},e.key))})}):null]})}function Zt(e){return`${Math.round(e*100)}%`}function Qt(e,t){let n=`${t}/${e}`,r=0;for(let e=0;e<n.length;e++)r=r*31+n.charCodeAt(e)>>>0;return`hsl(${r%360} 55% 55%)`}function $t(e){let t=new Map(e.map(e=>[e.date,e])),n=[],r=new Date;r.setHours(0,0,0,0),r.setDate(r.getDate()-6);for(let e=0;e<7;e++){let e=`${r.getFullYear()}-${String(r.getMonth()+1).padStart(2,`0`)}-${String(r.getDate()).padStart(2,`0`)}`,i=t.get(e);n.push({date:e,requests:i?.requests??0,measuredRequests:i?.measuredRequests??0,reportedRequests:i?.reportedRequests??0,totalTokens:i?.totalTokens??0,models:i?.models??[]}),r.setDate(r.getDate()+1)}return n}function en(e){let t=e.filter(e=>e>0).sort((e,t)=>e-t);if(t.length===0)return[0,0,0,0];let n=e=>t[Math.min(t.length-1,Math.floor(e*t.length))];return[n(.25),n(.5),n(.75),n(.95)]}function tn(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function nn(e){let t=en(e.map(e=>e.totalTokens)),n=new Map(e.map(e=>[e.date,e])),r=new Date;r.setHours(0,0,0,0);let i=new Date(r);i.setDate(i.getDate()-364),i.setDate(i.getDate()-i.getDay());let a=[],o=[],s=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],c=-4,l=-1,u=[],d=new Date(i);for(;d<=r;){let e=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,`0`)}-${String(d.getDate()).padStart(2,`0`)}`,r=d.getMonth();d.getDay()===0&&r!==l&&a.length-c>=4&&(o.push({label:s[r],col:a.length}),c=a.length,l=r);let i=n.get(e);u.push({date:e,requests:i?.requests??0,totalTokens:i?.totalTokens??0,level:i?tn(i.totalTokens,t):0,dayOfWeek:d.getDay()}),d.getDay()===6&&(a.push(u),u=[]),d.setDate(d.getDate()+1)}if(u.length>0){for(;u.length<7;)u.push({date:``,requests:0,totalTokens:0,level:0,dayOfWeek:u.length});a.push(u)}return{weeks:a,months:o,buckets:t}}function rn({apiBase:e}){let{t,locale:n}=Ce(),[r,i]=(0,_.useState)(`30d`),[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(!0),[l,u]=(0,_.useState)(``),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(null),h=(0,_.useCallback)(async(t,n)=>{c(!0);try{let r=await fetch(`${e}/api/usage?range=${t}`,{signal:n});if(!r.ok)throw Error(`fetch failed`);let i=await r.json();if(n.aborted)return;o(i)}catch{if(n.aborted)return;o(null)}finally{n.aborted||c(!1)}},[e]);(0,_.useEffect)(()=>{let e=new AbortController,t=window.setTimeout(()=>{h(r,e.signal)},0);return()=>{window.clearTimeout(t),e.abort()}},[h,r]);let g=(0,_.useMemo)(()=>nn(a?.days??[]),[a?.days]),v=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=v.current;if(!e)return;let t=()=>{e.scrollLeft=e.scrollWidth};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[g,r,s]);let y=(0,_.useMemo)(()=>$t(a?.days??[]),[a?.days]),b=(0,_.useMemo)(()=>(a?.days??[]).filter(e=>e.requests>0).length,[a?.days]),x=(0,_.useMemo)(()=>{let e=l.trim().toLowerCase(),t=[...a?.models??[]].sort((e,t)=>t.totalTokens-e.totalTokens);return e?t.filter(t=>t.model.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)||(t.resolvedModel??``).toLowerCase().includes(e)).slice(0,100):t.slice(0,100)},[a?.models,l]),C=(0,_.useMemo)(()=>[...a?.providers??[]].sort((e,t)=>t.totalTokens-e.totalTokens),[a?.providers]);return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{className:`page-head`,children:[(0,S.jsx)(`h2`,{children:t(`usage.title`)}),(0,S.jsx)(`div`,{className:`usage-range`,role:`group`,"aria-label":t(`usage.title`),children:[`all`,`30d`,`7d`].map(e=>(0,S.jsx)(`button`,{type:`button`,className:`usage-range-btn${r===e?` active`:``}`,onClick:()=>i(e),children:t(`usage.range.${e}`)},e))})]}),(0,S.jsx)(`p`,{className:`page-sub`,children:t(`usage.subtitle`)}),s&&!a?(0,S.jsx)(Ne,{title:t(`usage.loading`)}):!a||a.summary.requests===0?(0,S.jsx)(Ne,{title:t(`usage.empty`)}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.card.requests`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:a.summary.requests})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.card.measured`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:a.summary.measuredRequests})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.card.totalTokens`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:ke(a.summary.totalTokens,n)})]}),(0,S.jsxs)(`div`,{className:`stat`,title:t(`usage.card.cachedTokensHint`),children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.card.cachedTokens`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:ke(a.summary.cacheReadInputTokens??a.summary.cachedInputTokens,n)}),(a.summary.cacheCreationInputTokens??0)>0&&(0,S.jsxs)(`div`,{className:`muted text-caption`,children:[t(`usage.card.cacheWriteTokens`),`: `,ke(a.summary.cacheCreationInputTokens??0,n)]})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.card.coverage`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:Zt(a.summary.coverageRatio)})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.card.activeDays`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:b})]})]}),(0,S.jsxs)(`section`,{className:`panel`,style:{marginTop:16},children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`usage.section.heatmap`)}),r===`7d`?(0,S.jsx)(`div`,{className:`daybars`,children:y.map((e,t)=>{let r=Math.max(1,...y.map(e=>e.totalTokens)),i=Math.round(e.totalTokens/r*100),a=e.date.slice(5);return(0,S.jsxs)(`div`,{className:`daybar`,onMouseEnter:()=>f(t),onMouseLeave:()=>f(e=>e===t?null:e),children:[(0,S.jsx)(`div`,{className:`daybar-track`,children:(0,S.jsxs)(`div`,{className:`daybar-stack`,style:{height:`${i}%`},children:[e.models.map(e=>(0,S.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:e.totalTokens,background:Qt(e.model,e.provider)}},`${e.provider}/${e.model}`)),e.models.length===0&&e.totalTokens>0&&(0,S.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:1,background:`var(--green)`}})]})}),d===t&&e.totalTokens>0&&(0,S.jsxs)(`div`,{className:`daybar-tip`,children:[(0,S.jsx)(`div`,{className:`daybar-tip-date`,children:e.date}),e.models.slice(0,8).map(e=>(0,S.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,S.jsx)(`span`,{className:`daybar-tip-swatch`,style:{background:Qt(e.model,e.provider)}}),(0,S.jsx)(`span`,{className:`daybar-tip-name`,children:z(e.model)}),(0,S.jsx)(`span`,{className:`daybar-tip-val`,children:ke(e.totalTokens,n)})]},`${e.provider}/${e.model}`))]}),(0,S.jsx)(`span`,{className:`daybar-count`,children:ke(e.totalTokens,n)}),(0,S.jsx)(`span`,{className:`daybar-label muted`,children:a})]},t)})}):(0,S.jsxs)(`div`,{className:`heatmap`,ref:v,children:[(0,S.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${g.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,S.jsx)(`span`,{className:`heatmap-day-spacer`}),g.months.map((e,t)=>(0,S.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:e.label},t))]}),(0,S.jsxs)(`div`,{className:`heatmap-body`,children:[(0,S.jsxs)(`div`,{className:`heatmap-days`,children:[(0,S.jsx)(`span`,{}),(0,S.jsx)(`span`,{children:`Mon`}),(0,S.jsx)(`span`,{}),(0,S.jsx)(`span`,{children:`Wed`}),(0,S.jsx)(`span`,{}),(0,S.jsx)(`span`,{children:`Fri`}),(0,S.jsx)(`span`,{})]}),(0,S.jsx)(`div`,{className:`heatmap-grid`,style:{gridTemplateColumns:`repeat(${g.weeks.length}, var(--hm-cell))`},children:g.weeks.map((e,t)=>(0,S.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,n)=>(0,S.jsx)(`div`,{className:`heatmap-cell heatmap-cell-${e.level}`,onMouseEnter:r=>{if(!e.date)return;let i=r.target.getBoundingClientRect();m({wi:t,di:n,x:i.left+i.width/2,y:i.top})},onMouseLeave:()=>m(e=>e?.wi===t&&e?.di===n?null:e)},`${t}-${n}`))},t))})]}),p&&(()=>{let e=g.weeks[p.wi]?.[p.di];return e?.date?(0,S.jsxs)(`div`,{className:`heatmap-tip`,style:{left:p.x,top:p.y},children:[(0,S.jsx)(`div`,{className:`heatmap-tip-date`,children:e.date}),(0,S.jsxs)(`div`,{className:`heatmap-tip-val`,children:[ke(e.totalTokens,n),` tokens`]}),(0,S.jsxs)(`div`,{className:`heatmap-tip-req muted`,children:[e.requests,` requests`]})]}):null})(),(0,S.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,S.jsx)(`span`,{children:t(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,S.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,S.jsx)(`span`,{children:t(`usage.heatmap.more`)})]})]})]}),(0,S.jsxs)(`section`,{className:`panel`,style:{marginTop:16},children:[(0,S.jsxs)(`div`,{className:`panel-head`,children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`usage.section.models`)}),(0,S.jsx)(`input`,{className:`input`,placeholder:t(`usage.search.models`),value:l,onChange:e=>u(e.target.value)})]}),(0,S.jsx)(`div`,{className:`tbl-wrap usage-scroll`,children:(0,S.jsxs)(`table`,{className:`tbl`,children:[(0,S.jsx)(`thead`,{children:(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`th`,{children:t(`logs.col.model`)}),(0,S.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,S.jsx)(`th`,{className:`num`,children:t(`usage.col.requests`)}),(0,S.jsx)(`th`,{className:`num`,children:t(`usage.col.measured`)}),(0,S.jsx)(`th`,{className:`num`,children:t(`usage.col.tokens`)}),(0,S.jsx)(`th`,{children:t(`usage.col.share`)})]})}),(0,S.jsx)(`tbody`,{children:x.map(e=>(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`td`,{className:`mono`,children:z(e.resolvedModel??e.model)}),(0,S.jsx)(`td`,{className:`muted`,children:e.provider}),(0,S.jsx)(`td`,{className:`num`,children:e.requests}),(0,S.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,S.jsx)(`td`,{className:`num mono`,children:ke(e.totalTokens,n)}),(0,S.jsx)(`td`,{children:(0,S.jsx)(`div`,{className:`usage-bar`,children:(0,S.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},`${e.provider}/${e.model}/${e.resolvedModel??``}`))})]})})]}),(0,S.jsxs)(`section`,{className:`panel`,style:{marginTop:16},children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`usage.section.providers`)}),(0,S.jsx)(`div`,{className:`tbl-wrap usage-scroll`,children:(0,S.jsxs)(`table`,{className:`tbl`,children:[(0,S.jsx)(`thead`,{children:(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,S.jsx)(`th`,{className:`num`,children:t(`usage.col.requests`)}),(0,S.jsx)(`th`,{className:`num`,children:t(`usage.col.measured`)}),(0,S.jsx)(`th`,{className:`num`,children:t(`usage.col.tokens`)}),(0,S.jsx)(`th`,{children:t(`usage.col.share`)})]})}),(0,S.jsx)(`tbody`,{children:C.map(e=>(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`td`,{className:`mono`,children:e.provider}),(0,S.jsx)(`td`,{className:`num`,children:e.requests}),(0,S.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,S.jsx)(`td`,{className:`num mono`,children:ke(e.totalTokens,n)}),(0,S.jsx)(`td`,{children:(0,S.jsx)(`div`,{className:`usage-bar`,children:(0,S.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},e.provider))})]})})]}),(0,S.jsxs)(`section`,{className:`panel`,style:{marginTop:16},children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`usage.section.coverage`)}),(0,S.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.measured`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:a.summary.measuredRequests})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.reported`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:a.summary.reportedRequests})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.estimated`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:a.summary.estimatedRequests})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unreported`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:a.summary.unreportedRequests})]}),(0,S.jsxs)(`div`,{className:`stat`,children:[(0,S.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unsupported`)}),(0,S.jsx)(`div`,{className:`stat-value`,children:a.summary.unsupportedRequests})]})]}),(0,S.jsx)(`p`,{className:`muted text-control`,style:{marginTop:12},children:t(`usage.coverage.note`)})]})]})]})}function an({apiBase:e,onClose:t,onAdded:n}){let r=we(),i=(0,_.useRef)(!0),a=(0,_.useRef)(null),o=(0,_.useRef)(null),s=(0,_.useRef)(null),c=(0,_.useRef)(null);(0,_.useEffect)(()=>()=>{i.current=!1,a.current&&=(clearInterval(a.current),null),o.current&&=(clearTimeout(o.current),null)},[]);let[l,u]=(0,_.useState)(`pick`),[d,f]=(0,_.useState)(``),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(!1),b=()=>{a.current&&=(clearInterval(a.current),null),o.current&&=(clearTimeout(o.current),null)},x=async()=>{let t=s.current;s.current=null,c.current=null,g(``),b(),t&&await fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:t})}).catch(()=>{})},C=()=>{l===`oauth-waiting`&&x(),t()};return(0,_.useEffect)(()=>{let e=e=>{e.key===`Escape`&&C()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)}),(0,S.jsx)(`div`,{className:`modal-overlay`,onClick:C,children:(0,S.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:440},children:[l===`pick`&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`h3`,{style:{marginBottom:4},children:r(`codexAuth.addTitle`)}),(0,S.jsx)(`p`,{className:`modal-desc`,children:r(`codexAuth.addPickDesc`)}),(0,S.jsx)(`label`,{className:`field-label`,children:r(`codexAuth.addIdLabel`)}),(0,S.jsx)(`input`,{className:`input`,placeholder:`codex-work, codex-alt, team...`,value:d,onChange:e=>f(e.target.value),style:{marginBottom:12}}),(0,S.jsx)(`button`,{className:`list-row`,onClick:async()=>{m(``);try{let l=d.trim(),f=await fetch(`${e}/api/codex-auth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(l?{id:l}:{})}),p=await f.json();if(f.status===409){m(r(`codexAuth.oauthAlreadyInProgress`));return}if(p.url){s.current=p.flowId??null,g(p.url),c.current=window.open(p.url,`_blank`),c.current&&(c.current.opener=null),u(`oauth-waiting`),b();let d=p.flowId??``,f=d?`${e}/api/codex-auth/login-status?flowId=${encodeURIComponent(d)}${l?`&accountId=${encodeURIComponent(l)}`:``}`:`${e}/api/codex-auth/login-status`;a.current=setInterval(async()=>{try{let e=await fetch(f).then(e=>e.json());e.status===`done`?(b(),s.current=null,c.current=null,n(),t()):e.status===`error`||e.status===`expired`?(b(),s.current=null,c.current=null,i.current&&(u(`pick`),m(e.error??`Login failed`))):c.current?.closed&&(await x(),i.current&&(u(`pick`),m(r(`codexAuth.oauthCancelled`))))}catch{}},2e3),o.current=setTimeout(()=>{a.current&&(x(),i.current&&(u(`pick`),m(r(`modal.loginTimeout`))))},3e5)}p.error&&!p.url&&m(p.error)}catch(e){m(String(e))}},style:{marginBottom:8},children:(0,S.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,S.jsx)(me,{width:20}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`title`,children:r(`codexAuth.oauthLogin`)}),(0,S.jsx)(`div`,{className:`sub`,children:r(`codexAuth.oauthDesc`)})]})]})}),p&&(0,S.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:p}),(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:C,style:{width:`100%`},children:r(`codexAuth.cancel`)})]}),l===`oauth-waiting`&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`h3`,{style:{marginBottom:4},children:r(`codexAuth.oauthLogin`)}),(0,S.jsx)(`p`,{className:`modal-desc`,children:r(`codexAuth.oauthWaiting`)}),(0,S.jsxs)(`button`,{className:`btn btn-ghost`,onClick:async()=>{if(h)try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(h);else{let e=document.createElement(`textarea`);e.value=h,e.style.position=`fixed`,e.style.opacity=`0`,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e)}y(!0),setTimeout(()=>{i.current&&y(!1)},2500)}catch{m(r(`codexAuth.loginLinkCopyFailed`))}},disabled:!h,style:{width:`100%`,justifyContent:`center`,marginTop:12},children:[(0,S.jsx)(L,{width:14}),` `,r(v?`codexAuth.loginLinkCopied`:`codexAuth.copyLoginLink`)]}),p&&(0,S.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:p}),(0,S.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,S.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:C,style:{width:`100%`},children:r(`codexAuth.cancel`)})]})]})})}function on({apiBase:e}){let t=we(),[n,r]=(0,_.useState)([]),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(80),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(``),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(!1),[x,C]=(0,_.useState)(!1),[w,T]=(0,_.useState)(null),[ee,te]=(0,_.useState)(!1),E=(0,_.useCallback)(async(t=!1)=>{try{let[n,i]=await Promise.all([fetch(`${e}/api/codex-auth/accounts${t?`?refresh=1`:``}`).then(e=>e.json()),fetch(`${e}/api/codex-auth/active`).then(e=>e.json())]);return r(n.accounts??[]),a(i.activeCodexAccountId??null),s(i.autoSwitchThreshold??80),!0}catch{return!1}},[e]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{E()},0),t=window.setInterval(()=>{E()},3e4);return()=>{window.clearTimeout(e),window.clearInterval(t)}},[E]);let ne=async r=>{await fetch(`${e}/api/codex-auth/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:r})}),a(r),l(null),p(t(`codexAuth.switched`,{email:r&&r!==`__main__`?n.find(e=>e.id===r)?.email??r:`main`})),setTimeout(()=>p(``),5e3)},re=async n=>{window.confirm(t(`codexAuth.removeConfirm`,{id:n}))&&(await fetch(`${e}/api/codex-auth/accounts?id=${n}`,{method:`DELETE`}),E())},D=async()=>{let t=o>0?0:80;await fetch(`${e}/api/codex-auth/auto-switch`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({threshold:t})}),s(t)},O=async()=>{h(!0);try{p(t(await E(!0)?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`)),setTimeout(()=>p(``),5e3)}finally{h(!1)}},A=async t=>{v(t),b(!1),T(null),te(!0);try{let n=await fetch(`${e}/api/codex-auth/reset-credits?accountId=${encodeURIComponent(t.id)}`);n.ok&&T(((await n.json()).credits??[]).sort((e,t)=>new Date(e.granted_at).getTime()-new Date(t.granted_at).getTime()))}catch{}finally{te(!1)}},oe=async n=>{C(!0);try{let r=await fetch(`${e}/api/codex-auth/reset-credits/consume`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:n})});if(!r.ok){alert(t(`codexAuth.resetError`));return}let i=await r.json();if(i.code===`reset`||i.code===`already_redeemed`){let e=g?.quota?.resetCredits??1;v(null),b(!1),await E(!0),p(t(`codexAuth.resetSuccess`,{remaining:String(Math.max(0,e-1))})),setTimeout(()=>p(``),5e3)}else i.code===`nothing_to_reset`?alert(t(`codexAuth.resetNothingToReset`)):i.code===`no_credit`?alert(t(`codexAuth.resetNoCredit`)):alert(t(`codexAuth.resetError`))}catch{alert(t(`codexAuth.resetError`))}finally{C(!1)}},M=n.find(e=>e.isMain),se=n.filter(e=>!e.isMain),N=e=>i===e,P=!i||i===`__main__`;return(0,S.jsxs)(`div`,{children:[(0,S.jsxs)(`div`,{className:`page-head`,children:[(0,S.jsx)(`h2`,{className:`page-title`,children:t(`nav.codexAuth`)}),(0,S.jsxs)(`button`,{className:`btn btn-sm btn-ghost`,onClick:O,disabled:m,children:[(0,S.jsx)(k,{width:14}),` `,t(m?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]}),f&&(0,S.jsx)(je,{tone:`ok`,children:f}),(0,S.jsxs)(`div`,{className:`card ${P?`card-active`:``}`,onClick:()=>P?void 0:l({id:`__main__`,email:M?.email??`Codex App`,plan:M?.plan,isMain:!0,hasCredential:!0,quota:M?.quota??null}),style:{cursor:P?`default`:`pointer`,marginBottom:12},children:[(0,S.jsxs)(`div`,{className:`card-head`,children:[(0,S.jsx)(`span`,{className:`dot dot-green`}),(0,S.jsx)(`strong`,{children:t(`codexAuth.mainAccount`)}),(0,S.jsxs)(`span`,{className:`card-badges`,children:[M&&(0,S.jsx)(un,{account:{...M,id:`__main__`},onClick:()=>A({...M,id:`__main__`})}),(0,S.jsx)(`span`,{className:`badge ${P?`badge-primary`:`badge-muted`}`,children:t(P?`codexAuth.nextSession`:`codexAuth.current`)})]}),(0,S.jsxs)(`span`,{className:`card-right`,children:[(0,S.jsx)(ue,{width:14}),` `,t(`codexAuth.appLogin`)]})]}),(0,S.jsxs)(`div`,{className:`card-sub`,children:[M?.email??`Codex App login`,M?.plan?` · ${M.plan}`:``]}),M?.quota&&(0,S.jsx)(Ke,{quota:M.quota,plan:M.plan,threshold:o,t})]}),(0,S.jsxs)(`div`,{className:`section-sep`,children:[(0,S.jsx)(`span`,{className:`section-label`,children:t(`codexAuth.accountPool`)}),(0,S.jsx)(`div`,{className:`sep-line`}),(0,S.jsxs)(`button`,{className:`btn btn-sm btn-ghost`,onClick:()=>d(!0),children:[(0,S.jsx)(ae,{width:14}),` `,t(`codexAuth.add`)]})]}),se.length===0&&(0,S.jsx)(Ne,{title:t(`codexAuth.noPool`)}),se.map(e=>(0,S.jsxs)(`div`,{className:`card ${N(e.id)?`card-active`:``}`,onClick:()=>!e.needsReauth&&l(e),style:{cursor:e.needsReauth?`default`:`pointer`,marginBottom:8},children:[(0,S.jsxs)(`div`,{className:`card-head`,children:[(0,S.jsx)(`span`,{className:`dot ${e.needsReauth?`dot-amber`:N(e.id)?`dot-blue`:`dot-muted`}`}),(0,S.jsx)(`strong`,{children:e.email}),(0,S.jsxs)(`span`,{className:`card-badges`,children:[e.plan&&(0,S.jsx)(`span`,{className:`badge badge-green`,children:e.plan}),(0,S.jsx)(un,{account:e,onClick:()=>A(e)}),e.needsReauth&&(0,S.jsx)(`span`,{className:`badge badge-amber`,children:t(`codexAuth.needsReauth`)}),N(e.id)&&!e.needsReauth&&(0,S.jsx)(`span`,{className:`badge badge-primary`,children:t(`codexAuth.nextSession`)})]}),(0,S.jsx)(`button`,{className:`btn-icon btn-icon-danger card-right`,"aria-label":t(`common.remove`),onClick:t=>{t.stopPropagation(),re(e.id)},children:(0,S.jsx)(ie,{width:14})})]}),e.needsReauth?(0,S.jsx)(`div`,{className:`card-sub faint`,children:t(`codexAuth.tokenExpired`)}):(0,S.jsx)(Ke,{quota:e.quota,plan:e.plan,threshold:o,t})]},e.id)),(0,S.jsxs)(`div`,{className:`card card-row`,style:{marginTop:16},children:[(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`strong`,{children:t(`codexAuth.autoSwitch`)}),(0,S.jsx)(`div`,{className:`card-sub`,children:t(`codexAuth.autoSwitchDesc`)})]}),(0,S.jsx)(`button`,{className:`toggle ${o>0?`on`:``}`,onClick:D,"aria-pressed":o>0,"aria-label":t(`codexAuth.autoSwitch`),title:t(`codexAuth.autoSwitch`),children:(0,S.jsx)(`span`,{className:`toggle-knob`})})]}),c&&(0,S.jsx)(`div`,{className:`modal-overlay`,onClick:()=>l(null),children:(0,S.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,S.jsx)(`h3`,{children:c.id===`__main__`?t(`codexAuth.switchBack`):t(`codexAuth.switchTitle`)}),(0,S.jsx)(`p`,{className:`modal-desc`,children:c.id===`__main__`?t(`codexAuth.switchBackDesc`):t(`codexAuth.switchDesc`)}),(0,S.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,S.jsx)(`strong`,{children:c.id===`__main__`?M?.email:c.email}),c.plan&&(0,S.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:c.plan})]}),c.id!==`__main__`&&(0,S.jsxs)(`div`,{className:`notice-warn`,children:[(0,S.jsx)(j,{width:14}),` `,t(`codexAuth.cacheWarning`)]}),(0,S.jsxs)(`div`,{className:`modal-actions`,children:[(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>l(null),children:t(`codexAuth.cancel`)}),(0,S.jsx)(`button`,{className:`btn btn-primary`,onClick:()=>ne(c.id===`__main__`?`__main__`:c.id),children:t(`codexAuth.setAsNext`)})]})]})}),g&&(0,S.jsx)(`div`,{className:`modal-overlay`,onClick:()=>{v(null),b(!1),T(null)},children:(0,S.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:y?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,S.jsx)(`div`,{className:`confirm-icon`,children:(0,S.jsx)(j,{width:22})}),(0,S.jsx)(`h3`,{children:t(`codexAuth.confirmResetTitle`)}),(0,S.jsx)(`p`,{className:`modal-desc`,children:t(`codexAuth.confirmResetDesc`,{count:String(g.quota?.resetCredits??0)})}),w&&w[0]&&(0,S.jsx)(`p`,{className:`faint text-label`,children:t(`codexAuth.confirmWhichCredit`,{date:sn(w[0].granted_at)})}),(0,S.jsx)(`p`,{className:`faint text-label`,children:t(`codexAuth.irreversible`)})]}),(0,S.jsxs)(`div`,{className:`modal-actions`,children:[(0,S.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>b(!1),children:t(`codexAuth.cancel`)}),(0,S.jsx)(`button`,{className:`btn btn-primary`,onClick:()=>oe(g.id),disabled:x,children:t(x?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`h3`,{children:[(0,S.jsx)(de,{width:16}),` `,t(`codexAuth.resetCreditsTitle`)]}),(0,S.jsxs)(`div`,{className:`card-sub`,children:[g.email,g.plan?` · ${g.plan}`:``]}),(0,S.jsx)(`div`,{style:{margin:`16px 0`},children:(g.quota?.resetCredits??0)>0?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`p`,{style:{marginBottom:12},children:t(`codexAuth.resetCreditsAvailable`,{count:String(g.quota?.resetCredits??0)})}),ee&&(0,S.jsx)(`p`,{className:`faint text-label`,children:`Loading...`}),w&&w.length>0&&(0,S.jsx)(`div`,{className:`credit-list`,children:w.map((e,n)=>(0,S.jsx)(ln,{index:n,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:n===0,t},n))}),(0,S.jsx)(`button`,{className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:()=>b(!0),disabled:x,children:t(`codexAuth.useOneCredit`)}),(0,S.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:t(`codexAuth.fifoNote`)})]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`p`,{className:`faint`,children:t(`codexAuth.noResetCredits`)}),(0,S.jsx)(`p`,{className:`modal-desc`,children:t(`codexAuth.earnCreditsHint`)})]})})]})})}),u&&(0,S.jsx)(an,{apiBase:e,onClose:()=>d(!1),onAdded:()=>{E(),p(t(`codexAuth.accountAdded`)),setTimeout(()=>p(``),5e3)}})]})}function sn(e){let t=new Date(e);return new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`}).format(t)}function cn(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function ln({index:e,grantedAt:t,expiresAt:n,isNext:r,t:i}){let a=cn(n),o=a<=7;return(0,S.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,S.jsxs)(`div`,{className:`credit-item-head`,children:[(0,S.jsx)(de,{width:13}),(0,S.jsx)(`span`,{className:`credit-item-label`,children:r?i(`codexAuth.creditNext`):i(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,S.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:i(`codexAuth.creditNextBadge`)})]}),(0,S.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,S.jsx)(`span`,{children:i(`codexAuth.creditGranted`,{date:sn(t)})}),(0,S.jsx)(`span`,{className:o?`credit-urgent`:``,children:i(`codexAuth.creditExpires`,{date:sn(n),days:String(a)})})]})]})}function un({account:e,onClick:t}){let n=e.quota?.resetCredits;return n===void 0?null:(0,S.jsxs)(`button`,{type:`button`,className:`badge ${typeof n==`number`&&n>0?`badge-amber`:`badge-muted`} badge-clickable`,onClick:e=>{e.stopPropagation(),t()},"aria-label":`${n} reset credit(s)`,children:[(0,S.jsx)(de,{width:12}),n]})}function dn({apiBase:e}){let{t,locale:n}=Ce(),r=ve.find(e=>e.code===n)?.htmlLang,[i,a]=(0,_.useState)([]),[o,s]=(0,_.useState)(``),[c,l]=(0,_.useState)(``),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(null),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)(null),y=(0,_.useCallback)(async()=>{try{let t=await fetch(`${e}/api/keys`);if(t.ok){let e=await t.json();a(e.keys??[]),s(e.endpoint??``)}}catch{}},[e]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{y()},0);return()=>window.clearTimeout(e)},[y]);let b=o||`http://127.0.0.1:10100/v1/responses`,x=async()=>{d(!0);try{let t=await fetch(`${e}/api/keys`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:c||`default`})});t.ok&&(p((await t.json()).key),l(``),y())}finally{d(!1)}},C=async t=>{await fetch(`${e}/api/keys`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t})}),v(null),y()},w=()=>{f&&(navigator.clipboard.writeText(f),h(!0),setTimeout(()=>h(!1),2e3))},T=t(`api.subtitle`).split(/\{authHeader\}|\{altHeader\}/);return(0,S.jsxs)(`section`,{className:`api-page`,children:[(0,S.jsx)(`div`,{className:`page-head`,children:(0,S.jsx)(`h2`,{children:t(`api.title`)})}),(0,S.jsxs)(`p`,{className:`page-sub`,children:[T[0],(0,S.jsx)(`code`,{children:`Authorization: Bearer ocx_...`}),T[1],(0,S.jsx)(`code`,{children:`x-opencodex-api-key`}),T[2]]}),(0,S.jsxs)(`div`,{className:`panel api-panel`,children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`api.endpoint`)}),(0,S.jsx)(`code`,{className:`api-code api-code-inline`,children:b}),(0,S.jsx)(`p`,{className:`muted small`,children:t(`api.endpointNote`)})]}),f&&(0,S.jsxs)(`div`,{className:`panel api-panel panel-accent`,style:{marginTop:`1rem`},children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`api.newKeyTitle`)}),(0,S.jsx)(`p`,{className:`muted small`,children:t(`api.newKeyNote`)}),(0,S.jsxs)(`div`,{className:`api-form-row`,children:[(0,S.jsx)(`code`,{className:`api-code`,style:{flex:1,wordBreak:`break-all`},children:f}),(0,S.jsx)(`button`,{className:`btn btn-sm btn-ghost`,onClick:w,children:m?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(O,{}),` `,t(`api.copied`)]}):t(`api.copy`)})]}),(0,S.jsx)(`button`,{className:`btn btn-sm btn-ghost`,style:{alignSelf:`flex-start`},onClick:()=>p(null),children:t(`api.dismiss`)})]}),(0,S.jsxs)(`div`,{className:`panel api-panel`,style:{marginTop:`1rem`},children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`api.generateTitle`)}),(0,S.jsxs)(`div`,{className:`api-form-row`,children:[(0,S.jsx)(`input`,{type:`text`,placeholder:t(`api.keyNamePlaceholder`),value:c,onChange:e=>l(e.target.value),className:`input`}),(0,S.jsxs)(`button`,{className:`btn btn-primary`,onClick:x,disabled:u,children:[(0,S.jsx)(ae,{}),` `,t(u?`api.generating`:`api.generate`)]})]})]}),(0,S.jsxs)(`div`,{className:`panel api-panel`,style:{marginTop:`1rem`},children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`api.activeKeys`,{count:i.length})}),i.length===0?(0,S.jsx)(`p`,{className:`muted`,children:t(`api.noKeys`)}):(0,S.jsx)(`div`,{className:`tbl-wrap`,children:(0,S.jsxs)(`table`,{className:`tbl`,children:[(0,S.jsx)(`thead`,{children:(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`th`,{children:t(`api.colName`)}),(0,S.jsx)(`th`,{children:t(`api.colKey`)}),(0,S.jsx)(`th`,{children:t(`api.colCreated`)}),(0,S.jsx)(`th`,{})]})}),(0,S.jsx)(`tbody`,{children:i.map(e=>(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`td`,{children:e.name}),(0,S.jsx)(`td`,{children:(0,S.jsx)(`code`,{children:e.prefix})}),(0,S.jsx)(`td`,{children:new Date(e.createdAt).toLocaleDateString(r)}),(0,S.jsx)(`td`,{children:g===e.id?(0,S.jsxs)(`span`,{className:`api-actions`,children:[(0,S.jsx)(`button`,{className:`btn btn-sm btn-danger`,onClick:()=>C(e.id),children:t(`api.confirm`)}),(0,S.jsx)(`button`,{className:`btn btn-sm btn-ghost`,onClick:()=>v(null),children:t(`common.cancel`)})]}):(0,S.jsx)(`button`,{className:`btn btn-sm btn-ghost`,"aria-label":t(`api.deleteAria`),onClick:()=>v(e.id),children:(0,S.jsx)(ie,{})})})]},e.id))})]})})]}),(0,S.jsxs)(`div`,{className:`panel api-panel`,style:{marginTop:`1rem`},children:[(0,S.jsx)(`h3`,{className:`panel-title`,children:t(`api.usageTitle`)}),(0,S.jsx)(`pre`,{className:`api-code`,children:`curl ${b} \\
|
|
34
34
|
-H "Authorization: Bearer ocx_YOUR_KEY_HERE" \\
|
|
35
35
|
-H "Content-Type: application/json" \\
|
|
36
36
|
-d '{
|
|
37
37
|
"model": "gpt-5.4",
|
|
38
38
|
"input": "Hello, world!"
|
|
39
39
|
}'`})]})]})}function fn({apiBase:e}){let t=we(),[n,r]=(0,_.useState)(null),[i,a]=(0,_.useState)([]),[o,s]=(0,_.useState)(``),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(!0),f=(0,_.useCallback)(async()=>{try{let t=await fetch(`${e}/api/claude-code`).then(e=>e.json());r({...t,authMode:t.authMode===`proxy`?`proxy`:`subscription`,systemEnv:t.systemEnv!==!1,fastMode:t.fastMode??null,maxContextTokens:t.maxContextTokens??null,autoContext:t.autoContext!==!1,autoCompactWindow:t.autoCompactWindow??null,injectAgents:t.injectAgents!==!1,effectiveModelEnv:t.effectiveModelEnv??{}}),a(Object.entries(t.modelMap??{}).map(([e,t])=>({from:e,to:String(t)})))}catch{l(!1),s(t(`claude.loadFail`))}finally{d(!1)}},[e,t]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{f()},0);return()=>window.clearTimeout(e)},[f]);let p=(0,_.useMemo)(()=>{let e=(n?.available??[]).map(e=>({value:e,label:z(e)}));return[{value:``,label:t(`claude.slotUnset`)},...e]},[n?.available,t]),m=(0,_.useMemo)(()=>{let e=[1e5,2e5,25e4,3e5,35e4,4e5,5e5,6e5,75e4,9e5,1e6],r=e=>e>=1e6?`1M`:`${Math.round(e/1e3)}k`,i=n?.autoCompactWindow??null,a=i!==null&&!e.includes(i)?[...e,i].sort((e,t)=>e-t):e;return[{value:``,label:t(`claude.autoCompactDefault`)},...a.map(e=>({value:String(e),label:r(e)}))]},[n?.autoCompactWindow,t]),h=async()=>{if(!n)return;s(``);let r={};for(let e of i)e.from.trim()&&e.to.trim()&&(r[e.from.trim()]=e.to.trim());try{let i=await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:n.enabled,authMode:n.authMode,systemEnv:n.systemEnv,fastMode:n.fastMode,autoContext:n.autoContext,autoCompactWindow:n.autoCompactWindow,injectAgents:n.injectAgents,smallFastModel:n.smallFastModel,modelMap:r,webSearchSidecar:n.webSearchSidecar?{backend:n.webSearchSidecar.backend??null,model:n.webSearchSidecar.model??``}:null,visionSidecar:n.visionSidecar?{backend:n.visionSidecar.backend??null,model:n.visionSidecar.model??``}:null})}),a=await i.json();l(i.ok),s(i.ok?t(`claude.saved`):a.error||t(`claude.saveFailed`)),i.ok&&await f()}catch{l(!1),s(t(`claude.networkError`))}};if(u)return(0,S.jsx)(`div`,{className:`muted`,style:{padding:8},children:t(`claude.loading`)});if(!n)return(0,S.jsx)(je,{tone:`err`,children:o||t(`claude.loadFail`)});let g=`http://127.0.0.1:${n.port}`,v=n.effectiveModelEnv,y=n.autoContext&&n.maxContextTokens===null,b=[`export ANTHROPIC_BASE_URL=${g}`,...n.authMode===`proxy`?[`export ANTHROPIC_AUTH_TOKEN=opencodex-proxy`]:[`# no ANTHROPIC_AUTH_TOKEN: your claude.ai login (and connectors) stay active`],`export CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`,...y?[`export CLAUDE_CODE_AUTO_COMPACT_WINDOW=${n.autoCompactWindow??35e4}`]:[],...[`ANTHROPIC_MODEL`,`ANTHROPIC_DEFAULT_OPUS_MODEL`,`ANTHROPIC_DEFAULT_SONNET_MODEL`,`ANTHROPIC_DEFAULT_HAIKU_MODEL`,`ANTHROPIC_DEFAULT_FABLE_MODEL`].filter(e=>v[e]).map(e=>`export ${e}=${v[e]}`),`claude`].join(`
|
|
40
|
-
`);return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`page-head`,children:(0,S.jsxs)(`h2`,{children:[t(`nav.claude`),` Code`]})}),(0,S.jsx)(`p`,{className:`page-sub`,children:t(`claude.subtitle`)}),o&&(0,S.jsx)(je,{tone:c?`ok`:`err`,children:o}),(0,S.jsxs)(`div`,{className:`card`,style:{overflow:`hidden`},children:[(0,S.jsxs)(`div`,{className:`setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-label`,children:[(0,S.jsx)(`span`,{className:`title`,children:t(`claude.enabledLabel`)}),(0,S.jsx)(`span`,{className:`desc`,children:t(`claude.enabledHint`)})]}),(0,S.jsxs)(`label`,{className:`toggle`,children:[(0,S.jsx)(`input`,{type:`checkbox`,checked:n.enabled,onChange:e=>r({...n,enabled:e.target.checked})}),(0,S.jsx)(`span`,{className:`slider`})]})]}),(0,S.jsxs)(`div`,{className:`setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-label`,children:[(0,S.jsx)(`span`,{className:`title`,children:t(`claude.authMode`)}),(0,S.jsx)(`span`,{className:`desc`,children:t(`claude.authModeHint`)})]}),(0,S.jsx)(Me,{value:n.authMode,options:[{value:`subscription`,label:t(`claude.authModeSubscription`)},{value:`proxy`,label:t(`claude.authModeProxy`)}],onChange:e=>r({...n,authMode:e}),label:t(`claude.authMode`),style:{minWidth:220}})]}),(0,S.jsxs)(`div`,{className:`setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-label`,children:[(0,S.jsx)(`span`,{className:`title`,children:t(`claude.systemEnv`)}),(0,S.jsx)(`span`,{className:`desc`,children:t(`claude.systemEnvDesc`)}),n.systemEnv&&(0,S.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:t(`claude.systemEnvWarn`)})]}),(0,S.jsxs)(`label`,{className:`toggle`,children:[(0,S.jsx)(`input`,{type:`checkbox`,checked:n.systemEnv,onChange:e=>r({...n,systemEnv:e.target.checked})}),(0,S.jsx)(`span`,{className:`slider`})]})]}),(0,S.jsxs)(`div`,{className:`setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-label`,children:[(0,S.jsx)(`span`,{className:`title`,children:t(`claude.fastMode`)}),(0,S.jsx)(`span`,{className:`desc`,children:t(`claude.fastModeDesc`)})]}),(0,S.jsxs)(`select`,{value:n.fastMode===null?`auto`:n.fastMode?`on`:`off`,onChange:e=>{let t=e.target.value;r({...n,fastMode:t===`auto`?null:t===`on`})},style:{padding:`5px 10px`,borderRadius:`var(--radius-xs)`,border:`1px solid var(--border)`,background:`var(--surface)`,color:`var(--text)`,fontSize:12.5,fontWeight:500},children:[(0,S.jsx)(`option`,{value:`auto`,children:t(`claude.fastAuto`)}),(0,S.jsx)(`option`,{value:`on`,children:t(`claude.fastOn`)}),(0,S.jsx)(`option`,{value:`off`,children:t(`claude.fastOff`)})]})]}),(0,S.jsxs)(`div`,{className:`setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-label`,children:[(0,S.jsx)(`span`,{className:`title`,children:t(`claude.autoContext`)}),(0,S.jsx)(`span`,{className:`desc`,children:t(`claude.autoContextDesc`)}),n.maxContextTokens!==null&&(0,S.jsx)(`span`,{className:`desc`,style:{color:`var(--muted)`},children:t(`claude.autoContextInert`)})]}),(0,S.jsxs)(`label`,{className:`toggle`,children:[(0,S.jsx)(`input`,{type:`checkbox`,checked:n.autoContext,onChange:e=>r({...n,autoContext:e.target.checked})}),(0,S.jsx)(`span`,{className:`slider`})]})]}),n.autoContext&&(0,S.jsxs)(`div`,{className:`setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-label`,children:[(0,S.jsx)(`span`,{className:`title`,children:t(`claude.autoCompactWindow`)}),(0,S.jsx)(`span`,{className:`desc`,children:t(`claude.autoCompactWindowDesc`)}),n.autoCompactWindow!==null&&(0,S.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:t(`claude.autoCompactWindowWarn`)})]}),(0,S.jsx)(Me,{value:n.autoCompactWindow===null?``:String(n.autoCompactWindow),options:m,onChange:e=>r({...n,autoCompactWindow:e===``?null:Number(e)}),label:t(`claude.autoCompactWindow`),style:{minWidth:130}})]}),(0,S.jsxs)(`div`,{className:`setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-label`,children:[(0,S.jsx)(`span`,{className:`title`,children:t(`claude.injectAgents`)}),(0,S.jsx)(`span`,{className:`desc`,children:t(`claude.injectAgentsDesc`)})]}),(0,S.jsxs)(`label`,{className:`toggle`,children:[(0,S.jsx)(`input`,{type:`checkbox`,checked:n.injectAgents,onChange:e=>r({...n,injectAgents:e.target.checked})}),(0,S.jsx)(`span`,{className:`slider`})]})]}),[`webSearchSidecar`,`visionSidecar`].map(e=>{let i=n[e],a=e===`webSearchSidecar`?`claude.webSearchSidecar`:`claude.visionSidecar`,o=e===`webSearchSidecar`?`claude.webSearchSidecarHint`:`claude.visionSidecarHint`;return(0,S.jsxs)(`div`,{className:`setting-row`,style:{alignItems:`flex-start`},children:[(0,S.jsxs)(`div`,{className:`setting-label setting-copy`,style:{flex:1},children:[(0,S.jsx)(`span`,{className:`title`,children:t(a)}),(0,S.jsx)(`span`,{className:`desc`,children:t(o)})]}),(0,S.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8},children:[(0,S.jsx)(Me,{value:i?i.backend??`auto`:`inherit`,options:[{value:`inherit`,label:t(`claude.useMainSetting`)},{value:`auto`,label:t(`dash.backendAuto`)},{value:`openai`,label:t(`dash.backendOpenAI`)},{value:`anthropic`,label:t(`dash.backendAnthropic`)}],onChange:t=>r({...n,[e]:t===`inherit`?void 0:{...i,backend:t===`auto`?void 0:t}}),label:t(`dash.sidecarBackend`)}),(0,S.jsx)(`input`,{className:`input mono`,value:i?.model??``,onChange:t=>r({...n,[e]:{...i,model:t.target.value}}),placeholder:t(`claude.sidecarModelPlaceholder`),disabled:!i,"aria-label":t(`dash.sidecarModel`),style:{minWidth:210}})]})]},e)})]}),(0,S.jsx)(`div`,{className:`h-section`,children:t(`claude.quickstart`)}),(0,S.jsx)(`p`,{className:`muted`,style:{fontSize:12.5,margin:`0 0 8px`},children:(0,S.jsx)(Ee,{k:`claude.quickstartHint`,cmd:`ocx claude`})}),(0,S.jsx)(`pre`,{className:`mono card`,style:{padding:`10px 14px`,overflowX:`auto`,margin:0},children:`ocx claude`}),(0,S.jsxs)(`details`,{style:{margin:`10px 0 0`},children:[(0,S.jsx)(`summary`,{className:`muted`,style:{fontSize:12.5,cursor:`pointer`,padding:`2px 2px`},children:t(`claude.manualEnv`)}),(0,S.jsx)(`pre`,{className:`mono card`,style:{padding:`10px 14px`,overflowX:`auto`,margin:`6px 0 0`,fontSize:12},children:b})]}),(0,S.jsx)(`div`,{className:`h-section`,children:t(`claude.smallFastModel`)}),(0,S.jsx)(`p`,{className:`muted`,style:{fontSize:12.5,margin:`0 0 8px`},children:t(`claude.smallFastModelHint`)}),(0,S.jsx)(Me,{value:n.smallFastModel,options:p,onChange:e=>r({...n,smallFastModel:e}),label:t(`claude.smallFastModel`),style:{maxWidth:420}}),(0,S.jsxs)(`div`,{className:`h-section`,children:[t(`claude.modelMap`),` `,(0,S.jsx)(`span`,{className:`count`,children:i.length})]}),(0,S.jsx)(`p`,{className:`muted`,style:{fontSize:12.5,margin:`0 0 8px`},children:t(`claude.modelMapHint`)}),(0,S.jsx)(`div`,{className:`stack`,style:{gap:8},children:i.map((e,n)=>(0,S.jsxs)(`div`,{className:`row`,style:{gap:8},children:[(0,S.jsx)(`input`,{className:`input mono`,value:e.from,placeholder:t(`claude.mapFrom`),onChange:e=>a(t=>t.map((t,r)=>r===n?{...t,from:e.target.value}:t)),style:{flex:1}}),(0,S.jsx)(`span`,{className:`muted`,"aria-hidden":!0,children:`→`}),(0,S.jsx)(`input`,{className:`input mono`,value:e.to,placeholder:t(`claude.mapTo`),onChange:e=>a(t=>t.map((t,r)=>r===n?{...t,to:e.target.value}:t)),style:{flex:1}}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>a(e=>e.filter((e,t)=>t!==n)),"aria-label":t(`claude.removeMapping`),style:{color:`var(--red)`},children:(0,S.jsx)(ie,{})})]},n))}),(0,S.jsx)(`div`,{style:{marginTop:8},children:(0,S.jsxs)(`button`,{className:`btn btn-ghost btn-sm`,onClick:()=>a(e=>[...e,{from:``,to:``}]),children:[(0,S.jsx)(ae,{}),` `,t(`claude.addMapping`)]})}),(0,S.jsx)(`div`,{style:{marginTop:14},children:(0,S.jsx)(`button`,{className:`btn btn-primary`,onClick:h,children:t(`common.save`)})}),(0,S.jsxs)(`div`,{className:`h-section`,children:[t(`claude.aliases`),` `,(0,S.jsx)(`span`,{className:`count`,children:n.aliases.length})]}),(0,S.jsx)(`p`,{className:`muted`,style:{fontSize:12.5,margin:`0 0 8px`},children:t(`claude.aliasesHint`)}),n.aliases.length===0?(0,S.jsx)(`div`,{className:`muted`,style:{fontSize:12.5},children:t(`claude.none`)}):(0,S.jsx)(`div`,{className:`stack`,style:{gap:6,maxHeight:320,overflowY:`auto`},children:Array.from(n.aliases.reduce((e,t)=>{let n=/\(([^)]+)\)\s*$/.exec(t.display_name),r=n?n[1]:`etc`;return(e.get(r)??e.set(r,[]).get(r)).push(t),e},new Map)).map(([e,t])=>(0,S.jsxs)(`div`,{children:[(0,S.jsxs)(`div`,{className:`muted`,style:{fontSize:11.5,fontWeight:600,textTransform:`uppercase`,letterSpacing:0,margin:`6px 2px 4px`},children:[e,` · `,t.length]}),(0,S.jsx)(`div`,{className:`stack`,style:{gap:4},children:t.map(e=>(0,S.jsxs)(`div`,{className:`card row`,style:{padding:`6px 12px`,gap:10},children:[(0,S.jsx)(`code`,{className:`mono`,style:{flex:1,fontSize:12},children:e.id}),(0,S.jsx)(`span`,{className:`muted`,style:{fontSize:12},children:e.display_name})]},e.id))})]},e))})]})}var pn=`opencodex-api-token`,mn=!1,hn=null;function gn(e){try{let t=e instanceof Request?e.url:String(e);return new URL(t,window.location.href).pathname}catch{return null}}function _n(e){let t=gn(e);return!!t&&(t.startsWith(`/api/`)||t.startsWith(`/v1/`))}function vn(){try{return sessionStorage.getItem(pn)?.trim()||null}catch{return null}}function yn(e){try{sessionStorage.setItem(pn,e)}catch{}}function bn(){try{sessionStorage.removeItem(pn)}catch{}}function xn(e,t,n){let r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));return r.set(`X-OpenCodex-API-Key`,n),e instanceof Request?[new Request(e,{headers:r}),t?{...t,headers:r}:void 0]:[e,{...t,headers:r}]}async function Sn(){return hn||(hn=Promise.resolve().then(()=>window.prompt(`OpenCodex API token`)?.trim()||null).finally(()=>{hn=null}),hn)}function Cn(){if(mn)return;mn=!0;let e=window.fetch.bind(window);window.fetch=async(t,n)=>{if(!_n(t))return e(t,n);let r=vn(),[i,a]=r?xn(t,n,r):[t,n],o=await e(i,a);if(o.status!==401)return o;r&&bn();let s=await Sn();if(!s)return o;yn(s);let[c,l]=xn(t,n,s),u=await e(c,l);return u.status===401&&bn(),u}}Cn();var wn=new Set([`dashboard`,`providers`,`models`,`subagents`,`logs`,`debug`,`usage`,`codex-auth`,`api`,`claude`]);function Tn(){let e=location.hash.replace(/^#\/?/,``);return wn.has(e)?e:`dashboard`}var En=``,Dn=`ocx-theme`,On=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:w},{id:`providers`,tkey:`nav.providers`,Icon:T},{id:`models`,tkey:`nav.models`,Icon:ee},{id:`subagents`,tkey:`nav.subagents`,Icon:te},{id:`logs`,tkey:`nav.logs`,Icon:E},{id:`debug`,tkey:`nav.debug`,Icon:re},{id:`usage`,tkey:`nav.usage`,Icon:D},{id:`codex-auth`,tkey:`nav.codexAuth`,Icon:I},{id:`api`,tkey:`nav.api`,Icon:me},{id:`claude`,tkey:`nav.claude`,Icon:he}],kn={light:fe,dark:pe,system:R},An={light:`theme.light`,dark:`theme.dark`,system:`theme.system`};function jn(e){if(!e||typeof e!=`object`||!(`version`in e))return null;let t=e.version;return typeof t==`string`&&t.length>0?t:null}function Mn(){let e=localStorage.getItem(Dn);return e===`light`||e===`dark`?e:`system`}function Nn(){let[e,t]=(0,_.useState)(Tn),[n,r]=(0,_.useState)(Mn),[i,a]=(0,_.useState)(null),{locale:o,setLocale:s}=Ce(),c=we(),[l,u]=(0,_.useState)(!1),d=(0,_.useRef)(null),f=(0,_.useRef)(null),p=(0,_.useRef)(!1);(0,_.useEffect)(()=>{let e=()=>{t(Tn()),u(!1)};return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>{let t=`#${e}`;window.location.hash!==t&&(window.location.hash=e)},[e]),(0,_.useEffect)(()=>{let e=document.documentElement;n===`system`?(e.removeAttribute(`data-theme`),localStorage.removeItem(Dn)):(e.setAttribute(`data-theme`,n),localStorage.setItem(Dn,n))},[n]),(0,_.useEffect)(()=>{let e=!1,t=async()=>{try{let t=await fetch(`${En}/healthz`);if(!t.ok)return;let n=jn(await t.json());!e&&n&&a(n)}catch{}};t();let n=setInterval(t,3e4);return()=>{e=!0,clearInterval(n)}},[]);let m=()=>r(e=>e===`light`?`dark`:e===`dark`?`system`:`light`),h=kn[n],g=i??`2.7.19`,[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(null);(0,_.useEffect)(()=>{if(!l)return;let e=e=>{e.key===`Escape`&&u(!1)};window.addEventListener(`keydown`,e);let t=document.body.style.overflow;return document.body.style.overflow=`hidden`,()=>{window.removeEventListener(`keydown`,e),document.body.style.overflow=t}},[l]),(0,_.useEffect)(()=>{if(l){p.current=!0;let e=setTimeout(()=>f.current?.focus(),200);return()=>clearTimeout(e)}p.current&&(p.current=!1,d.current?.focus())},[l]),(0,_.useEffect)(()=>{let e=window.matchMedia(`(min-width: 761px)`),t=()=>{e.matches&&u(!1)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,_.useEffect)(()=>{let e=!1;return fetch(`${En}/api/claude-code`).then(e=>e.json()).then(t=>{!e&&typeof t.enabled==`boolean`&&x(t.enabled)}).catch(()=>{}),()=>{e=!0}},[]);let C=async()=>{if(b===null)return;let e=!b;x(e);try{(await fetch(`${En}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:e})})).ok||x(!e)}catch{x(!e)}},w=async()=>{if(confirm(c(`dash.stopConfirm`))){y(!0);try{await fetch(`${En}/api/stop`,{method:`POST`})}catch{}}},T=(0,S.jsxs)(`div`,{className:`brand`,children:[(0,S.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":`opencodex logo`}),(0,S.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,S.jsxs)(`span`,{className:`ver`,children:[`v`,g]})]});return(0,S.jsxs)(`div`,{className:`app`,children:[(0,S.jsxs)(`header`,{className:`mobile-topbar`,inert:l,children:[(0,S.jsx)(`button`,{ref:d,type:`button`,className:`menu-toggle`,onClick:()=>u(e=>!e),"aria-expanded":l,"aria-controls":`app-sidebar`,"aria-label":c(l?`nav.closeMenu`:`nav.openMenu`),title:c(l?`nav.closeMenu`:`nav.openMenu`),children:(0,S.jsx)(ne,{})}),T,(0,S.jsx)(`button`,{type:`button`,className:`theme-toggle stop-toggle`,onClick:w,disabled:v,"aria-label":c(`dash.stop`),title:c(`dash.stop`),children:(0,S.jsx)(ce,{})})]}),l&&(0,S.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>u(!1),"aria-hidden":`true`}),(0,S.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${l?` open`:``}`,ref:f,tabIndex:-1,children:[(0,S.jsxs)(`div`,{className:`drawer-head`,children:[T,(0,S.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>u(!1),"aria-label":c(`nav.closeMenu`),title:c(`nav.closeMenu`),children:(0,S.jsx)(ie,{})})]}),(0,S.jsx)(`nav`,{children:On.map(({id:n,tkey:r,Icon:i})=>(0,S.jsxs)(`button`,{className:`nav-item${e===n?` active`:``}`,"data-page":n,onClick:()=>{t(n),u(!1)},"aria-current":e===n?`page`:void 0,children:[(0,S.jsx)(i,{}),` `,c(r)]},n))}),(0,S.jsxs)(`div`,{className:`sidebar-foot`,children:[b!==null&&(0,S.jsxs)(`button`,{type:`button`,className:`theme-toggle`,onClick:C,"aria-pressed":b,"aria-label":c(`claude.toggleAria`),title:c(`claude.toggleAria`),style:b?{color:`var(--accent)`}:void 0,children:[(0,S.jsx)(he,{}),` `,(0,S.jsx)(`span`,{className:`mode`,children:b?`Claude ON`:`Claude OFF`})]}),(0,S.jsxs)(`div`,{className:`lang-toggle`,children:[(0,S.jsx)(me,{"aria-hidden":!0}),(0,S.jsx)(Me,{value:o,options:ve.map(e=>({value:e.code,label:e.name})),onChange:e=>s(e),label:c(`lang.label`),placement:`right`,style:{flex:1,minWidth:0,width:`100%`}})]}),(0,S.jsxs)(`button`,{type:`button`,className:`theme-toggle`,onClick:m,"aria-label":`${c(`theme.label`)}: ${c(An[n])}`,title:`${c(`theme.label`)}: ${c(An[n])}`,children:[(0,S.jsx)(h,{}),` `,(0,S.jsx)(`span`,{className:`mode`,children:c(An[n])})]}),(0,S.jsxs)(`button`,{type:`button`,className:`theme-toggle stop-toggle`,onClick:w,disabled:v,"aria-label":c(`dash.stop`),title:c(`dash.stop`),children:[(0,S.jsx)(ce,{}),` `,(0,S.jsx)(`span`,{className:`mode`,children:c(v?`dash.stopping`:`dash.stop`)})]}),(0,S.jsxs)(`a`,{className:`sidebar-link`,href:`https://github.com/lidge-jun/opencodex`,target:`_blank`,rel:`noreferrer`,children:[(0,S.jsx)(F,{}),` `,c(`common.github`)]})]})]}),(0,S.jsx)(`main`,{className:`main`,inert:l,children:(0,S.jsxs)(`div`,{className:`main-inner`,children:[e===`dashboard`&&(0,S.jsx)(ze,{apiBase:En}),e===`providers`&&(0,S.jsx)(tt,{apiBase:En}),e===`models`&&(0,S.jsx)(dt,{apiBase:En}),e===`subagents`&&(0,S.jsx)(ft,{apiBase:En}),e===`logs`&&(0,S.jsx)(qt,{apiBase:En}),e===`debug`&&(0,S.jsx)(Xt,{apiBase:En}),e===`usage`&&(0,S.jsx)(rn,{apiBase:En}),e===`codex-auth`&&(0,S.jsx)(on,{apiBase:En}),e===`api`&&(0,S.jsx)(dn,{apiBase:En}),e===`claude`&&(0,S.jsx)(fn,{apiBase:En})]})})]})}v.createRoot(document.getElementById(`root`)).render((0,S.jsx)(_.StrictMode,{children:(0,S.jsx)(Te,{children:(0,S.jsx)(Nn,{})})}));
|
|
40
|
+
`);return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`page-head`,children:(0,S.jsxs)(`h2`,{children:[t(`nav.claude`),` Code`]})}),(0,S.jsx)(`p`,{className:`page-sub`,children:t(`claude.subtitle`)}),o&&(0,S.jsx)(je,{tone:c?`ok`:`err`,children:o}),(0,S.jsxs)(`div`,{className:`card`,style:{overflow:`hidden`},children:[(0,S.jsxs)(`div`,{className:`setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-label`,children:[(0,S.jsx)(`span`,{className:`title`,children:t(`claude.enabledLabel`)}),(0,S.jsx)(`span`,{className:`desc`,children:t(`claude.enabledHint`)})]}),(0,S.jsxs)(`label`,{className:`toggle`,children:[(0,S.jsx)(`input`,{type:`checkbox`,checked:n.enabled,onChange:e=>r({...n,enabled:e.target.checked})}),(0,S.jsx)(`span`,{className:`slider`})]})]}),(0,S.jsxs)(`div`,{className:`setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-label`,children:[(0,S.jsx)(`span`,{className:`title`,children:t(`claude.authMode`)}),(0,S.jsx)(`span`,{className:`desc`,children:t(`claude.authModeHint`)})]}),(0,S.jsx)(Me,{value:n.authMode,options:[{value:`subscription`,label:t(`claude.authModeSubscription`)},{value:`proxy`,label:t(`claude.authModeProxy`)}],onChange:e=>r({...n,authMode:e}),label:t(`claude.authMode`),style:{minWidth:220}})]}),(0,S.jsxs)(`div`,{className:`setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-label`,children:[(0,S.jsx)(`span`,{className:`title`,children:t(`claude.systemEnv`)}),(0,S.jsx)(`span`,{className:`desc`,children:t(`claude.systemEnvDesc`)}),n.systemEnv&&(0,S.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:t(`claude.systemEnvWarn`)})]}),(0,S.jsxs)(`label`,{className:`toggle`,children:[(0,S.jsx)(`input`,{type:`checkbox`,checked:n.systemEnv,onChange:e=>r({...n,systemEnv:e.target.checked})}),(0,S.jsx)(`span`,{className:`slider`})]})]}),(0,S.jsxs)(`div`,{className:`setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-label`,children:[(0,S.jsx)(`span`,{className:`title`,children:t(`claude.fastMode`)}),(0,S.jsx)(`span`,{className:`desc`,children:t(`claude.fastModeDesc`)})]}),(0,S.jsxs)(`select`,{value:n.fastMode===null?`auto`:n.fastMode?`on`:`off`,onChange:e=>{let t=e.target.value;r({...n,fastMode:t===`auto`?null:t===`on`})},className:`text-label font-medium`,style:{padding:`5px 10px`,borderRadius:`var(--radius-xs)`,border:`1px solid var(--border)`,background:`var(--surface)`,color:`var(--text)`},children:[(0,S.jsx)(`option`,{value:`auto`,children:t(`claude.fastAuto`)}),(0,S.jsx)(`option`,{value:`on`,children:t(`claude.fastOn`)}),(0,S.jsx)(`option`,{value:`off`,children:t(`claude.fastOff`)})]})]}),(0,S.jsxs)(`div`,{className:`setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-label`,children:[(0,S.jsx)(`span`,{className:`title`,children:t(`claude.autoContext`)}),(0,S.jsx)(`span`,{className:`desc`,children:t(`claude.autoContextDesc`)}),n.maxContextTokens!==null&&(0,S.jsx)(`span`,{className:`desc`,style:{color:`var(--muted)`},children:t(`claude.autoContextInert`)})]}),(0,S.jsxs)(`label`,{className:`toggle`,children:[(0,S.jsx)(`input`,{type:`checkbox`,checked:n.autoContext,onChange:e=>r({...n,autoContext:e.target.checked})}),(0,S.jsx)(`span`,{className:`slider`})]})]}),n.autoContext&&(0,S.jsxs)(`div`,{className:`setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-label`,children:[(0,S.jsx)(`span`,{className:`title`,children:t(`claude.autoCompactWindow`)}),(0,S.jsx)(`span`,{className:`desc`,children:t(`claude.autoCompactWindowDesc`)}),n.autoCompactWindow!==null&&(0,S.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:t(`claude.autoCompactWindowWarn`)})]}),(0,S.jsx)(Me,{value:n.autoCompactWindow===null?``:String(n.autoCompactWindow),options:m,onChange:e=>r({...n,autoCompactWindow:e===``?null:Number(e)}),label:t(`claude.autoCompactWindow`),style:{minWidth:130}})]}),(0,S.jsxs)(`div`,{className:`setting-row`,children:[(0,S.jsxs)(`div`,{className:`setting-label`,children:[(0,S.jsx)(`span`,{className:`title`,children:t(`claude.injectAgents`)}),(0,S.jsx)(`span`,{className:`desc`,children:t(`claude.injectAgentsDesc`)})]}),(0,S.jsxs)(`label`,{className:`toggle`,children:[(0,S.jsx)(`input`,{type:`checkbox`,checked:n.injectAgents,onChange:e=>r({...n,injectAgents:e.target.checked})}),(0,S.jsx)(`span`,{className:`slider`})]})]}),[`webSearchSidecar`,`visionSidecar`].map(e=>{let i=n[e],a=e===`webSearchSidecar`?`claude.webSearchSidecar`:`claude.visionSidecar`,o=e===`webSearchSidecar`?`claude.webSearchSidecarHint`:`claude.visionSidecarHint`;return(0,S.jsxs)(`div`,{className:`setting-row`,style:{alignItems:`flex-start`},children:[(0,S.jsxs)(`div`,{className:`setting-label setting-copy`,style:{flex:1},children:[(0,S.jsx)(`span`,{className:`title`,children:t(a)}),(0,S.jsx)(`span`,{className:`desc`,children:t(o)})]}),(0,S.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8},children:[(0,S.jsx)(Me,{value:i?i.backend??`auto`:`inherit`,options:[{value:`inherit`,label:t(`claude.useMainSetting`)},{value:`auto`,label:t(`dash.backendAuto`)},{value:`openai`,label:t(`dash.backendOpenAI`)},{value:`anthropic`,label:t(`dash.backendAnthropic`)}],onChange:t=>r({...n,[e]:t===`inherit`?void 0:{...i,backend:t===`auto`?void 0:t}}),label:t(`dash.sidecarBackend`)}),(0,S.jsx)(`input`,{className:`input mono`,value:i?.model??``,onChange:t=>r({...n,[e]:{...i,model:t.target.value}}),placeholder:t(`claude.sidecarModelPlaceholder`),disabled:!i,"aria-label":t(`dash.sidecarModel`),style:{minWidth:210}})]})]},e)})]}),(0,S.jsx)(`div`,{className:`h-section`,children:t(`claude.quickstart`)}),(0,S.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:(0,S.jsx)(Ee,{k:`claude.quickstartHint`,cmd:`ocx claude`})}),(0,S.jsx)(`pre`,{className:`mono card`,style:{padding:`10px 14px`,overflowX:`auto`,margin:0},children:`ocx claude`}),(0,S.jsxs)(`details`,{style:{margin:`10px 0 0`},children:[(0,S.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:t(`claude.manualEnv`)}),(0,S.jsx)(`pre`,{className:`mono card text-label`,style:{padding:`10px 14px`,overflowX:`auto`,margin:`6px 0 0`},children:b})]}),(0,S.jsx)(`div`,{className:`h-section`,children:t(`claude.smallFastModel`)}),(0,S.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:t(`claude.smallFastModelHint`)}),(0,S.jsx)(Me,{value:n.smallFastModel,options:p,onChange:e=>r({...n,smallFastModel:e}),label:t(`claude.smallFastModel`),style:{maxWidth:420}}),(0,S.jsxs)(`div`,{className:`h-section`,children:[t(`claude.modelMap`),` `,(0,S.jsx)(`span`,{className:`count`,children:i.length})]}),(0,S.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:t(`claude.modelMapHint`)}),(0,S.jsx)(`div`,{className:`stack`,style:{gap:8},children:i.map((e,n)=>(0,S.jsxs)(`div`,{className:`row`,style:{gap:8},children:[(0,S.jsx)(`input`,{className:`input mono`,value:e.from,placeholder:t(`claude.mapFrom`),onChange:e=>a(t=>t.map((t,r)=>r===n?{...t,from:e.target.value}:t)),style:{flex:1}}),(0,S.jsx)(`span`,{className:`muted`,"aria-hidden":!0,children:`→`}),(0,S.jsx)(`input`,{className:`input mono`,value:e.to,placeholder:t(`claude.mapTo`),onChange:e=>a(t=>t.map((t,r)=>r===n?{...t,to:e.target.value}:t)),style:{flex:1}}),(0,S.jsx)(`button`,{className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>a(e=>e.filter((e,t)=>t!==n)),"aria-label":t(`claude.removeMapping`),style:{color:`var(--red)`},children:(0,S.jsx)(ie,{})})]},n))}),(0,S.jsx)(`div`,{style:{marginTop:8},children:(0,S.jsxs)(`button`,{className:`btn btn-ghost btn-sm`,onClick:()=>a(e=>[...e,{from:``,to:``}]),children:[(0,S.jsx)(ae,{}),` `,t(`claude.addMapping`)]})}),(0,S.jsx)(`div`,{style:{marginTop:14},children:(0,S.jsx)(`button`,{className:`btn btn-primary`,onClick:h,children:t(`common.save`)})}),(0,S.jsxs)(`div`,{className:`h-section`,children:[t(`claude.aliases`),` `,(0,S.jsx)(`span`,{className:`count`,children:n.aliases.length})]}),(0,S.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:t(`claude.aliasesHint`)}),n.aliases.length===0?(0,S.jsx)(`div`,{className:`muted text-label`,children:t(`claude.none`)}):(0,S.jsx)(`div`,{className:`stack`,style:{gap:6,maxHeight:320,overflowY:`auto`},children:Array.from(n.aliases.reduce((e,t)=>{let n=/\(([^)]+)\)\s*$/.exec(t.display_name),r=n?n[1]:`etc`;return(e.get(r)??e.set(r,[]).get(r)).push(t),e},new Map)).map(([e,t])=>(0,S.jsxs)(`div`,{children:[(0,S.jsxs)(`div`,{className:`muted text-caption font-semibold`,style:{textTransform:`uppercase`,letterSpacing:`var(--tracking-wide)`,margin:`6px 2px 4px`},children:[e,` · `,t.length]}),(0,S.jsx)(`div`,{className:`stack`,style:{gap:4},children:t.map(e=>(0,S.jsxs)(`div`,{className:`card row`,style:{padding:`6px 12px`,gap:10},children:[(0,S.jsx)(`code`,{className:`mono text-label`,style:{flex:1},children:e.id}),(0,S.jsx)(`span`,{className:`muted text-label`,children:e.display_name})]},e.id))})]},e))})]})}var pn=`opencodex-api-token`,mn=!1,hn=null;function gn(e){try{let t=e instanceof Request?e.url:String(e);return new URL(t,window.location.href).pathname}catch{return null}}function _n(e){let t=gn(e);return!!t&&(t.startsWith(`/api/`)||t.startsWith(`/v1/`))}function vn(){try{return sessionStorage.getItem(pn)?.trim()||null}catch{return null}}function yn(e){try{sessionStorage.setItem(pn,e)}catch{}}function bn(){try{sessionStorage.removeItem(pn)}catch{}}function xn(e,t,n){let r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));return r.set(`X-OpenCodex-API-Key`,n),e instanceof Request?[new Request(e,{headers:r}),t?{...t,headers:r}:void 0]:[e,{...t,headers:r}]}async function Sn(){return hn||(hn=Promise.resolve().then(()=>window.prompt(`OpenCodex API token`)?.trim()||null).finally(()=>{hn=null}),hn)}function Cn(){if(mn)return;mn=!0;let e=window.fetch.bind(window);window.fetch=async(t,n)=>{if(!_n(t))return e(t,n);let r=vn(),[i,a]=r?xn(t,n,r):[t,n],o=await e(i,a);if(o.status!==401)return o;r&&bn();let s=await Sn();if(!s)return o;yn(s);let[c,l]=xn(t,n,s),u=await e(c,l);return u.status===401&&bn(),u}}Cn();var wn=new Set([`dashboard`,`providers`,`models`,`subagents`,`logs`,`debug`,`usage`,`codex-auth`,`api`,`claude`]);function Tn(){let e=location.hash.replace(/^#\/?/,``);return wn.has(e)?e:`dashboard`}var En=``,Dn=`ocx-theme`,On=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:w},{id:`providers`,tkey:`nav.providers`,Icon:T},{id:`models`,tkey:`nav.models`,Icon:ee},{id:`subagents`,tkey:`nav.subagents`,Icon:te},{id:`logs`,tkey:`nav.logs`,Icon:E},{id:`debug`,tkey:`nav.debug`,Icon:re},{id:`usage`,tkey:`nav.usage`,Icon:D},{id:`codex-auth`,tkey:`nav.codexAuth`,Icon:I},{id:`api`,tkey:`nav.api`,Icon:me},{id:`claude`,tkey:`nav.claude`,Icon:he}],kn={light:fe,dark:pe,system:R},An={light:`theme.light`,dark:`theme.dark`,system:`theme.system`};function jn(e){if(!e||typeof e!=`object`||!(`version`in e))return null;let t=e.version;return typeof t==`string`&&t.length>0?t:null}function Mn(){let e=localStorage.getItem(Dn);return e===`light`||e===`dark`?e:`system`}function Nn(){let[e,t]=(0,_.useState)(Tn),[n,r]=(0,_.useState)(Mn),[i,a]=(0,_.useState)(null),{locale:o,setLocale:s}=Ce(),c=we(),[l,u]=(0,_.useState)(!1),d=(0,_.useRef)(null),f=(0,_.useRef)(null),p=(0,_.useRef)(!1);(0,_.useEffect)(()=>{let e=()=>{t(Tn()),u(!1)};return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>{let t=`#${e}`;window.location.hash!==t&&(window.location.hash=e)},[e]),(0,_.useEffect)(()=>{let e=document.documentElement;n===`system`?(e.removeAttribute(`data-theme`),localStorage.removeItem(Dn)):(e.setAttribute(`data-theme`,n),localStorage.setItem(Dn,n))},[n]),(0,_.useEffect)(()=>{let e=!1,t=async()=>{try{let t=await fetch(`${En}/healthz`);if(!t.ok)return;let n=jn(await t.json());!e&&n&&a(n)}catch{}};t();let n=setInterval(t,3e4);return()=>{e=!0,clearInterval(n)}},[]);let m=()=>r(e=>e===`light`?`dark`:e===`dark`?`system`:`light`),h=kn[n],g=i??`2.7.20`,[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(null);(0,_.useEffect)(()=>{if(!l)return;let e=e=>{e.key===`Escape`&&u(!1)};window.addEventListener(`keydown`,e);let t=document.body.style.overflow;return document.body.style.overflow=`hidden`,()=>{window.removeEventListener(`keydown`,e),document.body.style.overflow=t}},[l]),(0,_.useEffect)(()=>{if(l){p.current=!0;let e=setTimeout(()=>f.current?.focus(),200);return()=>clearTimeout(e)}p.current&&(p.current=!1,d.current?.focus())},[l]),(0,_.useEffect)(()=>{let e=window.matchMedia(`(min-width: 761px)`),t=()=>{e.matches&&u(!1)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,_.useEffect)(()=>{let e=!1;return fetch(`${En}/api/claude-code`).then(e=>e.json()).then(t=>{!e&&typeof t.enabled==`boolean`&&x(t.enabled)}).catch(()=>{}),()=>{e=!0}},[]);let C=async()=>{if(b===null)return;let e=!b;x(e);try{(await fetch(`${En}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:e})})).ok||x(!e)}catch{x(!e)}},w=async()=>{if(confirm(c(`dash.stopConfirm`))){y(!0);try{await fetch(`${En}/api/stop`,{method:`POST`})}catch{}}},T=(0,S.jsxs)(`div`,{className:`brand`,children:[(0,S.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":`opencodex logo`}),(0,S.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,S.jsxs)(`span`,{className:`ver`,children:[`v`,g]})]});return(0,S.jsxs)(`div`,{className:`app`,children:[(0,S.jsxs)(`header`,{className:`mobile-topbar`,inert:l,children:[(0,S.jsx)(`button`,{ref:d,type:`button`,className:`menu-toggle`,onClick:()=>u(e=>!e),"aria-expanded":l,"aria-controls":`app-sidebar`,"aria-label":c(l?`nav.closeMenu`:`nav.openMenu`),title:c(l?`nav.closeMenu`:`nav.openMenu`),children:(0,S.jsx)(ne,{})}),T,(0,S.jsx)(`button`,{type:`button`,className:`theme-toggle stop-toggle`,onClick:w,disabled:v,"aria-label":c(`dash.stop`),title:c(`dash.stop`),children:(0,S.jsx)(ce,{})})]}),l&&(0,S.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>u(!1),"aria-hidden":`true`}),(0,S.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${l?` open`:``}`,ref:f,tabIndex:-1,children:[(0,S.jsxs)(`div`,{className:`drawer-head`,children:[T,(0,S.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>u(!1),"aria-label":c(`nav.closeMenu`),title:c(`nav.closeMenu`),children:(0,S.jsx)(ie,{})})]}),(0,S.jsx)(`nav`,{children:On.map(({id:n,tkey:r,Icon:i})=>(0,S.jsxs)(`button`,{className:`nav-item${e===n?` active`:``}`,"data-page":n,onClick:()=>{t(n),u(!1)},"aria-current":e===n?`page`:void 0,children:[(0,S.jsx)(i,{}),` `,c(r)]},n))}),(0,S.jsxs)(`div`,{className:`sidebar-foot`,children:[b!==null&&(0,S.jsxs)(`button`,{type:`button`,className:`theme-toggle`,onClick:C,"aria-pressed":b,"aria-label":c(`claude.toggleAria`),title:c(`claude.toggleAria`),style:b?{color:`var(--accent)`}:void 0,children:[(0,S.jsx)(he,{}),` `,(0,S.jsx)(`span`,{className:`mode`,children:b?`Claude ON`:`Claude OFF`})]}),(0,S.jsxs)(`div`,{className:`lang-toggle`,children:[(0,S.jsx)(me,{"aria-hidden":!0}),(0,S.jsx)(Me,{value:o,options:ve.map(e=>({value:e.code,label:e.name})),onChange:e=>s(e),label:c(`lang.label`),placement:`right`,style:{flex:1,minWidth:0,width:`100%`}})]}),(0,S.jsxs)(`button`,{type:`button`,className:`theme-toggle`,onClick:m,"aria-label":`${c(`theme.label`)}: ${c(An[n])}`,title:`${c(`theme.label`)}: ${c(An[n])}`,children:[(0,S.jsx)(h,{}),` `,(0,S.jsx)(`span`,{className:`mode`,children:c(An[n])})]}),(0,S.jsxs)(`button`,{type:`button`,className:`theme-toggle stop-toggle`,onClick:w,disabled:v,"aria-label":c(`dash.stop`),title:c(`dash.stop`),children:[(0,S.jsx)(ce,{}),` `,(0,S.jsx)(`span`,{className:`mode`,children:c(v?`dash.stopping`:`dash.stop`)})]}),(0,S.jsxs)(`a`,{className:`sidebar-link`,href:`https://github.com/lidge-jun/opencodex`,target:`_blank`,rel:`noreferrer`,children:[(0,S.jsx)(F,{}),` `,c(`common.github`)]})]})]}),(0,S.jsx)(`main`,{className:`main`,inert:l,children:(0,S.jsxs)(`div`,{className:`main-inner`,children:[e===`dashboard`&&(0,S.jsx)(ze,{apiBase:En}),e===`providers`&&(0,S.jsx)(tt,{apiBase:En}),e===`models`&&(0,S.jsx)(dt,{apiBase:En}),e===`subagents`&&(0,S.jsx)(ft,{apiBase:En}),e===`logs`&&(0,S.jsx)(qt,{apiBase:En}),e===`debug`&&(0,S.jsx)(Xt,{apiBase:En}),e===`usage`&&(0,S.jsx)(rn,{apiBase:En}),e===`codex-auth`&&(0,S.jsx)(on,{apiBase:En}),e===`api`&&(0,S.jsx)(dn,{apiBase:En}),e===`claude`&&(0,S.jsx)(fn,{apiBase:En})]})})]})}v.createRoot(document.getElementById(`root`)).render((0,S.jsx)(_.StrictMode,{children:(0,S.jsx)(Te,{children:(0,S.jsx)(Nn,{})})}));
|