swayrouter 1.0.8 → 1.3.0
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/CHANGELOG.md +9 -0
- package/README.id.md +7 -3
- package/README.md +7 -3
- package/dashboard/dist/assets/{CliTools-aPWuAaGl.js → CliTools-BA3qQ4Y-.js} +1 -1
- package/dashboard/dist/assets/{Combo-BLv2ftiC.js → Combo-CoYmIAt0.js} +1 -1
- package/dashboard/dist/assets/{ConsoleLog-XQc0AJjY.js → ConsoleLog-DEJBcRXY.js} +1 -1
- package/dashboard/dist/assets/{Dashboard-DTZuAXn6.js → Dashboard-0H0FmS_z.js} +1 -1
- package/dashboard/dist/assets/{Header-BZEBRuoI.js → Header-DjeUJuR7.js} +1 -1
- package/dashboard/dist/assets/{Keys-DoBcUcd1.js → Keys-D5i0CJPw.js} +1 -1
- package/dashboard/dist/assets/{Login-CLA9YPSW.js → Login-Bmyb9mgb.js} +1 -1
- package/dashboard/dist/assets/{ManageApiKey-C6AcZdXV.js → ManageApiKey--COl62Nm.js} +1 -1
- package/dashboard/dist/assets/{OAuthCallback-CngALmEQ.js → OAuthCallback-DH2M63oY.js} +1 -1
- package/dashboard/dist/assets/{Provider-gBLoiXWc.js → Provider-DubAFZl3.js} +2 -2
- package/dashboard/dist/assets/{ProviderModelAccordion-BiCN7K3L.js → ProviderModelAccordion-Cuk2_DWf.js} +1 -1
- package/dashboard/dist/assets/{Proxy-WdkDbR59.js → Proxy-C2UzXL2r.js} +1 -1
- package/dashboard/dist/assets/{QuotaMonitor-DJnvSQmA.js → QuotaMonitor-gk5otjdB.js} +1 -1
- package/dashboard/dist/assets/{Settings-BqVAj_Z6.js → Settings-DlOhYL96.js} +1 -1
- package/dashboard/dist/assets/{Setup-YEZfhKZl.js → Setup-3-yf1tvY.js} +1 -1
- package/dashboard/dist/assets/{StatusBadge-CbCgRp1u.js → StatusBadge-iBeqU7Qd.js} +1 -1
- package/dashboard/dist/assets/{SwayChat-BNkpBa01.js → SwayChat-BlbMT8HI.js} +1 -1
- package/dashboard/dist/assets/{Usage-BtG4T3yX.js → Usage-C1uKYlTO.js} +1 -1
- package/dashboard/dist/assets/{accordion-I9hJ3zKn.js → accordion-DovdZQJu.js} +1 -1
- package/dashboard/dist/assets/{admin-extras-api-CZx9UMQG.js → admin-extras-api-5xk7DmbO.js} +1 -1
- package/dashboard/dist/assets/{api-keys-api-CoNfm8AZ.js → api-keys-api-DVdIV17Y.js} +1 -1
- package/dashboard/dist/assets/{card-3Ad838s5.js → card-DvGOwuMw.js} +1 -1
- package/dashboard/dist/assets/{checkbox-MVYpQird.js → checkbox-ClXwjb6M.js} +1 -1
- package/dashboard/dist/assets/{connections-api-BReJMHgi.js → connections-api-DlH7CVMr.js} +1 -1
- package/dashboard/dist/assets/{copy-button-D9SzZokt.js → copy-button-CCsXIvkJ.js} +1 -1
- package/dashboard/dist/assets/{currency-api-B0hvChGg.js → currency-api-CHfn9Y-I.js} +1 -1
- package/dashboard/dist/assets/{flip-button-yX_RgEC4.js → flip-button-CDurxfqc.js} +1 -1
- package/dashboard/dist/assets/{frame-R55qLb-9.js → frame-CY26iHQE.js} +1 -1
- package/dashboard/dist/assets/{index-Dne9pkEF.js → index-CkR38iPY.js} +2 -2
- package/dashboard/dist/assets/{ripple-button-BNF8KOIB.js → ripple-button-BrLlmKvT.js} +1 -1
- package/dashboard/dist/assets/{segmented-W2XJE85e.js → segmented-CxobJihW.js} +1 -1
- package/dashboard/dist/assets/{select-BnilqBos.js → select-DfWoWPVg.js} +1 -1
- package/dashboard/dist/assets/{skeleton-CuG5ZRYw.js → skeleton-81lPHspy.js} +1 -1
- package/dashboard/dist/assets/{table-CmYFkpYA.js → table-CEyzPvr7.js} +1 -1
- package/dashboard/dist/assets/{tabs-j6meB_LR.js → tabs-DkTPKASE.js} +1 -1
- package/dashboard/dist/assets/{tunnel-api-6Weym8SK.js → tunnel-api-m02RsElG.js} +1 -1
- package/dashboard/dist/index.html +1 -1
- package/package.json +1 -1
- package/src/config/errorConfig.js +35 -13
- package/src/dashboardGuard.js +29 -13
- package/src/executors/azure.js +12 -12
- package/src/executors/default.js +38 -13
- package/src/lib/db/repos/connectionsRepo.js +4 -0
- package/src/lib/db/repos/settingsRepo.js +54 -24
- package/src/providers/registry/azure.js +20 -19
- package/src/providers/registry/openai.js +15 -12
- package/src/routes/api/providers/[id]/route.js +13 -7
- package/src/routes/api/settings/route.js +43 -34
- package/src/services/accountFallback.js +78 -17
- package/src/sse/handlers/chat.js +63 -57
- package/src/sse/services/auth.js +15 -3
- package/src/translator/formats/responsesApi.js +8 -6
- package/src/translator/request/openai-responses.js +18 -15
- package/src/utils/error.js +1 -1
- package/src/utils/sessionManager.js +10 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{d as mr,r as d,j as e}from"./react-vendor-xnYrwzsL.js";import{m as pe,A as rt}from"./motion-vendor-g5fpGzmJ.js";import{a as pr}from"./query-vendor-DVevaSVS.js";import{H as fr}from"./Header-BZEBRuoI.js";import{a as Ue,P as hr}from"./ProviderModelAccordion-BiCN7K3L.js";import{E as xr,e as J,B as me,g as Ye,S as At,t as $,c as B,I as gr,D as Ct,m as Tt,n as _t,o as Mt,s as Et,q as Rt}from"./index-Dne9pkEF.js";import{F as br,c as yr}from"./frame-R55qLb-9.js";import{b as qt}from"./api-keys-api-CoNfm8AZ.js";import{p as wr,S as Xe,b as vr,r as jr,s as Nr,g as kr,M as Pt,i as Sr,a as Ar,f as Cr,c as Me,n as Ve,d as $t,e as Pe,h as Re,j as zt,k as Tr,l as _r,m as Dt,o as Mr,q as Er,t as Rr,u as nt,v as Pr,w as zr,x as Dr}from"./chatStudio-C0zPz_Z_.js";import{af as Qe,T as It,i as st,X as Ze,aJ as Lt,h as Ir,ay as Ee,ad as Bt,aK as Or,q as qr,ag as Ft,ap as $r,A as Lr,ah as Br,t as Fr,a as Jr,a0 as Kr,aB as Wr,r as Hr,C as Gr}from"./icons-vendor-CUx7SB5V.js";import{M as Ur,r as Yr}from"./markdown-vendor-BY8e1gQ8.js";import"./accordion-I9hJ3zKn.js";import"./ui-vendor-BuM9f2NY.js";const Xr={type:"object",properties:{},additionalProperties:!1},Vr=[{type:"function",function:{name:"router_overview",description:"Inspect the local Sway Router status. The result explicitly separates totalProviders (the unique union of built-in registry providers and custom provider nodes, including zero-connection providers), registeredProviderTypes, providerNodes, configuredProviders, activeProviders, inactiveOnlyProviders, connections, API keys, proxy pools, combos, admission load, and safe settings. When asked for the total number of providers, use totalProviders, not activeProviders or connectedProviders.",parameters:Xr}},{type:"function",function:{name:"router_models",description:"List models currently exposed by Sway Router, including provider and known capabilities such as vision, tools, reasoning, and image output.",parameters:{type:"object",properties:{query:{type:"string",description:"Optional model or provider filter."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum models to return."}},additionalProperties:!1}}},{type:"function",function:{name:"router_connections",description:"Inspect provider connection metadata without exposing API keys or OAuth tokens. Can filter by provider and active state.",parameters:{type:"object",properties:{provider:{type:"string",description:"Optional provider id or alias."},active_only:{type:"boolean",description:"Return only active connections."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum connections to return."}},additionalProperties:!1}}},{type:"function",function:{name:"router_api_keys",description:"Inspect gateway API key metadata and active/revoked counts. Never returns key secrets.",parameters:{type:"object",properties:{include_revoked:{type:"boolean"},limit:{type:"integer",minimum:1,maximum:100}},additionalProperties:!1}}},{type:"function",function:{name:"web_search",description:"Search the web and return bounded, normalized results. Use it when current or external information is needed.",parameters:{type:"object",properties:{query:{type:"string",description:"The web search query."},max_results:{type:"integer",minimum:1,maximum:8}},required:["query"],additionalProperties:!1}}},{type:"function",function:{name:"read_workspace",description:"Read the local workspace using safe read-only commands: pwd, ls/dir, cat/type, rg, and read-only git status/diff/log/show/branch.",parameters:{type:"object",properties:{command:{type:"string",description:"A safe read-only workspace command."}},required:["command"],additionalProperties:!1}}},{type:"function",function:{name:"curl",description:"Fetch a public HTTP(S) URL with a bounded GET or HEAD request. Private and loopback targets are blocked.",parameters:{type:"object",properties:{url:{type:"string",description:"Public http(s) URL."},method:{type:"string",enum:["GET","HEAD"]}},required:["url"],additionalProperties:!1}}},{type:"function",function:{name:"execute_javascript",description:"Run a short JavaScript diagnostic in the local workspace. This always requires explicit user approval before execution.",parameters:{type:"object",properties:{code:{type:"string",description:"JavaScript diagnostic code, maximum 6000 characters."}},required:["code"],additionalProperties:!1}}},{type:"function",function:{name:"generate_image",description:"Generate an image through an enabled Sway Router media provider. Use only when the user asks for an image and report clearly if media generation is not configured.",parameters:{type:"object",properties:{prompt:{type:"string",description:"Detailed image prompt."},provider:{type:"string",description:"Optional enabled media provider."},model:{type:"string",description:"Optional image model."},size:{type:"string",enum:["256x256","512x512","1024x1024"]},n:{type:"integer",minimum:1,maximum:4}},required:["prompt"],additionalProperties:!1}}}],Qr={router_overview:"Checking Router status",router_models:"Inspecting models",router_connections:"Inspecting connections",router_api_keys:"Inspecting API keys",web_search:"Searching the web",read_workspace:"Reading workspace",curl:"Fetching URL",execute_javascript:"Running JavaScript",generate_image:"Generating image"};function Zr(a){return Qr[a]||"Using agent tool"}async function G(a,r,n=""){const c={"Content-Type":"application/json",Accept:"application/json"};n.trim()&&(c.Authorization=`Bearer ${n.trim()}`);const s=await fetch(a,{method:"POST",credentials:"include",headers:c,body:JSON.stringify(r)}),o=await s.json().catch(()=>null);if(!s.ok){const u=o==null?void 0:o.error,h=typeof u=="string"?u:u&&typeof u=="object"&&typeof u.message=="string"?u.message:typeof(o==null?void 0:o.message)=="string"?o.message:`Tool request failed (${s.status})`;throw new Error(h)}return o??{ok:!0}}async function en(a,r,n={}){const c=n.apiKey||"";if(a==="router_overview")return G("/api/chat/tools/router",{action:"overview"},c);if(a==="router_models")return G("/api/chat/tools/router",{action:"models",query:r.query,limit:r.limit},c);if(a==="router_connections")return G("/api/chat/tools/router",{action:"connections",provider:r.provider,active_only:r.active_only,limit:r.limit},c);if(a==="router_api_keys")return G("/api/chat/tools/router",{action:"api_keys",include_revoked:r.include_revoked,limit:r.limit},c);if(a==="web_search")return G("/api/chat/tools/search",{query:r.query,max_results:r.max_results},c);if(a==="read_workspace")return G("/api/chat/tools/shell",{command:r.command},c);if(a==="curl")return G("/api/chat/tools/curl",{url:r.url,method:r.method},c);if(a==="generate_image")return G("/api/v1/images/generations",{prompt:r.prompt,provider:r.provider,model:r.model,size:r.size,n:r.n,response_format:"b64_json"},c);if(a==="execute_javascript"){const s=typeof r.code=="string"?r.code:"";if(!n.approve)throw new Error("JavaScript execution requires user approval");return await n.approve({name:"execute_javascript",code:s})?G("/api/chat/tools/shell",{mode:"execute",approved:!0,code:s},c):{ok:!1,denied:!0,error:"User denied JavaScript execution"}}throw new Error(`Unknown agent tool: ${a}`)}function tn(a,r=12e3){let n=a;if(n&&typeof n=="object")try{n=JSON.parse(JSON.stringify(n,(s,o)=>s==="b64_json"&&typeof o=="string"?`[image data omitted: ${o.length} bytes]`:s==="body"&&typeof o=="string"&&o.length>6e3?`${o.slice(0,6e3)}… [body truncated]`:o))}catch{n=String(n)}const c=typeof n=="string"?n:JSON.stringify(n);return c.length>r?`${c.slice(0,r)}… [tool result truncated]`:c}const Ot="sway-chat.lastModel",et="/dashboard/manage-apikey",rn="You are Sway Router Assistant, the capable internal agent of the Sway Router platform. Be a practical senior engineer and operator: understand the Router, inspect it when asked, use the right tools, solve problems step by step when useful, and explain what you found. When asked for the total number of providers, count the unique union of built-in registry providers and custom provider nodes, including providers with no connections; use router_overview.summary.totalProviders for that total and distinguish it from registeredProviderTypes, configuredProviders, activeProviders, and inactiveOnlyProviders. Never report activeProviders or connectedProviders as the total. Respond in the user's language, stay concise by default, ask a clarifying question when a request is underspecified, and use Markdown for readability. Format code in fenced blocks with the correct language and state uncertainty clearly instead of inventing facts.";async function nn(){const a=await qt().catch(()=>""),r={Accept:"application/json"};a&&(r.Authorization=`Bearer ${a}`);const n=await fetch("/v1/models",{credentials:"include",headers:r});if(!n.ok){const s=await n.json().catch(()=>null);throw new Error(nt((s==null?void 0:s.error)??(s==null?void 0:s.message))||`Models request failed (${n.status})`)}return((await n.json()).data??[]).flatMap(s=>{var h;const o=typeof s.id=="string"?s.id.trim():"";if(!o)return[];const u=typeof s.owned_by=="string"&&s.owned_by?s.owned_by:o.includes("/")?o.split("/",1)[0]:"other";return[{id:o,name:((h=s.name)==null?void 0:h.trim())||o,provider:u,capabilities:s.capabilities}]})}const sn=[0,90,180,90,180,270,180,270,360],on=["bg-white","bg-blue-200","bg-blue-400","bg-white/85","bg-blue-600","bg-white/70","bg-blue-300","bg-white/90","bg-primary"];function Jt({muted:a=!1}){return e.jsx("span",{className:"grid shrink-0 grid-cols-3 gap-[2px] p-0.5","aria-hidden":"true",children:sn.map((r,n)=>e.jsx("span",{className:B("size-1 rounded-[1px]",on[n],a?"opacity-25":"animate-chat-pixel motion-reduce:animate-none"),style:a?void 0:{animationDelay:`${r}ms`}},n))})}function Kt(a){const[r,n]=d.useState(()=>Dt(a.startAt));return d.useEffect(()=>{if(a.startAt==null||a.status!=="streaming")return;const c=()=>n(Dt(a.startAt));c();const s=window.setInterval(c,100);return()=>window.clearInterval(s)},[a.startAt,a.status]),r}const an=d.memo(function({message:r}){const n=Kt(r),c=$t({content:r.content,thinking:r.thinking}),s=c==="Thinking"?"Thinking…":c==="Writing"?"Writing…":c;return e.jsxs(pe.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},className:"inline-flex items-center gap-2 rounded-md py-1 text-[12px] text-muted-foreground","aria-label":`${s}${n>0?`, ${Pe(n)}`:""}`,role:"status","aria-live":"polite",children:[e.jsx(Jt,{}),e.jsx("span",{className:"animate-chat-shimmer bg-[length:200%_100%] bg-gradient-to-r from-muted-foreground via-foreground to-muted-foreground bg-clip-text font-medium text-transparent motion-reduce:animate-none",children:s}),e.jsx("span",{className:"font-mono tabular-nums opacity-60",children:Pe(n)})]})}),ln=d.memo(function({message:r,open:n,onToggle:c}){var w,y,F;const s=Kt(r),o=$t({content:r.content,thinking:r.thinking}),u=r.thoughtMs!=null?Pe(r.thoughtMs):"Thinking",h=!r.thinking&&(((w=r.streamUsage)==null?void 0:w.reasoning)??0)>0,m=(y=r.streamUsage)==null?void 0:y.reasoning,x=(r.thinking||"").split(/\r?\n+/).map(se=>se.replace(/^\s*(?:[-*•]|\d+[.)])\s*/,"").trim()).filter(Boolean).slice(-12),S=o==="Thinking"?"Thinking…":o==="Writing"?"Writing…":o,C=`thought-${r.id}`;return e.jsxs("div",{className:"mb-2 overflow-hidden rounded-xl border border-border/70 bg-muted/30",children:[e.jsxs("button",{type:"button",onClick:c,"aria-expanded":n,"aria-controls":C,className:"group flex min-h-9 w-full items-center gap-2 px-3 py-2 text-left text-xs text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground",children:[r.status==="streaming"?e.jsx(Jt,{}):e.jsx(Fr,{className:"size-3.5 shrink-0 text-muted-foreground/80","aria-hidden":"true"}),e.jsx("span",{className:B("min-w-0 truncate font-medium",r.status==="streaming"&&"animate-chat-shimmer bg-[length:200%_100%] bg-gradient-to-r from-muted-foreground via-foreground to-muted-foreground bg-clip-text text-transparent motion-reduce:animate-none"),children:r.status==="streaming"?S:`Thought for ${u}`}),r.status==="streaming"?e.jsx("span",{className:"shrink-0 font-mono text-[10px] tabular-nums opacity-60",children:Pe(s)}):null,m!=null&&m>0?e.jsxs("span",{className:"shrink-0 rounded border border-border/70 bg-surface px-1.5 py-0.5 font-mono text-[10px] tabular-nums",children:[Re(m)," reasoning"]}):null,e.jsx(st,{className:B("size-3.5 shrink-0 transition-transform duration-200",!n&&"-rotate-90"),"aria-hidden":"true"})]}),e.jsx(rt,{initial:!1,children:n?e.jsx(pe.div,{id:C,initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:"easeOut"},className:"overflow-hidden border-t border-border/60 bg-background/20",children:e.jsxs("div",{className:"px-3 pb-3 pt-2 text-xs leading-relaxed text-muted-foreground",children:[(F=r.toolActivity)!=null&&F.length?e.jsx(mn,{activities:r.toolActivity}):null,x.length>1?e.jsx("ol",{className:"max-h-48 space-y-2 overflow-y-auto pr-1",children:x.map((se,oe)=>{const X=r.status==="streaming"&&oe===x.length-1;return e.jsxs("li",{className:"relative flex items-start gap-2",children:[e.jsx("span",{className:B("mt-1.5 size-1.5 shrink-0 rounded-full",X?"animate-pulse bg-amber-300 motion-reduce:animate-none":"bg-emerald-400"),"aria-hidden":"true"}),e.jsx("span",{className:B("min-w-0 break-words",X&&"text-foreground"),children:se})]},`${se}-${oe}`)})}):r.thinking?e.jsx("div",{className:"max-h-48 overflow-y-auto whitespace-pre-wrap break-words",children:r.thinking}):null,h?e.jsx("div",{className:"text-muted-foreground/70",children:"This model used hidden reasoning tokens, but did not return the reasoning text."}):null]})}):null})]})},(a,r)=>a.message===r.message&&a.open===r.open);function be({label:a,value:r,title:n}){return e.jsx(J,{label:n,children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-border/70 bg-surface/60 px-2 py-1",children:[e.jsx("span",{className:"text-muted-foreground/75",children:a}),e.jsx("span",{className:"font-medium text-foreground/85",children:r})]})})}const cn=d.memo(function({message:r}){const n=r.streamUsage,c=n!=null&&(n.cached!=null||n.cacheCreation!=null),s=n!=null&&(n.prompt!=null||n.completion!=null||n.reasoning!=null||c);return r.ttfbMs==null&&r.durationMs==null&&!s?null:e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-[11px] tabular-nums text-muted-foreground",children:[r.ttfbMs!=null?e.jsx(be,{label:"Response starts",value:zt(r.ttfbMs),title:"Time until the model starts sending the answer."}):null,r.durationMs!=null?e.jsx(be,{label:"Completed in",value:zt(r.durationMs),title:"Total time from sending your message until the answer finished."}):null,s&&(n==null?void 0:n.completion)!=null?e.jsx(be,{label:"Answer length",value:`${Re(n.completion)} tokens`,title:"Tokens generated in the answer."}):null,c&&(n==null?void 0:n.cached)!=null&&n.cached>0?e.jsx(be,{label:"Cache read",value:`${Re(n.cached)} tokens`,title:"Input tokens served from the provider's prompt cache, which can reduce latency and cost."}):null,c&&(n==null?void 0:n.cacheCreation)!=null&&n.cacheCreation>0?e.jsx(be,{label:"Cache written",value:`${Re(n.cacheCreation)} tokens`,title:"Input tokens written to the provider's prompt cache for later requests."}):null]})});function Y(a){return a&&typeof a=="object"?a:null}function U(a){return typeof a=="string"?a:""}function tt(a,r){Array.isArray(r)&&r.forEach((n,c)=>{const s=Y(n);if(!s)return;const o=Number(s.index),u=Number.isInteger(o)&&o>=0?o:c,h=a.get(u)||{id:`call_${u}`,type:"function",function:{name:"",arguments:""}},m=Y(s.function),x=U((m==null?void 0:m.name)??s.name),S=(m==null?void 0:m.arguments)??s.arguments,C=typeof S=="string"?S:S==null?"":JSON.stringify(S);U(s.id)&&(h.id=U(s.id)),U(s.type)&&(h.type=U(s.type)),x&&(h.function.name=x),C&&(h.function.arguments+=C),a.set(u,h)})}function dn(a,r){const n=Y(a),c=Array.isArray(n==null?void 0:n.choices)?Y(n.choices[0]):null,s=Y(c==null?void 0:c.delta),o=Y(c==null?void 0:c.message);tt(r,s==null?void 0:s.tool_calls),tt(r,o==null?void 0:o.tool_calls),tt(r,n==null?void 0:n.tool_calls)}function un(a){const r=Y(a);if(!r)return String(a??"");if(r.denied===!0)return"Execution denied";if(r.error)return String(r.error).slice(0,280);if(Array.isArray(r.data))return`${r.data.length} image${r.data.length===1?"":"s"} returned`;if(typeof r.output=="string")return r.output.slice(0,280);if(typeof r.body=="string")return r.body.slice(0,280);if(r.summary&&typeof r.summary=="object")try{return JSON.stringify(r.summary).slice(0,280)}catch{}try{return JSON.stringify(r).slice(0,280)}catch{return"Tool completed"}}const mn=d.memo(function({activities:r}){if(!(r!=null&&r.length))return null;const n=s=>s.status==="error"?e.jsx(Jr,{className:"size-3.5 text-destructive","aria-hidden":"true"}):s.status==="denied"?e.jsx(Lt,{className:"size-3.5 text-amber-300","aria-hidden":"true"}):s.name==="web_search"||s.name==="curl"?e.jsx(Kr,{className:"size-3.5 text-sky-300","aria-hidden":"true"}):s.name==="generate_image"?e.jsx(Wr,{className:"size-3.5 text-fuchsia-300","aria-hidden":"true"}):s.name==="execute_javascript"||s.name==="read_workspace"?e.jsx(Hr,{className:"size-3.5 text-emerald-300","aria-hidden":"true"}):e.jsx(Gr,{className:"size-3.5 text-emerald-300","aria-hidden":"true"}),c=s=>s==="running"?"Running":s==="done"?"Done":s==="denied"?"Denied":"Failed";return e.jsx("div",{className:"mb-2 space-y-1.5","aria-label":"Sway Router Assistant activity",children:r.map(s=>{var h;const o=s.name==="generate_image"&&((h=Y(s.result))==null?void 0:h.data),u=Array.isArray(o)?o.flatMap(m=>{const x=Y(m);return U(x==null?void 0:x.url)?[U(x==null?void 0:x.url)]:U(x==null?void 0:x.b64_json)?[`data:image/png;base64,${U(x==null?void 0:x.b64_json)}`]:[]}):[];return e.jsxs("div",{className:"rounded-lg border border-border/70 bg-surface/45 px-2.5 py-1.5 text-[11px]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[s.status==="running"?e.jsx("span",{className:"size-3.5 animate-pulse rounded-full border border-primary/70 motion-reduce:animate-none","aria-hidden":"true"}):n(s),e.jsx("span",{className:"font-medium text-foreground/85",children:s.label}),e.jsx("span",{className:"ml-auto opacity-70",children:c(s.status)})]}),s.detail?e.jsx("div",{className:"mt-1 break-words text-muted-foreground/80",children:s.detail}):null,u.length?e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:u.map((m,x)=>e.jsx("img",{src:m,alt:"Generated by Sway Router Assistant",className:"max-h-64 max-w-full rounded-lg border border-border object-contain"},`${s.id}-${x}`))}):null]},s.id)})})}),pn={plain:"text-[#d4d4d4]",comment:"text-[#6a9955] italic",string:"text-[#ce9178]",number:"text-[#b5cea8]",keyword:"text-[#c586c0]",function:"text-[#dcdcaa]",property:"text-[#9cdcfe]",constant:"text-[#569cd6]",operator:"text-[#d4d4d4]",punctuation:"text-[#808080]",command:"text-[#dcdcaa]",variable:"text-[#9cdcfe]",flag:"text-[#c586c0]"},fn=new Set(["as","async","await","break","case","catch","class","const","continue","def","default","delete","do","else","export","extends","finally","for","from","function","if","import","in","interface","implements","lambda","let","new","of","package","pass","private","public","raise","return","static","switch","throw","try","type","typeof","var","void","while","with","yield"]),hn=new Set(["false","null","none","nil","true","undefined","NaN","True","False","None"]);function xn(a){const r=a.toLowerCase().replace(/^language-/,""),n=["bash","console","powershell","ps","ps1","sh","shell","zsh"].includes(r),c=n||["dockerfile","py","python","rb","ruby","yaml","yml"].includes(r);return{normalized:r,shell:n,hashComments:c}}function gn(a,r){const{shell:n,hashComments:c}=xn(r),s=[];let o=0,u=!0;const h=(m,x="plain")=>{m&&s.push({text:m,kind:x})};for(;o<a.length;){const m=a.slice(o);if(/\s/.test(a[o])){const w=/^\s+/.exec(m),y=(w==null?void 0:w[0])||a[o];h(y),u=u&&/^\s+$/.test(y),o+=y.length;continue}if(m.startsWith("//")||m.startsWith("/*")||c&&m.startsWith("#")){h(m,"comment");break}if(a[o]==='"'||a[o]==="'"||a[o]==="`"){const w=a[o];let y=o+1;for(;y<a.length;){if(a[y]==="\\"){y+=2;continue}if(a[y]===w){y+=1;break}y+=1}h(a.slice(o,y),"string"),u=!1,o=y;continue}if(n){const w=/^\$(?:\{[A-Za-z_][\w]*\}|[A-Za-z_][\w]*)/.exec(m);if(w){h(w[0],"variable"),u=!1,o+=w[0].length;continue}const y=/^--?[A-Za-z][\w-]*/.exec(m);if(y){h(y[0],"flag"),u=!1,o+=y[0].length;continue}}const x=/^\b(?:0[xob][\da-f]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)\b/i.exec(m);if(x){h(x[0],"number"),u=!1,o+=x[0].length;continue}const S=/^[A-Za-z_$][\w$-]*/.exec(m);if(S){const w=S[0],y=a.slice(o+w.length).replace(/^\s+/,""),F=n&&u?"command":hn.has(w)?"constant":fn.has(w)?"keyword":y.startsWith("(")?"function":y.startsWith(":")?"property":"plain";h(w,F),u=!1,o+=w.length;continue}const C=/^[=!<>+\-*/%&|^~?:]+/.exec(m);if(C){h(C[0],"operator"),u=!1,o+=C[0].length;continue}h(a[o],/[()[\]{},.;]/.test(a[o])?"punctuation":"plain"),u=!1,o+=1}return s}function bn(a){const r=a.toLowerCase().replace(/^language-/,"");return{js:"JavaScript",jsx:"JSX",ts:"TypeScript",tsx:"TSX",py:"Python",sh:"Shell",bash:"Bash",ps1:"PowerShell",json:"JSON",yaml:"YAML",yml:"YAML",md:"Markdown",css:"CSS",html:"HTML"}[r]||r||"Code"}function yn({code:a,language:r}){const[n,c]=d.useState(!1),s=a.replace(/\n$/,"").split(`
|
|
1
|
+
import{d as mr,r as d,j as e}from"./react-vendor-xnYrwzsL.js";import{m as pe,A as rt}from"./motion-vendor-g5fpGzmJ.js";import{a as pr}from"./query-vendor-DVevaSVS.js";import{H as fr}from"./Header-DjeUJuR7.js";import{a as Ue,P as hr}from"./ProviderModelAccordion-Cuk2_DWf.js";import{E as xr,e as J,B as me,g as Ye,S as At,t as $,c as B,I as gr,D as Ct,m as Tt,n as _t,o as Mt,s as Et,q as Rt}from"./index-CkR38iPY.js";import{F as br,c as yr}from"./frame-CY26iHQE.js";import{b as qt}from"./api-keys-api-DVdIV17Y.js";import{p as wr,S as Xe,b as vr,r as jr,s as Nr,g as kr,M as Pt,i as Sr,a as Ar,f as Cr,c as Me,n as Ve,d as $t,e as Pe,h as Re,j as zt,k as Tr,l as _r,m as Dt,o as Mr,q as Er,t as Rr,u as nt,v as Pr,w as zr,x as Dr}from"./chatStudio-C0zPz_Z_.js";import{af as Qe,T as It,i as st,X as Ze,aJ as Lt,h as Ir,ay as Ee,ad as Bt,aK as Or,q as qr,ag as Ft,ap as $r,A as Lr,ah as Br,t as Fr,a as Jr,a0 as Kr,aB as Wr,r as Hr,C as Gr}from"./icons-vendor-CUx7SB5V.js";import{M as Ur,r as Yr}from"./markdown-vendor-BY8e1gQ8.js";import"./accordion-DovdZQJu.js";import"./ui-vendor-BuM9f2NY.js";const Xr={type:"object",properties:{},additionalProperties:!1},Vr=[{type:"function",function:{name:"router_overview",description:"Inspect the local Sway Router status. The result explicitly separates totalProviders (the unique union of built-in registry providers and custom provider nodes, including zero-connection providers), registeredProviderTypes, providerNodes, configuredProviders, activeProviders, inactiveOnlyProviders, connections, API keys, proxy pools, combos, admission load, and safe settings. When asked for the total number of providers, use totalProviders, not activeProviders or connectedProviders.",parameters:Xr}},{type:"function",function:{name:"router_models",description:"List models currently exposed by Sway Router, including provider and known capabilities such as vision, tools, reasoning, and image output.",parameters:{type:"object",properties:{query:{type:"string",description:"Optional model or provider filter."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum models to return."}},additionalProperties:!1}}},{type:"function",function:{name:"router_connections",description:"Inspect provider connection metadata without exposing API keys or OAuth tokens. Can filter by provider and active state.",parameters:{type:"object",properties:{provider:{type:"string",description:"Optional provider id or alias."},active_only:{type:"boolean",description:"Return only active connections."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum connections to return."}},additionalProperties:!1}}},{type:"function",function:{name:"router_api_keys",description:"Inspect gateway API key metadata and active/revoked counts. Never returns key secrets.",parameters:{type:"object",properties:{include_revoked:{type:"boolean"},limit:{type:"integer",minimum:1,maximum:100}},additionalProperties:!1}}},{type:"function",function:{name:"web_search",description:"Search the web and return bounded, normalized results. Use it when current or external information is needed.",parameters:{type:"object",properties:{query:{type:"string",description:"The web search query."},max_results:{type:"integer",minimum:1,maximum:8}},required:["query"],additionalProperties:!1}}},{type:"function",function:{name:"read_workspace",description:"Read the local workspace using safe read-only commands: pwd, ls/dir, cat/type, rg, and read-only git status/diff/log/show/branch.",parameters:{type:"object",properties:{command:{type:"string",description:"A safe read-only workspace command."}},required:["command"],additionalProperties:!1}}},{type:"function",function:{name:"curl",description:"Fetch a public HTTP(S) URL with a bounded GET or HEAD request. Private and loopback targets are blocked.",parameters:{type:"object",properties:{url:{type:"string",description:"Public http(s) URL."},method:{type:"string",enum:["GET","HEAD"]}},required:["url"],additionalProperties:!1}}},{type:"function",function:{name:"execute_javascript",description:"Run a short JavaScript diagnostic in the local workspace. This always requires explicit user approval before execution.",parameters:{type:"object",properties:{code:{type:"string",description:"JavaScript diagnostic code, maximum 6000 characters."}},required:["code"],additionalProperties:!1}}},{type:"function",function:{name:"generate_image",description:"Generate an image through an enabled Sway Router media provider. Use only when the user asks for an image and report clearly if media generation is not configured.",parameters:{type:"object",properties:{prompt:{type:"string",description:"Detailed image prompt."},provider:{type:"string",description:"Optional enabled media provider."},model:{type:"string",description:"Optional image model."},size:{type:"string",enum:["256x256","512x512","1024x1024"]},n:{type:"integer",minimum:1,maximum:4}},required:["prompt"],additionalProperties:!1}}}],Qr={router_overview:"Checking Router status",router_models:"Inspecting models",router_connections:"Inspecting connections",router_api_keys:"Inspecting API keys",web_search:"Searching the web",read_workspace:"Reading workspace",curl:"Fetching URL",execute_javascript:"Running JavaScript",generate_image:"Generating image"};function Zr(a){return Qr[a]||"Using agent tool"}async function G(a,r,n=""){const c={"Content-Type":"application/json",Accept:"application/json"};n.trim()&&(c.Authorization=`Bearer ${n.trim()}`);const s=await fetch(a,{method:"POST",credentials:"include",headers:c,body:JSON.stringify(r)}),o=await s.json().catch(()=>null);if(!s.ok){const u=o==null?void 0:o.error,h=typeof u=="string"?u:u&&typeof u=="object"&&typeof u.message=="string"?u.message:typeof(o==null?void 0:o.message)=="string"?o.message:`Tool request failed (${s.status})`;throw new Error(h)}return o??{ok:!0}}async function en(a,r,n={}){const c=n.apiKey||"";if(a==="router_overview")return G("/api/chat/tools/router",{action:"overview"},c);if(a==="router_models")return G("/api/chat/tools/router",{action:"models",query:r.query,limit:r.limit},c);if(a==="router_connections")return G("/api/chat/tools/router",{action:"connections",provider:r.provider,active_only:r.active_only,limit:r.limit},c);if(a==="router_api_keys")return G("/api/chat/tools/router",{action:"api_keys",include_revoked:r.include_revoked,limit:r.limit},c);if(a==="web_search")return G("/api/chat/tools/search",{query:r.query,max_results:r.max_results},c);if(a==="read_workspace")return G("/api/chat/tools/shell",{command:r.command},c);if(a==="curl")return G("/api/chat/tools/curl",{url:r.url,method:r.method},c);if(a==="generate_image")return G("/api/v1/images/generations",{prompt:r.prompt,provider:r.provider,model:r.model,size:r.size,n:r.n,response_format:"b64_json"},c);if(a==="execute_javascript"){const s=typeof r.code=="string"?r.code:"";if(!n.approve)throw new Error("JavaScript execution requires user approval");return await n.approve({name:"execute_javascript",code:s})?G("/api/chat/tools/shell",{mode:"execute",approved:!0,code:s},c):{ok:!1,denied:!0,error:"User denied JavaScript execution"}}throw new Error(`Unknown agent tool: ${a}`)}function tn(a,r=12e3){let n=a;if(n&&typeof n=="object")try{n=JSON.parse(JSON.stringify(n,(s,o)=>s==="b64_json"&&typeof o=="string"?`[image data omitted: ${o.length} bytes]`:s==="body"&&typeof o=="string"&&o.length>6e3?`${o.slice(0,6e3)}… [body truncated]`:o))}catch{n=String(n)}const c=typeof n=="string"?n:JSON.stringify(n);return c.length>r?`${c.slice(0,r)}… [tool result truncated]`:c}const Ot="sway-chat.lastModel",et="/dashboard/manage-apikey",rn="You are Sway Router Assistant, the capable internal agent of the Sway Router platform. Be a practical senior engineer and operator: understand the Router, inspect it when asked, use the right tools, solve problems step by step when useful, and explain what you found. When asked for the total number of providers, count the unique union of built-in registry providers and custom provider nodes, including providers with no connections; use router_overview.summary.totalProviders for that total and distinguish it from registeredProviderTypes, configuredProviders, activeProviders, and inactiveOnlyProviders. Never report activeProviders or connectedProviders as the total. Respond in the user's language, stay concise by default, ask a clarifying question when a request is underspecified, and use Markdown for readability. Format code in fenced blocks with the correct language and state uncertainty clearly instead of inventing facts.";async function nn(){const a=await qt().catch(()=>""),r={Accept:"application/json"};a&&(r.Authorization=`Bearer ${a}`);const n=await fetch("/v1/models",{credentials:"include",headers:r});if(!n.ok){const s=await n.json().catch(()=>null);throw new Error(nt((s==null?void 0:s.error)??(s==null?void 0:s.message))||`Models request failed (${n.status})`)}return((await n.json()).data??[]).flatMap(s=>{var h;const o=typeof s.id=="string"?s.id.trim():"";if(!o)return[];const u=typeof s.owned_by=="string"&&s.owned_by?s.owned_by:o.includes("/")?o.split("/",1)[0]:"other";return[{id:o,name:((h=s.name)==null?void 0:h.trim())||o,provider:u,capabilities:s.capabilities}]})}const sn=[0,90,180,90,180,270,180,270,360],on=["bg-white","bg-blue-200","bg-blue-400","bg-white/85","bg-blue-600","bg-white/70","bg-blue-300","bg-white/90","bg-primary"];function Jt({muted:a=!1}){return e.jsx("span",{className:"grid shrink-0 grid-cols-3 gap-[2px] p-0.5","aria-hidden":"true",children:sn.map((r,n)=>e.jsx("span",{className:B("size-1 rounded-[1px]",on[n],a?"opacity-25":"animate-chat-pixel motion-reduce:animate-none"),style:a?void 0:{animationDelay:`${r}ms`}},n))})}function Kt(a){const[r,n]=d.useState(()=>Dt(a.startAt));return d.useEffect(()=>{if(a.startAt==null||a.status!=="streaming")return;const c=()=>n(Dt(a.startAt));c();const s=window.setInterval(c,100);return()=>window.clearInterval(s)},[a.startAt,a.status]),r}const an=d.memo(function({message:r}){const n=Kt(r),c=$t({content:r.content,thinking:r.thinking}),s=c==="Thinking"?"Thinking…":c==="Writing"?"Writing…":c;return e.jsxs(pe.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},className:"inline-flex items-center gap-2 rounded-md py-1 text-[12px] text-muted-foreground","aria-label":`${s}${n>0?`, ${Pe(n)}`:""}`,role:"status","aria-live":"polite",children:[e.jsx(Jt,{}),e.jsx("span",{className:"animate-chat-shimmer bg-[length:200%_100%] bg-gradient-to-r from-muted-foreground via-foreground to-muted-foreground bg-clip-text font-medium text-transparent motion-reduce:animate-none",children:s}),e.jsx("span",{className:"font-mono tabular-nums opacity-60",children:Pe(n)})]})}),ln=d.memo(function({message:r,open:n,onToggle:c}){var w,y,F;const s=Kt(r),o=$t({content:r.content,thinking:r.thinking}),u=r.thoughtMs!=null?Pe(r.thoughtMs):"Thinking",h=!r.thinking&&(((w=r.streamUsage)==null?void 0:w.reasoning)??0)>0,m=(y=r.streamUsage)==null?void 0:y.reasoning,x=(r.thinking||"").split(/\r?\n+/).map(se=>se.replace(/^\s*(?:[-*•]|\d+[.)])\s*/,"").trim()).filter(Boolean).slice(-12),S=o==="Thinking"?"Thinking…":o==="Writing"?"Writing…":o,C=`thought-${r.id}`;return e.jsxs("div",{className:"mb-2 overflow-hidden rounded-xl border border-border/70 bg-muted/30",children:[e.jsxs("button",{type:"button",onClick:c,"aria-expanded":n,"aria-controls":C,className:"group flex min-h-9 w-full items-center gap-2 px-3 py-2 text-left text-xs text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground",children:[r.status==="streaming"?e.jsx(Jt,{}):e.jsx(Fr,{className:"size-3.5 shrink-0 text-muted-foreground/80","aria-hidden":"true"}),e.jsx("span",{className:B("min-w-0 truncate font-medium",r.status==="streaming"&&"animate-chat-shimmer bg-[length:200%_100%] bg-gradient-to-r from-muted-foreground via-foreground to-muted-foreground bg-clip-text text-transparent motion-reduce:animate-none"),children:r.status==="streaming"?S:`Thought for ${u}`}),r.status==="streaming"?e.jsx("span",{className:"shrink-0 font-mono text-[10px] tabular-nums opacity-60",children:Pe(s)}):null,m!=null&&m>0?e.jsxs("span",{className:"shrink-0 rounded border border-border/70 bg-surface px-1.5 py-0.5 font-mono text-[10px] tabular-nums",children:[Re(m)," reasoning"]}):null,e.jsx(st,{className:B("size-3.5 shrink-0 transition-transform duration-200",!n&&"-rotate-90"),"aria-hidden":"true"})]}),e.jsx(rt,{initial:!1,children:n?e.jsx(pe.div,{id:C,initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:"easeOut"},className:"overflow-hidden border-t border-border/60 bg-background/20",children:e.jsxs("div",{className:"px-3 pb-3 pt-2 text-xs leading-relaxed text-muted-foreground",children:[(F=r.toolActivity)!=null&&F.length?e.jsx(mn,{activities:r.toolActivity}):null,x.length>1?e.jsx("ol",{className:"max-h-48 space-y-2 overflow-y-auto pr-1",children:x.map((se,oe)=>{const X=r.status==="streaming"&&oe===x.length-1;return e.jsxs("li",{className:"relative flex items-start gap-2",children:[e.jsx("span",{className:B("mt-1.5 size-1.5 shrink-0 rounded-full",X?"animate-pulse bg-amber-300 motion-reduce:animate-none":"bg-emerald-400"),"aria-hidden":"true"}),e.jsx("span",{className:B("min-w-0 break-words",X&&"text-foreground"),children:se})]},`${se}-${oe}`)})}):r.thinking?e.jsx("div",{className:"max-h-48 overflow-y-auto whitespace-pre-wrap break-words",children:r.thinking}):null,h?e.jsx("div",{className:"text-muted-foreground/70",children:"This model used hidden reasoning tokens, but did not return the reasoning text."}):null]})}):null})]})},(a,r)=>a.message===r.message&&a.open===r.open);function be({label:a,value:r,title:n}){return e.jsx(J,{label:n,children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-border/70 bg-surface/60 px-2 py-1",children:[e.jsx("span",{className:"text-muted-foreground/75",children:a}),e.jsx("span",{className:"font-medium text-foreground/85",children:r})]})})}const cn=d.memo(function({message:r}){const n=r.streamUsage,c=n!=null&&(n.cached!=null||n.cacheCreation!=null),s=n!=null&&(n.prompt!=null||n.completion!=null||n.reasoning!=null||c);return r.ttfbMs==null&&r.durationMs==null&&!s?null:e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-[11px] tabular-nums text-muted-foreground",children:[r.ttfbMs!=null?e.jsx(be,{label:"Response starts",value:zt(r.ttfbMs),title:"Time until the model starts sending the answer."}):null,r.durationMs!=null?e.jsx(be,{label:"Completed in",value:zt(r.durationMs),title:"Total time from sending your message until the answer finished."}):null,s&&(n==null?void 0:n.completion)!=null?e.jsx(be,{label:"Answer length",value:`${Re(n.completion)} tokens`,title:"Tokens generated in the answer."}):null,c&&(n==null?void 0:n.cached)!=null&&n.cached>0?e.jsx(be,{label:"Cache read",value:`${Re(n.cached)} tokens`,title:"Input tokens served from the provider's prompt cache, which can reduce latency and cost."}):null,c&&(n==null?void 0:n.cacheCreation)!=null&&n.cacheCreation>0?e.jsx(be,{label:"Cache written",value:`${Re(n.cacheCreation)} tokens`,title:"Input tokens written to the provider's prompt cache for later requests."}):null]})});function Y(a){return a&&typeof a=="object"?a:null}function U(a){return typeof a=="string"?a:""}function tt(a,r){Array.isArray(r)&&r.forEach((n,c)=>{const s=Y(n);if(!s)return;const o=Number(s.index),u=Number.isInteger(o)&&o>=0?o:c,h=a.get(u)||{id:`call_${u}`,type:"function",function:{name:"",arguments:""}},m=Y(s.function),x=U((m==null?void 0:m.name)??s.name),S=(m==null?void 0:m.arguments)??s.arguments,C=typeof S=="string"?S:S==null?"":JSON.stringify(S);U(s.id)&&(h.id=U(s.id)),U(s.type)&&(h.type=U(s.type)),x&&(h.function.name=x),C&&(h.function.arguments+=C),a.set(u,h)})}function dn(a,r){const n=Y(a),c=Array.isArray(n==null?void 0:n.choices)?Y(n.choices[0]):null,s=Y(c==null?void 0:c.delta),o=Y(c==null?void 0:c.message);tt(r,s==null?void 0:s.tool_calls),tt(r,o==null?void 0:o.tool_calls),tt(r,n==null?void 0:n.tool_calls)}function un(a){const r=Y(a);if(!r)return String(a??"");if(r.denied===!0)return"Execution denied";if(r.error)return String(r.error).slice(0,280);if(Array.isArray(r.data))return`${r.data.length} image${r.data.length===1?"":"s"} returned`;if(typeof r.output=="string")return r.output.slice(0,280);if(typeof r.body=="string")return r.body.slice(0,280);if(r.summary&&typeof r.summary=="object")try{return JSON.stringify(r.summary).slice(0,280)}catch{}try{return JSON.stringify(r).slice(0,280)}catch{return"Tool completed"}}const mn=d.memo(function({activities:r}){if(!(r!=null&&r.length))return null;const n=s=>s.status==="error"?e.jsx(Jr,{className:"size-3.5 text-destructive","aria-hidden":"true"}):s.status==="denied"?e.jsx(Lt,{className:"size-3.5 text-amber-300","aria-hidden":"true"}):s.name==="web_search"||s.name==="curl"?e.jsx(Kr,{className:"size-3.5 text-sky-300","aria-hidden":"true"}):s.name==="generate_image"?e.jsx(Wr,{className:"size-3.5 text-fuchsia-300","aria-hidden":"true"}):s.name==="execute_javascript"||s.name==="read_workspace"?e.jsx(Hr,{className:"size-3.5 text-emerald-300","aria-hidden":"true"}):e.jsx(Gr,{className:"size-3.5 text-emerald-300","aria-hidden":"true"}),c=s=>s==="running"?"Running":s==="done"?"Done":s==="denied"?"Denied":"Failed";return e.jsx("div",{className:"mb-2 space-y-1.5","aria-label":"Sway Router Assistant activity",children:r.map(s=>{var h;const o=s.name==="generate_image"&&((h=Y(s.result))==null?void 0:h.data),u=Array.isArray(o)?o.flatMap(m=>{const x=Y(m);return U(x==null?void 0:x.url)?[U(x==null?void 0:x.url)]:U(x==null?void 0:x.b64_json)?[`data:image/png;base64,${U(x==null?void 0:x.b64_json)}`]:[]}):[];return e.jsxs("div",{className:"rounded-lg border border-border/70 bg-surface/45 px-2.5 py-1.5 text-[11px]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[s.status==="running"?e.jsx("span",{className:"size-3.5 animate-pulse rounded-full border border-primary/70 motion-reduce:animate-none","aria-hidden":"true"}):n(s),e.jsx("span",{className:"font-medium text-foreground/85",children:s.label}),e.jsx("span",{className:"ml-auto opacity-70",children:c(s.status)})]}),s.detail?e.jsx("div",{className:"mt-1 break-words text-muted-foreground/80",children:s.detail}):null,u.length?e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:u.map((m,x)=>e.jsx("img",{src:m,alt:"Generated by Sway Router Assistant",className:"max-h-64 max-w-full rounded-lg border border-border object-contain"},`${s.id}-${x}`))}):null]},s.id)})})}),pn={plain:"text-[#d4d4d4]",comment:"text-[#6a9955] italic",string:"text-[#ce9178]",number:"text-[#b5cea8]",keyword:"text-[#c586c0]",function:"text-[#dcdcaa]",property:"text-[#9cdcfe]",constant:"text-[#569cd6]",operator:"text-[#d4d4d4]",punctuation:"text-[#808080]",command:"text-[#dcdcaa]",variable:"text-[#9cdcfe]",flag:"text-[#c586c0]"},fn=new Set(["as","async","await","break","case","catch","class","const","continue","def","default","delete","do","else","export","extends","finally","for","from","function","if","import","in","interface","implements","lambda","let","new","of","package","pass","private","public","raise","return","static","switch","throw","try","type","typeof","var","void","while","with","yield"]),hn=new Set(["false","null","none","nil","true","undefined","NaN","True","False","None"]);function xn(a){const r=a.toLowerCase().replace(/^language-/,""),n=["bash","console","powershell","ps","ps1","sh","shell","zsh"].includes(r),c=n||["dockerfile","py","python","rb","ruby","yaml","yml"].includes(r);return{normalized:r,shell:n,hashComments:c}}function gn(a,r){const{shell:n,hashComments:c}=xn(r),s=[];let o=0,u=!0;const h=(m,x="plain")=>{m&&s.push({text:m,kind:x})};for(;o<a.length;){const m=a.slice(o);if(/\s/.test(a[o])){const w=/^\s+/.exec(m),y=(w==null?void 0:w[0])||a[o];h(y),u=u&&/^\s+$/.test(y),o+=y.length;continue}if(m.startsWith("//")||m.startsWith("/*")||c&&m.startsWith("#")){h(m,"comment");break}if(a[o]==='"'||a[o]==="'"||a[o]==="`"){const w=a[o];let y=o+1;for(;y<a.length;){if(a[y]==="\\"){y+=2;continue}if(a[y]===w){y+=1;break}y+=1}h(a.slice(o,y),"string"),u=!1,o=y;continue}if(n){const w=/^\$(?:\{[A-Za-z_][\w]*\}|[A-Za-z_][\w]*)/.exec(m);if(w){h(w[0],"variable"),u=!1,o+=w[0].length;continue}const y=/^--?[A-Za-z][\w-]*/.exec(m);if(y){h(y[0],"flag"),u=!1,o+=y[0].length;continue}}const x=/^\b(?:0[xob][\da-f]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)\b/i.exec(m);if(x){h(x[0],"number"),u=!1,o+=x[0].length;continue}const S=/^[A-Za-z_$][\w$-]*/.exec(m);if(S){const w=S[0],y=a.slice(o+w.length).replace(/^\s+/,""),F=n&&u?"command":hn.has(w)?"constant":fn.has(w)?"keyword":y.startsWith("(")?"function":y.startsWith(":")?"property":"plain";h(w,F),u=!1,o+=w.length;continue}const C=/^[=!<>+\-*/%&|^~?:]+/.exec(m);if(C){h(C[0],"operator"),u=!1,o+=C[0].length;continue}h(a[o],/[()[\]{},.;]/.test(a[o])?"punctuation":"plain"),u=!1,o+=1}return s}function bn(a){const r=a.toLowerCase().replace(/^language-/,"");return{js:"JavaScript",jsx:"JSX",ts:"TypeScript",tsx:"TSX",py:"Python",sh:"Shell",bash:"Bash",ps1:"PowerShell",json:"JSON",yaml:"YAML",yml:"YAML",md:"Markdown",css:"CSS",html:"HTML"}[r]||r||"Code"}function yn({code:a,language:r}){const[n,c]=d.useState(!1),s=a.replace(/\n$/,"").split(`
|
|
2
2
|
`),o=String(s.length).length;async function u(){try{await navigator.clipboard.writeText(a),c(!0),window.setTimeout(()=>c(!1),1400)}catch{}}return e.jsxs("div",{className:"my-3 min-w-0 max-w-full overflow-hidden rounded-xl border border-[#2d2d30] bg-[#1e1e1e]",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-[#2d2d30] bg-[#181818] px-3 py-1.5 text-[10px] text-[#858585]",children:[e.jsx("span",{className:"font-mono uppercase tracking-wide",children:bn(r)}),e.jsx(J,{label:n?"Copied":"Copy code",children:e.jsxs("button",{type:"button",onClick:()=>void u(),className:"inline-flex items-center gap-1 rounded-md px-1.5 py-1 transition-colors hover:bg-white/[0.08] hover:text-[#d4d4d4]","aria-label":"Copy code",children:[n?e.jsx(Ft,{className:"size-3"}):e.jsx(Bt,{className:"size-3"}),n?"Copied":"Copy"]})})]}),e.jsx("pre",{className:"min-w-0 max-w-full overflow-x-auto p-3 font-mono text-[12px] leading-relaxed text-[#d4d4d4]",children:e.jsx("code",{children:s.map((h,m)=>e.jsxs("span",{className:"block min-h-[1.5em]",children:[e.jsx("span",{className:"mr-4 inline-block select-none text-right text-[#858585]",style:{width:`${o}ch`},children:m+1}),gn(h,r).map((x,S)=>e.jsx("span",{className:pn[x.kind],children:x.text},`${m}-${S}`))]},m))})})]})}function wn(a){const r=a.split(/\r?\n/);let n=null;for(const c of r){const s=/^\s*(`{3,}|~{3,})(.*)$/.exec(c);if(!s)continue;const o=s[1],u=o[0],h=s[2].trim();if(!n){n={marker:u,length:o.length};continue}u===n.marker&&h===""&&o.length>=n.length&&(n=null)}return n?`${a}${a.endsWith(`
|
|
3
3
|
`)?"":`
|
|
4
4
|
`}${n.marker.repeat(n.length)}`:a}const vn=d.memo(function({content:r,streaming:n=!1}){const c=n?wn(r):r;return e.jsx("div",{className:B("prose-chat min-w-0 max-w-full",n&&"prose-chat-streaming"),children:e.jsx(Ur,{remarkPlugins:[Yr],components:{code({className:s,children:o,...u}){return/language-/.test(s||"")?e.jsx("code",{className:B("font-mono",s),...u,children:o}):e.jsx("code",{className:"rounded bg-surface px-1 py-0.5 font-mono text-[0.85em]",...u,children:o})},pre({children:s}){var x,S;const o=Array.isArray(s)?s[0]:s,u=((x=o==null?void 0:o.props)==null?void 0:x.className)||"",h=/language-([\w-]+)/.exec(u),m=String(((S=o==null?void 0:o.props)==null?void 0:S.children)??"");return e.jsx(yn,{code:m,language:(h==null?void 0:h[1])||""})}},children:c||""})})});function Dn(){const a=mr(),[r]=d.useState(()=>{try{return wr(window.localStorage.getItem(Xe))}catch{return null}}),[n,c]=d.useState((r==null?void 0:r.model)||""),s=vr(rn,n),[o,u]=d.useState((r==null?void 0:r.messages)||[]),h=d.useRef(!1),m=d.useRef(null),x=d.useRef(!1),S=d.useRef(!1),[C,w]=d.useState("checking"),y=pr({queryKey:["sway-chat","models"],queryFn:nn,enabled:C!=="checking",staleTime:0,refetchOnMount:"always",retry:2,retryDelay:t=>Math.min(1e3*2**t,4e3)}),[F,se]=d.useState([]);d.useEffect(()=>{if(!y.data)return;if(se(y.data),!y.data.length){c("");return}let t="";try{t=window.localStorage.getItem(Ot)||""}catch{}if(S.current)return;const i=jr(n||t,y.data);c(i)},[y.data,n]);const[oe,X]=d.useState(""),[V,fe]=d.useState([]),ae=d.useRef(null),[Wt,Ht]=d.useState(()=>new Set),Gt=d.useCallback(t=>Ht(i=>{const l=new Set(i);return l.has(t)?l.delete(t):l.add(t),l}),[]),[ye,we]=d.useState(!1),[ze,ie]=d.useState(""),[ot,at]=d.useState(null),D=d.useRef(null),[ve,Ut]=d.useState(""),[te,je]=d.useState(!1),[he,it]=d.useState(""),[Ne,De]=d.useState(null),[Ie,Yt]=d.useState(null),[Xt,ke]=d.useState(!1),I=d.useRef(null),Oe=d.useRef(null),lt=d.useRef(null),qe=d.useRef(null),re=d.useRef(null),$e=d.useRef(!1),[Le,ct]=d.useState(!0),Se=d.useRef(null);d.useEffect(()=>{h.current=!0},[]),d.useEffect(()=>{if(h.current){if(m.current!==null&&window.clearTimeout(m.current),x.current){x.current=!1;return}return m.current=window.setTimeout(()=>{const t=Nr({model:n,systemPrompt:s,messages:o});if(t)try{window.localStorage.setItem(Xe,t)}catch{}m.current=null},700),()=>{m.current!==null&&window.clearTimeout(m.current)}}},[o,n,s]),d.useEffect(()=>()=>{var t,i;(t=I.current)==null||t.abort(),(i=D.current)==null||i.call(D,!1),D.current=null,m.current!==null&&window.clearTimeout(m.current)},[]),d.useEffect(()=>{let t=!1;return(async()=>{let i=!1;try{const l=await xr();if(t)return;Yt(l),i=!!l.requireApiKey;const b=await qt().catch(()=>"");if(t)return;b?(Ut(b),w("ready")):w(i?"blocked":"ready")}catch{t||w(i?"blocked":"ready")}})(),()=>{t=!0}},[]);const Be=d.useCallback((t="auto")=>{const i=qe.current;if(!i)return;const l=Math.max(0,i.scrollHeight-i.clientHeight);t==="auto"?Math.abs(i.scrollTop-l)>1&&(i.scrollTop=l):i.scrollTo({top:l,behavior:t})},[]);d.useEffect(()=>{if(Le){if($e.current){$e.current=!1;return}return re.current!==null&&window.cancelAnimationFrame(re.current),re.current=window.requestAnimationFrame(()=>{re.current=null,Be()}),()=>{re.current!==null&&(window.cancelAnimationFrame(re.current),re.current=null)}}},[o,ze,Le,Be]);const Vt=d.useCallback(()=>{const t=qe.current;if(!t)return;const i=t.scrollHeight-t.scrollTop-t.clientHeight<96;ct(l=>l===i?l:i)},[]);d.useEffect(()=>{if(!te)return;function t(l){Oe.current&&!Oe.current.contains(l.target)&&je(!1)}function i(l){l.key==="Escape"&&je(!1)}return document.addEventListener("mousedown",t),document.addEventListener("keydown",i),()=>{document.removeEventListener("mousedown",t),document.removeEventListener("keydown",i)}},[te]),d.useEffect(()=>{te&&(it(""),requestAnimationFrame(()=>{var t;return(t=lt.current)==null?void 0:t.focus()}))},[te]);const le=d.useMemo(()=>{if(F.some(i=>i.id===n)||!n)return F;const t=n.split("/");return[...F,{id:n,name:t[t.length-1]||n,provider:n.includes("/")?t[0]:"other"}]},[F,n]),E=d.useMemo(()=>le.find(t=>t.id===n),[le,n]),Qt=d.useMemo(()=>kr(le.filter(t=>t.id!==n),he),[le,n,he]),Fe=!ye&&!!n&&(oe.trim().length>0||V.length>0);function O(t,i){u(l=>l.map(b=>b.id===t?{...b,...i}:b))}function Zt(t){t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,128)}px`}const er=d.useCallback(t=>new Promise(i=>{var l;(l=D.current)==null||l.call(D,!1),D.current=i,at(t)}),[]);function Je(t){var i;(i=D.current)==null||i.call(D,t),D.current=null,at(null)}async function dt(t){var k;if(!t)return;if(((k=E==null?void 0:E.capabilities)==null?void 0:k.vision)===!1){$.error("The selected model does not support image input. Choose a vision-capable model first."),ae.current&&(ae.current.value="");return}const i=Array.from(t);if(V.length+i.length>Pt){$.error(`Max ${Pt} images per message`);return}const l=[];let b=V.reduce((p,R)=>p+R.size,0);for(const p of i){if(!Sr(p)){$.error(`"${p.name}" must be an image ≤ 2MB`);continue}if(b+p.size>Ar){$.error("Images in one message must stay under 4MB total");continue}const R=await Cr(p);l.push({id:Me(),name:p.name,size:p.size,url:R,mime:p.type}),b+=p.size}fe(p=>[...p,...l]),ae.current&&(ae.current.value="")}function tr(t){fe(i=>i.filter(l=>l.id!==t))}function rr(t){const i=Array.from(t.clipboardData.items).filter(l=>l.kind==="file"&&l.type.startsWith("image/")).map(l=>l.getAsFile()).filter(l=>!!l);i.length!==0&&(t.preventDefault(),dt(i))}function nr(t){t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),Fe&&ft())}function sr(){var t;(t=I.current)==null||t.abort()}function or(){var t;(t=I.current)==null||t.abort(),Je(!1),m.current!==null&&window.clearTimeout(m.current),x.current=!0;try{window.localStorage.removeItem(Xe)}catch{}u([]),ie(""),ke(!1)}function ut(t){S.current=!0,c(t);try{window.localStorage.setItem(Ot,t)}catch{}je(!1)}async function mt(t,i,l,b,k,p=[],R=!0){var kt,St;const v={"Content-Type":"application/json",Accept:"text/event-stream"};ve.trim()&&(v.Authorization=`Bearer ${ve.trim()}`);const j=Mr(t,l,p),A={model:b,messages:j,stream:!0,stream_options:{include_usage:!0}};R&&(A.tools=Vr,A.tool_choice="auto");const ce=JSON.stringify(A);if(Er(ce)>Rr)throw new Error("Chat context is too large for the gateway. Remove older images or start a new conversation.");const de=await fetch("/v1/chat/completions",{method:"POST",headers:v,body:ce,signal:k??((kt=I.current)==null?void 0:kt.signal)});if(!de.ok){const g=await de.json().catch(()=>null);throw new Error(nt((g==null?void 0:g.error)??(g==null?void 0:g.message))||`Request failed (${de.status})`)}const Ce=(St=de.body)==null?void 0:St.getReader();if(!Ce)throw new Error("Streaming is not supported by this browser");const xe=new TextDecoder;let Q="",K="",W="",q,P,Z=!1,ee=!1,ge=!1;const ue=new Map;let f,z=null,M=!1;const H=Date.now(),L=g=>Date.now()-g,ht=()=>{const g={content:K};W&&(g.thinking=W),f&&(g.streamUsage=f),q!=null&&(g.ttfbMs=q),P!=null&&(g.thoughtMs=P),O(i.id,g)},xt=()=>{z!==null&&(window.clearTimeout(z),z=null),M||ht()},cr=()=>{z!==null||M||(z=window.setTimeout(()=>{z=null,M||ht()},50))},gt=()=>{document.hidden||xt()},Te=()=>{M=!0,z!==null&&(window.clearTimeout(z),z=null),document.removeEventListener("visibilitychange",gt)};document.addEventListener("visibilitychange",gt);const dr=g=>{var _;if(!g||typeof g!="object")return!1;const T=g;return Array.isArray(T.choices)&&T.choices.some(N=>N&&N.finish_reason!=null)||Array.isArray(T.candidates)&&T.candidates.some(N=>N&&(N.finishReason!=null||N.finish_reason!=null))||((_=T.delta)==null?void 0:_.stop_reason)!=null||T.stop_reason!=null?!0:["message_stop","response.completed","response.failed","response.incomplete"].includes(String(T.type||""))},ne=[],bt=g=>{const T=g.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as o,j as e,d as rs}from"./react-vendor-xnYrwzsL.js";import{u as as,b as ns,a as W}from"./query-vendor-DVevaSVS.js";import{H as ls}from"./Header-
|
|
1
|
+
import{r as o,j as e,d as rs}from"./react-vendor-xnYrwzsL.js";import{u as as,b as ns,a as W}from"./query-vendor-DVevaSVS.js";import{H as ls}from"./Header-DjeUJuR7.js";import{S as is}from"./StatusBadge-iBeqU7Qd.js";import{C as os}from"./copy-button-CCsXIvkJ.js";import{u as ds,n as cs,F as ms,f as We,S as Z,a as us,g as He,b as xs}from"./currency-api-CHfn9Y-I.js";import{c as f,p as ps,e as v,B as P,I as hs,S as fs,h as xe,D as gs,m as bs,n as js,o as vs,s as ys,G as Ns,i as ws,H as $e}from"./index-CkR38iPY.js";import{ag as ks,ad as Ss,a8 as le,a9 as $,af as Cs,as as Ds,at as zs,q as Ps,X as qs,ab as As,A as _s,au as Ue,av as Ls,T as Rs,aw as Es}from"./icons-vendor-CUx7SB5V.js";import{D as Is,q as Ms,w as Os,x as Fs,r as Hs,t as $s,v as Us}from"./ui-vendor-BuM9f2NY.js";import{F as U,c as X,b as T,a as Ts,d as Bs}from"./frame-CY26iHQE.js";import{S as Qs}from"./segmented-CxobJihW.js";import{A as Ks,a as Vs,b as Gs,c as Js}from"./accordion-DovdZQJu.js";import{S as pe,a as he,d as fe,b as ge,c as Y}from"./select-DfWoWPVg.js";import{S as B}from"./skeleton-81lPHspy.js";import{T as Ws,a as Zs,b as ie,c as q,d as Xs,e as w}from"./table-CEyzPvr7.js";import{l as Ys}from"./admin-extras-api-5xk7DmbO.js";import{p as oe}from"./live-mode-CHShLY4E.js";import"./ripple-button-BrLlmKvT.js";import"./motion-vendor-g5fpGzmJ.js";const Te={python:"Python",typescript:"TypeScript",javascript:"JavaScript",go:"Go",curl:"cURL",bash:"Shell",php:"PHP",ruby:"Ruby",json:"JSON",text:"Plain text"},et={python:"example.py",typescript:"example.ts",javascript:"example.js",go:"main.go",curl:"request.sh",bash:"script.sh",php:"example.php",ruby:"example.rb",json:"payload.json"};function st(t,n){if(n==="text")return[t];const i=[];n==="python"?i.push({re:/(#.*)$/g,cls:"text-zinc-500"},{re:/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g,cls:"text-emerald-400"},{re:/\b(from|import|as|def|class|return|if|elif|else|for|while|with|try|except|raise|True|False|None|print|await|async|yield|lambda|pass|in|not|and|or)\b/g,cls:"text-violet-400"},{re:/\b(self|cls)\b/g,cls:"text-sky-400"},{re:/\b(\d+\.?\d*)\b/g,cls:"text-amber-400"}):n==="typescript"||n==="javascript"?i.push({re:/(\/\/.*)$/g,cls:"text-zinc-500"},{re:/(`(?:\\.|[^`\\])*`|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g,cls:"text-emerald-400"},{re:/\b(import|from|export|const|let|var|function|async|await|return|if|else|for|while|class|new|typeof|interface|type|extends|implements|true|false|null|undefined|of|in)\b/g,cls:"text-violet-400"},{re:/\b(console|OpenAI|Anthropic)\b/g,cls:"text-sky-400"},{re:/\b(\d+\.?\d*)\b/g,cls:"text-amber-400"}):n==="go"?i.push({re:/(\/\/.*)$/g,cls:"text-zinc-500"},{re:/(`(?:\\.|[^`\\])*`|"(?:\\.|[^"\\])*")/g,cls:"text-emerald-400"},{re:/\b(package|import|func|return|if|else|for|range|var|const|type|struct|map|defer|go|chan|select|case|default|true|false|nil|err|error|string|int|int64|any)\b/g,cls:"text-violet-400"},{re:/\b(fmt|http|json|io|bytes)\b/g,cls:"text-sky-400"},{re:/\b(\d+\.?\d*)\b/g,cls:"text-amber-400"}):n==="curl"||n==="bash"?i.push({re:/(#.*)$/g,cls:"text-zinc-500"},{re:/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g,cls:"text-emerald-400"},{re:/\b(curl|echo|export|cd|npm|pip|go|php|ruby)\b/g,cls:"text-violet-400"},{re:/(^|\s)(-[A-Za-z][A-Za-z0-9-]*)\b/g,cls:"text-sky-400"}):n==="php"?i.push({re:/(\/\/.*|#.*)$/g,cls:"text-zinc-500"},{re:/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g,cls:"text-emerald-400"},{re:/\b(function|return|echo|true|false|null|array|new|class|public|private|protected|use|namespace|if|else|foreach|as)\b/g,cls:"text-violet-400"},{re:/(\$[\w]+)/g,cls:"text-sky-400"},{re:/\b(\d+\.?\d*)\b/g,cls:"text-amber-400"}):n==="ruby"?i.push({re:/(#.*)$/g,cls:"text-zinc-500"},{re:/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g,cls:"text-emerald-400"},{re:/\b(require|def|end|do|if|else|elsif|unless|class|module|return|true|false|nil|puts|print|new|each)\b/g,cls:"text-violet-400"},{re:/(:[\w]+)/g,cls:"text-amber-400"},{re:/\b(\d+\.?\d*)\b/g,cls:"text-amber-400"}):n==="json"&&i.push({re:/("(?:\\.|[^"\\])*")(\s*:)/g,cls:"text-sky-400"},{re:/("(?:\\.|[^"\\])*")/g,cls:"text-emerald-400"},{re:/\b(true|false|null)\b/g,cls:"text-violet-400"},{re:/\b(-?\d+\.?\d*)\b/g,cls:"text-amber-400"});const u=[];for(const{re:d,cls:h}of i){d.lastIndex=0;let y;const D=new RegExp(d.source,d.flags.includes("g")?d.flags:d.flags+"g");for(;(y=D.exec(t))!==null;){const _=y[0];let b=y.index,j=_;if(n==="curl"||n==="bash"){const k=y[2]??y[1];k&&_.indexOf(k)>=0&&/^-\w/.test(k)&&(b=y.index+_.lastIndexOf(k),j=k)}const r=b+j.length;!u.some(k=>!(r<=k.start||b>=k.end))&&j.length&&u.push({start:b,end:r,cls:h,text:j})}}u.sort((d,h)=>d.start-h.start);const C=[];let g=0;return u.forEach((d,h)=>{d.start>g&&C.push(t.slice(g,d.start)),C.push(e.jsx("span",{className:d.cls,children:d.text},`${h}-${d.start}`)),g=d.end}),g<t.length&&C.push(t.slice(g)),C.length?C:[t]}function tt({code:t,language:n="text",filename:i,className:u,showLineNumbers:C=!0}){const[g,d]=o.useState(!1),h=o.useMemo(()=>t.replace(/\n$/,"").split(`
|
|
2
2
|
`),[t]),y=i??et[n]??Te[n],D=String(h.length).length;async function _(){try{await navigator.clipboard.writeText(t),d(!0),window.setTimeout(()=>d(!1),1500)}catch{}}return e.jsxs("div",{className:f("group relative flex h-[min(20rem,45vh)] w-full min-w-0 max-w-full flex-col overflow-hidden rounded-xl border border-white/10","bg-[#0b0d12]",u),children:[e.jsxs("div",{className:"relative z-10 flex items-center gap-3 border-b border-white/10 bg-white/[0.03] px-3 py-2 sm:px-3.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5","aria-hidden":!0,children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-border"}),e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/50"}),e.jsx("span",{className:"h-2 w-2 rounded-full bg-primary/70"})]}),e.jsx("div",{className:"min-w-0 flex-1 truncate text-center font-mono text-[11px] text-zinc-400 sm:text-xs",children:y}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"hidden rounded-md border border-white/10 bg-white/[0.04] px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-wide text-zinc-500 sm:inline",children:Te[n]}),e.jsxs("button",{type:"button",onClick:_,className:f("inline-flex h-7 items-center gap-1.5 rounded-md border border-white/10 bg-white/[0.04] px-2","font-mono text-[11px] text-zinc-300 transition-colors","hover:bg-white/[0.08] hover:text-white","focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-white/20"),"aria-label":"Copy code",children:[g?e.jsx(ks,{className:"h-3 w-3 text-emerald-400"}):e.jsx(Ss,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:g?"Copied":"Copy"})]})]})]}),e.jsx("div",{className:"relative z-10 min-h-0 flex-1 overflow-auto",children:e.jsx("pre",{className:"m-0 p-0 font-mono text-[12px] leading-[1.65] text-zinc-200 sm:text-[12.5px]",children:e.jsx("code",{className:"block min-w-full py-3",children:h.map((b,j)=>e.jsxs("div",{className:"flex px-0 hover:bg-white/[0.03]",children:[C?e.jsx("span",{className:"sticky left-0 select-none bg-[#0b0d12]/80 pl-3 pr-3 text-right text-zinc-600 backdrop-blur-[2px] sm:pl-4",style:{minWidth:`${D+2.5}ch`},"aria-hidden":!0,children:j+1}):e.jsx("span",{className:"w-3 shrink-0 sm:w-4","aria-hidden":!0}),e.jsx("span",{className:"flex-1 whitespace-pre pr-4 text-zinc-200",children:b.length?st(b,n):`
|
|
3
3
|
`})]},j))})})})]})}const rt=Is;function at({className:t,children:n,variant:i="inset",...u}){return e.jsxs(Ms,{children:[e.jsx(Os,{className:"fixed inset-0 z-50 bg-black/32 backdrop-blur-sm transition-opacity data-ending-style:opacity-0 data-starting-style:opacity-0"}),e.jsx(Fs,{className:"fixed inset-0 z-50 flex justify-end p-0 sm:p-3",children:e.jsx(Hs,{className:f("relative flex h-full min-h-0 w-full min-w-0 max-w-2xl flex-col overflow-hidden border bg-popover text-popover-foreground outline-none transition-[translate,opacity] duration-200 ease-out data-ending-style:translate-x-full data-ending-style:opacity-0 data-starting-style:translate-x-full data-starting-style:opacity-0 sm:rounded-2xl sm:border",i==="inset"&&"sm:h-[calc(100vh-1.5rem)] sm:max-h-[calc(100vh-1.5rem)]",t),...u,children:n})})]})}function nt({className:t,...n}){return e.jsx("div",{className:f("shrink-0 border-b border-border/70 px-6 py-5",t),...n})}function lt({className:t,...n}){return e.jsx($s,{className:f("font-heading text-xl font-semibold leading-none",t),...n})}function it({className:t,...n}){return e.jsx(Us,{className:f("mt-2 text-sm text-muted-foreground",t),...n})}function ot({className:t,...n}){return e.jsx("div",{className:f("min-h-0 flex-1 overflow-y-auto overflow-x-hidden px-6 py-5",t),...n})}function dt(t,n){const i=Number.isFinite(t)?Math.max(1,Math.floor(t)):1,u=Math.max(1,Math.floor((n==null?void 0:n.totalPages)??1));return{safePage:n?Math.min(i,u):i,totalPages:u}}function ct(t,n,i){return!n||i?!1:t>Math.max(1,Math.floor(n.totalPages))}const Q="all",mt=[{value:"today",label:"Today"},{value:"24h",label:"24h"},{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"1y",label:"1y"}],Be={today:"Today","24h":"Last 24 hours","7d":"Last 7 days","30d":"Last 30 days","90d":"Last 90 days","1y":"Last 1 year"},ve=[{value:"today",label:"Today"},{value:"24h",label:"Last 24 hours"},{value:"7d",label:"Last 7 days"},{value:"30d",label:"Last 30 days"},{value:"90d",label:"Last 90 days"},{value:"1y",label:"Last 1 year"},{value:"all",label:"All time"}],Qe=Object.fromEntries(ve.map(t=>[t.value,t.label])),ut=12;function xt(t){switch(t){case"today":{const n=new Date;return n.setHours(0,0,0,0),n.getTime()}case"24h":return Date.now()-1440*60*1e3;case"7d":return Date.now()-7*864e5;case"30d":return Date.now()-30*864e5;case"90d":return Date.now()-90*864e5;case"1y":{const n=new Date;return n.setHours(0,0,0,0),n.setDate(n.getDate()-364),n.getTime()}default:return null}}function E(t){return Number.isFinite(t)?Math.round(t).toLocaleString("id-ID"):"0"}function be(t,n,i){return We(t,n,i)}function Ke(t){const n=t==null?void 0:t.trim();if(!n)return"—";const i=n.lastIndexOf("/");return i>=0?n.slice(i+1):n}function je(t){if(!t)return"—";try{return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return t}}function Ze(t){if(t==null)return"{}";if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}function pt(t){if(t==null)return"Not captured";if(typeof t=="object"&&t!==null&&!Array.isArray(t)){const i=t;if(typeof i._redacted=="string")return"Capture unavailable";if(Object.keys(i).length===0)return"Empty payload"}const n=Ze(t);return`${n.split(`
|
|
4
4
|
`).length} lines · ${n.length.toLocaleString()} chars`}function Ve(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t._redacted=="string"}function Ge(t){return t.status==="ok"||t.status==="success"?"bg-emerald-500":t.status==="error"||t.error?"bg-red-500":t.status==="pending"||t.status==="processing"?"bg-amber-500":"bg-muted-foreground/64"}function Je(t){if(t.status){const n=t.status.toUpperCase();return n==="SUCCESS"?"OK":n}return t.error?"ERROR":"—"}function Rt(){var De,ze,Pe,qe;const t=rs(),[n,i]=o.useState("today"),[u,C]=o.useState(Q),[g,d]=o.useState(""),[h,y]=o.useState(""),[D,_]=o.useState("desc"),[b,j]=o.useState(1),[r,I]=o.useState(null),[k,ee]=o.useState(!1),[K,ye]=o.useState("today"),[S,Ne]=o.useState(!1),[N,we]=o.useState(!1),se=as();ds();const M=ns({mutationFn:Ns,onSuccess:async()=>{ee(!1),I(null),j(1),await se.invalidateQueries({queryKey:["usage-stats"]}),await se.invalidateQueries({queryKey:["usage-history"]}),await se.invalidateQueries({queryKey:["usage-request-details"]}),await se.invalidateQueries({queryKey:["request-detail"]})}}),de=W({queryKey:["usage-stats",n],queryFn:()=>ws({range:n}),enabled:oe(),retry:!1}),ke=W({queryKey:["currency-settings"],queryFn:xs,enabled:oe(),staleTime:720*60*1e3,retry:!1}),A=W({queryKey:["usage-history",b,u===Q?void 0:u,g.trim()||void 0,h||void 0,n,D],queryFn:()=>{const s=xt(n);return $e({page:b,pageSize:ut,provider:u===Q?void 0:u,query:g.trim()||void 0,status:h||void 0,sortDir:D,startDate:s?new Date(s).toISOString():void 0,source:"usage"})},enabled:oe(),retry:!1,placeholderData:s=>s}),Se=W({queryKey:["nodes"],queryFn:Ys,enabled:oe(),retry:!1}),te=W({queryKey:["request-detail",r==null?void 0:r.provider,r==null?void 0:r.model,r==null?void 0:r.timestamp],queryFn:()=>{const s=r!=null&&r.timestamp?new Date(r.timestamp).getTime():Date.now();return $e({provider:r==null?void 0:r.provider,model:r==null?void 0:r.model,startDate:new Date(s-5e3).toISOString(),endDate:new Date(s+5e3).toISOString(),pageSize:5,includePayloads:!0})},enabled:!!r,retry:!1}),l=o.useMemo(()=>{var s,a,c,p;return((a=(s=te.data)==null?void 0:s.details)==null?void 0:a.find(H=>H.provider===(r==null?void 0:r.provider)||!(r!=null&&r.provider)))??((p=(c=te.data)==null?void 0:c.details)==null?void 0:p[0])??null},[te.data,r]),m=de.data,z=cs((De=ke.data)==null?void 0:De.currency),V=((ze=ke.data)==null?void 0:ze.usdToIdr)??ms,ce=(m==null?void 0:m.totalCost)??0,Ce=We(ce,z,V),G=o.useMemo(()=>{var s;return(((s=A.data)==null?void 0:s.details)??[]).map(a=>{var c,p,H,Ae,_e,Le,Re,Ee,Ie,Me,Oe,Fe;return{id:a.id&&Number(a.id)||void 0,timestamp:a.timestamp,provider:a.provider,model:a.model,connectionId:a.connectionId,endpoint:a.endpoint,cost:a.cost,promptTokens:((c=a.tokens)==null?void 0:c.prompt_tokens)??((p=a.tokens)==null?void 0:p.input_tokens),completionTokens:((H=a.tokens)==null?void 0:H.completion_tokens)??((Ae=a.tokens)==null?void 0:Ae.output_tokens),cachedTokens:((_e=a.tokens)==null?void 0:_e.cached_tokens)??((Le=a.tokens)==null?void 0:Le.cache_read_input_tokens)??((Ee=(Re=a.tokens)==null?void 0:Re.prompt_tokens_details)==null?void 0:Ee.cached_tokens),cacheCreationTokens:((Ie=a.tokens)==null?void 0:Ie.cache_creation_input_tokens)??((Oe=(Me=a.tokens)==null?void 0:Me.prompt_tokens_details)==null?void 0:Oe.cache_creation_tokens),status:a.status,latencyMs:typeof((Fe=a.latency)==null?void 0:Fe.total)=="number"?a.latency.total:void 0,error:typeof a.error=="string"?a.error:null}})},[A.data]),L=de.isLoading||A.isLoading,R=o.useMemo(()=>{const s=new Map;for(const a of Se.data??[])s.set(a.id,a.name||a.id),a.prefix&&s.set(a.prefix,a.name||a.prefix);return a=>a?s.has(a)?s.get(a):ps(a)||a:"—"},[Se.data]),me=o.useMemo(()=>{const s=new Set;return Object.keys((m==null?void 0:m.byProvider)??{}).forEach(a=>s.add(a)),G.forEach(a=>a.provider&&s.add(a.provider)),Array.from(s).sort()},[m,G]),Xe=o.useMemo(()=>{const s={[Q]:"All providers"};for(const a of me)s[a]=R(a);return s},[R,me]),re=G,O=(Pe=A.data)==null?void 0:Pe.pagination,Ye=(O==null?void 0:O.totalItems)??0,{safePage:ue,totalPages:J}=dt(b,O),F=A.isFetching;o.useEffect(()=>{j(1)},[n,u,g,h,D]),o.useEffect(()=>{ct(b,O,A.isFetching)&&j(J)},[A.isFetching,b,O,J]);const ae=o.useMemo(()=>Array.from(new Set(G.map(s=>s.status).filter(Boolean))).sort(),[G]);o.useEffect(()=>{h&&!ae.includes(h)&&y("")},[h,ae]);const x=l==null?void 0:l.tokens,es=(x==null?void 0:x.prompt_tokens)??(x==null?void 0:x.input_tokens)??void 0,ss=(x==null?void 0:x.completion_tokens)??(x==null?void 0:x.output_tokens)??void 0,ts=(x==null?void 0:x.cached_tokens)??(x==null?void 0:x.cache_read_input_tokens)??void 0,ne=[l==null?void 0:l.request,l==null?void 0:l.providerRequest,l==null?void 0:l.providerResponse,l==null?void 0:l.response].some(s=>s!=null&&!Ve(s));return e.jsxs("div",{className:"flex min-h-full h-auto w-full min-w-0 flex-col gap-2.5 overflow-x-hidden lg:h-full",children:[e.jsx(ls,{className:"mb-0 shrink-0 sm:mb-0",title:"Usage & Cost",actions:e.jsx("div",{className:"w-full max-w-full sm:min-w-[26rem] sm:w-auto",children:e.jsx(Qs,{size:"sm",value:n,onChange:i,options:mt,className:"w-full"})})}),de.isError||A.isError?e.jsx("div",{className:"shrink-0 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:"Unable to load live usage data. Check your session and backend connection."}):null,e.jsxs("div",{className:"grid shrink-0 grid-cols-2 gap-2 sm:grid-cols-3 sm:gap-3 lg:grid-cols-5",children:[e.jsx(U,{className:"w-full rounded-xl p-0.5 sm:rounded-2xl sm:p-1",children:e.jsxs(X,{className:"rounded-lg p-2.5 sm:rounded-xl sm:p-4",children:[e.jsx(T,{className:"min-h-5 text-[10px] font-medium leading-tight text-muted-foreground sm:min-h-0 sm:text-[12px]",children:"Total requests"}),e.jsx("p",{className:"mt-1 text-lg font-semibold leading-none tabular-nums sm:text-2xl",children:L?"—":e.jsx(Z,{value:(m==null?void 0:m.total)??0})})]})}),e.jsx(U,{className:"w-full rounded-xl p-0.5 sm:rounded-2xl sm:p-1",children:e.jsxs(X,{className:"rounded-lg p-2.5 sm:rounded-xl sm:p-4",children:[e.jsx(T,{className:"min-h-5 text-[10px] font-medium leading-tight text-muted-foreground sm:min-h-0 sm:text-[12px]",children:"Total input tokens"}),e.jsx("p",{className:"mt-1 text-lg font-semibold leading-none tabular-nums text-success sm:text-2xl",children:L?"—":e.jsx(Z,{value:(m==null?void 0:m.totalPromptTokens)??0,className:"text-success"})})]})}),e.jsx(U,{className:"w-full rounded-xl p-0.5 sm:rounded-2xl sm:p-1",children:e.jsxs(X,{className:"rounded-lg p-2.5 sm:rounded-xl sm:p-4",children:[e.jsx(T,{className:"min-h-5 text-[10px] font-medium leading-tight text-muted-foreground sm:min-h-0 sm:text-[12px]",children:"Output tokens"}),e.jsx("p",{className:"mt-1 text-lg font-semibold leading-none tabular-nums text-destructive sm:text-2xl",children:L?"—":e.jsx(Z,{value:(m==null?void 0:m.totalCompletionTokens)??0,className:"text-destructive"})})]})}),e.jsx(U,{className:"w-full rounded-xl p-0.5 sm:rounded-2xl sm:p-1",children:e.jsxs(X,{className:"rounded-lg p-2.5 sm:rounded-xl sm:p-4",children:[e.jsx(T,{className:"min-h-5 text-[10px] font-medium leading-tight text-muted-foreground sm:min-h-0 sm:text-[12px]",children:"Cached tokens"}),e.jsx("p",{className:"mt-1 text-lg font-semibold leading-none tabular-nums text-warning sm:text-2xl",children:L?"—":e.jsx(Z,{value:(m==null?void 0:m.totalCachedTokens)??0,className:"text-warning"})})]})}),e.jsx(U,{className:"w-full rounded-xl p-0.5 sm:rounded-2xl sm:p-1",children:e.jsxs(X,{className:"rounded-lg p-2.5 sm:rounded-xl sm:p-4",children:[e.jsx(T,{className:"min-h-5 text-[10px] font-medium leading-tight text-muted-foreground sm:min-h-0 sm:text-[12px]",children:`Est. cost (${z})`}),e.jsx("p",{className:"mt-1 min-w-0 max-w-full truncate text-lg font-semibold leading-none tabular-nums sm:text-2xl",children:L?"—":e.jsx(v,{label:Ce,children:e.jsx("span",{className:"inline-block max-w-full truncate align-bottom",title:Ce,children:e.jsx(Z,{value:us(ce,z,V),prefix:z==="IDR"?"Rp":"$",locale:z==="IDR"?"id-ID":"en-US",decimals:z==="IDR"?0:ce<.01?4:2,className:"text-[clamp(1rem,4vw,1.5rem)]"})})})})]})})]}),e.jsxs(U,{className:"flex min-h-[24rem] flex-none flex-col rounded-xl bg-transparent p-0 sm:rounded-2xl sm:bg-muted/72 sm:p-1 lg:min-h-0 lg:flex-1",children:[e.jsx(Ts,{className:"border-b border-border/70 px-3 py-3 sm:border-0 sm:px-5 sm:py-4",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-3 gap-y-2",children:[e.jsxs("div",{children:[e.jsx(T,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Request history"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"To view payload details, enable “Capture full request payloads” in Settings."})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("div",{className:"flex items-center gap-0.5 sm:hidden",children:[e.jsx(v,{label:S?"Show provider names":"Hide provider names",children:e.jsxs("button",{type:"button","aria-label":S?"Show provider names":"Hide provider names","aria-pressed":S,onClick:()=>Ne(s=>!s),className:"inline-flex h-8 items-center gap-1.5 rounded-md px-2 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[S?e.jsx(le,{className:"size-3.5","aria-hidden":"true"}):e.jsx($,{className:"size-3.5","aria-hidden":"true"}),e.jsx("span",{children:"Provider"})]})}),e.jsx(v,{label:N?"Show full model names":"Hide provider prefixes from models",children:e.jsxs("button",{type:"button","aria-label":N?"Show full model names":"Hide provider prefixes from models","aria-pressed":N,onClick:()=>we(s=>!s),className:"inline-flex h-8 items-center gap-1.5 rounded-md px-2 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[N?e.jsx(le,{className:"size-3.5","aria-hidden":"true"}):e.jsx($,{className:"size-3.5","aria-hidden":"true"}),e.jsx("span",{children:"Model"})]})})]}),e.jsx(v,{label:"Clear history",children:e.jsxs(P,{type:"button",variant:"ghost",size:"sm",className:"size-8 px-0 text-destructive hover:bg-destructive/10 hover:text-destructive sm:h-7 sm:w-auto sm:px-2 sm:text-[11px]",onClick:()=>{ye(n),ee(!0)},disabled:M.isPending,"aria-label":"Clear history",children:[e.jsx(Cs,{className:"h-3.5 w-3.5 sm:hidden"}),e.jsx("span",{className:"hidden sm:inline",children:"Clear history"})]})}),e.jsx(v,{label:"Sort by date",children:e.jsxs("button",{type:"button",className:"inline-flex size-8 items-center justify-center rounded-md px-0 py-1 text-[11px] font-medium text-muted-foreground hover:bg-muted hover:text-foreground sm:h-7 sm:w-auto sm:gap-1.5 sm:px-2",onClick:()=>_(s=>s==="desc"?"asc":"desc"),"aria-label":D==="desc"?"Sort oldest first":"Sort newest first",children:[D==="desc"?e.jsx(Ds,{className:"h-3.5 w-3.5","aria-hidden":!0}):e.jsx(zs,{className:"h-3.5 w-3.5","aria-hidden":!0}),e.jsx("span",{className:"hidden sm:inline",children:"Sort by date"})]})})]})]})}),M.isError?e.jsx("div",{className:"mx-5 mb-3 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:"Failed to clear Usage history. Try again."}):null,e.jsxs("div",{className:"flex shrink-0 flex-col gap-2 border-b border-border/70 px-3 pb-3 sm:flex-row sm:items-center sm:border-0 sm:px-5",children:[e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(Ps,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(hs,{value:g,onChange:s=>d(s.target.value),placeholder:"Search model, provider, status, connection…",autoComplete:"off",autoCorrect:"off",autoCapitalize:"none",spellCheck:!1,className:"h-9 pl-9 pr-8 leading-none"}),g?e.jsx("button",{type:"button","aria-label":"Clear search",className:"absolute right-2.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>d(""),children:e.jsx(qs,{className:"h-4 w-4"})}):null]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:contents",children:[e.jsxs(pe,{items:Xe,value:u,onValueChange:s=>C(s??Q),children:[e.jsx(he,{className:"h-9 w-full sm:w-48",children:e.jsx(fe,{placeholder:"All providers"})}),e.jsxs(ge,{children:[e.jsx(Y,{value:Q,children:"All providers"}),me.map(s=>e.jsx(Y,{value:s,children:R(s)},s))]})]}),e.jsxs(pe,{items:{all:"All statuses",...Object.fromEntries(ae.map(s=>[s,s.toUpperCase()]))},value:h||"all",onValueChange:s=>y(s==="all"?"":s??""),children:[e.jsx(he,{className:"h-9 w-full sm:w-40",children:e.jsx(fe,{placeholder:"All statuses"})}),e.jsxs(ge,{children:[e.jsx(Y,{value:"all",children:"All statuses"}),ae.map(s=>e.jsx(Y,{value:s,children:s.toUpperCase()},s))]})]})]})]}),e.jsx("div",{className:"min-h-0 flex-1 px-3 pb-1 sm:px-1",children:e.jsxs(fs,{overscrollContain:!0,className:"h-full",children:[e.jsx("div",{className:"w-full min-w-0 rounded-xl border border-border/70 bg-card sm:hidden",children:L?e.jsx("div",{className:"divide-y divide-border/70",children:Array.from({length:6}).map((s,a)=>e.jsxs("div",{className:"px-2.5 py-2.5",children:[e.jsx(B,{className:"h-3.5 w-2/3"}),e.jsx(B,{className:"mt-2 h-3 w-full"})]},a))}):re.length===0?e.jsxs("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:["No usage rows for ",Be[n].toLowerCase()]}):e.jsx("div",{className:"divide-y divide-border/70",children:re.map((s,a)=>{const c=He(s);return e.jsx("article",{className:"min-w-0 px-2.5 py-2.5",children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("p",{className:"min-w-0 flex-1 truncate text-xs font-medium",children:S?"Hidden":R(s.provider)}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs(xe,{variant:"outline",className:"text-[10px] font-normal",children:[e.jsx("span",{"aria-hidden":"true",className:f("size-1.5 rounded-full",Ge(s))}),Je(s)]}),e.jsx(v,{label:"View details",children:e.jsx(P,{variant:"outline",size:"icon-xs",className:"size-6 shrink-0 p-0 [&_svg]:size-3",onClick:()=>I(s),"aria-label":"View request details",children:e.jsx($,{className:"h-3.5 w-3.5","aria-hidden":!0})})})]})]}),e.jsx(v,{label:N?"Showing model slug only":s.model||"—",children:e.jsx("p",{className:"mt-0.5 max-w-full truncate whitespace-nowrap font-mono text-[10px] text-muted-foreground",children:N?Ke(s.model):s.model||"—"})}),e.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1.5 truncate text-[10px] tabular-nums text-muted-foreground",children:[e.jsx("span",{className:"shrink-0",children:je(s.timestamp)}),e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsxs("span",{className:"shrink-0 text-success",children:["In ",E(s.promptTokens||0)]}),e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsxs("span",{className:"shrink-0 text-destructive",children:["Out ",E(s.completionTokens||0)]}),e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsx("span",{className:"shrink-0 text-foreground",children:be(s.cost??0,z,V)}),e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsx(v,{label:c.title,children:e.jsx("span",{className:f("shrink-0",c.hit?"text-warning":"text-muted-foreground"),children:c.label})})]})]})},s.id??`${s.timestamp}-${a}`)})})}),e.jsx("div",{className:"hidden sm:block",children:e.jsxs(Ws,{variant:"card",className:"min-w-[900px] text-[13px]",children:[e.jsx(Zs,{children:e.jsxs(ie,{children:[e.jsx(q,{className:"px-4 py-2",children:"Time"}),e.jsx(q,{className:"px-3 py-2",children:e.jsxs("div",{className:"group/column flex items-center gap-1.5",children:[e.jsx("span",{children:"Provider"}),e.jsx(v,{label:S?"Show provider names":"Hide provider names",children:e.jsx("button",{type:"button","aria-label":S?"Show provider names":"Hide provider names",onClick:()=>Ne(s=>!s),className:"inline-flex size-5 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity hover:bg-surface-hover hover:text-primary focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/column:opacity-100",children:S?e.jsx(le,{className:"size-3.5","aria-hidden":"true"}):e.jsx($,{className:"size-3.5","aria-hidden":"true"})})})]})}),e.jsx(q,{className:"px-3 py-2",children:e.jsxs("div",{className:"group/column flex items-center gap-1.5",children:[e.jsx("span",{children:"Model"}),e.jsx(v,{label:N?"Show full model names":"Hide provider prefixes from models",children:e.jsx("button",{type:"button","aria-label":N?"Show full model names":"Hide provider prefixes from models",onClick:()=>we(s=>!s),className:"inline-flex size-5 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity hover:bg-surface-hover hover:text-primary focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/column:opacity-100",children:N?e.jsx(le,{className:"size-3.5","aria-hidden":"true"}):e.jsx($,{className:"size-3.5","aria-hidden":"true"})})})]})}),e.jsx(q,{className:"px-3 py-2 text-success",children:"In"}),e.jsx(q,{className:"px-3 py-2 text-destructive",children:"Out"}),e.jsx(q,{className:"px-3 py-2",children:"Cache"}),e.jsx(q,{className:"px-3 py-2",children:"Cost"}),e.jsx(q,{className:"px-3 py-2",children:"Status"}),e.jsx(q,{className:"px-3 py-2 text-right",children:"Detail"})]})}),e.jsx(Xs,{children:L?Array.from({length:6}).map((s,a)=>e.jsx(ie,{children:e.jsx(w,{colSpan:9,className:"px-4 py-2",children:e.jsx(B,{className:"h-4 w-full"})})},a)):re.length===0?e.jsx(ie,{children:e.jsxs(w,{colSpan:9,className:"px-4 py-10 text-center text-muted-foreground",children:["No usage rows for ",Be[n].toLowerCase()]})}):re.map((s,a)=>e.jsxs(ie,{children:[e.jsx(w,{className:"whitespace-nowrap px-4 py-2 text-muted-foreground",children:je(s.timestamp)}),e.jsx(w,{className:"px-3 py-2 font-medium",children:e.jsx("span",{className:f(S&&"font-normal italic text-muted-foreground"),children:S?"Hidden":R(s.provider)})}),e.jsx(w,{className:"whitespace-nowrap px-3 py-2",children:e.jsx(v,{label:N?"Showing model slug only":s.model||"—",children:e.jsx("span",{className:"block min-w-max whitespace-nowrap font-mono text-[11px] text-muted-foreground",children:N?Ke(s.model):s.model||"—"})})}),e.jsx(w,{className:"px-3 py-2",children:e.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums text-success",children:[e.jsx(As,{className:"h-3 w-3"}),E(s.promptTokens||0)]})}),e.jsx(w,{className:"px-3 py-2",children:e.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums text-destructive",children:[e.jsx(_s,{className:"h-3 w-3"}),E(s.completionTokens||0)]})}),e.jsx(w,{className:"px-3 py-2",children:(()=>{const c=He(s);return e.jsx(v,{label:c.title,children:e.jsx("span",{className:f("whitespace-nowrap text-[11px] font-medium tabular-nums",c.hit?"text-warning":"text-muted-foreground"),children:c.label})})})()}),e.jsx(w,{className:"px-3 py-2 text-muted-foreground tabular-nums",children:be(s.cost??0,z,V)}),e.jsx(w,{className:"px-3 py-2",children:e.jsxs(xe,{variant:"outline",className:"font-normal",children:[e.jsx("span",{"aria-hidden":"true",className:f("size-1.5 rounded-full",Ge(s))}),Je(s)]})}),e.jsx(w,{className:"px-3 py-2 text-right",children:e.jsxs(P,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-[11px] text-muted-foreground hover:text-foreground",onClick:()=>I(s),children:[e.jsx($,{className:"h-3.5 w-3.5","aria-hidden":!0}),"View"]})})]},s.id??`${s.timestamp}-${a}`))})]})})]})}),Ye>0?e.jsx(Bs,{className:"px-3 py-3 sm:px-5 sm:py-4",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsxs("p",{className:"text-[10px] tabular-nums text-muted-foreground sm:text-[11px]",children:[ue,"/",J]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(P,{variant:"outline",size:"sm",className:"size-8 px-0 sm:h-7 sm:w-auto sm:px-2.5",loading:F,disabled:F||ue<=1,onClick:()=>j(s=>Math.max(1,s-1)),"aria-label":F?"Loading page":"Previous page",children:[e.jsx(Ue,{className:"h-4 w-4","aria-hidden":!0}),e.jsx("span",{className:"hidden sm:inline",children:"Prev"})]}),e.jsxs(P,{variant:"outline",size:"sm",className:"size-8 px-0 sm:h-7 sm:w-auto sm:px-2.5",loading:F,disabled:F||ue>=J,onClick:()=>j(s=>Math.min(J,s+1)),"aria-label":F?"Loading page":"Next page",children:[e.jsx("span",{className:"hidden sm:inline",children:"Next"}),e.jsx(Ls,{className:"h-4 w-4","aria-hidden":!0})]})]})]})}):null]}),e.jsx(gs,{open:k,onOpenChange:ee,children:e.jsxs(bs,{className:"max-w-[25rem] overflow-hidden p-0",children:[e.jsx("div",{className:"border-b border-border/70 bg-destructive/[0.06] px-5 py-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-destructive/10 text-destructive",children:e.jsx(Rs,{className:"h-4 w-4","aria-hidden":!0})}),e.jsxs(js,{className:"gap-1 text-left",children:[e.jsx(vs,{className:"text-sm font-semibold",children:"Clear Usage history?"}),e.jsx(ys,{className:"text-xs leading-5",children:"Remove request history, daily totals, and captured details for the selected time range."})]})]})}),e.jsxs("div",{className:"space-y-4 px-5 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"clear-history-range",className:"text-xs font-medium text-foreground",children:"Time range"}),e.jsxs(pe,{items:Object.fromEntries(ve.map(s=>[s.value,s.label])),value:K,onValueChange:s=>ye(s||"today"),children:[e.jsx(he,{id:"clear-history-range",className:"h-9 w-full text-xs",children:e.jsx(fe,{})}),e.jsx(ge,{className:"max-h-52 overscroll-contain",children:ve.map(s=>e.jsx(Y,{value:s.value,className:"min-h-8 py-1.5",children:s.label},s.value))})]})]}),e.jsxs("div",{className:"rounded-lg border border-border/70 bg-muted/30 px-3 py-2.5 text-xs leading-5 text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:Qe[K]})," will be removed. Providers, API keys, and settings will not be affected."]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(P,{variant:"outline",size:"sm",onClick:()=>ee(!1),disabled:M.isPending,children:"Cancel"}),e.jsx(P,{variant:"destructive",size:"sm",onClick:()=>M.mutate(K),disabled:M.isPending,children:M.isPending?"Clearing…":K==="all"?"Clear all history":`Clear ${Qe[K].toLowerCase()}`})]})]})]})}),e.jsx(rt,{open:!!r,onOpenChange:s=>{s||I(null)},children:e.jsxs(at,{variant:"inset",children:[e.jsxs(nt,{className:"px-4 py-3 sm:px-5 sm:py-4",children:[e.jsxs(P,{type:"button",variant:"ghost",size:"sm",className:"-ml-2 h-8 w-fit gap-1 px-2 text-xs text-muted-foreground hover:text-foreground",onClick:()=>I(null),"aria-label":"Back to usage history",children:[e.jsx(Ue,{className:"h-4 w-4","aria-hidden":!0}),"Back"]}),e.jsxs("div",{className:"mt-2 flex min-w-0 items-start justify-between gap-3 pr-8",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(lt,{className:"text-lg sm:text-xl",children:"Request detail"}),e.jsxs(it,{className:"break-words font-mono text-[11px] leading-4 sm:text-xs",children:[(r==null?void 0:r.model)||"Unknown model"," ·"," ",r?R(r.provider):""]})]}),r?e.jsx(is,{tone:r.status==="ok"||r.status==="success"?"ok":r.status==="error"?"err":"muted",className:"shrink-0 text-[10px]",children:(r.status||"—").toUpperCase()}):null]})]}),e.jsxs(ot,{className:"space-y-3 px-4 py-3 sm:space-y-4 sm:px-5 sm:py-4",children:[e.jsxs("section",{className:"rounded-xl border border-border/70 bg-surface/35 p-3 sm:p-3.5",children:[e.jsx("p",{className:"mb-3 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground",children:"Request summary"}),e.jsx("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-3 sm:grid-cols-3",children:[["Time",je(r==null?void 0:r.timestamp),!1],["Provider",r?R(r.provider):"—",!1],["Latency",((qe=l==null?void 0:l.latency)==null?void 0:qe.total)!=null?`${Math.round(l.latency.total)} ms`:(r==null?void 0:r.latencyMs)!=null?`${r.latencyMs} ms`:"—",!1],["Cost",be((r==null?void 0:r.cost)??(l==null?void 0:l.cost)??0,z,V),!1],["Connection ID",(l==null?void 0:l.connectionId)||(r==null?void 0:r.connectionId)||"—",!0],["Endpoint",(r==null?void 0:r.endpoint)||"—",!0]].map(([s,a,c])=>e.jsxs("div",{className:f("min-w-0",s==="Connection ID"&&"col-span-2 sm:col-span-2"),children:[e.jsx("dt",{className:"text-[9px] uppercase tracking-wide text-muted-foreground sm:text-[10px]",children:String(s)}),e.jsxs("dd",{className:"mt-0.5 flex min-w-0 items-center gap-2",children:[e.jsx(v,{label:String(a),children:e.jsx("span",{className:f("min-w-0 flex-1 text-[11px] text-foreground sm:text-xs",!!c&&"font-mono text-[10px] sm:text-[11px]",s==="Connection ID"?"break-all":"truncate"),children:String(a)})}),s==="Connection ID"&&a!=="—"?e.jsx(os,{value:String(a),label:"Copy",iconOnly:!0,className:"size-6 shrink-0 p-0 [&_svg]:mx-0 [&_svg]:size-3"}):null]})]},String(s)))})]}),r!=null&&r.error?e.jsx("p",{className:"rounded-lg border border-destructive/30 bg-destructive/8 px-3 py-2.5 text-xs text-destructive-foreground",children:r.error}):null,e.jsxs("section",{className:"rounded-xl border border-border/70 bg-surface/35 p-3 sm:p-3.5",children:[e.jsx("p",{className:"mb-3 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground",children:"Token usage"}),e.jsx("div",{className:"grid grid-cols-3 divide-x divide-border/70",children:[["Prompt",E(es??(r==null?void 0:r.promptTokens)??0),"text-success"],["Cached",E(ts??0),"text-foreground"],["Completion",E(ss??(r==null?void 0:r.completionTokens)??0),"text-destructive"]].map(([s,a,c],p)=>e.jsxs("div",{className:f("min-w-0 px-3 first:pl-0 last:pr-0",p===0&&"pl-0"),children:[e.jsx("p",{className:"text-[9px] uppercase tracking-wide text-muted-foreground sm:text-[10px]",children:String(s)}),e.jsx("p",{className:f("mt-0.5 text-sm font-semibold tabular-nums sm:text-base",String(c)),children:String(a)})]},String(s)))})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground sm:text-[11px]",children:"Payload"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:ne?"Select a captured payload to inspect and copy its JSON.":"Full payload was not captured. Metadata remains available above."})]}),e.jsx(xe,{variant:ne?"success":"outline",className:"text-[10px] font-normal",children:ne?"Payload captured":"Metadata only"}),ne?null:e.jsxs(P,{type:"button",variant:"outline",size:"sm",className:"h-7 gap-1.5 px-2 text-[11px]",onClick:()=>t("/dashboard/settings?tab=security"),children:[e.jsx(Es,{className:"size-3.5","aria-hidden":"true"}),"Enable in Settings"]})]}),te.isLoading?e.jsxs("div",{className:"space-y-2 rounded-xl border border-border/70 p-3",children:[e.jsx(B,{className:"h-9 w-full"}),e.jsx(B,{className:"h-9 w-full"}),e.jsx(B,{className:"h-9 w-full"})]}):l?(()=>{var c;const a=[{key:"request",label:"Request",filename:`${((c=l.request)==null?void 0:c.method)??"REQUEST"}.json`,value:l.request},{key:"providerRequest",label:"Provider request",filename:"provider-request.json",value:l.providerRequest},{key:"providerResponse",label:"Provider response",filename:"provider-response.json",value:l.providerResponse},{key:"response",label:"Response",filename:"response.json",value:l.response}].filter(p=>p.value!==void 0&&p.value!==null);return a.length?e.jsx(Ks,{multiple:!0,defaultValue:a[0]?[a[0].key]:[],className:"w-full min-w-0 overflow-hidden rounded-xl border border-border/70 bg-surface/30",children:a.map(p=>{const H=Ve(p.value);return e.jsxs(Vs,{value:p.key,className:"border-border/70 px-3 last:border-b-0",children:[e.jsx(Gs,{className:"gap-2 py-2 sm:py-2.5",children:e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"truncate text-xs sm:text-sm",children:p.label}),e.jsx("span",{className:"truncate text-[9px] font-normal text-muted-foreground sm:text-[10px]",children:pt(p.value)})]})}),e.jsx(Js,{className:"min-w-0 overflow-hidden pb-3",children:H?e.jsx("div",{className:"rounded-lg border border-border/70 bg-muted/30 px-3 py-2.5 text-xs text-muted-foreground",children:"Payload capture was unavailable for this field. Metadata is still available above."}):e.jsx(tt,{code:Ze(p.value),language:"json",filename:p.filename,className:"max-h-80 max-w-full min-w-0 overflow-auto"})})]},p.key)})}):e.jsx("p",{className:"rounded-xl border border-border/70 bg-surface/30 px-3 py-3 text-xs text-muted-foreground",children:"Full request and response payloads were not captured for this request."})})():e.jsx("p",{className:"rounded-xl border border-border/70 bg-surface/30 px-3 py-3 text-xs text-muted-foreground",children:"Full request and response payloads were not captured for this request."})]})]})]})})]})}export{Rt as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as a}from"./react-vendor-xnYrwzsL.js";import{c as e}from"./index-
|
|
1
|
+
import{j as a}from"./react-vendor-xnYrwzsL.js";import{c as e}from"./index-CkR38iPY.js";import{i as r}from"./icons-vendor-CUx7SB5V.js";import{a6 as i,a7 as s,a8 as c,a9 as d,aa as l}from"./ui-vendor-BuM9f2NY.js";function x(o){return a.jsx(i,{"data-slot":"accordion",...o})}function g({className:o,...t}){return a.jsx(s,{className:e("min-w-0 border-b last:border-b-0",o),"data-slot":"accordion-item",...t})}function h({className:o,children:t,...n}){return a.jsx(c,{className:"flex",children:a.jsxs(d,{className:e("flex flex-1 cursor-pointer items-start justify-between gap-4 rounded-md py-4 text-left font-medium text-sm outline-none transition-all focus-visible:ring-[3px] focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-64 data-panel-open:*:data-[slot=accordion-indicator]:rotate-180",o),"data-slot":"accordion-trigger",...n,children:[t,a.jsx(r,{className:"pointer-events-none size-4 shrink-0 translate-y-0.5 opacity-80 transition-transform duration-200 ease-in-out","data-slot":"accordion-indicator"})]})})}function b({className:o,children:t,...n}){return a.jsx(l,{className:"h-(--accordion-panel-height) overflow-hidden text-muted-foreground text-sm transition-[height] duration-200 ease-in-out data-ending-style:h-0 data-starting-style:h-0","data-slot":"accordion-panel",...n,children:a.jsx("div",{className:e("pt-0 pb-4",o),children:t})})}export{x as A,g as a,h as b,b as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{y as o}from"./index-
|
|
1
|
+
import{y as o}from"./index-CkR38iPY.js";async function r(){const{data:a}=await o.get("/provider-nodes");return a.nodes??[]}async function l(a){const{data:e}=await o.post("/provider-nodes",a);return e.node}async function i(a,e){const{data:t}=await o.put(`/provider-nodes/${a}`,e);return t.node}async function s(a){await o.delete(`/provider-nodes/${a}`)}async function c(){const{data:a}=await o.get("/proxy-pools",{params:{includeUsage:"true"}});return a.proxyPools??[]}async function p(a){const{data:e}=await o.post("/proxy-pools",a);return e.proxyPool??e.pool}async function d(a,e){const{data:t}=await o.put(`/proxy-pools/${a}`,e);return t.proxyPool??t.pool}async function u(a){const e=`/proxy-pools/${a.type}-deploy`,{data:t}=await o.post(e,a);return t}async function y(a){await o.delete(`/proxy-pools/${a}`)}async function m(a){const{data:e}=await o.post(`/proxy-pools/${a}/test`);return e}function b(a){var e;return{profileName:((e=a.profileName)==null?void 0:e.trim())||"Sway Router",profileAvatar:a.profileAvatar||"",currency:a.currency==="IDR"?"IDR":"USD",requireApiKey:!!a.requireApiKey,requireLogin:!!a.requireLogin,payloadCaptureEnabled:a.payloadCaptureEnabled!==!1,rtkEnabled:a.rtkEnabled!==!1,cavemanEnabled:!!a.cavemanEnabled,cavemanLevel:String(a.cavemanLevel||"full"),ponytailEnabled:!!a.ponytailEnabled,ponytailLevel:String(a.ponytailLevel||"full")}}function v(a){return{requireApiKey:a.requireApiKey,requireLogin:a.requireLogin,payloadCaptureEnabled:a.payloadCaptureEnabled,rtkEnabled:a.rtkEnabled,cavemanEnabled:a.cavemanEnabled,cavemanLevel:a.cavemanLevel,ponytailEnabled:a.ponytailEnabled,ponytailLevel:a.ponytailLevel}}async function f(){const{data:a}=await o.get("/combos");return a.combos??[]}async function x(a){const{data:e}=await o.post("/combos",a);return e}async function E(a,e){const{data:t}=await o.put(`/combos/${encodeURIComponent(a)}`,e);return t}async function w(a){await o.delete(`/combos/${encodeURIComponent(a)}`)}export{c as a,E as b,l as c,s as d,x as e,w as f,f as g,u as h,p as i,d as j,y as k,r as l,v as m,b as s,m as t,i as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{y as i}from"./index-
|
|
1
|
+
import{y as i}from"./index-CkR38iPY.js";async function c(e){const{data:t}=await i.get("/keys",{params:e!=null&&e.includeRevoked?{includeRevoked:1}:void 0});return(t.keys??[]).map(a)}async function d(e){var r;const t=((r=e.name)==null?void 0:r.trim())||"default",{data:n}=await i.post("/keys",{name:t});return{key:{id:n.id??`key_${Math.random().toString(36).slice(2,10)}`,name:n.name??t,prefix:n.key?n.key.slice(0,10):void 0,key:n.key,isActive:!0,isDefault:n.isDefault===!0,createdAt:new Date().toISOString()},message:"Save this key now — it will not be shown again."}}async function f(e,t){const{data:n}=await i.put(`/keys/${encodeURIComponent(e)}`,{isActive:t.isActive});return a(n.key)}async function k(e){await i.delete(`/keys/${encodeURIComponent(e)}`)}async function p(e){const{data:t}=await i.put(`/keys/${encodeURIComponent(e)}`,{rotate:!0});return a(t.key)}async function y(e){var n;const{data:t}=await i.get(`/keys/${encodeURIComponent(e)}`);return((n=t.key)==null?void 0:n.key)||""}async function l(){const t=(await c({includeRevoked:!1})).find(n=>n.isActive!==!1);return t?t.key?t.key:t.id?y(t.id):"":""}function a(e){const t=e.key?s(e.key):void 0;return{...e,prefix:e.prefix||e.keyPrefix||t,keyPrefix:e.keyPrefix||e.prefix||t}}function m(e){return e.prefix||e.keyPrefix?e.prefix||e.keyPrefix||"":e.key?s(e.key):"swy-••••"}function s(e){const t=e.trim();if(t.length<=11)return t;const n=t.startsWith("sk-")?"sk-":t.slice(0,3);return t.length>14?`${n}${t.slice(3,11)}…`:t}export{k as a,l as b,d as c,m as d,y as g,c as l,p as r,f as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as o}from"./index-
|
|
1
|
+
import{c as o}from"./index-CkR38iPY.js";import{u as e,m as s}from"./ui-vendor-BuM9f2NY.js";function c({className:a,render:t,...r}){const d={className:o("relative flex flex-col rounded-2xl border bg-card not-dark:bg-clip-padding text-card-foreground",a),"data-slot":"card"};return e({defaultTagName:"div",props:s(d,r),render:t})}function i({className:a,render:t,...r}){const d={className:o("grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 p-6 in-[[data-slot=card]:has(>[data-slot=card-panel])]:pb-4 has-data-[slot=card-action]:grid-cols-[1fr_auto]",a),"data-slot":"card-header"};return e({defaultTagName:"div",props:s(d,r),render:t})}function p({className:a,render:t,...r}){const d={className:o("font-heading font-semibold text-lg leading-none",a),"data-slot":"card-title"};return e({defaultTagName:"div",props:s(d,r),render:t})}function u({className:a,render:t,...r}){const d={className:o("flex-1 p-6 in-[[data-slot=card]:has(>[data-slot=card-header]:not(.border-b))]:pt-0 in-[[data-slot=card]:has(>[data-slot=card-footer]:not(.border-t))]:pb-0",a),"data-slot":"card-panel"};return e({defaultTagName:"div",props:s(d,r),render:t})}export{c as C,i as a,p as b,u as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as e}from"./react-vendor-xnYrwzsL.js";import{c as n}from"./index-
|
|
1
|
+
import{j as e}from"./react-vendor-xnYrwzsL.js";import{c as n}from"./index-CkR38iPY.js";import{R as o,U as a}from"./ui-vendor-BuM9f2NY.js";function u({className:i,...r}){return e.jsx(o,{className:n("relative inline-flex size-4.5 shrink-0 items-center justify-center rounded-[.25rem] border border-input bg-background not-dark:bg-clip-padding outline-none ring-ring focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-offset-background aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/48 data-disabled:cursor-not-allowed data-disabled:opacity-64 sm:size-4 dark:not-data-checked:bg-input/32 dark:aria-invalid:ring-destructive/24",i),"data-slot":"checkbox",...r,children:e.jsx(a,{className:"absolute -inset-px flex items-center justify-center rounded-[.25rem] text-primary-foreground data-unchecked:hidden data-checked:bg-primary data-indeterminate:text-foreground","data-slot":"checkbox-indicator",render:(t,s)=>e.jsx("span",{...t,children:s.indeterminate?e.jsx("svg",{"aria-hidden":"true",className:"size-3.5 sm:size-3",fill:"none",height:"24",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"3",viewBox:"0 0 24 24",width:"24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M5.252 12h13.496"})}):e.jsx("svg",{"aria-hidden":"true",className:"size-3.5 sm:size-3",fill:"none",height:"24",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"3",viewBox:"0 0 24 24",width:"24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M5.252 12.7 10.2 18.63 18.748 5.37"})})})})})}export{u as C};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{y as s,U as L,V as M}from"./index-
|
|
1
|
+
import{y as s,U as L,V as M}from"./index-CkR38iPY.js";function I(t){return!!(t!=null&&t.isCustom||t!=null&&t.nodeType||t!=null&&t.passthroughModels)}async function P(t,e=!1){const{data:a}=await s.get(`/providers/${encodeURIComponent(t)}/models`,e?{params:{refresh:"1"}}:void 0);return a}async function z(t){const{data:e}=await s.get("/providers",{params:t});return{connections:e.connections??[],pagination:e.pagination??{page:t.page??1,pageSize:t.pageSize??50,totalItems:0,totalPages:0,hasNext:!1,hasPrev:!1}}}async function $(){const{data:t}=await s.get("/providers/counts");return t.counts??[]}async function T(){try{const{data:t}=await s.get("/providers/catalog"),e=t.providers??[];if(e.length)return e}catch{}return[]}async function B(){const[t,e,a]=await Promise.all([T(),$(),s.get("/provider-nodes")]),f=t.length?t:L(),m=a.data.nodes??[],l=o=>String(o||"").trim().toLowerCase().replace(/[^a-z0-9]/g,""),c=new Map;for(const o of e){const i=String(o.provider).trim().toLowerCase();c.set(i,o),c.set(l(i),o)}for(const o of f){const i=[o.id,o.alias].filter(Boolean).flatMap(u=>{const n=String(u).trim().toLowerCase();return[n,l(n)]}),r=i.map(u=>c.get(u)).find(Boolean);if(r)for(const u of i)c.set(u,r)}for(const o of m){const i=[o.id,o.prefix].filter(Boolean).flatMap(u=>{const n=String(u).trim().toLowerCase();return[n,l(n)]}),r=i.map(u=>c.get(u)).find(Boolean);if(r)for(const u of i)c.set(u,r)}const w=Array.from(new Set(e.map(o=>String(o.provider).trim()))),g=new Set,h=w.filter(o=>{const i=l(o);return g.has(i)?!1:(g.add(i),!0)});w.splice(0,w.length,...h);const p=new Set,y=[],k=new Map(m.map(o=>[o.id,o])),v=o=>{const i=o.trim().toLowerCase(),r=l(i);return f.find(u=>[u.id,u.alias].some(n=>{const d=String(n||"").trim().toLowerCase();return d===i||l(d)===r}))},x=o=>{const i=o.trim().toLowerCase();return c.get(i)||c.get(l(i))||(()=>{const r=v(o);if(r)return c.get(String(r.id).trim().toLowerCase())||c.get(l(r.id))||(r.alias?c.get(String(r.alias).trim().toLowerCase())||c.get(l(r.alias)):void 0)})()};for(const o of f){const i=x(o.id)||(o.alias?x(o.alias):void 0);if(!i)continue;const r=o.id.trim().toLowerCase();c.set(r,i),c.set(l(r),i),o.alias&&(c.set(o.alias.trim().toLowerCase(),i),c.set(l(o.alias),i))}for(const o of w){const i=o.trim().toLowerCase(),r=v(o),u=(r==null?void 0:r.id)||o,n=M(u)||r,d=k.get(u)||k.get(o),C=c.get(i)||c.get(l(i))||c.get(u.toLowerCase())||c.get(l(u));y.push({id:u,alias:(d==null?void 0:d.prefix)||(n==null?void 0:n.alias),name:(d==null?void 0:d.name)||(n==null?void 0:n.name)||u,color:n==null?void 0:n.color,icon:d?"sway-custom":n==null?void 0:n.icon,textIcon:n==null?void 0:n.textIcon,category:n==null?void 0:n.category,authType:(n==null?void 0:n.authType)||"apikey",noAuth:n==null?void 0:n.noAuth,authModes:n==null?void 0:n.authModes,thinkingConfig:r==null?void 0:r.thinkingConfig,passthroughModels:(r==null?void 0:r.passthroughModels)===!0,isCustom:!!d,baseUrl:d==null?void 0:d.baseUrl,nodeType:d==null?void 0:d.type,apiType:d==null?void 0:d.apiType,connected:(C==null?void 0:C.total)??0}),p.add(u)}for(const o of m)p.has(o.id)||(y.push({id:o.id,alias:o.prefix||o.id,name:o.name||o.prefix||o.id,authType:"apikey",isCustom:!0,baseUrl:o.baseUrl,nodeType:o.type,apiType:o.apiType,icon:"sway",connected:0}),p.add(o.id));for(const o of f)p.has(o.id)||y.push({...o,connected:0});return y}async function U(t){const{data:e}=await s.post("/providers",t);return e.connection}async function O(t,e){const{data:a}=await s.put(`/providers/${t}`,e);return a.connection}async function b(t){const{data:e}=await s.delete(`/providers/${t}`);return e}async function K(t,e){const{data:a}=await s.put(`/providers/${t}`,{isActive:!e});return a.connection}async function D(t,e,a){const{data:f}=await s.post(`/providers/${t}/test`,{},{signal:a==null?void 0:a.signal});return f}async function N(t,e){const{data:a}=await s.post(`/providers/${t}/test-models`,e!=null&&e.model?{model:e.model}:{},{signal:e==null?void 0:e.signal});return a}async function R(t,e){const{data:a}=await s.post("/models/test",{model:t,kind:"llm"},{signal:e==null?void 0:e.signal});return a}async function _(t){const{data:e}=await s.post("/providers/validate",t);return e}async function j(t){const{data:e}=await s.post("/providers/validate",t);return e}function S(t,e){if(t==="codex")return"http://localhost:1455/auth/callback";if(t==="xai")return"http://127.0.0.1:56121/callback";const a=typeof window<"u"?window.location.protocol:"http:",f=(typeof window<"u"?window.location.port:"14045")||(a==="https:"?"443":"80"),m=typeof window<"u"?window.location.hostname:"localhost";return`http://${m==="127.0.0.1"||m==="localhost"?m:"localhost"}:${f}/callback`}async function q(t,e=S(t),a){const f={redirect_uri:e};for(const[l,c]of Object.entries({}))c!==void 0&&(f[l]=c);const{data:m}=await s.get(`/oauth/${t}/authorize`,{params:f});return m}async function H(t,e){const{data:a}=await s.get(`/oauth/${t}/start-proxy`,{params:{app_port:String(e.appPort)}});return a}async function E(t,e){const{data:a}=await s.post(`/oauth/${t}/register-session`,e);return a}async function F(t,e){const{data:a}=await s.get(`/oauth/${t}/poll-status`,{params:{state:e}});return a}async function V(t){const{data:e}=await s.get(`/oauth/${t}/stop-proxy`);return e}async function G(t,e){const a={};e!=null&&e.authMethod&&(a.auth_method=e.authMethod),e!=null&&e.region&&(a.region=e.region),e!=null&&e.startUrl&&(a.start_url=e.startUrl);const{data:f}=await s.get(`/oauth/${t}/device-code`,Object.keys(a).length?{params:a}:void 0);return f}async function J(t,e){const{data:a}=await s.post(`/oauth/${t}/poll`,e);return a}async function Q(t,e){const{data:a}=await s.post(`/oauth/${t}/exchange`,e);return a}async function W(t,e){if(t==="codex"){const{data:a}=await s.post("/oauth/codex/import-token",{accessToken:e.accessToken,name:e.displayName});return a}if(t==="cursor"){if(!e.machineId)throw new Error("Cursor import requires a Machine ID");const{data:a}=await s.post("/oauth/cursor/import",{accessToken:e.accessToken,machineId:e.machineId});return a}return{success:!1,error:`Import token is not supported for "${t}" — use OAuth or device flow`}}async function X(){const{data:t}=await s.get("/oauth/cursor/auto-import");return t}async function Y(t){const{data:e}=await s.post("/oauth/kiro/api-key",t);return e}async function Z(t){const{data:e}=await s.post("/oauth/kiro/import",t);return e}async function tt(t){const{data:e}=await s.post("/oauth/kiro/import-cli-proxy",t);return e}async function et(t){var f,m,l,c,w;const e=(f=t.baseUrl)==null?void 0:f.trim();if(!e)return{ok:!1,success:!1,message:"No upstream base URL to import models from",models:[]};const a=(m=t.provider)!=null&&m.toLowerCase().includes("openrouter")?"openrouter-free":((l=t.provider)==null?void 0:l.toLowerCase())==="opencode-zen"?"opencode-all":(c=t.provider)!=null&&c.toLowerCase().includes("opencode")?"opencode-free":(w=t.provider)!=null&&w.toLowerCase().includes("mimo")?"mimo-free":"openrouter-free";try{const{data:g}=await s.get("/providers/suggested-models",{params:{url:e,type:a}}),h=(g.data??[]).map(p=>p.id).filter(p=>!!p);return{ok:h.length>0,success:h.length>0,message:h.length?`Found ${h.length} models`:"No models matched the catalog filter",models:h,count:h.length}}catch(g){return{ok:!1,success:!1,message:(g==null?void 0:g.message)||"Import failed",error:(g==null?void 0:g.message)||"Import failed",models:[]}}}export{z as A,B,$ as C,H as a,G as b,V as c,J as d,j as e,X as f,S as g,D as h,O as i,R as j,N as k,P as l,et as m,K as n,b as o,F as p,U as q,E as r,q as s,_ as t,I as u,Y as v,Z as w,tt as x,W as y,Q as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as n,j as t}from"./react-vendor-xnYrwzsL.js";import{R as l}from"./ripple-button-
|
|
1
|
+
import{r as n,j as t}from"./react-vendor-xnYrwzsL.js";import{R as l}from"./ripple-button-BrLlmKvT.js";import{e as m,c as u}from"./index-CkR38iPY.js";import{ag as d,ad as f}from"./icons-vendor-CUx7SB5V.js";function w({value:i,className:r,label:a="Copy",onCopy:s,iconOnly:c=!1}){const[e,o]=n.useState(!1);async function p(){try{await navigator.clipboard.writeText(i),o(!0),window.setTimeout(()=>o(!1),1500),s==null||s()}catch{}}return t.jsx(m,{label:e?"Copied":a||"Copy",children:t.jsxs(l,{type:"button",variant:"outline",size:"sm",onClick:p,className:u(r),"aria-label":a||"Copy",children:[e?t.jsx(d,{className:"h-3.5 w-3.5"}):t.jsx(f,{className:"h-3.5 w-3.5"}),c?null:e?"Copied":a]})})}export{w as C};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as u,j as b}from"./react-vendor-xnYrwzsL.js";import{a as S,u as I,b as F,m as R}from"./motion-vendor-g5fpGzmJ.js";import{c as N,y as x}from"./index-
|
|
1
|
+
import{r as u,j as b}from"./react-vendor-xnYrwzsL.js";import{a as S,u as I,b as F,m as R}from"./motion-vendor-g5fpGzmJ.js";import{c as N,y as x}from"./index-CkR38iPY.js";import{u as U}from"./query-vendor-DVevaSVS.js";const $={type:"spring",stiffness:300,damping:25};function j({value:e,prefix:n="",suffix:t="",decimals:r=0,locale:s="id-ID",className:a}){const c=S(e,$),d=I(),m=u.useRef(e),o=u.useRef(null),i=u.useRef(new Intl.NumberFormat(s,{minimumFractionDigits:r,maximumFractionDigits:r})),[f,g]=u.useState(!1);u.useEffect(()=>{i.current=new Intl.NumberFormat(s,{minimumFractionDigits:r,maximumFractionDigits:r})},[r,s]);const y=F(c,p=>`${n}${i.current.format(Number.isFinite(p)?p:0)}${t}`),[T,h]=u.useState(`${n}${i.current.format(Number.isFinite(e)?e:0)}${t}`);return u.useEffect(()=>{if(c.set(e),m.current!==e)return m.current=e,g(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>g(!1),220),()=>{o.current&&clearTimeout(o.current)}},[c,e]),u.useEffect(()=>y.on("change",h),[y]),b.jsx(R.span,{className:N("tabular-nums text-foreground",a),animate:{transform:f&&!d?"translateY(-1px) scale(1.015)":"translateY(0) scale(1)"},transition:{duration:.18,ease:[.23,1,.32,1]},children:T})}function D(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e):0}function q(e){const n=D(e.cachedTokens),t=D(e.cacheCreationTokens),r=n>0,s=[r?`HIT · ${n.toLocaleString("id-ID")}`:"MISS"];return t>0&&s.push(`+${t.toLocaleString("id-ID")}`),{hit:r,readTokens:n,creationTokens:t,label:s.join(" "),title:r?`Cache hit: ${n.toLocaleString("id-ID")} tokens read${t>0?`; ${t.toLocaleString("id-ID")} tokens created`:""}`:t>0?`Cache miss: ${t.toLocaleString("id-ID")} tokens created`:"Cache miss: no cached tokens read"}}const C=new Set(["usage-stats","usage-history","usage-chart","usage-heatmap","usage-request-details","request-detail"]);function Q(){const e=U();u.useEffect(()=>{let n=!1,t=null,r=null,s=null,a=1e3;const c=()=>{s=null,!n&&e.invalidateQueries({predicate:i=>{const f=i.queryKey[0];return typeof f=="string"&&C.has(f)}})},d=()=>{s||(s=setTimeout(c,0))},m=()=>{n||r||(r=setTimeout(()=>{r=null,o()},a),a=Math.min(a*2,1e4))},o=()=>{if(n||t)return;const i=new EventSource("/api/usage/stream");t=i,i.onopen=()=>{n||t!==i||(a=1e3)},i.onmessage=()=>{n||t!==i||d()},i.onerror=()=>{t===i&&(i.close(),t=null,m())}};return o(),()=>{n=!0,r&&clearTimeout(r),s&&clearTimeout(s),r=null,s=null,t==null||t.close(),t=null}},[e])}const l=16500,E="USD",k=new Intl.NumberFormat("id-ID",{style:"currency",currency:"IDR",currencyDisplay:"symbol",minimumFractionDigits:0,maximumFractionDigits:0});function A(e){return e==="IDR"?"IDR":E}function L(e,n,t=l){const r=Number(e);if(!Number.isFinite(r))return 0;if(n==="USD")return Math.max(0,r);const s=Number(t);return Math.max(0,r)*(Number.isFinite(s)&&s>0?s:l)}function K(e,n,t=l){const r=L(e,n,t);return n==="USD"?`$${r>=1?r.toFixed(2):r.toFixed(4)}`:k.format(r)}async function G(){const{data:e}=await x.get("/settings/currency");return{currency:A(e.currency),usdToIdr:Number.isFinite(Number(e.usdToIdr))&&Number(e.usdToIdr)>0?Number(e.usdToIdr):l,rateUpdatedAt:typeof e.rateUpdatedAt=="string"?e.rateUpdatedAt:null,rateSource:e.rateSource||"fallback"}}export{l as F,j as S,L as a,G as b,K as f,q as g,A as n,Q as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as o}from"./react-vendor-xnYrwzsL.js";import{e as a,c as r}from"./index-
|
|
1
|
+
import{j as o}from"./react-vendor-xnYrwzsL.js";import{e as a,c as r}from"./index-CkR38iPY.js";function f({active:e,onToggle:t,disabled:n,className:i,activeLabel:s="Active",inactiveLabel:l="Inactive"}){return o.jsx(a,{label:e?"On":"Off",children:o.jsx("button",{type:"button",role:"switch","aria-checked":e,"aria-label":e?"On":"Off",disabled:n,onClick:t,className:r("relative inline-flex h-5 w-9 shrink-0 items-center rounded-full p-0.5 touch-manipulation","transition-colors duration-150 ease-out outline-none","pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-6 pointer-coarse:after:min-w-6","focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",e?"bg-primary":"bg-muted-foreground/30",n&&"cursor-not-allowed opacity-50",!n&&"cursor-pointer",i),children:o.jsx("span",{className:r("pointer-events-none block h-4 w-4 rounded-full bg-white","transition-transform duration-150 ease-out",e?"translate-x-4":"translate-x-0")})})})}export{f as F};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as r}from"./react-vendor-xnYrwzsL.js";import{c as t}from"./index-
|
|
1
|
+
import{j as r}from"./react-vendor-xnYrwzsL.js";import{c as t}from"./index-CkR38iPY.js";function l({className:e,...a}){return r.jsx("div",{className:t("relative flex flex-col rounded-2xl bg-muted/72 p-1","*:[[data-slot=frame-panel]+[data-slot=frame-panel]]:mt-1",e),"data-slot":"frame",...a})}function m({className:e,...a}){return r.jsx("div",{className:t("relative rounded-xl border-x border-b border-border border-t-0 bg-background bg-clip-padding p-5",e),"data-slot":"frame-panel",...a})}function n({className:e,...a}){return r.jsx("header",{className:t("flex flex-col px-4 py-3 sm:px-5 sm:py-4",e),"data-slot":"frame-panel-header",...a})}function d({className:e,...a}){return r.jsx("div",{className:t("font-semibold text-sm",e),"data-slot":"frame-panel-title",...a})}function p({className:e,...a}){return r.jsx("footer",{className:t("px-4 py-3 sm:px-5 sm:py-4",e),"data-slot":"frame-panel-footer",...a})}export{l as F,n as a,d as b,m as c,p as d};
|