@mangostudio/cli-linux-x64 0.1.0-canary.f244aa2 → 0.1.0-canary.f67cc5d

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.
@@ -0,0 +1,90 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownContentRenderer-ByynE5sq.js","assets/rolldown-runtime-BYbx6iT9.js","assets/ui-BEql6gkw.js","assets/markdown-parser-B0W8Yv4o.js"])))=>i.map(i=>d[i]);
2
+ import{a as e}from"./rolldown-runtime-BYbx6iT9.js";import{i as t,n,r,t as i}from"./ui-BEql6gkw.js";import{$ as a,A as o,B as s,Bt as c,C as l,D as u,E as d,F as f,Ft as p,G as m,H as h,Ht as g,I as _,It as v,J as y,K as b,L as x,Lt as S,M as C,Mt as w,N as ee,Nt as te,O as ne,P as re,Pt as T,Q as E,R as ie,Rt as ae,S as oe,T as se,U as ce,Ut as le,V as ue,Vt as de,W as fe,X as pe,Y as me,Z as he,_ as ge,a as _e,at as ve,b as ye,c as be,ct as xe,d as Se,dt as Ce,et as we,f as Te,ft as D,g as Ee,h as De,ht as O,i as Oe,it as ke,j as Ae,jt as je,k as Me,l as Ne,lt as Pe,m as Fe,mt as Ie,n as Le,nt as Re,o as ze,ot as Be,p as Ve,pt as k,q as He,r as Ue,rt as We,s as Ge,st as Ke,t as qe,tt as Je,u as A,ut as j,v as Ye,w as Xe,x as Ze,y as Qe,z as $e,zt as et}from"./vendor-Dja0k3Kp.js";import{a as tt,i as nt,n as M,o as rt,r as it,t as at}from"./vendor-deps-DHoTlQF_.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var N=e(t(),1),ot=w();function st(){return typeof window<`u`&&window.location?.origin?window.location.origin:`http://localhost:3001`}var ct=je({baseURL:st(),basePath:`/api/auth`}),lt=null;function ut(e){lt=e}function dt(){lt?.()}var ft=new rt({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,refetchOnReconnect:!0,staleTime:1e3*30}}}),P=r(),pt=(0,N.createContext)(null);function mt({children:e}){let[t,n]=(0,N.useState)([]),r=(0,N.useCallback)((e,t=`info`)=>{let r=crypto.randomUUID();n(n=>[...n,{id:r,message:e,type:t}]),setTimeout(()=>{n(e=>e.filter(e=>e.id!==r))},4e3)},[]),i=(0,N.useCallback)(e=>{n(t=>t.filter(t=>t.id!==e))},[]),a={success:`border-success/30 text-success`,error:`border-error/30 text-error`,info:`border-outline-variant/30 text-on-surface`};return(0,P.jsxs)(pt,{value:{toast:r},children:[e,(0,P.jsx)(`div`,{className:`fixed bottom-4 right-4 z-50 flex flex-col gap-2 pointer-events-none`,children:t.map(e=>(0,P.jsxs)(`div`,{className:`glass-panel pointer-events-auto flex items-center gap-3 px-4 py-3 rounded-xl border text-sm max-w-sm ${a[e.type]}`,children:[(0,P.jsx)(`span`,{className:`flex-1`,children:e.message}),(0,P.jsx)(`button`,{type:`button`,onClick:()=>i(e.id),className:`shrink-0 opacity-50 hover:opacity-100 transition-opacity cursor-pointer`,children:(0,P.jsx)(Ue,{size:14})})]},e.id))})]})}function F(){let e=(0,N.use)(pt);if(!e)throw Error(`useToast deve ser usado dentro de ToastProvider`);return e}var I={auth:{loginTitle:`Mango Studio`,signupTitle:`Create Account`,emailLabel:`Email`,emailPlaceholder:`you@email.com`,passwordLabel:`Password`,passwordPlaceholder:`••••••••`,signupPasswordLabel:`Password (8 characters minimum)`,nameLabel:`Name`,namePlaceholder:`Your name`,loginButton:`Sign In`,loginLoading:`Signing in...`,signupButton:`Create Account`,signupLoading:`Creating...`,loginLink:`Sign in`,signupLink:`Create account`,noAccount:`Don't have an account?`,hasAccount:`Already have an account?`,loginError:`Login failed`,signupError:`Account creation failed`,logoutButton:`Sign Out`,logoutLoading:`Signing out...`,logoutError:`Logout failed. Please try again.`},chat:{newChat:`New Chat`,empty:`Start a conversation`,deleted:`Chat deleted`,editTitle:`Edit title`,deleteTitle:`Delete chat`,sectionLabel:`Chats`,stopGenerating:`Stop`,streaming:`Generating...`,input:{modeChat:`Chat`,modeAgent:`Agent`,modeImage:`Create Image`,send:`Send`,generate:`Generate`,stop:`Stop`,placeholder:`Ask the AI model anything...`,imagePlaceholder:`Describe your image...`,addReferenceImage:`Add reference image`,createImages:`Create images`,createImagesHint:`Hint to the model to use the image generation tool`,selectAgent:`Select agent`,agentsLoading:`Loading agents...`},feed:{emptyTitle:`Start a conversation or create an image`,emptySubtitle:`Switch to Create Image mode to generate art`,generatingImage:`Generating image...`,statusGenerating:`Generating`,statusThinking:`Thinking`,statusGenerated:`Generated`,statusReplied:`Replied`,modelFallback:`AI model`,modelStatus:`{status} with: {model}`,download:`Download`,saveToGallery:`Save to Gallery`,regenerate:`Regenerate`,imageUnavailable:`Image no longer available`,imageUnavailableHint:`The image was deleted, moved, or is not accessible yet.`,generatedImageAlt:`Generated image`,imageGenerationFailed:`Image generation failed`,styleParams:`Style Parameters`,thoughtFor:`Thought for {time}`,respondedIn:`Responded in {time}`,noResponse:`No response`,neuralDiffusionPath:`Using Neural Diffusion Path.`,createImageBadge:`Create Image`,subagentTrace:`Subagent trace`,subagentPendingName:`Subagent`,subagentStatusCompleted:`Completed`,subagentStatusFailed:`Failed`,subagentStatusAborted:`Aborted`,subagentStatusTimeout:`Timed out`,subagentTools:`{count} tools`,subagentNoTools:`No tools`,subagentLastMessage:`Last message`,subagentMessages:`Messages`,subagentToolCalls:`Tool calls`,subagentLifecycle:`Lifecycle`,subagentLifecycleDelegationStarted:`Delegation started`,subagentLifecycleDelegationCompleted:`Delegation completed`,subagentLifecycleDelegationFailed:`Delegation failed`,subagentLifecycleAttempt:`Attempt {attempt}`,subagentLifecycleRecovered:`Recovered response`,subagentLifecycleTimeout:`Timed out`,subagentLifecycleFallback:`Fallback response created`},context:{label:`Context`,tokens:`~{used} / {limit} tokens`,modeStateful:`Stateful`,modeReplay:`Replay`,modeCompacted:`Compacted`,modeDegraded:`Degraded`,warning:`This conversation is approaching the model context limit.`,danger:`MangoStudio may need to compact or leave stateful mode.`,critical:`This conversation can no longer remain stateful on the current provider.`,keepHistory:`Original messages stay in chat history by default.`,compactAction:`Compact and continue`,newChatAction:`Start summarized chat`,continueAction:`Continue anyway`,compactPending:`Compacting...`,newChatPending:`Starting chat...`,compactedSuccess:`Chat compacted`,summarizedChatSuccess:`Summarized chat started`,compactFailed:`Failed to compact chat`,summarizedChatFailed:`Failed to start summarized chat`},fallback:{toReplay:`Stateful continuation is no longer available. Continuing with transcript replay.`,generic:`Conversation mode changed from {from} to {to}.`},continuation:{title:{providerChanged:`{fromProvider} {fromMode} state cannot be reused by {provider}. Replayed transcript and started {provider} {toMode} continuation.`,modelChanged:`Model changed to {model}. Replayed transcript on {provider} {toMode}.`,systemPromptChanged:`System prompt changed. Replayed transcript on {provider} {toMode}.`,toolsetChanged:`Toolset changed. Replayed transcript on {provider} {toMode}.`,agentChanged:`Agent changed. Replayed transcript on {provider} {toMode}.`,agentRuntimeChanged:`Agent settings changed. Replayed transcript on {provider} {toMode}.`,cursorExpired:`{provider} {fromMode} cursor expired. Falling back to transcript replay.`,cursorInvalid:`{provider} {fromMode} cursor was invalidated. Falling back to transcript replay.`,toolResultCursorLoss:`{provider} {fromMode} cursor was lost during tool execution. Response may be incomplete.`,envelopeMalformed:`Stored continuation state was unreadable. Restarting with transcript replay.`},recovered:`(recovered)`,notRecovered:`(not recovered)`},cursorLost:`Cursor lost — fallback to {detail}`,toolLoopExhausted:`Tool loop limit reached`,genericFailure:`Generation failed`,copyCode:`Copy code`,codeCopied:`Copied!`,copyMessage:`Copy message`,messageCopied:`Message copied!`,scrollToBottom:`Scroll to bottom`,emptyGreeting:`Hello, {name}!`,emptySubtitle:`How can I help you today?`,suggestion1:`Explain a complex concept simply`,suggestion2:`Write a Python script to...`,suggestion3:`Help me debug a problem`,suggestion4:`Create an image`,systemEvents:{chatCompacted:`Context compacted into a summary`,summaryHandoff:`This chat started from a summarized handoff`,cursorInternalToolCall:`Cursor used {tool}`},titleGenerationFailed:`Failed to generate chat title`},studio:{title:`Studio`,empty:`Image creation workspace — coming soon.`},gallery:{title:`Gallery`,empty:`Your creations will appear here.`,download:`Download Full Image`,view:`View`},settings:{title:`Settings`,tabs:{general:`General`,connectors:`Connectors`,providers:`Providers`,appearance:`Appearance`,context:`Context`,agents:`Agents`,prompts:`Prompts`,tools:`Tools`,metrics:`Metrics`,logs:`Logs`},context:{title:`Context`,description:`Control when MangoStudio warns, compacts, or starts a summarized handoff.`,keepHistory:`Compaction keeps the original chat transcript unless you clean it up later.`,behaviorLabel:`Compaction behavior`,behaviorDescription:`Choose what happens when a chat reaches your warning threshold.`,behaviorOptions:{ask:`Ask every time`,autoCompact:`Auto compact current chat`,newChat:`Continue in summarized chat`,off:`Turn prompts off`},providerCompactionLabel:`Allow provider-side compaction`,providerCompactionDescription:`When supported, let the provider compact cursor-based state near your warning threshold.`,warningThresholdLabel:`Warning threshold`,warningThresholdDescription:`Show compaction choices when context usage reaches this value.`,dangerThresholdLabel:`Danger threshold`,dangerThresholdDescription:`Escalate the warning tone before the hard stop threshold.`,hardStopThresholdLabel:`Hard stop threshold`,hardStopThresholdDescription:`Treat context pressure as critical at or above this value.`,summaryModelLabel:`Preferred summary model`,summaryModelDescription:`Use the current chat model or force a specific text model for summaries.`,summaryModelCurrent:`Use current chat model`,thresholdHint:`{value}% of context`},prompts:{defaultPromptsLabel:`Default Prompts`,ruleFilesLabel:`Rule Files`,customRulesLabel:`Custom Rules`,customRulesDescription:`Add paths to custom .md files to be included in generation requests.`,textSystemPromptLabel:`Default Text System Prompt`,textSystemPromptPlaceholder:`e.g. You are a helpful creative partner. Be concise and insightful...`,imageSystemPromptLabel:`Default Image System Prompt`,imageSystemPromptPlaceholder:`e.g. Always generate images in a cinematic style with dramatic lighting...`,agentsMdLabel:`AGENTS.md`,agentsMdDescription:`Repository rules defined in the AGENTS.md file.`,claudeMdLabel:`CLAUDE.md`,claudeMdDescription:`Global instructions defined in the CLAUDE.md file.`,enabledLabel:`Enabled`,injectionRoleLabel:`Injection Role`,injectionRoleSystem:`Send as System Prompt`,injectionRoleUser:`Send as User Prompt`,frequencyLabel:`Frequency`,frequencyFirstTurn:`Send only in first prompt`,frequencyFirstTurnHint:`Recommended`,frequencyEveryTurn:`Send every time`,addRule:`Add Rule`,removeRule:`Remove`,rulePathLabel:`Path`,rulePathPlaceholder:`e.g. ~/my-projects/rules.md`},agents:{title:`Agents`,description:`Configure built-in and Markdown agents for focused workflows.`,create:`Create Agent`,createTitle:`New Agent`,newAgentName:`New Agent`,newAgentDescription:`Describe when this agent should be used.`,builtIn:`Built-in`,user:`User`,name:`Name`,slug:`File Slug`,agentDescription:`Description`,role:`Role`,roles:{primary:`Primary`,subagent:`Subagent`,both:`Both`},systemPrompt:`System Prompt`,model:`Model Override`,modelDefaultOption:`Use the agent default model`,thinking:`Enable Thinking`,reasoningEffort:`Reasoning Effort`,reasoningEfforts:{low:`Low`,medium:`Medium`,high:`High`,xhigh:`Extra High`,max:`Maximum`},maxToolIterations:`Max Tool Iterations`,toolsEnabled:`Tools Enabled`,toolAllowlist:`Allowed Tools`,noTools:`No tools available.`,subagents:`Allowed Subagents`,noSubagents:`No eligible subagents exist yet.`,path:`Path`,friendlyMode:`Fields`,rawMode:`Markdown`,rawMarkdown:`Raw Markdown`,preview:`Preview`,previewing:`Previewing...`,save:`Save`,saving:`Saving...`,reset:`Reset`,delete:`Delete`,cancel:`Cancel`,retry:`Retry`,saved:`Agent saved`,deleted:`Agent deleted`,previewed:`Markdown validated`,loadError:`Failed to load agents`,saveError:`Failed to save agent`,createError:`Failed to create agent`,deleteError:`Failed to delete agent`,previewError:`Failed to preview agent`,deleteTitle:`Delete agent`,deleteDescription:`This Markdown-backed agent will be removed from disk.`,deleteConfirm:`Delete agent`,deleting:`Deleting...`,sectionIdentity:`Identity`,sectionBehavior:`Behavior`,sectionReasoning:`Reasoning`,sectionTools:`Tools`,unsavedChanges:`Unsaved changes`,confirmResetTitle:`Discard changes?`,confirmResetDescription:`Any unsaved changes will be lost.`,confirmReset:`Discard`,emptyStateTitle:`No agents yet`,emptyStateDescription:`Create your first agent to get started.`,selectAgent:`Select an agent`,builtInAgents:`Built-in Agents`,userAgents:`Custom Agents`},general:{languageLabel:`Language`,languageDescription:`User interface language`,textPromptLabel:`Default Text System Prompt`,textPromptPlaceholder:`e.g. You are a helpful creative partner. Be concise and insightful...`,imagePromptLabel:`Default Image System Prompt`,imagePromptPlaceholder:`e.g. Always generate images in a cinematic style with dramatic lighting...`,imageQualityLabel:`Default Image Quality`,maxToolIterationsLabel:`Max Tool Iterations`,maxToolIterationsDescription:`Upper bound on how many tool-calling rounds the model may take in a single turn.`,maxToolIterationsHint:`{value} of 1000`,chatTitlesLabel:`Chat Titles`,chatTitlesDescription:`Automatically rename timestamped new chats from the first user prompt.`,chatTitlesToggleLabel:`Auto rename new chats`,chatTitleSourceLabel:`Title source`,chatTitleSourcePrompt:`First prompt text`,chatTitleSourceModel:`Generate with a model`,chatTitleModelLabel:`Title model`,chatTitleModelDescription:`Use the current chat model or force a specific text model for title generation.`,chatTitleModelCurrent:`Use the current chat model`,chatTitlePrefixLengthLabel:`Prompt title length`,chatTitlePrefixLengthDescription:`Use the first characters from the prompt when a timestamped chat gets its first message.`,chatTitlePrefixLengthHint:`{value} characters`,multiAgentLabel:`Multi-agent turns`,multiAgentDescription:`Allow agents to delegate bounded work to configured subagents during a turn.`,multiAgentEnabledLabel:`Enable delegation`,chatDelegationEnabledLabel:`Allow Chat mode delegation`,traceVisibilityLabel:`Trace visibility`,traceVisibilityCompact:`Compact`,traceVisibilityFull:`Full`,traceVisibilityOff:`Off`,maxDepthLabel:`Max delegation depth`,maxSubagentCallsLabel:`Max subagent calls`,timeoutLabel:`Subagent timeout`,defaultMaxTurnsLabel:`Default subagent turns`,secondsHint:`{value}s`},connectors:{title:`AI Connectors`,addButton:`Add Connector`,emptyTitle:`No Connectors Found`,emptyDescription:`Add your first API key to start generating.`,deleteConfirm:`Are you sure you want to delete this connector?`,addModalTitle:`Add Connector`,addModalDescription:`Choose the provider, configure the API key and storage.`,chatgptAddModalDescription:`Connect a ChatGPT subscription in your browser. No API key is required.`,providerLabel:`Provider`,selectProvider:`Select Provider`,baseUrlLabel:`Base URL`,baseUrlRequired:`Base URL is required for OpenAI Compatible connectors.`,baseUrlPlaceholder:`https://api.example.com/v1`,deepseekBaseUrlPlaceholder:`https://api.deepseek.com`,organizationIdLabel:`Organization ID (optional)`,organizationIdPlaceholder:`org-...`,organizationIdHelper:`Required only for keys scoped to a specific OpenAI organization.`,projectIdLabel:`Project ID (optional)`,projectIdPlaceholder:`proj_...`,projectIdHelper:`Required for project-scoped keys in the OpenAI API.`,nameLabel:`Name`,namePlaceholder:`e.g. Personal Project`,apiKeyLabel:`API Key`,apiKeyPlaceholder:`sk-...`,saveToLabel:`Save To`,sources:{bunSecrets:`OS Secret Store`,bunSecretsDesc:`Native secure storage`,configFile:`config.toml`,configFileDesc:`~/.mango/config.toml`,envFile:`.env File`,envFileDesc:`App root .env`},cancelButton:`Cancel`,addConnectorButton:`Add Connector`,validating:`Validating...`,chatgptOAuthTitle:`Sign in with ChatGPT`,chatgptOAuthDescription:`MangoStudio opens OpenAI sign-in and saves rotating tokens in the system secret store.`,chatgptSignInButton:`Sign in with ChatGPT`,chatgptSigningIn:`Opening sign-in...`,chatgptWaitingTitle:`Complete the sign-in in your browser`,chatgptWaitingDescription:`After approval, this connector will appear here with your ChatGPT models.`,chatgptRemoteAccessHint:`Your browser must be able to reach this computer to complete the local callback.`,chatgptCancelSignIn:`Cancel sign-in`,chatgptSignInSucceeded:`ChatGPT connected.`,chatgptPortBusyError:"Port 1455 is already in use. Close any running `codex login` and retry.",chatgptDeniedError:`ChatGPT sign-in was not completed. Try again.`,chatgptExpiredError:`The sign-in session expired. Start sign-in again.`,chatgptFailedError:`Failed to start ChatGPT sign-in.`,chatgptPopupBlocked:`Your browser blocked the sign-in window. Allow pop-ups for MangoStudio and retry.`,chatgptNameRequired:`Name is required to connect ChatGPT.`,chatgptReauthWarning:`This ChatGPT session expired or was revoked. Sign in again to use this connector.`,chatgptReauthenticate:`Re-authenticate`,chatgptReauthenticating:`Waiting for sign-in...`,chatgptReconnectSuccess:`ChatGPT reconnected.`,chatgptSignedInAs:`Signed in as {account}`,chatgptAccountUnknown:`ChatGPT account`,chatgptPlanBadge:`{plan} plan`,chatgptPlanPlus:`Plus`,chatgptPlanPro:`Pro`,chatgptPlanTeam:`Team`,chatgptPlanFree:`Free`,chatgptPlanUnknown:`Unknown`,chatgptPlanCustom:`{plan}`,chatgptUsageWindowHours:`{hours}h limit`,chatgptUsageWindowDays:`{days}-day limit`,chatgptUsagePrimaryFallback:`Session limit`,chatgptUsageSecondaryFallback:`Weekly limit`,chatgptUsageUsed:`{percent}% used`,chatgptUsageResets:`resets in {time}`,chatgptUsageLimitReached:`Limit reached`,chatgptUsageResetCredits:`{count} reset credits`,chatgptUsageResetCreditsNextExpiry:`next expires in {time}`,chatgptUsageCreditsBalance:`Credits: {balance}`,chatgptUsageCreditsUnlimited:`Unlimited credits`,chatgptUsageUpdated:`updated {time} ago`,chatgptRedeemButton:`Use a rate-limit reset`,chatgptRedeeming:`Redeeming...`,chatgptRedeemConfirmTitle:`Use a rate-limit reset?`,chatgptRedeemConfirmBody:`This spends one of your {count} reset credits to restore exhausted rate-limit windows. It cannot be undone.`,chatgptRedeemConfirmAction:`Use reset`,chatgptRedeemSuccess:`Rate limit reset — {count} window(s) restored.`,chatgptRedeemNothingToReset:`Nothing to reset — no rate-limit window is exhausted right now.`,chatgptRedeemNoCredit:`No reset credits are available on this account.`,chatgptRedeemAlreadyRedeemed:`This reset was already redeemed.`,chatgptRedeemFailed:`Could not redeem the reset credit. Retrying will not spend a second credit.`,chatgptPromoDismiss:`Dismiss announcement`,chatgptStatsToggle:`Usage stats`,chatgptStatsLoading:`Loading usage stats...`,chatgptStatsEmpty:`No usage stats available for this account.`,chatgptStatsLifetime:`Lifetime tokens`,chatgptStatsPeakDay:`Peak day`,chatgptStatsLongestTurn:`Longest turn`,chatgptStatsCurrentStreak:`Current streak`,chatgptStatsLongestStreak:`Longest streak`,chatgptStatsStreakValue:`{days} days`,chatgptStatsChartTitle:`Tokens per day — last 30 days`,chatgptStatsDayTokens:`{date}: {tokens} tokens`,chatgptPaceOnPace:`on pace`,chatgptPaceRunningHot:`running hot`,chatgptPaceProjected:`may run out in {time}`,chatgptHistoryToggle:`Usage history`,chatgptHistoryLoading:`Loading usage history...`,chatgptHistoryEmpty:`No usage history recorded yet.`,chatgptHistoryChartTitle:`Weekly limit — last {days} days`,chatgptHistoryPoint:`{time}: {percent}% used`,chatgptHistoryDisclaimer:`Usage as observed from MangoStudio; other apps burn the same quota between refreshes.`,chatgptAlertThresholdLabel:`Quota alerts`,chatgptAlertThresholdOff:`Off`,chatgptAlertThresholdOption:`At {percent}%`,chatgptAlertThresholdCrossed:`{name}: {window} is at {percent}% of its quota`,chatgptAlertWindowReset:`{name}: {window} reset — your quota is back`,cursorNodeRequired:`You need NodeJS installed to run Cursor SDK Agents.`,cursorNodeNotFound:"`node` binary not found",cursorNodeInvalid:`The configured Node.js binary at {path} is not runnable. Fix or remove MANGO_NODE_PATH / cursor.node_path.`,cursorNodeVersionInsufficient:`Node.js {minVersion}+ is required for Cursor SDK Agents (found {version}).`,cursorSidecarMissing:`Cursor SDK sidecar script is missing.`,cursorSidecarMissingAt:`Cursor SDK sidecar script is missing at {path}.`,cursorSdkMissing:`Cursor SDK package is missing from the sidecar. Reinstall MangoStudio.`,cursorSdkMissingAt:`Cursor SDK package is missing from the sidecar at {path}. Reinstall MangoStudio.`,cursorSdkIncomplete:`Cursor SDK package is incomplete. Reinstall MangoStudio.`,cursorSdkIncompleteAt:`Cursor SDK package is incomplete at {path}. Reinstall MangoStudio.`,cursorNativeRuntimeMissing:`This platform has no Cursor native runtime in the sidecar. Reinstall MangoStudio.`,cursorNativeRuntimeMissingPackage:`Cursor native runtime package {packageName} is missing. Reinstall MangoStudio.`,cursorRuntimeDoctorHint:"Run `mango doctor` for a full Cursor runtime checklist (use `--all` to check without a connector).",modalsModalTitle:`Choose Available Models`,modelsModalTitle:`Choose Available Models`,modelsModalDescription:`Models enabled for`,modelsModalDescriptionSuffix:`will be available in the chat.`,textModelsLabel:`Text Models`,imageModelsLabel:`Image Models`,doneButton:`Done`,configureModels:`Configure Models`,deleteConnector:`Delete Connector`,sharedConnector:`Shared`,managedExternally:`Managed externally via environment configuration.`,sharedDeleteBlocked:`This shared connector must be removed from the configuration file.`,searchModelsPlaceholder:`Search models by name or ID...`,noModelsDiscovered:`No models have been discovered for this connector yet.`,addSuccess:`Connector added successfully!`,deleteSuccess:`Connector deleted successfully!`,updateModelsSuccess:`Models updated successfully!`,errorRequired:`Name and API Key are required.`,failedToLoad:`Failed to load connectors`,failedToAdd:`Failed to add connector`,failedToDelete:`Failed to delete connector`,failedToUpdateModels:`Failed to update models`,unknownError:`An unknown error occurred`,noSearchResults:`No models match your search`},providers:{title:`AI Providers`,backToMenu:`Back to providers`,sectionReasoning:`Reasoning & Thinking`,sectionTools:`Tool Configuration`,sectionCache:`Prompt Caching`,sectionAdvanced:`Advanced`,save:`Save`,saving:`Saving...`,cancel:`Cancel`,reset:`Reset to defaults`,saved:`Settings saved`,saveError:`Failed to save provider settings`,loadError:`Failed to load providers`,invalidProvider:`Provider not found`,perProviderSettings:`Per-provider runtime settings override global defaults.`,noProviders:`No AI providers available.`,modelsEnabled:`{count} models enabled`,connectorsCount:`{count} connectors`,thinkingEnabled:`Enable thinking`,reasoningEffort:`Reasoning effort`,maxOutputTokens:`Max output tokens`,maxToolIterations:`Max tool iterations`,parallelToolCalls:`Parallel tool calls`,compaction:`Provider-side compaction`,cachePreference:`Prompt cache preference`,cacheAuto:`Auto`,cacheStablePrefix:`Stable prefix`,cacheOff:`Off`,capabilityThinking:`Thinking`,capabilityTools:`Tools`,capabilityCaching:`Caching`,capabilityCompaction:`Compaction`,reservedForFuture:`Reserved for future settings`,maxOutputTokensPlaceholder:`1 – {limit}`},tools:{title:`Tools`,description:`Enable or disable tools and configure their parameters.`,categories:{system:`System`,image:`Image`,interaction:`Interaction`},enabled:`Enabled`,disabled:`Disabled`,cannotDisable:`This tool cannot be disabled.`,save:`Save`,saving:`Saving...`,saved:`Settings saved`,saveError:`Failed to save tool settings`,loadError:`Failed to load tools`,noTools:`No tools available.`,maxToolIterationsLabel:`Max Tool Iterations`,maxToolIterationsDescription:`Upper bound on how many tool-calling rounds the model may take in a single turn.`,maxToolIterationsHint:`{value} of 1000`,executionTitle:`Execution`,autoModelOption:`Auto (first available)`,letAiDecideQualityLabel:`Let AI decide quality`,letAiDecideQualityDescription:`When enabled, the AI can choose different image sizes per request.`,toolNames:{readFile:`Read file`,writeFile:`Write file`,listDirectory:`List directory`,glob:`Glob`,grep:`Grep`},toolDescriptions:{readFile:`Allows the AI to read text files from disk.`,writeFile:`Allows the AI to write text content to files on disk.`,listDirectory:`Allows the AI to list files and directories on disk.`,glob:`Allows the AI to find files and directories by glob pattern.`,grep:`Allows the AI to search file contents with regular expressions.`},parameters:{allowedPathsLabel:`Allowed paths`,allowedPathsDescription:`Paths the tool is allowed to access. Leave empty to allow all.`,deniedPathsLabel:`Denied paths`,deniedPathsDescription:`Paths the tool is denied from accessing. Leave empty to deny none.`},pathList:{add:`Add`,edit:`Edit`,delete:`Delete`,save:`Save`,cancel:`Cancel`,pathPlaceholder:`e.g. /home/user/projects`,noPaths:`No paths configured.`}},metrics:{title:`Metrics`,description:`Live in-memory counters for provider cache hit rates and probe timeout totals.`,refresh:`Refresh`,failedToLoad:`Failed to load metrics`,empty:`No provider metrics have been recorded yet.`,generatedAtLabel:`Last updated: {value}`,totalProbeTimeoutsLabel:`Probe timeouts: {value}`,cacheSectionTitle:`Cache Hit Rate`,probeSectionTitle:`Probe Timeouts by Operation`,cacheLabel:`Cache`,hitsLabel:`Hits`,missesLabel:`Misses`,hitRateLabel:`Hit rate`,caches:{sdkClient:`SDK client`,preparedRuntime:`Prepared runtime`,providerRoute:`Provider route`},operations:{healthcheck:`Healthcheck`,modelList:`Model listing`}},logs:{title:`Logs`,description:`Recent provider probe timeouts captured by the current runtime process.`,refresh:`Refresh`,failedToLoad:`Failed to load logs`,empty:`No recent provider probe timeout events.`,providerLabel:`Provider`,operationLabel:`Operation`,eventKinds:{probeTimeout:`Probe timeout`},operations:{healthcheck:`Healthcheck`,modelList:`Model listing`}},appearance:{title:`Appearance`,appTheme:{label:`App Theme`,description:`Choose the visual theme for the application`,dark:`Dark`,light:`Light`,system:`System`,comingSoon:`Coming soon`},fontSize:{label:`Font Size`,description:`Adjust the text size in chat messages`,small:`Small`,default:`Default`,large:`Large`},chatDensity:{label:`Chat Density`,description:`Control spacing between messages`,compact:`Compact`,default:`Default`,comfortable:`Comfortable`},codeTheme:{label:`Code Theme`,description:`Choose the syntax highlighting theme for code blocks`,auto:`Auto (match app theme)`,manual:`Manual`,darkPreference:`Dark preference`,lightPreference:`Light preference`,oneDarkPro:`One Dark Pro`,githubDarkDimmed:`GitHub Dark Dimmed`,githubLight:`GitHub Light`,oneLight:`One Light`}},app:{loadError:`Failed to load app settings`,saveError:`Failed to save app settings`}},common:{loading:`Loading...`,appName:`Mango Studio`,downloadFilenamePrefix:`mangostudio`,mangoStudioLogo:`Mango Studio Logo`,retry:`Retry`,noResultsFor:`No results for "{query}"`,contextIndicator:`Context usage indicator`,settingsNavigation:`Settings navigation`,openMenu:`Open menu`,closeMenu:`Close menu`,disclaimer:`Artificial Intelligence can make mistakes. Please double-check the results.`},providers:{gemini:`Google Gemini`,anthropic:`Anthropic`,openai:`OpenAI`,"openai-compatible":`OpenAI Compatible`,deepseek:`DeepSeek`,cursor:`Cursor`,chatgpt:`ChatGPT`,openrouter:`OpenRouter`},thinking:{label:`Thought process`,labelContinued:`Continued thinking`,streaming:`Thinking...`,streamingContinued:`Thinking again...`,toggle:`View reasoning`,enable:`Thinking`,enabled:`Thinking enabled`,disabled:`Thinking disabled`,effort:`Effort`,effortLow:`Low`,effortMedium:`Medium`,effortHigh:`High`,effortXHigh:`Extra High`,effortMax:`Maximum`,reasoningBadge:`Reasoning`},tools:{calling:`Calling...`,running:`Running tool`,done:`Done`,error:`Tool error`,moreCount:`+{count} more`,argsLabel:`args`,errorLabel:`error`,resultLabel:`result`,labels:{list_directory:`List`,read_file:`Read`,write_file:`Write`,glob:`Glob`,grep:`Grep`,generate_image:`Generate Image`,get_current_datetime:`Date`,bash:`Bash`,zsh:`Zsh`,powershell:`PowerShell`}},errors:{unknown:`An unknown error occurred`,imageNotSupported:`This provider does not support image generation.`,referenceImageUploadFailed:`Failed to upload reference image. Please try again.`,textGenerationFailed:`Failed to get a response. Please try again.`,imageGenerationFailed:`Failed to generate image. Please try again.`,streamRequestFailed:`Stream request failed`,streamResponseNoBody:`Stream response has no body`},models:{loading:`Loading models...`,unavailable:`Models unavailable`,noModelsAvailable:`No models available`,preview:`Preview`},api:{unauthorized:`Unauthorized`},generation:{toolLoopExhausted:`The model exceeded the maximum number of tool interactions.`}},ht={auth:{loginTitle:`Mango Studio`,signupTitle:`Criar Conta`,emailLabel:`Email`,emailPlaceholder:`seu@email.com`,passwordLabel:`Senha`,passwordPlaceholder:`••••••••`,signupPasswordLabel:`Senha (mínimo 8 caracteres)`,nameLabel:`Nome`,namePlaceholder:`Seu nome`,loginButton:`Entrar`,loginLoading:`Entrando...`,signupButton:`Criar Conta`,signupLoading:`Criando...`,loginLink:`Fazer login`,signupLink:`Criar conta`,noAccount:`Não tem conta?`,hasAccount:`Já tem conta?`,loginError:`Erro ao fazer login`,signupError:`Erro ao criar conta`,logoutButton:`Sair`,logoutLoading:`Saindo...`,logoutError:`Erro ao sair. Tente novamente.`},chat:{newChat:`Novo Chat`,empty:`Inicie uma conversa`,deleted:`Chat excluído`,editTitle:`Editar título`,deleteTitle:`Excluir chat`,sectionLabel:`Chats`,stopGenerating:`Parar`,streaming:`Gerando...`,input:{modeChat:`Chat`,modeAgent:`Agente`,modeImage:`Criar Imagem`,send:`Enviar`,generate:`Gerar`,stop:`Parar`,placeholder:`Pergunte ao modelo de IA...`,imagePlaceholder:`Descreva sua imagem...`,addReferenceImage:`Adicionar imagem de referência`,createImages:`Criar imagens`,createImagesHint:`Sugerir ao modelo que use a ferramenta de geração de imagens`,selectAgent:`Selecionar agente`,agentsLoading:`Carregando agentes...`},feed:{emptyTitle:`Inicie uma conversa ou crie uma imagem`,emptySubtitle:`Mude para o modo Criar Imagem para gerar arte`,generatingImage:`Gerando imagem...`,statusGenerating:`Gerando`,statusThinking:`Pensando`,statusGenerated:`Gerado`,statusReplied:`Respondido`,modelFallback:`Modelo de IA`,modelStatus:`{status} com: {model}`,download:`Baixar`,saveToGallery:`Salvar na Galeria`,regenerate:`Regenerar`,imageUnavailable:`Imagem não disponível`,imageUnavailableHint:`A imagem foi excluída, movida ou ainda não está acessível.`,generatedImageAlt:`Imagem gerada`,imageGenerationFailed:`Falha ao gerar imagem`,styleParams:`Parâmetros de Estilo`,thoughtFor:`Pensou por {time}`,respondedIn:`Respondeu em {time}`,noResponse:`Sem resposta`,neuralDiffusionPath:`Usando Neural Diffusion Path.`,createImageBadge:`Criar Imagem`,subagentTrace:`Trace de subagente`,subagentPendingName:`Subagente`,subagentStatusCompleted:`Concluído`,subagentStatusFailed:`Falhou`,subagentStatusAborted:`Abortado`,subagentStatusTimeout:`Tempo esgotado`,subagentTools:`{count} ferramentas`,subagentNoTools:`Sem ferramentas`,subagentLastMessage:`Última mensagem`,subagentMessages:`Mensagens`,subagentToolCalls:`Chamadas de ferramenta`,subagentLifecycle:`Ciclo de vida`,subagentLifecycleDelegationStarted:`Delegação iniciada`,subagentLifecycleDelegationCompleted:`Delegação concluída`,subagentLifecycleDelegationFailed:`Delegação falhou`,subagentLifecycleAttempt:`Tentativa {attempt}`,subagentLifecycleRecovered:`Resposta recuperada`,subagentLifecycleTimeout:`Tempo esgotado`,subagentLifecycleFallback:`Resposta fallback criada`},context:{label:`Contexto`,tokens:`~{used} / {limit} tokens`,modeStateful:`Stateful`,modeReplay:`Replay`,modeCompacted:`Compactado`,modeDegraded:`Degradado`,warning:`Esta conversa está se aproximando do limite de contexto do modelo.`,danger:`O MangoStudio pode precisar compactar ou sair do modo stateful.`,critical:`Esta conversa não pode mais permanecer stateful no provedor atual.`,keepHistory:`As mensagens originais continuam no histórico por padrão.`,compactAction:`Compactar e continuar`,newChatAction:`Iniciar chat resumido`,continueAction:`Continuar assim mesmo`,compactPending:`Compactando...`,newChatPending:`Iniciando chat...`,compactedSuccess:`Chat compactado`,summarizedChatSuccess:`Chat resumido iniciado`,compactFailed:`Falha ao compactar o chat`,summarizedChatFailed:`Falha ao iniciar o chat resumido`},fallback:{toReplay:`Continuação stateful não está mais disponível. Continuando com replay do transcript.`,generic:`Modo da conversa alterado de {from} para {to}.`},continuation:{title:{providerChanged:`Estado {fromProvider} {fromMode} não pode ser reutilizado por {provider}. Transcript reproduzido e continuação {provider} {toMode} iniciada.`,modelChanged:`Modelo alterado para {model}. Transcript reproduzido em {provider} {toMode}.`,systemPromptChanged:`System prompt alterado. Transcript reproduzido em {provider} {toMode}.`,toolsetChanged:`Conjunto de ferramentas alterado. Transcript reproduzido em {provider} {toMode}.`,agentChanged:`Agente alterado. Transcript reproduzido em {provider} {toMode}.`,agentRuntimeChanged:`Configurações do agente alteradas. Transcript reproduzido em {provider} {toMode}.`,cursorExpired:`Cursor {provider} {fromMode} expirou. Usando replay do transcript.`,cursorInvalid:`Cursor {provider} {fromMode} foi invalidado. Usando replay do transcript.`,toolResultCursorLoss:`Cursor {provider} {fromMode} perdido durante execução de ferramenta. Resposta pode estar incompleta.`,envelopeMalformed:`Estado de continuação armazenado era inválido. Reiniciando com replay do transcript.`},recovered:`(recuperado)`,notRecovered:`(não recuperado)`},cursorLost:`Cursor perdido — fallback para {detail}`,toolLoopExhausted:`Limite de iterações de ferramentas atingido`,genericFailure:`Falha na geração`,copyCode:`Copiar código`,codeCopied:`Copiado!`,copyMessage:`Copiar mensagem`,messageCopied:`Mensagem copiada!`,scrollToBottom:`Ir para o final`,emptyGreeting:`Olá, {name}!`,emptySubtitle:`Como posso te ajudar hoje?`,suggestion1:`Explique um conceito complexo de forma simples`,suggestion2:`Escreva um script em Python para...`,suggestion3:`Me ajude a depurar um problema`,suggestion4:`Crie uma imagem`,systemEvents:{chatCompacted:`Contexto compactado em um resumo`,summaryHandoff:`Este chat começou a partir de um resumo anterior`,cursorInternalToolCall:`Cursor usou {tool}`},titleGenerationFailed:`Falha ao gerar título do chat`},studio:{title:`Studio`,empty:`Espaço de criação de imagens — em breve.`},gallery:{title:`Galeria`,empty:`Suas criações aparecerão aqui.`,download:`Baixar imagem completa`,view:`Ver`},settings:{title:`Configurações`,tabs:{general:`Geral`,connectors:`Conectores`,providers:`Provedores`,appearance:`Aparência`,context:`Contexto`,agents:`Agentes`,prompts:`Prompts`,tools:`Ferramentas`,metrics:`Métricas`,logs:`Logs`},context:{title:`Contexto`,description:`Controle quando o MangoStudio avisa, compacta ou continua em um chat resumido.`,keepHistory:`A compactação mantém o transcript original salvo até você limpá-lo depois.`,behaviorLabel:`Comportamento de compactação`,behaviorDescription:`Escolha o que acontece quando uma conversa atinge o limite de aviso.`,behaviorOptions:{ask:`Perguntar sempre`,autoCompact:`Compactar o chat atual automaticamente`,newChat:`Continuar em um chat resumido`,off:`Desativar avisos`},providerCompactionLabel:`Permitir compactação pelo provider`,providerCompactionDescription:`Quando disponível, deixe o provider compactar o estado com cursor perto do limite de aviso.`,warningThresholdLabel:`Limite de aviso`,warningThresholdDescription:`Mostrar ações de compactação quando o uso de contexto atingir este valor.`,dangerThresholdLabel:`Limite de perigo`,dangerThresholdDescription:`Intensificar o aviso antes de atingir o limite crítico.`,hardStopThresholdLabel:`Limite crítico`,hardStopThresholdDescription:`Tratar a pressão de contexto como crítica neste valor ou acima dele.`,summaryModelLabel:`Modelo preferido para resumo`,summaryModelDescription:`Use o modelo atual do chat ou force um modelo de texto específico para os resumos.`,summaryModelCurrent:`Usar o modelo atual do chat`,thresholdHint:`{value}% do contexto`},prompts:{defaultPromptsLabel:`Prompts Padrão`,ruleFilesLabel:`Arquivos de Regras`,customRulesLabel:`Regras Personalizadas`,customRulesDescription:`Adicione caminhos para arquivos .md personalizados que serão incluídos nas requisições.`,textSystemPromptLabel:`System Prompt de Texto Padrão`,textSystemPromptPlaceholder:`ex. Você é um parceiro criativo útil. Seja conciso e perspicaz...`,imageSystemPromptLabel:`System Prompt de Imagem Padrão`,imageSystemPromptPlaceholder:`ex. Sempre gere imagens em estilo cinemático com iluminação dramática...`,agentsMdLabel:`AGENTS.md`,agentsMdDescription:`Regras do repositório definidas no arquivo AGENTS.md.`,claudeMdLabel:`CLAUDE.md`,claudeMdDescription:`Instruções globais definidas no arquivo CLAUDE.md.`,enabledLabel:`Ativado`,injectionRoleLabel:`Função de Injeção`,injectionRoleSystem:`Enviar como System Prompt`,injectionRoleUser:`Enviar como User Prompt`,frequencyLabel:`Frequência`,frequencyFirstTurn:`Enviar apenas no primeiro prompt`,frequencyFirstTurnHint:`Recomendado`,frequencyEveryTurn:`Enviar sempre`,addRule:`Adicionar Regra`,removeRule:`Remover`,rulePathLabel:`Caminho`,rulePathPlaceholder:`ex. ~/meus-projetos/regras.md`},agents:{title:`Agentes`,description:`Configure agentes integrados e agentes em Markdown para fluxos de trabalho.`,create:`Criar Agente`,createTitle:`Novo Agente`,newAgentName:`Novo Agente`,newAgentDescription:`Descreva quando este agente deve ser usado.`,builtIn:`Integrado`,user:`Usuário`,name:`Nome`,slug:`Slug do Arquivo`,agentDescription:`Descrição`,role:`Função`,roles:{primary:`Primário`,subagent:`Subagente`,both:`Ambos`},systemPrompt:`System Prompt`,model:`Modelo Sobrescrito`,modelDefaultOption:`Usar o modelo padrão do agente`,thinking:`Ativar Raciocínio`,reasoningEffort:`Esforço de Raciocínio`,reasoningEfforts:{low:`Baixo`,medium:`Médio`,high:`Alto`,xhigh:`Extra Alto`,max:`Máximo`},maxToolIterations:`Máx. Iterações de Ferramentas`,toolsEnabled:`Ferramentas Ativadas`,toolAllowlist:`Ferramentas Permitidas`,noTools:`Nenhuma ferramenta disponível.`,subagents:`Subagentes Permitidos`,noSubagents:`Nenhum subagente elegível existe ainda.`,path:`Caminho`,friendlyMode:`Campos`,rawMode:`Markdown`,rawMarkdown:`Markdown Bruto`,preview:`Pré-visualizar`,previewing:`Pré-visualizando...`,save:`Salvar`,saving:`Salvando...`,reset:`Restaurar`,delete:`Excluir`,cancel:`Cancelar`,retry:`Tentar novamente`,saved:`Agente salvo`,deleted:`Agente excluído`,previewed:`Markdown validado`,loadError:`Falha ao carregar agentes`,saveError:`Falha ao salvar agente`,createError:`Falha ao criar agente`,deleteError:`Falha ao excluir agente`,previewError:`Falha ao pré-visualizar agente`,deleteTitle:`Excluir agente`,deleteDescription:`Este agente em Markdown será removido do disco.`,deleteConfirm:`Excluir agente`,deleting:`Excluindo...`,sectionIdentity:`Identidade`,sectionBehavior:`Comportamento`,sectionReasoning:`Raciocínio`,sectionTools:`Ferramentas`,unsavedChanges:`Alterações não salvas`,confirmResetTitle:`Descartar alterações?`,confirmResetDescription:`Quaisquer alterações não salvas serão perdidas.`,confirmReset:`Descartar`,emptyStateTitle:`Nenhum agente ainda`,emptyStateDescription:`Crie seu primeiro agente para começar.`,selectAgent:`Selecionar um agente`,builtInAgents:`Agentes Integrados`,userAgents:`Agentes Personalizados`},general:{languageLabel:`Idioma`,languageDescription:`Idioma da interface do usuário`,textPromptLabel:`System Prompt de Texto Padrão`,textPromptPlaceholder:`ex. Você é um parceiro criativo útil. Seja conciso e perspicaz...`,imagePromptLabel:`System Prompt de Imagem Padrão`,imagePromptPlaceholder:`ex. Sempre gere imagens em estilo cinemático com iluminação dramática...`,imageQualityLabel:`Qualidade de Imagem Padrão`,maxToolIterationsLabel:`Iterações Máximas de Ferramentas`,maxToolIterationsDescription:`Limite máximo de rodadas de chamada de ferramentas que o modelo pode executar em um turno.`,maxToolIterationsHint:`{value} de 1000`,chatTitlesLabel:`Títulos dos Chats`,chatTitlesDescription:`Renomeie automaticamente novos chats com timestamp a partir do primeiro prompt do usuário.`,chatTitlesToggleLabel:`Renomear novos chats automaticamente`,chatTitleSourceLabel:`Origem do título`,chatTitleSourcePrompt:`Texto inicial do prompt`,chatTitleSourceModel:`Gerar com um modelo`,chatTitleModelLabel:`Modelo para título`,chatTitleModelDescription:`Use o modelo atual do chat ou force um modelo de texto específico para gerar títulos.`,chatTitleModelCurrent:`Usar o modelo atual do chat`,chatTitlePrefixLengthLabel:`Tamanho do título por prompt`,chatTitlePrefixLengthDescription:`Use os primeiros caracteres do prompt quando um chat com timestamp receber a primeira mensagem.`,chatTitlePrefixLengthHint:`{value} caracteres`,multiAgentLabel:`Turnos multiagente`,multiAgentDescription:`Permita que agentes deleguem trabalho delimitado a subagentes configurados durante um turno.`,multiAgentEnabledLabel:`Ativar delegação`,chatDelegationEnabledLabel:`Permitir delegação no modo Chat`,traceVisibilityLabel:`Visibilidade do trace`,traceVisibilityCompact:`Compacto`,traceVisibilityFull:`Completo`,traceVisibilityOff:`Desativado`,maxDepthLabel:`Profundidade máxima de delegação`,maxSubagentCallsLabel:`Máx. chamadas de subagentes`,timeoutLabel:`Timeout do subagente`,defaultMaxTurnsLabel:`Turnos padrão do subagente`,secondsHint:`{value}s`},connectors:{title:`Conectores de IA`,addButton:`Adicionar Conector`,emptyTitle:`Nenhum Conector Encontrado`,emptyDescription:`Adicione sua primeira chave de API para começar a gerar.`,deleteConfirm:`Tem certeza que deseja excluir este conector?`,addModalTitle:`Adicionar Conector`,addModalDescription:`Escolha o provider, configure a chave de API e o armazenamento.`,chatgptAddModalDescription:`Conecte uma assinatura ChatGPT pelo navegador. Nenhuma chave de API é necessária.`,providerLabel:`Provider`,selectProvider:`Selecione o Provider`,baseUrlLabel:`URL Base`,baseUrlRequired:`URL Base é obrigatória para conectores OpenAI Compatível.`,baseUrlPlaceholder:`https://api.example.com/v1`,deepseekBaseUrlPlaceholder:`https://api.deepseek.com`,organizationIdLabel:`Organization ID (opcional)`,organizationIdPlaceholder:`org-...`,organizationIdHelper:`Necessário apenas para chaves associadas a uma organização específica.`,projectIdLabel:`Project ID (opcional)`,projectIdPlaceholder:`proj_...`,projectIdHelper:`Necessário para chaves de projeto restrito no OpenAI.`,nameLabel:`Nome`,namePlaceholder:`ex. Projeto Pessoal`,apiKeyLabel:`Chave de API`,apiKeyPlaceholder:`sk-...`,saveToLabel:`Salvar em`,sources:{bunSecrets:`Armazenamento Seguro do SO`,bunSecretsDesc:`Armazenamento seguro nativo`,configFile:`config.toml`,configFileDesc:`~/.mango/config.toml`,envFile:`Arquivo .env`,envFileDesc:`.env na raiz do app`},cancelButton:`Cancelar`,addConnectorButton:`Adicionar Conector`,validating:`Validando...`,chatgptOAuthTitle:`Entrar com ChatGPT`,chatgptOAuthDescription:`O MangoStudio abrirá o login da OpenAI e salvará tokens rotativos no armazenamento seguro do sistema.`,chatgptSignInButton:`Entrar com ChatGPT`,chatgptSigningIn:`Abrindo login...`,chatgptWaitingTitle:`Conclua o login no navegador`,chatgptWaitingDescription:`Depois da aprovação, este conector aparecerá aqui com seus modelos ChatGPT.`,chatgptRemoteAccessHint:`O navegador precisa conseguir acessar este computador para concluir o retorno local.`,chatgptCancelSignIn:`Cancelar login`,chatgptSignInSucceeded:`ChatGPT conectado.`,chatgptPortBusyError:"A porta 1455 já está em uso. Feche qualquer `codex login` em execução e tente novamente.",chatgptDeniedError:`O login do ChatGPT não foi concluído. Tente novamente.`,chatgptExpiredError:`A sessão de login expirou. Inicie o login novamente.`,chatgptFailedError:`Falha ao iniciar o login do ChatGPT.`,chatgptPopupBlocked:`O navegador bloqueou a janela de login. Permita pop-ups para o MangoStudio e tente novamente.`,chatgptNameRequired:`Nome é obrigatório para conectar o ChatGPT.`,chatgptReauthWarning:`Esta sessão ChatGPT expirou ou foi revogada. Entre novamente para usar este conector.`,chatgptReauthenticate:`Reautenticar`,chatgptReauthenticating:`Aguardando login...`,chatgptReconnectSuccess:`ChatGPT reconectado.`,chatgptSignedInAs:`Conectado como {account}`,chatgptAccountUnknown:`Conta ChatGPT`,chatgptPlanBadge:`Plano {plan}`,chatgptPlanPlus:`Plus`,chatgptPlanPro:`Pro`,chatgptPlanTeam:`Team`,chatgptPlanFree:`Free`,chatgptPlanUnknown:`Desconhecido`,chatgptPlanCustom:`{plan}`,chatgptUsageWindowHours:`Limite de {hours}h`,chatgptUsageWindowDays:`Limite de {days} dias`,chatgptUsagePrimaryFallback:`Limite da sessão`,chatgptUsageSecondaryFallback:`Limite semanal`,chatgptUsageUsed:`{percent}% usado`,chatgptUsageResets:`reinicia em {time}`,chatgptUsageLimitReached:`Limite atingido`,chatgptUsageResetCredits:`{count} créditos de reinício`,chatgptUsageResetCreditsNextExpiry:`próximo expira em {time}`,chatgptUsageCreditsBalance:`Créditos: {balance}`,chatgptUsageCreditsUnlimited:`Créditos ilimitados`,chatgptUsageUpdated:`atualizado há {time}`,chatgptRedeemButton:`Usar um reset de limite`,chatgptRedeeming:`Resgatando...`,chatgptRedeemConfirmTitle:`Usar um reset de limite?`,chatgptRedeemConfirmBody:`Isso gasta um dos seus {count} créditos de reset para restaurar janelas de limite esgotadas. Não pode ser desfeito.`,chatgptRedeemConfirmAction:`Usar reset`,chatgptRedeemSuccess:`Limite resetado — {count} janela(s) restaurada(s).`,chatgptRedeemNothingToReset:`Nada para resetar — nenhuma janela de limite está esgotada no momento.`,chatgptRedeemNoCredit:`Não há créditos de reset disponíveis nesta conta.`,chatgptRedeemAlreadyRedeemed:`Este reset já foi resgatado.`,chatgptRedeemFailed:`Não foi possível resgatar o crédito de reset. Tentar novamente não gasta um segundo crédito.`,chatgptPromoDismiss:`Dispensar anúncio`,chatgptStatsToggle:`Estatísticas de uso`,chatgptStatsLoading:`Carregando estatísticas de uso...`,chatgptStatsEmpty:`Nenhuma estatística de uso disponível para esta conta.`,chatgptStatsLifetime:`Tokens no total`,chatgptStatsPeakDay:`Pico diário`,chatgptStatsLongestTurn:`Turno mais longo`,chatgptStatsCurrentStreak:`Sequência atual`,chatgptStatsLongestStreak:`Maior sequência`,chatgptStatsStreakValue:`{days} dias`,chatgptStatsChartTitle:`Tokens por dia — últimos 30 dias`,chatgptStatsDayTokens:`{date}: {tokens} tokens`,chatgptPaceOnPace:`no ritmo`,chatgptPaceRunningHot:`ritmo acelerado`,chatgptPaceProjected:`pode esgotar em {time}`,chatgptHistoryToggle:`Histórico de uso`,chatgptHistoryLoading:`Carregando histórico de uso...`,chatgptHistoryEmpty:`Nenhum histórico de uso registrado ainda.`,chatgptHistoryChartTitle:`Limite semanal — últimos {days} dias`,chatgptHistoryPoint:`{time}: {percent}% usado`,chatgptHistoryDisclaimer:`Uso conforme observado pelo MangoStudio; outros apps consomem a mesma cota entre atualizações.`,chatgptAlertThresholdLabel:`Alertas de cota`,chatgptAlertThresholdOff:`Desligado`,chatgptAlertThresholdOption:`Em {percent}%`,chatgptAlertThresholdCrossed:`{name}: {window} está em {percent}% da cota`,chatgptAlertWindowReset:`{name}: {window} reiniciou — sua cota voltou`,cursorNodeRequired:`Você precisa do Node.js instalado para executar agentes Cursor SDK.`,cursorNodeNotFound:"Binário `node` não encontrado.",cursorNodeInvalid:`O binário Node.js configurado em {path} não pode ser executado. Corrija ou remova MANGO_NODE_PATH / cursor.node_path.`,cursorNodeVersionInsufficient:`Node.js {minVersion}+ é necessário para agentes Cursor SDK (encontrado {version}).`,cursorSidecarMissing:`O script sidecar do Cursor SDK está ausente.`,cursorSidecarMissingAt:`O script sidecar do Cursor SDK está ausente em {path}.`,cursorSdkMissing:`O pacote Cursor SDK está ausente do sidecar. Reinstale o MangoStudio.`,cursorSdkMissingAt:`O pacote Cursor SDK está ausente do sidecar em {path}. Reinstale o MangoStudio.`,cursorSdkIncomplete:`O pacote Cursor SDK está incompleto. Reinstale o MangoStudio.`,cursorSdkIncompleteAt:`O pacote Cursor SDK está incompleto em {path}. Reinstale o MangoStudio.`,cursorNativeRuntimeMissing:`Esta plataforma não tem runtime nativo do Cursor no sidecar. Reinstale o MangoStudio.`,cursorNativeRuntimeMissingPackage:`O pacote de runtime nativo do Cursor {packageName} está ausente. Reinstale o MangoStudio.`,cursorRuntimeDoctorHint:"Execute `mango doctor` para uma checklist completa do runtime Cursor (use `--all` para verificar sem um conector).",modalsModalTitle:`Escolher Modelos Disponíveis`,modelsModalTitle:`Escolher Modelos Disponíveis`,modelsModalDescription:`Os modelos habilitados para`,modelsModalDescriptionSuffix:`estarão disponíveis no chat.`,textModelsLabel:`Modelos de Texto`,imageModelsLabel:`Modelos de Imagem`,doneButton:`Concluído`,configureModels:`Configurar Modelos`,deleteConnector:`Excluir Conector`,sharedConnector:`Compartilhado`,managedExternally:`Gerenciado externamente via configuração do ambiente.`,sharedDeleteBlocked:`Este conector compartilhado precisa ser removido do arquivo de configuração.`,searchModelsPlaceholder:`Buscar modelos por nome ou ID...`,noModelsDiscovered:`Nenhum modelo foi descoberto para este conector ainda.`,addSuccess:`Conector adicionado com sucesso!`,deleteSuccess:`Conector excluído com sucesso!`,updateModelsSuccess:`Modelos atualizados com sucesso!`,errorRequired:`Nome e Chave de API são obrigatórios.`,failedToLoad:`Falha ao carregar conectores`,failedToAdd:`Falha ao adicionar conector`,failedToDelete:`Falha ao excluir conector`,failedToUpdateModels:`Falha ao atualizar modelos`,unknownError:`Ocorreu um erro desconhecido`,noSearchResults:`Nenhum modelo corresponde à sua pesquisa`},providers:{title:`Provedores de IA`,backToMenu:`Voltar para provedores`,sectionReasoning:`Raciocínio`,sectionTools:`Configuração de Ferramentas`,sectionCache:`Cache de Prompt`,sectionAdvanced:`Avançado`,save:`Salvar`,saving:`Salvando...`,cancel:`Cancelar`,reset:`Restaurar padrões`,saved:`Configurações salvas`,saveError:`Falha ao salvar configurações do provedor`,loadError:`Falha ao carregar provedores`,invalidProvider:`Provedor não encontrado`,perProviderSettings:`Configurações por provedor substituem os padrões globais.`,noProviders:`Nenhum provedor de IA disponível.`,modelsEnabled:`{count} modelos habilitados`,connectorsCount:`{count} conectores`,thinkingEnabled:`Ativar raciocínio`,reasoningEffort:`Esforço de raciocínio`,maxOutputTokens:`Máx. tokens de saída`,maxToolIterations:`Máx. iterações de ferramentas`,parallelToolCalls:`Chamadas paralelas de ferramentas`,compaction:`Compactação pelo provedor`,cachePreference:`Preferência de cache de prompt`,cacheAuto:`Automático`,cacheStablePrefix:`Prefixo estável`,cacheOff:`Desligado`,capabilityThinking:`Raciocínio`,capabilityTools:`Ferramentas`,capabilityCaching:`Cache`,capabilityCompaction:`Compactação`,reservedForFuture:`Reservado para configurações futuras`,maxOutputTokensPlaceholder:`1 – {limit}`},tools:{title:`Ferramentas`,description:`Ative ou desative ferramentas e configure seus parâmetros.`,categories:{system:`Sistema`,image:`Imagem`,interaction:`Interação`},enabled:`Ativada`,disabled:`Desativada`,cannotDisable:`Esta ferramenta não pode ser desativada.`,save:`Salvar`,saving:`Salvando...`,saved:`Configurações salvas`,saveError:`Falha ao salvar configurações da ferramenta`,loadError:`Falha ao carregar ferramentas`,noTools:`Nenhuma ferramenta disponível.`,maxToolIterationsLabel:`Iterações Máximas de Ferramentas`,maxToolIterationsDescription:`Limite máximo de rodadas de chamada de ferramentas que o modelo pode executar em um turno.`,maxToolIterationsHint:`{value} de 1000`,executionTitle:`Execução`,autoModelOption:`Automático (primeiro disponível)`,letAiDecideQualityLabel:`IA decide a qualidade`,letAiDecideQualityDescription:`Quando ativado, a IA pode escolher diferentes tamanhos de imagem por solicitação.`,toolNames:{readFile:`Ler arquivo`,writeFile:`Escrever arquivo`,listDirectory:`Listar diretório`,glob:`Glob`,grep:`Grep`},toolDescriptions:{readFile:`Permite que a IA leia arquivos de texto do disco.`,writeFile:`Permite que a IA escreva conteúdo de texto em arquivos no disco.`,listDirectory:`Permite que a IA liste arquivos e diretórios no disco.`,glob:`Permite que a IA encontre arquivos e diretórios por padrão glob.`,grep:`Permite que a IA pesquise o conteúdo de arquivos com expressões regulares.`},parameters:{allowedPathsLabel:`Caminhos permitidos`,allowedPathsDescription:`Caminhos que a ferramenta pode acessar. Deixe vazio para permitir todos.`,deniedPathsLabel:`Caminhos negados`,deniedPathsDescription:`Caminhos que a ferramenta não pode acessar. Deixe vazio para não negar nenhum.`},pathList:{add:`Adicionar`,edit:`Editar`,delete:`Excluir`,save:`Salvar`,cancel:`Cancelar`,pathPlaceholder:`ex. /home/usuario/projetos`,noPaths:`Nenhum caminho configurado.`}},metrics:{title:`Métricas`,description:`Contadores em memória para taxa de acerto de cache dos providers e total de timeouts de probes.`,refresh:`Atualizar`,failedToLoad:`Falha ao carregar métricas`,empty:`Nenhuma métrica de provider foi registrada ainda.`,generatedAtLabel:`Última atualização: {value}`,totalProbeTimeoutsLabel:`Timeouts de probe: {value}`,cacheSectionTitle:`Taxa de Acerto de Cache`,probeSectionTitle:`Timeouts de Probe por Operação`,cacheLabel:`Cache`,hitsLabel:`Acertos`,missesLabel:`Falhas`,hitRateLabel:`Taxa de acerto`,caches:{sdkClient:`Cliente SDK`,preparedRuntime:`Runtime preparado`,providerRoute:`Roteamento do provider`},operations:{healthcheck:`Healthcheck`,modelList:`Listagem de modelos`}},logs:{title:`Logs`,description:`Timeouts recentes de probes de provider capturados pelo processo atual.`,refresh:`Atualizar`,failedToLoad:`Falha ao carregar logs`,empty:`Nenhum evento recente de timeout de probe de provider.`,providerLabel:`Provider`,operationLabel:`Operação`,eventKinds:{probeTimeout:`Timeout de probe`},operations:{healthcheck:`Healthcheck`,modelList:`Listagem de modelos`}},appearance:{title:`Aparência`,appTheme:{label:`Tema do Aplicativo`,description:`Escolha o tema visual para o aplicativo`,dark:`Escuro`,light:`Claro`,system:`Sistema`,comingSoon:`Em breve`},fontSize:{label:`Tamanho de Fonte`,description:`Ajuste o tamanho do texto nas mensagens do chat`,small:`Pequeno`,default:`Padrão`,large:`Grande`},chatDensity:{label:`Densidade do Chat`,description:`Controle o espaçamento entre as mensagens`,compact:`Compacto`,default:`Padrão`,comfortable:`Confortável`},codeTheme:{label:`Tema de Código`,description:`Escolha o tema de destaque de sintaxe para blocos de código`,auto:`Automático (seguir tema do app)`,manual:`Manual`,darkPreference:`Preferência escura`,lightPreference:`Preferência clara`,oneDarkPro:`One Dark Pro`,githubDarkDimmed:`GitHub Dark Dimmed`,githubLight:`GitHub Light`,oneLight:`One Light`}},app:{loadError:`Falha ao carregar configurações do app`,saveError:`Falha ao salvar configurações do app`}},common:{loading:`Carregando...`,appName:`Mango Studio`,downloadFilenamePrefix:`mangostudio`,mangoStudioLogo:`Logo do Mango Studio`,retry:`Tentar novamente`,noResultsFor:`Nenhum resultado para "{query}"`,contextIndicator:`Indicador de uso de contexto`,settingsNavigation:`Navegação de configurações`,openMenu:`Abrir menu`,closeMenu:`Fechar menu`,disclaimer:`A Inteligencia Artificial pode cometer erros, verifique os resultados com cautela`},providers:{gemini:`Google Gemini`,anthropic:`Anthropic`,openai:`OpenAI`,"openai-compatible":`OpenAI Compatível`,deepseek:`DeepSeek`,cursor:`Cursor`,chatgpt:`ChatGPT`,openrouter:`OpenRouter`},thinking:{label:`Processo de raciocínio`,labelContinued:`Continuação do raciocínio`,streaming:`Pensando...`,streamingContinued:`Pensando novamente...`,toggle:`Ver raciocínio`,enable:`Raciocinar`,enabled:`Raciocínio ativo`,disabled:`Raciocínio desativado`,effort:`Esforço`,effortLow:`Baixo`,effortMedium:`Médio`,effortHigh:`Alto`,effortXHigh:`Extra Alto`,effortMax:`Máximo`,reasoningBadge:`Reasoning`},tools:{calling:`Chamando...`,running:`Executando ferramenta`,done:`Concluído`,error:`Erro na ferramenta`,moreCount:`+{count} mais`,argsLabel:`argumentos`,errorLabel:`erro`,resultLabel:`resultado`,labels:{list_directory:`Listar`,read_file:`Leu`,write_file:`Escreveu`,glob:`Glob`,grep:`Grep`,generate_image:`Gerar Imagem`,get_current_datetime:`Data`,bash:`Bash`,zsh:`Zsh`,powershell:`PowerShell`}},errors:{unknown:`Ocorreu um erro desconhecido`,imageNotSupported:`Este provider não suporta geração de imagens.`,referenceImageUploadFailed:`Falha ao enviar a imagem de referência. Tente novamente.`,textGenerationFailed:`Falha ao obter uma resposta. Tente novamente.`,imageGenerationFailed:`Falha ao gerar imagem. Tente novamente.`,streamRequestFailed:`Falha na requisição de stream`,streamResponseNoBody:`Resposta do stream sem corpo`},models:{loading:`Carregando modelos...`,unavailable:`Modelos indisponíveis`,noModelsAvailable:`Nenhum modelo disponível`,preview:`Pré-visualização`},api:{unauthorized:`Unauthorized`},generation:{toolLoopExhausted:`O modelo excedeu o número máximo de interações com ferramentas.`}},gt=`mangostudio:locale`,_t={"pt-BR":ht,en:I};function vt(){let e=localStorage.getItem(gt);return e===`pt-BR`||e===`en`?e:navigator.language.startsWith(`pt`)?`pt-BR`:`en`}var yt=(0,N.createContext)(null);function bt({children:e}){let[t,n]=(0,N.useState)(()=>vt());return(0,P.jsx)(yt,{value:{t:(0,N.useMemo)(()=>_t[t],[t]),locale:t,setLocale:(0,N.useCallback)(e=>{n(e),localStorage.setItem(gt,e)},[])},children:e})}function L(){let e=(0,N.use)(yt);if(!e)throw Error(`useI18n deve ser usado dentro de I18nProvider`);return e}var xt=`mango-studio-theme`,St={mode:`auto`,darkTheme:`one-dark-pro`,lightTheme:`github-light`},Ct={appTheme:`dark`,codeTheme:St,fontSize:`default`,chatDensity:`default`},wt=(0,N.createContext)(null);function Tt(){try{let e=localStorage.getItem(xt);if(e){let t=JSON.parse(e);return typeof t.codeTheme==`string`&&(t.codeTheme={...St,darkTheme:t.codeTheme}),{...Ct,...t}}}catch{}return Ct}function Et({children:e}){let[t,n]=(0,N.useState)(Tt),[r,i]=(0,N.useState)(()=>window.matchMedia(`(prefers-color-scheme: dark)`).matches),a=(0,N.useMemo)(()=>t.appTheme===`system`?r?`dark`:`light`:t.appTheme,[t.appTheme,r]),o=(0,N.useMemo)(()=>t.codeTheme.mode===`manual`||a===`dark`?t.codeTheme.darkTheme:t.codeTheme.lightTheme,[t.codeTheme,a]);(0,N.useEffect)(()=>{try{localStorage.setItem(xt,JSON.stringify(t))}catch{}document.documentElement.dataset.theme=a,document.documentElement.dataset.fontSize=t.fontSize,document.documentElement.dataset.chatDensity=t.chatDensity},[t,a]),(0,N.useEffect)(()=>{if(t.appTheme!==`system`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`),n=()=>i(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[t.appTheme]);let s=(0,N.useCallback)(e=>{n(t=>({...t,...e}))},[]);return(0,P.jsx)(wt,{value:(0,N.useMemo)(()=>({config:t,resolvedTheme:a,resolvedCodeTheme:o,setConfig:s}),[t,a,o,s]),children:e})}function Dt(){let e=(0,N.use)(wt);if(!e)throw Error(`useTheme must be used inside ThemeProvider`);return e}var Ot=ae()({component:()=>(0,P.jsx)(Ie,{client:ft,children:(0,P.jsx)(Et,{children:(0,P.jsx)(bt,{children:(0,P.jsx)(mt,{children:(0,P.jsx)(v,{})})})})})}),kt={primary:`bg-primary text-on-primary shadow-lg shadow-primary/20 hover:opacity-90`,secondary:`bg-surface-container-high text-on-surface hover:bg-surface-container-highest`,ghost:`text-on-surface/70 hover:text-on-surface hover:bg-surface-container-high`},At={sm:`px-3 py-1.5 text-xs`,md:`px-4 py-2 text-sm`};function R({variant:e=`primary`,size:t=`md`,loading:n=!1,disabled:r,className:i=``,children:a,...o}){return(0,P.jsxs)(`button`,{disabled:r||n,className:`
3
+ inline-flex items-center justify-center gap-2 rounded-xl font-bold
4
+ transition-all duration-200 active:scale-95 cursor-pointer
5
+ disabled:opacity-50 disabled:cursor-not-allowed disabled:active:scale-100
6
+ ${kt[e]} ${At[t]} ${i}
7
+ `.trim(),...o,children:[n&&(0,P.jsx)(`span`,{className:`w-4 h-4 rounded-full border-2 border-current border-t-transparent animate-spin shrink-0`}),a]})}var jt={glass:`glass-panel`,solid:`bg-surface-container-high`};function z({variant:e=`solid`,className:t=``,children:n}){return(0,P.jsx)(`div`,{className:`rounded-2xl border border-outline-variant/10 p-8 ${jt[e]} ${t}`,children:n})}function B({label:e,error:t,id:n,className:r=``,...i}){return(0,P.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[e&&(0,P.jsx)(`label`,{htmlFor:n,className:`text-sm font-medium text-on-surface-variant`,children:e}),(0,P.jsx)(`input`,{id:n,className:`
8
+ w-full rounded-xl px-4 py-2.5 text-sm
9
+ bg-surface-container-high text-on-surface
10
+ border border-outline-variant/20
11
+ placeholder:text-on-surface/30
12
+ focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20
13
+ transition-colors
14
+ ${t?`border-error/60`:``}
15
+ ${r}
16
+ `.trim(),...i}),t&&(0,P.jsx)(`p`,{className:`text-xs text-error`,children:t})]})}var Mt=`/assets/logo-DsGvk33E.png`;function Nt({className:e=``,alt:t}){let{t:n}=L();return(0,P.jsx)(`img`,{src:Mt,alt:t??n.common.mangoStudioLogo,className:`object-contain ${e}`,draggable:!1})}var Pt=S(`/signup`)({component:Ft});function Ft(){let e=c(),{t}=L(),[n,r]=(0,N.useState)(``),[i,a]=(0,N.useState)(``),[o,s]=(0,N.useState)(``),[l,u]=(0,N.useState)(``),[d,f]=(0,N.useState)(!1),p=async r=>{r.preventDefault(),f(!0),u(``),await ct.signUp.email({name:n,email:i,password:o},{onSuccess:()=>{e({to:`/`})},onError:e=>{u(e.error.message||t.auth.signupError)}}),f(!1)};return(0,P.jsx)(`div`,{className:`min-h-screen flex items-center justify-center bg-surface-dim px-4`,children:(0,P.jsx)(z,{variant:`glass`,className:`w-full max-w-sm`,children:(0,P.jsxs)(`form`,{id:`signup-form`,onSubmit:e=>void p(e),method:`post`,action:`#`,className:`space-y-5`,children:[(0,P.jsxs)(`div`,{className:`flex flex-col items-center gap-2 mb-4`,children:[(0,P.jsx)(Nt,{className:`w-24 h-24`}),(0,P.jsx)(`h1`,{className:`font-headline text-2xl font-semibold text-center text-on-surface`,children:t.auth.signupTitle})]}),l&&(0,P.jsx)(`p`,{className:`text-xs text-error text-center bg-error/10 rounded-lg px-3 py-2`,children:l}),(0,P.jsx)(B,{type:`text`,id:`name`,name:`name`,label:t.auth.nameLabel,placeholder:t.auth.namePlaceholder,value:n,onChange:e=>r(e.target.value),autoComplete:`name`,required:!0}),(0,P.jsx)(B,{type:`email`,id:`email`,name:`email`,label:t.auth.emailLabel,placeholder:t.auth.emailPlaceholder,value:i,onChange:e=>a(e.target.value),autoComplete:`email`,required:!0}),(0,P.jsx)(B,{type:`password`,id:`password`,name:`password`,label:t.auth.signupPasswordLabel,placeholder:t.auth.passwordPlaceholder,value:o,onChange:e=>s(e.target.value),autoComplete:`new-password`,minLength:8,required:!0}),(0,P.jsx)(R,{type:`submit`,variant:`primary`,loading:d,className:`w-full`,children:d?t.auth.signupLoading:t.auth.signupButton}),(0,P.jsxs)(`p`,{className:`text-sm text-center text-on-surface/50`,children:[t.auth.hasAccount,` `,(0,P.jsx)(et,{to:`/login`,className:`text-primary hover:underline`,children:t.auth.loginLink})]})]})})})}var It=/[\u0000-\u001F\u007F]/g;function Lt(e){if(!e)return`/`;let t=e.trim().replace(It,``);if(!t)return`/`;if(t.startsWith(`/`))return t[1]===`/`||t[1]===`\\`?`/`:t;try{let e=new URL(t);return e.origin===window.location.origin&&e.pathname+e.search+e.hash||`/`}catch{return`/`}}var Rt=S(`/login`)({validateSearch:e=>typeof e.redirect==`string`?{redirect:Lt(e.redirect)}:{},component:zt});function zt(){let e=g(),{t}=L(),{data:n,isPending:r}=ct.useSession(),{redirect:i}=Rt.useSearch(),[a,o]=(0,N.useState)(``),[s,c]=(0,N.useState)(``),[l,u]=(0,N.useState)(``),[d,f]=(0,N.useState)(!1);(0,N.useEffect)(()=>{!r&&n?.user&&e.history.push(i??`/`)},[n?.user,r,e,i]);let p=async e=>{e.preventDefault(),f(!0),u(``),await ct.signIn.email({email:a,password:s},{onError:e=>{u(e.error.message||t.auth.loginError)}}),f(!1)};return(0,P.jsx)(`div`,{className:`min-h-screen flex items-center justify-center bg-surface-dim px-4`,children:(0,P.jsx)(z,{variant:`glass`,className:`w-full max-w-sm`,children:(0,P.jsxs)(`form`,{id:`login-form`,onSubmit:e=>void p(e),method:`post`,action:`#`,className:`space-y-5`,children:[(0,P.jsxs)(`div`,{className:`flex flex-col items-center gap-2 mb-4`,children:[(0,P.jsx)(Nt,{className:`w-24 h-24`}),(0,P.jsx)(`h1`,{className:`font-headline text-2xl font-semibold text-center text-on-surface`,children:t.auth.loginTitle})]}),l&&(0,P.jsx)(`p`,{className:`text-xs text-error text-center bg-error/10 rounded-lg px-3 py-2`,children:l}),(0,P.jsx)(B,{type:`email`,id:`email`,name:`email`,label:t.auth.emailLabel,placeholder:t.auth.emailPlaceholder,value:a,onChange:e=>o(e.target.value),autoComplete:`email`,required:!0}),(0,P.jsx)(B,{type:`password`,id:`password`,name:`password`,label:t.auth.passwordLabel,placeholder:t.auth.passwordPlaceholder,value:s,onChange:e=>c(e.target.value),autoComplete:`current-password`,required:!0}),(0,P.jsx)(R,{type:`submit`,variant:`primary`,loading:d,className:`w-full`,children:d?t.auth.loginLoading:t.auth.loginButton}),(0,P.jsxs)(`p`,{className:`text-sm text-center text-on-surface/50`,children:[t.auth.noAccount,` `,(0,P.jsx)(et,{to:`/signup`,className:`text-primary hover:underline`,children:t.auth.signupLink})]})]})})})}var Bt=I.errors.unknown;function Vt(...e){return nt(tt(e))}function V(e,t=Bt){if(typeof e==`string`)return e||t;if(e&&typeof e==`object`){let t=e;if(typeof t.error==`string`&&t.error)return t.error}return t}var Ht={configured:!1,status:`idle`,allModels:[],textModels:[],imageModels:[],discoveredTextModels:[],discoveredImageModels:[]};function Ut(e,t){return!!e&&t.some(t=>t.modelId===e)}function Wt(e,t){return e&&Ut(e,t)?e:t[0]?.modelId??``}function Gt(e,t,n){return e&&Ut(e,n)?e:Wt(t,n)}function Kt(e,t){return e.status===`loading`?t.loading:e.status===`error`?t.unavailable:t.noModelsAvailable}function qt({activeModel:e,activeModels:t,isDisabled:r,onSelect:o,modelCatalog:s,lockedProvider:c}){let[l,u]=(0,N.useState)(!1),f=(0,N.useRef)(null),{t:p}=L(),m=t.find(t=>t.modelId===e),h=Kt(s,{loading:p.models.loading,unavailable:p.models.unavailable,noModelsAvailable:p.models.noModelsAvailable});(0,N.useEffect)(()=>{function e(e){f.current&&!f.current.contains(e.target)&&u(!1)}return l&&document.addEventListener(`mousedown`,e),()=>{document.removeEventListener(`mousedown`,e)}},[l]);let g=()=>{r||u(!l)},_=e=>{o(e),u(!1)},v=t.reduce((e,t)=>{let n=t.provider??`other`;return e[n]||(e[n]=[]),e[n].push(t),e},{}),y=e=>e in p.providers?p.providers[e]:e,b=e=>{let t=e.toLowerCase();return t.includes(`flash`)?(0,P.jsx)(Le,{className:`w-3.5 h-3.5 text-amber-400`}):t.includes(`pro`)?(0,P.jsx)(ce,{className:`w-3.5 h-3.5 text-primary`}):t.includes(`lite`)?(0,P.jsx)(xe,{className:`w-3.5 h-3.5 text-emerald-400`}):(0,P.jsx)(A,{className:`w-3.5 h-3.5 text-blue-400`})};return(0,P.jsxs)(`div`,{className:`relative`,ref:f,children:[(0,P.jsxs)(`button`,{type:`button`,onClick:g,disabled:r,className:Vt(`flex items-center gap-2 px-3 py-1.5 rounded-lg transition-all duration-200 border border-transparent`,`group hover:bg-surface-container-high active:scale-95`,l&&`bg-surface-container-high border-primary/20`,r&&`opacity-50 cursor-not-allowed`),children:[(0,P.jsx)(`span`,{className:`font-headline text-lg font-bold tracking-tight text-on-background group-hover:text-primary transition-colors`,children:m?.displayName||h}),(0,P.jsx)(E,{className:Vt(`w-4 h-4 text-on-background/40 group-hover:text-primary transition-all duration-200`,l&&`rotate-180 text-primary`)})]}),(0,P.jsx)(n,{children:l&&(0,P.jsx)(i.div,{initial:{opacity:0,y:8,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:8,scale:.95},transition:{duration:.15,ease:`easeOut`},className:`dropdown-panel absolute left-0 top-full mt-3 w-[19rem] max-h-[70vh] hide-scrollbar overflow-y-auto`,children:(0,P.jsx)(`div`,{className:`py-2`,children:Object.keys(v).length===0?(0,P.jsx)(`div`,{className:`px-4 py-3 text-sm text-on-surface-variant italic`,children:p.models.noModelsAvailable}):Object.entries(v).map(([t,n])=>(0,P.jsxs)(`div`,{className:`mb-2 last:mb-0`,children:[(0,P.jsx)(`div`,{className:`px-4 py-1.5 text-[10px] font-bold uppercase tracking-wider text-on-surface-variant/50`,children:y(t)}),n.map(t=>{let n=c!=null&&t.provider!==c;return(0,P.jsxs)(`button`,{type:`button`,onClick:()=>!n&&_(t.modelId),disabled:n,className:Vt(`w-full flex items-center justify-between px-4 py-2.5 text-left transition-all duration-150`,!n&&`hover:bg-primary/10 active:bg-primary/20 group/item`,e===t.modelId&&!n&&`bg-primary/5`,n&&`opacity-40 cursor-not-allowed`),children:[(0,P.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,P.jsx)(`div`,{className:`flex-shrink-0 w-5 h-5 flex items-center justify-center`,children:n?(0,P.jsx)(d,{className:`w-3.5 h-3.5 text-on-surface-variant`}):b(t.displayName)}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`div`,{className:Vt(`text-sm font-medium transition-colors`,e===t.modelId&&!n?`text-primary`:`text-on-surface group-hover/item:text-on-surface`),children:t.displayName}),(0,P.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[t.modelId.includes(`preview`)&&(0,P.jsx)(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded-full bg-surface-container-highest text-on-surface-variant border border-outline-variant/30`,children:p.models.preview}),t.capabilities?.reasoning&&!n&&(0,P.jsx)(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded-full bg-primary/15 text-primary border border-primary/30`,children:p.thinking.reasoningBadge})]})]})]}),e===t.modelId&&!n&&(0,P.jsx)(a,{className:`w-4 h-4 text-primary`})]},t.modelId)})]},t))})})})]})}function Jt({activeModel:e,activeModels:t,isModelSelectorDisabled:n,currentChatId:r,currentPage:i,onUpdateChatModel:a,onSetPageModel:o,onNewChat:s,onNavigateToSettings:l,modelCatalog:u,lockedProvider:d,onMobileMenuToggle:f}){let p=c(),{data:m}=ct.useSession(),{toast:h}=F(),{t:g}=L(),[_,v]=(0,N.useState)(!1);(0,N.useEffect)(()=>{_&&!m?.user&&p({to:`/login`})},[_,m?.user,p]);let y=async()=>{v(!0),await ct.signOut({fetchOptions:{onError:()=>{v(!1),h(g.auth.logoutError,`error`)}}})};return(0,P.jsxs)(`header`,{className:`bg-surface-dim flex justify-between items-center px-3 sm:px-4 md:px-6 py-3 md:py-4 w-full sticky top-0 z-40 border-b border-outline-variant/10`,children:[(0,P.jsxs)(`div`,{className:`flex items-center gap-2 sm:gap-3 md:gap-4 min-w-0 flex-1`,children:[(0,P.jsx)(`button`,{type:`button`,onClick:f,className:`md:hidden p-2 rounded-lg hover:bg-surface-container-high transition-colors text-on-surface shrink-0`,"aria-label":g.common.openMenu,children:(0,P.jsx)(oe,{size:20})}),i!==`studio`&&(0,P.jsx)(`div`,{className:`min-w-0 flex-1 max-w-[60vw] sm:max-w-none`,children:(0,P.jsx)(qt,{activeModel:e,activeModels:t,isDisabled:n,onSelect:e=>r?a(r,e):o(e),modelCatalog:u,lockedProvider:d})})]}),(0,P.jsxs)(`div`,{className:`flex items-center gap-2 sm:gap-3 shrink-0 ml-2`,children:[i===`chat`&&(0,P.jsxs)(`button`,{type:`button`,onClick:s,className:`flex items-center gap-2 px-3 sm:px-4 py-2 rounded-full bg-surface-container-high hover:bg-surface-container-highest transition-colors text-sm font-medium text-on-surface active:scale-95 duration-200 shrink-0`,children:[(0,P.jsx)(Ye,{size:16}),(0,P.jsx)(`span`,{className:`hidden sm:inline`,children:g.chat.newChat})]}),(0,P.jsx)(`button`,{type:`button`,onClick:l,className:`p-2 rounded-full transition-all duration-200 active:scale-95 shrink-0 ${i===`settings`?`bg-primary/10 text-primary`:`bg-surface-container-high text-on-surface hover:bg-surface-container-highest cursor-pointer`}`,title:g.settings.title,children:(0,P.jsx)(Te,{size:18})}),m?.user&&(0,P.jsxs)(`div`,{className:`flex items-center gap-2 sm:gap-3 ml-1 sm:ml-2 pl-2 sm:pl-4 border-l border-outline-variant/20 shrink-0`,children:[(0,P.jsx)(`span`,{className:`text-sm font-medium text-on-surface hidden md:inline max-w-[120px] truncate`,children:m.user.name}),(0,P.jsxs)(`button`,{type:`button`,onClick:()=>void y(),disabled:_,"data-testid":`logout-button`,className:`text-xs px-2 sm:px-3 py-1.5 rounded-full bg-surface-container-high hover:bg-surface-container-highest transition-colors cursor-pointer text-on-surface disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5 shrink-0`,children:[_&&(0,P.jsx)(`span`,{className:`w-3 h-3 rounded-full border-2 border-current border-t-transparent animate-spin`}),(0,P.jsx)(`span`,{className:`hidden sm:inline`,children:_?g.auth.logoutLoading:g.auth.logoutButton}),(0,P.jsx)(`span`,{className:`sm:hidden`,children:_?g.auth.logoutLoading:g.auth.logoutButton.slice(0,4)})]})]})]})]})}function Yt({ratio:e,severity:t}){let{t:n}=L(),r=2.5,i=(20-r)/2,a=2*Math.PI*i,o=a*(1-Math.min(e,1)),s=Math.round(e*100),c=t===`critical`||t===`danger`?`stroke-error`:t===`warning`?`stroke-warning`:`stroke-primary`;return(0,P.jsxs)(`div`,{className:`relative flex items-center justify-center shrink-0`,style:{width:20,height:20},children:[(0,P.jsxs)(`svg`,{width:20,height:20,className:`-rotate-90`,children:[(0,P.jsx)(`title`,{children:n.common.contextIndicator}),(0,P.jsx)(`circle`,{cx:20/2,cy:20/2,r:i,fill:`none`,className:`stroke-on-surface/10`,strokeWidth:r}),(0,P.jsx)(`circle`,{cx:20/2,cy:20/2,r:i,fill:`none`,className:c,strokeWidth:r,strokeDasharray:a,strokeDashoffset:o,strokeLinecap:`round`})]}),(0,P.jsx)(`span`,{className:`absolute text-[7px] font-bold tabular-nums text-on-surface-variant`,children:s})]})}function Xt({currentPage:e,onNavigate:t,chats:n,currentChatId:r,onSelectChat:i,onUpdateChatTitle:a,onDeleteChat:s,onNewChat:c,contextCache:l,isMobileOpen:u=!1,onMobileClose:d}){let[f,p]=(0,N.useState)(null),[m,h]=(0,N.useState)(``),g=(0,N.useRef)(null),{toast:_}=F(),{t:v}=L();(0,N.useEffect)(()=>{f&&g.current&&(g.current.focus(),g.current.select())},[f]);let y=(e,t)=>{t.stopPropagation(),p(e.id),h(e.title)},b=e=>{m.trim()&&m!==n.find(t=>t.id===e)?.title&&a(e,m.trim()),p(null)},x=()=>{p(null)},S=(e,t)=>{t.stopPropagation(),s(e),_(v.chat.deleted,`success`)},C=(e,t)=>{e.key===`Enter`?b(t):e.key===`Escape`&&x()},w=e=>{t(e),d?.()},ee=t=>`flex items-center gap-3 px-4 py-3 rounded-lg transition-all duration-300 w-full text-left ${e===t?`text-primary bg-surface-container-high`:`text-on-surface/70 hover:bg-surface-container-high hover:text-on-surface`}`;return(0,P.jsxs)(P.Fragment,{children:[u&&(0,P.jsx)(`div`,{className:`fixed inset-0 bg-black/60 backdrop-blur-sm z-40 md:hidden`,onClick:d,"aria-hidden":`true`}),(0,P.jsxs)(`aside`,{className:`bg-surface-container-low flex-col h-full border-r border-outline-variant/20 w-64 fixed left-0 top-0 z-50 transition-transform duration-300 ease-out
17
+ ${u?`flex translate-x-0`:`hidden -translate-x-full`} md:flex md:translate-x-0
18
+ `,children:[(0,P.jsxs)(`div`,{className:`px-6 py-6 mb-4 flex items-center gap-3`,children:[(0,P.jsx)(Nt,{className:`w-10 h-10 shrink-0`}),(0,P.jsx)(`h1`,{className:`font-headline text-lg font-semibold text-on-background tracking-tight truncate`,children:v.common.appName}),(0,P.jsx)(`button`,{type:`button`,onClick:d,className:`ml-auto md:hidden p-2 rounded-lg hover:bg-surface-container-high transition-colors text-on-surface`,"aria-label":v.common.closeMenu,children:(0,P.jsx)(Ue,{size:20})})]}),(0,P.jsx)(`div`,{className:`px-4 mb-4 flex items-center gap-2`,children:(0,P.jsxs)(`button`,{type:`button`,onClick:c,className:`flex-1 flex items-center justify-center gap-2 py-2.5 bg-primary text-on-primary rounded-xl font-bold transition-transform active:scale-95 shadow-lg shadow-primary/20`,children:[(0,P.jsx)(Ye,{size:18}),(0,P.jsx)(`span`,{children:v.chat.newChat})]})}),(0,P.jsx)(`div`,{className:`px-4 mb-4 md:hidden`,"data-testid":`mobile-shortcuts`,children:(0,P.jsxs)(`div`,{className:`grid grid-cols-3 gap-2`,children:[(0,P.jsxs)(`button`,{type:`button`,onClick:()=>w(`studio`),className:`flex flex-col items-center justify-center gap-1 p-2 rounded-lg transition-all duration-200 text-xs font-medium ${e===`studio`?`text-primary bg-surface-container-high`:`text-on-surface/70 hover:bg-surface-container-high hover:text-on-surface`}`,children:[(0,P.jsx)(o,{size:20}),(0,P.jsx)(`span`,{children:v.studio.title})]}),(0,P.jsxs)(`button`,{type:`button`,onClick:()=>w(`gallery`),className:`flex flex-col items-center justify-center gap-1 p-2 rounded-lg transition-all duration-200 text-xs font-medium ${e===`gallery`?`text-primary bg-surface-container-high`:`text-on-surface/70 hover:bg-surface-container-high hover:text-on-surface`}`,children:[(0,P.jsx)(ne,{size:20}),(0,P.jsx)(`span`,{children:v.gallery.title})]}),(0,P.jsxs)(`button`,{type:`button`,onClick:()=>w(`settings`),className:`flex flex-col items-center justify-center gap-1 p-2 rounded-lg transition-all duration-200 text-xs font-medium ${e===`settings`?`text-primary bg-surface-container-high`:`text-on-surface/70 hover:bg-surface-container-high hover:text-on-surface`}`,children:[(0,P.jsx)(Te,{size:20}),(0,P.jsx)(`span`,{children:v.settings.title})]})]})}),(0,P.jsxs)(`nav`,{className:`flex-1 px-4 overflow-y-auto hide-scrollbar space-y-1`,children:[(0,P.jsx)(`div`,{className:`text-xs font-label text-on-surface-variant/50 uppercase tracking-wider px-4 py-2 mt-2`,children:v.chat.sectionLabel}),n.map(t=>{let n=l?.get(t.id),a=()=>{f!==t.id&&(i(t.id),w(`chat`))};return(0,P.jsxs)(`div`,{role:`button`,tabIndex:0,className:`group relative flex items-center gap-3 px-4 py-2.5 rounded-lg transition-all duration-300 w-full text-left truncate cursor-pointer ${e===`chat`&&r===t.id?`text-primary bg-surface-container-high`:`text-on-surface/70 hover:bg-surface-container-high hover:text-on-surface`}`,onClick:a,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),a())},children:[n?(0,P.jsx)(Yt,{ratio:n.estimatedUsageRatio,severity:n.severity}):(0,P.jsx)(Ze,{size:16,className:`shrink-0`}),f===t.id?(0,P.jsx)(`div`,{className:`flex items-center gap-1 w-full mr-1`,children:(0,P.jsx)(`input`,{ref:g,type:`text`,value:m,onChange:e=>h(e.target.value),onKeyDown:e=>C(e,t.id),onBlur:()=>b(t.id),className:`bg-surface-container-highest text-on-surface px-1 py-0.5 rounded border border-primary outline-none text-sm w-full`})}):(0,P.jsx)(`span`,{className:`font-body text-sm truncate flex-1`,children:t.title}),f!==t.id&&(0,P.jsxs)(`div`,{className:`opacity-0 group-hover:opacity-100 flex items-center gap-1 transition-opacity shrink-0`,children:[(0,P.jsx)(`button`,{type:`button`,onClick:e=>y(t,e),className:`p-1 hover:text-primary transition-colors`,title:v.chat.editTitle,children:(0,P.jsx)(Qe,{size:14})}),(0,P.jsx)(`button`,{type:`button`,onClick:e=>S(t.id,e),className:`p-1 hover:text-error transition-colors`,title:v.chat.deleteTitle,children:(0,P.jsx)(Ge,{size:14})})]})]},t.id)})]}),(0,P.jsxs)(`div`,{className:`p-4 mt-auto border-t border-outline-variant/10 space-y-1 hidden md:block`,children:[(0,P.jsxs)(`button`,{type:`button`,onClick:()=>w(`studio`),className:ee(`studio`),children:[(0,P.jsx)(o,{size:18}),(0,P.jsx)(`span`,{className:`font-label font-medium text-sm`,children:v.studio.title})]}),(0,P.jsxs)(`button`,{type:`button`,onClick:()=>w(`gallery`),className:ee(`gallery`),children:[(0,P.jsx)(ne,{size:18}),(0,P.jsx)(`span`,{className:`font-label font-medium text-sm`,children:v.gallery.title})]}),(0,P.jsxs)(`button`,{type:`button`,onClick:()=>w(`settings`),className:ee(`settings`),children:[(0,P.jsx)(Te,{size:18}),(0,P.jsx)(`span`,{className:`font-label font-medium text-sm`,children:v.settings.title})]})]})]})]})}function Zt({children:e,currentPage:t,onNavigate:n,chats:r,currentChatId:i,onSelectChat:a,onUpdateChatTitle:o,onDeleteChat:s,onNewChat:c,contextCache:l,isMobileSidebarOpen:u=!1,onMobileSidebarClose:d}){return(0,P.jsxs)(`div`,{className:`flex h-screen overflow-hidden bg-surface text-on-surface font-body selection:bg-primary/30`,children:[(0,P.jsx)(Xt,{currentPage:t,onNavigate:n,chats:r,currentChatId:i,onSelectChat:a,onUpdateChatTitle:o,onDeleteChat:s,onNewChat:c,contextCache:l,isMobileOpen:u,onMobileClose:d}),(0,P.jsx)(`main`,{className:`flex-1 md:ml-64 flex flex-col h-full relative w-full min-w-0`,children:e})]})}var Qt={sm:`w-4 h-4`,md:`w-6 h-6`,lg:`w-10 h-10`};function $t({size:e=`md`,className:t=``}){return(0,P.jsx)(`div`,{className:`${Qt[e]} rounded-full border-2 border-primary border-t-transparent animate-spin ${t}`})}var en=!1;function tn(){en||window.location.pathname===`/login`||window.location.pathname===`/signup`||(en=!0,setTimeout(()=>{dt(),en=!1},100))}var H=it(st(),{fetcher:(async(e,t)=>{let n=await fetch(e,{...t,credentials:`include`});return n.status===401&&tn(),n})}),U={all:[`chats`],lists:()=>[...U.all,`list`],list:e=>[...U.lists(),{filters:e}],details:()=>[...U.all,`detail`],detail:e=>[...U.details(),e]},nn=()=>D({queryKey:U.lists(),queryFn:async()=>{let{data:e,error:t}=await H.api.chats.get();if(t)throw Error(V(t.value));return e}});function rn(e,t){e.setQueriesData({queryKey:U.lists()},e=>t(e??[]))}function an(e,t){return{...e,...t}}function on(){return k(nn())}function sn(){let e=O();return j({mutationFn:async e=>{let{data:t,error:n}=await H.api.chats.post(e);if(n)throw Error(V(n.value));return t},onSuccess:t=>{e.setQueryData(U.detail(t.id),t),rn(e,e=>[t,...e.filter(e=>e.id!==t.id)])}})}function cn(){let e=O();return j({mutationFn:async({id:e,updates:t})=>{let{data:n,error:r}=await H.api.chats({id:e}).put(t);if(r)throw Error(V(r.value));return n},onSuccess:(t,n)=>{e.setQueryData(U.detail(n.id),e=>e&&an(e,n.updates)),rn(e,e=>e.map(e=>e.id===n.id?an(e,n.updates):e))}})}function ln(){let e=O();return j({mutationFn:async e=>{let{data:t,error:n}=await H.api.chats({id:e}).delete();if(n)throw Error(V(n.value));return t},onSuccess:(t,n)=>{e.removeQueries({queryKey:U.detail(n),exact:!0}),rn(e,e=>e.filter(e=>e.id!==n))}})}var W={all:[`messages`],lists:()=>[...W.all,`list`],list:e=>[...W.lists(),e]},un=e=>Ce({queryKey:W.list(e),queryFn:async({pageParam:t})=>{let n=t?{cursor:t,limit:`50`}:{limit:`50`},{data:r,error:i}=await H.api.chats({id:e}).messages.get({query:n});if(i)throw Error(V(i.value));return r},initialPageParam:null,getNextPageParam:e=>e.nextCursor});function dn(e){return Pe({...un(e??``),enabled:!!e})}var fn={all:[`agent-settings`],list:()=>[...fn.all,`list`]};function pn(){return D({queryKey:fn.list(),staleTime:3e4,queryFn:async()=>{let{data:e,error:t}=await H.api.settings.agents.get();if(t)throw Error(V(t.value,I.settings.agents.loadError));return e}})}var G=1e3,mn=1e3,hn=1e3,gn=1e3,_n=1e3,vn=1e3,yn=`New Chat`,bn=/^New Chat \[[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}\]$/;function xn(e){return String(e).padStart(2,`0`)}function Sn(e=new Date){return`${yn} [${e.getFullYear()}-${xn(e.getMonth()+1)}-${xn(e.getDate())} ${xn(e.getHours())}:${xn(e.getMinutes())}]`}function Cn(e){return bn.test(e)}function wn(e){if(!Number.isFinite(e))return 30;let t=Math.round(e);return t<10?10:t>80?80:t}function Tn(e,t=30){let n=e.replace(/\s+/g,` `).trim();if(n.length===0)return null;let r=wn(t);return n.length<=r?n:`${n.slice(0,r).trimEnd()}...`}var En=`current_model`,Dn=[`512px`,`1K`,`2K`,`4K`],On={textSystemPrompt:``,imageSystemPrompt:``,agentsMd:{id:`agentsMd`,label:`AGENTS.md`,path:`~/.mango/AGENTS.md`,enabled:!1,injectionRole:`system`,sendFrequency:`first-turn`},claudeMd:{id:`claudeMd`,label:`CLAUDE.md`,path:`~/.claude/CLAUDE.md`,enabled:!1,injectionRole:`system`,sendFrequency:`first-turn`},customRules:[]},K={compactionBehavior:`ask`,warningThreshold:.85,dangerThreshold:.92,hardStopThreshold:.97,preferredSummaryModel:`current_model`,providerCompactionEnabled:!0},kn={autoRenameEnabled:!0,strategy:`prompt_prefix`,promptPrefixLength:30,preferredModel:En},q={enabled:!0,chatDelegationEnabled:!1,traceVisibility:`compact`,maxDepth:1,maxSubagentCalls:gn,timeoutMs:900*1e3,defaultMaxTurns:vn},J={promptSettings:On,globalImageQuality:`1K`,thinkingEnabled:!1,reasoningEffort:`medium`,maxToolIterations:mn,multiAgentSettings:q,contextSettings:K,chatTitleSettings:kn};function An(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jn(e){return e===`system`||e===`user`}function Mn(e){return e===`first-turn`||e===`every-turn`}function Nn(e){return e===`ask`||e===`auto_compact_current_chat`||e===`continue_with_summary_new_chat`||e===`off`}function Pn(e){return e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`}function Fn(e){return typeof e==`string`&&Dn.includes(e)}function In(e){return e===`prompt_prefix`||e===`model`}function Ln(e){return e===`compact`||e===`full`||e===`off`}function Rn(e,t){return Number.isFinite(e)?Math.min(.99,Math.max(.5,Math.round(e*100)/100)):t}function zn(e,t,n,r){return typeof e!=`number`||!Number.isFinite(e)?t:Math.min(r,Math.max(n,Math.round(e)))}function Bn(e,t){return An(e)?{id:typeof e.id==`string`&&e.id.length>0?e.id:t.id,label:typeof e.label==`string`?e.label:t.label,path:typeof e.path==`string`?e.path:t.path,enabled:typeof e.enabled==`boolean`?e.enabled:t.enabled,injectionRole:jn(e.injectionRole)?e.injectionRole:t.injectionRole,sendFrequency:Mn(e.sendFrequency)?e.sendFrequency:t.sendFrequency}:t}function Vn(e){return An(e)?{textSystemPrompt:typeof e.textSystemPrompt==`string`?e.textSystemPrompt:``,imageSystemPrompt:typeof e.imageSystemPrompt==`string`?e.imageSystemPrompt:``,agentsMd:Bn(e.agentsMd,On.agentsMd),claudeMd:Bn(e.claudeMd,On.claudeMd),customRules:Array.isArray(e.customRules)?e.customRules.map((e,t)=>Bn(e,{id:`custom-rule-${t+1}`,label:``,path:``,enabled:!1,injectionRole:`system`,sendFrequency:`first-turn`})):[]}:On}function Hn(e){if(!Number.isFinite(e))return mn;let t=Math.round(e);return t<1?1:t>1e3?G:t}function Un(e){if(!An(e))return K;let[t,n,r]=[Rn(typeof e.warningThreshold==`number`?e.warningThreshold:K.warningThreshold,K.warningThreshold),Rn(typeof e.dangerThreshold==`number`?e.dangerThreshold:K.dangerThreshold,K.dangerThreshold),Rn(typeof e.hardStopThreshold==`number`?e.hardStopThreshold:K.hardStopThreshold,K.hardStopThreshold)].sort((e,t)=>e-t);return{compactionBehavior:Nn(e.compactionBehavior)?e.compactionBehavior:K.compactionBehavior,warningThreshold:t,dangerThreshold:n,hardStopThreshold:r,preferredSummaryModel:typeof e.preferredSummaryModel==`string`&&e.preferredSummaryModel.length>0?e.preferredSummaryModel:K.preferredSummaryModel,providerCompactionEnabled:typeof e.providerCompactionEnabled==`boolean`?e.providerCompactionEnabled:K.providerCompactionEnabled}}function Wn(e){return An(e)?{autoRenameEnabled:typeof e.autoRenameEnabled==`boolean`?e.autoRenameEnabled:kn.autoRenameEnabled,strategy:In(e.strategy)?e.strategy:kn.strategy,promptPrefixLength:wn(typeof e.promptPrefixLength==`number`?e.promptPrefixLength:kn.promptPrefixLength),preferredModel:typeof e.preferredModel==`string`&&e.preferredModel.length>0?e.preferredModel:kn.preferredModel}:kn}function Gn(e){return An(e)?{enabled:typeof e.enabled==`boolean`?e.enabled:q.enabled,chatDelegationEnabled:typeof e.chatDelegationEnabled==`boolean`?e.chatDelegationEnabled:q.chatDelegationEnabled,traceVisibility:Ln(e.traceVisibility)?e.traceVisibility:q.traceVisibility,maxDepth:zn(e.maxDepth,q.maxDepth,0,3),maxSubagentCalls:zn(e.maxSubagentCalls,q.maxSubagentCalls,0,hn),timeoutMs:zn(e.timeoutMs,q.timeoutMs,1e3,36e5),defaultMaxTurns:zn(e.defaultMaxTurns,q.defaultMaxTurns,1,_n)}:q}function Kn(e){return An(e)?{promptSettings:Vn(e.promptSettings),globalImageQuality:Fn(e.globalImageQuality)?e.globalImageQuality:J.globalImageQuality,thinkingEnabled:typeof e.thinkingEnabled==`boolean`?e.thinkingEnabled:J.thinkingEnabled,reasoningEffort:Pn(e.reasoningEffort)?e.reasoningEffort:J.reasoningEffort,maxToolIterations:Hn(typeof e.maxToolIterations==`number`?e.maxToolIterations:J.maxToolIterations),multiAgentSettings:Gn(e.multiAgentSettings),contextSettings:Un(e.contextSettings),chatTitleSettings:Wn(e.chatTitleSettings)}:J}var qn=M.Union([M.Literal(`chat`),M.Literal(`agent`),M.Literal(`image`)]),Jn=M.Union([M.Literal(`image`),M.Literal(`text`),M.Literal(`pdf`),M.Literal(`data`),M.Literal(`unknown`)]),Yn=M.Union([M.Literal(`stateful`),M.Literal(`stateless-loop`),M.Literal(`replay`),M.Literal(`compacted`),M.Literal(`degraded`)]),Xn=M.Union([M.Literal(`normal`),M.Literal(`info`),M.Literal(`warning`),M.Literal(`danger`),M.Literal(`critical`)]),Zn=M.Union([M.Literal(`ask`),M.Literal(`auto_compact_current_chat`),M.Literal(`continue_with_summary_new_chat`),M.Literal(`off`)]),Qn=M.Object({estimatedInputTokens:M.Number(),contextLimit:M.Number(),estimatedUsageRatio:M.Number(),mode:Yn,severity:Xn}),$n=M.Object({compactionBehavior:Zn,warningThreshold:M.Number({minimum:.5,maximum:.99}),dangerThreshold:M.Number({minimum:.5,maximum:.99}),hardStopThreshold:M.Number({minimum:.5,maximum:.99}),preferredSummaryModel:M.String(),providerCompactionEnabled:M.Boolean()}),er=M.Object({id:M.String(),chatId:M.String(),messageId:M.Optional(M.Union([M.String(),M.Null()])),originalName:M.String(),mimeType:M.String(),sizeBytes:M.Number(),kind:Jn,url:M.String(),createdAt:M.Number()});M.Object({attachment:er}),M.Object({title:M.String(),model:M.Optional(M.String())}),M.Object({prompt:M.String(),model:M.String()}),M.Object({title:M.String()}),M.Object({title:M.Optional(M.String()),model:M.Optional(M.String()),textModel:M.Optional(M.String()),imageModel:M.Optional(M.String()),lastUsedMode:M.Optional(qn),selectedAgentId:M.Optional(M.String())}),M.Object({model:M.Optional(M.String())}),M.Object({model:M.Optional(M.String())}),M.Object({chatId:M.String(),summaryMessageId:M.String(),contextInfo:M.Union([Qn,M.Null()])}),M.Object({id:M.String(),chatId:M.String(),role:M.Union([M.Literal(`user`),M.Literal(`ai`)]),text:M.String(),imageUrl:M.Optional(M.String()),referenceImage:M.Optional(M.String()),timestamp:M.Number(),isGenerating:M.Optional(M.Boolean()),generationTime:M.Optional(M.String()),modelName:M.Optional(M.String()),styleParams:M.Optional(M.Array(M.String())),interactionMode:M.Optional(qn)}),M.Object({text:M.Optional(M.String()),imageUrl:M.Optional(M.String()),isGenerating:M.Optional(M.Boolean()),generationTime:M.Optional(M.String()),modelName:M.Optional(M.String()),styleParams:M.Optional(M.Array(M.String()))});var tr=M.Union([M.Literal(`agents`),M.Literal(`claude`)]),nr=M.Union([M.Literal(`system`),M.Literal(`user`)]),rr=M.Union([M.Literal(`first-turn`),M.Literal(`every-turn`)]),ir=M.Object({id:M.String(),label:M.String(),path:M.String(),enabled:M.Boolean(),injectionRole:nr,sendFrequency:rr}),ar=M.Object({textSystemPrompt:M.String(),imageSystemPrompt:M.String(),agentsMd:ir,claudeMd:ir,customRules:M.Array(ir)}),or=M.Object({kind:M.Optional(tr),label:M.String(),path:M.String(),exists:M.Boolean(),readable:M.Boolean(),sizeBytes:M.Optional(M.Integer({minimum:0})),error:M.Optional(M.String())});M.Object({path:M.String({minLength:1})}),M.Composite([or,M.Object({content:M.Optional(M.String()),truncated:M.Boolean()})]),M.Object({files:M.Array(or)});function sr(e,t){return M.Unsafe(M.Array(e,t))}var cr=M.Union([M.Literal(`gemini`),M.Literal(`openai`),M.Literal(`openai-compatible`),M.Literal(`anthropic`),M.Literal(`deepseek`),M.Literal(`cursor`),M.Literal(`chatgpt`)]),lr=M.Literal(`provider`),Y=M.Union([M.Literal(`low`),M.Literal(`medium`),M.Literal(`high`),M.Literal(`xhigh`),M.Literal(`max`)]),ur=M.Union([M.Literal(`auto`),M.Literal(`stable-prefix`),M.Literal(`off`)]),dr=M.Object({supportedEfforts:sr(Y,{minItems:1}),defaultEffort:Y,maxEffort:M.Optional(Y),thinkingToggleSupported:M.Boolean(),reasoningWithToolsSupported:M.Boolean()}),fr=M.Object({provider:cr,thinkingEnabled:M.Optional(M.Boolean()),reasoningEffort:M.Optional(Y),maxOutputTokens:M.Optional(M.Integer({minimum:1,maximum:1e6})),maxToolIterations:M.Optional(M.Integer({minimum:1,maximum:G})),providerCompactionEnabled:M.Optional(M.Boolean()),promptCachePreference:M.Optional(ur),parallelToolCallsEnabled:M.Optional(M.Boolean())}),pr=`22.13`,mr=M.Union([M.Literal(`cursor.node_not_found`),M.Literal(`cursor.node_invalid`),M.Literal(`cursor.version_insufficient`),M.Literal(`cursor.sidecar_missing`),M.Literal(`cursor.sdk_missing`),M.Literal(`cursor.sdk_incomplete`),M.Literal(`cursor.native_runtime_missing`)]),hr=M.Object({foundVersion:M.Optional(M.String()),packageName:M.Optional(M.String()),sidecarPath:M.Optional(M.String()),nodePath:M.Optional(M.String())});M.Object({thinkingEnabled:M.Optional(M.Boolean()),reasoningEffort:M.Optional(Y),maxOutputTokens:M.Optional(M.Integer({minimum:1,maximum:1e6})),maxToolIterations:M.Optional(M.Integer({minimum:1,maximum:G})),providerCompactionEnabled:M.Optional(M.Boolean()),promptCachePreference:M.Optional(ur),parallelToolCallsEnabled:M.Optional(M.Boolean())});var gr=M.Object({provider:cr,displayName:M.String(),scope:lr,reasoning:dr,promptCachingSupported:M.Boolean(),toolUseSupported:M.Boolean(),structuredOutputSupported:M.Boolean(),maxOutputTokensLimit:M.Integer({minimum:1}),settings:fr,runtimeAvailable:M.Boolean(),runtimeUnavailableReason:M.Optional(mr),runtimeUnavailableReasonParams:M.Optional(hr)});M.Object({providers:M.Array(gr)});var _r=M.Union([M.Literal(`512px`),M.Literal(`1K`),M.Literal(`2K`),M.Literal(`4K`)]),vr=M.Object({autoRenameEnabled:M.Boolean(),strategy:M.Union([M.Literal(`prompt_prefix`),M.Literal(`model`)]),promptPrefixLength:M.Integer({minimum:10,maximum:80}),preferredModel:M.String()}),yr=M.Object({enabled:M.Boolean(),chatDelegationEnabled:M.Boolean(),traceVisibility:M.Union([M.Literal(`compact`),M.Literal(`full`),M.Literal(`off`)]),maxDepth:M.Integer({minimum:0,maximum:3}),maxSubagentCalls:M.Integer({minimum:0,maximum:hn}),timeoutMs:M.Integer({minimum:1e3,maximum:36e5}),defaultMaxTurns:M.Integer({minimum:1,maximum:_n})});M.Object({promptSettings:ar,globalImageQuality:_r,thinkingEnabled:M.Boolean(),reasoningEffort:Y,maxToolIterations:M.Integer({minimum:1,maximum:G}),multiAgentSettings:yr,contextSettings:$n,chatTitleSettings:vr});var br={all:[`app-settings`],current:()=>[...br.all,`current`]};function xr(){return D({queryKey:br.current(),staleTime:3e4,queryFn:async()=>{let{data:e,error:t}=await H.api.settings.app.get();if(t)throw Error(V(t.value,I.settings.app.loadError));return Kn(e??J)}})}function Sr(){let[e,t]=(0,N.useState)(null),{data:n,isLoading:r,error:i,refetch:a}=on(),o=sn(),s=cn(),c=ln(),l=(0,N.useMemo)(()=>n||[],[n]),u=i?i.message:null,d=e??(l.length>0?l[0].id:null),f=(0,N.useCallback)(async()=>{await a()},[a]),p=(0,N.useCallback)(async e=>{let n=await o.mutateAsync({title:e||Sn()});return t(n.id),n},[o]),m=(0,N.useCallback)(async(e,t,n)=>{await s.mutateAsync({id:e,updates:{[t]:n}})},[s]),h=(0,N.useCallback)(async(e,t)=>{await s.mutateAsync({id:e,updates:{title:t}})},[s]),g=(0,N.useCallback)(async(e,t)=>{await s.mutateAsync({id:e,updates:t})},[s]),_=(0,N.useCallback)(async n=>{if(await c.mutateAsync(n),e===n){let e=l.filter(e=>e.id!==n);t(e.length>0?e[0].id:null)}},[c,e,l]),v=(0,N.useCallback)(e=>{t(e)},[]);return{chats:l,currentChatId:d,currentChat:l.find(e=>e.id===d)||null,isLoading:r,error:u,loadChats:f,createChat:p,updateChatModel:m,updateChatTitle:h,updateChatAgentSelection:g,deleteChat:_,selectChat:v,setCurrentChatId:t}}function Cr(){let e=O();return{appendOptimisticMessages:(0,N.useCallback)((t,n)=>{e.setQueryData(W.list(t),e=>{let t=e??{pages:[{messages:[],nextCursor:null}],pageParams:[null]},r=t.pages[0];return r?{...t,pages:[{...r,messages:[...r.messages,...n]},...t.pages.slice(1)]}:t})},[e]),replaceOptimisticMessages:(0,N.useCallback)((t,n,r)=>{e.setQueryData(W.list(t),e=>{if(!e)return{pages:[{messages:r,nextCursor:null}],pageParams:[null]};let t=e.pages.map(t=>{let i=t.messages.filter(e=>!n.includes(e.id));return{...t,messages:t===e.pages[0]?[...i,...r]:i}});return{...e,pages:t}})},[e]),updateOptimisticMessage:(0,N.useCallback)((t,n,r)=>{e.setQueryData(W.list(t),e=>{if(!e)return e;let t=e.pages.map(e=>({...e,messages:e.messages.map(e=>e.id===n?{...e,...r}:e)}));return{...e,pages:t}})},[e])}}var wr=[`chat`,`default`,`explore`],Tr=/^user:[a-z0-9]+(?:-[a-z0-9]+)*$/,Er=Object.freeze({id:`chat`,name:`Chat`,description:`General-purpose conversational chat agent.`,kind:`builtin`,role:`primary`,source:{type:`builtin`},systemPrompt:``,toolNames:[],toolsEnabled:!0,subagentIds:[],metadata:{}}),Dr=Object.freeze({id:`default`,name:`Default`,description:`Default task-focused agent profile.`,kind:`builtin`,role:`both`,source:{type:`builtin`},systemPrompt:``,toolNames:[],toolsEnabled:!0,subagentIds:[`explore`],metadata:{}}),Or=Object.freeze({id:`explore`,name:`Explore`,description:`Built-in subagent for bounded research and codebase exploration.`,kind:`builtin`,role:`subagent`,source:{type:`builtin`},systemPrompt:`Explore the requested problem space carefully. Gather relevant context, inspect available files or tools when useful, and return a concise, concrete final report.
19
+
20
+ Final report requirements:
21
+ - Always end with a "Final Report" section.
22
+ - Include: key findings, relevant file paths, tools/commands used, risks or unknowns, and recommended next steps.
23
+ - Do not make changes unless explicitly asked.`,toolNames:[],toolsEnabled:!0,subagentIds:[],metadata:{}});Object.freeze([Er,Dr,Or]);function kr(e){return typeof e==`string`&&Ar(e)}function Ar(e){return jr(e)||Tr.test(e)}function jr(e){return wr.some(t=>t===e)}var Mr=M.Union([M.Literal(`chat`),M.Literal(`default`),M.Literal(`explore`)]),Nr=M.Unsafe(M.String({pattern:`^user:[a-z0-9]+(?:-[a-z0-9]+)*$`})),Pr=M.Union([Mr,Nr]);M.Union([M.Literal(`chat`),M.Literal(`agent`)]);var Fr=M.Union([M.Literal(`builtin`),M.Literal(`user`)]),Ir=M.Union([M.Literal(`primary`),M.Literal(`subagent`),M.Literal(`both`)]),Lr=M.Union([M.Object({type:M.Literal(`builtin`)}),M.Object({type:M.Literal(`markdown`),path:M.Optional(M.String({minLength:1}))})]),Rr=M.Record(M.String(),M.Unknown()),zr=M.Object({id:Pr,name:M.String({minLength:1}),description:M.String(),kind:Fr,role:Ir,source:Lr,systemPrompt:M.String(),model:M.Optional(M.String({minLength:1})),thinkingEnabled:M.Optional(M.Boolean()),reasoningEffort:M.Optional(Y),maxToolIterations:M.Optional(M.Integer({minimum:1,maximum:G})),toolNames:sr(M.String({minLength:1})),toolsEnabled:M.Boolean(),subagentIds:sr(Pr),metadata:Rr});M.Object({agents:M.Array(zr)});var Br=M.Object({name:M.String({minLength:1}),description:M.String(),role:Ir,systemPrompt:M.String(),model:M.Optional(M.String({minLength:1})),thinkingEnabled:M.Optional(M.Boolean()),reasoningEffort:M.Optional(Y),maxToolIterations:M.Optional(M.Integer({minimum:1,maximum:G})),toolNames:sr(M.String({minLength:1})),toolsEnabled:M.Boolean(),subagentIds:sr(Pr),metadata:Rr});M.Intersect([Br,M.Object({slug:M.Optional(M.String({minLength:1}))})]),M.Object({markdown:M.String(),id:M.Optional(Nr)}),M.Object({profile:zr,markdown:M.String()}),M.Object({success:M.Literal(!0)});function Vr({currentChatId:e}){let[t,n]=(0,N.useState)(!1),[r,i]=(0,N.useState)(null),[a,o]=(0,N.useState)(null),s=(0,N.useRef)(null),c=(0,N.useRef)(new Map),[l,u]=(0,N.useState)(0),d=(0,N.useRef)(e);return d.current=e,(0,N.useEffect)(()=>{i(e?c.current.get(e)??null:null),o(null)},[e]),{isGenerating:t,setIsGenerating:n,contextInfo:r,fallbackNotice:a,setFallbackNotice:o,handleStop:(0,N.useCallback)(()=>{s.current?.abort()},[]),abortControllerRef:s,setAbortController:(0,N.useCallback)(e=>{s.current=e},[]),updateContextInfo:(0,N.useCallback)((e,t)=>{i(t),c.current.set(e,t),u(e=>e+1)},[]),seedContextInfo:(0,N.useCallback)((e,t)=>{c.current.set(e,t),u(e=>e+1),e===d.current&&i(t)},[]),contextCache:c.current}}async function Hr(e){let{data:t,error:n}=await H.api.chats[`title-suggestion`].post(e);if(n)throw Error(V(n.value,I.chat.titleGenerationFailed));return t}async function Ur(e,t){let{data:n,error:r}=await H.api.chats({id:e}).compact.post(t);if(r)throw Error(V(r.value));return n}async function Wr(e,t){let{data:n,error:r}=await H.api.chats({id:e})[`summarize-to-new-chat`].post(t);if(r)throw Error(V(r.value));return n}function Gr(e,t){if(!e?.length)return t;if(!t?.length)return e;let n=[...e];for(let e of t)n.some(t=>t.event===e.event&&t.attempt===e.attempt&&t.detail===e.detail)||n.push(e);return n}var Kr={subagent_delegation_started:`delegation_started`,subagent_delegation_completed:`delegation_completed`,subagent_delegation_failed:`delegation_failed`,subagent_response_attempt:`response_attempt`,subagent_response_recovered:`response_recovered`,subagent_response_timeout:`response_timeout`,subagent_response_fallback:`response_fallback`};function qr({userMessageId:e,aiMessageId:t}){return{text:``,parts:[],currentUserMessageId:e,currentAiMessageId:t,receivedServerUserMessageId:!1,receivedServerAiMessageId:!1,activeThinkingIndex:null,userMessageUpdate:null,aiMessageUpdate:null}}function Jr(e,t,n){let r=Yr(e);switch(t.type){case`user_message_id`:return mi(r,{id:t.messageId},t.messageId,!0);case`error`:return Xr(r,t.error);case`thinking_start`:return Zr(r);case`thinking`:return Qr(r,t.text);case`text`:return $r(r,t.text);case`tool_call_started`:return ei(r,t.callId,t.name);case`tool_call_completed`:return ti(r,t.callId,t.arguments);case`tool_result`:return ni(r,t.callId,t.result,t.isError);case`subagent_started`:return ri(r,t);case`subagent_text`:return ii(r,t.callId,t.text);case`subagent_tool_call_started`:return ai(r,t.callId,t.toolCallId,t.name);case`subagent_completed`:return oi(r,t.callId,t.summary,t.toolCallCount);case`subagent_failed`:return si(r,t.callId,t.error);case`image_generation_started`:return ci(r,t);case`image_generation_completed`:return li(r,t);case`image_generation_failed`:return ui(r,t);case`continuation_transition`:return di(r,t);case`system_event`:return fi(r,t.event,t.detail,n.pendingSubagentName);case`done`:return pi(r,t.messageId,t.generationTime);case`context_info`:case`fallback_notice`:return r;default:return t}}function Yr(e){return{...e,userMessageUpdate:null,aiMessageUpdate:null}}function Xr(e,t){let n=[...e.parts,{type:`error`,text:t}];return X({...e,parts:n},{isGenerating:!1,text:e.text||t,parts:n})}function Zr(e){let t=[...e.parts,{type:`thinking`,text:``}];return X({...e,parts:t,activeThinkingIndex:t.length-1},{parts:t})}function Qr(e,t){let n=e.activeThinkingIndex===null?Zr(e):e,r=n.activeThinkingIndex;if(r===null)return n;let i=n.parts[r],a=i?.type===`thinking`?i.text:``,o=hi(n.parts,r,{type:`thinking`,text:`${a}${t}`});return X({...n,parts:o},{parts:o})}function $r(e,t){let n=`${e.text}${t}`,r=gi(e.parts,n);return X({...e,text:n,parts:r,activeThinkingIndex:null},{text:n,parts:r})}function ei(e,t,n){let r=[...e.parts,{type:`tool_call`,toolCallId:t,name:n,args:{}}];return X({...e,parts:r,activeThinkingIndex:null},{parts:r})}function ti(e,t,n){let r=_i(n),i=e.parts.map(e=>e.type===`tool_call`&&e.toolCallId===t?{...e,args:r}:e);return X({...e,parts:i},{parts:i})}function ni(e,t,n,r){let i=[...e.parts,{type:`tool_result`,toolCallId:t,content:JSON.stringify(n),isError:r}];return X({...e,parts:i},{parts:i})}function ri(e,t){let n=yi(e.parts,{type:`subagent_trace`,toolCallId:t.callId,agentId:t.agentId,agentName:t.agentName,status:`running`,summary:t.task,toolCallCount:0,messages:[],tools:[]});return X({...e,parts:n},{parts:n})}function ii(e,t,n){let r=bi(e.parts,t,e=>{let t=e.messages.at(-1),r=t?.role===`assistant`?[...e.messages.slice(0,-1),{role:`assistant`,text:`${t.text}${n}`}]:[...e.messages,{role:`assistant`,text:n}],i=r.at(-1)?.text;return{...e,...i?{lastMessage:i}:{},messages:r}});return X({...e,parts:r},{parts:r})}function ai(e,t,n,r){let i=bi(e.parts,t,e=>({...e,toolCallCount:e.toolCallCount+1,tools:[...e.tools,{callId:n,name:r}]}));return X({...e,parts:i},{parts:i})}function oi(e,t,n,r){let i=bi(e.parts,t,e=>({...e,status:`completed`,summary:n,toolCallCount:r,lastMessage:n}));return X({...e,parts:i},{parts:i})}function si(e,t,n){let r=bi(e.parts,t,e=>({...e,status:`failed`,summary:n,error:n}));return X({...e,parts:r},{parts:r})}function ci(e,t){let n=vi(e.parts,{type:`generated_image`,imageId:t.imageId,toolCallId:t.toolCallId,status:`generating`,prompt:t.prompt});return X({...e,parts:n,activeThinkingIndex:null},{parts:n})}function li(e,t){let n=vi(e.parts,{type:`generated_image`,imageId:t.imageId,toolCallId:t.toolCallId,status:`completed`,prompt:t.prompt,imageUrl:t.imageUrl,modelName:t.modelName,generationTime:t.generationTime});return X({...e,parts:n},{parts:n})}function ui(e,t){let n=vi(e.parts,{type:`generated_image`,imageId:t.imageId,toolCallId:t.toolCallId,status:`error`,prompt:t.prompt,error:t.error,modelName:t.modelName,generationTime:t.generationTime});return X({...e,parts:n},{parts:n})}function di(e,t){let n=[...e.parts,{type:`continuation_transition`,provider:t.provider,modelName:t.modelName,fromProvider:t.fromProvider,fromMode:t.fromMode,toMode:t.toMode,reasonCode:t.reasonCode,detail:t.detail,recovered:!1}];return X({...e,parts:n},{parts:n})}function fi(e,t,n,r){let i=Si(t,n),a=i?xi(e.parts,i,r):[...e.parts,{type:`system_event`,event:t,detail:n}];return X({...e,parts:a},{parts:a})}function pi(e,t,n){return X({...e,activeThinkingIndex:null},{isGenerating:!1,text:e.text,parts:[...e.parts],generationTime:n,...t?{id:t}:{}},t,t?!0:e.receivedServerAiMessageId)}function mi(e,t,n=e.currentUserMessageId,r=e.receivedServerUserMessageId){return{...e,currentUserMessageId:n,receivedServerUserMessageId:r,userMessageUpdate:{targetMessageId:e.currentUserMessageId,patch:t}}}function X(e,t,n=e.currentAiMessageId,r=e.receivedServerAiMessageId){return{...e,currentAiMessageId:n,receivedServerAiMessageId:r,aiMessageUpdate:{targetMessageId:e.currentAiMessageId,patch:t}}}function hi(e,t,n){return e.map((e,r)=>r===t?n:e)}function gi(e,t){let n=e.findIndex(e=>e.type===`text`);return n===-1?[...e,{type:`text`,text:t}]:[...e.slice(0,n),...e.slice(n+1),{type:`text`,text:t}]}function _i(e){try{return JSON.parse(e)}catch{return{}}}function vi(e,t){let n=e.findIndex(e=>e.type===`generated_image`&&e.imageId===t.imageId&&e.toolCallId===t.toolCallId);return n===-1?[...e,t]:hi(e,n,t)}function yi(e,t){let n=e.findIndex(e=>e.type===`subagent_trace`&&e.toolCallId===t.toolCallId);return n===-1?[...e,t]:e.map((e,r)=>r!==n||e.type!==`subagent_trace`?e:{...t,messages:t.messages.length>0?t.messages:e.messages,tools:t.tools.length>0?t.tools:e.tools,events:Gr(e.events,t.events)})}function bi(e,t,n){return e.map(e=>e.type!==`subagent_trace`||e.toolCallId!==t?e:n(e))}function xi(e,t,n){let r=e.findIndex(e=>e.type===`subagent_trace`&&e.toolCallId===t.callId),i={event:t.event,...t.attempt===void 0?{}:{attempt:t.attempt},...t.detail?{detail:t.detail}:{}};return r===-1?[...e,{type:`subagent_trace`,toolCallId:t.callId,agentId:t.agentId??t.callId,agentName:t.agentId??n,status:`running`,summary:``,toolCallCount:0,messages:[],tools:[],events:[i]}]:e.map((e,a)=>{if(a!==r||e.type!==`subagent_trace`)return e;let o=e.agentName===n&&t.agentId?t.agentId:e.agentName;return{...e,agentId:t.agentId??e.agentId,agentName:o,events:Gr(e.events,[i])}})}function Si(e,t){let n=Kr[e];if(!n)return null;let r=Ci(t,`call`);if(!r)return null;let i=Ci(t,`attempt`),a=i?Number(i):void 0,o=Ci(t,`agent`)??Ci(t,`target`);return{callId:r,event:n,...o?{agentId:o}:{},...a!==void 0&&Number.isFinite(a)?{attempt:a}:{},...t?{detail:t}:{}}}function Ci(e,t){return e?.match(RegExp(`(?:^|\\s)${t}=([^\\s]+)`))?.[1]}async function wi(e,t,n){let r=await fetch(`${st()}/api/respond/stream`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),credentials:`include`,signal:n});if(!r.ok){let e=I.errors.streamRequestFailed;try{let t=await r.json();t&&typeof t==`object`&&`error`in t&&typeof t.error==`string`&&(e=t.error)}catch{}throw Error(e)}if(!r.body)throw Error(I.errors.streamResponseNoBody);let i=r.body.getReader(),a=new TextDecoder,o=``;try{for(;;){let{value:e,done:n}=await i.read();if(n)break;o+=a.decode(e,{stream:!0});let r=o.split(`
24
+ `);o=r.pop()??``;for(let e of r)if(e.startsWith(`data: `))try{t(JSON.parse(e.slice(6)))}catch{}}}finally{i.releaseLock()}}function Ti(e,t){return e.preferredSummaryModel===`current_model`?t:e.preferredSummaryModel}function Ei(e,t,n){return e.autoRenameEnabled?n?!0:t!==void 0&&Cn(t):!1}function Di(e,t){return e.preferredModel===`current_model`?t:e.preferredModel}async function Oi(e,t,n){let r=Tn(e,t.promptPrefixLength);if(!r||t.strategy===`prompt_prefix`)return r;try{return(await Hr({prompt:e,model:Di(t,n)})).title}catch{return r}}async function ki({chats:e,chatId:t,prompt:n,chatTitleSettings:r,currentModel:i}){let a=await Oi(n,r,i);a&&await e.updateChatTitle(t,a)}function Ai(e){ki(e).catch(e=>{console.warn(`[chat-title] Failed to auto rename chat`,e)})}function ji(e,t,n){t&&n(e,t.targetMessageId,t.patch)}function Mi({chats:e,getActiveModel:t,systemPrompt:n,promptSettings:r,optimistic:i,thinkingEnabled:a,reasoningEffort:o,maxToolIterations:s,contextSettings:c,chatTitleSettings:l,currentChatId:u,getAgentSelection:d}){let f=O(),{t:p}=L(),m=p.chat.feed.subagentPendingName,h=Vr({currentChatId:u}),{appendOptimisticMessages:g,updateOptimisticMessage:_}=i,[v,y]=(0,N.useState)(null),b=(0,N.useCallback)(e=>{e.contextInfo&&h.seedContextInfo(e.chatId,e.contextInfo)},[h]),x=(0,N.useCallback)(async t=>{await Promise.all([e.loadChats(),f.invalidateQueries({queryKey:W.list(t)})])},[e,f]),S=(0,N.useCallback)(async(i,u)=>{if(h.abortControllerRef.current)return;h.setIsGenerating(!0);let v=e.currentChatId,y=!1,b=e.currentChat?.title;if(!v){let t=await e.createChat();v=t.id,b=t.title,y=!0}let x=t(),S=d(),C=S.mode===`agent`?`agent`:`chat`;Ei(l,b,y)&&Ai({chats:e,chatId:v,prompt:i,chatTitleSettings:l,currentModel:x});let w=`optimistic-user-${crypto.randomUUID()}`,ee=`optimistic-ai-${crypto.randomUUID()}`,te={id:w,chatId:v,role:`user`,text:i,timestamp:Date.now(),interactionMode:C,...C===`agent`?{agentId:S.agentId,agentName:S.agentName}:{}},ne={id:ee,chatId:v,role:`ai`,text:``,timestamp:Date.now(),isGenerating:!0,modelName:x,interactionMode:C,...C===`agent`?{agentId:S.agentId,agentName:S.agentName}:{}};g(v,[te,ne]);let re=new AbortController;h.setAbortController(re);let T=qr({userMessageId:w,aiMessageId:ee});try{await wi({chatId:v,prompt:i,model:x,systemPrompt:n||void 0,promptSettings:r,thinkingEnabled:a,reasoningEffort:o,maxToolIterations:s,contextSettings:c,toolIntent:u,agentMode:S.mode,agentId:kr(S.agentId)?S.agentId:void 0},e=>{T=Jr(T,e,{pendingSubagentName:m}),ji(v,T.userMessageUpdate,_),ji(v,T.aiMessageUpdate,_),e.type===`context_info`&&h.updateContextInfo(v,{estimatedInputTokens:e.estimatedInputTokens,contextLimit:e.contextLimit,estimatedUsageRatio:e.estimatedUsageRatio,mode:e.mode,severity:e.severity}),e.type===`fallback_notice`&&h.setFallbackNotice({from:e.from,to:e.to,reason:e.reason})},re.signal)}catch(e){if(e instanceof Error&&e.name===`AbortError`)_(v,T.currentAiMessageId,{isGenerating:!1});else{console.error(`[respond]`,e);let t=e instanceof Error?e.message:p.errors.textGenerationFailed,n=T.parts.some(e=>e.type===`error`)?T.parts:[...T.parts,{type:`error`,text:t}];_(v,T.currentAiMessageId,{isGenerating:!1,text:T.text||t,parts:n})}}finally{h.setAbortController(null),h.setIsGenerating(!1),y&&e.loadChats(),(!T.receivedServerUserMessageId||!T.receivedServerAiMessageId)&&f.invalidateQueries({queryKey:W.list(v)})}},[e,t,n,r,p,g,_,f,a,o,s,c,l,d,h,m]),C=(0,N.useCallback)(async()=>{let n=e.currentChatId;if(!n)throw Error(`No active chat available for compaction.`);y(`compact`);try{b(await Ur(n,{model:Ti(c,t())})),await x(n)}finally{y(null)}},[e.currentChatId,c,t,x,b]),w=(0,N.useCallback)(async()=>{let n=e.currentChatId;if(!n)throw Error(`No active chat available for summary handoff.`);y(`new-chat`);try{let r=await Wr(n,{model:Ti(c,t())});b(r),await e.loadChats(),e.setCurrentChatId(r.chatId),await f.invalidateQueries({queryKey:W.list(r.chatId)})}finally{y(null)}},[e,c,t,f,b]);return{isGenerating:h.isGenerating,handleRespond:S,handleCompactCurrentChat:C,handleStartSummarizedChat:w,handleStop:h.handleStop,contextInfo:h.contextInfo,fallbackNotice:h.fallbackNotice,seedContextInfo:h.seedContextInfo,contextCache:h.contextCache,isContextActionPending:v!==null}}async function Ni(e,t){let{data:n,error:r}=await H.api.settings.providers({provider:e}).put(t);if(r)throw Error(V(r.value,I.settings.providers.saveError));return n}var Pi={all:[`provider-settings`],list:()=>[...Pi.all,`list`],detail:e=>[...Pi.all,`detail`,e]};function Fi(){return D({queryKey:Pi.list(),staleTime:3e4,queryFn:async()=>{let{data:e,error:t}=await H.api.settings.providers.get();if(t)throw Error(V(t.value,I.settings.providers.loadError));return e}})}function Ii(e){return D({queryKey:Pi.detail(e),staleTime:3e4,queryFn:async()=>{let{data:t,error:n}=await H.api.settings.providers({provider:e}).get();if(n)throw Error(V(n.value,I.settings.providers.loadError));return t}})}function Li(e,t){e.setQueryData(Pi.detail(t.provider),t),e.setQueryData(Pi.list(),e=>e&&{providers:e.providers.map(e=>e.provider===t.provider?t:e)})}function Ri(){let{data:e,isLoading:t,error:n,refetch:r}=k(Fi());return{providers:e?.providers??[],isLoading:t,error:n,refetch:r}}function zi(e){let t=O(),{data:n,isLoading:r,error:i,refetch:a}=k({...Ii(e??``),enabled:!!e});return{descriptor:n??null,isLoading:r,error:i,refetch:a,invalidate:async()=>{e&&(await t.invalidateQueries({queryKey:Pi.detail(e)}),await t.invalidateQueries({queryKey:Pi.list()}))}}}function Bi(e){let t=O();return j({mutationFn:t=>Ni(e,t),onSuccess:e=>{Li(t,e)}})}function Vi({catalog:e,settings:t,currentTextModel:n}){let r=e.textModels,i=(0,N.useMemo)(()=>Gt(n??void 0,void 0,r),[r,n]),a=(0,N.useCallback)(()=>i,[i]),o=e.status!==`ready`||r.length===0,s=(0,N.useMemo)(()=>n?r.find(e=>e.modelId===n)?.provider??null:null,[r,n]),{descriptor:c}=zi(s);return{activeModels:r,activeModel:i,getActiveModel:a,isModelSelectorDisabled:o,lockedProvider:s,effectiveThinkingEnabled:c?.settings.thinkingEnabled??t.thinkingEnabled,effectiveReasoningEffort:c?.settings.reasoningEffort??t.reasoningEffort,effectiveMaxToolIterations:c?.settings.maxToolIterations??t.maxToolIterations}}function Hi({currentChatId:e,currentChat:t,updateChatAgentSelection:n}){let[r,i]=(0,N.useState)(null),a=k(pn()),o=(0,N.useMemo)(()=>a.data?.agents??[],[a.data?.agents]),s=(0,N.useMemo)(()=>({mode:t?.lastUsedMode===`agent`?`agent`:`chat`,agentId:t?.selectedAgentId??`default`}),[t?.lastUsedMode,t?.selectedAgentId]),c=r?.chatId===e?r:s,l=c.mode,u=c.agentId,d=(0,N.useMemo)(()=>o.find(e=>e.id===u)??null,[o,u]),f=(0,N.useCallback)((t,r)=>{i({chatId:e,mode:t,agentId:r}),e&&n(e,{lastUsedMode:t,selectedAgentId:t===`agent`?r:`chat`})},[e,n]),p=(0,N.useCallback)(e=>{f(e,e===`agent`?u||`default`:`chat`)},[f,u]),m=(0,N.useCallback)(e=>{f(`agent`,e)},[f]);return{agents:o,isAgentListLoading:a.isLoading,agentExecutionMode:l,selectedAgentId:u,selectedAgent:d,setAgentExecutionMode:p,setSelectedAgentId:m}}function Ui(e,t){(0,N.useEffect)(()=>{for(let n of e)`contextInfo`in n&&n.contextInfo&&t(n.id,n.contextInfo)},[e,t])}function Wi({chats:e,navigate:t}){return{handleNewChat:(0,N.useCallback)(async()=>{await e.createChat(),await t({to:`/`})},[e,t]),handleUpdateChatModel:(0,N.useCallback)(async(t,n)=>{await e.updateChatModel(t,`textModel`,n)},[e]),handleSelectChat:(0,N.useCallback)(n=>{e.selectChat(n),t({to:`/`})},[e,t]),handleUpdateChatTitle:(0,N.useCallback)(async(t,n)=>{await e.updateChatTitle(t,n)},[e]),handleDeleteChat:(0,N.useCallback)(async t=>{await e.deleteChat(t)},[e]),handleNavigate:(0,N.useCallback)(e=>{t({to:{chat:`/`,gallery:`/gallery`,settings:`/settings`,studio:`/studio`}[e]})},[t])}}function Gi({handleRespond:e,stopGeneration:t}){let[n,r]=(0,N.useState)(!1);return{imageToolIntent:n,setImageToolIntent:r,handleSubmit:(0,N.useCallback)(t=>{e(t,n?`image_generation_requested`:void 0),r(!1)},[e,n]),handleStop:(0,N.useCallback)(()=>{t(),r(!1)},[t])}}async function Ki(e){let{data:t,error:n}=await H.api.settings.app.put(e);if(n)throw Error(V(n.value,I.settings.app.saveError));return t}var qi=300;function Ji(){return{id:`custom-${Date.now()}`,label:``,path:``,enabled:!1,injectionRole:`system`,sendFrequency:`first-turn`}}function Yi(){let e=O(),t=(0,N.useRef)(null),n=(0,N.useRef)(null),{data:r,isLoading:i,error:a}=k({...xr(),placeholderData:J}),o=j({mutationFn:Ki,onMutate:t=>{let n=e.getQueryData(br.current())??J;return e.setQueryData(br.current(),t),{previousSettings:n}},onError:(t,n,r)=>{r?.previousSettings&&e.setQueryData(br.current(),r.previousSettings)},onSuccess:t=>{e.setQueryData(br.current(),Kn(t))}}),s=(0,N.useMemo)(()=>Kn(r??J),[r]),c=(0,N.useCallback)(()=>{n.current&&=(clearTimeout(n.current),null);let e=t.current;e&&(t.current=null,o.mutate(e))},[o]);(0,N.useEffect)(()=>()=>{c()},[c]);let l=(0,N.useCallback)(r=>{let i=Kn(r(Kn(e.getQueryData(br.current())??J)));e.setQueryData(br.current(),i),t.current=i,n.current&&clearTimeout(n.current),n.current=setTimeout(()=>{c()},qi)},[c,e]),u=(0,N.useCallback)(e=>{l(t=>({...t,promptSettings:e(t.promptSettings)}))},[l]),d=(0,N.useCallback)(e=>{l(t=>({...t,contextSettings:{...t.contextSettings,...e}}))},[l]),f=(0,N.useCallback)(e=>{l(t=>({...t,chatTitleSettings:Wn({...t.chatTitleSettings,...e})}))},[l]),p=(0,N.useCallback)(e=>{l(t=>({...t,multiAgentSettings:{...t.multiAgentSettings,...e}}))},[l]),m=(0,N.useCallback)(e=>{u(t=>({...t,textSystemPrompt:e}))},[u]),h=(0,N.useCallback)(e=>{u(t=>({...t,imageSystemPrompt:e}))},[u]),g=(0,N.useCallback)((e,t)=>{u(n=>e===`agentsMd`||e===`claudeMd`?{...n,[e]:{...n[e],...t}}:{...n,customRules:n.customRules.map(n=>n.id===e?{...n,...t}:n)})},[u]),_=(0,N.useCallback)(()=>{u(e=>({...e,customRules:[...e.customRules,Ji()]}))},[u]),v=(0,N.useCallback)(e=>{u(t=>({...t,customRules:t.customRules.filter(t=>t.id!==e)}))},[u]),y=(0,N.useCallback)(()=>{l(()=>J)},[l]);return{isLoading:i,error:a,globalTextSystemPrompt:s.promptSettings.textSystemPrompt,setGlobalTextSystemPrompt:m,globalImageSystemPrompt:s.promptSettings.imageSystemPrompt,setGlobalImageSystemPrompt:h,promptSettings:s.promptSettings,setTextSystemPrompt:m,setImageSystemPrompt:h,updateRuleFileSetting:g,addCustomRule:_,removeCustomRule:v,globalImageQuality:s.globalImageQuality,setGlobalImageQuality:e=>{l(t=>({...t,globalImageQuality:e}))},thinkingEnabled:s.thinkingEnabled,setThinkingEnabled:e=>{l(t=>({...t,thinkingEnabled:e}))},reasoningEffort:s.reasoningEffort,setReasoningEffort:e=>{l(t=>({...t,reasoningEffort:e}))},maxToolIterations:s.maxToolIterations,setMaxToolIterations:e=>{l(t=>({...t,maxToolIterations:Hn(e)}))},contextSettings:s.contextSettings,multiAgentSettings:s.multiAgentSettings,chatTitleSettings:s.chatTitleSettings,setContextCompactionBehavior:e=>d({compactionBehavior:e}),setContextWarningThreshold:e=>d({warningThreshold:e}),setContextDangerThreshold:e=>d({dangerThreshold:e}),setContextHardStopThreshold:e=>d({hardStopThreshold:e}),setPreferredSummaryModel:e=>d({preferredSummaryModel:e}),setProviderCompactionEnabled:e=>d({providerCompactionEnabled:e}),setMultiAgentEnabled:e=>p({enabled:e}),setChatDelegationEnabled:e=>p({chatDelegationEnabled:e}),setTraceVisibility:e=>p({traceVisibility:e}),setMaxDelegationDepth:e=>p({maxDepth:e}),setMaxSubagentCalls:e=>p({maxSubagentCalls:e}),setSubagentTimeoutMs:e=>p({timeoutMs:e}),setDefaultSubagentMaxTurns:e=>p({defaultMaxTurns:e}),setChatAutoRenameEnabled:e=>f({autoRenameEnabled:e}),setChatTitleStrategy:e=>f({strategy:e}),setChatTitlePromptPrefixLength:e=>f({promptPrefixLength:e}),setPreferredChatTitleModel:e=>f({preferredModel:e}),resetSettings:y}}var Xi={all:[`model-catalog`]},Zi=()=>D({queryKey:Xi.all,queryFn:async()=>{let{data:e,error:t}=await H.api.settings.models.get();if(t)throw Error(V(t.value));return e},staleTime:1e3*60*55,gcTime:1e3*60*60*2});function Qi(){let e=O(),{data:t,isLoading:n,error:r,refetch:i}=k(Zi()),a=(0,N.useCallback)(async()=>{await i()},[i]),o=(0,N.useCallback)(t=>{e.setQueryData(Xi.all,t)},[e]);return{catalog:t||Ht,isLoading:n,error:r?r.message:null,refreshCatalog:a,setCatalog:o}}function $i(){let e=Sr(),t=Qi(),n=Yi(),r=c(),i=Cr(),a=e.currentChat,o=Vi({catalog:t.catalog,settings:n,currentTextModel:a?.textModel}),s=Hi({currentChatId:e.currentChatId,currentChat:a,updateChatAgentSelection:e.updateChatAgentSelection}),l=Mi({chats:e,getActiveModel:o.getActiveModel,systemPrompt:n.globalTextSystemPrompt,promptSettings:n.promptSettings,optimistic:i,thinkingEnabled:o.effectiveThinkingEnabled,reasoningEffort:o.effectiveReasoningEffort,maxToolIterations:o.effectiveMaxToolIterations,contextSettings:n.contextSettings,chatTitleSettings:n.chatTitleSettings,currentChatId:e.currentChatId,getAgentSelection:()=>({mode:s.agentExecutionMode,agentId:s.agentExecutionMode===`agent`?s.selectedAgentId:`chat`,agentName:s.agentExecutionMode===`agent`?s.selectedAgent?.name:void 0})});Ui(e.chats,l.seedContextInfo);let u=Wi({chats:e,navigate:r}),d=Gi({handleRespond:l.handleRespond,stopGeneration:l.handleStop});return{imageToolIntent:d.imageToolIntent,agentExecutionMode:s.agentExecutionMode,selectedAgentId:s.selectedAgentId,agents:s.agents,isAgentListLoading:s.isAgentListLoading,isGenerating:l.isGenerating,chats:e.chats,currentChatId:e.currentChatId,catalog:t.catalog,settings:n,activeModels:o.activeModels,activeModel:o.activeModel,isModelSelectorDisabled:o.isModelSelectorDisabled,contextInfo:l.contextInfo,fallbackNotice:l.fallbackNotice,seedContextInfo:l.seedContextInfo,contextCache:l.contextCache,isContextActionPending:l.isContextActionPending,lockedProvider:o.lockedProvider,setImageToolIntent:d.setImageToolIntent,setAgentExecutionMode:s.setAgentExecutionMode,setSelectedAgentId:s.setSelectedAgentId,handleNewChat:u.handleNewChat,handleUpdateChatModel:u.handleUpdateChatModel,handleUpdateChatTitle:u.handleUpdateChatTitle,handleDeleteChat:u.handleDeleteChat,handleSelectChat:u.handleSelectChat,handleNavigate:u.handleNavigate,handleSubmit:d.handleSubmit,handleStop:d.handleStop,handleCompactCurrentChat:l.handleCompactCurrentChat,handleStartSummarizedChat:l.handleStartSummarizedChat,refreshCatalog:t.refreshCatalog}}var ea=(0,N.createContext)(null);function ta(){let e=(0,N.use)(ea);if(!e)throw Error(`useApp must be used within AppContext`);return e}var na=S(`/_authenticated`)({beforeLoad:({context:e,location:t})=>{e.auth.isAuthenticated||le({to:`/login`,search:{redirect:t.href},throw:!0})},loader:async({context:{queryClient:e}})=>{let t=e.ensureQueryData(nn());await Promise.all([t,e.ensureQueryData(Zi()),e.ensureQueryData(xr()),e.ensureQueryData(pn())]);let n=(await t)[0]?.id;n&&await e.prefetchInfiniteQuery(un(n))},component:ra});function ra(){let{auth:e}=na.useRouteContext(),t=c(),n=$i(),r=te().location.pathname,[i,a]=(0,N.useState)(!1);if(!e.isAuthenticated)return t({to:`/login`}),null;let o=`chat`;return r.includes(`/gallery`)&&(o=`gallery`),r.includes(`/settings`)&&(o=`settings`),r.includes(`/studio`)&&(o=`studio`),(0,P.jsx)(ea,{value:n,children:(0,P.jsxs)(Zt,{currentPage:o,onNavigate:e=>n.handleNavigate(e),chats:n.chats,currentChatId:n.currentChatId,onSelectChat:n.handleSelectChat,onUpdateChatTitle:(e,t)=>void n.handleUpdateChatTitle(e,t),onDeleteChat:e=>void n.handleDeleteChat(e),onNewChat:()=>void n.handleNewChat(),contextCache:n.contextCache,isMobileSidebarOpen:i,onMobileSidebarClose:()=>a(!1),children:[(0,P.jsx)(Jt,{activeModel:n.activeModel,activeModels:n.activeModels,isModelSelectorDisabled:n.isModelSelectorDisabled,currentChatId:n.currentChatId,currentPage:o,onUpdateChatModel:(e,t)=>void n.handleUpdateChatModel(e,t),onSetPageModel:e=>{n.currentChatId&&n.handleUpdateChatModel(n.currentChatId,e)},onNewChat:()=>void n.handleNewChat(),onNavigateToSettings:()=>n.handleNavigate(`settings`),modelCatalog:n.catalog,lockedProvider:n.lockedProvider,onMobileMenuToggle:()=>a(e=>!e)}),(0,P.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden flex flex-col`,children:(0,P.jsx)(N.Suspense,{fallback:(0,P.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,P.jsx)($t,{size:`lg`})}),children:(0,P.jsx)(v,{})})})]})})}var ia=24;function aa(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=ia}function oa(e){return e?.parts?.filter(e=>e.type===`generated_image`).map(e=>`${e.imageId}:${e.status}:${e.imageUrl??``}`).join(`,`)??``}function sa(e,t){let[n,r]=(0,N.useState)(!1),i=(0,N.useRef)(null),a=(0,N.useRef)(!0),o=(0,N.useRef)(null),s=(0,N.useRef)(!0),c=(0,N.useRef)(e),l=t.at(-1),u=l?.id??null,d=l?.isGenerating??!1,f=l?.parts?.length??0,p=l?.text?.length??0,m=oa(l);return(0,N.useEffect)(()=>{c.current!==e&&(c.current=e,a.current=!0,s.current=!0)},[e]),(0,N.useLayoutEffect)(()=>{let e=i.current;!s.current||!e||t.length===0||(e.scrollTop=e.scrollHeight,s.current=!1)},[e,t.length]),(0,N.useLayoutEffect)(()=>{d&&o.current!==u&&(a.current=!0);let e=i.current;!d||!e||!a.current||(e.scrollTop=e.scrollHeight)},[u,d,f,p,m]),(0,N.useEffect)(()=>{o.current=d?u:null},[u,d]),{parentRef:i,showScrollButton:n,handleScroll:(0,N.useCallback)(e=>{let t=aa(e.currentTarget);a.current=t,r(!t)},[]),scrollToBottom:(0,N.useCallback)(()=>{let e=i.current;e&&(a.current=!0,r(!1),e.scrollTo({top:e.scrollHeight,behavior:`smooth`}))},[])}}function ca(e,t){return`${la(e)||`mangostudio`}-art-${la(String(t))||String(Date.now())}.png`}function la(e){return e.trim().replace(/[^a-zA-Z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``)}function ua(e,t){let n=document.createElement(`a`);n.href=e,n.download=ca(t,Date.now()),document.body.appendChild(n),n.click(),document.body.removeChild(n)}function da({msg:e}){let{t}=L();return(0,P.jsxs)(`div`,{className:`space-y-6`,children:[e.styleParams&&e.styleParams.length>0&&(0,P.jsxs)(`div`,{className:`bg-surface-container-low p-6 rounded-xl border border-outline-variant/5`,children:[(0,P.jsxs)(`h3`,{className:`font-headline text-sm font-bold mb-4 flex items-center gap-2 text-on-surface`,children:[(0,P.jsx)(A,{className:`text-primary`,size:16}),t.chat.feed.styleParams]}),(0,P.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:e.styleParams.map(e=>(0,P.jsx)(`span`,{className:`px-3 py-1 bg-surface-container-high text-on-surface-variant text-[10px] font-bold rounded-sm uppercase tracking-wider`,children:e},e))})]}),e.text&&!e.imageUrl&&(0,P.jsx)(`div`,{className:`bg-error/10 border border-error/20 p-4 rounded-xl text-error text-sm font-body`,children:e.text}),!e.text&&!e.imageUrl&&(0,P.jsx)(`div`,{className:`bg-surface-container-lowest p-6 rounded-xl border border-outline-variant/5`,children:(0,P.jsx)(`p`,{className:`font-body text-xs text-on-surface-variant leading-relaxed`,children:t.chat.feed.neuralDiffusionPath})})]})}function fa({msg:e}){let{t}=L(),[n,r]=(0,N.useState)(!1),i=e.imageUrl;return(0,P.jsxs)(`div`,{className:`flex flex-col gap-4 w-full`,children:[e.generationTime&&(0,P.jsxs)(`div`,{className:`flex items-center gap-2 text-xs text-on-surface-variant bg-surface-container-lowest py-2 px-3 rounded-lg w-fit border border-outline-variant/10`,children:[(0,P.jsx)(A,{size:12,className:`text-primary`}),(0,P.jsx)(`span`,{children:t.chat.feed.thoughtFor.replace(`{time}`,e.generationTime)})]}),(0,P.jsxs)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-6 items-start w-full`,children:[i&&(0,P.jsx)(`div`,{className:`group relative bg-surface-container-lowest rounded-xl overflow-hidden aspect-[4/5] shadow-2xl transition-transform duration-500 hover:scale-[1.01]`,children:n?(0,P.jsxs)(`div`,{className:`w-full h-full flex flex-col items-center justify-center text-on-surface-variant/50 p-6 text-center bg-surface-container-high`,children:[(0,P.jsx)(C,{size:48,className:`mb-4 opacity-50`}),(0,P.jsx)(`p`,{className:`font-headline font-bold mb-2`,children:t.chat.feed.imageUnavailable}),(0,P.jsx)(`p`,{className:`text-xs font-body`,children:t.chat.feed.imageUnavailableHint})]}):(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(`img`,{src:i,alt:`Generated`,className:`w-full h-full object-cover grayscale-[20%] group-hover:grayscale-0 transition-[filter] duration-700`,decoding:`async`,onError:()=>r(!0)}),(0,P.jsxs)(`div`,{className:`absolute bottom-4 left-4 right-4 glass-panel rounded-xl p-3 flex justify-between items-center translate-y-12 opacity-0 group-hover:translate-y-0 group-hover:opacity-100 transition-all duration-300`,children:[(0,P.jsxs)(`div`,{className:`flex gap-2`,children:[(0,P.jsx)(`button`,{type:`button`,onClick:()=>ua(i,t.common.downloadFilenamePrefix),className:`w-9 h-9 rounded-lg flex items-center justify-center bg-surface-container-highest/40 hover:bg-primary/20 text-on-surface transition-colors`,title:t.chat.feed.download,children:(0,P.jsx)(ue,{size:16})}),(0,P.jsx)(`button`,{type:`button`,className:`w-9 h-9 rounded-lg flex items-center justify-center bg-surface-container-highest/40 hover:bg-primary/20 text-on-surface transition-colors`,title:t.chat.feed.saveToGallery,children:(0,P.jsx)(ke,{size:16})})]}),(0,P.jsx)(`button`,{type:`button`,className:`px-4 py-1.5 rounded-lg bg-primary/10 hover:bg-primary/20 text-primary text-xs font-bold transition-colors`,children:t.chat.feed.regenerate})]})]})}),(0,P.jsx)(da,{msg:e})]})]})}var pa=`modulepreload`,ma=function(e){return`/`+e},ha={},ga=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=ma(t,n),t in ha)return;ha[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:pa,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},_a=(0,N.lazy)(()=>ga(()=>import(`./MarkdownContentRenderer-ByynE5sq.js`).then(e=>({default:e.MarkdownContentRenderer})),__vite__mapDeps([0,1,2,3])));function va(e){return(0,P.jsx)(N.Suspense,{fallback:(0,P.jsx)(ya,{...e}),children:(0,P.jsx)(_a,{...e})})}function ya({content:e,className:t}){return(0,P.jsx)(`div`,{className:`markdown-content ${t??``}`,children:e})}function ba(e,t){let n=t.chat.continuation.title;switch(e){case`provider_changed`:return n.providerChanged;case`model_changed`:return n.modelChanged;case`system_prompt_changed`:return n.systemPromptChanged;case`toolset_changed`:return n.toolsetChanged;case`agent_changed`:return n.agentChanged;case`agent_runtime_changed`:return n.agentRuntimeChanged;case`cursor_expired`:return n.cursorExpired;case`cursor_invalid`:return n.cursorInvalid;case`tool_result_cursor_loss`:return n.toolResultCursorLoss;case`envelope_malformed`:return n.envelopeMalformed}}function xa(e,t){return e.replace(/{provider}/g,t.provider).replace(/{model}/g,t.model).replace(/{fromProvider}/g,t.fromProvider).replace(/{fromMode}/g,t.fromMode).replace(/{toMode}/g,t.toMode)}var Sa=e=>e===`tool_result_cursor_loss`;function Ca({provider:e,modelName:t,fromProvider:n,fromMode:r,toMode:i,reasonCode:a,recovered:o}){let{t:s}=L(),c=xa(ba(a,s),{provider:e,model:t,fromProvider:n??e,fromMode:r,toMode:i}),l=o?s.chat.continuation.recovered:s.chat.continuation.notRecovered,u=Sa(a),d=u?`text-error/80`:`text-on-surface-variant/60`,f=u?`bg-error/30`:`bg-outline-variant/20`;return(0,P.jsxs)(`div`,{className:`flex items-center gap-2 py-2 text-xs my-1 ${d}`,children:[(0,P.jsx)(`div`,{className:`flex-1 h-px ${f}`}),(0,P.jsxs)(`span`,{className:`font-medium whitespace-nowrap`,children:[c,` `,l]}),(0,P.jsx)(`div`,{className:`flex-1 h-px ${f}`})]})}var wa=`1 / 1`;function Ta({src:e,alt:t,aspectRatio:n=wa,objectFit:r=`cover`,className:i,imageClassName:a,onLoadError:o}){let[s,c]=(0,N.useState)(!1),l=r===`contain`?`object-contain`:`object-cover`;return(0,P.jsxs)(`div`,{className:`relative overflow-hidden ${i??``}`,style:{aspectRatio:n},children:[(0,P.jsx)(`img`,{src:e,alt:t,className:`absolute inset-0 w-full h-full ${l} transition-opacity duration-300 ${s?`opacity-100`:`opacity-0`} ${a??``}`,decoding:`async`,onLoad:()=>c(!0),onError:o}),!s&&(0,P.jsx)(`div`,{"aria-hidden":!0,className:`absolute inset-0 animate-pulse bg-surface-container-highest/40`})]})}function Ea({part:e}){let{t}=L(),[r,a]=(0,N.useState)(!1),[s,c]=(0,N.useState)(!1),l=e.prompt&&e.prompt.length>80?`${e.prompt.slice(0,80)}\u2026`:e.prompt,u=e.generationTime?t.chat.feed.thoughtFor.replace(`{time}`,e.generationTime):null,d=e.modelName??null;if(e.status===`completed`&&e.imageUrl&&!r){let r=e.imageUrl;return(0,P.jsxs)(`div`,{className:`bg-surface-container-lowest rounded-2xl overflow-hidden border border-outline-variant/10 shadow-sm max-w-md`,children:[(0,P.jsxs)(`button`,{type:`button`,onClick:()=>c(e=>!e),className:`w-full flex items-center gap-2.5 px-4 py-2.5 hover:bg-surface-container-high/50 transition-colors cursor-pointer`,children:[(0,P.jsx)(o,{size:14,className:`text-primary shrink-0`}),(0,P.jsx)(`span`,{className:`text-xs text-on-surface-variant/70 font-body truncate flex-1 text-left`,children:l||t.chat.feed.generatedImageAlt}),(0,P.jsx)(E,{size:14,className:`text-on-surface-variant/40 shrink-0 transition-transform duration-300 ${s?``:`rotate-180`}`})]}),(0,P.jsx)(n,{initial:!1,children:!s&&(0,P.jsxs)(i.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:`auto`},exit:{opacity:0,height:0},transition:{duration:.2,ease:`easeOut`},children:[(d||u)&&(0,P.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap px-4 pb-2`,children:[d&&(0,P.jsx)(`span`,{className:`text-[10px] text-on-surface-variant/60 font-mono bg-surface-container-high px-2 py-0.5 rounded-full`,children:d}),u&&(0,P.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-on-surface-variant/60`,children:[(0,P.jsx)(A,{size:10,className:`text-primary/50`}),u]})]}),(0,P.jsxs)(`div`,{className:`group relative`,children:[(0,P.jsx)(Ta,{src:r,alt:t.chat.feed.generatedImageAlt,className:`bg-surface-container-high`,objectFit:`contain`,onLoadError:()=>a(!0)}),(0,P.jsx)(`div`,{className:`absolute bottom-3 left-3 right-3 glass-panel rounded-xl p-2 flex justify-between items-center translate-y-12 opacity-0 group-hover:translate-y-0 group-hover:opacity-100 transition-all duration-300`,children:(0,P.jsxs)(`div`,{className:`flex gap-2`,children:[(0,P.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),ua(r,t.common.downloadFilenamePrefix)},className:`w-8 h-8 rounded-lg flex items-center justify-center bg-surface-container-highest/40 hover:bg-primary/20 text-on-surface transition-colors`,title:t.chat.feed.download,children:(0,P.jsx)(ue,{size:14})}),(0,P.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),ua(r,t.common.downloadFilenamePrefix)},className:`w-8 h-8 rounded-lg flex items-center justify-center bg-surface-container-highest/40 hover:bg-primary/20 text-on-surface transition-colors`,title:t.chat.feed.saveToGallery,children:(0,P.jsx)(ke,{size:14})})]})})]})]},`image-content`)})]})}return e.status===`completed`&&r?(0,P.jsxs)(`div`,{className:`bg-surface-container-low rounded-2xl border border-outline-variant/10 p-6 flex flex-col items-center gap-3 text-on-surface-variant/50 max-w-md`,children:[(0,P.jsx)(C,{size:32}),(0,P.jsx)(`span`,{className:`text-xs font-body`,children:t.chat.feed.imageUnavailable}),d&&(0,P.jsx)(`span`,{className:`text-[10px] text-on-surface-variant/40 font-mono`,children:d})]}):e.status===`error`?(0,P.jsxs)(`div`,{className:`bg-error/10 border border-error/20 p-4 rounded-xl flex items-start gap-3 max-w-md`,children:[(0,P.jsx)(pe,{size:16,className:`text-error shrink-0 mt-0.5`}),(0,P.jsxs)(`div`,{className:`flex flex-col gap-1 min-w-0`,children:[(0,P.jsx)(`span`,{className:`text-error text-xs font-bold`,children:t.chat.feed.imageGenerationFailed}),e.error&&(0,P.jsx)(`span`,{className:`text-error/70 text-[11px] font-body leading-relaxed`,children:e.error}),(d||u)&&(0,P.jsx)(`span`,{className:`text-error/40 text-[10px] font-mono mt-0.5`,children:[d,u].filter(Boolean).join(` · `)})]})]}):(0,P.jsxs)(`div`,{className:`bg-surface-container-lowest border border-outline-variant/10 rounded-2xl p-5 flex flex-col gap-3 max-w-md animate-pulse`,children:[(0,P.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,P.jsx)(`div`,{className:`w-10 h-10 rounded-xl bg-surface-container-high flex items-center justify-center shrink-0`,children:(0,P.jsx)(o,{size:20,className:`text-primary/50 shrink-0`})}),(0,P.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,P.jsx)(`span`,{className:`text-xs font-medium text-on-surface`,children:d?t.chat.feed.modelStatus.replace(`{status}`,t.chat.feed.statusGenerating).replace(`{model}`,()=>d):t.chat.feed.generatingImage}),(0,P.jsx)(`span`,{className:`text-[10px] text-on-surface-variant/50 font-body`,children:e.prompt})]})]}),(0,P.jsx)(`div`,{className:`aspect-square bg-surface-container-high rounded-xl`}),(0,P.jsx)(`div`,{className:`h-1 w-full bg-surface-container-high rounded-full overflow-hidden`,children:(0,P.jsx)(`div`,{className:`h-full bg-primary w-1/3 rounded-full animate-[slide_1s_ease-in-out_infinite_alternate]`})})]})}function Da(e,t,n){switch(e){case`cursor_lost`:return{label:n.chat.cursorLost.replace(`{detail}`,t??``),severity:`info`};case`tool_loop_exhausted`:return{label:t?`${n.chat.toolLoopExhausted} — ${t}`:n.chat.toolLoopExhausted,severity:`error`};case`chat_compacted`:return{label:n.chat.systemEvents.chatCompacted,severity:`info`};case`summary_handoff`:return{label:n.chat.systemEvents.summaryHandoff,severity:`info`};case`cursor_internal_tool_call`:return{label:n.chat.systemEvents.cursorInternalToolCall.replace(`{tool}`,t??``),severity:`info`};default:return{label:t??e,severity:`info`}}}function Oa({event:e,detail:t}){let{t:n}=L(),{label:r,severity:i}=Da(e,t,n),a=i===`error`?`text-error/80`:`text-on-surface-variant/60`,o=i===`error`?`bg-error/30`:`bg-outline-variant/20`;return(0,P.jsxs)(`div`,{className:`flex items-center gap-2 py-2 text-xs my-1 ${a}`,children:[(0,P.jsx)(`div`,{className:`flex-1 h-px ${o}`}),(0,P.jsx)(`span`,{className:`font-medium whitespace-nowrap`,children:r}),(0,P.jsx)(`div`,{className:`flex-1 h-px ${o}`})]})}var ka=new Map;function Aa(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=24}function ja({messageId:e,text:t,isStreaming:r}){let{t:a}=L(),o=(0,N.useRef)(ka.get(e)??{expanded:r,scrollTop:0,shouldAutoFollow:r}),[s,c]=(0,N.useState)(o.current.expanded),l=(0,N.useRef)(null),u=(0,N.useRef)(o.current),d=(0,N.useRef)(r),f=(0,N.useCallback)(t=>{u.current={...u.current,...t},ka.set(e,u.current)},[e]);return(0,N.useEffect)(()=>{!d.current&&r&&(c(!0),f({expanded:!0,shouldAutoFollow:!0})),d.current&&!r&&(c(!1),f({expanded:!1,shouldAutoFollow:!1})),d.current=r},[r,f]),(0,N.useLayoutEffect)(()=>{if(!s||!l.current)return;let e=l.current,t=Math.max(0,e.scrollHeight-e.clientHeight);if(r&&u.current.shouldAutoFollow){e.scrollTop=t,f({scrollTop:e.scrollTop});return}e.scrollTop=Math.min(u.current.scrollTop,t)},[s,r,t,f]),(0,P.jsxs)(`div`,{className:`mb-3`,children:[(0,P.jsxs)(`button`,{type:`button`,onClick:()=>{let e=!s;c(e),f({expanded:e})},className:`glass-surface flex items-center gap-2 text-xs text-on-surface-variant/70
25
+ py-1.5 px-3 rounded-full w-fit border border-outline-variant/20
26
+ hover:border-outline-variant/40 hover:text-on-surface-variant
27
+ transition-all duration-200 cursor-pointer`,children:[(0,P.jsx)(Re,{size:11,className:`text-primary/70`}),(0,P.jsx)(`span`,{className:`tracking-wide`,children:r?a.thinking.streaming:a.thinking.label}),(0,P.jsx)(E,{size:11,className:`transition-transform duration-300 text-primary/50 ${s?`rotate-180`:``}`})]}),(0,P.jsx)(n,{initial:!1,children:s&&(0,P.jsx)(i.div,{initial:{opacity:0,height:0,y:-4},animate:{opacity:1,height:`auto`,y:0},exit:{opacity:0,height:0,y:-6},transition:{duration:.22,ease:`easeOut`},className:`glass-surface-subtle mt-1.5 rounded-xl border border-outline-variant/15 overflow-hidden`,children:(0,P.jsx)(`div`,{ref:l,onScroll:e=>{let t=e.currentTarget;f({scrollTop:t.scrollTop,shouldAutoFollow:r?Aa(t):u.current.shouldAutoFollow})},className:`p-4 max-h-48 sm:max-h-72 md:max-h-96 overflow-y-auto app-scrollbar`,children:(0,P.jsxs)(`div`,{className:`text-xs text-on-surface-variant/60 leading-relaxed markdown-content--thinking`,children:[(0,P.jsx)(va,{content:t,isStreaming:r,copyCodeLabel:a.chat.copyCode,codeCopiedLabel:a.chat.codeCopied}),r&&(0,P.jsx)(`span`,{className:`inline-block w-0.5 h-[1em] bg-primary/40 ml-0.5 align-middle animate-blink`})]})})},`thinking-body`)})]})}function Ma({toolName:e,className:t}){switch(e){case`list_directory`:return(0,P.jsx)(re,{size:11,className:t});case`read_file`:return(0,P.jsx)(f,{size:11,className:t});case`write_file`:return(0,P.jsx)(x,{size:11,className:t});case`generate_image`:return(0,P.jsx)(Ae,{size:11,className:t});case`get_current_datetime`:return(0,P.jsx)(b,{size:11,className:t});case`bash`:case`zsh`:case`powershell`:return(0,P.jsx)(be,{size:11,className:t});case`grep`:return(0,P.jsx)(Fe,{size:11,className:t});case`glob`:return(0,P.jsx)(_,{size:11,className:t});default:return(0,P.jsx)(Oe,{size:11,className:t})}}function Na(e){if(typeof e!=`string`||e.trim().length===0)return null;let t=e.trim(),n=t.match(/^\/home\/[^/]+/);return n&&(t=`~${t.slice(n[0].length)}`),t}function Pa(e,t){switch(e){case`list_directory`:case`read_file`:case`write_file`:return Na(t.path);case`bash`:case`zsh`:case`powershell`:return typeof t.command==`string`&&t.command.trim().length>0?t.command.trim():null;case`grep`:case`glob`:return typeof t.pattern==`string`&&t.pattern.trim().length>0?t.pattern.trim():null;default:return null}}function Fa({name:e,args:t,result:r,isError:a,isPending:o}){let{t:s}=L(),[c,l]=(0,N.useState)(!1),u=s.tools.labels?.[e]??e,d=Pa(e,t),f=null;if(r)try{f=JSON.parse(r)}catch{f=r}return(0,P.jsxs)(`div`,{className:`mb-3`,children:[(0,P.jsxs)(`button`,{type:`button`,onClick:()=>l(e=>!e),className:`glass-surface flex items-center gap-2 text-xs py-1.5 px-3 rounded-full w-fit max-w-full border
28
+ transition-all duration-200 cursor-pointer ${a?`border-error/30 text-error`:o?`border-primary/30 text-primary`:`border-success/25 text-success`}`,children:[o?(0,P.jsx)(Ma,{toolName:e,className:`animate-pulse shrink-0`}):a?(0,P.jsx)(pe,{size:11,className:`shrink-0`}):(0,P.jsx)(y,{size:11,className:`shrink-0`}),(0,P.jsx)(`span`,{className:`tracking-wide shrink-0`,children:u}),d&&(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(ve,{size:9,className:`text-on-surface-variant/40 shrink-0`}),(0,P.jsx)(`span`,{className:`font-mono text-on-surface-variant/60 truncate max-w-[160px] sm:max-w-[260px] md:max-w-[380px]`,children:d})]}),(0,P.jsx)(E,{size:11,className:`transition-transform duration-300 opacity-50 shrink-0 ${c?`rotate-180`:``}`})]}),(0,P.jsx)(n,{initial:!1,children:c&&(0,P.jsx)(i.div,{initial:{opacity:0,height:0,y:-4},animate:{opacity:1,height:`auto`,y:0},exit:{opacity:0,height:0,y:-6},transition:{duration:.2,ease:`easeOut`},className:`glass-surface-subtle mt-1.5 rounded-xl border border-outline-variant/15 overflow-hidden`,children:(0,P.jsxs)(`div`,{className:`p-4 space-y-3 text-xs font-mono max-h-48 sm:max-h-72 md:max-h-96 overflow-y-auto app-scrollbar`,children:[Object.keys(t).length>0&&(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`p`,{className:`text-on-surface-variant/50 uppercase tracking-wider text-[10px] mb-1`,children:s.tools.argsLabel}),(0,P.jsx)(`pre`,{className:`text-on-surface-variant/70 whitespace-pre-wrap leading-relaxed`,children:JSON.stringify(t,null,2)})]}),f!==null&&(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`p`,{className:`uppercase tracking-wider text-[10px] mb-1 ${a?`text-error/50`:`text-on-surface-variant/50`}`,children:a?s.tools.errorLabel:s.tools.resultLabel}),(0,P.jsx)(`pre`,{className:`whitespace-pre-wrap leading-relaxed ${a?`text-error/80`:`text-on-surface-variant/70`}`,children:typeof f==`string`?f:JSON.stringify(f,null,2)})]})]})},`tool-body`)})]})}function Ia({calls:e}){let{t}=L(),[r,a]=(0,N.useState)(!1),o=e[0].name,s=t.tools.labels?.[o]??o,c=Pa(o,e[0].args),l=e.length-1,u=t.tools.moreCount.replace(`{count}`,String(l)),d=e.some(e=>e.isPending),f=e.some(e=>e.isError);return(0,P.jsxs)(`div`,{className:`mb-3`,children:[(0,P.jsxs)(`button`,{type:`button`,onClick:()=>a(e=>!e),className:`glass-surface flex items-center gap-2 text-xs py-1.5 px-3 rounded-full w-fit max-w-full border
29
+ transition-all duration-200 cursor-pointer ${f?`border-error/30 text-error`:d?`border-primary/30 text-primary`:`border-success/25 text-success`}`,children:[d?(0,P.jsx)(Ma,{toolName:o,className:`animate-pulse shrink-0`}):f?(0,P.jsx)(pe,{size:11,className:`shrink-0`}):(0,P.jsx)(y,{size:11,className:`shrink-0`}),(0,P.jsx)(`span`,{className:`tracking-wide shrink-0`,children:s}),c&&(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(ve,{size:9,className:`text-on-surface-variant/40 shrink-0`}),(0,P.jsx)(`span`,{className:`font-mono text-on-surface-variant/60 truncate max-w-[120px] sm:max-w-[200px] md:max-w-[300px]`,children:c})]}),l>0&&(0,P.jsx)(`span`,{className:`rounded-full bg-surface-container-high px-1.5 py-0.5 text-[10px] text-on-surface-variant/70 shrink-0`,children:u}),(0,P.jsx)(E,{size:11,className:`transition-transform duration-300 opacity-50 shrink-0 ${r?`rotate-180`:``}`})]}),(0,P.jsx)(n,{initial:!1,children:r&&(0,P.jsx)(i.div,{initial:{opacity:0,height:0,y:-4},animate:{opacity:1,height:`auto`,y:0},exit:{opacity:0,height:0,y:-6},transition:{duration:.2,ease:`easeOut`},className:`mt-1.5 ml-2 border-l border-outline-variant/15 pl-3`,children:e.map(e=>(0,P.jsx)(Fa,{name:e.name,args:e.args,result:e.result,isError:e.isError,isPending:e.isPending},e.toolCallId))},`group-body`)})]})}var La=new Set([`read_file`,`write_file`,`list_directory`,`glob`,`grep`]);function Ra(e,t){let n=new Map,r=new Set;for(let i=0;i<e.length;i++){let a=e[i];if(a.type!==`tool_call`||r.has(i)||!La.has(a.name))continue;let o=za(e,i,a.name);if(!(o.length<2)){n.set(i,o.map(n=>Ba(e,n,t)));for(let e=1;e<o.length;e++)r.add(o[e])}}return{groups:n,consumed:r}}function za(e,t,n){let r=[t];for(let i=t+1;i<e.length;i++){let t=e[i];if(t.type!==`tool_result`){if(t.type===`tool_call`&&t.name===n){r.push(i);continue}break}}return r}function Ba(e,t,n){let r=e[t];if(r.type!==`tool_call`)throw Error(`Expected tool_call at index ${t}`);let i=e.find(e=>e.type===`tool_result`&&e.toolCallId===r.toolCallId);return{toolCallId:r.toolCallId,name:r.name,args:r.args,result:i?.content??null,isError:i?.isError,isPending:n&&!i}}function Va({parts:e,messageId:t,isStreaming:n}){let{t:r}=L(),{groups:i,consumed:a}=(0,N.useMemo)(()=>Ra(e,n),[e,n]);return(0,P.jsx)(P.Fragment,{children:e.map((o,s)=>{switch(o.type){case`thinking`:{let r=`${t}-thinking-${s}`,i=n&&!e.slice(s+1).some(e=>e.type===`thinking`);return(0,P.jsx)(ja,{messageId:r,text:o.text,isStreaming:i},r)}case`tool_call`:{if(a.has(s))return null;let t=i.get(s);if(t)return(0,P.jsx)(Ia,{calls:t},o.toolCallId);let r=e.find(e=>e.type===`tool_result`&&e.toolCallId===o.toolCallId);return(0,P.jsx)(Fa,{name:o.name,args:o.args,result:r?.content??null,isError:r?.isError,isPending:n&&!r},o.toolCallId)}case`tool_result`:return null;case`generated_image`:return(0,P.jsx)(Ea,{part:o},o.imageId);case`subagent_trace`:return(0,P.jsx)(Ha,{part:o},`${t}-subagent-${s}`);case`text`:return(0,P.jsxs)(`div`,{className:`bg-surface-container-low p-5 rounded-2xl border border-outline-variant/10 font-body text-sm leading-relaxed text-on-surface max-w-2xl`,children:[(0,P.jsx)(va,{content:o.text,isStreaming:n,copyCodeLabel:r.chat.copyCode,codeCopiedLabel:r.chat.codeCopied}),n&&s===e.length-1&&(0,P.jsx)(`span`,{className:`inline-block w-0.5 h-[1em] bg-primary ml-0.5 align-middle animate-blink`})]},`${t}-text-${s}`);case`system_event`:return(0,P.jsx)(Oa,{event:o.event,detail:o.detail},`${t}-se-${s}`);case`continuation_transition`:return(0,P.jsx)(Ca,{provider:o.provider,modelName:o.modelName,fromProvider:o.fromProvider,fromMode:o.fromMode,toMode:o.toMode,reasonCode:o.reasonCode,recovered:o.recovered},`${t}-ct-${s}`);case`error`:return(0,P.jsx)(`div`,{className:`bg-error/10 border border-error/20 p-4 rounded-xl text-error text-sm font-body`,children:o.text},`${t}-error-${s}`);default:return null}})})}function Ha({part:e}){let{t}=L(),[n,r]=(0,N.useState)(!1),i=t.chat.feed,a=Wa(e.status,i),o=e.toolCallCount>0?i.subagentTools.replace(`{count}`,String(e.toolCallCount)):i.subagentNoTools;return(0,P.jsxs)(`div`,{className:`max-w-2xl rounded-2xl border border-outline-variant/15 bg-surface-container-low text-sm text-on-surface`,children:[(0,P.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),className:`flex w-full items-start gap-3 p-4 text-left`,children:[(0,P.jsx)(`span`,{className:`mt-0.5 text-on-surface-variant`,children:n?(0,P.jsx)(E,{size:16}):(0,P.jsx)(he,{size:16})}),(0,P.jsxs)(`span`,{className:`min-w-0 flex-1 space-y-1`,children:[(0,P.jsxs)(`span`,{className:`flex flex-wrap items-center gap-2`,children:[(0,P.jsx)(`span`,{className:`font-semibold text-on-surface`,children:e.agentName}),(0,P.jsx)(`span`,{className:`rounded-full bg-surface-container-high px-2 py-0.5 text-xs text-on-surface-variant`,children:i.subagentTrace}),(0,P.jsx)(`span`,{className:`rounded-full bg-surface-container-high px-2 py-0.5 text-xs text-on-surface-variant`,children:a}),(0,P.jsx)(`span`,{className:`rounded-full bg-surface-container-high px-2 py-0.5 text-xs text-on-surface-variant`,children:o})]}),(0,P.jsx)(`span`,{className:`block truncate text-on-surface-variant/80`,children:e.lastMessage??e.summary})]})]}),n&&(0,P.jsxs)(`div`,{className:`space-y-4 border-t border-outline-variant/10 p-4`,children:[e.events?.length?(0,P.jsxs)(`div`,{className:`space-y-2`,children:[(0,P.jsx)(`h4`,{className:`text-xs font-bold uppercase tracking-widest text-on-surface-variant/80`,children:i.subagentLifecycle}),(0,P.jsx)(`div`,{className:`space-y-1.5`,children:e.events.map((t,n)=>(0,P.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-xl bg-surface-container-high px-3 py-2 text-xs text-on-surface-variant`,children:[(0,P.jsx)(`span`,{children:Ga(t,i)}),t.attempt?(0,P.jsxs)(`span`,{className:`rounded-full bg-surface-container-lowest px-2 py-0.5 font-medium`,children:[`#`,t.attempt]}):null]},`${e.toolCallId}-event-${n}`))})]}):null,e.lastMessage?(0,P.jsx)(Ua,{title:i.subagentLastMessage,body:e.lastMessage}):null,e.messages.length>0?(0,P.jsxs)(`div`,{className:`space-y-2`,children:[(0,P.jsx)(`h4`,{className:`text-xs font-bold uppercase tracking-widest text-on-surface-variant/80`,children:i.subagentMessages}),(0,P.jsx)(`div`,{className:`space-y-2`,children:e.messages.map((n,r)=>(0,P.jsx)(`div`,{className:`rounded-xl bg-surface-container-high px-3 py-2 text-on-surface-variant`,children:(0,P.jsx)(va,{content:n.text,copyCodeLabel:t.chat.copyCode,codeCopiedLabel:t.chat.codeCopied})},`${e.toolCallId}-message-${r}`))})]}):null,e.tools.length>0?(0,P.jsxs)(`div`,{className:`space-y-2`,children:[(0,P.jsx)(`h4`,{className:`text-xs font-bold uppercase tracking-widest text-on-surface-variant/80`,children:i.subagentToolCalls}),(0,P.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:e.tools.map(e=>(0,P.jsx)(`span`,{className:`rounded-full bg-surface-container-high px-2.5 py-1 text-xs text-on-surface-variant`,children:e.name},e.callId))})]}):null,e.error?(0,P.jsx)(Ua,{title:i.subagentStatusFailed,body:e.error}):null]})]})}function Ua({title:e,body:t}){let{t:n}=L();return(0,P.jsxs)(`div`,{className:`space-y-2`,children:[(0,P.jsx)(`h4`,{className:`text-xs font-bold uppercase tracking-widest text-on-surface-variant/80`,children:e}),(0,P.jsx)(`div`,{className:`rounded-xl bg-surface-container-high px-3 py-2 text-on-surface-variant`,children:(0,P.jsx)(va,{content:t,copyCodeLabel:n.chat.copyCode,codeCopiedLabel:n.chat.codeCopied})})]})}function Wa(e,t){return e===`completed`?t.subagentStatusCompleted:e===`aborted`?t.subagentStatusAborted:e===`timeout`?t.subagentStatusTimeout:e===`running`?t.statusGenerating:t.subagentStatusFailed}function Ga(e,t){return e.event===`delegation_started`?t.subagentLifecycleDelegationStarted:e.event===`delegation_completed`?t.subagentLifecycleDelegationCompleted:e.event===`delegation_failed`?t.subagentLifecycleDelegationFailed:e.event===`response_recovered`?t.subagentLifecycleRecovered:e.event===`response_timeout`?t.subagentLifecycleTimeout:e.event===`response_fallback`?t.subagentLifecycleFallback:t.subagentLifecycleAttempt.replace(`{attempt}`,String(e.attempt??1))}function Ka(e){let t=[],n=``,r=``,i=()=>{n&&=(t.push({type:`thinking`,text:n}),``),r&&=(t.push({type:`text`,text:r}),``)};for(let a of e){if(a.type===`thinking`){n+=a.text;continue}if(a.type===`text`){r+=a.text;continue}i(),t.push(a)}return i(),t}function qa(e){return Ka(e.parts??(e.text?[{type:`text`,text:e.text}]:[]))}function Ja(e){return e.interactionMode===`image`||!e.interactionMode&&!!e.imageUrl}function Ya(e){return qa(e).filter(e=>e.type===`text`).map(e=>e.text).join(`
30
+
31
+ `)}function Xa({msg:e,isImageTurn:t}){let{t:n}=L(),r=qa(e),i=r.some(e=>e.type===`thinking`||e.type===`text`||e.type===`tool_call`);return t||!i?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(`span`,{className:`text-sm font-medium text-on-surface animate-pulse`,children:t?n.chat.feed.generatingImage:n.thinking.streaming}),t?(0,P.jsx)(`div`,{className:`h-1 w-24 bg-surface-container-highest rounded-full overflow-hidden`,children:(0,P.jsx)(`div`,{className:`h-full bg-primary w-1/2 animate-[slide_1s_ease-in-out_infinite_alternate]`})}):(0,P.jsxs)(`div`,{className:`skeleton-pulse mt-1`,children:[(0,P.jsx)(`div`,{className:`skeleton-line`}),(0,P.jsx)(`div`,{className:`skeleton-line`}),(0,P.jsx)(`div`,{className:`skeleton-line`})]})]}):(0,P.jsx)(Va,{parts:r,messageId:e.id,isStreaming:!0})}function Za({msg:e}){let{t}=L(),n=qa(e),r=n.some(e=>e.type===`text`||e.type===`tool_call`);return(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(Va,{parts:n,messageId:e.id,isStreaming:!1}),!r&&(0,P.jsx)(`div`,{className:`bg-surface-container-low p-5 rounded-2xl border border-outline-variant/10 font-body text-sm leading-relaxed text-on-surface max-w-2xl`,children:(0,P.jsx)(`span`,{className:`text-on-surface-variant/50 italic`,children:t.chat.feed.noResponse})})]})}var Qa=2e3;function $a({msg:e,label:t,copiedLabel:n}){let[r,i]=(0,N.useState)(!1),o=async()=>{let t=Ya(e);if(t)try{await navigator.clipboard.writeText(t),i(!0),setTimeout(()=>i(!1),Qa)}catch{}};return(0,P.jsx)(`button`,{type:`button`,onClick:()=>void o(),className:`opacity-0 group-hover:opacity-70 hover:!opacity-100 transition-opacity duration-200 text-on-surface-variant/60 hover:text-on-surface-variant cursor-pointer`,title:r?n:t,children:r?(0,P.jsx)(a,{size:14,className:`text-success`}):(0,P.jsx)(fe,{size:14})})}function eo(e,t,n){return e.isGenerating?t?n.statusGenerating:n.statusThinking:t?n.statusGenerated:n.statusReplied}function to({msg:e,isImageTurn:t}){let{t:n}=L(),r=n.chat.feed,i=e.modelName?r.modelStatus.replace(`{status}`,eo(e,t,r)).replace(`{model}`,()=>e.modelName??``):r.modelFallback;return(0,P.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,P.jsx)(`div`,{className:`w-6 h-6 rounded-full bg-primary-container flex items-center justify-center`,children:(0,P.jsx)(A,{size:14,className:`text-on-primary`})}),(0,P.jsx)(`span`,{className:`text-xs font-bold font-headline tracking-wide uppercase text-primary`,children:i}),!e.isGenerating&&!t&&(0,P.jsx)($a,{msg:e,label:n.chat.copyMessage,copiedLabel:n.chat.messageCopied}),!e.isGenerating&&(0,P.jsx)(`span`,{className:`opacity-0 group-hover:opacity-100 transition-opacity duration-200 text-[10px] text-on-surface-variant/50 font-label ml-auto`,children:at(e.timestamp,`h:mm a`)})]})}function no({msg:e,isImageTurn:t}){let{t:n}=L();return e.isGenerating?(0,P.jsx)(`div`,{className:`flex flex-col gap-3 py-4 pl-9`,children:(0,P.jsx)(Xa,{msg:e,isImageTurn:t})}):t?(0,P.jsx)(fa,{msg:e}):(0,P.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[e.generationTime&&(0,P.jsxs)(`div`,{className:`flex items-center gap-2 text-xs text-on-surface-variant bg-surface-container-lowest py-2 px-3 rounded-lg w-fit border border-outline-variant/10`,children:[(0,P.jsx)(A,{size:12,className:`text-primary`}),(0,P.jsx)(`span`,{children:n.chat.feed.respondedIn.replace(`{time}`,e.generationTime)})]}),(0,P.jsx)(Za,{msg:e})]})}function ro({msg:e,isImageTurn:t}){return(0,P.jsxs)(`div`,{className:`group flex flex-col gap-4 w-full`,children:[(0,P.jsx)(to,{msg:e,isImageTurn:t}),(0,P.jsx)(no,{msg:e,isImageTurn:t})]})}function io({msg:e,isImageTurn:t}){let{t:n}=L(),[r,i]=(0,N.useState)(!1);return(0,P.jsxs)(P.Fragment,{children:[e.referenceImage&&(0,P.jsx)(`div`,{className:`mb-2 max-w-[200px] rounded-xl overflow-hidden border border-outline-variant/20 shadow-sm`,children:r?(0,P.jsxs)(`div`,{className:`w-full aspect-square bg-surface-container-high flex flex-col items-center justify-center text-on-surface-variant/50 p-4 text-center`,children:[(0,P.jsx)(C,{size:24,className:`mb-2`}),(0,P.jsx)(`span`,{className:`text-[10px] font-label`,children:n.chat.feed.imageUnavailable})]}):(0,P.jsx)(Ta,{src:e.referenceImage,alt:`Reference`,onLoadError:()=>i(!0)})}),(0,P.jsxs)(`div`,{className:`flex flex-col items-end gap-1.5`,children:[(0,P.jsx)(`div`,{className:`px-5 py-3 rounded-2xl bg-surface-container-low text-on-surface border border-outline-variant/10 font-body chat-message-body leading-relaxed`,children:(0,P.jsx)(va,{content:e.text,copyCodeLabel:n.chat.copyCode,codeCopiedLabel:n.chat.codeCopied})}),t&&(0,P.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] font-bold text-primary/70 font-label px-1`,children:[(0,P.jsx)(o,{size:11}),n.chat.feed.createImageBadge]})]}),(0,P.jsx)(`span`,{className:`text-[10px] text-on-surface-variant font-label px-2`,children:at(e.timestamp,`h:mm a`)})]})}function ao({message:e,index:t,start:n,measureRef:r}){let a=Ja(e),o=e.role===`user`;return(0,P.jsx)(`div`,{ref:r,"data-index":t,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${n}px)`,paddingBottom:`var(--chat-message-gap)`,willChange:`transform`,contain:`layout style paint`},children:(0,P.jsx)(i.div,{initial:!1,animate:{opacity:1,y:0},className:`flex flex-col gap-2 ${o?`items-end ml-auto max-w-[92%] sm:max-w-[85%] md:max-w-[80%]`:`items-start mr-auto max-w-full`}`,children:o?(0,P.jsx)(io,{msg:e,isImageTurn:a}):(0,P.jsx)(ro,{msg:e,isImageTurn:a})})})}var oo=(0,N.memo)(ao),so=150,co=5;function lo(){let{t:e}=L();return(0,P.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full text-on-surface-variant/50 px-4`,children:[(0,P.jsx)(A,{size:48,className:`mb-4 opacity-50`}),(0,P.jsx)(`p`,{className:`text-lg font-headline text-center`,children:e.chat.feed.emptyTitle}),(0,P.jsx)(`p`,{className:`text-xs mt-2 text-on-surface-variant/40 text-center`,children:e.chat.feed.emptySubtitle})]})}function uo({chatId:e,messages:t}){let{t:r}=L(),{parentRef:a,showScrollButton:o,handleScroll:s,scrollToBottom:c}=sa(e,t),l=(0,N.useCallback)(()=>a.current,[a]),u=(0,N.useCallback)(e=>t[e]?.id??e,[t]),d=(0,N.useCallback)(()=>so,[]),f=qe({count:t.length,getScrollElement:l,getItemKey:u,estimateSize:d,overscan:co});return(0,P.jsxs)(`section`,{ref:a,onScroll:s,className:`flex-1 min-h-0 overflow-y-auto px-3 sm:px-4 md:px-6 py-4 sm:py-6 md:py-8 hide-scrollbar max-w-5xl mx-auto w-full`,children:[t.length===0&&(0,P.jsx)(lo,{}),t.length>0&&(0,P.jsx)(`div`,{style:{height:`${f.getTotalSize()}px`,width:`100%`,position:`relative`},children:f.getVirtualItems().map(e=>(0,P.jsx)(oo,{message:t[e.index],index:e.index,start:e.start,measureRef:f.measureElement},e.key))}),(0,P.jsx)(n,{children:o&&t.length>0&&(0,P.jsxs)(i.button,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{duration:.2},type:`button`,onClick:c,className:`glass-elevated sticky bottom-4 left-1/2 -translate-x-1/2 z-10 flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium text-on-surface-variant border border-outline-variant/30 cursor-pointer hover:border-outline-variant/50 hover:text-on-surface transition-colors duration-200`,title:r.chat.scrollToBottom,children:[(0,P.jsx)(Ke,{size:13}),r.chat.scrollToBottom]},`scroll-to-bottom`)})]})}function fo({chatId:e,messages:t,status:n,userName:r,onSubmit:i}){return n===`pending`&&e?(0,P.jsx)(po,{}):t.length===0?(0,P.jsx)(mo,{userName:r,onSubmit:i}):(0,P.jsx)(uo,{chatId:e,messages:t})}function po(){return(0,P.jsx)(`div`,{className:`flex-1 flex justify-center items-center`,children:(0,P.jsx)(u,{className:`w-8 h-8 animate-spin text-primary`})})}function mo({userName:e,onSubmit:t}){let{t:n}=L(),r=[{text:n.chat.suggestion1,icon:(0,P.jsx)(Ze,{size:14})},{text:n.chat.suggestion2,icon:(0,P.jsx)(m,{size:14})},{text:n.chat.suggestion3,icon:(0,P.jsx)(Je,{size:14})},{text:n.chat.suggestion4,icon:(0,P.jsx)(o,{size:14})}];return(0,P.jsxs)(`div`,{className:`flex-1 flex flex-col items-center justify-center gap-4 sm:gap-6 select-none px-3 sm:px-6`,children:[(0,P.jsxs)(`div`,{className:`text-center`,children:[(0,P.jsx)(A,{size:36,className:`mx-auto mb-3 text-primary/40`}),(0,P.jsx)(`h2`,{className:`text-base sm:text-lg font-headline font-bold text-on-surface/80 px-2`,children:n.chat.emptyGreeting.replace(`{name}`,e)}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/50 mt-1 px-2`,children:n.chat.emptySubtitle})]}),(0,P.jsx)(`div`,{className:`flex flex-wrap justify-center gap-2 max-w-lg px-2`,children:r.map(e=>(0,P.jsxs)(`button`,{type:`button`,onClick:()=>t(e.text),className:`glass-surface flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-body text-on-surface-variant border border-outline-variant/20 hover:border-outline-variant/40 hover:text-on-surface transition-colors duration-200 cursor-pointer`,children:[e.icon,e.text]},e.text))})]})}function ho({title:e,detail:t,keepHistoryNote:n,compactLabel:r,newChatLabel:i,continueLabel:a,pendingLabel:o,isPending:s,onCompact:c,onStartSummarizedChat:l,onContinue:u}){return(0,P.jsx)(z,{variant:`solid`,className:`border-warning/20 bg-warning/8 p-4`,children:(0,P.jsxs)(`div`,{className:`flex flex-col gap-4 md:flex-row md:items-start md:justify-between`,children:[(0,P.jsxs)(`div`,{className:`space-y-2`,children:[(0,P.jsxs)(`div`,{className:`flex items-center gap-2 text-warning`,children:[(0,P.jsx)(ze,{size:16}),(0,P.jsx)(`span`,{className:`text-sm font-bold`,children:e})]}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/80`,children:t}),(0,P.jsx)(`p`,{className:`text-xs text-on-surface-variant/60`,children:n})]}),(0,P.jsxs)(`div`,{className:`flex flex-wrap gap-2 md:justify-end`,children:[(0,P.jsxs)(R,{variant:`primary`,size:`sm`,disabled:s,loading:s,onClick:c,children:[(0,P.jsx)(A,{size:14}),s?o:r]}),(0,P.jsxs)(R,{variant:`secondary`,size:`sm`,disabled:s,onClick:l,children:[(0,P.jsx)(f,{size:14}),i]}),(0,P.jsx)(R,{variant:`ghost`,size:`sm`,disabled:s,onClick:u,children:a})]})]})})}function go({notice:e}){let{t}=L();return(0,P.jsx)(`div`,{className:`px-6 py-2 text-xs text-on-surface-variant bg-surface-container-low border-t border-outline-variant/10`,children:(0,P.jsx)(`div`,{className:`mx-auto max-w-4xl`,children:(0,P.jsxs)(`div`,{className:`relative w-full pl-4 text-center`,role:`status`,"aria-live":`polite`,children:[(0,P.jsx)(`span`,{"aria-hidden":`true`,className:`absolute left-0 top-1/2 -translate-y-1/2 text-on-surface-variant/60`,children:`・`}),e.to===`replay`?t.chat.fallback.toReplay:t.chat.fallback.generic.replace(`{from}`,e.from).replace(`{to}`,e.to)]})})})}function _o({warningMessage:e,isPending:t,onCompact:n,onStartSummarizedChat:r,onContinue:i}){let{t:a}=L();return(0,P.jsx)(`div`,{className:`px-6 pt-4`,children:(0,P.jsx)(`div`,{className:`mx-auto max-w-4xl`,children:(0,P.jsx)(ho,{title:a.chat.context.label,detail:e,keepHistoryNote:a.chat.context.keepHistory,compactLabel:a.chat.context.compactAction,newChatLabel:a.chat.context.newChatAction,continueLabel:a.chat.context.continueAction,pendingLabel:a.chat.context.compactPending,isPending:t,onCompact:n,onStartSummarizedChat:r,onContinue:i})})})}function vo({enabled:e,effort:t,visible:r,onToggle:o,onEffortChange:s}){let{t:c}=L(),[l,u]=(0,N.useState)(!1),d=(0,N.useRef)(null);if((0,N.useEffect)(()=>{if(!l)return;function e(e){d.current&&!d.current.contains(e.target)&&u(!1)}return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[l]),!r)return null;let f=[`low`,`medium`,`high`],p={low:c.thinking.effortLow,medium:c.thinking.effortMedium,high:c.thinking.effortHigh,xhigh:c.thinking.effortHigh,max:c.thinking.effortHigh};return(0,P.jsxs)(`div`,{className:`relative`,ref:d,children:[(0,P.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,P.jsxs)(`button`,{type:`button`,onClick:()=>o(!e),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium transition-all duration-200 ${e?`bg-primary/15 text-primary border border-primary/30`:`bg-surface-container-high text-on-surface-variant hover:bg-surface-container-highest border border-transparent`}`,children:[(0,P.jsx)(Re,{size:13}),(0,P.jsx)(`span`,{children:c.thinking.enable})]}),e&&(0,P.jsxs)(`button`,{type:`button`,onClick:()=>u(!l),className:`flex items-center gap-1 px-3 py-1.5 rounded-full bg-surface-container-high text-on-surface-variant hover:bg-surface-container-highest hover:text-on-surface transition-all duration-200 text-xs font-medium border border-outline-variant/20`,children:[(0,P.jsx)(`span`,{children:p[t]}),(0,P.jsx)(E,{size:11,className:`transition-transform duration-200 ${l?`rotate-180`:``}`})]})]}),(0,P.jsx)(n,{children:l&&(0,P.jsx)(i.div,{initial:{opacity:0,y:6,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.95},transition:{duration:.15,ease:`easeOut`},className:`dropdown-panel absolute left-0 top-full mt-3 w-40`,children:(0,P.jsx)(`div`,{className:`py-1`,children:f.map(e=>(0,P.jsxs)(`button`,{type:`button`,onClick:()=>{s(e),u(!1)},className:`w-full flex items-center justify-between px-4 py-2 text-sm hover:bg-primary/10 transition-colors group/item`,children:[(0,P.jsx)(`span`,{className:t===e?`text-primary font-medium`:`text-on-surface group-hover/item:text-primary/90`,children:p[e]}),t===e&&(0,P.jsx)(a,{size:14,className:`text-primary`})]},e))})})})]})}function yo(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(e>=1e4?0:1)}k`:String(e)}function bo({onSubmit:e,disabled:t,submitDisabled:n=!1,isGenerating:r,onStop:i,thinkingEnabled:a=!1,reasoningEffort:s=`medium`,onThinkingToggle:c,onReasoningEffortChange:l,reasoningVisible:u=!1,contextInfo:d,imageToolIntent:f=!1,onImageToolIntentChange:p,agentExecutionMode:m=`chat`,selectedAgentId:h=`default`,agents:g=[],isAgentListLoading:_=!1,onAgentExecutionModeChange:v,onSelectedAgentIdChange:y}){let{t:b}=L(),[x,S]=(0,N.useState)(``),C=g.filter(e=>e.role===`primary`||e.role===`both`);return(0,P.jsx)(`footer`,{className:`shrink-0 p-3 sm:p-4 md:p-6`,children:(0,P.jsxs)(`div`,{className:`max-w-4xl mx-auto w-full`,children:[(0,P.jsx)(`div`,{className:`flex items-center justify-between mb-2 sm:mb-3`,children:(0,P.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[v?(0,P.jsx)(`div`,{className:`flex items-center rounded-full border border-outline-variant/20 bg-surface-container-lowest p-0.5 text-[10px] sm:text-[11px] font-medium`,children:[`chat`,`agent`].map(e=>(0,P.jsx)(`button`,{type:`button`,onClick:()=>v(e),disabled:t,className:`rounded-full px-2.5 py-1 transition-colors ${m===e?`bg-primary text-on-primary shadow-sm`:`text-on-surface-variant hover:text-on-surface`}`,"aria-pressed":m===e,children:e===`chat`?b.chat.input.modeChat:b.chat.input.modeAgent},e))}):null,m===`agent`&&y?(0,P.jsx)(`label`,{className:`sr-only`,htmlFor:`chat-agent-selector`,children:b.chat.input.selectAgent}):null,m===`agent`&&y?(0,P.jsxs)(`select`,{id:`chat-agent-selector`,value:h,onChange:e=>y(e.target.value),disabled:t||_||C.length===0,className:`h-7 max-w-[11rem] rounded-full border border-outline-variant/20 bg-surface-container-lowest px-2 text-[10px] sm:text-[11px] font-medium text-on-surface-variant outline-none transition-colors hover:text-on-surface focus:border-primary/40`,"aria-label":b.chat.input.selectAgent,children:[_?(0,P.jsx)(`option`,{value:h,children:b.chat.input.agentsLoading}):null,C.map(e=>(0,P.jsx)(`option`,{value:e.id,children:e.name},e.id))]}):null,c&&l?(0,P.jsx)(vo,{enabled:a,effort:s,visible:u,onToggle:c,onEffortChange:l}):null,p&&(0,P.jsxs)(`button`,{type:`button`,onClick:()=>p(!f),disabled:t,className:`flex items-center gap-1.5 px-2 py-0.5 sm:px-2.5 sm:py-1 rounded-full text-[10px] sm:text-[11px] font-medium transition-all duration-200 shrink-0 ${f?`bg-primary text-on-primary shadow-sm`:`text-on-surface-variant hover:text-on-surface border border-outline-variant/20 hover:border-outline-variant/40`}`,title:b.chat.input.createImagesHint,children:[(0,P.jsx)(o,{size:12,className:`sm:hidden`}),(0,P.jsx)(o,{size:13,className:`hidden sm:block`}),(0,P.jsx)(`span`,{className:`hidden sm:inline`,children:b.chat.input.createImages})]}),d&&(0,P.jsxs)(`span`,{className:`flex items-center gap-1 px-2 py-0.5 sm:px-2.5 sm:py-1 rounded-full text-[10px] sm:text-[11px] font-medium tabular-nums border transition-colors shrink-0 ${d.severity===`critical`?`bg-error/15 text-error border-error/30`:d.severity===`danger`?`bg-warning/15 text-warning border-warning/30`:d.severity===`warning`?`bg-warning/10 text-warning/80 border-warning/20`:`bg-surface-container-high text-on-surface-variant border-transparent`}`,title:`~${d.estimatedInputTokens.toLocaleString()} / ${d.contextLimit.toLocaleString()} tokens · ${d.mode}`,children:[(0,P.jsx)(`span`,{className:`sm:hidden`,children:yo(d.estimatedInputTokens)}),(0,P.jsx)(`span`,{className:`hidden sm:inline`,children:`${b.chat.context.label}: ${yo(d.estimatedInputTokens)} / ${yo(d.contextLimit)}`})]})]})}),(0,P.jsxs)(`form`,{onSubmit:r=>{r.preventDefault(),!(!x.trim()||t||n)&&(e(x),S(``))},className:`bg-surface-container-lowest border border-outline-variant/10 rounded-2xl p-1.5 sm:p-2 shadow-2xl flex items-center gap-1.5 sm:gap-2 group transition-all focus-within:ring-1 focus-within:ring-primary/30`,children:[(0,P.jsx)(`input`,{type:`text`,value:x,onChange:e=>S(e.target.value),disabled:t,className:`flex-1 bg-transparent border-none focus:ring-0 text-sm font-body text-on-surface placeholder:text-on-surface-variant/40 py-2 outline-none min-w-0`,placeholder:b.chat.input.placeholder}),(0,P.jsxs)(`div`,{className:`flex items-center gap-1 pr-0.5 sm:pr-1 shrink-0`,children:[!r&&(0,P.jsxs)(`button`,{type:`button`,className:`w-9 h-9 sm:w-10 sm:h-10 flex items-center justify-center rounded-xl text-on-surface-variant hover:bg-surface-container-high transition-all`,children:[(0,P.jsx)(ye,{size:18,className:`sm:hidden`}),(0,P.jsx)(ye,{size:20,className:`hidden sm:block`})]}),r?(0,P.jsxs)(`button`,{type:`button`,onClick:i,className:`h-9 sm:h-10 px-3 sm:px-4 rounded-xl font-bold text-xs flex items-center gap-1.5 sm:gap-2 transition-all active:scale-95 bg-surface-container-high text-on-surface hover:bg-error/20 hover:text-error shrink-0`,children:[(0,P.jsx)(`span`,{className:`hidden sm:inline`,children:b.chat.input.stop}),` `,(0,P.jsx)(Ne,{size:12,className:`sm:hidden`}),(0,P.jsx)(Ne,{size:14,className:`hidden sm:block`})]}):(0,P.jsxs)(`button`,{type:`submit`,disabled:t||n||!x.trim(),className:`h-9 sm:h-10 px-3 sm:px-4 rounded-xl text-on-primary font-bold text-xs flex items-center gap-1.5 sm:gap-2 hover:brightness-110 transition-all active:scale-95 shadow-lg shadow-primary-container/20 disabled:opacity-50 shrink-0`,style:{background:`var(--gradient-primary)`},children:[(0,P.jsx)(`span`,{className:`hidden sm:inline`,children:b.chat.input.send}),` `,(0,P.jsx)(Ve,{size:14,className:`sm:hidden`}),(0,P.jsx)(Ve,{size:16,className:`hidden sm:block`})]})]})]}),(0,P.jsx)(`p`,{className:`text-center text-[10px] text-on-surface-variant/40 mt-2 sm:mt-3 font-label`,children:b.common.disclaimer})]})})}function xo({chatId:e,seedContextInfo:t}){let{data:n,status:r}=dn(e),i=n?.pages[0]?.contextInfo;return(0,N.useEffect)(()=>{e&&i&&t&&t(e,i)},[e,i,t]),{messages:(0,N.useMemo)(()=>n?.pages.flatMap(e=>e.messages)??[],[n?.pages]),status:r}}function So({chatId:e,contextInfo:t,contextSettings:n,isContextActionPending:r,onCompactCurrentChat:i,onStartSummarizedChat:a}){let{t:o}=L(),{toast:s}=F(),[c,l]=(0,N.useState)(null),u=(0,N.useRef)(null),d=(0,N.useMemo)(()=>!e||!t?null:`${e}:${t.mode}:${t.estimatedInputTokens}`,[e,t]),f=!!t&&t.estimatedUsageRatio>=n.warningThreshold,p=!!t&&t.estimatedUsageRatio>=n.dangerThreshold,m=!!t&&t.estimatedUsageRatio>=n.hardStopThreshold,h=f&&n.compactionBehavior===`ask`&&d!==null&&d!==c,g=m?o.chat.context.critical:p?o.chat.context.danger:o.chat.context.warning;return(0,N.useEffect)(()=>{!f||!d||r||u.current===d||(n.compactionBehavior===`auto_compact_current_chat`||n.compactionBehavior===`continue_with_summary_new_chat`)&&(u.current=d,(async()=>{try{n.compactionBehavior===`auto_compact_current_chat`&&(await i(),s(o.chat.context.compactedSuccess,`success`)),n.compactionBehavior===`continue_with_summary_new_chat`&&(await a(),s(o.chat.context.summarizedChatSuccess,`success`))}catch{s(n.compactionBehavior===`continue_with_summary_new_chat`?o.chat.context.summarizedChatFailed:o.chat.context.compactFailed,`error`)}})())},[n.compactionBehavior,f,r,i,a,o.chat.context.compactFailed,o.chat.context.compactedSuccess,o.chat.context.summarizedChatFailed,o.chat.context.summarizedChatSuccess,s,d]),{requiresDecision:h,warningMessage:g,handleCompactClick:async()=>{try{await i(),s(o.chat.context.compactedSuccess,`success`)}catch{s(o.chat.context.compactFailed,`error`)}},handleSummarizedChatClick:async()=>{try{await a(),s(o.chat.context.summarizedChatSuccess,`success`)}catch{s(o.chat.context.summarizedChatFailed,`error`)}},handleContinue:()=>{l(d)}}}function Co({chatId:e,onSubmit:t,disabled:n,isGenerating:r,onStop:i,thinkingEnabled:a,reasoningEffort:o,onThinkingToggle:s,onReasoningEffortChange:c,reasoningVisible:l,contextInfo:u,fallbackNotice:d,seedContextInfo:f,contextSettings:p,isContextActionPending:m,onCompactCurrentChat:h,onStartSummarizedChat:g,imageToolIntent:_,onImageToolIntentChange:v,agentExecutionMode:y=`chat`,selectedAgentId:b=`default`,agents:x=[],isAgentListLoading:S=!1,onAgentExecutionModeChange:C,onSelectedAgentIdChange:w}){let{messages:ee,status:te}=xo({chatId:e,seedContextInfo:f}),{data:ne}=ct.useSession(),re=ne?.user?.name?.split(` `)[0]??``,T=So({chatId:e,contextInfo:u,contextSettings:p,isContextActionPending:m,onCompactCurrentChat:h,onStartSummarizedChat:g});return(0,P.jsxs)(`div`,{className:`flex flex-col h-full min-h-0`,children:[(0,P.jsx)(fo,{chatId:e,messages:ee,status:te,userName:re,onSubmit:t}),d&&(0,P.jsx)(go,{notice:d}),T.requiresDecision&&(0,P.jsx)(_o,{warningMessage:T.warningMessage,isPending:m,onCompact:()=>void T.handleCompactClick(),onStartSummarizedChat:()=>void T.handleSummarizedChatClick(),onContinue:T.handleContinue}),(0,P.jsx)(bo,{onSubmit:t,disabled:n,submitDisabled:T.requiresDecision||m,isGenerating:r,onStop:i,thinkingEnabled:a,reasoningEffort:o,onThinkingToggle:s,onReasoningEffortChange:c,reasoningVisible:l,contextInfo:u,imageToolIntent:_,onImageToolIntentChange:v,agentExecutionMode:y,selectedAgentId:b,agents:x,isAgentListLoading:S,onAgentExecutionModeChange:C,onSelectedAgentIdChange:w})]})}var wo=S(`/_authenticated/`)({component:To});function To(){let e=ta(),t=e.activeModels.find(t=>t.modelId===e.activeModel)?.capabilities?.reasoning===!0;return(0,P.jsx)(Co,{chatId:e.currentChatId,onSubmit:t=>void e.handleSubmit(t),disabled:e.isGenerating,isGenerating:e.isGenerating,onStop:e.handleStop,thinkingEnabled:e.settings.thinkingEnabled,reasoningEffort:e.settings.reasoningEffort,onThinkingToggle:e.settings.setThinkingEnabled,onReasoningEffortChange:e.settings.setReasoningEffort,reasoningVisible:t,contextInfo:e.contextInfo,fallbackNotice:e.fallbackNotice,seedContextInfo:e.seedContextInfo,contextSettings:e.settings.contextSettings,isContextActionPending:e.isContextActionPending,onCompactCurrentChat:e.handleCompactCurrentChat,onStartSummarizedChat:e.handleStartSummarizedChat,imageToolIntent:e.imageToolIntent,onImageToolIntentChange:e.setImageToolIntent,agentExecutionMode:e.agentExecutionMode,selectedAgentId:e.selectedAgentId,agents:e.agents,isAgentListLoading:e.isAgentListLoading,onAgentExecutionModeChange:e.setAgentExecutionMode,onSelectedAgentIdChange:e.setSelectedAgentId})}var Eo=S(`/_authenticated/studio`)({component:Do});function Do(){let{t:e}=L();return(0,P.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-4 px-4`,children:[(0,P.jsx)(`div`,{className:`rounded-full bg-surface-container-high p-4`,children:(0,P.jsx)(o,{size:32,className:`text-primary`})}),(0,P.jsx)(`h1`,{className:`text-xl font-semibold text-on-surface`,children:e.studio.title}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant text-center max-w-sm`,children:e.studio.empty})]})}function Oo(){let{t:e}=L(),t=[{to:`/settings/general`,label:e.settings.tabs.general},{to:`/settings/connectors`,label:e.settings.tabs.connectors},{to:`/settings/providers`,label:e.settings.tabs.providers},{to:`/settings/agents`,label:e.settings.tabs.agents},{to:`/settings/prompts`,label:e.settings.tabs.prompts},{to:`/settings/appearance`,label:e.settings.tabs.appearance},{to:`/settings/context`,label:e.settings.tabs.context},{to:`/settings/tools`,label:e.settings.tabs.tools},{to:`/settings/metrics`,label:e.settings.tabs.metrics},{to:`/settings/logs`,label:e.settings.tabs.logs}];return(0,P.jsx)(`nav`,{className:`flex flex-wrap gap-1 sm:gap-0.5 border-b border-outline-variant/20 pb-0`,"aria-label":e.common.settingsNavigation,children:t.map(({to:e,label:t})=>(0,P.jsx)(et,{to:e,className:`px-3 sm:px-4 py-2.5 text-sm font-medium rounded-t-lg transition-all duration-200 text-on-surface-variant/60 hover:text-on-surface hover:bg-surface-container-high/60 whitespace-nowrap`,activeProps:{className:`px-3 sm:px-4 py-2.5 text-sm font-semibold rounded-t-lg transition-all duration-200 text-primary border-b-2 border-primary -mb-px bg-primary/5 whitespace-nowrap`},children:t},e))})}var ko=S(`/_authenticated/settings`)({component:Ao});function Ao(){let{t:e}=L();return(0,P.jsx)(`div`,{className:`h-full overflow-y-auto`,children:(0,P.jsxs)(`div`,{className:`px-4 py-6 sm:px-8 sm:py-8 lg:px-12 max-w-7xl mx-auto space-y-4 sm:space-y-6 w-full`,children:[(0,P.jsxs)(`div`,{className:`flex items-center gap-3 sm:gap-4`,children:[(0,P.jsx)(`div`,{className:`p-2.5 sm:p-3 bg-primary-container text-on-primary-container rounded-2xl`,children:(0,P.jsx)(Te,{size:24})}),(0,P.jsx)(`h1`,{className:`text-2xl sm:text-3xl font-bold font-headline text-on-background`,children:e.settings.title})]}),(0,P.jsx)(Oo,{}),(0,P.jsx)(v,{})]})})}var jo={all:[`gallery`],lists:()=>[...jo.all,`list`]},Mo=()=>Ce({queryKey:jo.lists(),queryFn:async({pageParam:e})=>{let t=e?{cursor:e,limit:`20`}:{limit:`20`},{data:n,error:r}=await H.api.messages.images.get({query:t});if(r)throw Error(V(r.value));return n},initialPageParam:null,getNextPageParam:e=>e.nextCursor});function No(){return Pe(Mo())}function Po(){let[e,t]=(0,N.useState)(null),r=(0,N.useRef)(null),{t:a}=L(),{data:o,fetchNextPage:s,hasNextPage:c,isFetchingNextPage:l,status:d}=No(),f=o?.pages.flatMap(e=>e.items)||[];return(0,N.useEffect)(()=>{let e=new IntersectionObserver(e=>{e[0].isIntersecting&&c&&!l&&s()},{threshold:.1});return r.current&&e.observe(r.current),()=>e.disconnect()},[c,l,s]),(0,P.jsxs)(`div`,{className:`p-4 sm:p-6 md:p-8 space-y-6 sm:space-y-8 h-full flex flex-col overflow-y-auto`,children:[(0,P.jsxs)(`div`,{className:`flex items-center gap-3 sm:gap-4 mb-6 sm:mb-8 shrink-0`,children:[(0,P.jsx)(`div`,{className:`p-3 bg-primary-container text-on-primary-container rounded-2xl`,children:(0,P.jsx)(ne,{size:24})}),(0,P.jsx)(`h1`,{className:`text-2xl sm:text-3xl font-bold font-headline text-on-background`,children:a.gallery.title})]}),d===`pending`?(0,P.jsx)(`div`,{className:`flex justify-center items-center py-20`,children:(0,P.jsx)(u,{className:`w-8 h-8 animate-spin text-primary`})}):f.length===0?(0,P.jsxs)(`div`,{className:`text-center py-20 text-on-surface-variant/50 flex-1 flex flex-col items-center justify-center`,children:[(0,P.jsx)(ne,{size:48,className:`mx-auto mb-4 opacity-50`}),(0,P.jsx)(`p`,{className:`text-sm font-body`,children:a.gallery.empty})]}):(0,P.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 pb-12`,children:[f.map(e=>(0,P.jsxs)(`div`,{className:`group relative aspect-square rounded-2xl overflow-hidden bg-surface-container-high border border-outline-variant/20 shadow-sm hover:shadow-xl transition-all duration-300`,children:[(0,P.jsx)(`img`,{src:e.imageUrl,alt:e.prompt,className:`w-full h-full object-cover transition-transform duration-500 group-hover:scale-105`,referrerPolicy:`no-referrer`,loading:`lazy`,decoding:`async`}),(0,P.jsxs)(`div`,{className:`absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex flex-col justify-end p-4`,children:[(0,P.jsx)(`p`,{className:`text-white text-sm line-clamp-3 font-medium mb-3 drop-shadow-md`,children:e.prompt}),(0,P.jsxs)(`div`,{className:`flex gap-2`,children:[(0,P.jsxs)(`button`,{type:`button`,onClick:()=>t(e),className:`p-2 bg-white/20 hover:bg-white/30 backdrop-blur-md rounded-lg text-white transition-colors flex-1 flex items-center justify-center gap-2`,children:[(0,P.jsx)(Xe,{size:16}),(0,P.jsx)(`span`,{className:`text-xs font-bold uppercase tracking-wider`,children:a.gallery.view})]}),(0,P.jsx)(`a`,{href:e.imageUrl,download:ca(a.common.downloadFilenamePrefix,e.id),target:`_blank`,rel:`noreferrer`,className:`p-2 bg-primary hover:bg-primary/90 rounded-lg text-on-primary transition-colors flex items-center justify-center`,children:(0,P.jsx)(ue,{size:16})})]})]})]},e.id)),(0,P.jsx)(`div`,{ref:r,className:`col-span-full h-10 flex justify-center items-center`,children:l&&(0,P.jsx)(u,{className:`w-6 h-6 animate-spin text-primary`})})]}),(0,P.jsx)(n,{children:e&&(0,P.jsxs)(i.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:`fixed inset-0 z-[100] flex items-center justify-center p-4 md:p-8 bg-black/90 backdrop-blur-sm`,onClick:()=>t(null),children:[(0,P.jsx)(`button`,{type:`button`,className:`absolute top-6 right-6 p-3 bg-white/10 hover:bg-white/20 rounded-full text-white transition-colors`,onClick:()=>t(null),children:(0,P.jsx)(Ue,{size:24})}),(0,P.jsxs)(i.div,{initial:{scale:.9,y:20},animate:{scale:1,y:0},exit:{scale:.9,y:20},className:`relative max-w-5xl w-full max-h-full flex flex-col items-center`,onClick:e=>e.stopPropagation(),children:[(0,P.jsx)(`img`,{src:e.imageUrl,alt:e.prompt,className:`max-w-full max-h-[75vh] object-contain rounded-lg shadow-2xl`,referrerPolicy:`no-referrer`}),(0,P.jsxs)(`div`,{className:`mt-6 p-4 bg-surface-container-highest/80 backdrop-blur-md rounded-xl max-w-2xl w-full text-center border border-outline-variant/20`,children:[(0,P.jsx)(`p`,{className:`text-on-surface font-medium`,children:e.prompt}),(0,P.jsxs)(`a`,{href:e.imageUrl,download:ca(a.common.downloadFilenamePrefix,e.id),target:`_blank`,rel:`noreferrer`,className:`mt-4 inline-flex items-center gap-2 px-4 py-2 bg-primary text-on-primary rounded-full text-sm font-bold hover:bg-primary/90 transition-colors`,children:[(0,P.jsx)(ue,{size:16}),a.gallery.download]})]})]})]})})]})}var Fo=S(`/_authenticated/gallery`)({loader:({context:{queryClient:e}})=>e.prefetchInfiniteQuery(Mo()),component:Po}),Io=S(`/_authenticated/settings/`)({beforeLoad:()=>{le({to:`/settings/general`,throw:!0})}});async function Lo(e,t){let{data:n,error:r}=await H.api.settings.tools({toolName:e}).put(t);if(r)throw Error(V(r.value,I.settings.tools.saveError));return n}var Ro={all:[`tool-settings`],list:()=>[...Ro.all,`list`]};function zo(){return D({queryKey:Ro.list(),staleTime:3e4,queryFn:async()=>{let{data:e,error:t}=await H.api.settings.tools.get();if(t)throw Error(V(t.value,I.settings.tools.loadError));return e}})}function Bo(e,t){e.setQueryData(Ro.list(),e=>e&&{tools:e.tools.map(e=>e.name===t.name?t:e)})}function Vo(){let{data:e,isLoading:t,error:n,refetch:r}=k(zo());return{descriptors:e?.tools??[],isLoading:t,error:n,refetch:r}}function Ho(){let e=O();return j({mutationFn:async({toolName:e,body:t})=>Lo(e,t),onSuccess:t=>{Bo(e,t)}})}function Uo(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`?String(e):``}function Wo(e){return typeof e==`object`&&!!e&&`path`in e&&typeof e.path==`string`&&`enabled`in e&&typeof e.enabled==`boolean`}function Go(e){return Array.isArray(e)&&e.every(Wo)}function Ko({value:e,onChange:t,disabled:n,placeholder:r}){let{t:i}=L(),a=i.settings.tools.pathList,o=Go(e)?e:[],[s,c]=(0,N.useState)(``),[l,u]=(0,N.useState)(null),[d,f]=(0,N.useState)(``),p=()=>{let e=s.trim();e&&(o.some(t=>t.path===e)||(t([...o,{path:e,enabled:!0}]),c(``)))},m=e=>{t(o.map((t,n)=>n===e?{...t,enabled:!t.enabled}:t))},h=e=>{t(o.filter((t,n)=>n!==e))},g=e=>{u(e),f(o[e].path)},_=()=>{if(l===null)return;let e=d.trim();e&&(o.some((t,n)=>n!==l&&t.path===e)||(t(o.map((t,n)=>n===l?{...t,path:e}:t)),u(null),f(``)))},v=()=>{u(null),f(``)};return(0,P.jsxs)(`div`,{className:`space-y-2`,children:[(0,P.jsxs)(`div`,{className:`flex gap-2`,children:[(0,P.jsx)(`input`,{type:`text`,value:s,onChange:e=>c(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),p())},disabled:n,placeholder:r,className:`flex-1 rounded-xl px-4 py-2.5 text-sm bg-surface-container-lowest text-on-surface border border-outline-variant/20 placeholder:text-on-surface/30 focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20 transition-colors disabled:opacity-50 disabled:cursor-not-allowed`}),(0,P.jsx)(R,{variant:`secondary`,size:`sm`,disabled:n||!s.trim(),onClick:p,children:a.add})]}),o.length===0?(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/40 py-2`,children:a.noPaths}):(0,P.jsx)(`ul`,{className:`space-y-1.5`,children:o.map((e,t)=>(0,P.jsxs)(`li`,{className:`flex items-center gap-2 p-2 rounded-lg bg-surface-container-lowest border border-outline-variant/10`,children:[(0,P.jsx)(`input`,{type:`checkbox`,checked:e.enabled,onChange:()=>m(t),disabled:n,className:`h-4 w-4 rounded border-outline-variant/30 accent-primary shrink-0 disabled:opacity-50 disabled:cursor-not-allowed`}),l===t?(0,P.jsx)(`input`,{type:`text`,value:d,onChange:e=>f(e.target.value),onBlur:_,onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),_()),e.key===`Escape`&&v()},className:`flex-1 rounded-lg px-3 py-1.5 text-sm bg-surface-container-lowest text-on-surface border border-outline-variant/20 focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20`}):(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(`span`,{className:`flex-1 text-sm ${e.enabled?`text-on-surface`:`text-on-surface-variant/40 line-through`}`,children:e.path}),(0,P.jsx)(`button`,{type:`button`,onClick:()=>g(t),disabled:n,className:`p-1.5 rounded-md text-on-surface-variant hover:bg-surface-container-high disabled:opacity-50 disabled:cursor-not-allowed`,"aria-label":a.edit,children:(0,P.jsx)(Qe,{className:`w-3.5 h-3.5`})}),(0,P.jsx)(`button`,{type:`button`,onClick:()=>h(t),disabled:n,className:`p-1.5 rounded-md text-danger hover:bg-danger/10 disabled:opacity-50 disabled:cursor-not-allowed`,"aria-label":a.delete,children:(0,P.jsx)(Ge,{className:`w-3.5 h-3.5`})})]})]},e.path))})]})}function qo({descriptor:e,value:t,onChange:n,disabled:r}){let i=(0,N.useId)(),{t:a}=L(),{catalog:o}=Qi(),s=(0,N.useMemo)(()=>{let e=o.imageModels??[],t=new Map;for(let n of e){let e=n.provider??`other`,r=t.get(e);r?r.push(n):t.set(e,[n])}return{models:e,groups:t}},[o.imageModels]),c=(0,N.useMemo)(()=>e.name===`letAiDecideQuality`?a.settings.tools.letAiDecideQualityLabel:e.name===`allowedPaths`?a.settings.tools.parameters.allowedPathsLabel:e.name===`deniedPaths`?a.settings.tools.parameters.deniedPathsLabel:e.label,[e.name,e.label,a]),l=(0,N.useMemo)(()=>e.name===`letAiDecideQuality`?a.settings.tools.letAiDecideQualityDescription:e.name===`allowedPaths`?a.settings.tools.parameters.allowedPathsDescription:e.name===`deniedPaths`?a.settings.tools.parameters.deniedPathsDescription:e.description,[e.name,e.description,a]),u=`w-full rounded-xl px-4 py-2.5 text-sm bg-surface-container-lowest text-on-surface border border-outline-variant/20 placeholder:text-on-surface/30 focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20 transition-colors disabled:opacity-50 disabled:cursor-not-allowed`,d=t??e.defaultValue??``;if(e.modelType===`image`)return(0,P.jsxs)(`div`,{className:`space-y-1`,children:[c&&(0,P.jsx)(`label`,{htmlFor:`${i}-model`,className:`text-sm text-on-surface-variant`,children:c}),(0,P.jsxs)(`select`,{id:`${i}-model`,value:Uo(d),onChange:e=>n(e.target.value),disabled:r,className:u,children:[(0,P.jsx)(`option`,{value:`auto`,children:a.settings.tools.autoModelOption}),[...s.groups.entries()].map(([e,t])=>(0,P.jsx)(`optgroup`,{label:e,children:t.map(e=>(0,P.jsx)(`option`,{value:e.modelId,children:e.displayName},e.modelId))},e))]})]});switch(e.type){case`boolean`:return(0,P.jsxs)(`label`,{className:`flex items-center gap-3 cursor-pointer`,children:[(0,P.jsx)(`input`,{type:`checkbox`,checked:!!d,onChange:e=>n(e.target.checked),disabled:r,className:`h-4 w-4 rounded border-outline-variant/30 accent-primary disabled:opacity-50 disabled:cursor-not-allowed`}),c]});case`number`:return(0,P.jsxs)(`div`,{className:`space-y-1`,children:[c&&(0,P.jsx)(`label`,{htmlFor:`${i}-number`,className:`text-sm text-on-surface-variant`,children:c}),(0,P.jsx)(`input`,{id:`${i}-number`,type:`number`,min:e.min,max:e.max,step:1,value:d===``?``:Number(d),onChange:e=>n(e.target.value?Number(e.target.value):void 0),disabled:r,placeholder:l,className:u})]});case`select`:return(0,P.jsxs)(`div`,{className:`space-y-1`,children:[c&&(0,P.jsx)(`label`,{htmlFor:`${i}-select`,className:`text-sm text-on-surface-variant`,children:c}),(0,P.jsx)(`select`,{id:`${i}-select`,value:Uo(d),onChange:e=>n(e.target.value),disabled:r,className:u,children:e.options?.map(e=>(0,P.jsx)(`option`,{value:e.value,children:e.label},e.value))})]});case`string_list`:{let e=Array.isArray(d)?d.join(`
32
+ `):Uo(d);return(0,P.jsxs)(`div`,{className:`space-y-1`,children:[c&&(0,P.jsx)(`label`,{htmlFor:`${i}-list`,className:`text-sm text-on-surface-variant`,children:c}),(0,P.jsx)(`textarea`,{id:`${i}-list`,value:e,onChange:e=>{n(e.target.value.split(`
33
+ `).map(e=>e.trim()).filter(e=>e.length>0))},disabled:r,placeholder:l,rows:4,className:`${u} resize-y`})]})}case`path_list`:return(0,P.jsxs)(`div`,{className:`space-y-1`,children:[c&&(0,P.jsx)(`span`,{className:`text-sm text-on-surface-variant`,children:c}),(0,P.jsx)(Ko,{value:d,onChange:n,disabled:r,placeholder:l})]});default:return(0,P.jsxs)(`div`,{className:`space-y-1`,children:[c&&(0,P.jsx)(`label`,{htmlFor:`${i}-text`,className:`text-sm text-on-surface-variant`,children:c}),(0,P.jsx)(`input`,{id:`${i}-text`,type:`text`,value:Uo(d),onChange:e=>n(e.target.value),disabled:r,placeholder:l,className:u})]})}}var Jo=300;function Yo(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Xo(e,t){let n=t.settings.tools;switch(e.name){case`read_file`:return{title:n.toolNames.readFile,description:n.toolDescriptions.readFile};case`write_file`:return{title:n.toolNames.writeFile,description:n.toolDescriptions.writeFile};case`list_directory`:return{title:n.toolNames.listDirectory,description:n.toolDescriptions.listDirectory};case`glob`:return{title:n.toolNames.glob,description:n.toolDescriptions.glob};case`grep`:return{title:n.toolNames.grep,description:n.toolDescriptions.grep};default:return{title:e.title,description:e.description}}}function Zo({descriptor:e}){let{t}=L(),n=t.settings.tools,{mutateAsync:r,isPending:i}=Ho(),a=Xo(e,t),o=(0,N.useRef)(null),s=(0,N.useRef)(!0),[c,l]=(0,N.useState)(e.enabled),[u,d]=(0,N.useState)({...e.parameters});(0,N.useEffect)(()=>(s.current=!0,()=>{s.current=!1}),[]);let f=(0,N.useCallback)(async()=>{let t=!c;l(t);try{let n=await r({toolName:e.name,body:{enabled:t}});if(!s.current)return;l(typeof n.enabled==`boolean`?n.enabled:t)}catch{if(!s.current)return;l(e.enabled)}},[c,r,e.name,e.enabled]),p=(0,N.useCallback)((e,t)=>{d(n=>({...n,[e]:t}))},[]),m=(0,N.useCallback)(async()=>{let t=u;try{let n=await r({toolName:e.name,body:{parameters:t}}),i=n.parameters&&typeof n.parameters==`object`?{...n.parameters}:t;if(!s.current)return;d(e=>Yo(e,t)?i:e)}catch{if(!s.current)return;d(n=>Yo(n,t)?{...e.parameters}:n)}},[r,e.name,e.parameters,u]),h=e.parameterDescriptors.length>0,g=(0,N.useMemo)(()=>c&&h&&!Yo(u,e.parameters),[e.parameters,c,h,u]);(0,N.useEffect)(()=>{if(!(!g||i))return o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{m()},Jo),()=>{o.current&&=(clearTimeout(o.current),null)}},[g,i,m]);let _=(0,N.useRef)({hasUnsavedParams:g,isPending:i,persistParameters:m});return _.current={hasUnsavedParams:g,isPending:i,persistParameters:m},(0,N.useEffect)(()=>()=>{o.current&&clearTimeout(o.current);let e=_.current;!e.hasUnsavedParams||e.isPending||e.persistParameters()},[]),(0,P.jsxs)(z,{variant:`solid`,className:`space-y-4 p-4 sm:p-6`,children:[(0,P.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,P.jsxs)(`div`,{className:`space-y-1 min-w-0`,children:[(0,P.jsx)(`h4`,{className:`text-sm font-bold text-on-surface`,children:a.title}),a.description&&(0,P.jsx)(`p`,{className:`text-xs text-on-surface-variant/70 leading-relaxed`,children:a.description})]}),e.canDisable?(0,P.jsxs)(`label`,{className:`flex items-center gap-2 shrink-0`,children:[(0,P.jsx)(`span`,{className:`text-xs text-on-surface-variant`,children:c?n.enabled:n.disabled}),(0,P.jsx)(`input`,{type:`checkbox`,checked:c,onChange:()=>void f(),className:`h-4 w-4 rounded border-outline-variant/30 accent-primary`})]}):(0,P.jsx)(`span`,{className:`text-xs text-on-surface-variant/50 italic shrink-0 text-right`,children:n.cannotDisable})]}),h&&(0,P.jsxs)(`div`,{className:`space-y-3 pt-2 border-t border-outline-variant/10`,children:[e.parameterDescriptors.map(e=>{let t=e.name===`defaultQuality`&&u.letAiDecideQuality===!0;return(0,P.jsx)(qo,{descriptor:e,value:u[e.name],onChange:t=>p(e.name,t),disabled:!c||t},e.name)}),i&&(0,P.jsx)(`p`,{className:`text-xs text-on-surface-variant`,role:`status`,"aria-live":`polite`,children:n.saving})]})]})}var Qo=[`system`,`image`,`interaction`];function $o({maxToolIterations:e,setMaxToolIterations:t}){let{t:n}=L(),{descriptors:r,isLoading:i,error:a,refetch:o}=Vo(),s=n.settings.tools,c=(0,N.useMemo)(()=>{let e={system:[],image:[],interaction:[]};for(let t of r)e[t.category]?.push(t);return e},[r]),l=s.maxToolIterationsHint.replace(`{value}`,String(e));return i?(0,P.jsx)(`div`,{className:`flex items-center justify-center py-16`,children:(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant`,children:n.common.loading})}):a?(0,P.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-16`,children:[(0,P.jsx)(`p`,{className:`text-sm text-destructive`,children:s.loadError}),(0,P.jsx)(R,{variant:`ghost`,size:`sm`,onClick:()=>void o(),children:n.common.retry})]}):(0,P.jsxs)(`div`,{className:`space-y-6`,children:[(0,P.jsxs)(z,{variant:`solid`,className:`space-y-3 p-4 sm:p-6`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:s.executionTitle}),(0,P.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-baseline sm:justify-between gap-1 sm:gap-4`,children:[(0,P.jsx)(`h4`,{className:`text-sm text-on-surface font-medium`,children:s.maxToolIterationsLabel}),(0,P.jsx)(`span`,{className:`text-sm font-medium text-on-surface`,children:l})]}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:s.maxToolIterationsDescription}),(0,P.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,P.jsx)(`input`,{type:`range`,min:1,max:G,step:1,value:e,onChange:e=>t(Number(e.target.value)),"aria-label":s.maxToolIterationsLabel,className:`flex-1 h-2 bg-surface-container-lowest rounded-full appearance-none cursor-pointer accent-primary`}),(0,P.jsx)(`input`,{type:`number`,min:1,max:G,step:1,value:e,onChange:e=>t(Number(e.target.value)),onBlur:e=>t(Number(e.target.value)),"aria-label":s.maxToolIterationsLabel,className:`
34
+ w-20 rounded-xl px-3 py-2 text-sm text-center
35
+ bg-surface-container-lowest text-on-surface
36
+ border border-outline-variant/20
37
+ focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20
38
+ transition-colors
39
+ `})]})]}),r.length===0?(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60 text-center py-8`,children:s.noTools}):Qo.map(e=>{let t=c[e];return t.length===0?null:(0,P.jsxs)(`section`,{className:`space-y-3`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label px-1`,children:s.categories[e]}),(0,P.jsx)(`div`,{className:`space-y-3`,children:t.map(e=>(0,P.jsx)(Zo,{descriptor:e},e.name))})]},e)})]})}var es=S(`/_authenticated/settings/tools`)({loader:({context:{queryClient:e}})=>e.prefetchQuery(zo()),component:ts});function ts(){let e=ta();return(0,P.jsx)($o,{maxToolIterations:e.settings.maxToolIterations,setMaxToolIterations:e.settings.setMaxToolIterations})}var ns=S(`/_authenticated/settings/providers`)({loader:({context:{queryClient:e}})=>e.prefetchQuery(Fi()),component:()=>(0,P.jsx)(v,{})});function rs({label:e,id:t,checked:n,defaultChecked:r,...i}){let a=t??e.toLowerCase().replace(/\s+/g,`-`);return(0,P.jsxs)(`label`,{htmlFor:a,className:`inline-flex items-center gap-3 cursor-pointer group`,children:[(0,P.jsx)(`input`,{id:a,type:`checkbox`,role:`switch`,className:`sr-only peer`,"aria-checked":n??r??!1,checked:n,defaultChecked:r,...i}),(0,P.jsx)(`span`,{className:`
40
+ relative inline-block w-10 h-6 rounded-full
41
+ bg-surface-container-lowest border border-outline-variant/20
42
+ peer-checked:bg-primary peer-checked:border-primary/60
43
+ transition-colors duration-200
44
+ after:content-[''] after:absolute after:top-0.5 after:left-0.5
45
+ after:w-5 after:h-5 after:rounded-full after:bg-on-surface after:shadow-sm
46
+ after:transition-transform after:duration-200
47
+ peer-checked:after:translate-x-4 peer-checked:after:bg-on-primary
48
+ group-hover:after:scale-105
49
+ `}),(0,P.jsx)(`span`,{className:`text-sm text-on-surface select-none`,children:e})]})}var is=[{value:`system`,label:`system`},{value:`user`,label:`user`}],as=[{value:`first-turn`,label:`first-turn`},{value:`every-turn`,label:`every-turn`}];function os({setting:e,isFixed:t=!1,onUpdate:n,onRemove:r,labels:i}){return(0,P.jsxs)(`div`,{className:`space-y-4 p-4 sm:p-5 bg-surface-container-lowest rounded-xl border border-outline-variant/10`,children:[(0,P.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,P.jsx)(`div`,{className:`flex-1 space-y-1.5`,children:t?(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`p`,{className:`text-sm font-medium text-on-surface`,children:e.path}),e.label&&(0,P.jsx)(`p`,{className:`text-xs text-on-surface-variant/60`,children:e.label})]}):(0,P.jsx)(B,{id:`rule-path-${e.id}`,label:i.rulePathLabel,value:e.path,placeholder:i.rulePathPlaceholder,onChange:e=>n({path:e.target.value})})}),!t&&r&&(0,P.jsx)(R,{variant:`ghost`,size:`sm`,onClick:r,"aria-label":i.removeRule,children:i.removeRule})]}),(0,P.jsx)(`div`,{className:`flex items-center`,children:(0,P.jsx)(rs,{id:`rule-enabled-${e.id}`,label:i.enabledLabel,checked:e.enabled,onChange:e=>n({enabled:e.target.checked})})}),(0,P.jsxs)(`fieldset`,{children:[(0,P.jsx)(`legend`,{className:`text-sm font-medium text-on-surface-variant mb-2`,children:i.injectionRoleLabel}),(0,P.jsx)(`div`,{className:`flex gap-2`,role:`radiogroup`,"aria-label":i.injectionRoleLabel,children:is.map(t=>(0,P.jsxs)(`label`,{className:`
50
+ px-4 py-2 rounded-lg text-sm font-medium cursor-pointer transition-all
51
+ ${e.injectionRole===t.value?`bg-primary text-on-primary shadow-sm`:`bg-surface-container-high text-on-surface-variant hover:bg-surface-container-highest`}
52
+ `,children:[(0,P.jsx)(`input`,{type:`radio`,name:`role-${e.id}`,value:t.value,checked:e.injectionRole===t.value,onChange:()=>n({injectionRole:t.value}),className:`sr-only`}),t.value===`system`?i.injectionRoleSystem:i.injectionRoleUser]},t.value))})]}),(0,P.jsxs)(`fieldset`,{children:[(0,P.jsx)(`legend`,{className:`text-sm font-medium text-on-surface-variant mb-2`,children:i.frequencyLabel}),(0,P.jsx)(`div`,{className:`flex gap-2`,role:`radiogroup`,"aria-label":i.frequencyLabel,children:as.map(t=>(0,P.jsxs)(`label`,{className:`
53
+ px-4 py-2 rounded-lg text-sm font-medium cursor-pointer transition-all
54
+ ${e.sendFrequency===t.value?`bg-primary text-on-primary shadow-sm`:`bg-surface-container-high text-on-surface-variant hover:bg-surface-container-highest`}
55
+ `,children:[(0,P.jsx)(`input`,{type:`radio`,name:`freq-${e.id}`,value:t.value,checked:e.sendFrequency===t.value,onChange:()=>n({sendFrequency:t.value}),className:`sr-only`}),t.value===`first-turn`?i.frequencyFirstTurn:i.frequencyEveryTurn]},t.value))}),e.sendFrequency===`first-turn`&&(0,P.jsx)(`p`,{className:`text-xs text-on-surface-variant/50 mt-1.5 ml-1`,children:i.frequencyFirstTurnHint})]})]})}function ss({promptSettings:e,onTextSystemPromptChange:t,onImageSystemPromptChange:n,onUpdateRuleFile:r,onAddCustomRule:i,onRemoveCustomRule:a}){let{t:o}=L(),s=o.settings.prompts,c=(0,N.useCallback)(e=>r(`agentsMd`,e),[r]),l=(0,N.useCallback)(e=>r(`claudeMd`,e),[r]),u={enabledLabel:s.enabledLabel,injectionRoleLabel:s.injectionRoleLabel,injectionRoleSystem:s.injectionRoleSystem,injectionRoleUser:s.injectionRoleUser,frequencyLabel:s.frequencyLabel,frequencyFirstTurn:s.frequencyFirstTurn,frequencyFirstTurnHint:s.frequencyFirstTurnHint,frequencyEveryTurn:s.frequencyEveryTurn,removeRule:s.removeRule,rulePathLabel:s.rulePathLabel,rulePathPlaceholder:s.rulePathPlaceholder};return(0,P.jsxs)(`div`,{className:`space-y-4`,children:[(0,P.jsxs)(z,{variant:`solid`,className:`space-y-3 p-4 sm:p-6`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:s.defaultPromptsLabel}),(0,P.jsx)(`label`,{className:`text-sm font-medium text-on-surface-variant`,htmlFor:`text-system-prompt`,children:s.textSystemPromptLabel}),(0,P.jsx)(`textarea`,{id:`text-system-prompt`,value:e.textSystemPrompt,onChange:e=>t(e.target.value),placeholder:s.textSystemPromptPlaceholder,className:`
56
+ w-full bg-surface-container-lowest border border-outline-variant/20 rounded-xl p-4
57
+ text-sm text-on-surface focus:ring-1 focus:ring-primary/40 focus:outline-none
58
+ focus:border-primary/60 placeholder:text-on-surface-variant/40
59
+ min-h-25 transition-all resize-none font-body
60
+ `}),(0,P.jsx)(`label`,{className:`text-sm font-medium text-on-surface-variant`,htmlFor:`image-system-prompt`,children:s.imageSystemPromptLabel}),(0,P.jsx)(`textarea`,{id:`image-system-prompt`,value:e.imageSystemPrompt,onChange:e=>n(e.target.value),placeholder:s.imageSystemPromptPlaceholder,className:`
61
+ w-full bg-surface-container-lowest border border-outline-variant/20 rounded-xl p-4
62
+ text-sm text-on-surface focus:ring-1 focus:ring-primary/40 focus:outline-none
63
+ focus:border-primary/60 placeholder:text-on-surface-variant/40
64
+ min-h-25 transition-all resize-none font-body
65
+ `})]}),(0,P.jsxs)(z,{variant:`solid`,className:`space-y-4 p-4 sm:p-6`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:s.ruleFilesLabel}),(0,P.jsx)(os,{setting:e.agentsMd,isFixed:!0,onUpdate:c,labels:u}),(0,P.jsx)(os,{setting:e.claudeMd,isFixed:!0,onUpdate:l,labels:u})]}),(0,P.jsxs)(z,{variant:`solid`,className:`space-y-4 p-4 sm:p-6`,children:[(0,P.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4`,children:[(0,P.jsxs)(`div`,{className:`space-y-1`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:s.customRulesLabel}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:s.customRulesDescription})]}),(0,P.jsxs)(R,{variant:`secondary`,size:`sm`,onClick:i,className:`shrink-0 whitespace-nowrap`,children:[(0,P.jsx)(Ye,{className:`w-3.5 h-3.5`}),s.addRule]})]}),e.customRules.map(e=>(0,P.jsx)(os,{setting:e,onUpdate:t=>r(e.id,t),onRemove:()=>a(e.id),labels:u},e.id)),e.customRules.length===0&&(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/40 text-center py-4`,children:s.addRule})]})]})}var cs=S(`/_authenticated/settings/prompts`)({component:ls});function ls(){let e=ta();return(0,P.jsx)(ss,{promptSettings:e.settings.promptSettings,onTextSystemPromptChange:e.settings.setTextSystemPrompt,onImageSystemPromptChange:e.settings.setImageSystemPrompt,onUpdateRuleFile:e.settings.updateRuleFileSetting,onAddCustomRule:e.settings.addCustomRule,onRemoveCustomRule:e.settings.removeCustomRule})}var us={all:[`observability`],metrics:()=>[...us.all,`metrics`],logs:()=>[...us.all,`logs`]};function ds(){return D({queryKey:us.metrics(),staleTime:5e3,refetchInterval:5e3,queryFn:async()=>{let{data:e,error:t}=await H.api.settings.metrics.get();if(t)throw Error(V(t.value,I.settings.metrics.failedToLoad));return e}})}function fs(){return D({queryKey:us.logs(),staleTime:5e3,refetchInterval:5e3,queryFn:async()=>{let{data:e,error:t}=await H.api.settings.logs.get();if(t)throw Error(V(t.value,I.settings.logs.failedToLoad));return e}})}var ps=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`});function ms(e){return ps.format(e)}function hs(e){return`${Math.round(e*100)}%`}function gs(){let{t:e}=L(),{data:t,error:n,isLoading:r,isFetching:i,refetch:a}=k(fs()),o=e.settings.logs,s={healthcheck:o.operations.healthcheck,"model-list":o.operations.modelList};return r?(0,P.jsx)(z,{variant:`solid`,className:`p-4 sm:p-6 text-sm text-on-surface-variant/70`,children:e.common.loading}):n?(0,P.jsx)(z,{variant:`solid`,className:`p-4 sm:p-6 text-sm text-error`,children:o.failedToLoad}):(0,P.jsxs)(`div`,{className:`space-y-4`,children:[(0,P.jsx)(z,{variant:`solid`,className:`space-y-4 p-4 sm:p-6`,children:(0,P.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between`,children:[(0,P.jsxs)(`div`,{className:`space-y-1`,children:[(0,P.jsx)(`h2`,{className:`text-lg font-semibold text-on-surface`,children:o.title}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/70`,children:o.description})]}),(0,P.jsx)(R,{variant:`secondary`,size:`sm`,onClick:()=>void a(),loading:i,children:o.refresh})]})}),t?.entries.length?t.entries.map(t=>(0,P.jsxs)(z,{variant:`solid`,className:`space-y-3 p-4 sm:p-6`,children:[(0,P.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between`,children:[(0,P.jsxs)(`div`,{className:`space-y-1`,children:[(0,P.jsx)(`p`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:o.eventKinds.probeTimeout}),(0,P.jsx)(`h3`,{className:`text-base font-semibold text-on-surface`,children:e.providers[t.provider]}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface`,children:t.message})]}),(0,P.jsx)(`span`,{className:`text-xs text-on-surface-variant/60`,children:ms(t.timestamp)})]}),(0,P.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,P.jsxs)(`div`,{className:`rounded-xl bg-surface-container-lowest px-4 py-3`,children:[(0,P.jsx)(`p`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/70 font-label`,children:o.providerLabel}),(0,P.jsx)(`p`,{className:`mt-1 text-sm text-on-surface`,children:e.providers[t.provider]})]}),(0,P.jsxs)(`div`,{className:`rounded-xl bg-surface-container-lowest px-4 py-3`,children:[(0,P.jsx)(`p`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/70 font-label`,children:o.operationLabel}),(0,P.jsx)(`p`,{className:`mt-1 text-sm text-on-surface`,children:s[t.operation]})]})]})]},t.id)):(0,P.jsx)(z,{variant:`solid`,className:`p-4 sm:p-6 text-sm text-on-surface-variant/70`,children:o.empty})]})}function _s(e){return(0,P.jsx)(`div`,{className:`overflow-x-auto`,children:(0,P.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,P.jsx)(`thead`,{children:(0,P.jsxs)(`tr`,{className:`text-left text-on-surface-variant/70`,children:[(0,P.jsx)(`th`,{className:`whitespace-nowrap py-2 pr-4 font-medium`,children:e.cacheLabel}),(0,P.jsx)(`th`,{className:`whitespace-nowrap py-2 pr-4 font-medium`,children:e.hitsLabel}),(0,P.jsx)(`th`,{className:`whitespace-nowrap py-2 pr-4 font-medium`,children:e.missesLabel}),(0,P.jsx)(`th`,{className:`whitespace-nowrap py-2 font-medium`,children:e.hitRateLabel})]})}),(0,P.jsx)(`tbody`,{children:e.entries.map(t=>(0,P.jsxs)(`tr`,{className:`border-t border-outline-variant/10`,children:[(0,P.jsx)(`td`,{className:`whitespace-nowrap py-2 pr-4 text-on-surface`,children:e.cacheLabels[t.cacheName]}),(0,P.jsx)(`td`,{className:`whitespace-nowrap py-2 pr-4 text-on-surface`,children:t.hits}),(0,P.jsx)(`td`,{className:`whitespace-nowrap py-2 pr-4 text-on-surface`,children:t.misses}),(0,P.jsx)(`td`,{className:`whitespace-nowrap py-2 text-on-surface`,children:hs(t.hitRate)})]},t.cacheName))})]})})}function vs(){let{t:e}=L(),{data:t,error:n,isLoading:r,isFetching:i,refetch:a}=k(ds()),o=e.settings.metrics,s=t?.generatedAt?ms(t.generatedAt):`-`,c={"sdk-client":o.caches.sdkClient,"prepared-runtime":o.caches.preparedRuntime,"provider-route":o.caches.providerRoute},l={healthcheck:o.operations.healthcheck,"model-list":o.operations.modelList};return r?(0,P.jsx)(z,{variant:`solid`,className:`p-4 sm:p-6 text-sm text-on-surface-variant/70`,children:e.common.loading}):n?(0,P.jsx)(z,{variant:`solid`,className:`p-4 sm:p-6 text-sm text-error`,children:o.failedToLoad}):(0,P.jsxs)(`div`,{className:`space-y-4`,children:[(0,P.jsx)(z,{variant:`solid`,className:`space-y-4 p-4 sm:p-6`,children:(0,P.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between`,children:[(0,P.jsxs)(`div`,{className:`space-y-1`,children:[(0,P.jsx)(`h2`,{className:`text-lg font-semibold text-on-surface`,children:o.title}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/70`,children:o.description}),(0,P.jsx)(`p`,{className:`text-xs text-on-surface-variant/60`,children:o.generatedAtLabel.replace(`{value}`,s)})]}),(0,P.jsx)(R,{variant:`secondary`,size:`sm`,onClick:()=>void a(),loading:i,children:o.refresh})]})}),t?.providers.length?t.providers.map(t=>(0,P.jsxs)(z,{variant:`solid`,className:`space-y-4 p-4 sm:p-6`,children:[(0,P.jsxs)(`div`,{className:`flex flex-col gap-1 sm:flex-row sm:items-baseline sm:justify-between`,children:[(0,P.jsx)(`h3`,{className:`text-base font-semibold text-on-surface`,children:e.providers[t.provider]}),(0,P.jsx)(`span`,{className:`text-sm text-on-surface-variant/70`,children:o.totalProbeTimeoutsLabel.replace(`{value}`,String(t.totalProbeTimeouts))})]}),(0,P.jsxs)(`div`,{className:`grid gap-4`,children:[(0,P.jsxs)(`div`,{className:`space-y-3`,children:[(0,P.jsx)(`h4`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:o.cacheSectionTitle}),(0,P.jsx)(_s,{cacheLabel:o.cacheLabel,cacheLabels:c,hitRateLabel:o.hitRateLabel,hitsLabel:o.hitsLabel,missesLabel:o.missesLabel,entries:t.caches})]}),(0,P.jsxs)(`div`,{className:`space-y-3`,children:[(0,P.jsx)(`h4`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:o.probeSectionTitle}),(0,P.jsx)(`div`,{className:`space-y-2`,children:t.probeTimeouts.map(e=>(0,P.jsxs)(`div`,{className:`grid grid-cols-[1fr_auto] items-center gap-3 rounded-xl bg-surface-container-lowest px-4 py-3`,children:[(0,P.jsx)(`span`,{className:`text-sm text-on-surface`,children:l[e.operation]}),(0,P.jsx)(`span`,{className:`rounded-full bg-surface-container-high px-2.5 py-1 text-xs font-semibold text-on-surface tabular-nums`,children:e.timeoutCount})]},e.operation))})]})]})]},t.provider)):(0,P.jsx)(z,{variant:`solid`,className:`p-4 sm:p-6 text-sm text-on-surface-variant/70`,children:o.empty})]})}var ys=S(`/_authenticated/settings/metrics`)({loader:({context:{queryClient:e}})=>e.prefetchQuery(ds()),component:vs}),bs=S(`/_authenticated/settings/logs`)({loader:({context:{queryClient:e}})=>e.prefetchQuery(fs()),component:gs}),xs=[`512px`,`1K`,`2K`,`4K`],Ss=[{value:`en`,label:`English`},{value:`pt-BR`,label:`Português (BR)`}],Cs=10,ws=80,Ts=3e4;function Es({imageQuality:e,setImageQuality:t,chatTitleSettings:n,availableTitleModels:r,setChatAutoRenameEnabled:i,setChatTitleStrategy:a,setChatTitlePromptPrefixLength:o,setPreferredChatTitleModel:s,multiAgentSettings:c,setMultiAgentEnabled:l,setChatDelegationEnabled:u,setTraceVisibility:d,setMaxDelegationDepth:f,setMaxSubagentCalls:p,setSubagentTimeoutMs:m,setDefaultSubagentMaxTurns:h}){let{t:g,locale:_,setLocale:v}=L(),y=g.settings.general,b=n.preferredModel!==`current_model`&&!r.some(e=>e.modelId===n.preferredModel)?[{modelId:n.preferredModel,displayName:n.preferredModel}]:[];return(0,P.jsxs)(`div`,{className:`space-y-4`,children:[(0,P.jsxs)(z,{variant:`solid`,className:`space-y-3 p-4 sm:p-6`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:y.languageLabel}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:y.languageDescription}),(0,P.jsx)(`select`,{value:_,onChange:e=>v(e.target.value),id:`language-select`,className:`
66
+ w-full rounded-xl px-4 py-2.5 text-sm
67
+ bg-surface-container-lowest text-on-surface
68
+ border border-outline-variant/20
69
+ focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20
70
+ transition-colors cursor-pointer
71
+ `,children:Ss.map(({value:e,label:t})=>(0,P.jsx)(`option`,{value:e,children:t},e))})]}),(0,P.jsxs)(z,{variant:`solid`,className:`space-y-3 p-4 sm:p-6`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:y.imageQualityLabel}),(0,P.jsx)(`div`,{className:`grid grid-cols-2 sm:grid-cols-4 gap-2`,children:xs.map(n=>(0,P.jsx)(R,{variant:e===n?`primary`:`secondary`,size:`md`,onClick:()=>t(n),children:n},n))})]}),(0,P.jsxs)(z,{variant:`solid`,className:`space-y-4 p-4 sm:p-6`,children:[(0,P.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,P.jsxs)(`div`,{className:`space-y-1`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:y.multiAgentLabel}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:y.multiAgentDescription})]}),(0,P.jsx)(`input`,{type:`checkbox`,checked:c.enabled,onChange:e=>l(e.target.checked),"aria-label":y.multiAgentEnabledLabel,className:`mt-1 h-4 w-4 rounded border-outline-variant/30 accent-primary`})]}),(0,P.jsxs)(`label`,{className:`flex items-center gap-2 rounded-xl border border-outline-variant/20 bg-surface-container-lowest px-3 py-2 text-sm text-on-surface`,children:[(0,P.jsx)(`input`,{type:`checkbox`,checked:c.chatDelegationEnabled,onChange:e=>u(e.target.checked),disabled:!c.enabled,className:`accent-primary disabled:opacity-50`}),y.chatDelegationEnabledLabel]}),(0,P.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2 xl:grid-cols-4`,children:[(0,P.jsxs)(`label`,{className:`block space-y-2`,children:[(0,P.jsx)(`span`,{className:`text-sm font-semibold text-on-surface`,children:y.traceVisibilityLabel}),(0,P.jsxs)(`select`,{value:c.traceVisibility,onChange:e=>d(e.target.value),disabled:!c.enabled,className:`w-full rounded-xl px-3 py-2 text-sm bg-surface-container-lowest text-on-surface border border-outline-variant/20 focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20 disabled:opacity-50`,children:[(0,P.jsx)(`option`,{value:`compact`,children:y.traceVisibilityCompact}),(0,P.jsx)(`option`,{value:`full`,children:y.traceVisibilityFull}),(0,P.jsx)(`option`,{value:`off`,children:y.traceVisibilityOff})]})]}),(0,P.jsx)(Ds,{label:y.maxDepthLabel,value:c.maxDepth,min:0,max:3,disabled:!c.enabled,onChange:f}),(0,P.jsx)(Ds,{label:y.maxSubagentCallsLabel,value:c.maxSubagentCalls,min:0,max:hn,disabled:!c.enabled,onChange:p}),(0,P.jsx)(Ds,{label:y.defaultMaxTurnsLabel,value:c.defaultMaxTurns,min:1,max:_n,disabled:!c.enabled,onChange:h})]}),(0,P.jsxs)(`div`,{className:`space-y-3`,children:[(0,P.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-baseline sm:justify-between gap-1 sm:gap-4`,children:[(0,P.jsx)(`label`,{htmlFor:`subagent-timeout`,className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:y.timeoutLabel}),(0,P.jsx)(`span`,{className:`text-sm font-medium text-on-surface`,children:y.secondsHint.replace(`{value}`,String(Math.round(c.timeoutMs/1e3)))})]}),(0,P.jsx)(`input`,{id:`subagent-timeout`,type:`range`,min:3e4,max:9e5,step:Ts,value:c.timeoutMs,onChange:e=>m(Number(e.target.value)),disabled:!c.enabled,className:`w-full h-2 bg-surface-container-lowest rounded-full appearance-none cursor-pointer accent-primary disabled:cursor-not-allowed disabled:opacity-50`})]})]}),(0,P.jsxs)(z,{variant:`solid`,className:`space-y-4 p-4 sm:p-6`,children:[(0,P.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,P.jsxs)(`div`,{className:`space-y-1`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:y.chatTitlesLabel}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:y.chatTitlesDescription})]}),(0,P.jsx)(`input`,{type:`checkbox`,checked:n.autoRenameEnabled,onChange:e=>i(e.target.checked),"aria-label":y.chatTitlesToggleLabel,className:`mt-1 h-4 w-4 rounded border-outline-variant/30 accent-primary`})]}),(0,P.jsxs)(`div`,{className:`space-y-3`,children:[(0,P.jsx)(`label`,{htmlFor:`chat-title-strategy`,className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:y.chatTitleSourceLabel}),(0,P.jsxs)(`select`,{id:`chat-title-strategy`,value:n.strategy,onChange:e=>a(e.target.value),disabled:!n.autoRenameEnabled,className:`w-full rounded-xl px-4 py-2.5 text-sm bg-surface-container-lowest text-on-surface border border-outline-variant/20 focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20 transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-50`,children:[(0,P.jsx)(`option`,{value:`prompt_prefix`,children:y.chatTitleSourcePrompt}),(0,P.jsx)(`option`,{value:`model`,children:y.chatTitleSourceModel})]})]}),n.strategy===`model`?(0,P.jsxs)(`div`,{className:`space-y-3`,children:[(0,P.jsx)(`label`,{htmlFor:`chat-title-model`,className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:y.chatTitleModelLabel}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:y.chatTitleModelDescription}),(0,P.jsxs)(`select`,{id:`chat-title-model`,value:n.preferredModel,onChange:e=>s(e.target.value),disabled:!n.autoRenameEnabled,className:`w-full rounded-xl px-4 py-2.5 text-sm bg-surface-container-lowest text-on-surface border border-outline-variant/20 focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20 transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-50`,children:[(0,P.jsx)(`option`,{value:`current_model`,children:y.chatTitleModelCurrent}),b.map(e=>(0,P.jsx)(`option`,{value:e.modelId,children:e.displayName},e.modelId)),r.map(e=>(0,P.jsx)(`option`,{value:e.modelId,children:e.displayName},e.modelId))]})]}):null,(0,P.jsxs)(`div`,{className:`space-y-3`,children:[(0,P.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-baseline sm:justify-between gap-1 sm:gap-4`,children:[(0,P.jsx)(`label`,{htmlFor:`chat-title-prefix-length`,className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:y.chatTitlePrefixLengthLabel}),(0,P.jsx)(`span`,{className:`text-sm font-medium text-on-surface`,children:y.chatTitlePrefixLengthHint.replace(`{value}`,String(n.promptPrefixLength))})]}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:y.chatTitlePrefixLengthDescription}),(0,P.jsx)(`input`,{id:`chat-title-prefix-length`,type:`range`,min:Cs,max:ws,step:1,value:n.promptPrefixLength,onChange:e=>o(Number(e.target.value)),disabled:!n.autoRenameEnabled,className:`w-full h-2 bg-surface-container-lowest rounded-full appearance-none cursor-pointer accent-primary disabled:cursor-not-allowed disabled:opacity-50`})]})]})]})}function Ds({label:e,value:t,min:n,max:r,disabled:i,onChange:a}){return(0,P.jsxs)(`label`,{className:`block space-y-2`,children:[(0,P.jsx)(`span`,{className:`text-sm font-semibold text-on-surface`,children:e}),(0,P.jsx)(`input`,{type:`number`,min:n,max:r,value:t,disabled:i,onChange:e=>a(Number(e.target.value)),className:`w-full rounded-xl border border-outline-variant/20 bg-surface-container-lowest px-3 py-2 text-sm text-on-surface focus:border-primary/60 focus:outline-none focus:ring-1 focus:ring-primary/20 disabled:opacity-50`})]})}var Os=S(`/_authenticated/settings/general`)({component:ks});function ks(){let e=ta();return(0,P.jsx)(Es,{imageQuality:e.settings.globalImageQuality,setImageQuality:e.settings.setGlobalImageQuality,chatTitleSettings:e.settings.chatTitleSettings,availableTitleModels:e.catalog.textModels,setChatAutoRenameEnabled:e.settings.setChatAutoRenameEnabled,setChatTitleStrategy:e.settings.setChatTitleStrategy,setChatTitlePromptPrefixLength:e.settings.setChatTitlePromptPrefixLength,setPreferredChatTitleModel:e.settings.setPreferredChatTitleModel,multiAgentSettings:e.settings.multiAgentSettings,setMultiAgentEnabled:e.settings.setMultiAgentEnabled,setChatDelegationEnabled:e.settings.setChatDelegationEnabled,setTraceVisibility:e.settings.setTraceVisibility,setMaxDelegationDepth:e.settings.setMaxDelegationDepth,setMaxSubagentCalls:e.settings.setMaxSubagentCalls,setSubagentTimeoutMs:e.settings.setSubagentTimeoutMs,setDefaultSubagentMaxTurns:e.settings.setDefaultSubagentMaxTurns})}var As=50,js=99;function Ms(e,t){return t.replace(`{value}`,String(Math.round(e*100)))}function Ns(e){return Math.round(e*100)}function Ps({settings:e,availableModels:t,setCompactionBehavior:n,setWarningThreshold:r,setDangerThreshold:i,setHardStopThreshold:a,setPreferredSummaryModel:o,setProviderCompactionEnabled:s}){let{t:c}=L(),l=c.settings.context,u=e.preferredSummaryModel!==`current_model`&&!t.some(t=>t.modelId===e.preferredSummaryModel)?[{modelId:e.preferredSummaryModel,displayName:e.preferredSummaryModel}]:[];return(0,P.jsxs)(`div`,{className:`space-y-4`,children:[(0,P.jsxs)(z,{variant:`solid`,className:`space-y-3 p-4 sm:p-6`,children:[(0,P.jsx)(`h2`,{className:`text-lg font-bold text-on-surface`,children:l.title}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/70`,children:l.description}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:l.keepHistory})]}),(0,P.jsxs)(z,{variant:`solid`,className:`space-y-3 p-4 sm:p-6`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:l.behaviorLabel}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:l.behaviorDescription}),(0,P.jsxs)(`select`,{value:e.compactionBehavior,onChange:e=>n(e.target.value),"aria-label":l.behaviorLabel,className:`w-full rounded-xl px-4 py-2.5 text-sm bg-surface-container-lowest text-on-surface border border-outline-variant/20 focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20 transition-colors cursor-pointer`,children:[(0,P.jsx)(`option`,{value:`ask`,children:l.behaviorOptions.ask}),(0,P.jsx)(`option`,{value:`auto_compact_current_chat`,children:l.behaviorOptions.autoCompact}),(0,P.jsx)(`option`,{value:`continue_with_summary_new_chat`,children:l.behaviorOptions.newChat}),(0,P.jsx)(`option`,{value:`off`,children:l.behaviorOptions.off})]})]}),(0,P.jsx)(z,{variant:`solid`,className:`space-y-3 p-4 sm:p-6`,children:(0,P.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,P.jsxs)(`div`,{className:`space-y-1`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:l.providerCompactionLabel}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:l.providerCompactionDescription})]}),(0,P.jsx)(`input`,{type:`checkbox`,checked:e.providerCompactionEnabled,onChange:e=>s(e.target.checked),"aria-label":l.providerCompactionLabel,className:`mt-1 h-4 w-4 rounded border-outline-variant/30 accent-primary`})]})}),(0,P.jsxs)(z,{variant:`solid`,className:`space-y-5 p-4 sm:p-6`,children:[(0,P.jsx)(Fs,{label:l.warningThresholdLabel,description:l.warningThresholdDescription,hint:Ms(e.warningThreshold,l.thresholdHint),value:Ns(e.warningThreshold),onChange:e=>r(e/100)}),(0,P.jsx)(Fs,{label:l.dangerThresholdLabel,description:l.dangerThresholdDescription,hint:Ms(e.dangerThreshold,l.thresholdHint),value:Ns(e.dangerThreshold),onChange:e=>i(e/100)}),(0,P.jsx)(Fs,{label:l.hardStopThresholdLabel,description:l.hardStopThresholdDescription,hint:Ms(e.hardStopThreshold,l.thresholdHint),value:Ns(e.hardStopThreshold),onChange:e=>a(e/100)})]}),(0,P.jsxs)(z,{variant:`solid`,className:`space-y-3 p-4 sm:p-6`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:l.summaryModelLabel}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:l.summaryModelDescription}),(0,P.jsxs)(`select`,{value:e.preferredSummaryModel,onChange:e=>o(e.target.value),"aria-label":l.summaryModelLabel,className:`w-full rounded-xl px-4 py-2.5 text-sm bg-surface-container-lowest text-on-surface border border-outline-variant/20 focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20 transition-colors cursor-pointer`,children:[(0,P.jsx)(`option`,{value:`current_model`,children:l.summaryModelCurrent}),u.map(e=>(0,P.jsx)(`option`,{value:e.modelId,children:e.displayName},e.modelId)),t.map(e=>(0,P.jsx)(`option`,{value:e.modelId,children:e.displayName},e.modelId))]})]})]})}function Fs({label:e,description:t,hint:n,value:r,onChange:i}){return(0,P.jsxs)(`div`,{className:`space-y-3`,children:[(0,P.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-baseline sm:justify-between gap-1 sm:gap-4`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:e}),(0,P.jsx)(`span`,{className:`text-sm font-medium text-on-surface`,children:n})]}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:t}),(0,P.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,P.jsx)(`input`,{type:`range`,min:As,max:js,step:1,value:r,onChange:e=>i(Number(e.target.value)),"aria-label":e,className:`flex-1 h-2 bg-surface-container-lowest rounded-full appearance-none cursor-pointer accent-primary`}),(0,P.jsx)(`input`,{type:`number`,min:As,max:js,step:1,value:r,onChange:e=>i(Number(e.target.value)),onBlur:e=>i(Number(e.target.value)),"aria-label":e,className:`w-20 rounded-xl px-3 py-2 text-sm text-center bg-surface-container-lowest text-on-surface border border-outline-variant/20 focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20 transition-colors`})]})]})}var Is=S(`/_authenticated/settings/context`)({component:Ls});function Ls(){let e=ta();return(0,P.jsx)(Ps,{settings:e.settings.contextSettings,availableModels:e.catalog.textModels,setCompactionBehavior:e.settings.setContextCompactionBehavior,setWarningThreshold:e.settings.setContextWarningThreshold,setDangerThreshold:e.settings.setContextDangerThreshold,setHardStopThreshold:e.settings.setContextHardStopThreshold,setPreferredSummaryModel:e.settings.setPreferredSummaryModel,setProviderCompactionEnabled:e.settings.setProviderCompactionEnabled})}var Z=I.settings.connectors,Q=class extends Error{code;constructor(e,t){if(super(V(e,t)),this.name=`ConnectorApiError`,e&&typeof e==`object`){let t=e;typeof t.code==`string`&&(this.code=t.code)}}};async function Rs(e){let{data:t,error:n}=await H.api.settings.connectors.post(e);if(n)throw new Q(n.value,Z.failedToAdd);return t}async function zs(e){let{error:t}=await H.api.settings.connectors({id:e}).delete();if(t)throw new Q(t.value,Z.failedToDelete)}async function Bs(e,t){let{error:n}=await H.api.settings.connectors({id:e}).models.put({enabledModels:t});if(n)throw new Q(n.value,Z.failedToUpdateModels)}async function Vs(e){let{data:t,error:n}=await H.api.settings.connectors.chatgpt.oauth.start.post(e);if(n)throw new Q(n.value,Z.chatgptFailedError);return t}async function Hs(e){let{data:t,error:n}=await H.api.settings.connectors.chatgpt.oauth({sessionId:e}).status.get();if(n)throw new Q(n.value,Z.chatgptFailedError);return t}async function Us(e,t){let{data:n,error:r}=await H.api.settings.connectors({id:e}).usage.reset.post({redeemRequestId:t});if(r)throw new Q(r.value,Z.chatgptRedeemFailed);return n}async function Ws(e){let{data:t,error:n}=await H.api.settings.connectors({id:e}).usage.stats.get();if(n)throw new Q(n.value,Z.failedToLoad);return t}async function Gs(e,t){let{data:n,error:r}=await H.api.settings.connectors({id:e}).usage.history.get({query:t});if(r)throw new Q(r.value,Z.failedToLoad);return n}async function Ks(e){let{error:t}=await H.api.settings.connectors.chatgpt.oauth({sessionId:e}).cancel.post();if(t)throw new Q(t.value,Z.chatgptFailedError)}var qs={UNAUTHORIZED:`UNAUTHORIZED`,METHOD_NOT_ALLOWED:`METHOD_NOT_ALLOWED`,NOT_FOUND:`NOT_FOUND`,VALIDATION:`VALIDATION`,PROVIDER_ERROR:`PROVIDER_ERROR`,OWNERSHIP:`OWNERSHIP`,RATE_LIMITED:`RATE_LIMITED`,CHATGPT_REAUTH_REQUIRED:`CHATGPT_REAUTH_REQUIRED`,INTERNAL:`INTERNAL`};M.Object({error:M.String(),code:M.Optional(M.String()),details:M.Optional(M.Record(M.String(),M.String()))}),M.Object({type:M.Literal(`error`),error:M.String(),code:M.Optional(M.String()),done:M.Literal(!0)});var Js=2e3;function Ys(e){return(e instanceof Q&&e.code===qs.PROVIDER_ERROR||e instanceof Error)&&e.message.includes(`1455`)}function Xs(e,t){return Ys(e)?t.chatgptPortBusyError:e instanceof Q&&e.code===qs.CHATGPT_REAUTH_REQUIRED?t.chatgptDeniedError:e instanceof Error&&e.message?e.message:t.chatgptFailedError}function Zs(e,t){return e.error?.includes(`1455`)?t.chatgptPortBusyError:t.chatgptDeniedError}function Qs({messages:e,onSuccess:t}){let[n,r]=(0,N.useState)(`idle`),[i,a]=(0,N.useState)(null),[o,s]=(0,N.useState)(null),c=(0,N.useRef)(t),l=(0,N.useRef)(null),u=(0,N.useRef)(!1);(0,N.useEffect)(()=>{c.current=t},[t]);let d=j({mutationFn:Vs}),f=j({mutationFn:Ks}),p=(0,N.useCallback)(()=>{l.current=null,u.current=!1,a(null),r(`idle`),s(null)},[]),m=(0,N.useCallback)((e,t=`failed`)=>{l.current=null,u.current=!1,a(null),r(t),s(e)},[]),h=(0,N.useCallback)(async({name:t,connectorId:n,popup:i})=>{let o=t.trim();if(!o){m(e.chatgptNameRequired),i?.close();return}if(!i){m(e.chatgptPopupBlocked);return}r(`starting`),s(null);try{let e=await d.mutateAsync({name:o,...n?{connectorId:n}:{}});i.location.href=e.authorizeUrl,l.current=e.sessionId,u.current=!0,a(e),r(`waiting`)}catch(t){i.close(),m(Xs(t,e))}},[m,e,d]),g=(0,N.useCallback)(async()=>{let t=l.current;if(!t){p();return}try{await f.mutateAsync(t),p()}catch(t){m(Xs(t,e))}},[f,m,e,p]);return(0,N.useEffect)(()=>{if(n!==`waiting`||!i)return;let t=!1,a=!1,o,d=async e=>{l.current=null,u.current=!1,r(`completed`),s(null),await c.current(e.connectorId)},f=async()=>{if(!(t||a)){if(Date.now()>=i.expiresAt){a=!0,m(e.chatgptExpiredError,`expired`);return}try{let n=await Hs(i.sessionId);if(t||a)return;if(n.status===`completed`){a=!0,await d(n);return}if(n.status===`failed`){a=!0,m(Zs(n,e));return}n.status===`expired`&&(a=!0,m(e.chatgptExpiredError,`expired`))}catch(n){!t&&!a&&m(Xs(n,e))}}};return f(),o=window.setInterval(()=>void f(),Js),()=>{t=!0,o!==void 0&&window.clearInterval(o)}},[m,e,n,i]),(0,N.useEffect)(()=>()=>{let e=l.current;!u.current||!e||Ks(e)},[]),{phase:n,session:i,error:o,isStarting:n===`starting`,isWaiting:n===`waiting`,isBusy:n===`starting`||n===`waiting`,start:h,cancel:g,reset:p}}function $s(e,t,n){switch(e){case`cursor.node_not_found`:return`${n.cursorNodeRequired} ${n.cursorNodeNotFound}`;case`cursor.node_invalid`:return n.cursorNodeInvalid.replace(`{path}`,t?.nodePath??`?`);case`cursor.version_insufficient`:return n.cursorNodeVersionInsufficient.replace(`{minVersion}`,pr).replace(`{version}`,t?.foundVersion??`?`);case`cursor.sidecar_missing`:return t?.sidecarPath?n.cursorSidecarMissingAt.replace(`{path}`,t.sidecarPath):n.cursorSidecarMissing;case`cursor.sdk_missing`:return t?.sidecarPath?n.cursorSdkMissingAt.replace(`{path}`,t.sidecarPath):n.cursorSdkMissing;case`cursor.sdk_incomplete`:return t?.sidecarPath?n.cursorSdkIncompleteAt.replace(`{path}`,t.sidecarPath):n.cursorSdkIncomplete;case`cursor.native_runtime_missing`:return t?.packageName?n.cursorNativeRuntimeMissingPackage.replace(`{packageName}`,t.packageName):n.cursorNativeRuntimeMissing;default:return}}var ec=[{id:`gemini`},{id:`openai`},{id:`openai-compatible`},{id:`anthropic`},{id:`deepseek`},{id:`cursor`},{id:`chatgpt`}];function tc({form:e,setForm:t,isSaving:n,formError:r,showKey:i,setShowKey:a,onSubmit:o,onOAuthSuccess:c,onClose:l}){let{t:d}=L(),f=d.settings.connectors,{data:p}=k(Fi()),m=e.provider===`chatgpt`,g=Qs({messages:f,onSuccess:c}),_=e=>p?.providers.find(t=>t.provider===e)?.runtimeAvailable===!1,v=e=>{let t=p?.providers.find(t=>t.provider===e);if(t?.runtimeAvailable===!1)return $s(t.runtimeUnavailableReason,t.runtimeUnavailableReasonParams,f)},y=[{id:`bun-secrets`,label:f.sources.bunSecrets,icon:(0,P.jsx)(Se,{size:16}),desc:f.sources.bunSecretsDesc},{id:`config-file`,label:f.sources.configFile,icon:(0,P.jsx)(ie,{size:16}),desc:f.sources.configFileDesc},{id:`environment`,label:f.sources.envFile,icon:(0,P.jsx)(h,{size:16}),desc:f.sources.envFileDesc}],b=ec.flatMap(({id:e})=>{if(!_(e))return[];let t=v(e);return t?[{id:e,hint:t}]:[]}),x=_(`cursor`);return(0,P.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm animate-in fade-in duration-200`,children:(0,P.jsxs)(`div`,{className:`bg-surface-container-high w-full max-w-lg rounded-3xl p-5 sm:p-8 shadow-2xl border border-outline-variant/20 flex flex-col max-h-[90vh] sm:max-h-[85vh]`,children:[(0,P.jsxs)(`div`,{className:`space-y-2 mb-5 sm:mb-6`,children:[(0,P.jsx)(`h3`,{className:`text-xl font-bold text-on-surface`,children:f.addModalTitle}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/70`,children:m?f.chatgptAddModalDescription:f.addModalDescription})]}),(0,P.jsxs)(`div`,{className:`flex-1 overflow-y-auto hide-scrollbar pr-1 space-y-4 min-h-0`,children:[(0,P.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,P.jsx)(`span`,{className:`text-sm font-medium text-on-surface-variant`,children:f.providerLabel}),(0,P.jsx)(`div`,{className:`grid grid-cols-2 sm:grid-cols-3 gap-2`,children:ec.map(({id:n})=>{let r=_(n);return(0,P.jsx)(`button`,{type:`button`,disabled:r,onClick:()=>{r||t({...e,provider:n,apiKey:n===`chatgpt`?``:e.apiKey,source:n===`chatgpt`?`bun-secrets`:e.source,baseUrl:n===`openai-compatible`||n===`deepseek`?e.baseUrl:``})},className:`min-h-11 py-2.5 px-3 rounded-xl border text-xs sm:text-sm font-semibold text-center leading-snug transition-all ${r?`opacity-40 cursor-not-allowed bg-surface-container-lowest border-outline-variant/10 text-on-surface-variant`:e.provider===n?`bg-primary/10 border-primary text-primary`:`bg-surface-container-lowest border-outline-variant/10 text-on-surface hover:border-outline-variant/30`}`,children:d.providers[n]},n)})}),b.length>0?(0,P.jsxs)(`div`,{className:`mt-1 rounded-xl border border-outline-variant/15 bg-surface-container-lowest px-3 py-2.5 space-y-1.5`,children:[b.map(({id:e,hint:t})=>(0,P.jsxs)(`p`,{className:`text-[11px] leading-snug text-on-surface-variant/70`,children:[(0,P.jsxs)(`span`,{className:`font-semibold text-on-surface-variant`,children:[d.providers[e],`:`]}),` `,t]},e)),x?(0,P.jsx)(`p`,{className:`text-[11px] leading-snug text-on-surface-variant/70`,children:f.cursorRuntimeDoctorHint}):null]}):null]}),(0,P.jsx)(B,{id:`connector-name`,label:f.nameLabel,type:`text`,value:e.name,onChange:n=>t({...e,name:n.target.value}),placeholder:f.namePlaceholder}),m?(0,P.jsxs)(`div`,{className:`rounded-2xl border border-outline-variant/15 bg-surface-container-lowest p-4 space-y-3`,children:[(0,P.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,P.jsx)(`div`,{className:`mt-0.5 rounded-xl bg-primary/10 p-2 text-primary`,children:(0,P.jsx)(se,{size:18})}),(0,P.jsxs)(`div`,{className:`space-y-1`,children:[(0,P.jsx)(`p`,{className:`text-sm font-bold text-on-surface`,children:f.chatgptOAuthTitle}),(0,P.jsx)(`p`,{className:`text-xs leading-relaxed text-on-surface-variant/65`,children:f.chatgptOAuthDescription})]})]}),g.isWaiting?(0,P.jsxs)(`div`,{className:`rounded-xl border border-primary/20 bg-primary/10 p-3 space-y-2`,children:[(0,P.jsx)(`p`,{className:`text-xs font-bold text-primary`,children:f.chatgptWaitingTitle}),(0,P.jsx)(`p`,{className:`text-xs leading-relaxed text-on-surface-variant/75`,children:f.chatgptWaitingDescription}),(0,P.jsx)(`p`,{className:`text-[11px] leading-relaxed text-on-surface-variant/55`,children:f.chatgptRemoteAccessHint}),(0,P.jsx)(R,{type:`button`,variant:`secondary`,size:`sm`,onClick:()=>void g.cancel(),className:`w-full`,children:f.chatgptCancelSignIn})]}):null,g.error?(0,P.jsxs)(`div`,{className:`flex items-start gap-2 rounded-xl border border-error/20 bg-error/10 p-3 text-xs text-error`,children:[(0,P.jsx)(ze,{size:15,className:`mt-0.5 shrink-0`}),(0,P.jsx)(`span`,{children:g.error})]}):null]}):null,!m&&(e.provider===`openai-compatible`||e.provider===`deepseek`)&&(0,P.jsx)(B,{id:`connector-baseurl`,label:f.baseUrlLabel,type:`text`,value:e.baseUrl,onChange:n=>t({...e,baseUrl:n.target.value}),placeholder:e.provider===`deepseek`?f.deepseekBaseUrlPlaceholder:f.baseUrlPlaceholder}),!m&&e.provider===`openai`&&(0,P.jsxs)(P.Fragment,{children:[(0,P.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,P.jsx)(B,{id:`connector-organization-id`,label:f.organizationIdLabel,type:`text`,value:e.organizationId,onChange:n=>t({...e,organizationId:n.target.value}),placeholder:f.organizationIdPlaceholder}),(0,P.jsx)(`p`,{className:`text-[10px] text-on-surface-variant/50 ml-1`,children:f.organizationIdHelper})]}),(0,P.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,P.jsx)(B,{id:`connector-project-id`,label:f.projectIdLabel,type:`text`,value:e.projectId,onChange:n=>t({...e,projectId:n.target.value}),placeholder:f.projectIdPlaceholder}),(0,P.jsx)(`p`,{className:`text-[10px] text-on-surface-variant/50 ml-1`,children:f.projectIdHelper})]})]}),!m&&(0,P.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,P.jsx)(`label`,{htmlFor:`connector-apikey`,className:`text-sm font-medium text-on-surface-variant`,children:f.apiKeyLabel}),(0,P.jsxs)(`div`,{className:`flex gap-2`,children:[(0,P.jsx)(`input`,{id:`connector-apikey`,type:i?`text`:`password`,value:e.apiKey,onChange:n=>t({...e,apiKey:n.target.value}),className:`
72
+ flex-1 rounded-xl px-4 py-2.5 text-sm
73
+ bg-surface-container-high text-on-surface
74
+ border border-outline-variant/20
75
+ placeholder:text-on-surface/30
76
+ focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20
77
+ transition-colors
78
+ `,placeholder:f.apiKeyPlaceholder}),(0,P.jsx)(R,{variant:`secondary`,size:`md`,onClick:()=>a(!i),className:`px-3`,type:`button`,children:i?(0,P.jsx)(s,{size:18}):(0,P.jsx)($e,{size:18})})]})]}),!m&&(0,P.jsxs)(`div`,{className:`space-y-3`,children:[(0,P.jsx)(`span`,{className:`text-xs font-bold text-on-surface-variant uppercase ml-1`,children:f.saveToLabel}),(0,P.jsx)(`div`,{className:`grid grid-cols-1 gap-2`,children:y.map(n=>(0,P.jsxs)(`button`,{type:`button`,onClick:()=>t({...e,source:n.id}),className:`flex items-start gap-4 p-4 rounded-2xl border text-left transition-all ${e.source===n.id?`bg-primary/10 border-primary text-primary`:`bg-surface-container-lowest border-outline-variant/10 text-on-surface hover:border-outline-variant/30`}`,children:[(0,P.jsx)(`div`,{className:`mt-1`,children:n.icon}),(0,P.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,P.jsx)(`div`,{className:`text-sm font-bold`,children:n.label}),(0,P.jsx)(`div`,{className:`text-[10px] ${e.source===n.id?`text-primary/70`:`text-on-surface-variant/60`}`,children:n.desc})]})]},n.id))})]})]}),!m&&r?(0,P.jsx)(`p`,{className:`mt-4 text-xs text-error font-medium text-center shrink-0`,children:r}):null,(0,P.jsxs)(`div`,{className:`flex gap-3 pt-4 sm:pt-5 shrink-0`,children:[(0,P.jsx)(R,{variant:`secondary`,onClick:l,className:`flex-1`,children:f.cancelButton}),(0,P.jsx)(R,{variant:`primary`,onClick:m?()=>{let t=window.open(`about:blank`,`_blank`);g.start({name:e.name,popup:t})}:o,loading:m?g.isStarting:n,disabled:m?g.isBusy:n,className:`flex-1`,children:m?g.isBusy?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(u,{size:16,className:`animate-spin`}),g.isWaiting?f.chatgptReauthenticating:f.chatgptSigningIn]}):(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(se,{size:16}),f.chatgptSignInButton]}):n?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(u,{size:16,className:`animate-spin`}),f.validating]}):f.addConnectorButton})]})]})})}var nc=[75,90],rc=new Map,ic=[`primary`,`secondary`];function ac(e,t,n){let r=[],i=new Map;for(let a of t)if(a.usage)for(let t of ic){let o=a.usage[t];if(!o)continue;let s=`${a.id}:${t}`,c=e.get(s);if(i.set(s,{usedPercent:o.usedPercent}),n===null)continue;let l={connectorId:a.id,connectorName:a.name,window:t,usedPercent:o.usedPercent};c&&c.usedPercent>=100&&o.usedPercent<c.usedPercent?r.push({kind:`reset`,...l}):o.usedPercent>=n&&(c===void 0||c.usedPercent<n)&&r.push({kind:`threshold`,...l})}return{events:r,next:i}}var oc=e=>`mango.chatgpt-promo-dismissed:${e}`;function sc(e){try{return window.localStorage.getItem(oc(e))}catch{return null}}function cc({connectorId:e,message:t}){let{t:n}=L(),[r,i]=(0,N.useState)(()=>sc(e));return r===t?null:(0,P.jsxs)(`div`,{className:`mt-1.5 flex max-w-xs items-start gap-2 rounded-xl border border-primary/20 bg-primary/5 px-3 py-2`,children:[(0,P.jsx)(l,{size:14,className:`mt-0.5 shrink-0 text-primary/80`}),(0,P.jsx)(`p`,{className:`flex-1 text-[11px] leading-relaxed text-on-surface-variant`,children:t}),(0,P.jsx)(`button`,{type:`button`,onClick:()=>{i(t);try{window.localStorage.setItem(oc(e),t)}catch{}},title:n.settings.connectors.chatgptPromoDismiss,"aria-label":n.settings.connectors.chatgptPromoDismiss,className:`shrink-0 cursor-pointer opacity-50 transition-opacity hover:opacity-100`,children:(0,P.jsx)(Ue,{size:12})})]})}function lc(e,t,n){switch(e){case`reset`:return{message:n.chatgptRedeemSuccess.replace(`{count}`,String(t)),type:`success`};case`nothing_to_reset`:return{message:n.chatgptRedeemNothingToReset,type:`info`};case`no_credit`:return{message:n.chatgptRedeemNoCredit,type:`error`};case`already_redeemed`:return{message:n.chatgptRedeemAlreadyRedeemed,type:`info`}}}function uc({connectorId:e,messages:t,toast:n,onSettled:r}){let[i,a]=(0,N.useState)(!1),o=(0,N.useRef)(null);return{redeem:(0,N.useCallback)(async()=>{o.current===null&&(o.current=crypto.randomUUID());let i=o.current;a(!0);try{let r=await Us(e,i);o.current=null;let{message:a,type:s}=lc(r.code,r.windowsReset,t);n(a,s)}catch{n(t.chatgptRedeemFailed,`error`)}finally{a(!1),await r?.()}},[e,t,n,r]),isRedeeming:i}}function dc({connector:e,onRedeemed:t}){let{t:n}=L(),{toast:r}=F(),i=n.settings.connectors,[a,o]=(0,N.useState)(!1),{redeem:s,isRedeeming:c}=uc({connectorId:e.id,messages:i,toast:r,onSettled:t}),l=e.usage?.resetCredits?.availableCount??0;return!e.usage?.limitReached||l<1?null:(0,P.jsxs)(`div`,{className:`mt-1.5`,children:[(0,P.jsx)(R,{variant:`secondary`,size:`sm`,onClick:()=>o(!0),disabled:c,children:c?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(ge,{size:14,className:`animate-spin`}),i.chatgptRedeeming]}):(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(Le,{size:14}),i.chatgptRedeemButton]})}),a&&(0,P.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm animate-in fade-in duration-200`,children:(0,P.jsxs)(`div`,{className:`bg-surface-container-high w-full max-w-sm rounded-3xl p-5 sm:p-8 shadow-2xl border border-outline-variant/20 space-y-5 sm:space-y-6`,children:[(0,P.jsxs)(`div`,{className:`space-y-2 text-center`,children:[(0,P.jsx)(`div`,{className:`p-4 bg-primary/10 rounded-full w-fit mx-auto text-primary mb-2`,children:(0,P.jsx)(Le,{size:32})}),(0,P.jsx)(`h3`,{className:`text-xl font-bold text-on-surface`,children:i.chatgptRedeemConfirmTitle}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/70`,children:i.chatgptRedeemConfirmBody.replace(`{count}`,String(l))})]}),(0,P.jsxs)(`div`,{className:`flex gap-3`,children:[(0,P.jsx)(R,{variant:`secondary`,onClick:()=>o(!1),className:`flex-1`,children:i.cancelButton}),(0,P.jsx)(R,{variant:`primary`,onClick:()=>{o(!1),s()},className:`flex-1`,children:i.chatgptRedeemConfirmAction})]})]})})]})}var fc=7,pc=6e4,mc=300,hc=72,gc=6,_c=e=>[`chatgpt-usage-history`,e,fc];function vc(e,t){return new Intl.DateTimeFormat(t,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`}).format(new Date(e))}function yc(e,t){let n=t-fc*24*60*6e4,r=t-n,i=hc-gc*2;return e.map((t,a)=>{let o=e[a-1],s=Math.min(100,Math.max(0,t.usedPercent));return{x:(Math.max(t.sampledAt,n)-n)/r*mc,y:hc-gc-s/100*i,sample:t,resetBoundary:o!==void 0&&t.usedPercent<o.usedPercent}})}function bc({samples:e,locale:t,s:n}){let r=n.chatgptHistoryChartTitle.replace(`{days}`,String(fc)),i=yc(e,Date.now()),a=i.map(e=>`${e.x},${e.y}`).join(` `),o=i[0],s=i[i.length-1],c=o&&s?`${o.x},${hc-gc} ${a} ${s.x},${hc-gc}`:``;return(0,P.jsxs)(`div`,{className:`space-y-2`,children:[(0,P.jsx)(`p`,{className:`text-[10px] font-medium uppercase text-on-surface-variant/55`,children:r}),(0,P.jsxs)(`svg`,{role:`img`,"aria-label":r,viewBox:`0 0 ${mc} ${hc}`,className:`h-20 w-full rounded-lg border border-outline-variant/10 bg-surface-container-high/35`,preserveAspectRatio:`none`,children:[i.length>1&&(0,P.jsx)(`polygon`,{points:c,className:`fill-primary/15`,stroke:`none`}),i.length>1&&(0,P.jsx)(`polyline`,{points:a,fill:`none`,strokeWidth:2,vectorEffect:`non-scaling-stroke`,className:`stroke-primary/70`}),i.filter(e=>e.resetBoundary).map(e=>(0,P.jsx)(`line`,{x1:e.x,y1:gc,x2:e.x,y2:hc-gc,strokeDasharray:`3 3`,vectorEffect:`non-scaling-stroke`,className:`stroke-outline-variant/60`},`reset-${e.sample.sampledAt}`)),i.map(e=>{let r=n.chatgptHistoryPoint.replace(`{time}`,vc(e.sample.sampledAt,t)).replace(`{percent}`,String(Math.round(e.sample.usedPercent)));return(0,P.jsx)(`circle`,{cx:e.x,cy:e.y,r:3,className:`fill-primary/80`,children:(0,P.jsx)(`title`,{children:r})},e.sample.sampledAt)})]}),(0,P.jsx)(`p`,{className:`text-[10px] text-on-surface-variant/50`,children:n.chatgptHistoryDisclaimer})]})}function xc({connectorId:e}){let{t,locale:n}=L(),r=t.settings.connectors,[i,a]=(0,N.useState)(!1),o=`chatgpt-usage-history-${e}`,s=k({queryKey:_c(e),queryFn:()=>Gs(e,{window:`secondary`,days:fc}),enabled:i,staleTime:pc}),c=s.data?.samples??[];return(0,P.jsxs)(`div`,{className:`mt-1.5 max-w-xs space-y-2`,children:[(0,P.jsxs)(R,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>a(e=>!e),"aria-expanded":i,"aria-controls":o,className:`px-2`,children:[(0,P.jsx)(ee,{size:14}),r.chatgptHistoryToggle,(0,P.jsx)(E,{size:14,className:`transition-transform ${i?`rotate-180`:``}`})]}),i&&(0,P.jsx)(`div`,{id:o,className:`space-y-3 rounded-xl border border-outline-variant/10 bg-surface-container-low px-3 py-3`,children:s.isLoading||s.isFetching?(0,P.jsxs)(`p`,{className:`flex items-center gap-2 text-[11px] text-on-surface-variant/60`,children:[(0,P.jsx)(ge,{size:13,className:`animate-spin`}),r.chatgptHistoryLoading]}):s.isError?(0,P.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,P.jsxs)(`p`,{className:`flex items-center gap-2 text-[11px] text-error`,children:[(0,P.jsx)(ze,{size:13}),r.failedToLoad]}),(0,P.jsxs)(R,{variant:`ghost`,size:`sm`,onClick:()=>void s.refetch(),children:[(0,P.jsx)(ge,{size:13}),t.common.retry]})]}):c.length===0?(0,P.jsx)(`p`,{className:`text-[11px] text-on-surface-variant/60`,children:r.chatgptHistoryEmpty}):(0,P.jsx)(bc,{samples:c,locale:n,s:r})})]})}function Sc(e){return Math.min(100,Math.max(0,e))}function Cc(e,t){if(e.windowMinutes===void 0||e.resetsAt===void 0)return null;let n=e.windowMinutes*6e4;if(n<=0||e.resetsAt<=t)return null;let r=Math.min(n,Math.max(0,t-(e.resetsAt-n))),i=r/n*100,a=Sc(e.usedPercent);if(a>=100)return{status:`runningHot`,elapsedPercent:i,projectedExhaustionAt:t};if(r<=0||a<=i)return{status:`onPace`,elapsedPercent:i};let o=t+(100-a)/(a/r);return{status:`runningHot`,elapsedPercent:i,projectedExhaustionAt:Math.min(o,e.resetsAt)}}var wc=5*6e4;function Tc(e){let t=Math.max(1,Math.round(e/6e4));if(t<60)return`${t}m`;let n=Math.floor(t/60);if(n<24){let e=t%60;return e>0?`${n}h ${e}m`:`${n}h`}let r=Math.floor(n/24),i=n%24;return i>0?`${r}d ${i}h`:`${r}d`}function Ec(e,t,n){if(e.windowMinutes===void 0)return t;let r=e.windowMinutes/60;return r>=24?n.chatgptUsageWindowDays.replace(`{days}`,String(Math.round(r/24))):n.chatgptUsageWindowHours.replace(`{hours}`,String(Math.round(r)))}function Dc({window:e,fallbackLabel:t,s:n,now:r}){let i=Math.min(100,Math.max(0,e.usedPercent)),a=e.resetsAt!==void 0&&e.resetsAt>r,o=Cc(e,r),s=o&&(o.status===`runningHot`?o.projectedExhaustionAt!==void 0&&o.projectedExhaustionAt>r?`${n.chatgptPaceRunningHot} · ${n.chatgptPaceProjected.replace(`{time}`,Tc(o.projectedExhaustionAt-r))}`:n.chatgptPaceRunningHot:n.chatgptPaceOnPace);return(0,P.jsxs)(`div`,{className:`space-y-1`,children:[(0,P.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-[10px] text-on-surface-variant/60`,children:[(0,P.jsx)(`span`,{children:Ec(e,t,n)}),(0,P.jsxs)(`span`,{children:[n.chatgptUsageUsed.replace(`{percent}`,String(Math.round(i))),a&&` · ${n.chatgptUsageResets.replace(`{time}`,Tc(e.resetsAt-r))}`,s&&(0,P.jsxs)(P.Fragment,{children:[` · `,(0,P.jsx)(`span`,{className:o?.status===`runningHot`?`text-amber-200/90`:void 0,children:s})]})]})]}),(0,P.jsx)(`div`,{role:`progressbar`,"aria-valuenow":Math.round(i),"aria-valuemin":0,"aria-valuemax":100,className:`h-1.5 overflow-hidden rounded-full bg-surface-container-high`,children:(0,P.jsx)(`div`,{className:`h-full rounded-full ${i>=90?`bg-error/80`:`bg-primary/70`}`,style:{width:`${i}%`}})})]})}function Oc({usage:e}){let{t}=L(),n=t.settings.connectors,r=Date.now(),i=[];if(e.resetCredits&&e.resetCredits.availableCount>0){let t=n.chatgptUsageResetCredits.replace(`{count}`,String(e.resetCredits.availableCount));e.resetCredits.nextExpiresAt!==void 0&&e.resetCredits.nextExpiresAt>r&&(t+=` · ${n.chatgptUsageResetCreditsNextExpiry.replace(`{time}`,Tc(e.resetCredits.nextExpiresAt-r))}`),i.push(t)}return e.credits?.unlimited?i.push(n.chatgptUsageCreditsUnlimited):e.credits?.balance!==void 0&&i.push(n.chatgptUsageCreditsBalance.replace(`{balance}`,String(e.credits.balance))),r-e.capturedAt>wc&&i.push(n.chatgptUsageUpdated.replace(`{time}`,Tc(r-e.capturedAt))),(0,P.jsxs)(`div`,{className:`mt-1.5 max-w-xs space-y-1.5`,children:[e.limitReached&&(0,P.jsx)(`p`,{className:`text-[11px] font-medium text-amber-200/90`,children:n.chatgptUsageLimitReached}),e.primary&&(0,P.jsx)(Dc,{window:e.primary,fallbackLabel:n.chatgptUsagePrimaryFallback,s:n,now:r}),e.secondary&&(0,P.jsx)(Dc,{window:e.secondary,fallbackLabel:n.chatgptUsageSecondaryFallback,s:n,now:r}),i.length>0&&(0,P.jsx)(`p`,{className:`text-[10px] text-on-surface-variant/50`,children:i.join(` · `)})]})}var kc=30,Ac=6e4,jc=e=>[`chatgpt-usage-stats`,e];function Mc(e,t){return new Intl.NumberFormat(t,{maximumFractionDigits:0}).format(Math.round(e))}function Nc(e,t){let n=new Date(`${e}T12:00:00`);return Number.isNaN(n.getTime())?e:new Intl.DateTimeFormat(t,{month:`short`,day:`numeric`}).format(n)}function Pc(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60){let e=t%60;return e>0?`${n}m ${e}s`:`${n}m`}let r=Math.floor(n/60),i=n%60;return i>0?`${r}h ${i}m`:`${r}h`}function Fc(e){return(e.dailyUsage??[]).filter(e=>Number.isFinite(e.tokens)).map(e=>({startDate:String(e.startDate),tokens:Math.max(0,e.tokens)})).sort((e,t)=>e.startDate.localeCompare(t.startDate)).slice(-kc)}function Ic(e,t){return e.lifetimeTokens!==void 0||e.peakDailyTokens!==void 0||e.longestRunningTurnSec!==void 0||e.currentStreakDays!==void 0||e.longestStreakDays!==void 0||t.length>0}function Lc({label:e,value:t}){return(0,P.jsxs)(`div`,{className:`min-w-0 rounded-lg border border-outline-variant/10 bg-surface-container-high/50 px-2.5 py-2`,children:[(0,P.jsx)(`p`,{className:`truncate text-[10px] font-medium text-on-surface-variant/55`,children:e}),(0,P.jsx)(`p`,{className:`mt-0.5 truncate font-mono text-sm text-on-surface`,children:t})]})}function Rc({buckets:e,locale:t,s:n}){let r=Math.max(...e.map(e=>e.tokens),0);return(0,P.jsxs)(`div`,{className:`space-y-2`,children:[(0,P.jsx)(`p`,{className:`text-[10px] font-medium uppercase text-on-surface-variant/55`,children:n.chatgptStatsChartTitle}),(0,P.jsx)(`div`,{role:`img`,"aria-label":n.chatgptStatsChartTitle,className:`flex h-20 items-end gap-1 rounded-lg border border-outline-variant/10 bg-surface-container-high/35 px-2 py-2`,children:e.map(e=>{let i=r>0?e.tokens/r*100:0,a=Nc(e.startDate,t),o=Mc(e.tokens,t),s=n.chatgptStatsDayTokens.replace(`{date}`,a).replace(`{tokens}`,o);return(0,P.jsx)(`div`,{title:s,className:`min-w-1 flex-1 rounded-sm bg-primary/65`,style:{height:e.tokens>0?`${Math.max(8,i)}%`:`2px`},children:(0,P.jsx)(`span`,{className:`sr-only`,children:s})},`${e.startDate}:${e.tokens}`)})})]})}function zc({stats:e,locale:t,s:n}){let r=(0,N.useMemo)(()=>e?Fc(e):[],[e]);if(!e||!Ic(e,r))return(0,P.jsx)(`p`,{className:`text-[11px] text-on-surface-variant/60`,children:n.chatgptStatsEmpty});let i=e=>n.chatgptStatsStreakValue.replace(`{days}`,Mc(e,t));return(0,P.jsxs)(`div`,{className:`space-y-3`,children:[(0,P.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[e.lifetimeTokens!==void 0&&(0,P.jsx)(Lc,{label:n.chatgptStatsLifetime,value:Mc(e.lifetimeTokens,t)}),e.peakDailyTokens!==void 0&&(0,P.jsx)(Lc,{label:n.chatgptStatsPeakDay,value:Mc(e.peakDailyTokens,t)}),e.longestRunningTurnSec!==void 0&&(0,P.jsx)(Lc,{label:n.chatgptStatsLongestTurn,value:Pc(e.longestRunningTurnSec)}),e.currentStreakDays!==void 0&&(0,P.jsx)(Lc,{label:n.chatgptStatsCurrentStreak,value:i(e.currentStreakDays)}),e.longestStreakDays!==void 0&&(0,P.jsx)(Lc,{label:n.chatgptStatsLongestStreak,value:i(e.longestStreakDays)})]}),r.length>0&&(0,P.jsx)(Rc,{buckets:r,locale:t,s:n})]})}function Bc({connectorId:e}){let{t,locale:n}=L(),r=t.settings.connectors,[i,a]=(0,N.useState)(!1),o=`chatgpt-usage-stats-${e}`,s=k({queryKey:jc(e),queryFn:()=>Ws(e),enabled:i,staleTime:Ac});return(0,P.jsxs)(`div`,{className:`mt-1.5 max-w-xs space-y-2`,children:[(0,P.jsxs)(R,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>a(e=>!e),"aria-expanded":i,"aria-controls":o,className:`px-2`,children:[(0,P.jsx)(we,{size:14}),r.chatgptStatsToggle,(0,P.jsx)(E,{size:14,className:`transition-transform ${i?`rotate-180`:``}`})]}),i&&(0,P.jsx)(`div`,{id:o,className:`space-y-3 rounded-xl border border-outline-variant/10 bg-surface-container-low px-3 py-3`,children:s.isLoading||s.isFetching?(0,P.jsxs)(`p`,{className:`flex items-center gap-2 text-[11px] text-on-surface-variant/60`,children:[(0,P.jsx)(ge,{size:13,className:`animate-spin`}),r.chatgptStatsLoading]}):s.isError?(0,P.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,P.jsxs)(`p`,{className:`flex items-center gap-2 text-[11px] text-error`,children:[(0,P.jsx)(ze,{size:13}),r.failedToLoad]}),(0,P.jsxs)(R,{variant:`ghost`,size:`sm`,onClick:()=>void s.refetch(),children:[(0,P.jsx)(ge,{size:13}),t.common.retry]})]}):(0,P.jsx)(zc,{stats:s.data?.stats??null,locale:n,s:r})})]})}function Vc(e){return e.userId===null&&e.source!==`config-file`&&e.source!==`environment`}function Hc(e,t){let n=e?.toLowerCase()??``;switch(n){case`plus`:return t.chatgptPlanPlus;case`pro`:return t.chatgptPlanPro;case`team`:return t.chatgptPlanTeam;case`free`:return t.chatgptPlanFree;case``:return t.chatgptPlanUnknown;default:return t.chatgptPlanCustom.replace(`{plan}`,e??n)}}function Uc({connector:e,onConfigure:t,onDelete:n,onReauthenticated:r,onUsageChanged:i}){let{t:a}=L(),o=a.settings.connectors,s=Vc(e),c=e.provider===`chatgpt`,l=Qs({messages:o,onSuccess:async()=>{await r(e)}}),u=Hc(e.planType,o);return(0,P.jsxs)(`div`,{className:`bg-surface-container-lowest border rounded-2xl p-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4 ${e.needsReauth?`border-amber-500/30`:`border-outline-variant/10`}`,children:[(0,P.jsxs)(`div`,{className:`flex items-start gap-4`,children:[(0,P.jsx)(`div`,{className:`p-2.5 rounded-xl ${e.needsReauth?`bg-amber-500/10 text-amber-200`:e.configured?`bg-primary/10 text-primary`:`bg-error/10 text-error/80`}`,children:e.needsReauth?(0,P.jsx)(ze,{size:20}):e.configured?(0,P.jsx)(me,{size:20}):(0,P.jsx)(He,{size:20})}),(0,P.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,P.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[(0,P.jsx)(`h3`,{className:`font-bold text-on-surface`,children:e.name}),(0,P.jsx)(`span`,{className:`text-[10px] px-2 py-0.5 rounded-full bg-surface-container-high text-on-surface-variant border border-outline-variant/20`,children:a.providers[e.provider]}),s&&(0,P.jsx)(`span`,{className:`text-[10px] px-2 py-0.5 rounded-full bg-amber-500/10 text-amber-200 border border-amber-500/20`,children:o.sharedConnector})]}),(0,P.jsxs)(`div`,{className:`flex items-center gap-2 text-xs`,children:[(0,P.jsxs)(`span`,{className:`flex items-center gap-1 text-on-surface-variant/60`,children:[e.source===`bun-secrets`&&(0,P.jsx)(Se,{size:12}),e.source===`config-file`&&(0,P.jsx)(ie,{size:12}),e.source===`environment`&&(0,P.jsx)(h,{size:12}),e.source.replace(`-`,` `)]}),(0,P.jsx)(`span`,{className:`text-outline-variant`,children:`•`}),c?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(`span`,{className:`text-on-surface-variant/60`,children:o.chatgptSignedInAs.replace(`{account}`,e.accountLabel??e.maskedSuffix??o.chatgptAccountUnknown)}),(0,P.jsx)(`span`,{className:`text-outline-variant`,children:`•`}),(0,P.jsx)(`span`,{className:`rounded-full border border-outline-variant/20 bg-surface-container-high px-2 py-0.5 text-[10px] text-on-surface-variant`,children:o.chatgptPlanBadge.replace(`{plan}`,u)})]}):(0,P.jsx)(`span`,{className:`font-mono text-on-surface-variant/60`,children:e.maskedSuffix??`****`})]}),c&&e.needsReauth?(0,P.jsx)(`p`,{className:`text-[11px] leading-relaxed text-amber-200/80`,children:o.chatgptReauthWarning}):null,c&&!e.needsReauth?(0,P.jsxs)(P.Fragment,{children:[e.usage?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(Oc,{usage:e.usage}),(0,P.jsx)(dc,{connector:e,onRedeemed:i}),e.usage.promoMessage?(0,P.jsx)(cc,{connectorId:e.id,message:e.usage.promoMessage}):null]}):null,(0,P.jsx)(xc,{connectorId:e.id}),(0,P.jsx)(Bc,{connectorId:e.id})]}):null,l.error?(0,P.jsx)(`p`,{className:`text-[11px] leading-relaxed text-error`,children:l.error}):null,s&&(0,P.jsx)(`p`,{className:`text-[10px] text-on-surface-variant/50`,children:o.managedExternally})]})]}),(0,P.jsxs)(`div`,{className:`flex items-center gap-2`,children:[c&&e.needsReauth?(0,P.jsx)(R,{variant:`secondary`,size:`sm`,onClick:()=>{let t=window.open(`about:blank`,`_blank`);l.start({name:e.name,connectorId:e.id,popup:t})},disabled:l.isBusy,children:l.isBusy?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(ge,{size:15,className:`animate-spin`}),o.chatgptReauthenticating]}):(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(ge,{size:15}),o.chatgptReauthenticate]})}):null,(0,P.jsx)(R,{variant:`ghost`,size:`sm`,onClick:()=>t(e),title:o.configureModels,className:`p-2`,children:(0,P.jsx)(Te,{size:18})}),(0,P.jsx)(R,{variant:`ghost`,size:`sm`,onClick:()=>n(e),title:s?o.sharedDeleteBlocked:o.deleteConnector,className:`p-2 text-error/70 hover:text-error hover:bg-error/10 disabled:opacity-40 disabled:hover:bg-transparent`,disabled:s,children:(0,P.jsx)(Ge,{size:18})})]})]})}function Wc({connectors:e,alertThreshold:t,onAlertThresholdChange:n,onAddConnector:r,onConfigureConnector:i,onDeleteConnector:a,onReauthenticatedConnector:o,onUsageChanged:s}){let{t:c}=L(),l=c.settings.connectors,u=e.some(e=>e.provider===`chatgpt`);return(0,P.jsxs)(z,{variant:`solid`,className:`p-4 sm:p-6 space-y-4`,children:[(0,P.jsxs)(`div`,{className:`flex items-center justify-between gap-3 flex-wrap`,children:[(0,P.jsx)(`h2`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:l.title}),(0,P.jsxs)(`div`,{className:`flex items-center gap-3`,children:[u&&(0,P.jsxs)(`label`,{className:`flex items-center gap-1.5 text-[10px] text-on-surface-variant/60`,children:[l.chatgptAlertThresholdLabel,(0,P.jsxs)(`select`,{value:t===null?`off`:String(t),onChange:e=>n(e.target.value===`off`?null:Number(e.target.value)),className:`rounded-lg border border-outline-variant/20 bg-surface-container-high px-2 py-1 text-xs text-on-surface`,children:[(0,P.jsx)(`option`,{value:`off`,children:l.chatgptAlertThresholdOff}),nc.map(e=>(0,P.jsx)(`option`,{value:e,children:l.chatgptAlertThresholdOption.replace(`{percent}`,String(e))},e))]})]}),(0,P.jsxs)(R,{variant:`secondary`,size:`sm`,onClick:r,className:`gap-1.5`,children:[(0,P.jsx)(`span`,{className:`text-base leading-none`,children:`+`}),l.addButton]})]})]}),e.length===0?(0,P.jsxs)(`div`,{className:`bg-surface-container-lowest border border-dashed border-outline-variant/30 rounded-2xl p-8 text-center space-y-4`,children:[(0,P.jsx)(`div`,{className:`p-4 bg-surface-container-high rounded-full w-fit mx-auto text-on-surface-variant/40`,children:(0,P.jsx)(Me,{size:32})}),(0,P.jsxs)(`div`,{className:`space-y-1`,children:[(0,P.jsx)(`p`,{className:`text-on-surface font-bold`,children:l.emptyTitle}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:l.emptyDescription})]}),(0,P.jsx)(R,{variant:`primary`,onClick:r,children:l.addConnectorButton})]}):(0,P.jsx)(`div`,{className:`grid grid-cols-1 gap-3`,children:e.map(e=>(0,P.jsx)(Uc,{connector:e,onConfigure:i,onDelete:a,onReauthenticated:o,onUsageChanged:s},e.id))})]})}function Gc({title:e,models:t,enabledModelIds:n,onToggleModel:r}){return t.length===0?null:(0,P.jsxs)(`div`,{className:`space-y-3`,children:[(0,P.jsx)(`h4`,{className:`text-[10px] uppercase tracking-widest font-bold text-on-surface-variant/60`,children:e}),(0,P.jsx)(`div`,{className:`grid grid-cols-1 gap-2`,children:t.map(e=>(0,P.jsx)(Kc,{model:e,isEnabled:n.has(e.modelId),onToggleModel:r},e.modelId))})]})}function Kc({model:e,isEnabled:t,onToggleModel:n}){return(0,P.jsxs)(`label`,{className:`flex items-center gap-4 p-4 rounded-xl border cursor-pointer transition-all ${t?`bg-primary/10 border-primary/30`:`bg-surface-container-lowest border-outline-variant/10 hover:border-outline-variant/30`}`,children:[(0,P.jsx)(`input`,{type:`checkbox`,checked:t,onChange:t=>{n(e.modelId,t.target.checked)},className:`w-5 h-5 rounded border-outline-variant text-primary focus:ring-primary bg-surface-container-lowest`}),(0,P.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,P.jsx)(`div`,{className:`text-sm font-bold ${t?`text-primary`:`text-on-surface`}`,children:e.displayName}),(0,P.jsx)(`div`,{className:`text-[10px] font-mono text-on-surface-variant/60`,children:e.modelId})]})]})}function qc({connector:e,modelCatalog:t,modelSearchQuery:n,onSearchChange:r,onToggleModel:i,onClose:a}){let{t:o}=L(),s=o.settings.connectors,c=t.discoveredTextModels.filter(t=>!t.provider||t.provider===e.provider),l=t.discoveredImageModels.filter(t=>!t.provider||t.provider===e.provider),u=n.toLowerCase().trim(),d=e=>u?e.filter(e=>e.displayName.toLowerCase().includes(u)||e.modelId.toLowerCase().includes(u)):e,f=d(c),p=d(l),m=new Set(e.enabledModels);return(0,P.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm animate-in fade-in duration-200`,children:(0,P.jsxs)(`div`,{className:`bg-surface-container-high w-full max-w-lg rounded-3xl p-5 sm:p-8 shadow-2xl border border-outline-variant/20 flex flex-col max-h-[90vh] sm:max-h-[80vh]`,children:[(0,P.jsxs)(`div`,{className:`space-y-2 mb-6`,children:[(0,P.jsx)(`h3`,{className:`text-xl font-bold text-on-surface`,children:s.modelsModalTitle}),(0,P.jsxs)(`p`,{className:`text-sm text-on-surface-variant/70`,children:[s.modelsModalDescription,` `,(0,P.jsx)(`span`,{className:`text-primary font-bold`,children:e.name}),` `,s.modelsModalDescriptionSuffix]})]}),(0,P.jsx)(`div`,{className:`relative mb-4`,children:(0,P.jsx)(`input`,{type:`text`,value:n,onChange:e=>r(e.target.value),placeholder:s.searchModelsPlaceholder,className:`w-full rounded-xl border border-outline-variant/20 bg-surface-container-lowest px-4 py-3 text-sm text-on-surface placeholder:text-on-surface-variant/50 focus:border-primary/50 focus:outline-none focus:ring-1 focus:ring-primary/30`})}),(0,P.jsxs)(`div`,{className:`flex-1 overflow-y-auto pr-2 space-y-6 hide-scrollbar`,children:[(0,P.jsx)(Gc,{title:s.textModelsLabel,models:f,enabledModelIds:m,onToggleModel:i}),(0,P.jsx)(Gc,{title:s.imageModelsLabel,models:p,enabledModelIds:m,onToggleModel:i}),c.length===0&&l.length===0&&(0,P.jsx)(`div`,{className:`rounded-2xl border border-dashed border-outline-variant/20 bg-surface-container-lowest px-4 py-8 text-center text-sm text-on-surface-variant/70`,children:s.noModelsDiscovered}),(c.length>0||l.length>0)&&f.length===0&&p.length===0&&(0,P.jsx)(`div`,{className:`rounded-2xl border border-dashed border-outline-variant/20 bg-surface-container-lowest px-4 py-8 text-center text-sm text-on-surface-variant/70`,children:o.common.noResultsFor.replace(`{query}`,()=>n)})]}),(0,P.jsx)(R,{variant:`primary`,onClick:a,className:`mt-8 w-full py-4`,children:s.doneButton})]})})}function Jc({connector:e,onConfirm:t,onCancel:n}){let{t:r}=L(),i=r.settings.connectors;return(0,P.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm animate-in fade-in duration-200`,children:(0,P.jsxs)(`div`,{className:`bg-surface-container-high w-full max-w-sm rounded-3xl p-5 sm:p-8 shadow-2xl border border-outline-variant/20 space-y-5 sm:space-y-6`,children:[(0,P.jsxs)(`div`,{className:`space-y-2 text-center`,children:[(0,P.jsx)(`div`,{className:`p-4 bg-error/10 rounded-full w-fit mx-auto text-error mb-2`,children:(0,P.jsx)(Ge,{size:32})}),(0,P.jsx)(`h3`,{className:`text-xl font-bold text-on-surface`,children:i.deleteConnector}),(0,P.jsxs)(`p`,{className:`text-sm text-on-surface-variant/70`,children:[i.deleteConfirm,` `,(0,P.jsx)(`br`,{}),(0,P.jsxs)(`span`,{className:`text-on-surface font-bold`,children:[`“`,e.name,`”`]})]})]}),(0,P.jsxs)(`div`,{className:`flex gap-3`,children:[(0,P.jsx)(R,{variant:`secondary`,onClick:n,className:`flex-1`,children:i.cancelButton}),(0,P.jsx)(R,{variant:`primary`,onClick:t,className:`flex-1 bg-error hover:bg-error/80 shadow-error/20`,children:i.deleteConnector})]})]})})}var Yc=`mango.chatgpt-usage-alert-threshold`,Xc=rc;function Zc(){switch(window.localStorage.getItem(Yc)){case`off`:return null;case`75`:return 75;case`90`:return 90;default:return 90}}function Qc(e){let{t}=L(),{toast:n}=F(),[r,i]=(0,N.useState)(Zc);return(0,N.useEffect)(()=>{let{events:i,next:a}=ac(Xc,e,r);Xc=a;let o=t.settings.connectors;for(let e of i){let t=e.window===`primary`?o.chatgptUsagePrimaryFallback:o.chatgptUsageSecondaryFallback;e.kind===`reset`?n(o.chatgptAlertWindowReset.replace(`{name}`,e.connectorName).replace(`{window}`,t),`success`):n(o.chatgptAlertThresholdCrossed.replace(`{name}`,e.connectorName).replace(`{window}`,t).replace(`{percent}`,String(Math.round(e.usedPercent))),`info`)}},[e,r,t,n]),{threshold:r,updateThreshold:(0,N.useCallback)(e=>{i(e),window.localStorage.setItem(Yc,e===null?`off`:String(e))},[])}}var $c={name:``,apiKey:``,provider:`gemini`,baseUrl:``,organizationId:``,projectId:``,source:`bun-secrets`};function el({onSuccess:e,errorRequired:t,baseUrlRequired:n,unknownError:r}){let[i,a]=(0,N.useState)($c),[o,s]=(0,N.useState)(!1),[c,l]=(0,N.useState)(null),[u,d]=(0,N.useState)(!1),f=()=>{a($c),l(null),d(!1)};return{form:i,setForm:a,isSaving:o,formError:c,showKey:u,setShowKey:d,submit:async()=>{if(!i.name.trim()||i.provider!==`chatgpt`&&!i.apiKey.trim()){l(t);return}if(i.provider!==`chatgpt`){if(i.provider===`openai-compatible`&&!i.baseUrl.trim()){l(n);return}s(!0),l(null);try{let t={name:i.name,apiKey:i.apiKey,source:i.source,provider:i.provider};i.provider===`openai-compatible`&&i.baseUrl.trim()&&(t.baseUrl=i.baseUrl.trim()),i.provider===`deepseek`&&i.baseUrl.trim()&&(t.baseUrl=i.baseUrl.trim()),i.provider===`openai`&&(i.organizationId.trim()&&(t.organizationId=i.organizationId.trim()),i.projectId.trim()&&(t.projectId=i.projectId.trim())),await Rs(t),await e(),f()}catch(e){l(e instanceof Error?e.message:r)}finally{s(!1)}}},reset:f}}var tl={status:[`connector-status`]},nl=()=>D({queryKey:tl.status,queryFn:async()=>{let{data:e,error:t}=await H.api.settings.connectors.get();if(t)throw Error(V(t.value,I.settings.connectors.failedToLoad));return e}});function rl(){let{data:e,refetch:t}=k(nl()),n=(0,N.useCallback)(async()=>{await t()},[t]);return{connectorStatus:e,connectors:e?.connectors??[],reload:n}}function il(e,t,n){let[r,i]=(0,N.useState)(null),[a,o]=(0,N.useState)(``);return{selectedConnector:r,modelSearchQuery:a,setModelSearchQuery:o,openModals:e=>{i(e),o(``)},closeModal:()=>i(null),getDiscoveredModels:t=>({textModels:e.discoveredTextModels.filter(e=>!e.provider||e.provider===t.provider),imageModels:e.discoveredImageModels.filter(e=>!e.provider||e.provider===t.provider)}),handleToggleModel:async(e,a)=>{if(!r)return;let o=a?[...r.enabledModels,e]:r.enabledModels.filter(t=>t!==e);i({...r,enabledModels:o});try{await Bs(r.id,o),await t(),await n()}catch(e){console.error(`[connectors] Failed to update models`,e)}}}}function al(e){return e.userId===null&&e.source!==`config-file`&&e.source!==`environment`}function ol({modelCatalog:e,reloadModelCatalog:t}){let{t:n}=L(),{toast:r}=F(),i=n.settings.connectors,{connectors:a,reload:o}=rl(),s=Qc(a),[c,l]=(0,N.useState)(!1),[u,d]=(0,N.useState)(null),f=el({errorRequired:i.errorRequired,baseUrlRequired:i.baseUrlRequired,unknownError:n.errors.unknown,onSuccess:async()=>{l(!1),r(i.addSuccess,`success`),await o(),await t()}}),p=il(e,o,t),m=async e=>{let n=a.find(t=>t.id===e);if(n&&al(n)){r(i.sharedDeleteBlocked,`error`),d(null);return}try{await zs(e),await t(),r(i.deleteSuccess,`success`)}catch(e){console.error(e),r(i.failedToDelete,`error`)}finally{await o(),d(null)}};return(0,P.jsxs)(`div`,{className:`space-y-4`,children:[(0,P.jsx)(Wc,{connectors:a,alertThreshold:s.threshold,onAlertThresholdChange:s.updateThreshold,onAddConnector:()=>l(!0),onConfigureConnector:p.openModals,onReauthenticatedConnector:async()=>{r(i.chatgptReconnectSuccess,`success`),await o(),await t()},onUsageChanged:o,onDeleteConnector:e=>{if(al(e)){r(i.sharedDeleteBlocked,`error`);return}d(e)}}),c&&(0,P.jsx)(tc,{form:f.form,setForm:f.setForm,isSaving:f.isSaving,formError:f.formError,showKey:f.showKey,setShowKey:f.setShowKey,onSubmit:()=>void f.submit(),onOAuthSuccess:async()=>{l(!1),f.reset(),r(i.addSuccess,`success`),await o(),await t()},onClose:()=>{l(!1),f.reset()}}),p.selectedConnector&&(0,P.jsx)(qc,{connector:p.selectedConnector,modelCatalog:e,modelSearchQuery:p.modelSearchQuery,onSearchChange:p.setModelSearchQuery,onToggleModel:p.handleToggleModel,onClose:p.closeModal}),u&&(0,P.jsx)(Jc,{connector:u,onConfirm:()=>void m(u.id),onCancel:()=>d(null)})]})}var sl=S(`/_authenticated/settings/connectors`)({loader:({context:{queryClient:e}})=>e.prefetchQuery(nl()),component:cl});function cl(){let e=ta();return(0,P.jsx)(ol,{modelCatalog:e.catalog,reloadModelCatalog:e.refreshCatalog})}var ll=[`one-dark-pro`,`github-dark-dimmed`,`github-light`,`one-light`],ul={"one-dark-pro":`#282c34`,"github-dark-dimmed":`#22272e`,"github-light":`#ffffff`,"one-light":`#fafafa`},dl={"one-dark-pro":{keyword:`#c678dd`,identifier:`#e5c07b`,operator:`#56b6c2`,string:`#98c379`,punctuation:`#abb2bf`,functionName:`#61afef`,parameter:`#e06c75`},"github-dark-dimmed":{keyword:`#f47067`,identifier:`#f69d50`,operator:`#adbac7`,string:`#96d0ff`,punctuation:`#adbac7`,functionName:`#dcbdfb`,parameter:`#f69d50`},"github-light":{keyword:`#cf222e`,identifier:`#953800`,operator:`#24292f`,string:`#0a3069`,punctuation:`#24292f`,functionName:`#8250df`,parameter:`#953800`},"one-light":{keyword:`#a626a4`,identifier:`#c18401`,operator:`#0184bc`,string:`#50a14f`,punctuation:`#383a42`,functionName:`#4078f2`,parameter:`#e45649`}};function fl({themeId:e}){let t=dl[e];return(0,P.jsx)(`pre`,{className:`p-3 text-[11px] leading-normal font-mono overflow-hidden`,style:{background:ul[e]},children:(0,P.jsxs)(`code`,{children:[(0,P.jsx)(`span`,{style:{color:t.keyword},children:`const`}),` `,(0,P.jsx)(`span`,{style:{color:t.identifier},children:`greeting`}),` `,(0,P.jsx)(`span`,{style:{color:t.operator},children:`=`}),` `,(0,P.jsx)(`span`,{style:{color:t.string},children:`"hello"`}),(0,P.jsx)(`span`,{style:{color:t.punctuation},children:`;`}),`
79
+ `,(0,P.jsx)(`span`,{style:{color:t.keyword},children:`function`}),` `,(0,P.jsx)(`span`,{style:{color:t.functionName},children:`greet`}),(0,P.jsx)(`span`,{style:{color:t.punctuation},children:`(`}),(0,P.jsx)(`span`,{style:{color:t.parameter},children:`name`}),(0,P.jsx)(`span`,{style:{color:t.punctuation},children:`)`}),` `,(0,P.jsx)(`span`,{style:{color:t.punctuation},children:`{`}),`
80
+ `,` `,(0,P.jsx)(`span`,{style:{color:t.keyword},children:`return`}),` `,(0,P.jsx)(`span`,{style:{color:t.string},children:"`${greeting}, ${name}`"}),(0,P.jsx)(`span`,{style:{color:t.punctuation},children:`;`}),`
81
+ `,(0,P.jsx)(`span`,{style:{color:t.punctuation},children:`}`})]})})}function pl({selected:e,disabled:t,onClick:n,label:r,badge:i}){return(0,P.jsxs)(`button`,{type:`button`,onClick:n,disabled:t,"aria-pressed":e,className:`
82
+ flex-1 px-4 py-2.5 rounded-xl text-sm font-semibold transition-all duration-200
83
+ border focus:outline-none focus:ring-2 focus:ring-primary/40
84
+ ${e?`bg-primary/15 border-primary/50 text-primary`:t?`opacity-40 cursor-not-allowed border-outline-variant/20 text-on-surface-variant/50`:`border-outline-variant/20 text-on-surface-variant hover:bg-surface-container-high hover:text-on-surface cursor-pointer`}
85
+ `,children:[r,i&&(0,P.jsx)(`span`,{className:`ml-1.5 text-[10px] font-label font-bold text-on-surface-variant/50 uppercase tracking-wide`,children:i})]})}function ml({title:e,description:t,children:n}){return(0,P.jsxs)(z,{variant:`solid`,className:`space-y-3 p-4 sm:p-6`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:e}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:t}),n]})}var hl={"one-dark-pro":`oneDarkPro`,"github-dark-dimmed":`githubDarkDimmed`,"github-light":`githubLight`,"one-light":`oneLight`};function gl({themeId:e,selected:t,onClick:n,label:r}){return(0,P.jsxs)(`button`,{type:`button`,onClick:n,"aria-pressed":t,className:`
86
+ rounded-xl border-2 transition-all duration-200 overflow-hidden text-left
87
+ focus:outline-none focus:ring-2 focus:ring-primary/40
88
+ ${t?`border-primary ring-1 ring-primary/30`:`border-outline-variant/20 hover:border-outline-variant/50 cursor-pointer`}
89
+ `,children:[(0,P.jsx)(fl,{themeId:e}),(0,P.jsx)(`div`,{className:`px-3 py-2 text-xs font-semibold text-on-surface-variant bg-surface-container-high`,children:r})]})}var _l=`The quick brown fox jumps over the lazy dog.`;function vl(){let{t:e}=L(),{config:t,setConfig:n}=Dt(),r=e.settings.appearance,i=e=>n({fontSize:e}),a=e=>n({chatDensity:e}),o=t.codeTheme,s=e=>n({codeTheme:{...o,mode:e}}),c=e=>n({codeTheme:{...o,darkTheme:e}}),l=e=>n({codeTheme:{...o,lightTheme:e}}),u=ll.filter(e=>e===`one-dark-pro`||e===`github-dark-dimmed`),d=ll.filter(e=>e===`github-light`||e===`one-light`);return(0,P.jsxs)(`div`,{className:`space-y-4`,children:[(0,P.jsx)(ml,{title:r.appTheme.label,description:r.appTheme.description,children:(0,P.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,P.jsx)(pl,{selected:t.appTheme===`dark`,onClick:()=>n({appTheme:`dark`}),label:r.appTheme.dark}),(0,P.jsx)(pl,{selected:t.appTheme===`light`,onClick:()=>n({appTheme:`light`}),label:r.appTheme.light}),(0,P.jsx)(pl,{selected:t.appTheme===`system`,onClick:()=>n({appTheme:`system`}),label:r.appTheme.system})]})}),(0,P.jsxs)(ml,{title:r.codeTheme.label,description:r.codeTheme.description,children:[(0,P.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,P.jsx)(pl,{selected:o.mode===`auto`,onClick:()=>s(`auto`),label:r.codeTheme.auto}),(0,P.jsx)(pl,{selected:o.mode===`manual`,onClick:()=>s(`manual`),label:r.codeTheme.manual})]}),o.mode===`auto`?(0,P.jsxs)(`div`,{className:`space-y-3 mt-2`,children:[(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`p`,{className:`text-xs font-semibold text-on-surface-variant/70 mb-2`,children:r.codeTheme.darkPreference}),(0,P.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:u.map(e=>(0,P.jsx)(gl,{themeId:e,selected:o.darkTheme===e,onClick:()=>c(e),label:r.codeTheme[hl[e]]},e))})]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`p`,{className:`text-xs font-semibold text-on-surface-variant/70 mb-2`,children:r.codeTheme.lightPreference}),(0,P.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:d.map(e=>(0,P.jsx)(gl,{themeId:e,selected:o.lightTheme===e,onClick:()=>l(e),label:r.codeTheme[hl[e]]},e))})]})]}):(0,P.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3 mt-2`,children:ll.map(e=>(0,P.jsx)(gl,{themeId:e,selected:o.darkTheme===e,onClick:()=>c(e),label:r.codeTheme[hl[e]]},e))})]}),(0,P.jsxs)(ml,{title:r.fontSize.label,description:r.fontSize.description,children:[(0,P.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:[`small`,`default`,`large`].map(e=>(0,P.jsx)(pl,{selected:t.fontSize===e,onClick:()=>i(e),label:r.fontSize[e]},e))}),(0,P.jsx)(`p`,{className:`mt-2 text-on-surface-variant/70 font-body leading-relaxed transition-all duration-200`,style:{fontSize:`var(--chat-font-size)`},children:_l})]}),(0,P.jsx)(ml,{title:r.chatDensity.label,description:r.chatDensity.description,children:(0,P.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:[`compact`,`default`,`comfortable`].map(e=>(0,P.jsx)(pl,{selected:t.chatDensity===e,onClick:()=>a(e),label:r.chatDensity[e]},e))})})]})}var yl=S(`/_authenticated/settings/appearance`)({component:bl});function bl(){return(0,P.jsx)(vl,{})}var xl=I.settings.agents;async function Sl(e,t){let{data:n,error:r}=await H.api.settings.agents({agentId:e}).put(El(t));if(r)throw Error(V(r.value,xl.saveError));return n}async function Cl(e){let{data:t,error:n}=await H.api.settings.agents.post({...El(e),...e.slug?{slug:e.slug}:{}});if(n)throw Error(V(n.value,xl.createError));return t}async function wl(e){let{data:t,error:n}=await H.api.settings.agents({agentId:e}).delete();if(n)throw Error(V(n.value,xl.deleteError));return t}async function Tl(e){let{data:t,error:n}=await H.api.settings.agents.preview.post(e);if(n)throw Error(V(n.value,xl.previewError));return t}function El(e){return{...e,toolNames:[...e.toolNames],subagentIds:[...e.subagentIds]}}function Dl({title:e,draft:t,labels:n,mode:r,dirty:i,isUserAgent:a,onFriendlyMode:o,onRawMode:s}){return(0,P.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between p-4 sm:p-6 border-b border-outline-variant/10`,children:[(0,P.jsxs)(`div`,{className:`min-w-0`,children:[(0,P.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[(0,P.jsx)(`h2`,{className:`text-xl font-bold text-on-surface`,children:e}),(0,P.jsx)(`span`,{className:`rounded-full bg-surface-container-lowest px-2 py-0.5 text-xs text-on-surface-variant`,children:t.kind===`builtin`?n.builtIn:n.user}),i&&(0,P.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full bg-amber-500/10 px-2 py-0.5 text-xs text-amber-600 dark:text-amber-400`,children:[(0,P.jsx)(pe,{size:12}),n.unsavedChanges]})]}),(0,P.jsx)(`p`,{className:`mt-1 text-sm text-on-surface-variant/70 truncate`,children:t.id})]}),a&&(0,P.jsxs)(`div`,{className:`flex gap-1 p-1 rounded-xl bg-surface-container-lowest border border-outline-variant/10 shrink-0`,children:[(0,P.jsx)(Ol,{active:r===`friendly`,onClick:o,children:n.friendlyMode}),(0,P.jsx)(Ol,{active:r===`raw`,onClick:s,children:n.rawMode})]})]})}function Ol({active:e,onClick:t,children:n}){return(0,P.jsx)(`button`,{type:`button`,onClick:t,className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all duration-200 ${e?`bg-surface-container-high text-on-surface shadow-sm`:`text-on-surface-variant/60 hover:text-on-surface`}`,children:n})}function kl({draft:e,labels:t,isUserAgent:n,isNew:r,isSaving:i,dirty:a,onDelete:o,onReset:s,onSave:c}){return(0,P.jsxs)(`div`,{className:`sticky bottom-0 z-10 flex flex-wrap justify-between gap-2 border-t border-outline-variant/10 bg-surface-container-high/95 backdrop-blur-sm p-4 sm:p-6 rounded-b-2xl`,children:[(0,P.jsx)(`div`,{children:n&&!r&&(0,P.jsxs)(R,{type:`button`,variant:`ghost`,onClick:()=>o(e),children:[(0,P.jsx)(Ge,{size:16}),t.delete]})}),(0,P.jsxs)(`div`,{className:`flex gap-2`,children:[(0,P.jsxs)(R,{type:`button`,variant:`ghost`,onClick:s,children:[(0,P.jsx)(Ee,{size:16}),t.reset]}),(0,P.jsxs)(R,{type:`button`,loading:i,disabled:!a&&!r,onClick:c,children:[(0,P.jsx)(De,{size:16}),i?t.saving:t.save]})]})]})}function Al({labels:e,onCancel:t,onConfirm:n}){return(0,P.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4`,children:(0,P.jsxs)(`div`,{className:`w-full max-w-md rounded-2xl border border-outline-variant/20 bg-surface p-5 shadow-xl space-y-4`,children:[(0,P.jsxs)(`div`,{className:`space-y-1`,children:[(0,P.jsx)(`h3`,{className:`text-lg font-bold text-on-surface`,children:e.confirmResetTitle}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/70`,children:e.confirmResetDescription})]}),(0,P.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,P.jsx)(R,{type:`button`,variant:`ghost`,onClick:t,children:e.cancel}),(0,P.jsx)(R,{type:`button`,variant:`primary`,onClick:n,children:e.confirmReset})]})]})})}function jl({label:e,markdown:t,onChange:n}){return(0,P.jsxs)(`label`,{className:`block space-y-2`,children:[(0,P.jsx)(`span`,{className:`text-sm font-semibold text-on-surface`,children:e}),(0,P.jsx)(`textarea`,{value:t,onChange:e=>n(e.target.value),rows:12,className:`w-full rounded-xl border border-outline-variant/20 bg-surface-container-lowest px-3 py-2 font-mono text-sm text-on-surface focus:border-primary/60 focus:outline-none focus:ring-1 focus:ring-primary/20`})]})}function Ml({label:e,disabledLabel:t,tools:n,selectedToolNames:r,disabled:i=!1,onChange:a}){let o=new Set(r);return(0,P.jsxs)(`fieldset`,{className:`space-y-2`,disabled:i,children:[(0,P.jsx)(`legend`,{className:`text-sm font-semibold text-on-surface`,children:e}),n.length===0?(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:t}):(0,P.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-2 ${i?`opacity-50`:``}`,children:n.map(e=>(0,P.jsxs)(`label`,{className:`flex items-start gap-2.5 rounded-xl border px-3 py-2.5 text-sm text-on-surface transition-all duration-200 ${i?`border-outline-variant/10 bg-surface-container-lowest/50 cursor-not-allowed`:o.has(e.name)?`border-primary/30 bg-primary/5 cursor-pointer`:`border-outline-variant/20 bg-surface-container-lowest hover:border-outline-variant/40 hover:bg-surface-container-high cursor-pointer`}`,children:[(0,P.jsx)(`input`,{type:`checkbox`,checked:o.has(e.name),onChange:t=>{a(t.target.checked?[...r,e.name]:r.filter(t=>t!==e.name))},className:`mt-0.5 accent-primary`}),(0,P.jsxs)(`span`,{className:`flex-1 min-w-0`,children:[(0,P.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,P.jsx)(Oe,{size:12,className:`shrink-0 text-on-surface-variant/50`}),(0,P.jsx)(`span`,{className:`block font-medium text-sm`,children:e.title})]}),(0,P.jsx)(`span`,{className:`block text-xs text-on-surface-variant/60 truncate`,children:e.name})]})]},e.name))})]})}var Nl=[`primary`,`subagent`,`both`],Pl=[`low`,`medium`,`high`,`xhigh`,`max`];function Fl({labels:e,rawMarkdown:t,isPreviewing:n,onChange:r,onPreview:i}){return(0,P.jsxs)(`div`,{className:`space-y-3`,children:[(0,P.jsx)(jl,{label:e.rawMarkdown,markdown:t,onChange:r}),(0,P.jsxs)(R,{type:`button`,variant:`secondary`,loading:n,onClick:i,children:[(0,P.jsx)($e,{size:16}),n?e.previewing:e.preview]})]})}function Il({draft:e,allAgents:t,tools:n,modelOptions:r,labels:i,isNew:a,isUserAgent:o,onDraftChange:s}){let c=t.filter(t=>t.id!==e.id&&(t.role===`subagent`||t.role===`both`)),l=new Set(e.subagentIds),u=e.source.type===`markdown`?e.source.path:void 0,d=new Set(r.map(e=>e.value)),f=e.model&&!d.has(e.model)?[{value:e.model,label:e.model},...r]:r;return(0,P.jsxs)(`div`,{className:`space-y-6`,children:[(0,P.jsx)(Ll,{draft:e,labels:i,isNew:a,onDraftChange:s}),(0,P.jsx)(Rl,{draft:e,labels:i,modelOptions:f,onDraftChange:s}),(0,P.jsx)(zl,{draft:e,labels:i,onDraftChange:s}),(0,P.jsx)(Bl,{draft:e,labels:i,tools:n,eligibleSubagents:c,selectedSubagents:l,onDraftChange:s}),o&&u&&(0,P.jsx)(Hl,{label:i.path,value:u})]})}function Ll({draft:e,labels:t,isNew:n,onDraftChange:r}){return(0,P.jsx)(Vl,{title:t.sectionIdentity,children:(0,P.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2 xl:grid-cols-3`,children:[(0,P.jsx)(Ul,{label:t.name,value:e.name,onChange:e=>r({name:e})}),n&&(0,P.jsx)(Ul,{label:t.slug,value:e.slug??``,onChange:e=>r({slug:e})}),(0,P.jsx)(Ul,{label:t.description,value:e.description,onChange:e=>r({description:e})}),(0,P.jsxs)(`label`,{className:`block space-y-2`,children:[(0,P.jsx)(`span`,{className:`text-sm font-semibold text-on-surface`,children:t.role}),(0,P.jsx)(`select`,{value:e.role,onChange:e=>r({role:e.target.value}),className:`w-full rounded-xl border border-outline-variant/20 bg-surface-container-lowest px-3 py-2 text-sm text-on-surface focus:border-primary/60 focus:outline-none focus:ring-1 focus:ring-primary/20`,children:Nl.map(e=>(0,P.jsx)(`option`,{value:e,children:t.roles[e]},e))})]})]})})}function Rl({draft:e,labels:t,modelOptions:n,onDraftChange:r}){return(0,P.jsxs)(Vl,{title:t.sectionBehavior,children:[(0,P.jsxs)(`label`,{className:`block space-y-2`,children:[(0,P.jsx)(`span`,{className:`text-sm font-semibold text-on-surface`,children:t.systemPrompt}),(0,P.jsx)(`textarea`,{value:e.systemPrompt,onChange:e=>r({systemPrompt:e.target.value}),rows:6,className:`w-full rounded-xl border border-outline-variant/20 bg-surface-container-lowest px-3 py-2 text-sm text-on-surface focus:border-primary/60 focus:outline-none focus:ring-1 focus:ring-primary/20 resize-y`})]}),(0,P.jsxs)(`label`,{className:`block space-y-2`,children:[(0,P.jsx)(`span`,{className:`text-sm font-semibold text-on-surface`,children:t.model}),(0,P.jsxs)(`select`,{value:e.model??``,onChange:e=>r({model:e.target.value?e.target.value:void 0}),className:`w-full rounded-xl border border-outline-variant/20 bg-surface-container-lowest px-3 py-2 text-sm text-on-surface focus:border-primary/60 focus:outline-none focus:ring-1 focus:ring-primary/20`,children:[(0,P.jsx)(`option`,{value:``,children:t.modelDefaultOption}),n.map(e=>(0,P.jsx)(`option`,{value:e.value,children:e.label},e.value))]})]})]})}function zl({draft:e,labels:t,onDraftChange:n}){return(0,P.jsx)(Vl,{title:t.sectionReasoning,children:(0,P.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2 xl:grid-cols-3`,children:[(0,P.jsxs)(`label`,{className:`flex items-center gap-2 rounded-xl border border-outline-variant/20 bg-surface-container-lowest px-3 py-2 text-sm text-on-surface`,children:[(0,P.jsx)(`input`,{type:`checkbox`,checked:e.thinkingEnabled??!1,onChange:e=>n({thinkingEnabled:e.target.checked}),className:`accent-primary`}),t.thinking]}),(0,P.jsxs)(`label`,{className:`block space-y-2`,children:[(0,P.jsx)(`span`,{className:`text-sm font-semibold text-on-surface`,children:t.reasoningEffort}),(0,P.jsxs)(`select`,{value:e.reasoningEffort??``,onChange:e=>n({reasoningEffort:e.target.value?e.target.value:void 0}),className:`w-full rounded-xl border border-outline-variant/20 bg-surface-container-lowest px-3 py-2 text-sm text-on-surface focus:border-primary/60 focus:outline-none focus:ring-1 focus:ring-primary/20`,children:[(0,P.jsx)(`option`,{value:``}),Pl.map(e=>(0,P.jsx)(`option`,{value:e,children:t.reasoningEfforts[e]},e))]})]}),(0,P.jsx)(Wl,{label:t.maxToolIterations,value:e.maxToolIterations??``,onChange:e=>n({maxToolIterations:e})})]})})}function Bl({draft:e,labels:t,tools:n,eligibleSubagents:r,selectedSubagents:i,onDraftChange:a}){return(0,P.jsxs)(Vl,{title:t.sectionTools,children:[(0,P.jsxs)(`label`,{className:`flex items-center gap-2 rounded-xl border border-outline-variant/20 bg-surface-container-lowest px-3 py-2 text-sm text-on-surface w-fit`,children:[(0,P.jsx)(`input`,{type:`checkbox`,checked:e.toolsEnabled,onChange:e=>a({toolsEnabled:e.target.checked}),className:`accent-primary`}),t.toolsEnabled]}),(0,P.jsx)(Ml,{label:t.toolAllowlist,disabledLabel:t.noTools,tools:n,selectedToolNames:e.toolNames,disabled:!e.toolsEnabled,onChange:e=>a({toolNames:e})}),(0,P.jsxs)(`fieldset`,{className:`space-y-2`,disabled:r.length===0,children:[(0,P.jsx)(`legend`,{className:`text-sm font-semibold text-on-surface`,children:t.subagents}),r.length===0?(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:t.noSubagents}):(0,P.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-2 xl:grid-cols-3`,children:r.map(t=>(0,P.jsxs)(`label`,{className:`flex items-center gap-2 rounded-xl border border-outline-variant/20 bg-surface-container-lowest px-3 py-2 text-sm text-on-surface`,children:[(0,P.jsx)(`input`,{type:`checkbox`,checked:i.has(t.id),onChange:n=>{a({subagentIds:n.target.checked?[...e.subagentIds,t.id]:e.subagentIds.filter(e=>e!==t.id)})},className:`accent-primary`}),t.name]},t.id))})]})]})}function Vl({title:e,children:t}){return(0,P.jsxs)(`section`,{className:`space-y-4`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/80 font-label`,children:e}),t]})}function Hl({label:e,value:t}){return(0,P.jsxs)(`label`,{className:`block space-y-2`,children:[(0,P.jsx)(`span`,{className:`text-sm font-semibold text-on-surface`,children:e}),(0,P.jsx)(`input`,{readOnly:!0,value:t,className:`w-full rounded-xl border border-outline-variant/20 bg-surface-container-lowest px-3 py-2 text-sm text-on-surface-variant`})]})}function Ul({label:e,value:t,onChange:n,placeholder:r}){return(0,P.jsxs)(`label`,{className:`block space-y-2`,children:[(0,P.jsx)(`span`,{className:`text-sm font-semibold text-on-surface`,children:e}),(0,P.jsx)(`input`,{value:t,onChange:e=>n(e.target.value),placeholder:r,className:`w-full rounded-xl border border-outline-variant/20 bg-surface-container-lowest px-3 py-2 text-sm text-on-surface focus:border-primary/60 focus:outline-none focus:ring-1 focus:ring-primary/20`})]})}function Wl({label:e,value:t,onChange:n}){return(0,P.jsxs)(`label`,{className:`block space-y-2`,children:[(0,P.jsx)(`span`,{className:`text-sm font-semibold text-on-surface`,children:e}),(0,P.jsx)(`input`,{type:`number`,min:1,max:G,value:t,onChange:e=>{let t=Number(e.target.value);n(Number.isFinite(t)&&e.target.value?t:void 0)},className:`w-full rounded-xl border border-outline-variant/20 bg-surface-container-lowest px-3 py-2 text-sm text-on-surface focus:border-primary/60 focus:outline-none focus:ring-1 focus:ring-primary/20`})]})}function Gl(e,t){return e.name===t.name&&e.description===t.description&&e.role===t.role&&e.systemPrompt===t.systemPrompt&&e.model===t.model&&e.thinkingEnabled===t.thinkingEnabled&&e.reasoningEffort===t.reasoningEffort&&e.maxToolIterations===t.maxToolIterations&&e.toolsEnabled===t.toolsEnabled&&JSON.stringify(e.toolNames)===JSON.stringify(t.toolNames)&&JSON.stringify(e.subagentIds)===JSON.stringify(t.subagentIds)&&e.slug===t.slug}function Kl({agent:e,allAgents:t,tools:n,modelOptions:r,labels:i,isNew:a,isSaving:o,isPreviewing:s,onSave:c,onPreviewMarkdown:l,onDelete:u,onCancelNew:d}){let[f,p]=(0,N.useState)(e),[m,h]=(0,N.useState)(`friendly`),[g,_]=(0,N.useState)(()=>Jl(e)),[v,y]=(0,N.useState)(!1),b=!Gl(f,e),x=f.kind===`user`,S=a?i.createTitle:f.name,C=e=>{p(t=>({...t,...e}))},w=(0,N.useCallback)(()=>{c(f,ql(f))},[f,c]),ee=(0,N.useCallback)(()=>{if(b){y(!0);return}if(a){d();return}p(e),_(Jl(e))},[b,a,e,d]),te=(0,N.useCallback)(()=>{if(y(!1),a){d();return}p(e),_(Jl(e))},[a,e,d]),ne=(0,N.useCallback)(()=>{l(g,f.id).then(e=>{p({...e,slug:f.slug}),_(Jl(e))})},[f.id,f.slug,l,g]);return(0,N.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&e.key===`s`&&(e.preventDefault(),!o&&b&&w())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[w,o,b]),(0,P.jsxs)(`div`,{className:`space-y-0 rounded-2xl border border-outline-variant/20 bg-surface-container-high`,children:[(0,P.jsx)(Dl,{title:S,draft:f,labels:i,mode:m,dirty:b,isUserAgent:x,onFriendlyMode:()=>h(`friendly`),onRawMode:()=>{_(Jl(f)),h(`raw`)}}),(0,P.jsx)(`div`,{className:`p-4 sm:p-6 space-y-6`,children:m===`raw`&&x?(0,P.jsx)(Fl,{labels:i,rawMarkdown:g,isPreviewing:s,onChange:_,onPreview:ne}):(0,P.jsx)(Il,{draft:f,allAgents:t,tools:n,modelOptions:r,labels:i,isNew:a,isUserAgent:x,onDraftChange:C})}),(0,P.jsx)(kl,{draft:f,labels:i,isUserAgent:x,isNew:a,isSaving:o,dirty:b,onDelete:u,onReset:ee,onSave:w}),v&&(0,P.jsx)(Al,{labels:i,onCancel:()=>y(!1),onConfirm:te})]})}function ql(e){return{name:e.name,description:e.description,role:e.role,systemPrompt:e.systemPrompt,...e.model?{model:e.model}:{},...e.thinkingEnabled===void 0?{}:{thinkingEnabled:e.thinkingEnabled},...e.reasoningEffort?{reasoningEffort:e.reasoningEffort}:{},...e.maxToolIterations?{maxToolIterations:e.maxToolIterations}:{},toolNames:e.toolNames,toolsEnabled:e.toolsEnabled,subagentIds:e.subagentIds,metadata:e.metadata}}function Jl(e){let t=[`---`,`name: ${JSON.stringify(e.name)}`,`description: ${JSON.stringify(e.description)}`,`role: ${e.role}`];return e.model&&t.push(`model: ${JSON.stringify(e.model)}`),e.toolNames.length>0&&t.push(`tools:`,...e.toolNames.map(e=>` - ${JSON.stringify(e)}`)),e.subagentIds.length>0&&t.push(`subagents:`,...e.subagentIds.map(e=>` - ${JSON.stringify(e)}`)),t.push(`---`,``,e.systemPrompt,``),t.join(`
90
+ `)}function Yl({agents:e,selectedAgentId:t,builtInLabel:n,userLabel:r,builtInAgentsTitle:i,userAgentsTitle:a,onSelect:o}){let s=e.filter(e=>e.kind===`builtin`),c=e.filter(e=>e.kind===`user`);return(0,P.jsxs)(`div`,{className:`flex flex-col gap-6`,children:[s.length>0&&(0,P.jsxs)(`section`,{className:`space-y-3`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/70 font-label px-1`,children:i}),(0,P.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4`,children:s.map(e=>(0,P.jsx)(Xl,{agent:e,kindLabel:n,active:e.id===t,onSelect:()=>o(e.id)},e.id))})]}),c.length>0&&(0,P.jsxs)(`section`,{className:`space-y-3`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant/70 font-label px-1`,children:a}),(0,P.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4`,children:c.map(e=>(0,P.jsx)(Xl,{agent:e,kindLabel:r,active:e.id===t,onSelect:()=>o(e.id)},e.id))})]})]})}function Xl({agent:e,kindLabel:t,active:n,onSelect:r}){let i=e.kind===`builtin`?We:_e;return(0,P.jsx)(`button`,{type:`button`,onClick:r,className:`group w-full rounded-2xl border text-left transition-all duration-200 ${n?`border-primary/40 bg-primary/10 text-on-surface shadow-sm`:`border-outline-variant/20 bg-surface-container-high text-on-surface hover:bg-surface-container-highest hover:border-outline-variant/40`}`,children:(0,P.jsxs)(`span`,{className:`flex items-center gap-3 px-3 py-2.5`,children:[(0,P.jsx)(`span`,{className:`shrink-0 rounded-xl p-1.5 transition-colors ${n?`bg-primary/20 text-primary`:`bg-surface-container-lowest text-on-surface-variant/60 group-hover:text-on-surface-variant`}`,children:(0,P.jsx)(i,{size:16})}),(0,P.jsxs)(`span`,{className:`flex-1 min-w-0`,children:[(0,P.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,P.jsx)(`span`,{className:`font-semibold text-sm truncate`,children:e.name}),(0,P.jsx)(`span`,{className:`shrink-0 rounded-full px-2 py-0.5 text-[10px] font-medium ${n?`bg-primary/20 text-primary`:`bg-surface-container-lowest text-on-surface-variant/70`}`,children:t})]}),(0,P.jsx)(`span`,{className:`block truncate text-xs text-on-surface-variant/60 mt-0.5`,children:e.description||e.id})]}),(0,P.jsx)(he,{size:14,className:`shrink-0 transition-all duration-200 ${n?`text-primary translate-x-0 opacity-100`:`text-on-surface-variant/30 opacity-0 -translate-x-1 group-hover:opacity-100 group-hover:translate-x-0`}`})]})})}function Zl({title:e,description:t,cancelLabel:n,confirmLabel:r,deletingLabel:i,isOpen:a,isDeleting:o,onCancel:s,onConfirm:c}){return a?(0,P.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4`,children:(0,P.jsxs)(`div`,{className:`w-full max-w-md rounded-2xl border border-outline-variant/20 bg-surface p-5 shadow-xl`,children:[(0,P.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,P.jsxs)(`div`,{className:`space-y-1`,children:[(0,P.jsx)(`h3`,{className:`text-lg font-bold text-on-surface`,children:e}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/70`,children:t})]}),(0,P.jsx)(`button`,{type:`button`,onClick:s,className:`rounded-lg p-1 text-on-surface-variant hover:bg-surface-container-high`,"aria-label":n,children:(0,P.jsx)(Ue,{size:18})})]}),(0,P.jsxs)(`div`,{className:`mt-5 flex justify-end gap-2`,children:[(0,P.jsx)(R,{type:`button`,variant:`ghost`,onClick:s,disabled:o,children:n}),(0,P.jsxs)(R,{type:`button`,variant:`primary`,loading:o,onClick:c,children:[(0,P.jsx)(Ge,{size:16}),o?i:r]})]})]})}):null}function Ql({title:e,description:t,icon:n,action:r}){return(0,P.jsx)(z,{variant:`solid`,className:`space-y-3 p-4 sm:p-6`,children:(0,P.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between`,children:[(0,P.jsxs)(`div`,{className:`flex gap-3 items-start`,children:[(0,P.jsx)(`div`,{className:`rounded-2xl bg-primary/10 p-2 text-primary`,children:n}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`h2`,{className:`text-lg font-bold text-on-surface`,children:e}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/70`,children:t})]})]}),r]})})}var $l=`user:new-agent`;function eu(){let{t:e}=L(),{toast:t}=F(),n=O(),r=e.settings.agents,i=k(pn()),a=k(zo()),o=Qi(),[s,c]=(0,N.useState)(null),[l,u]=(0,N.useState)(null),[d,f]=(0,N.useState)(null),p=(0,N.useMemo)(()=>i.data?.agents??[],[i.data?.agents]),m=(0,N.useMemo)(()=>ru(o.catalog),[o.catalog]),h=(0,N.useMemo)(()=>l||(p.find(e=>e.id===s)??p[0]??null),[p,l,s]),g=()=>{let e=nu(r.newAgentName,r.newAgentDescription);u(e),c(e.id)},_=async()=>{await n.invalidateQueries({queryKey:fn.list()})},v=j({mutationFn:async({agent:e,body:t})=>e.kind===`user`&&e.id===$l?Cl({...t,...e.slug?{slug:e.slug}:{}}):Sl(e.id,t),onSuccess:async e=>{u(null),c(e.id),await _(),t(r.saved,`success`)},onError:e=>{t(e instanceof Error?e.message:r.saveError,`error`)}}),y=j({mutationFn:({markdown:e,agentId:t})=>Tl({markdown:e,id:t.startsWith(`user:`)?t:void 0}),onSuccess:()=>{t(r.previewed,`success`)},onError:e=>{t(e instanceof Error?e.message:r.previewError,`error`)}}),b=j({mutationFn:e=>wl(e),onSuccess:async()=>{f(null),c(null),await _(),t(r.deleted,`success`)},onError:e=>{t(e instanceof Error?e.message:r.deleteError,`error`)}});return i.isLoading||a.isLoading?(0,P.jsx)(`div`,{className:`flex items-center justify-center py-16`,children:(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant`,children:e.common.loading})}):i.error||a.error?(0,P.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-16`,children:[(0,P.jsx)(`p`,{className:`text-sm text-destructive`,children:r.loadError}),(0,P.jsx)(R,{variant:`ghost`,size:`sm`,onClick:()=>{i.refetch(),a.refetch()},children:r.retry})]}):p.length===0&&!l?(0,P.jsxs)(`div`,{className:`space-y-6`,children:[(0,P.jsx)(tu,{labels:r,onCreate:g}),(0,P.jsxs)(z,{variant:`solid`,className:`p-8 sm:p-12 text-center space-y-4`,children:[(0,P.jsx)(`div`,{className:`p-4 bg-surface-container-high rounded-full w-fit mx-auto text-on-surface-variant/40`,children:(0,P.jsx)(We,{size:32})}),(0,P.jsxs)(`div`,{className:`space-y-1`,children:[(0,P.jsx)(`p`,{className:`text-on-surface font-bold`,children:r.emptyStateTitle}),(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant/60`,children:r.emptyStateDescription})]}),(0,P.jsxs)(R,{variant:`primary`,onClick:g,children:[(0,P.jsx)(Ye,{size:16}),r.create]})]})]}):(0,P.jsxs)(`div`,{className:`space-y-6`,children:[(0,P.jsx)(tu,{labels:r,onCreate:g}),(0,P.jsx)(Yl,{agents:l?[l,...p]:p,selectedAgentId:h?.id??null,builtInLabel:r.builtIn,userLabel:r.user,builtInAgentsTitle:r.builtInAgents,userAgentsTitle:r.userAgents,onSelect:e=>{e!==$l&&u(null),c(e)}}),h&&(0,P.jsx)(Kl,{agent:h,allAgents:p,tools:a.data?.tools??[],modelOptions:m,labels:{builtIn:r.builtIn,user:r.user,createTitle:r.createTitle,name:r.name,slug:r.slug,description:r.agentDescription,role:r.role,roles:r.roles,systemPrompt:r.systemPrompt,model:r.model,modelDefaultOption:r.modelDefaultOption,thinking:r.thinking,reasoningEffort:r.reasoningEffort,reasoningEfforts:r.reasoningEfforts,maxToolIterations:r.maxToolIterations,toolsEnabled:r.toolsEnabled,toolAllowlist:r.toolAllowlist,noTools:r.noTools,subagents:r.subagents,noSubagents:r.noSubagents,path:r.path,friendlyMode:r.friendlyMode,rawMode:r.rawMode,rawMarkdown:r.rawMarkdown,preview:r.preview,previewing:r.previewing,save:r.save,saving:r.saving,reset:r.reset,delete:r.delete,sectionIdentity:r.sectionIdentity,sectionBehavior:r.sectionBehavior,sectionReasoning:r.sectionReasoning,sectionTools:r.sectionTools,unsavedChanges:r.unsavedChanges,confirmResetTitle:r.confirmResetTitle,confirmResetDescription:r.confirmResetDescription,confirmReset:r.confirmReset,cancel:r.cancel},isNew:h.id===$l,isSaving:v.isPending,isPreviewing:y.isPending,onSave:(e,t)=>v.mutate({agent:e,body:t}),onPreviewMarkdown:async(e,t)=>(await y.mutateAsync({markdown:e,agentId:t})).profile,onDelete:f,onCancelNew:()=>u(null)},h.id),(0,P.jsx)(Zl,{title:r.deleteTitle,description:r.deleteDescription,cancelLabel:r.cancel,confirmLabel:r.deleteConfirm,deletingLabel:r.deleting,isOpen:d!==null,isDeleting:b.isPending,onCancel:()=>f(null),onConfirm:()=>{d&&b.mutate(d.id)}})]})}function tu({labels:e,onCreate:t}){return(0,P.jsx)(Ql,{title:e.title,description:e.description,icon:(0,P.jsx)(We,{size:22}),action:(0,P.jsxs)(R,{type:`button`,variant:`secondary`,onClick:t,children:[(0,P.jsx)(Ye,{size:16}),e.create]})})}function nu(e,t){return{id:$l,name:e,description:t,kind:`user`,role:`primary`,source:{type:`markdown`},systemPrompt:``,toolNames:[],toolsEnabled:!0,subagentIds:[],metadata:{},slug:``}}function ru(e){let t=e.textModels.length>0?e.textModels:e.allModels,n=new Map;for(let e of t)n.has(e.modelId)||n.set(e.modelId,e);return Array.from(n.values()).sort((e,t)=>{let n=String(e.provider??``).localeCompare(String(t.provider??``));return n===0?e.displayName.localeCompare(t.displayName):n}).map(e=>{let t=e.displayName&&e.displayName!==e.modelId?`${e.displayName} (${e.modelId})`:e.modelId;return{value:e.modelId,label:t}})}var iu=S(`/_authenticated/settings/agents`)({loader:({context:{queryClient:e}})=>Promise.all([e.prefetchQuery(pn()),e.prefetchQuery(zo())]),component:eu}),au=[`low`,`medium`,`high`,`xhigh`,`max`],ou={low:`effortLow`,medium:`effortMedium`,high:`effortHigh`,xhigh:`effortXHigh`,max:`effortMax`};function su({descriptor:e}){let{t}=L(),n=t.providers[e.provider]??e.displayName,r=e.reasoning.supportedEfforts.map(e=>t.thinking[ou[e]]).join(`, `);return(0,P.jsxs)(`div`,{className:`rounded-2xl border border-outline-variant/10 bg-surface-container-lowest p-4`,children:[(0,P.jsx)(`div`,{className:`flex items-start justify-between`,children:(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`h3`,{className:`text-sm font-medium text-on-surface`,children:n}),(0,P.jsx)(`p`,{className:`mt-0.5 text-xs text-on-surface-variant`,children:r})]})}),(0,P.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-1.5`,children:[e.reasoning.thinkingToggleSupported&&(0,P.jsx)(`span`,{className:`rounded-full bg-surface-container-high px-2 py-0.5 text-[10px] font-medium text-on-surface-variant`,children:t.settings.providers.capabilityThinking}),e.toolUseSupported&&(0,P.jsx)(`span`,{className:`rounded-full bg-surface-container-high px-2 py-0.5 text-[10px] font-medium text-on-surface-variant`,children:t.settings.providers.capabilityTools}),e.promptCachingSupported&&(0,P.jsx)(`span`,{className:`rounded-full bg-surface-container-high px-2 py-0.5 text-[10px] font-medium text-on-surface-variant`,children:t.settings.providers.capabilityCaching})]})]})}function cu(){let{t:e}=L(),{providers:t,isLoading:n,error:r,refetch:i}=Ri();return n?(0,P.jsx)(`div`,{className:`flex items-center justify-center py-16`,children:(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant`,children:e.common.loading})}):r?(0,P.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-16`,children:[(0,P.jsx)(`p`,{className:`text-sm text-destructive`,children:e.settings.providers.loadError}),(0,P.jsx)(`button`,{type:`button`,onClick:()=>void i(),className:`text-xs text-primary underline underline-offset-2 hover:no-underline`,children:e.common.retry})]}):t.length===0?(0,P.jsx)(`div`,{className:`flex items-center justify-center py-16`,children:(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant`,children:e.settings.providers.noProviders})}):(0,P.jsxs)(z,{variant:`solid`,className:`p-4 sm:p-6 space-y-4`,children:[(0,P.jsx)(`h2`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface`,children:e.settings.providers.title}),(0,P.jsx)(`p`,{className:`text-xs text-on-surface-variant`,children:e.settings.providers.perProviderSettings}),(0,P.jsx)(`div`,{className:`grid grid-cols-1 gap-3`,children:t.map(e=>(0,P.jsx)(et,{to:`/settings/providers/$provider`,params:{provider:e.provider},className:`block`,children:(0,P.jsx)(su,{descriptor:e})},e.provider))})]})}var lu=[{value:`auto`,labelKey:`cacheAuto`},{value:`stable-prefix`,labelKey:`cacheStablePrefix`},{value:`off`,labelKey:`cacheOff`}];function uu({cachingSupported:e,form:t,onChange:n}){let{t:r}=L(),i=r.settings.providers,a=(e,r)=>{n({...t,[e]:r})};return(0,P.jsxs)(z,{variant:`solid`,className:`space-y-4 p-4 sm:p-6`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant`,children:i.sectionCache}),e&&(0,P.jsxs)(`div`,{className:`space-y-2`,children:[(0,P.jsx)(`label`,{htmlFor:`cache-preference`,className:`text-sm text-on-surface`,children:i.cachePreference}),(0,P.jsx)(`select`,{id:`cache-preference`,value:t.promptCachePreference??`auto`,onChange:e=>a(`promptCachePreference`,e.target.value),className:`w-full rounded-xl px-4 py-2.5 text-sm bg-surface-container-high text-on-surface border border-outline-variant/20 focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20 transition-colors cursor-pointer`,children:lu.map(({value:e,labelKey:t})=>(0,P.jsx)(`option`,{value:e,children:i[t]},e))})]}),(0,P.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,P.jsx)(`label`,{htmlFor:`compaction-toggle`,className:`text-sm text-on-surface`,children:i.compaction}),(0,P.jsx)(`input`,{id:`compaction-toggle`,type:`checkbox`,checked:t.providerCompactionEnabled??!1,onChange:e=>a(`providerCompactionEnabled`,e.target.checked),className:`h-4 w-4 rounded border-outline-variant/30 accent-primary`})]})]})}function du(){let{t:e}=L(),t=e.settings.providers;return(0,P.jsxs)(z,{variant:`solid`,className:`p-6`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant`,children:e.settings.providers.sectionAdvanced}),(0,P.jsx)(`p`,{className:`mt-2 text-xs text-on-surface-variant`,children:t.reservedForFuture})]})}function fu({policy:e,form:t,onChange:n}){let{t:r}=L(),i=r.settings.providers,a=new Set(e.supportedEfforts);return(0,P.jsxs)(z,{variant:`solid`,className:`space-y-4 p-4 sm:p-6`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant`,children:i.sectionReasoning}),e.thinkingToggleSupported&&(0,P.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,P.jsx)(`label`,{htmlFor:`thinking-toggle`,className:`text-sm text-on-surface`,children:i.thinkingEnabled}),(0,P.jsx)(`input`,{id:`thinking-toggle`,type:`checkbox`,checked:t.thinkingEnabled??!1,onChange:e=>n({...t,thinkingEnabled:e.target.checked}),className:`h-4 w-4 rounded border-outline-variant/30 accent-primary`})]}),(0,P.jsxs)(`div`,{className:`space-y-2`,children:[(0,P.jsx)(`span`,{className:`text-sm text-on-surface`,children:i.reasoningEffort}),(0,P.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:au.filter(e=>a.has(e)).map(i=>(0,P.jsx)(`button`,{type:`button`,onClick:()=>n({...t,reasoningEffort:i}),className:`rounded-lg px-3 py-1.5 text-xs font-medium transition-colors cursor-pointer ${(t.reasoningEffort??e.defaultEffort)===i?`bg-primary text-on-primary`:`bg-surface-container-high text-on-surface-variant hover:bg-surface-container-highest`}`,children:r.thinking[ou[i]]},i))})]})]})}function pu({maxOutputTokensLimit:e,toolUseSupported:t,form:n,onChange:r}){let{t:i}=L(),a=i.settings.providers;return(0,P.jsxs)(z,{variant:`solid`,className:`space-y-4 p-4 sm:p-6`,children:[(0,P.jsx)(`h3`,{className:`text-xs uppercase tracking-widest font-bold text-on-surface-variant`,children:a.sectionTools}),t&&(0,P.jsxs)(`div`,{className:`space-y-2`,children:[(0,P.jsxs)(`div`,{className:`flex items-baseline justify-between`,children:[(0,P.jsx)(`label`,{htmlFor:`tool-iterations`,className:`text-sm text-on-surface`,children:a.maxToolIterations}),(0,P.jsx)(`span`,{className:`text-xs text-on-surface-variant`,children:n.maxToolIterations??`—`})]}),(0,P.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,P.jsx)(`input`,{id:`tool-iterations`,type:`range`,min:1,max:1e3,step:1,value:n.maxToolIterations??1e3,onChange:e=>r({...n,maxToolIterations:Number(e.target.value)}),className:`flex-1 h-2 bg-surface-container-lowest rounded-full appearance-none cursor-pointer accent-primary`}),(0,P.jsx)(`input`,{type:`number`,min:1,max:1e3,step:1,value:n.maxToolIterations??1e3,onChange:e=>r({...n,maxToolIterations:Number(e.target.value)}),"aria-label":a.maxToolIterations,className:`w-24 rounded-xl px-3 py-2 text-sm text-center bg-surface-container-lowest text-on-surface border border-outline-variant/20 focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20 transition-colors`})]})]}),(0,P.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,P.jsx)(`label`,{htmlFor:`max-output-tokens`,className:`text-sm text-on-surface`,children:a.maxOutputTokens}),(0,P.jsx)(`input`,{id:`max-output-tokens`,type:`number`,min:1,max:e,step:1,value:n.maxOutputTokens??``,onChange:e=>r({...n,maxOutputTokens:e.target.value?Number(e.target.value):void 0}),placeholder:a.maxOutputTokensPlaceholder.replace(`{limit}`,String(e)),className:`w-full rounded-xl px-4 py-2.5 text-sm bg-surface-container-high text-on-surface border border-outline-variant/20 placeholder:text-on-surface/30 focus:outline-none focus:border-primary/60 focus:ring-1 focus:ring-primary/20 transition-colors`})]}),t&&(0,P.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,P.jsx)(`label`,{htmlFor:`parallel-tool-calls`,className:`text-sm text-on-surface`,children:a.parallelToolCalls}),(0,P.jsx)(`input`,{id:`parallel-tool-calls`,type:`checkbox`,checked:n.parallelToolCallsEnabled??!1,onChange:e=>r({...n,parallelToolCallsEnabled:e.target.checked}),className:`h-4 w-4 rounded border-outline-variant/30 accent-primary`})]})]})}var mu=300;function hu(e,t){return JSON.stringify(e??{})===JSON.stringify(t??{})}function gu(e){return{thinkingEnabled:e.thinkingEnabled,reasoningEffort:e.reasoningEffort,maxOutputTokens:e.maxOutputTokens,maxToolIterations:e.maxToolIterations,providerCompactionEnabled:e.providerCompactionEnabled,promptCachePreference:e.promptCachePreference,parallelToolCallsEnabled:e.parallelToolCallsEnabled}}function _u(){let{provider:e}=de({from:`/_authenticated/settings/providers/$provider`}),{t}=L(),{descriptor:n,isLoading:r,error:i,refetch:a}=zi(e),o=t.settings.providers;return r?(0,P.jsx)(`div`,{className:`flex items-center justify-center py-16`,children:(0,P.jsx)(`p`,{className:`text-sm text-on-surface-variant`,children:t.common.loading})}):i||!n?(0,P.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-16`,children:[(0,P.jsx)(`p`,{className:`text-sm text-destructive`,children:o.loadError}),(0,P.jsx)(R,{variant:`ghost`,size:`sm`,onClick:()=>void a(),children:t.common.retry})]}):(0,P.jsx)(vu,{provider:e,descriptor:n,providerName:t.providers[n.provider]??n.displayName},e)}function vu({provider:e,descriptor:t,providerName:n}){let{t:r}=L(),{toast:i}=F(),a=Bi(e),o=r.settings.providers,s=gu(t.settings),[c,l]=(0,N.useState)(s),[u,d]=(0,N.useState)(s),f=(0,N.useRef)(null),p=!hu(c,u),m=(0,N.useCallback)(async()=>{if(!p)return;let e=c;try{let t=gu((await a.mutateAsync(e)).settings);d(t),l(n=>hu(n,e)?t:n)}catch(t){l(t=>hu(t,e)?u:t),i(t instanceof Error?t.message:o.saveError,`error`)}},[u,p,c,o.saveError,i,a]);return(0,N.useEffect)(()=>{if(!(!p||a.isPending))return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{m()},mu),()=>{f.current&&=(clearTimeout(f.current),null)}},[p,m,a.isPending]),(0,N.useEffect)(()=>()=>{f.current&&clearTimeout(f.current),!(!p||a.isPending)&&m()},[p,m,a.isPending]),(0,P.jsxs)(`div`,{className:`space-y-6`,children:[(0,P.jsxs)(et,{to:`/settings/providers`,className:`inline-flex items-center gap-1.5 text-xs text-on-surface-variant hover:text-on-surface transition-colors`,children:[(0,P.jsx)(Be,{size:14}),o.backToMenu]}),(0,P.jsxs)(`div`,{children:[(0,P.jsx)(`h2`,{className:`text-lg font-bold text-on-surface`,children:n}),(0,P.jsx)(`p`,{className:`mt-0.5 text-xs text-on-surface-variant`,children:o.perProviderSettings}),a.isPending&&(0,P.jsx)(`p`,{className:`mt-1 text-xs text-on-surface-variant`,role:`status`,"aria-live":`polite`,children:o.saving})]}),(0,P.jsxs)(`div`,{className:`space-y-4`,children:[(0,P.jsx)(fu,{policy:t.reasoning,form:c,onChange:l}),(0,P.jsx)(pu,{maxOutputTokensLimit:t.maxOutputTokensLimit,toolUseSupported:t.toolUseSupported,form:c,onChange:l}),(0,P.jsx)(uu,{cachingSupported:t.promptCachingSupported,form:c,onChange:l}),(0,P.jsx)(du,{})]})]})}var yu=S(`/_authenticated/settings/providers/`)({component:cu}),bu=S(`/_authenticated/settings/providers/$provider`)({loader:({context:{queryClient:e},params:t})=>e.ensureQueryData(Ii(t.provider)),component:_u}),xu=Pt.update({id:`/signup`,path:`/signup`,getParentRoute:()=>Ot}),Su=Rt.update({id:`/login`,path:`/login`,getParentRoute:()=>Ot}),Cu=na.update({id:`/_authenticated`,getParentRoute:()=>Ot}),wu=wo.update({id:`/`,path:`/`,getParentRoute:()=>Cu}),Tu=Eo.update({id:`/studio`,path:`/studio`,getParentRoute:()=>Cu}),$=ko.update({id:`/settings`,path:`/settings`,getParentRoute:()=>Cu}),Eu=Fo.update({id:`/gallery`,path:`/gallery`,getParentRoute:()=>Cu}),Du=Io.update({id:`/`,path:`/`,getParentRoute:()=>$}),Ou=es.update({id:`/tools`,path:`/tools`,getParentRoute:()=>$}),ku=ns.update({id:`/providers`,path:`/providers`,getParentRoute:()=>$}),Au=cs.update({id:`/prompts`,path:`/prompts`,getParentRoute:()=>$}),ju=ys.update({id:`/metrics`,path:`/metrics`,getParentRoute:()=>$}),Mu=bs.update({id:`/logs`,path:`/logs`,getParentRoute:()=>$}),Nu=Os.update({id:`/general`,path:`/general`,getParentRoute:()=>$}),Pu=Is.update({id:`/context`,path:`/context`,getParentRoute:()=>$}),Fu=sl.update({id:`/connectors`,path:`/connectors`,getParentRoute:()=>$}),Iu=yl.update({id:`/appearance`,path:`/appearance`,getParentRoute:()=>$}),Lu=iu.update({id:`/agents`,path:`/agents`,getParentRoute:()=>$}),Ru=yu.update({id:`/`,path:`/`,getParentRoute:()=>ku}),zu={AuthenticatedSettingsProvidersProviderRoute:bu.update({id:`/$provider`,path:`/$provider`,getParentRoute:()=>ku}),AuthenticatedSettingsProvidersIndexRoute:Ru},Bu={AuthenticatedSettingsAgentsRoute:Lu,AuthenticatedSettingsAppearanceRoute:Iu,AuthenticatedSettingsConnectorsRoute:Fu,AuthenticatedSettingsContextRoute:Pu,AuthenticatedSettingsGeneralRoute:Nu,AuthenticatedSettingsLogsRoute:Mu,AuthenticatedSettingsMetricsRoute:ju,AuthenticatedSettingsPromptsRoute:Au,AuthenticatedSettingsProvidersRoute:ku._addFileChildren(zu),AuthenticatedSettingsToolsRoute:Ou,AuthenticatedSettingsIndexRoute:Du},Vu={AuthenticatedGalleryRoute:Eu,AuthenticatedSettingsRoute:$._addFileChildren(Bu),AuthenticatedStudioRoute:Tu,AuthenticatedIndexRoute:wu},Hu={AuthenticatedRoute:Cu._addFileChildren(Vu),LoginRoute:Su,SignupRoute:xu},Uu=p({routeTree:Ot._addFileChildren(Hu)._addFileTypes(),context:{auth:{isAuthenticated:!1,user:null,isPending:!0},queryClient:ft},defaultPreload:`intent`});ut(()=>{Uu.navigate({to:`/login`})});function Wu(){let{data:e,isPending:t}=ct.useSession();return t?(0,P.jsx)(`div`,{className:`min-h-screen bg-surface-dim flex items-center justify-center`,children:(0,P.jsx)(`div`,{className:`w-6 h-6 rounded-full border-2 border-primary border-t-transparent animate-spin`})}):(0,P.jsx)(T,{router:Uu,context:{auth:{isAuthenticated:!!e?.user,user:e?.user??null,isPending:!1},queryClient:ft}})}var Gu=document.getElementById(`root`);if(!Gu)throw Error(`Root element #root not found`);(0,ot.createRoot)(Gu).render((0,P.jsx)(N.StrictMode,{children:(0,P.jsx)(Wu,{})}));export{L as i,ga as n,Dt as r,ll as t};