@iaforged/context-code 2.3.0 → 2.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/context-bootstrap.js +8 -1
- package/contextcode-bootstrap.js +7 -1
- package/dist/src/QueryEngine.js +1 -1
- package/dist/src/cli/handlers/auth.js +1 -1
- package/dist/src/cli/handlers/modelList.js +1 -1
- package/dist/src/cli/structuredIO.js +1 -1
- package/dist/src/commands/branch/index.js +1 -1
- package/dist/src/commands/login/login.js +1 -1
- package/dist/src/commands/profile/index.js +1 -1
- package/dist/src/commands/profile/profile.js +1 -1
- package/dist/src/commands/provider/index.js +1 -1
- package/dist/src/commands/provider/provider.js +1 -1
- package/dist/src/components/ConsoleOAuthFlow.js +1 -1
- package/dist/src/components/LogoV2/Opus1mMergeNotice.js +1 -1
- package/dist/src/components/ModelPicker.js +1 -1
- package/dist/src/components/SessionTokenFooter.js +1 -0
- package/dist/src/constants/oauth.js +1 -1
- package/dist/src/core/providers/providerCore.js +1 -1
- package/dist/src/hooks/useTypeahead.js +1 -1
- package/dist/src/main.js +1 -1
- package/dist/src/screens/REPL.js +1 -1
- package/dist/src/services/api/openai.js +1 -1
- package/dist/src/services/oauth/auth-code-listener.js +1 -1
- package/dist/src/services/oauth/client.js +1 -1
- package/dist/src/services/oauth/geminiCli.js +1 -1
- package/dist/src/utils/auth.js +1 -1
- package/dist/src/utils/claudeInChrome/setup.js +1 -1
- package/dist/src/utils/config.js +1 -1
- package/dist/src/utils/env.js +1 -1
- package/dist/src/utils/envUtils.js +1 -1
- package/dist/src/utils/git.js +1 -1
- package/dist/src/utils/localInstaller.js +1 -1
- package/dist/src/utils/model/configs.js +1 -1
- package/dist/src/utils/model/model.js +1 -1
- package/dist/src/utils/model/modelAllowlist.js +1 -1
- package/dist/src/utils/model/modelOptions.js +1 -1
- package/dist/src/utils/model/providerBaseUrls.js +1 -1
- package/dist/src/utils/model/providerCatalog.js +1 -1
- package/dist/src/utils/model/providerModels.js +1 -1
- package/dist/src/utils/model/providerProfiles.js +1 -1
- package/dist/src/utils/model/providerProfilesDb.js +1 -1
- package/dist/src/utils/model/providers.js +1 -1
- package/dist/src/utils/model/validateModel.js +1 -1
- package/dist/src/utils/permissions/filesystem.js +1 -1
- package/dist/src/utils/ripgrep.js +1 -1
- package/dist/webapp/ngsw.json +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsxs as e,jsx as o,Fragment as r}from"react/jsx-runtime";import{c as i}from"react/compiler-runtime";import{useCallback as t,useEffect as n,useRef as a,useState as s}from"react";import{logEvent as l}from"../services/analytics/index.js";import{installOAuthTokens as d}from"../cli/handlers/auth.js";import{useTerminalSize as c}from"../hooks/useTerminalSize.js";import{setClipboard as u}from"../ink/termio/osc.js";import{useTerminalNotification as p}from"../ink/useTerminalNotification.js";import{Box as m,Link as h,Text as g}from"../ink.js";import{useKeybinding as f}from"../keybindings/useKeybinding.js";import{getSSLErrorHint as _}from"../services/api/errorUtils.js";import{sendNotification as v}from"../services/notifier.js";import{OAuthService as C}from"../services/oauth/index.js";import{getOAuthRequestDetails as y}from"../services/oauth/client.js";import{checkGeminiGoogleCredentialsValid as b,getOauthAccountInfo as A,saveGeminiGoogleOAuthTokens as k,saveProviderApiKey as P,validateForceLoginOrg as x}from"../utils/auth.js";import{startGeminiCliOAuthFlow as O}from"../services/oauth/geminiCli.js";import{ensureProviderProfile as I,isProfiledProvider as S,resolveProviderProfile as w,setActiveProviderProfile as z,setProviderProfileLastModel as D}from"../utils/model/providerProfiles.js";import{setStoredActiveProviderPreference as M,setStoredLastModelForProvider as T}from"../utils/model/providerProfilesDb.js";import{logError as j}from"../utils/log.js";import{getVisibleProvider as E}from"../utils/model/providerCatalog.js";import{getConfiguredProviderBaseUrl as R,setProviderBaseUrl as U}from"../utils/model/providerBaseUrls.js";import{getSettings_DEPRECATED as K}from"../utils/settings/settings.js";import{setCustomProviderModels as W}from"../utils/config.js";import{Select as L}from"./CustomSelect/select.js";import{KeyboardShortcutHint as G}from"./design-system/KeyboardShortcutHint.js";import{Spinner as B}from"./Spinner.js";import N from"./TextInput.js";const $=["deepseek","minimax","openrouter","zai","nvidia","ollama","openai","claudeai","gemini-google","gemini-api","console"];function sortLoginProviderOptions(e){const o=new Map($.map((e,o)=>[e,o]));return[...e].sort((e,r)=>(o.get(e.value)??Number.MAX_SAFE_INTEGER)-(o.get(r.value)??Number.MAX_SAFE_INTEGER))}const F="Pega aqui el codigo si se solicita > ";function formatOAuthDebugDetails(e,o){if("openai"!==e)return"";const r=y({provider:e,port:o,isManual:!1});return[`authorize=${r.authorizeUrl}`,`redirect_uri=${r.redirectUri}`,`scope=${r.scopes.join(" ")}`].join("\n")}export function ConsoleOAuthFlow({onDone:r,startingMessage:i,mode:y="login",forceLoginMethod:A,profileName:R}){const L=K()||{},B=A??L.forceLoginMethod,N=L.forceLoginOrgUUID,$="claudeai"===B?"Método de acceso preseleccionado: Plan de suscripción (Context Pro/Max)":"console"===B?"Método de acceso preseleccionado: Facturación por uso de API (Anthropic Console)":"openai"===B?"Método de acceso preseleccionado: OpenAI / Codex OAuth":null,F=p(),[V,X]=s(()=>"setup-token"===y||"claudeai"===B||"console"===B||"openai"===B?{state:"ready_to_start"}:{state:"idle"}),[Y,q]=s(""),[H,Z]=s(0),[J]=s(()=>new C),[Q,ee]=s(()=>"openai"===B?"openai":"anthropic"),[oe,re]=s(()=>"setup-token"===y||"claudeai"===B),[ie,te]=s(!1),[ne,ae]=s(!1),se=c().columns-37-1,[le,de]=s(""),[ce,ue]=s(0),[pe,me]=s(""),[he,ge]=s(0),[fe,_e]=s(""),[ve,Ce]=s(""),[ye,be]=s(""),[Ae,ke]=s(0),[Pe,xe]=s(0),[Oe,Ie]=s(0);n(()=>{"claudeai"===B?l("tengu_oauth_claudeai_forced",{}):"console"===B&&l("tengu_oauth_console_forced",{})},[B]),n(()=>{if("about_to_retry"===V.state){const e=setTimeout(X,1e3,V.nextState);return()=>clearTimeout(e)}},[V]),f("confirm:yes",()=>{l("tengu_oauth_success",{loginWithClaudeAi:oe}),r(Q)},{context:"Confirmation",isActive:"success"===V.state&&"setup-token"!==y}),n(()=>{if("success"===V.state&&!process.stdin.isTTY){const e=setTimeout(()=>{l("tengu_oauth_success",{loginWithClaudeAi:oe}),r(Q)},800);return()=>clearTimeout(e)}},[V.state,Q,oe,r]),f("confirm:yes",()=>{X({state:"idle"})},{context:"Confirmation",isActive:"platform_setup"===V.state}),f("confirm:yes",()=>{De()},{context:"Confirmation",isActive:"provider_google_setup"===V.state}),f("confirm:yes",()=>{"error"===V.state&&V.toRetry&&(q(""),X({state:"about_to_retry",nextState:V.toRetry}))},{context:"Confirmation",isActive:"error"===V.state&&!!V.toRetry}),f("cancel",()=>{X({state:"idle"})},{context:"Confirmation",isActive:"provider_api_key_input"===V.state||"provider_local_setup"===V.state||"provider_google_setup"===V.state||"error"===V.state}),n(()=>{"c"===Y&&"waiting_for_login"===V.state&&ie&&!ne&&(u(V.url).then(e=>{e&&process.stdout.write(e),ae(!0),setTimeout(ae,2e3,!1)}),q(""))},[Y,V,ie,ne]);const Se=t(async(e,o)=>{const i=e.trim();if(i)try{await P(o,i),de(""),ue(0);const e=E(o).label;v({message:`API key de ${e} guardada`,notificationType:"auth_success"},F),r(o)}catch(e){j(e),X({state:"error",message:e.message,toRetry:{state:"provider_api_key_input",provider:o}})}else X({state:"error",message:"Debes ingresar una API key.",toRetry:{state:"provider_api_key_input",provider:o}})},[r,F]),we=t((e,o)=>{const i=e.trim();if(i)try{const e=U(o,i);me(e),ge(0),v({message:`URL de ${E(o).label} guardada`,notificationType:"auth_success"},F),r(o)}catch(e){j(e),X({state:"error",message:e.message,toRetry:{state:"provider_local_setup",provider:o}})}else X({state:"error",message:"Debes ingresar una URL para Ollama.",toRetry:{state:"provider_local_setup",provider:o}})},[r,F]),ze=t((e,o)=>{const i=V;if("custom_provider_wizard"===i.state&&i.provider)if("endpoint"===e){const e=o.trim();if(e&&!e.startsWith("http"))return void X({state:"error",message:"La URL debe empezar con http:// o https://.",toRetry:i});if(!e)return void X({state:"error",message:"El endpoint es obligatorio. Ejemplo: http://localhost:8001/v1",toRetry:i});X({state:"custom_provider_wizard",provider:i.provider,step:"api_key",apiKey:i.apiKey,endpoint:e,model:i.model})}else if("api_key"===e){const e=o.trim();if(!e)return void X({state:"error",message:"La API key no puede estar vacia.",toRetry:i});X({state:"custom_provider_wizard",provider:i.provider,step:"model_list",apiKey:e,endpoint:i.endpoint,model:"",availableModels:[],modelsLoading:!0});const r=new AbortController,t=setTimeout(()=>r.abort(),15e3);fetch(`${i.endpoint}/models`,{headers:{Authorization:`Bearer ${e}`},signal:r.signal}).then(e=>e.json()).then(e=>{clearTimeout(t);const o=e.data?.map(e=>e.id)||[];X(e=>"custom_provider_wizard"!==e.state||"model_list"!==e.step?e:{...e,availableModels:o,modelsLoading:!1})}).catch(e=>{clearTimeout(t),j(e),X(e=>"custom_provider_wizard"!==e.state||"model_list"!==e.step?e:{...e,availableModels:[],modelsLoading:!1})})}else if("model"===e){const e="model_list"===i.step&&Array.isArray(i.availableModels)?i.availableModels:[];let t=null;try{if(S(i.provider))if(R&&R.trim()){const e=I(i.provider,R.trim());z(e.id),t=e.id}else t=w(i.provider,{createIfMissing:!0})?.id??null}catch(e){j(e)}P(i.provider,i.apiKey).then(()=>{U(i.provider,i.endpoint);try{M(i.provider)}catch(e){j(e)}const n=o?.trim();if(n)try{T(i.provider,n),S(i.provider)&&D(i.provider,n)}catch(e){j(e)}if(e.length>0)try{W(i.provider,e,t)}catch(e){j(e)}v({message:`Configuracion de ${E(i.provider).label} guardada`,notificationType:"auth_success"},F),r(i.provider)}).catch(e=>{j(e),X({state:"error",message:e.message,toRetry:i})})}},[r,F,V,R]),De=t(async()=>{X({state:"provider_google_auth_running"});try{if(await b())return void r("gemini-google");const e=await O();k(e);if(!await b())return v({message:"OAuth de Gemini guardado; Code Assist no valido el proyecto de cuota",notificationType:"auth_success"},F),void r("gemini-google");v({message:"Credenciales de Gemini Google listas",notificationType:"auth_success"},F),r("gemini-google")}catch(e){j(e),X({state:"error",message:e.message,toRetry:{state:"provider_google_setup"}})}},[r,F]),Me=t(async()=>{try{l("tengu_oauth_flow_start",{loginWithClaudeAi:oe,provider:Q});const e=await J.startOAuthFlow(async e=>{X({state:"waiting_for_login",url:e}),setTimeout(te,3e3,!0)},{loginWithClaudeAi:oe,provider:Q,inferenceOnly:"setup-token"===y,expiresIn:"setup-token"===y?31536e3:void 0,orgUUID:N}).catch(e=>{const o=e.message.includes("Token exchange failed"),r=_(e),i=J.getPort(),t="openai"===Q&&i?formatOAuthDebugDetails(Q,i):"";throw X({state:"error",message:r??(o?"No se pudo intercambiar el codigo de autorizacion por el token de acceso. Intentalo de nuevo."+(t?`\n${t}`:""):e.message),toRetry:"setup-token"===y?{state:"ready_to_start"}:{state:"idle"}}),l("tengu_oauth_token_exchange_error",{error:e.message,ssl_error:null!==r}),e});if("setup-token"===y)X({state:"success",token:e.accessToken});else{X({state:"creating_api_key"});const o=R?w("openai"===Q?"openai":"anthropic",R):void 0;if(await d(e,Q,o?.id),"anthropic"===Q){const e=await x();if(!e.valid)throw new Error(e.message)}X({state:"success"}),v({message:"openai"===Q?"Inicio de sesión con OpenAI / Codex completado":"Inicio de sesión en Context Code completado",notificationType:"auth_success"},F)}}catch(e){const o=e.message,r=_(e),i=J.getPort(),t="openai"===Q&&i?formatOAuthDebugDetails(Q,i):"";X({state:"error",message:r??("openai"===Q&&t&&!o.includes("redirect_uri=")?`${o}\n${t}`:o),toRetry:{state:"setup-token"===y?"ready_to_start":"idle"}}),l("tengu_oauth_error",{error:o,ssl_error:null!==r})}},[Q,J,te,oe,y,N,F]),Te=a(!1);return n(()=>{"ready_to_start"!==V.state||Te.current||(Te.current=!0,process.nextTick((e,o)=>{e(),o.current=!1},Me,Te))},[V.state,Me]),n(()=>{if("setup-token"===y&&"success"===V.state){const e=setTimeout((e,o)=>{l("tengu_oauth_success",{loginWithClaudeAi:e}),o(Q)},500,oe,r,Q);return()=>clearTimeout(e)}},[y,V,oe,r,Q]),n(()=>()=>{J.cleanup()},[J]),e(m,{flexDirection:"column",gap:1,children:["waiting_for_login"===V.state&&ie&&e(m,{flexDirection:"column",gap:1,paddingBottom:1,children:[e(m,{paddingX:1,children:[e(g,{dimColor:!0,children:["Browser didn't open? Use the url below to sign in"," "]}),o(g,ne?{color:"success",children:"(Copied!)"}:{dimColor:!0,children:o(G,{shortcut:"c",action:"copiar",parens:!0})})]}),o(h,{url:V.url,children:o(g,{dimColor:!0,children:V.url})})]},"urlToCopy"),"setup-token"===y&&"success"===V.state&&V.token&&e(m,{flexDirection:"column",gap:1,paddingTop:1,children:[o(g,{color:"success",children:"✓ Long-lived authentication token created successfully!"}),e(m,{flexDirection:"column",gap:1,children:[o(g,{children:"Your OAuth token (valid for 1 year):"}),o(g,{color:"warning",children:V.token}),o(g,{dimColor:!0,children:"Store this token securely. You won't be able to see it again."}),o(g,{dimColor:!0,children:"Use this token by setting: export CONTEXT_CODE_OAUTH_TOKEN=<token>"})]})]},"tokenOutput"),o(m,{paddingLeft:1,flexDirection:"column",gap:1,children:o(OAuthStatusMessage,{oauthStatus:V,oauthProvider:Q,mode:y,startingMessage:i,forcedMethodMessage:$,showPastePrompt:ie,pastedCode:Y,setPastedCode:q,cursorOffset:H,setCursorOffset:Z,textInputColumns:se,handleSubmitCode:async function(e,o){try{const[r,i]=e.split("#");if(!r||!i)return void X({state:"error",message:"Codigo invalido. Asegurate de copiar el codigo completo",toRetry:{state:"waiting_for_login",url:o}});l("tengu_oauth_manual_entry",{}),J.handleManualAuthCodeInput({authorizationCode:r,state:i})}catch(e){j(e),X({state:"error",message:e.message,toRetry:{state:"waiting_for_login",url:o}})}},setOAuthStatus:X,setLoginWithClaudeAi:re,setOAuthProvider:ee,providerApiKey:le,setProviderApiKey:de,providerApiKeyCursorOffset:ce,setProviderApiKeyCursorOffset:ue,handleProviderApiKeySubmit:Se,providerBaseUrl:pe,setProviderBaseUrlInput:me,providerBaseUrlCursorOffset:he,setProviderBaseUrlCursorOffset:ge,handleProviderBaseUrlSubmit:we,onDone:r,wizardApiKey:fe,setWizardApiKey:_e,wizardEndpoint:ve,setWizardEndpoint:Ce,wizardModel:ye,setWizardModel:be,wizardApiKeyCursor:Ae,setWizardApiKeyCursor:ke,wizardEndpointCursor:Pe,setWizardEndpointCursor:xe,wizardModelCursor:Oe,setWizardModelCursor:Ie,handleCustomProviderWizardSubmit:ze})})]})}function OAuthStatusMessage(t){const n=i(68),{oauthStatus:a,oauthProvider:s,mode:d,startingMessage:c,forcedMethodMessage:u,showPastePrompt:p,pastedCode:f,setPastedCode:_,cursorOffset:v,setCursorOffset:C,textInputColumns:y,handleSubmitCode:b,setOAuthStatus:k,setLoginWithClaudeAi:P,setOAuthProvider:x,providerApiKey:O,setProviderApiKey:I,providerApiKeyCursorOffset:S,setProviderApiKeyCursorOffset:w,handleProviderApiKeySubmit:z,providerBaseUrl:D,setProviderBaseUrlInput:M,providerBaseUrlCursorOffset:T,setProviderBaseUrlCursorOffset:j,handleProviderBaseUrlSubmit:U,onDone:K,wizardApiKey:W,setWizardApiKey:G,wizardEndpoint:$,setWizardEndpoint:V,wizardModel:X,setWizardModel:Y,wizardApiKeyCursor:q,setWizardApiKeyCursor:H,wizardEndpointCursor:Z,setWizardEndpointCursor:J,wizardModelCursor:Q,setWizardModelCursor:ee,handleCustomProviderWizardSubmit:oe}=t;switch(a.state){case"idle":{const r=c||"Context Code puede usarse con tu suscripción de Claude, la facturación de Anthropic Console o OpenAI / Codex OAuth.";let i,t,a,s,d,u,p;return n[0]!==r?(i=o(g,{bold:!0,children:r}),n[0]=r,n[1]=i):i=n[1],n[2]===Symbol.for("react.memo_cache_sentinel")?(t=o(g,{children:"Selecciona el metodo de acceso:"}),n[2]=t):t=n[2],n[3]===Symbol.for("react.memo_cache_sentinel")?(a={label:e(g,{children:["Claude account with subscription ·"," ",o(g,{dimColor:!0,children:"Pro, Max, Team, or Enterprise"}),!1,"\n"]}),value:"claudeai"},n[3]=a):a=n[3],n[4]===Symbol.for("react.memo_cache_sentinel")?(s={label:e(g,{children:["Anthropic Console account ·"," ",o(g,{dimColor:!0,children:"API usage billing"}),"\n"]}),value:"console"},n[4]=s):s=n[4],n[5]===Symbol.for("react.memo_cache_sentinel")?(d=[a,s,{label:e(g,{children:["Cuenta de OpenAI / Codex ·"," ",o(g,{dimColor:!0,children:"Login OAuth"}),"\n"]}),value:"openai"},{label:e(g,{children:["OpenRouter ·"," ",o(g,{dimColor:!0,children:"API key / OpenAI-compatible"}),"\n"]}),value:"openrouter"},{label:e(g,{children:["Ollama ·"," ",o(g,{dimColor:!0,children:"Servidor local compatible"}),"\n"]}),value:"ollama"},{label:e(g,{children:["Gemini API - ",o(g,{dimColor:!0,children:"API key / OpenAI-compatible"}),"\n"]}),value:"gemini-api"},{label:e(g,{children:["Gemini Google - ",o(g,{dimColor:!0,children:"OAuth/ADC de Google"}),"\n"]}),value:"gemini-google"},{label:e(g,{children:["Z.AI ·"," ",o(g,{dimColor:!0,children:"API key / OpenAI-compatible"}),"\n"]}),value:"zai"},{label:e(g,{children:["MiniMax ·"," ",o(g,{dimColor:!0,children:"API key / Anthropic-compatible"}),"\n"]}),value:"minimax"},{label:e(g,{children:["NVIDIA API ·"," ",o(g,{dimColor:!0,children:"API key / build.nvidia.com"}),"\n"]}),value:"nvidia"},{label:e(g,{children:["DeepSeek ·"," ",o(g,{dimColor:!0,children:"API key / contexto 1M (V4)"}),"\n"]}),value:"deepseek"},{label:e(g,{children:["Custom OpenAI ·"," ",o(g,{dimColor:!0,children:"Wizard API key + endpoint"}),"\n"]}),value:"custom-openai"},{label:e(g,{children:["Custom Anthropic ·"," ",o(g,{dimColor:!0,children:"Wizard API key + endpoint"}),"\n"]}),value:"custom-anthropic"}],n[5]=d):d=n[5],n[6]!==P||n[7]!==k||n[8]!==x||n[65]!==K?(u=o(m,{children:o(L,{options:sortLoginProviderOptions(d),onChange:e=>{"platform"===e?(l("tengu_oauth_platform_selected",{}),k({state:"platform_setup"})):"openai"===e?(l("tengu_oauth_openai_selected",{}),x("openai"),P(!1),k({state:"ready_to_start"})):"openrouter"===e?k({state:"provider_api_key_input",provider:"openrouter"}):"gemini-api"===e||"zai"===e||"minimax"===e||"nvidia"===e||"deepseek"===e?k({state:"provider_api_key_input",provider:e}):"gemini-google"===e?k({state:"provider_google_setup"}):"ollama"===e||"ollama-cloud"===e?(M(R(e)),j(0),k({state:"provider_local_setup",provider:e})):"custom-openai"===e||"custom-anthropic"===e?k({state:"custom_provider_wizard",provider:e,step:"endpoint",apiKey:"",endpoint:"",model:""}):(x("anthropic"),k({state:"ready_to_start"}),"claudeai"===e?(l("tengu_oauth_claudeai_selected",{}),P(!0)):(l("tengu_oauth_console_selected",{}),P(!1)))}})}),n[6]=P,n[7]=k,n[8]=x,n[65]=K,n[66]=u):u=n[66],n[10]!==i||n[11]!==u?(p=e(m,{flexDirection:"column",gap:1,marginTop:1,children:[i,t,u]}),n[10]=i,n[11]=u,n[12]=p):p=n[12],p}case"provider_api_key_input":{let r,i,t,s;if(n[50]!==a.provider?(r=e(g,{bold:!0,children:["Ingresa la API key de ",E(a.provider).label]}),n[50]=a.provider,n[51]=r):r=n[51],n[52]!==a.provider){const r=E(a.provider);i=e(m,{flexDirection:"column",gap:0,children:[o(g,{dimColor:!0,children:r.description}),e(g,{dimColor:!0,children:["Siguiente paso: ",r.setup.nextStep]})]}),n[52]=a.provider,n[53]=i}else i=n[53];return n[54]!==O||n[55]!==S||n[56]!==I||n[57]!==w||n[58]!==y||n[59]!==z?(t=e(m,{children:[o(g,{children:"API key > "}),o(N,{value:O,onChange:I,onSubmit:e=>z(e,a.provider),cursorOffset:S,onChangeCursorOffset:w,columns:y,mask:"*"})]}),n[54]=O,n[55]=S,n[56]=I,n[57]=w,n[58]=y,n[59]=z,n[60]=t):t=n[60],n[61]!==r||n[62]!==i||n[63]!==t?(s=e(m,{flexDirection:"column",gap:1,children:[r,i,t]}),n[61]=r,n[62]=i,n[63]=t,n[64]=s):s=n[64],s}case"provider_local_setup":{const r=E(a.provider);return e(m,{flexDirection:"column",gap:1,children:[o(g,{bold:!0,children:r.label}),o(g,{dimColor:!0,children:r.setup.intro}),o(g,{dimColor:!0,children:r.setup.nextStep}),o(g,{children:"URL del servidor > "}),o(m,{children:o(N,{value:D,onChange:M,onSubmit:e=>U(e,a.provider),cursorOffset:T,onChangeCursorOffset:j,columns:y})}),e(g,{color:"success",children:["Presiona ",o(g,{bold:!0,children:"Enter"})," para guardar la URL y continuar."]})]})}case"provider_google_setup":return e(m,{flexDirection:"column",gap:1,children:[o(g,{bold:!0,children:"Gemini Google OAuth"}),o(g,{dimColor:!0,children:"Context Code usara el flujo OAuth compatible con Gemini CLI y abrira Google en el navegador."}),o(g,{dimColor:!0,children:"Se guardara el access token y refresh token en el perfil activo de Gemini Google."}),e(g,{color:"success",children:["Presiona ",o(g,{bold:!0,children:"Enter"})," para iniciar sesion con tu cuenta de Google."]})]});case"provider_google_auth_running":return e(m,{children:[o(B,{}),o(g,{children:"Abriendo Google OAuth para Gemini..."})]});case"custom_provider_wizard":{const r=E(a.provider),i="custom-openai"===a.provider?"https://api.openai.com/v1":"https://api.anthropic.com/v1";if("endpoint"===a.step)return e(m,{flexDirection:"column",gap:1,children:[e(g,{bold:!0,children:[r.label," - Paso 1/3"]}),o(g,{dimColor:!0,children:"URL del servidor API (ej: http://localhost:8001/v1)"}),o(g,{children:"Endpoint > "}),o(m,{children:o(N,{value:$,onChange:V,onSubmit:oe.bind(null,"endpoint"),cursorOffset:Z,onChangeCursorOffset:J,columns:y})}),e(g,{dimColor:!0,children:["Default: ",i]}),e(g,{color:"success",children:["Presiona ",o(g,{bold:!0,children:"Enter"})," para continuar."]})]});if("api_key"===a.step)return e(m,{flexDirection:"column",gap:1,children:[e(g,{bold:!0,children:[r.label," - Paso 2/3"]}),e(g,{dimColor:!0,children:["Ingresa tu API key para ",r.label,"."]}),o(g,{children:"API key > "}),o(m,{children:o(N,{value:W,onChange:G,onSubmit:oe.bind(null,"api_key"),cursorOffset:q,onChangeCursorOffset:H,columns:y,mask:"*"})}),e(g,{color:"success",children:["Presiona ",o(g,{bold:!0,children:"Enter"})," para obtener modelos disponibles."]})]});if("model_list"===a.step){if(a.modelsLoading)return e(m,{flexDirection:"column",gap:1,children:[e(g,{bold:!0,children:[r.label," - Cargando modelos..."]}),e(m,{children:[o(B,{}),e(g,{children:[" Obteniendo lista de modelos desde ",a.endpoint,"/models"]})]})]});const i=a.availableModels||[];if(i.length>0){const t=i.map(e=>({label:e,value:e}));return e(m,{flexDirection:"column",gap:1,children:[e(g,{bold:!0,children:[r.label," - Paso 3/3"]}),o(g,{dimColor:!0,children:"Selecciona un modelo de la lista:"}),o(m,{children:o(L,{options:t,onChange:e=>{k(o=>({...o,model:e})),oe("model",e)}})}),e(g,{color:"success",children:["Presiona ",o(g,{bold:!0,children:"Enter"})," para guardar la configuracion."]})]})}return e(m,{flexDirection:"column",gap:1,children:[e(g,{bold:!0,children:[r.label," - Paso 3/3"]}),o(g,{dimColor:!0,children:"No se pudo obtener la lista de modelos."}),o(g,{dimColor:!0,children:"Ingresa el nombre del modelo manualmente."}),o(g,{dimColor:!0,children:"Podras cambiarlo luego con el comando /model."}),o(g,{children:"Modelo > "}),o(m,{children:o(N,{value:X,onChange:Y,onSubmit:oe.bind(null,"model"),cursorOffset:Q,onChangeCursorOffset:ee,columns:y})}),e(g,{color:"success",children:["Presiona ",o(g,{bold:!0,children:"Enter"})," para guardar la configuracion."]})]})}break}case"platform_setup":{let r,i,t,a,s,l,d,c;return n[12]===Symbol.for("react.memo_cache_sentinel")?(r=o(g,{bold:!0,children:"Usando plataformas de terceros"}),n[12]=r):r=n[12],n[13]===Symbol.for("react.memo_cache_sentinel")?(i=o(g,{children:"Context Code soporta Amazon Bedrock, Microsoft Foundry y Vertex AI. Configura las variables de entorno requeridas y luego reinicia Context Code."}),t=o(g,{children:"Si formas parte de una organización empresarial, contacta a tu administrador para las instrucciones de configuración."}),n[13]=i,n[14]=t):(i=n[13],t=n[14]),n[15]===Symbol.for("react.memo_cache_sentinel")?(a=o(g,{bold:!0,children:"Documentation:"}),n[15]=a):a=n[15],n[16]===Symbol.for("react.memo_cache_sentinel")?(s=e(g,{children:["· Amazon Bedrock:"," ",o(h,{url:"https://docs.iaforged.com/",children:"https://docs.iaforged.com/"})]}),n[16]=s):s=n[16],n[17]===Symbol.for("react.memo_cache_sentinel")?(l=e(g,{children:["· Microsoft Foundry:"," ",o(h,{url:"https://docs.iaforged.com/",children:"https://docs.iaforged.com/"})]}),n[17]=l):l=n[17],n[18]===Symbol.for("react.memo_cache_sentinel")?(d=e(m,{flexDirection:"column",marginTop:1,children:[a,s,l,e(g,{children:["· Vertex AI:"," ",o(h,{url:"https://docs.iaforged.com/",children:"https://docs.iaforged.com/"})]})]}),n[18]=d):d=n[18],n[19]===Symbol.for("react.memo_cache_sentinel")?(c=e(m,{flexDirection:"column",gap:1,marginTop:1,children:[r,e(m,{flexDirection:"column",gap:1,children:[i,t,d,o(m,{marginTop:1,children:e(g,{dimColor:!0,children:["Presiona ",o(g,{bold:!0,children:"Enter"})," para volver a las opciones de acceso."]})})]})]}),n[19]=c):c=n[19],c}case"waiting_for_login":{let r,i,t,s;return n[20]!==u?(r=u&&o(m,{children:o(g,{dimColor:!0,children:u})}),n[20]=u,n[21]=r):r=n[21],n[22]!==p?(i=!p&&e(m,{children:[o(B,{}),o(g,{children:"Abriendo el navegador para iniciar sesión…"})]}),n[22]=p,n[23]=i):i=n[23],n[24]!==v||n[25]!==b||n[26]!==a.url||n[27]!==f||n[28]!==C||n[29]!==_||n[30]!==p||n[31]!==y?(t=p&&e(m,{children:[o(g,{children:F}),o(N,{value:f,onChange:_,onSubmit:e=>b(e,a.url),cursorOffset:v,onChangeCursorOffset:C,columns:y,mask:"*"})]}),n[24]=v,n[25]=b,n[26]=a.url,n[27]=f,n[28]=C,n[29]=_,n[30]=p,n[31]=y,n[32]=t):t=n[32],n[33]!==r||n[34]!==i||n[35]!==t?(s=e(m,{flexDirection:"column",gap:1,children:[r,i,t]}),n[33]=r,n[34]=i,n[35]=t,n[36]=s):s=n[36],s}case"creating_api_key":{let r;return n[37]===Symbol.for("react.memo_cache_sentinel")?(r=o(m,{flexDirection:"column",gap:1,children:e(m,{children:[o(B,{}),o(g,{children:"Creando API key para Context Code…"})]})}),n[37]=r):r=n[37],r}case"about_to_retry":{let e;return n[38]===Symbol.for("react.memo_cache_sentinel")?(e=o(m,{flexDirection:"column",gap:1,children:o(g,{color:"permission",children:"Reintentando…"})}),n[38]=e):e=n[38],e}case"success":{let i,t;if(n[39]!==d||n[40]!==a.token){const t="openai"===s?"Inicio de sesión en OpenAI / Codex exitoso. Presiona ":"Inicio de sesión exitoso. Presiona ";i="setup-token"===d&&a.token?null:e(r,{children:[A()?.emailAddress?e(g,{dimColor:!0,children:["Sesión iniciada como"," ",o(g,{children:A()?.emailAddress})]}):null,e(g,{color:"success",children:[t,o(g,{bold:!0,children:"Enter"})," para continuar…"]})]}),n[39]=d,n[40]=a.token,n[41]=i}else i=n[41];return n[42]!==i?(t=o(m,{flexDirection:"column",children:i}),n[42]=i,n[43]=t):t=n[43],t}case"error":{let r,i,t;return n[44]!==a.message?(r=e(g,{color:"error",children:["OAuth error: ",a.message]}),n[44]=a.message,n[45]=r):r=n[45],n[46]!==a.toRetry?(i=a.toRetry&&o(m,{marginTop:1,children:e(g,{color:"permission",children:["Press ",o(g,{bold:!0,children:"Enter"})," to retry."]})}),n[46]=a.toRetry,n[47]=i):i=n[47],n[48]!==r||n[49]!==i?(t=e(m,{flexDirection:"column",gap:1,children:[r,i]}),n[48]=r,n[49]=i,n[50]=t):t=n[50],t}default:return null}}
|
|
1
|
+
import{jsxs as e,jsx as o,Fragment as r}from"react/jsx-runtime";import{c as i}from"react/compiler-runtime";import{useCallback as t,useEffect as n,useRef as a,useState as s}from"react";import{logEvent as l}from"../services/analytics/index.js";import{installOAuthTokens as d}from"../cli/handlers/auth.js";import{useTerminalSize as c}from"../hooks/useTerminalSize.js";import{setClipboard as u}from"../ink/termio/osc.js";import{useTerminalNotification as p}from"../ink/useTerminalNotification.js";import{Box as m,Link as h,Text as g}from"../ink.js";import{useKeybinding as f}from"../keybindings/useKeybinding.js";import{getSSLErrorHint as _}from"../services/api/errorUtils.js";import{sendNotification as v}from"../services/notifier.js";import{OAuthService as C}from"../services/oauth/index.js";import{getOAuthRequestDetails as y}from"../services/oauth/client.js";import{checkGeminiGoogleCredentialsValid as b,getOauthAccountInfo as A,saveGeminiGoogleOAuthTokens as k,saveProviderApiKey as P,validateForceLoginOrg as x}from"../utils/auth.js";import{startGeminiCliOAuthFlow as I}from"../services/oauth/geminiCli.js";import{ensureProviderProfile as O,isProfiledProvider as S,resolveProviderProfile as z,setActiveProviderProfile as w,setProviderProfileLastModel as D}from"../utils/model/providerProfiles.js";import{setStoredActiveProviderPreference as M,setStoredLastModelForProvider as T}from"../utils/model/providerProfilesDb.js";import{logError as j}from"../utils/log.js";import{getVisibleProvider as E}from"../utils/model/providerCatalog.js";import{getConfiguredProviderBaseUrl as R,setProviderBaseUrl as U}from"../utils/model/providerBaseUrls.js";import{getSettings_DEPRECATED as K}from"../utils/settings/settings.js";import{setCustomProviderModels as W}from"../utils/config.js";import{Select as L}from"./CustomSelect/select.js";import{KeyboardShortcutHint as G}from"./design-system/KeyboardShortcutHint.js";import{Spinner as B}from"./Spinner.js";import N from"./TextInput.js";const F=["deepseek","minimax","openrouter","zai","nvidia","ollama","openai","claudeai","gemini-google","gemini-api","console","xai","gmi","novita","stepfun","huggingface","opencode-zen","arcee","alibaba","kimi"];function sortLoginProviderOptions(e){const o=new Map(F.map((e,o)=>[e,o]));return[...e].sort((e,r)=>(o.get(e.value)??Number.MAX_SAFE_INTEGER)-(o.get(r.value)??Number.MAX_SAFE_INTEGER))}const $="Pega aqui el codigo si se solicita > ";function formatOAuthDebugDetails(e,o){if("openai"!==e)return"";const r=y({provider:e,port:o,isManual:!1});return[`authorize=${r.authorizeUrl}`,`redirect_uri=${r.redirectUri}`,`scope=${r.scopes.join(" ")}`].join("\n")}export function ConsoleOAuthFlow({onDone:r,startingMessage:i,mode:y="login",forceLoginMethod:A,profileName:R}){const L=K()||{},B=A??L.forceLoginMethod,N=L.forceLoginOrgUUID,F="claudeai"===B?"Método de acceso preseleccionado: Plan de suscripción (Context Pro/Max)":"console"===B?"Método de acceso preseleccionado: Facturación por uso de API (Anthropic Console)":"openai"===B?"Método de acceso preseleccionado: OpenAI / Codex OAuth":null,$=p(),[H,V]=s(()=>"setup-token"===y||"claudeai"===B||"console"===B||"openai"===B?{state:"ready_to_start"}:{state:"idle"}),[X,Y]=s(""),[q,Z]=s(0),[Q]=s(()=>new C),[J,ee]=s(()=>"openai"===B?"openai":"anthropic"),[oe,re]=s(()=>"setup-token"===y||"claudeai"===B),[ie,te]=s(!1),[ne,ae]=s(!1),se=c().columns-37-1,[le,de]=s(""),[ce,ue]=s(0),[pe,me]=s(""),[he,ge]=s(0),[fe,_e]=s(""),[ve,Ce]=s(""),[ye,be]=s(""),[Ae,ke]=s(0),[Pe,xe]=s(0),[Ie,Oe]=s(0);n(()=>{"claudeai"===B?l("tengu_oauth_claudeai_forced",{}):"console"===B&&l("tengu_oauth_console_forced",{})},[B]),n(()=>{if("about_to_retry"===H.state){const e=setTimeout(V,1e3,H.nextState);return()=>clearTimeout(e)}},[H]),f("confirm:yes",()=>{l("tengu_oauth_success",{loginWithClaudeAi:oe}),r(J)},{context:"Confirmation",isActive:"success"===H.state&&"setup-token"!==y}),n(()=>{if("success"===H.state&&!process.stdin.isTTY){const e=setTimeout(()=>{l("tengu_oauth_success",{loginWithClaudeAi:oe}),r(J)},800);return()=>clearTimeout(e)}},[H.state,J,oe,r]),f("confirm:yes",()=>{V({state:"idle"})},{context:"Confirmation",isActive:"platform_setup"===H.state}),f("confirm:yes",()=>{De()},{context:"Confirmation",isActive:"provider_google_setup"===H.state}),f("confirm:yes",()=>{"error"===H.state&&H.toRetry&&(Y(""),V({state:"about_to_retry",nextState:H.toRetry}))},{context:"Confirmation",isActive:"error"===H.state&&!!H.toRetry}),f("cancel",()=>{V({state:"idle"})},{context:"Confirmation",isActive:"provider_api_key_input"===H.state||"provider_local_setup"===H.state||"provider_google_setup"===H.state||"error"===H.state}),n(()=>{"c"===X&&"waiting_for_login"===H.state&&ie&&!ne&&(u(H.url).then(e=>{e&&process.stdout.write(e),ae(!0),setTimeout(ae,2e3,!1)}),Y(""))},[X,H,ie,ne]);const Se=t(async(e,o)=>{const i=e.trim();if(i)try{await P(o,i),de(""),ue(0);const e=E(o).label;v({message:`API key de ${e} guardada`,notificationType:"auth_success"},$),r(o)}catch(e){j(e),V({state:"error",message:e.message,toRetry:{state:"provider_api_key_input",provider:o}})}else V({state:"error",message:"Debes ingresar una API key.",toRetry:{state:"provider_api_key_input",provider:o}})},[r,$]),ze=t((e,o)=>{const i=e.trim();if(i)try{const e=U(o,i);me(e),ge(0),v({message:`URL de ${E(o).label} guardada`,notificationType:"auth_success"},$),r(o)}catch(e){j(e),V({state:"error",message:e.message,toRetry:{state:"provider_local_setup",provider:o}})}else V({state:"error",message:"Debes ingresar una URL para Ollama.",toRetry:{state:"provider_local_setup",provider:o}})},[r,$]),we=t((e,o,i)=>{const t=H;if("custom_provider_wizard"===t.state&&t.provider)if("endpoint"===e){const e=o.trim();if(e&&!e.startsWith("http"))return void V({state:"error",message:"La URL debe empezar con http:// o https://.",toRetry:t});if(!e)return void V({state:"error",message:"El endpoint es obligatorio. Ejemplo: http://localhost:8001/v1",toRetry:t});V({state:"custom_provider_wizard",provider:t.provider,step:"api_key",apiKey:t.apiKey,endpoint:e,model:t.model})}else if("api_key"===e){const e=o.trim();if(!e)return void V({state:"error",message:"La API key no puede estar vacia.",toRetry:t});V({state:"custom_provider_wizard",provider:t.provider,step:"model_list",apiKey:e,endpoint:t.endpoint,model:"",availableModels:[],modelsLoading:!0});const r=new AbortController,i=setTimeout(()=>r.abort(),3e5);fetch(`${t.endpoint}/models`,{headers:{Authorization:`Bearer ${e}`},signal:r.signal}).then(e=>e.json()).then(e=>{clearTimeout(i);const o=e.data?.map(e=>e.id)||[];V(e=>"custom_provider_wizard"!==e.state||"model_list"!==e.step?e:{...e,availableModels:o,modelsLoading:!1})}).catch(e=>{clearTimeout(i),j(e),V(e=>"custom_provider_wizard"!==e.state||"model_list"!==e.step?e:{...e,availableModels:[],modelsLoading:!1})})}else if("model"===e){const e=i&&i.length>0?i:"model_list"===t.step&&Array.isArray(t.availableModels)?t.availableModels:[];let n=null;try{if(S(t.provider))if(R&&R.trim()){const e=O(t.provider,R.trim());w(e.id),n=e.id}else n=z(t.provider,{createIfMissing:!0})?.id??null}catch(e){j(e)}P(t.provider,t.apiKey).then(()=>{U(t.provider,t.endpoint);try{M(t.provider)}catch(e){j(e)}const i=o?.trim();if(i)try{T(t.provider,i),S(t.provider)&&D(t.provider,i)}catch(e){j(e)}if(e.length>0)try{W(t.provider,e,n)}catch(e){j(e)}v({message:`Configuracion de ${E(t.provider).label} guardada`,notificationType:"auth_success"},$),r(t.provider)}).catch(e=>{j(e),V({state:"error",message:e.message,toRetry:t})})}},[r,$,H,R]),De=t(async()=>{V({state:"provider_google_auth_running"});try{if(await b())return void r("gemini-google");const e=await I();k(e);if(!await b())return v({message:"OAuth de Gemini guardado; Code Assist no valido el proyecto de cuota",notificationType:"auth_success"},$),void r("gemini-google");v({message:"Credenciales de Gemini Google listas",notificationType:"auth_success"},$),r("gemini-google")}catch(e){j(e),V({state:"error",message:e.message,toRetry:{state:"provider_google_setup"}})}},[r,$]),Me=t(async()=>{try{l("tengu_oauth_flow_start",{loginWithClaudeAi:oe,provider:J});const e=await Q.startOAuthFlow(async e=>{V({state:"waiting_for_login",url:e}),setTimeout(te,3e3,!0)},{loginWithClaudeAi:oe,provider:J,inferenceOnly:"setup-token"===y,expiresIn:"setup-token"===y?31536e3:void 0,orgUUID:N}).catch(e=>{const o=e.message.includes("Token exchange failed"),r=_(e),i=Q.getPort(),t="openai"===J&&i?formatOAuthDebugDetails(J,i):"";throw V({state:"error",message:r??(o?"No se pudo intercambiar el codigo de autorizacion por el token de acceso. Intentalo de nuevo."+(t?`\n${t}`:""):e.message),toRetry:"setup-token"===y?{state:"ready_to_start"}:{state:"idle"}}),l("tengu_oauth_token_exchange_error",{error:e.message,ssl_error:null!==r}),e});if("setup-token"===y)V({state:"success",token:e.accessToken});else{V({state:"creating_api_key"});const o=R?z("openai"===J?"openai":"anthropic",R):void 0;if(await d(e,J,o?.id),"anthropic"===J){const e=await x();if(!e.valid)throw new Error(e.message)}V({state:"success"}),v({message:"openai"===J?"Inicio de sesión con OpenAI / Codex completado":"Inicio de sesión en Context Code completado",notificationType:"auth_success"},$)}}catch(e){const o=e.message,r=_(e),i=Q.getPort(),t="openai"===J&&i?formatOAuthDebugDetails(J,i):"";V({state:"error",message:r??("openai"===J&&t&&!o.includes("redirect_uri=")?`${o}\n${t}`:o),toRetry:{state:"setup-token"===y?"ready_to_start":"idle"}}),l("tengu_oauth_error",{error:o,ssl_error:null!==r})}},[J,Q,te,oe,y,N,$]),Te=a(!1);return n(()=>{"ready_to_start"!==H.state||Te.current||(Te.current=!0,process.nextTick((e,o)=>{e(),o.current=!1},Me,Te))},[H.state,Me]),n(()=>{if("setup-token"===y&&"success"===H.state){const e=setTimeout((e,o)=>{l("tengu_oauth_success",{loginWithClaudeAi:e}),o(J)},500,oe,r,J);return()=>clearTimeout(e)}},[y,H,oe,r,J]),n(()=>()=>{Q.cleanup()},[Q]),e(m,{flexDirection:"column",gap:1,children:["waiting_for_login"===H.state&&ie&&e(m,{flexDirection:"column",gap:1,paddingBottom:1,children:[e(m,{paddingX:1,children:[e(g,{dimColor:!0,children:["Browser didn't open? Use the url below to sign in"," "]}),o(g,ne?{color:"success",children:"(Copied!)"}:{dimColor:!0,children:o(G,{shortcut:"c",action:"copiar",parens:!0})})]}),o(h,{url:H.url,children:o(g,{dimColor:!0,children:H.url})})]},"urlToCopy"),"setup-token"===y&&"success"===H.state&&H.token&&e(m,{flexDirection:"column",gap:1,paddingTop:1,children:[o(g,{color:"success",children:"✓ Long-lived authentication token created successfully!"}),e(m,{flexDirection:"column",gap:1,children:[o(g,{children:"Your OAuth token (valid for 1 year):"}),o(g,{color:"warning",children:H.token}),o(g,{dimColor:!0,children:"Store this token securely. You won't be able to see it again."}),o(g,{dimColor:!0,children:"Use this token by setting: export CONTEXT_CODE_OAUTH_TOKEN=<token>"})]})]},"tokenOutput"),o(m,{paddingLeft:1,flexDirection:"column",gap:1,children:o(OAuthStatusMessage,{oauthStatus:H,oauthProvider:J,mode:y,startingMessage:i,forcedMethodMessage:F,showPastePrompt:ie,pastedCode:X,setPastedCode:Y,cursorOffset:q,setCursorOffset:Z,textInputColumns:se,handleSubmitCode:async function(e,o){try{const[r,i]=e.split("#");if(!r||!i)return void V({state:"error",message:"Codigo invalido. Asegurate de copiar el codigo completo",toRetry:{state:"waiting_for_login",url:o}});l("tengu_oauth_manual_entry",{}),Q.handleManualAuthCodeInput({authorizationCode:r,state:i})}catch(e){j(e),V({state:"error",message:e.message,toRetry:{state:"waiting_for_login",url:o}})}},setOAuthStatus:V,setLoginWithClaudeAi:re,setOAuthProvider:ee,providerApiKey:le,setProviderApiKey:de,providerApiKeyCursorOffset:ce,setProviderApiKeyCursorOffset:ue,handleProviderApiKeySubmit:Se,providerBaseUrl:pe,setProviderBaseUrlInput:me,providerBaseUrlCursorOffset:he,setProviderBaseUrlCursorOffset:ge,handleProviderBaseUrlSubmit:ze,onDone:r,wizardApiKey:fe,setWizardApiKey:_e,wizardEndpoint:ve,setWizardEndpoint:Ce,wizardModel:ye,setWizardModel:be,wizardApiKeyCursor:Ae,setWizardApiKeyCursor:ke,wizardEndpointCursor:Pe,setWizardEndpointCursor:xe,wizardModelCursor:Ie,setWizardModelCursor:Oe,handleCustomProviderWizardSubmit:we})})]})}function OAuthStatusMessage(t){const n=i(68),{oauthStatus:a,oauthProvider:s,mode:d,startingMessage:c,forcedMethodMessage:u,showPastePrompt:p,pastedCode:f,setPastedCode:_,cursorOffset:v,setCursorOffset:C,textInputColumns:y,handleSubmitCode:b,setOAuthStatus:k,setLoginWithClaudeAi:P,setOAuthProvider:x,providerApiKey:I,setProviderApiKey:O,providerApiKeyCursorOffset:S,setProviderApiKeyCursorOffset:z,handleProviderApiKeySubmit:w,providerBaseUrl:D,setProviderBaseUrlInput:M,providerBaseUrlCursorOffset:T,setProviderBaseUrlCursorOffset:j,handleProviderBaseUrlSubmit:U,onDone:K,wizardApiKey:W,setWizardApiKey:G,wizardEndpoint:F,setWizardEndpoint:H,wizardModel:V,setWizardModel:X,wizardApiKeyCursor:Y,setWizardApiKeyCursor:q,wizardEndpointCursor:Z,setWizardEndpointCursor:Q,wizardModelCursor:J,setWizardModelCursor:ee,handleCustomProviderWizardSubmit:oe}=t;switch(a.state){case"idle":{const r=c||"Context Code puede usarse con tu suscripción de Claude, la facturación de Anthropic Console o OpenAI / Codex OAuth.";let i,t,a,s,d,u,p;return n[0]!==r?(i=o(g,{bold:!0,children:r}),n[0]=r,n[1]=i):i=n[1],n[2]===Symbol.for("react.memo_cache_sentinel")?(t=o(g,{children:"Selecciona el metodo de acceso:"}),n[2]=t):t=n[2],n[3]===Symbol.for("react.memo_cache_sentinel")?(a={label:e(g,{children:["Claude account with subscription ·"," ",o(g,{dimColor:!0,children:"Pro, Max, Team, or Enterprise"}),!1,"\n"]}),value:"claudeai"},n[3]=a):a=n[3],n[4]===Symbol.for("react.memo_cache_sentinel")?(s={label:e(g,{children:["Anthropic Console account ·"," ",o(g,{dimColor:!0,children:"API usage billing"}),"\n"]}),value:"console"},n[4]=s):s=n[4],n[5]===Symbol.for("react.memo_cache_sentinel")?(d=[a,s,{label:e(g,{children:["Cuenta de OpenAI / Codex ·"," ",o(g,{dimColor:!0,children:"Login OAuth"}),"\n"]}),value:"openai"},{label:e(g,{children:["OpenRouter ·"," ",o(g,{dimColor:!0,children:"API key / OpenAI-compatible"}),"\n"]}),value:"openrouter"},{label:e(g,{children:["Ollama ·"," ",o(g,{dimColor:!0,children:"Servidor local compatible"}),"\n"]}),value:"ollama"},{label:e(g,{children:["Gemini API - ",o(g,{dimColor:!0,children:"API key / OpenAI-compatible"}),"\n"]}),value:"gemini-api"},{label:e(g,{children:["Gemini Google - ",o(g,{dimColor:!0,children:"OAuth/ADC de Google"}),"\n"]}),value:"gemini-google"},{label:e(g,{children:["Z.AI ·"," ",o(g,{dimColor:!0,children:"API key / OpenAI-compatible"}),"\n"]}),value:"zai"},{label:e(g,{children:["MiniMax ·"," ",o(g,{dimColor:!0,children:"API key / Anthropic-compatible"}),"\n"]}),value:"minimax"},{label:e(g,{children:["NVIDIA API ·"," ",o(g,{dimColor:!0,children:"API key / build.nvidia.com"}),"\n"]}),value:"nvidia"},{label:e(g,{children:["DeepSeek ·"," ",o(g,{dimColor:!0,children:"API key / contexto 1M (V4)"}),"\n"]}),value:"deepseek"},{label:e(g,{children:["xAI / Grok ·"," ",o(g,{dimColor:!0,children:"API key / api.x.ai"}),"\n"]}),value:"xai"},{label:e(g,{children:["GMI Cloud ·"," ",o(g,{dimColor:!0,children:"API key / api.gmi-serving.com"}),"\n"]}),value:"gmi"},{label:e(g,{children:["NovitaAI ·"," ",o(g,{dimColor:!0,children:"API key / novita.ai"}),"\n"]}),value:"novita"},{label:e(g,{children:["StepFun ·"," ",o(g,{dimColor:!0,children:"API key / stepfun.ai"}),"\n"]}),value:"stepfun"},{label:e(g,{children:["HuggingFace ·"," ",o(g,{dimColor:!0,children:"Token HF / router.huggingface.co"}),"\n"]}),value:"huggingface"},{label:e(g,{children:["OpenCode Zen ·"," ",o(g,{dimColor:!0,children:"API key / opencode.ai/zen"}),"\n"]}),value:"opencode-zen"},{label:e(g,{children:["Arcee AI ·"," ",o(g,{dimColor:!0,children:"API key / api.arcee.ai"}),"\n"]}),value:"arcee"},{label:e(g,{children:["Alibaba / Qwen ·"," ",o(g,{dimColor:!0,children:"API key / DashScope compatible"}),"\n"]}),value:"alibaba"},{label:e(g,{children:["Kimi / Moonshot ·"," ",o(g,{dimColor:!0,children:"API key / api.moonshot.ai"}),"\n"]}),value:"kimi"},{label:e(g,{children:["Custom OpenAI ·"," ",o(g,{dimColor:!0,children:"Wizard API key + endpoint"}),"\n"]}),value:"custom-openai"},{label:e(g,{children:["Custom Anthropic ·"," ",o(g,{dimColor:!0,children:"Wizard API key + endpoint"}),"\n"]}),value:"custom-anthropic"}],n[5]=d):d=n[5],n[6]!==P||n[7]!==k||n[8]!==x||n[65]!==K?(u=o(m,{children:o(L,{options:sortLoginProviderOptions(d),onChange:e=>{"platform"===e?(l("tengu_oauth_platform_selected",{}),k({state:"platform_setup"})):"openai"===e?(l("tengu_oauth_openai_selected",{}),x("openai"),P(!1),k({state:"ready_to_start"})):"openrouter"===e?k({state:"provider_api_key_input",provider:"openrouter"}):"gemini-api"===e||"zai"===e||"minimax"===e||"nvidia"===e||"deepseek"===e||"xai"===e||"gmi"===e||"novita"===e||"stepfun"===e||"huggingface"===e||"opencode-zen"===e||"arcee"===e||"alibaba"===e||"kimi"===e?k({state:"provider_api_key_input",provider:e}):"gemini-google"===e?k({state:"provider_google_setup"}):"ollama"===e||"ollama-cloud"===e?(M(R(e)),j(0),k({state:"provider_local_setup",provider:e})):"custom-openai"===e||"custom-anthropic"===e?k({state:"custom_provider_wizard",provider:e,step:"endpoint",apiKey:"",endpoint:"",model:""}):(x("anthropic"),k({state:"ready_to_start"}),"claudeai"===e?(l("tengu_oauth_claudeai_selected",{}),P(!0)):(l("tengu_oauth_console_selected",{}),P(!1)))}})}),n[6]=P,n[7]=k,n[8]=x,n[65]=K,n[66]=u):u=n[66],n[10]!==i||n[11]!==u?(p=e(m,{flexDirection:"column",gap:1,marginTop:1,children:[i,t,u]}),n[10]=i,n[11]=u,n[12]=p):p=n[12],p}case"provider_api_key_input":{let r,i,t,s;if(n[50]!==a.provider?(r=e(g,{bold:!0,children:["Ingresa la API key de ",E(a.provider).label]}),n[50]=a.provider,n[51]=r):r=n[51],n[52]!==a.provider){const r=E(a.provider);i=e(m,{flexDirection:"column",gap:0,children:[o(g,{dimColor:!0,children:r.description}),e(g,{dimColor:!0,children:["Siguiente paso: ",r.setup.nextStep]})]}),n[52]=a.provider,n[53]=i}else i=n[53];return n[54]!==I||n[55]!==S||n[56]!==O||n[57]!==z||n[58]!==y||n[59]!==w?(t=e(m,{children:[o(g,{children:"API key > "}),o(N,{value:I,onChange:O,onSubmit:e=>w(e,a.provider),cursorOffset:S,onChangeCursorOffset:z,columns:y,mask:"*"})]}),n[54]=I,n[55]=S,n[56]=O,n[57]=z,n[58]=y,n[59]=w,n[60]=t):t=n[60],n[61]!==r||n[62]!==i||n[63]!==t?(s=e(m,{flexDirection:"column",gap:1,children:[r,i,t]}),n[61]=r,n[62]=i,n[63]=t,n[64]=s):s=n[64],s}case"provider_local_setup":{const r=E(a.provider);return e(m,{flexDirection:"column",gap:1,children:[o(g,{bold:!0,children:r.label}),o(g,{dimColor:!0,children:r.setup.intro}),o(g,{dimColor:!0,children:r.setup.nextStep}),o(g,{children:"URL del servidor > "}),o(m,{children:o(N,{value:D,onChange:M,onSubmit:e=>U(e,a.provider),cursorOffset:T,onChangeCursorOffset:j,columns:y})}),e(g,{color:"success",children:["Presiona ",o(g,{bold:!0,children:"Enter"})," para guardar la URL y continuar."]})]})}case"provider_google_setup":return e(m,{flexDirection:"column",gap:1,children:[o(g,{bold:!0,children:"Gemini Google OAuth"}),o(g,{dimColor:!0,children:"Context Code usara el flujo OAuth compatible con Gemini CLI y abrira Google en el navegador."}),o(g,{dimColor:!0,children:"Se guardara el access token y refresh token en el perfil activo de Gemini Google."}),e(g,{color:"success",children:["Presiona ",o(g,{bold:!0,children:"Enter"})," para iniciar sesion con tu cuenta de Google."]})]});case"provider_google_auth_running":return e(m,{children:[o(B,{}),o(g,{children:"Abriendo Google OAuth para Gemini..."})]});case"custom_provider_wizard":{const r=E(a.provider),i="custom-openai"===a.provider?"https://api.openai.com/v1":"https://api.anthropic.com/v1";if("endpoint"===a.step)return e(m,{flexDirection:"column",gap:1,children:[e(g,{bold:!0,children:[r.label," - Paso 1/3"]}),o(g,{dimColor:!0,children:"URL del servidor API (ej: http://localhost:8001/v1)"}),o(g,{children:"Endpoint > "}),o(m,{children:o(N,{value:F,onChange:H,onSubmit:oe.bind(null,"endpoint"),cursorOffset:Z,onChangeCursorOffset:Q,columns:y})}),e(g,{dimColor:!0,children:["Default: ",i]}),e(g,{color:"success",children:["Presiona ",o(g,{bold:!0,children:"Enter"})," para continuar."]})]});if("api_key"===a.step)return e(m,{flexDirection:"column",gap:1,children:[e(g,{bold:!0,children:[r.label," - Paso 2/3"]}),e(g,{dimColor:!0,children:["Ingresa tu API key para ",r.label,"."]}),o(g,{children:"API key > "}),o(m,{children:o(N,{value:W,onChange:G,onSubmit:oe.bind(null,"api_key"),cursorOffset:Y,onChangeCursorOffset:q,columns:y,mask:"*"})}),e(g,{color:"success",children:["Presiona ",o(g,{bold:!0,children:"Enter"})," para obtener modelos disponibles."]})]});if("model_list"===a.step){if(a.modelsLoading)return e(m,{flexDirection:"column",gap:1,children:[e(g,{bold:!0,children:[r.label," - Cargando modelos..."]}),e(m,{children:[o(B,{}),e(g,{children:[" Obteniendo lista de modelos desde ",a.endpoint,"/models"]})]})]});const i=a.availableModels||[];if(i.length>0){const t=i.map(e=>({label:e,value:e}));return e(m,{flexDirection:"column",gap:1,children:[e(g,{bold:!0,children:[r.label," - Paso 3/3"]}),o(g,{dimColor:!0,children:"Selecciona un modelo de la lista:"}),o(m,{children:o(L,{options:t,onChange:e=>{k(o=>({...o,model:e})),oe("model",e,i)}})}),e(g,{color:"success",children:["Presiona ",o(g,{bold:!0,children:"Enter"})," para guardar la configuracion."]})]})}return e(m,{flexDirection:"column",gap:1,children:[e(g,{bold:!0,children:[r.label," - Paso 3/3"]}),o(g,{dimColor:!0,children:"No se pudo obtener la lista de modelos."}),o(g,{dimColor:!0,children:"Ingresa el nombre del modelo manualmente."}),o(g,{dimColor:!0,children:"Podras cambiarlo luego con el comando /model."}),o(g,{children:"Modelo > "}),o(m,{children:o(N,{value:V,onChange:X,onSubmit:oe.bind(null,"model"),cursorOffset:J,onChangeCursorOffset:ee,columns:y})}),e(g,{color:"success",children:["Presiona ",o(g,{bold:!0,children:"Enter"})," para guardar la configuracion."]})]})}break}case"platform_setup":{let r,i,t,a,s,l,d,c;return n[12]===Symbol.for("react.memo_cache_sentinel")?(r=o(g,{bold:!0,children:"Usando plataformas de terceros"}),n[12]=r):r=n[12],n[13]===Symbol.for("react.memo_cache_sentinel")?(i=o(g,{children:"Context Code soporta Amazon Bedrock, Microsoft Foundry y Vertex AI. Configura las variables de entorno requeridas y luego reinicia Context Code."}),t=o(g,{children:"Si formas parte de una organización empresarial, contacta a tu administrador para las instrucciones de configuración."}),n[13]=i,n[14]=t):(i=n[13],t=n[14]),n[15]===Symbol.for("react.memo_cache_sentinel")?(a=o(g,{bold:!0,children:"Documentation:"}),n[15]=a):a=n[15],n[16]===Symbol.for("react.memo_cache_sentinel")?(s=e(g,{children:["· Amazon Bedrock:"," ",o(h,{url:"https://docs.iaforged.com/",children:"https://docs.iaforged.com/"})]}),n[16]=s):s=n[16],n[17]===Symbol.for("react.memo_cache_sentinel")?(l=e(g,{children:["· Microsoft Foundry:"," ",o(h,{url:"https://docs.iaforged.com/",children:"https://docs.iaforged.com/"})]}),n[17]=l):l=n[17],n[18]===Symbol.for("react.memo_cache_sentinel")?(d=e(m,{flexDirection:"column",marginTop:1,children:[a,s,l,e(g,{children:["· Vertex AI:"," ",o(h,{url:"https://docs.iaforged.com/",children:"https://docs.iaforged.com/"})]})]}),n[18]=d):d=n[18],n[19]===Symbol.for("react.memo_cache_sentinel")?(c=e(m,{flexDirection:"column",gap:1,marginTop:1,children:[r,e(m,{flexDirection:"column",gap:1,children:[i,t,d,o(m,{marginTop:1,children:e(g,{dimColor:!0,children:["Presiona ",o(g,{bold:!0,children:"Enter"})," para volver a las opciones de acceso."]})})]})]}),n[19]=c):c=n[19],c}case"waiting_for_login":{let r,i,t,s;return n[20]!==u?(r=u&&o(m,{children:o(g,{dimColor:!0,children:u})}),n[20]=u,n[21]=r):r=n[21],n[22]!==p?(i=!p&&e(m,{children:[o(B,{}),o(g,{children:"Abriendo el navegador para iniciar sesión…"})]}),n[22]=p,n[23]=i):i=n[23],n[24]!==v||n[25]!==b||n[26]!==a.url||n[27]!==f||n[28]!==C||n[29]!==_||n[30]!==p||n[31]!==y?(t=p&&e(m,{children:[o(g,{children:$}),o(N,{value:f,onChange:_,onSubmit:e=>b(e,a.url),cursorOffset:v,onChangeCursorOffset:C,columns:y,mask:"*"})]}),n[24]=v,n[25]=b,n[26]=a.url,n[27]=f,n[28]=C,n[29]=_,n[30]=p,n[31]=y,n[32]=t):t=n[32],n[33]!==r||n[34]!==i||n[35]!==t?(s=e(m,{flexDirection:"column",gap:1,children:[r,i,t]}),n[33]=r,n[34]=i,n[35]=t,n[36]=s):s=n[36],s}case"creating_api_key":{let r;return n[37]===Symbol.for("react.memo_cache_sentinel")?(r=o(m,{flexDirection:"column",gap:1,children:e(m,{children:[o(B,{}),o(g,{children:"Creando API key para Context Code…"})]})}),n[37]=r):r=n[37],r}case"about_to_retry":{let e;return n[38]===Symbol.for("react.memo_cache_sentinel")?(e=o(m,{flexDirection:"column",gap:1,children:o(g,{color:"permission",children:"Reintentando…"})}),n[38]=e):e=n[38],e}case"success":{let i,t;if(n[39]!==d||n[40]!==a.token){const t="openai"===s?"Inicio de sesión en OpenAI / Codex exitoso. Presiona ":"Inicio de sesión exitoso. Presiona ";i="setup-token"===d&&a.token?null:e(r,{children:[A()?.emailAddress?e(g,{dimColor:!0,children:["Sesión iniciada como"," ",o(g,{children:A()?.emailAddress})]}):null,e(g,{color:"success",children:[t,o(g,{bold:!0,children:"Enter"})," para continuar…"]})]}),n[39]=d,n[40]=a.token,n[41]=i}else i=n[41];return n[42]!==i?(t=o(m,{flexDirection:"column",children:i}),n[42]=i,n[43]=t):t=n[43],t}case"error":{let r,i,t;return n[44]!==a.message?(r=e(g,{color:"error",children:["OAuth error: ",a.message]}),n[44]=a.message,n[45]=r):r=n[45],n[46]!==a.toRetry?(i=a.toRetry&&o(m,{marginTop:1,children:e(g,{color:"permission",children:["Press ",o(g,{bold:!0,children:"Enter"})," to retry."]})}),n[46]=a.toRetry,n[47]=i):i=n[47],n[48]!==r||n[49]!==i?(t=e(m,{flexDirection:"column",gap:1,children:[r,i]}),n[48]=r,n[49]=i,n[50]=t):t=n[50],t}default:return null}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e,jsxs as o}from"react/jsx-runtime";import{c as r}from"react/compiler-runtime";import{useEffect as t,useState as
|
|
1
|
+
import{jsx as e,jsxs as o}from"react/jsx-runtime";import{c as r}from"react/compiler-runtime";import{useEffect as t,useState as i}from"react";import{UP_ARROW as m}from"../../constants/figures.js";import{Box as s,Text as n}from"../../ink.js";import{getGlobalConfig as c,saveGlobalConfig as u}from"../../utils/config.js";import{isOpus1mMergeEnabled as p}from"../../utils/model/model.js";import{AnimatedAsterisk as f}from"./AnimatedAsterisk.js";export function shouldShowOpus1mMergeNotice(){return p()&&(c().opus1mMergeNoticeSeenCount??0)<0}export function Opus1mMergeNotice(){const p=r(4),[a]=i(shouldShowOpus1mMergeNotice);let l,d,g;return p[0]!==a?(l=()=>{if(!a)return;const e=(c().opus1mMergeNoticeSeenCount??0)+1;u(o=>(o.opus1mMergeNoticeSeenCount??0)>=e?o:{...o,opus1mMergeNoticeSeenCount:e})},d=[a],p[0]=a,p[1]=l,p[2]=d):(l=p[1],d=p[2]),t(l,d),a?(p[3]===Symbol.for("react.memo_cache_sentinel")?(g=o(s,{paddingLeft:2,children:[e(f,{char:m}),o(n,{dimColor:!0,children:[" ","Opus ahora tiene 1M de contexto por defecto · 5x más espacio, mismo precio"]})]}),p[3]=g):g=p[3],g):null}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e,jsxs as o,Fragment as t}from"react/jsx-runtime";import r from"lodash-es/capitalize.js";import*as i from"react";import{useMemo as n,useState as l}from"react";import{useExitOnCtrlCDWithKeybindings as
|
|
1
|
+
import{jsx as e,jsxs as o,Fragment as t}from"react/jsx-runtime";import r from"lodash-es/capitalize.js";import*as i from"react";import{useMemo as n,useState as l}from"react";import{useExitOnCtrlCDWithKeybindings as s}from"../hooks/useExitOnCtrlCDWithKeybindings.js";import{logEvent as a}from"../services/analytics/index.js";import{FAST_MODE_MODEL_DISPLAY as c,isFastModeAvailable as d,isFastModeCooldown as u,isFastModeEnabled as f}from"../utils/fastMode.js";import{Box as m,Text as p,useInput as h}from"../ink.js";import{useKeybindings as v}from"../keybindings/useKeybinding.js";import{useAppState as g,useSetAppState as b}from"../state/AppState.js";import{getGlobalConfig as C,saveGlobalConfig as j}from"../utils/config.js";import{convertEffortValueToLevel as x,getDefaultEffortForModel as E,modelSupportsEffort as S,modelSupportsMaxEffort as O,resolvePickerEffortPersistence as P,toPersistableEffort as k}from"../utils/effort.js";import{getDefaultMainLoopModel as M,modelDisplayString as w,parseUserSpecifiedModel as y}from"../utils/model/model.js";import{getModelOptions as L}from"../utils/model/modelOptions.js";import{getAPIProvider as V,isOpenAICompatibleProvider as D}from"../utils/model/providers.js";import{getSettingsForSource as F,updateSettingsForSource as _}from"../utils/settings/settings.js";import{ConfigurableShortcutHint as A}from"./ConfigurableShortcutHint.js";import{Select as I}from"./CustomSelect/index.js";import{Byline as H}from"./design-system/Byline.js";import{KeyboardShortcutHint as R}from"./design-system/KeyboardShortcutHint.js";import{Pane as z}from"./design-system/Pane.js";import{effortLevelToSymbol as B}from"./EffortIndicator.js";const N="__NO_PREFERENCE__",$="__MODEL_HEADER__";function writePickerState(e){j(o=>({...o,modelPickerFavorites:e.favorites,modelPickerRecent:e.recent}))}function providerLabel(e){switch(e){case"firstParty":return"Claude";case"openai":return"OpenAI";case"openrouter":return"OpenRouter";case"ollama":return"Ollama";case"ollama-cloud":return"Ollama Cloud";case"gemini-api":return"Gemini API";case"gemini-google":return"Gemini Google";case"zai":return"Z.AI";case"minimax":return"MiniMax";case"nvidia":return"NVIDIA";case"deepseek":return"DeepSeek";case"custom-openai":return"OpenAI personalizado";case"custom-anthropic":return"Anthropic personalizado";default:return e}}function asSelectValue(e){return null===e?N:e}function isHeaderValue(e){return e?.startsWith($)??!1}function resolveOptionModel(e){if(e&&!isHeaderValue(e))return e===N?M():y(e)}function getDefaultEffortLevelForOption(e){const o=resolveOptionModel(e)??M(),t=E(o);return void 0!==t?x(t):"high"}function EffortLevelIndicator({effort:o}){return e(p,{color:o?"claude":"subtle",children:B(o??"low")})}export function ModelPicker({initial:j,sessionModel:E,onSelect:M,onCancel:y,isStandaloneCommand:B,showFastModeNotice:G,headerText:K,skipSettingsWrite:W,onOpenProvider:T}){const U=b(),Q=s(),Z=null===j?N:j,[q,J]=l(Z),[X,Y]=l(()=>function(){const e=C();return{favorites:e.modelPickerFavorites??[],recent:e.modelPickerRecent??[]}}()),ee=g(e=>!!f()&&e.fastMode),[oe,te]=l(!1),re=g(e=>e.effortValue),[ie,ne]=l(void 0!==re?x(re):void 0),[le,se]=l([]);i.useEffect(()=>{(async()=>{const e=V();if(D(e)){const{getCachedProviderModels:o,fetchProviderModels:t}=await import("../utils/model/providerModels.js"),r=o(e);if(r)se(r);else{const o=await t(e);se(o)}}})()},[]);const ae=n(()=>L(ee??!1),[ee]),ce=n(()=>{if(0===le.length)return ae;const e=new Set;return[...ae,...le].filter(o=>{const t=o.value??N;return!e.has(t)&&(e.add(t),!0)})},[ae,le]),de=n(()=>null===j||ce.some(e=>e.value===j)?ce:[...ce,{value:j,label:w(j),description:"Modelo actual"}],[j,ce]),ue=n(()=>new Map(de.map(e=>[asSelectValue(e.value),e])),[de]),fe=n(()=>{const e=de.map(e=>asSelectValue(e.value)),o=new Set(e),t=X.favorites.filter(e=>o.has(e)),r=X.recent.filter(e=>e!==N&&o.has(e)&&!t.includes(e)),i=e.filter(e=>!t.includes(e)&&!r.includes(e)),n=[];if(t.length>0){n.push({value:`${$}:favorites`,label:"Favoritos",disabled:!0});for(const e of t){const o=ue.get(e);o&&n.push({value:e,label:`★ ${o.label}`,description:o.description})}}if(r.length>0){n.push({value:`${$}:recent`,label:"Recientes",disabled:!0});for(const e of r){const o=ue.get(e);o&&n.push({value:e,label:o.label,description:o.description})}}n.push({value:`${$}:provider`,label:providerLabel(V()),disabled:!0});for(const e of i){const o=ue.get(e);o&&n.push({value:e,label:o.label,description:o.description})}return n},[ue,de,X.favorites,X.recent]),me=n(()=>fe.some(e=>e.value===Z&&!e.disabled)?Z:fe.find(e=>!e.disabled)?.value,[fe,Z]),pe=Math.min(10,fe.length),he=Math.max(0,fe.length-pe),ve=fe.find(e=>e.value===q)?.label,ge=resolveOptionModel(q),be=!!ge&&S(ge),Ce=!!ge&&O(ge),je=getDefaultEffortLevelForOption(q),xe="max"!==ie||Ce?ie:"high",handleCycleEffort=e=>{be&&(ne(o=>function(e,o,t){const r=t?["low","medium","high","max"]:["low","medium","high"],i=r.indexOf(e),n=-1!==i?i:r.indexOf("high");return"right"===o?r[(n+1)%r.length]:r[(n-1+r.length)%r.length]}(o??je,e,Ce)),te(!0))};v({"modelPicker:decreaseEffort":()=>handleCycleEffort("left"),"modelPicker:increaseEffort":()=>handleCycleEffort("right")},{context:"ModelPicker"}),h((e,o)=>{const t=q;if(t&&!isHeaderValue(t)){if(o.ctrl&&"f"===e.toLowerCase()&&t!==N){const e=X.favorites.includes(t)?X.favorites.filter(e=>e!==t):[t,...X.favorites].slice(0,25),o={...X,favorites:e};return Y(o),void writePickerState(o)}o.ctrl&&"a"===e.toLowerCase()&&T&&T()}});const Ee=q&&!isHeaderValue(q)&&q!==N&&X.favorites.includes(q)?"Quitar favorito":"Favorito",Se=o(m,{flexDirection:"column",children:[o(m,{marginBottom:1,flexDirection:"column",children:[e(p,{color:"remember",bold:!0,children:"Seleccionar modelo"}),e(p,{dimColor:!0,children:K??"Cambia entre modelos. Se aplica a esta sesion y a futuras sesiones de Context Code. Para otros nombres de modelo, usa --model."}),E&&o(p,{dimColor:!0,children:["Usando ",w(E)," en esta sesion (definido por el modo plan). Al elegir otro modelo se deshace este ajuste."]})]}),o(m,{flexDirection:"column",marginBottom:1,children:[e(I,{defaultValue:Z,defaultFocusValue:me,options:fe,onChange:e=>{if(isHeaderValue(e))return;if(a("tengu_model_command_menu_effort",{effort:ie}),!W){const o=P(ie,getDefaultEffortLevelForOption(e),F("userSettings")?.effortLevel,oe),t=k(o);void 0!==t&&_("userSettings",{effortLevel:t}),U(e=>({...e,effortValue:o}))}const o=oe&&ge&&S(ge)?ie:void 0,t=[e,...X.recent.filter(o=>o!==e)].slice(0,15),r={...X,recent:t};Y(r),writePickerState(r),M(function(e){return e===N?null:e}(e),o)},onFocus:e=>{J(e),oe||void 0!==re||isHeaderValue(e)||ne(getDefaultEffortLevelForOption(e))},onCancel:y??(()=>{}),visibleOptionCount:pe,hideIndexes:!0,layout:"compact-vertical"}),he>0&&e(m,{paddingLeft:3,children:o(p,{dimColor:!0,children:["y ",he," más…"]})})]}),e(m,{marginBottom:1,flexDirection:"column",children:o(p,be?{dimColor:!0,children:[e(EffortLevelIndicator,{effort:xe})," ",r("low"===xe?"bajo":"medium"===xe?"medio":"high"===xe?"alto":"máximo")," ","esfuerzo",xe===je?" (predeterminado)":""," ",e(p,{color:"subtle",children:"← → para ajustar"})]}:{color:"subtle",children:[e(EffortLevelIndicator,{effort:void 0})," Esfuerzo no soportado",ve?` para ${String(ve)}`:""]})}),f()?G?e(m,{marginBottom:1,children:o(p,{dimColor:!0,children:["El modo rápido está ",e(p,{bold:!0,children:"ACTIVADO"})," y disponible solo con"," ",c," (/fast). Cambiar a otros modelos desactivará el modo rápido."]})}):d()&&!u()?e(m,{marginBottom:1,children:o(p,{dimColor:!0,children:["Usa ",e(p,{bold:!0,children:"/fast"})," para activar el modo rápido (solo"," ",c,")."]})}):null:null,B&&e(p,{dimColor:!0,italic:!0,children:Q.pending?o(t,{children:["Presiona ",Q.keyName," de nuevo para salir"]}):o(H,{children:[e(R,{shortcut:"Enter",action:"confirmar"}),e(R,{shortcut:"Ctrl+F",action:Ee}),e(R,{shortcut:"Ctrl+A",action:"Proveedor"}),e(A,{action:"select:cancel",context:"Seleccionar",fallback:"Esc",description:"salir"})]})})]});return B?e(z,{color:"permission",children:Se}):Se}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsxs as o,jsx as r}from"react/jsx-runtime";import{getTotalCost as e,getTotalInputTokens as t,getTotalOutputTokens as i}from"../cost-tracker.js";import{useMainLoopModel as n}from"../hooks/useMainLoopModel.js";import{Box as s,Text as m}from"../ink.js";import{getAPIProvider as l}from"../utils/model/providers.js";import{getCurrentUsage as d}from"../utils/tokens.js";function formatNumber(o){return o>=1e6?`${(o/1e6).toFixed(2)}M`:o>=1e3?`${(o/1e3).toFixed(1)}k`:String(o)}export const SessionTokenFooter=({messages:c})=>{const a=l(),u=n(),f=t(),p=i(),h=d(c),k=h?.input_tokens??0,j=h?.output_tokens??0,x=e(),b="firstParty"===a||"openai"===a||"bedrock"===a||"vertex"===a||"foundry"===a;return r(s,{paddingX:1,children:o(m,{dimColor:!0,children:[a," · ",u||"sin modelo"," ",o(m,{color:"cyan",children:["↑ ",formatNumber(f)]})," / ",o(m,{color:"green",children:["↓ ",formatNumber(p)]})," tokens en esta sesion",h&&o(m,{dimColor:!0,children:[" · ultima respuesta: ",r(m,{color:"cyan",children:formatNumber(k)})," / ",r(m,{color:"green",children:formatNumber(j)})]}),x>0&&o(m,{dimColor:!0,children:[" · ",o(m,{color:"yellow",children:["$",x.toFixed(4)]}),b?"":" (estimado)"]})]})})};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isEnvTruthy as e}from"../utils/envUtils.js";function getOauthConfigType(){if("ant"===process.env.USER_TYPE){if(e(process.env.USE_LOCAL_OAUTH))return"local";if(e(process.env.USE_STAGING_OAUTH))return"staging"}return"prod"}export function fileSuffixForOauthConfig(){if(process.env.CONTEXT_CODE_CUSTOM_OAUTH_URL||process.env.CLAUDE_CODE_CUSTOM_OAUTH_URL)return"-custom-oauth";switch(getOauthConfigType()){case"local":return"-local-oauth";case"staging":return"-staging-oauth";case"prod":return""}}function parseSpaceSeparatedList(e){return e?.split(/\s+/).filter(Boolean)??[]}const t="/auth/callback",_=`http://localhost:1455${t}`,o=["openid","profile","email","offline_access"];export const CLAUDE_AI_INFERENCE_SCOPE="user:inference";export const CLAUDE_AI_PROFILE_SCOPE="user:profile";export const OAUTH_BETA_HEADER="oauth-2025-04-20";export const CONSOLE_OAUTH_SCOPES=["org:create_api_key","user:profile"];export const CLAUDE_AI_OAUTH_SCOPES=["user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"];export const ALL_OAUTH_SCOPES=Array.from(new Set([...CONSOLE_OAUTH_SCOPES,...CLAUDE_AI_OAUTH_SCOPES]));const a={BASE_API_URL:"https://api.anthropic.com",CONSOLE_AUTHORIZE_URL:"https://platform.claude.com/oauth/authorize",CLAUDE_AI_AUTHORIZE_URL:"https://claude.com/cai/oauth/authorize",CLAUDE_AI_ORIGIN:"https://claude.ai",TOKEN_URL:"https://platform.claude.com/v1/oauth/token",API_KEY_URL:"https://api.anthropic.com/api/oauth/claude_cli/create_api_key",ROLES_URL:"https://api.anthropic.com/api/oauth/claude_cli/roles",CONSOLE_SUCCESS_URL:"https://platform.claude.com/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code",CLAUDEAI_SUCCESS_URL:"https://platform.claude.com/oauth/code/success?app=claude-code",MANUAL_REDIRECT_URL:"https://platform.claude.com/oauth/code/callback",CLIENT_ID:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",OAUTH_FILE_SUFFIX:"",MCP_PROXY_URL:"https://mcp-proxy.anthropic.com",MCP_PROXY_PATH:"/v1/mcp/{server_id}"};export const MCP_CLIENT_METADATA_URL="https://claude.ai/oauth/claude-code-client-metadata";const c="ant"===process.env.USER_TYPE?{BASE_API_URL:"https://api-staging.anthropic.com",CONSOLE_AUTHORIZE_URL:"https://platform.staging.ant.dev/oauth/authorize",CLAUDE_AI_AUTHORIZE_URL:"https://claude-ai.staging.ant.dev/oauth/authorize",CLAUDE_AI_ORIGIN:"https://claude-ai.staging.ant.dev",TOKEN_URL:"https://platform.staging.ant.dev/v1/oauth/token",API_KEY_URL:"https://api-staging.anthropic.com/api/oauth/claude_cli/create_api_key",ROLES_URL:"https://api-staging.anthropic.com/api/oauth/claude_cli/roles",CONSOLE_SUCCESS_URL:"https://platform.staging.ant.dev/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code",CLAUDEAI_SUCCESS_URL:"https://platform.staging.ant.dev/oauth/code/success?app=claude-code",MANUAL_REDIRECT_URL:"https://platform.staging.ant.dev/oauth/code/callback",CLIENT_ID:"22422756-60c9-4084-8eb7-27705fd5cf9a",OAUTH_FILE_SUFFIX:"-staging-oauth",MCP_PROXY_URL:"https://mcp-proxy-staging.anthropic.com",MCP_PROXY_PATH:"/v1/mcp/{server_id}"}:void 0;const s=["https://beacon.claude-ai.staging.ant.dev","https://claude.fedstart.com","https://claude-staging.fedstart.com"];export function getOauthConfig(){let e=(()=>{switch(getOauthConfigType()){case"local":return function(){const e=(process.env.CONTEXT_LOCAL_OAUTH_API_BASE??process.env.CLAUDE_LOCAL_OAUTH_API_BASE)?.replace(/\/$/,"")??"http://localhost:8000",t=(process.env.CONTEXT_LOCAL_OAUTH_APPS_BASE??process.env.CLAUDE_LOCAL_OAUTH_APPS_BASE)?.replace(/\/$/,"")??"http://localhost:4000",_=(process.env.CONTEXT_LOCAL_OAUTH_CONSOLE_BASE??process.env.CLAUDE_LOCAL_OAUTH_CONSOLE_BASE)?.replace(/\/$/,"")??"http://localhost:3000";return{BASE_API_URL:e,CONSOLE_AUTHORIZE_URL:`${_}/oauth/authorize`,CLAUDE_AI_AUTHORIZE_URL:`${t}/oauth/authorize`,CLAUDE_AI_ORIGIN:t,TOKEN_URL:`${e}/v1/oauth/token`,API_KEY_URL:`${e}/api/oauth/claude_cli/create_api_key`,ROLES_URL:`${e}/api/oauth/claude_cli/roles`,CONSOLE_SUCCESS_URL:`${_}/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code`,CLAUDEAI_SUCCESS_URL:`${_}/oauth/code/success?app=claude-code`,MANUAL_REDIRECT_URL:`${_}/oauth/code/callback`,CLIENT_ID:"22422756-60c9-4084-8eb7-27705fd5cf9a",OAUTH_FILE_SUFFIX:"-local-oauth",MCP_PROXY_URL:"http://localhost:8205",MCP_PROXY_PATH:"/v1/toolbox/shttp/mcp/{server_id}"}}();case"staging":return c??a;case"prod":return a}})();const t=process.env.CONTEXT_CODE_CUSTOM_OAUTH_URL??process.env.CLAUDE_CODE_CUSTOM_OAUTH_URL;if(t){const _=t.replace(/\/$/,"");if(!s.includes(_)){const e=void 0!==process.env.CONTEXT_CODE_CUSTOM_OAUTH_URL?"CONTEXT_CODE_CUSTOM_OAUTH_URL":"CLAUDE_CODE_CUSTOM_OAUTH_URL";throw new Error(`${e} is not an approved endpoint.`)}e={...e,BASE_API_URL:_,CONSOLE_AUTHORIZE_URL:`${_}/oauth/authorize`,CLAUDE_AI_AUTHORIZE_URL:`${_}/oauth/authorize`,CLAUDE_AI_ORIGIN:_,TOKEN_URL:`${_}/v1/oauth/token`,API_KEY_URL:`${_}/api/oauth/claude_cli/create_api_key`,ROLES_URL:`${_}/api/oauth/claude_cli/roles`,CONSOLE_SUCCESS_URL:`${_}/oauth/code/success?app=claude-code`,CLAUDEAI_SUCCESS_URL:`${_}/oauth/code/success?app=claude-code`,MANUAL_REDIRECT_URL:`${_}/oauth/code/callback`,OAUTH_FILE_SUFFIX:"-custom-oauth"}}const _=process.env.CONTEXT_CODE_OAUTH_CLIENT_ID??process.env.CLAUDE_CODE_OAUTH_CLIENT_ID;return _&&(e={...e,CLIENT_ID:_}),e}export function getOpenAIOAuthConfig(){const e=process.env.OPENAI_OAUTH_BASE_URL?.replace(/\/$/,"")??process.env.OPENAI_OAUTH_ENDPOINT_BASE?.replace(/\/$/,"")??"https://auth.openai.com";return{AUTHORIZE_URL:process.env.OPENAI_OAUTH_AUTHORIZE_URL??`${e}/oauth/authorize`,TOKEN_URL:process.env.OPENAI_OAUTH_TOKEN_URL??`${e}/oauth/token`,CLIENT_ID:process.env.OPENAI_OAUTH_CLIENT_ID??"app_EMoamEEZ73f0CkXaXp7hrann",MANUAL_REDIRECT_URL:process.env.OPENAI_OAUTH_MANUAL_REDIRECT_URL??process.env.OPENAI_OAUTH_REDIRECT_URL??_,LOCAL_REDIRECT_URL:process.env.OPENAI_OAUTH_LOCAL_REDIRECT_URL??_,CALLBACK_PATH:process.env.OPENAI_OAUTH_CALLBACK_PATH??t,CALLBACK_PORT:parseInt(process.env.OPENAI_OAUTH_CALLBACK_PORT||String(1455),10),SUCCESS_URL:process.env.OPENAI_OAUTH_SUCCESS_URL??(e?`${e}/oauth/code/success?app=codex`:void 0),FILE_SUFFIX:"-openai-oauth",BASE_API_URL:e,PROFILE_URL:process.env.OPENAI_OAUTH_PROFILE_URL??(e?`${e}/api/oauth/profile`:void 0),SCOPES:parseSpaceSeparatedList(process.env.OPENAI_OAUTH_SCOPES).length>0?parseSpaceSeparatedList(process.env.OPENAI_OAUTH_SCOPES):[...o]}}
|
|
1
|
+
import{isEnvTruthy as e}from"../utils/envUtils.js";function getOauthConfigType(){if("ant"===process.env.USER_TYPE){if(e(process.env.USE_LOCAL_OAUTH))return"local";if(e(process.env.USE_STAGING_OAUTH))return"staging"}return"prod"}export function fileSuffixForOauthConfig(){if(process.env.CONTEXT_CODE_CUSTOM_OAUTH_URL||process.env.CLAUDE_CODE_CUSTOM_OAUTH_URL)return"-custom-oauth";switch(getOauthConfigType()){case"local":return"-local-oauth";case"staging":return"-staging-oauth";case"prod":return""}}function parseSpaceSeparatedList(e){return e?.split(/\s+/).filter(Boolean)??[]}export function getOpenAIOriginator(){return process.env.OPENAI_OAUTH_ORIGINATOR?.trim()||"codex_cli_rs"}const t="/auth/callback",_=`http://localhost:1455${t}`,o=["openid","profile","email","offline_access"];export const CLAUDE_AI_INFERENCE_SCOPE="user:inference";export const CLAUDE_AI_PROFILE_SCOPE="user:profile";export const OAUTH_BETA_HEADER="oauth-2025-04-20";export const CONSOLE_OAUTH_SCOPES=["org:create_api_key","user:profile"];export const CLAUDE_AI_OAUTH_SCOPES=["user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"];export const ALL_OAUTH_SCOPES=Array.from(new Set([...CONSOLE_OAUTH_SCOPES,...CLAUDE_AI_OAUTH_SCOPES]));const a={BASE_API_URL:"https://api.anthropic.com",CONSOLE_AUTHORIZE_URL:"https://platform.claude.com/oauth/authorize",CLAUDE_AI_AUTHORIZE_URL:"https://claude.com/cai/oauth/authorize",CLAUDE_AI_ORIGIN:"https://claude.ai",TOKEN_URL:"https://platform.claude.com/v1/oauth/token",API_KEY_URL:"https://api.anthropic.com/api/oauth/claude_cli/create_api_key",ROLES_URL:"https://api.anthropic.com/api/oauth/claude_cli/roles",CONSOLE_SUCCESS_URL:"https://platform.claude.com/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code",CLAUDEAI_SUCCESS_URL:"https://platform.claude.com/oauth/code/success?app=claude-code",MANUAL_REDIRECT_URL:"https://platform.claude.com/oauth/code/callback",CLIENT_ID:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",OAUTH_FILE_SUFFIX:"",MCP_PROXY_URL:"https://mcp-proxy.anthropic.com",MCP_PROXY_PATH:"/v1/mcp/{server_id}"};export const MCP_CLIENT_METADATA_URL="https://claude.ai/oauth/claude-code-client-metadata";const c="ant"===process.env.USER_TYPE?{BASE_API_URL:"https://api-staging.anthropic.com",CONSOLE_AUTHORIZE_URL:"https://platform.staging.ant.dev/oauth/authorize",CLAUDE_AI_AUTHORIZE_URL:"https://claude-ai.staging.ant.dev/oauth/authorize",CLAUDE_AI_ORIGIN:"https://claude-ai.staging.ant.dev",TOKEN_URL:"https://platform.staging.ant.dev/v1/oauth/token",API_KEY_URL:"https://api-staging.anthropic.com/api/oauth/claude_cli/create_api_key",ROLES_URL:"https://api-staging.anthropic.com/api/oauth/claude_cli/roles",CONSOLE_SUCCESS_URL:"https://platform.staging.ant.dev/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code",CLAUDEAI_SUCCESS_URL:"https://platform.staging.ant.dev/oauth/code/success?app=claude-code",MANUAL_REDIRECT_URL:"https://platform.staging.ant.dev/oauth/code/callback",CLIENT_ID:"22422756-60c9-4084-8eb7-27705fd5cf9a",OAUTH_FILE_SUFFIX:"-staging-oauth",MCP_PROXY_URL:"https://mcp-proxy-staging.anthropic.com",MCP_PROXY_PATH:"/v1/mcp/{server_id}"}:void 0;const s=["https://beacon.claude-ai.staging.ant.dev","https://claude.fedstart.com","https://claude-staging.fedstart.com"];export function getOauthConfig(){let e=(()=>{switch(getOauthConfigType()){case"local":return function(){const e=(process.env.CONTEXT_LOCAL_OAUTH_API_BASE??process.env.CLAUDE_LOCAL_OAUTH_API_BASE)?.replace(/\/$/,"")??"http://localhost:8000",t=(process.env.CONTEXT_LOCAL_OAUTH_APPS_BASE??process.env.CLAUDE_LOCAL_OAUTH_APPS_BASE)?.replace(/\/$/,"")??"http://localhost:4000",_=(process.env.CONTEXT_LOCAL_OAUTH_CONSOLE_BASE??process.env.CLAUDE_LOCAL_OAUTH_CONSOLE_BASE)?.replace(/\/$/,"")??"http://localhost:3000";return{BASE_API_URL:e,CONSOLE_AUTHORIZE_URL:`${_}/oauth/authorize`,CLAUDE_AI_AUTHORIZE_URL:`${t}/oauth/authorize`,CLAUDE_AI_ORIGIN:t,TOKEN_URL:`${e}/v1/oauth/token`,API_KEY_URL:`${e}/api/oauth/claude_cli/create_api_key`,ROLES_URL:`${e}/api/oauth/claude_cli/roles`,CONSOLE_SUCCESS_URL:`${_}/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code`,CLAUDEAI_SUCCESS_URL:`${_}/oauth/code/success?app=claude-code`,MANUAL_REDIRECT_URL:`${_}/oauth/code/callback`,CLIENT_ID:"22422756-60c9-4084-8eb7-27705fd5cf9a",OAUTH_FILE_SUFFIX:"-local-oauth",MCP_PROXY_URL:"http://localhost:8205",MCP_PROXY_PATH:"/v1/toolbox/shttp/mcp/{server_id}"}}();case"staging":return c??a;case"prod":return a}})();const t=process.env.CONTEXT_CODE_CUSTOM_OAUTH_URL??process.env.CLAUDE_CODE_CUSTOM_OAUTH_URL;if(t){const _=t.replace(/\/$/,"");if(!s.includes(_)){const e=void 0!==process.env.CONTEXT_CODE_CUSTOM_OAUTH_URL?"CONTEXT_CODE_CUSTOM_OAUTH_URL":"CLAUDE_CODE_CUSTOM_OAUTH_URL";throw new Error(`${e} is not an approved endpoint.`)}e={...e,BASE_API_URL:_,CONSOLE_AUTHORIZE_URL:`${_}/oauth/authorize`,CLAUDE_AI_AUTHORIZE_URL:`${_}/oauth/authorize`,CLAUDE_AI_ORIGIN:_,TOKEN_URL:`${_}/v1/oauth/token`,API_KEY_URL:`${_}/api/oauth/claude_cli/create_api_key`,ROLES_URL:`${_}/api/oauth/claude_cli/roles`,CONSOLE_SUCCESS_URL:`${_}/oauth/code/success?app=claude-code`,CLAUDEAI_SUCCESS_URL:`${_}/oauth/code/success?app=claude-code`,MANUAL_REDIRECT_URL:`${_}/oauth/code/callback`,OAUTH_FILE_SUFFIX:"-custom-oauth"}}const _=process.env.CONTEXT_CODE_OAUTH_CLIENT_ID??process.env.CLAUDE_CODE_OAUTH_CLIENT_ID;return _&&(e={...e,CLIENT_ID:_}),e}export function getOpenAIOAuthConfig(){const e=process.env.OPENAI_OAUTH_BASE_URL?.replace(/\/$/,"")??process.env.OPENAI_OAUTH_ENDPOINT_BASE?.replace(/\/$/,"")??"https://auth.openai.com";return{AUTHORIZE_URL:process.env.OPENAI_OAUTH_AUTHORIZE_URL??`${e}/oauth/authorize`,TOKEN_URL:process.env.OPENAI_OAUTH_TOKEN_URL??`${e}/oauth/token`,CLIENT_ID:process.env.OPENAI_OAUTH_CLIENT_ID??"app_EMoamEEZ73f0CkXaXp7hrann",MANUAL_REDIRECT_URL:process.env.OPENAI_OAUTH_MANUAL_REDIRECT_URL??process.env.OPENAI_OAUTH_REDIRECT_URL??_,LOCAL_REDIRECT_URL:process.env.OPENAI_OAUTH_LOCAL_REDIRECT_URL??_,CALLBACK_PATH:process.env.OPENAI_OAUTH_CALLBACK_PATH??t,CALLBACK_PORT:parseInt(process.env.OPENAI_OAUTH_CALLBACK_PORT||String(1455),10),SUCCESS_URL:process.env.OPENAI_OAUTH_SUCCESS_URL??(e?`${e}/oauth/code/success?app=codex`:void 0),FILE_SUFFIX:"-openai-oauth",BASE_API_URL:e,PROFILE_URL:process.env.OPENAI_OAUTH_PROFILE_URL??(e?`${e}/api/oauth/profile`:void 0),SCOPES:parseSpaceSeparatedList(process.env.OPENAI_OAUTH_SCOPES).length>0?parseSpaceSeparatedList(process.env.OPENAI_OAUTH_SCOPES):[...o]}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getVisibleProvider as e,VISIBLE_PROVIDERS as r}from"../../utils/model/providerCatalog.js";import{getActiveProviderProfile as i,getLastUsedProviderProfile as o,isProfiledProvider as t,listProviderProfiles as a,setActiveProfileForProvider as n}from"../../utils/model/providerProfiles.js";import{switchProviderPreference as l}from"../../utils/model/providerSwitch.js";import{hasStoredProviderApiKey as d,hasStoredProviderOAuthTokens as u}from"../../utils/auth.js";export function isCoreProviderEnabled(){return"0"!==process.env.CORE_PROVIDER_ENABLED}export function listCoreProviders(){return r.map(e=>({id:e.id,label:e.label,implemented:e.implemented}))}export function normalizeCoreProviderInput(e){if(e)switch(e.trim().toLowerCase()){case"z.ai":case"z-ai":return"zai";case"open-router":return"openrouter";case"ollama-cloud":case"ollama_cloud":case"ollamacloud":return"ollama-cloud";case"gemini":case"gemini-api-key":case"google-ai":case"google-ai-studio":return"gemini-api";case"gemini-google":case"google":case"google-oauth":return"gemini-google";default:return e.trim().toLowerCase()}}export function getCoreProviderLabel(r){return e(r).label}export function listCoreProviderProfiles(){const e=a(),r=i(),o=e.reduce((e,i)=>{const o=i.provider;return e[o]||(e[o]=[]),e[o].push({id:i.id,name:i.name,provider:o,baseUrl:i.baseUrl,isActive:i.id===r?.id,isAuthenticated:isProviderProfileAuthenticated(o,i.id)}),e},{});return{activeProfile:r?{id:r.id,name:r.name,provider:r.provider,baseUrl:r.baseUrl}:null,providers:o}}export function getCoreCurrentProviderProfile(){const e=i();return e?{activeProfile:{id:e.id,name:e.name,provider:e.provider,baseUrl:e.baseUrl}}:{activeProfile:null}}export function setCoreActiveProfile(e,r){t(e)&&n(e,r)}export function isCoreSelectedProfileReady(e,r){if(!r||!t(e))return!0;const i=o(e);return!!i&&isProviderProfileAuthenticated(e,i.id)}export function switchCoreProvider(e){const r=l({currentModel:e.currentModel,currentProvider:e.currentProvider,targetProvider:e.targetProvider,targetProfileName:e.targetProfileName}),i=t(e.targetProvider)?o(e.targetProvider):null;return{restoredModel:r,activeProfileName:i?.name}}function isProviderProfileAuthenticated(e,r){return"claude"===e?u("claude",r):"openai"===e?u("openai",r):"openrouter"!==e&&"gemini-api"!==e&&"zai"!==e&&"minimax"!==e&&"nvidia"!==e||d(e,r)}
|
|
1
|
+
import{getVisibleProvider as e,VISIBLE_PROVIDERS as r}from"../../utils/model/providerCatalog.js";import{getActiveProviderProfile as i,getLastUsedProviderProfile as o,isProfiledProvider as t,listProviderProfiles as a,setActiveProfileForProvider as n}from"../../utils/model/providerProfiles.js";import{switchProviderPreference as l}from"../../utils/model/providerSwitch.js";import{hasStoredProviderApiKey as d,hasStoredProviderOAuthTokens as u}from"../../utils/auth.js";export function isCoreProviderEnabled(){return"0"!==process.env.CORE_PROVIDER_ENABLED}export function listCoreProviders(){return r.map(e=>({id:e.id,label:e.label,implemented:e.implemented}))}export function normalizeCoreProviderInput(e){if(e)switch(e.trim().toLowerCase()){case"z.ai":case"z-ai":return"zai";case"open-router":return"openrouter";case"ollama-cloud":case"ollama_cloud":case"ollamacloud":return"ollama-cloud";case"gemini":case"gemini-api-key":case"google-ai":case"google-ai-studio":return"gemini-api";case"gemini-google":case"google":case"google-oauth":return"gemini-google";default:return e.trim().toLowerCase()}}export function getCoreProviderLabel(r){return e(r).label}export function listCoreProviderProfiles(){const e=a(),r=i(),o=e.reduce((e,i)=>{const o=i.provider;return e[o]||(e[o]=[]),e[o].push({id:i.id,name:i.name,provider:o,baseUrl:i.baseUrl,isActive:i.id===r?.id,isAuthenticated:isProviderProfileAuthenticated(o,i.id)}),e},{});return{activeProfile:r?{id:r.id,name:r.name,provider:r.provider,baseUrl:r.baseUrl}:null,providers:o}}export function getCoreCurrentProviderProfile(){const e=i();return e?{activeProfile:{id:e.id,name:e.name,provider:e.provider,baseUrl:e.baseUrl}}:{activeProfile:null}}export function setCoreActiveProfile(e,r){t(e)&&n(e,r)}export function isCoreSelectedProfileReady(e,r){if(!r||!t(e))return!0;const i=o(e);return!!i&&isProviderProfileAuthenticated(e,i.id)}export function switchCoreProvider(e){const r=l({currentModel:e.currentModel,currentProvider:e.currentProvider,targetProvider:e.targetProvider,targetProfileName:e.targetProfileName}),i=t(e.targetProvider)?o(e.targetProvider):null;return{restoredModel:r,activeProfileName:i?.name}}function isProviderProfileAuthenticated(e,r){return"claude"===e?u("claude",r):"openai"===e?u("openai",r):"openrouter"!==e&&"gemini-api"!==e&&"zai"!==e&&"minimax"!==e&&"nvidia"!==e&&"deepseek"!==e&&"xai"!==e&&"gmi"!==e&&"novita"!==e&&"stepfun"!==e&&"huggingface"!==e&&"opencode-zen"!==e&&"arcee"!==e&&"alibaba"!==e&&"kimi"!==e||d(e,r)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsxs as e}from"react/jsx-runtime";import{useCallback as t,useEffect as n,useMemo as o,useRef as s,useState as r}from"react";import{useNotifications as i}from"../context/notifications.js";import{Text as a}from"../ink.js";import{logEvent as l}from"../services/analytics/index.js";import{useDebounceCallback as m}from"usehooks-ts";import{getCommandName as g}from"../commands.js";import{getModeFromInput as c,getValueFromInput as u}from"../components/PromptInput/inputModes.js";import{useIsModalOverlayActive as d,useRegisterOverlay as p}from"../context/overlayContext.js";import{KeyboardEvent as f}from"../ink/events/keyboard-event.js";import{useInput as h}from"../ink.js";import{useOptionalKeybindingContext as v,useRegisterKeybindingContext as A}from"../keybindings/KeybindingContext.js";import{useKeybindings as b}from"../keybindings/useKeybinding.js";import{useShortcutDisplay as S}from"../keybindings/useShortcutDisplay.js";import{useAppState as w,useAppStateStore as $}from"../state/AppState.js";import{isAgentSwarmsEnabled as y}from"../utils/agentSwarmsEnabled.js";import{getShellCompletions as C}from"../utils/bash/shellCompletion.js";import{formatLogMetadata as x}from"../utils/format.js";import{getSessionIdFromLog as k,searchSessionsByCustomTitle as H}from"../utils/sessionStorage.js";import{applyCommandSuggestion as P,findMidInputSlashCommand as T,getBestCommandMatch as W,isCommandInput as L}from"../utils/suggestions/commandSuggestions.js";import{getDirectoryCompletions as j}from"../utils/suggestions/directoryCompletion.js";import{getShellHistoryCompletion as N}from"../utils/suggestions/shellHistoryCompletion.js";import{getSlackChannelSuggestions as I,hasSlackMcpServer as M}from"../utils/suggestions/slackChannelSuggestions.js";import{TEAM_LEAD_NAME as q}from"../utils/swarm/constants.js";import{listProviderProfiles as Q}from"../utils/model/providerProfiles.js";import{applyFileSuggestion as D,findLongestCommonPrefix as R,onIndexBuildComplete as V,startBackgroundCacheRefresh as O}from"./fileSuggestions.js";import{generateUnifiedSuggestions as E}from"./unifiedSuggestions.js";const _=/^@[\p{L}\p{N}\p{M}_\-./\\()[\]~:]*/u,z=/^[\p{L}\p{N}\p{M}_\-./\\()[\]~:]+/u,G=/(@[\p{L}\p{N}\p{M}_\-./\\()[\]~:]*|[\p{L}\p{N}\p{M}_\-./\\()[\]~:]+)$/u,F=/[\p{L}\p{N}\p{M}_\-./\\()[\]~:]+$/u,K=/(^|\s)@([\p{L}\p{N}\p{M}_\-./\\()[\]~:]*|"[^"]*"?)$/u,B=/(^|\s)#([a-z0-9][a-z0-9_-]*)$/,U=["list","current","use","rename","remove","model","agent"],Z=["list","show","enable","disable","setup","orchestrator"],J=["list","create","show","orchestrator","equipo","add-member"],X=["frontend","backend","docs","tests","review","database","devops"],Y=[{provider:"claude",label:"Context"},{provider:"openai",label:"OpenAI"},{provider:"openrouter",label:"OpenRouter"},{provider:"ollama",label:"Ollama"},{provider:"ollama-cloud",label:"Ollama Cloud"},{provider:"gemini-api",label:"Gemini API"},{provider:"gemini-google",label:"Gemini Google OAuth"},{provider:"zai",label:"Z.AI"},{provider:"minimax",label:"MiniMax"},{provider:"nvidia",label:"NVIDIA API"},{provider:"deepseek",label:"DeepSeek"},{provider:"custom-openai",label:"Custom OpenAI"},{provider:"custom-anthropic",label:"Custom Anthropic"}];function isPathMetadata(e){return"object"==typeof e&&null!==e&&"type"in e&&("directory"===e.type||"file"===e.type)}function getPreservedSelection(e,t,n){if(0===n.length)return-1;if(t<0)return 0;const o=e[t];if(!o)return 0;const s=n.findIndex(e=>e.id===o.id);return s>=0?s:0}function replaceProfileArgs(e,t){const n="/profile";return t.length>0?`${n} ${t}`:n}function buildProfileArgSuggestion(e,t,n,o){return{id:e,displayText:t,description:o,metadata:{replacement:n}}}function replaceWorkspaceArgs(e){const t="/workspace";return e.length>0?`${t} ${e}`:t}function buildWorkspaceArgSuggestion(e,t,n,o){return{id:e,displayText:t,description:o,metadata:{replacement:n}}}function replaceTeamArgs(e){const t="/team";return e.length>0?`${t} ${e}`:t}function buildTeamArgSuggestion(e,t,n,o){return{id:e,displayText:t,description:o,metadata:{replacement:n}}}function getProviderCommandSuggestions(e){const t=extractCommandNameAndArgs(e);if(!t||"provider"!==t.commandName)return null;const n=t.args??"",o=/\s$/.test(n),s=n.trim().length>0?n.trim().split(/\s+/):[],r=o?[...s,""]:s,i=r[0]??"",a=r[1]??"",makeProviderSuggestions=e=>Y.filter(t=>t.provider.startsWith(e.toLowerCase())).map(e=>buildProfileArgSuggestion(`provider-choice-${e.provider}`,e.provider,`/provider ${e.provider} `,e.label));if(r.length<=1){const e=i.toLowerCase();return{suggestions:[...["list","current","reset"].filter(t=>t.startsWith(e)).map(e=>buildProfileArgSuggestion(`provider-subcommand-${e}`,e,`/provider ${e} `,"list"===e?"Listar proveedores":"current"===e?"Ver proveedor actual":"Resetear configuración")),...makeProviderSuggestions(e)],commandArgumentHint:"<proveedor|list|current>"}}if(["list","current","reset"].includes(i.toLowerCase()))return{suggestions:[],commandArgumentHint:void 0};if(Y.some(e=>e.provider===i.toLowerCase())&&r.length<=2){const e=a.toLowerCase(),t=((e,t)=>Q(e).filter(e=>e.name.toLowerCase().startsWith(t.toLowerCase())).map(t=>buildProfileArgSuggestion(`provider-profile-${t.id}`,t.name,`/provider ${e} ${t.name} `,`${t.agentName}${t.lastModel?` · ${t.lastModel}`:""}`)))(i.toLowerCase(),e);return{suggestions:[...t,...["reset","set","url","clear"].filter(t=>t.startsWith(e)).map(e=>buildProfileArgSuggestion(`provider-keyword-${e}`,e,`/provider ${i} ${e} `,`Acción: ${e}`))],commandArgumentHint:"<perfil|url|reset>"}}return{suggestions:[],commandArgumentHint:void 0}}function buildSlashArgSuggestion(e,t,n,o){return{id:e,displayText:t,description:o,metadata:{replacement:n}}}const ee=[{name:"status",description:"Ver configuración actual"},{name:"browser",description:"Cambiar navegador",valueAfter:"<chromium|chrome|firefox|webkit|msedge>"},{name:"visible",description:"Modo visible (headed)"},{name:"headless",description:"Modo oculto (headless)"},{name:"executable",description:'Ruta a binario custom o "clear"'},{name:"device",description:'Dispositivo a emular o "clear"'},{name:"viewport",description:'Tamaño viewport (ej 1280x720) o "clear"'},{name:"reset",description:"Borrar config y volver a defaults"},{name:"help",description:"Ver ayuda detallada"}],te=[{name:"chromium",description:"Chromium (default, Playwright lo descarga)"},{name:"chrome",description:"Google Chrome del sistema"},{name:"msedge",description:"Microsoft Edge del sistema (Windows)"},{name:"firefox",description:"Firefox (Playwright lo descarga)"},{name:"webkit",description:"WebKit (Playwright lo descarga)"}];const ne=[{name:"status",description:"Ver estado del bridge y números autorizados"},{name:"permitidos",description:"Listar/configurar números autorizados"},{name:"start",description:"Iniciar bridge (requiere cuenta vinculada)"},{name:"stop",description:"Detener bridge"},{name:"help",description:"Ver ayuda detallada"},{name:"global",description:"Subcomandos del canal global (status/start/stop)"}],oe=[{name:"status",description:"Estado del daemon global"},{name:"start",description:"Iniciar daemon global"},{name:"stop",description:"Detener daemon global"}];const se=[{name:"status",description:"Ver estado del bot y usuarios permitidos"},{name:"permitidos",description:"Listar usuarios autorizados"},{name:"help",description:"Ver ayuda detallada"},{name:"global",description:"Subcomandos del canal global (status/start/stop)"}];const re=[{name:"start",description:"Iniciar servidor y abrir en navegador"},{name:"stop",description:"Detener servidor web"},{name:"status",description:"Ver estado del servidor y conexiones"},{name:"open",description:"Abrir la WebApp en el navegador"},{name:"token",description:"Ver token de autenticación actual"},{name:"port",description:"Cambiar puerto del servidor"},{name:"autostart",description:"Activar/desactivar inicio automático"},{name:"help",description:"Ver ayuda detallada"}];function getProviderAgentRefSuggestions(e,t,n=!0){const o=e.toLowerCase(),s=[];for(const e of Y)for(const r of Q(e.provider)){const i=`${e.provider}/${r.agentName||`${r.name}-lead`}`;i.toLowerCase().startsWith(o)&&s.push(buildTeamArgSuggestion(`team-agent-${r.id}`,i,replaceTeamArgs([...t,i].join(" ")+(n?" ":"")),r.lastModel?`${e.label} - ${r.lastModel}`:e.label))}return s}function applyCommandArgSuggestion(e,t,n){const o=e.metadata,s=o?.replacement??e.displayText;t(s),n(s.length)}function buildResumeInputFromSuggestion(e){const t=e.metadata;return t?.sessionId?`/resume ${t.sessionId}`:`/resume ${e.displayText}`}export function extractSearchToken(e){return e.isQuoted?e.token.slice(2).replace(/"$/,""):e.token.startsWith("@")?e.token.substring(1):e.token}export function formatReplacementValue(e){const{displayText:t,mode:n,hasAtPrefix:o,needsQuotes:s,isQuoted:r,isComplete:i}=e,a=i?" ":"";return r||s?"bash"===n?`"${t}"${a}`:`@"${t}"${a}`:o?"bash"===n?`${t}${a}`:`@${t}${a}`:t}export function applyShellSuggestion(e,t,n,o,s,r){const i=t.slice(0,n).lastIndexOf(" ")+1;let a;a="variable"===r?"$"+e.displayText+" ":"command"===r?e.displayText+" ":e.displayText;o(t.slice(0,i)+a+t.slice(n)),s(i+a.length)}const ie=/(^|\s)@[\w-]*$/;function applyTriggerSuggestion(e,t,n,o,s,r){const i=t.slice(0,n).match(o);if(!i||void 0===i.index)return;const a=i.index+(i[1]?.length??0),l=t.slice(0,a);s(l+e.displayText+" "+t.slice(n)),r(l.length+e.displayText.length+1)}let ae=null;export function applyDirectorySuggestion(e,t,n,o,s){const r=s?"/":" ",i=e.slice(0,n),a="@"+t+r;return{newInput:i+a+e.slice(n+o),cursorPos:i.length+a.length}}export function extractCompletionToken(e,t,n=!1){if(!e)return null;const o=e.substring(0,t);if(n){const n=/@"([^"]*)"?$/,s=o.match(n);if(s&&void 0!==s.index){const n=e.substring(t).match(/^[^"]*"?/),o=n?n[0]:"";return{token:s[0]+o,startPos:s.index,isQuoted:!0}}}if(n){const n=o.lastIndexOf("@");if(n>=0&&(0===n||/\s/.test(o[n-1]))){const s=o.substring(n),r=s.match(_);if(r&&r[0].length===s.length){const o=e.substring(t).match(z),s=o?o[0]:"";return{token:r[0]+s,startPos:n,isQuoted:!1}}}}const s=n?G:F,r=o.match(s);if(!r||void 0===r.index)return null;const i=e.substring(t).match(z),a=i?i[0]:"";return{token:r[0]+a,startPos:r.index,isQuoted:!1}}function extractCommandNameAndArgs(e){if(L(e)){const t=e.indexOf(" ");return-1===t?{commandName:e.slice(1),args:""}:{commandName:e.slice(1,t),args:e.slice(t+1)}}return null}export function useTypeahead({commands:_,onInputChange:z,onSubmit:G,setCursorOffset:F,input:le,cursorOffset:me,mode:ge,agents:ce,setSuggestionsState:ue,suggestionsState:{suggestions:de,selectedSuggestion:pe,commandArgumentHint:fe},suppressSuggestions:he=!1,markAccepted:ve,onModeChange:Ae}){const{addNotification:be}=i(),Se=S("chat:thinkingToggle","Chat","alt+t"),[we,$e]=r("none"),ye=o(()=>{const e=_.filter(e=>!e.isHidden);if(0===e.length)return;return Math.max(...e.map(e=>g(e).length))+6},[_]),[Ce,xe]=r(void 0),ke=w(e=>e.mcp.resources),He=$(),Pe=w(e=>e.promptSuggestion),Te=w(e=>!!e.viewingAgentTaskId),We=v(),[Le,je]=r(void 0),Ne=o(()=>{if("prompt"!==ge||he)return;const e=T(le,me);if(!e)return;const t=W(e.partialCommand,_);return t?{text:t.suffix,fullCommand:t.fullCommand,insertPosition:e.startPos+1+e.partialCommand.length}:void 0},[le,me,ge,_,he]),Ie=he?void 0:"prompt"===ge?Ne:Le,Me=s(me);Me.current=me;const qe=s(null),Qe=s(""),De=(s(""),s("")),Re=s("");s(de).current=de;const Ve=s(null),Oe=t(()=>{ue(()=>({commandArgumentHint:void 0,suggestions:[],selectedSuggestion:-1})),$e("none"),xe(void 0),je(void 0)},[ue]),Ee=t(async(e,t=!1)=>{qe.current=e;const n=await E(e,ke,ce,t);if(qe.current===e){if(0===n.length)return ue(()=>({commandArgumentHint:void 0,suggestions:[],selectedSuggestion:-1})),$e("none"),void xe(void 0);ue(e=>({commandArgumentHint:void 0,suggestions:n,selectedSuggestion:getPreservedSelection(e.suggestions,e.selectedSuggestion,n)})),$e(n.length>0?"file":"none"),xe(void 0)}},[ke,ue,$e,xe,ce]);n(()=>(O(),V(()=>{const e=qe.current;null!==e&&(qe.current=null,Ee(e,""===e))})),[Ee]);const _e=m(Ee,50),ze=t(async e=>{Re.current=e;const t=await I(He.getState().mcp.clients,e);Re.current===e&&(ue(e=>({commandArgumentHint:void 0,suggestions:t,selectedSuggestion:getPreservedSelection(e.suggestions,e.selectedSuggestion,t)})),$e(t.length>0?"slack-channel":"none"),xe(void 0))},[ue]),Ge=m(ze,150),Fe=t(async(e,t)=>{const n=t??Me.current;if(he)return _e.cancel(),void Oe();if("prompt"===ge){const t=T(e,n);if(t){if(W(t.partialCommand,_))return ue(()=>({commandArgumentHint:void 0,suggestions:[],selectedSuggestion:-1})),$e("none"),void xe(void 0)}}if("bash"===ge&&e.trim()){De.current=e;const t=await N(e);if(De.current!==e)return;if(t)return je({text:t.suffix,fullCommand:t.fullCommand,insertPosition:e.length}),ue(()=>({commandArgumentHint:void 0,suggestions:[],selectedSuggestion:-1})),$e("none"),void xe(void 0);je(void 0)}const o="bash"!==ge?e.substring(0,n).match(/(^|\s)@([\w-]*)$/):null;if(o){const e=(o[2]??"").toLowerCase(),t=He.getState(),n=[],s=new Set;if(y()&&t.teamContext)for(const o of Object.values(t.teamContext.teammates??{}))o.name!==q&&o.name.toLowerCase().startsWith(e)&&(s.add(o.name),n.push({id:`dm-${o.name}`,displayText:`@${o.name}`,description:"send message"}));for(const[o,r]of t.agentNameRegistry){if(s.has(o))continue;if(!o.toLowerCase().startsWith(e))continue;const i=t.tasks[r]?.status;n.push({id:`dm-${o}`,displayText:`@${o}`,description:i?`send message · ${i}`:"send message"})}if(n.length>0)return _e.cancel(),ue(e=>({commandArgumentHint:void 0,suggestions:n,selectedSuggestion:getPreservedSelection(e.suggestions,e.selectedSuggestion,n)})),$e("agent"),void xe(void 0)}if("prompt"===ge){const t=e.substring(0,n).match(B);if(t&&M(He.getState().mcp.clients))return void Ge(t[2]);"slack-channel"===we&&(Ge.cancel(),Oe())}const s=e.substring(0,n).match(K),r=n===e.length&&n>0&&e.length>0&&" "===e[n-1];if("prompt"===ge&&L(e)&&n>0){const t=extractCommandNameAndArgs(e);if(t&&"add-dir"===t.commandName&&t.args){const{args:e}=t;if(e.match(/\s+$/))return _e.cancel(),void Oe();const n=await j(e);return n.length>0?(ue(e=>({suggestions:n,selectedSuggestion:getPreservedSelection(e.suggestions,e.selectedSuggestion,n),commandArgumentHint:void 0})),void $e("directory")):(_e.cancel(),void Oe())}if(t&&"resume"===t.commandName&&void 0!==t.args&&e.includes(" ")){const{args:e}=t,n=(await H(e,{limit:10})).map(e=>{const t=k(e);return{id:`resume-title-${t}`,displayText:e.customTitle,description:x(e),metadata:{sessionId:t}}});return n.length>0?(ue(e=>({suggestions:n,selectedSuggestion:getPreservedSelection(e.suggestions,e.selectedSuggestion,n),commandArgumentHint:void 0})),void $e("custom-title")):void Oe()}}const i="prompt"===ge?function(e){const t=extractCommandNameAndArgs(e);if(!t||"team"!==t.commandName)return null;const n=t.args??"",o=/\s$/.test(n),s=n.trim().length>0?n.trim().split(/\s+/):[],r=o?[...s,""]:s,i=r[0]??"",a=i.toLowerCase();if(r.length<=1){const e=i.toLowerCase();return{suggestions:J.filter(t=>t.startsWith(e)).map(e=>buildTeamArgSuggestion(`team-subcommand-${e}`,e,replaceTeamArgs(`${e} `))),commandArgumentHint:"<subcomando>"}}if("list"===a)return{suggestions:[],commandArgumentHint:void 0};if("create"===a)return{suggestions:[],commandArgumentHint:"<nombre-equipo>"};if("show"===a)return{suggestions:[],commandArgumentHint:"<equipo>"};if("orchestrator"===a)return r.length<=2?{suggestions:[],commandArgumentHint:"<equipo>"}:{suggestions:getProviderAgentRefSuggestions(r[r.length-1]??"",r.slice(0,r.length-1),!1),commandArgumentHint:"<provider/agent>"};if("equipo"===a){if(r.length<=2)return{suggestions:[],commandArgumentHint:"<equipo>"};if(r.length<=3){const e=r[1]??"",t=(r[2]??"").toLowerCase();return{suggestions:X.filter(e=>e.startsWith(t)).map(t=>buildTeamArgSuggestion(`team-equipo-${t}`,t,replaceTeamArgs(["equipo",e,t,""].join(" ").trimEnd()+" "),`equipo ${t}`)),commandArgumentHint:"<area>"}}return{suggestions:getProviderAgentRefSuggestions(r[r.length-1]??"",r.slice(0,r.length-1),!1),commandArgumentHint:"<provider/agent>"}}if("add-member"===a){if(r.length<=2)return{suggestions:[],commandArgumentHint:"<equipo>"};if(r.length<=3){const e=r[1]??"",t=(r[2]??"").toLowerCase();return{suggestions:X.filter(e=>e.startsWith(t)).map(t=>buildTeamArgSuggestion(`team-member-equipo-${t}`,t,replaceTeamArgs(["add-member",e,t,""].join(" ").trimEnd()+" "),`equipo ${t}`)),commandArgumentHint:"<area>"}}return r.length<=4?{suggestions:getProviderAgentRefSuggestions(r[3]??"",r.slice(0,3)),commandArgumentHint:"<provider/agent>"}:{suggestions:[],commandArgumentHint:"[duty]"}}return{suggestions:[],commandArgumentHint:void 0}}(e):null;if(i){const{suggestions:e,commandArgumentHint:t}=i;return ue(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),$e(e.length>0?"command-arg":"none"),void xe(void 0)}const a="prompt"===ge?function(e){const t=extractCommandNameAndArgs(e);if(!t||"workspace"!==t.commandName)return null;const n=t.args??"",o=/\s$/.test(n),s=n.trim().length>0?n.trim().split(/\s+/):[],r=o?[...s,""]:s,i=r[0]??"",a=i.toLowerCase();if(r.length<=1){const e=i.toLowerCase();return{suggestions:Z.filter(t=>t.startsWith(e)).map(e=>buildWorkspaceArgSuggestion(`workspace-subcommand-${e}`,e,replaceWorkspaceArgs(`${e} `))),commandArgumentHint:"<subcomando>"}}if(["show","enable","disable"].includes(a)&&r.length<=2){const e=(r[1]??"").toLowerCase();return{suggestions:Y.filter(t=>t.provider.startsWith(e)).map(e=>buildWorkspaceArgSuggestion(`workspace-provider-${e.provider}`,e.provider,replaceWorkspaceArgs(`${a} ${e.provider}`),e.label)),commandArgumentHint:"<proveedor>"}}if("orchestrator"===a)return{suggestions:[],commandArgumentHint:"[equipo] [provider/agent]"};if("setup"!==a)return{suggestions:[],commandArgumentHint:void 0};if(r.length<=2)return{suggestions:[],commandArgumentHint:"<equipo> [orchestrator=<area|provider/agent>]"};const l=r.length-1,m=r[l]??"",g=r.slice(0,l);if(!g.some(e=>e.toLowerCase().startsWith("orchestrator="))&&"orchestrator=".startsWith(m.toLowerCase()))return{suggestions:[buildWorkspaceArgSuggestion("workspace-orchestrator","orchestrator=",replaceWorkspaceArgs([...g,"orchestrator="].join(" ")),"escoger coordinador principal")],commandArgumentHint:"orchestrator=<area|provider/agent>"};if(m.toLowerCase().startsWith("orchestrator=")){const e=m.slice(13).toLowerCase(),t=X.filter(t=>t.startsWith(e)).map(e=>buildWorkspaceArgSuggestion(`workspace-orchestrator-equipo-${e}`,e,replaceWorkspaceArgs([...g,`orchestrator=${e} `].join(" ").trimEnd()),`usar el equipo ${e} como orquestador`)),n=[];for(const t of Y)for(const o of Q(t.provider)){const s=`${t.provider}/${o.agentName||`${o.name}-lead`}`;s.toLowerCase().startsWith(e)&&n.push(buildWorkspaceArgSuggestion(`workspace-orchestrator-agent-${o.id}`,s,replaceWorkspaceArgs([...g,`orchestrator=${s} `].join(" ").trimEnd()),`agente de ${t.label}`))}return{suggestions:[...t,...n],commandArgumentHint:"orchestrator=<area|provider/agent>"}}const c=m.indexOf(":");if(c>=0){const e=m.slice(0,c),t=m.slice(c+1).toLowerCase();return{suggestions:X.filter(e=>e.startsWith(t)).map(t=>buildWorkspaceArgSuggestion(`workspace-equipo-${e}-${t}`,t,replaceWorkspaceArgs([...g,`${e}:${t} `].join(" ").trimEnd()),`equipo ${t}`)),commandArgumentHint:"<proveedor/perfil:area>"}}const u=m.toLowerCase(),d=[];for(const e of Y)for(const t of Q(e.provider)){const n=`${e.provider}/${t.name}`;n.toLowerCase().startsWith(u)&&d.push(buildWorkspaceArgSuggestion(`workspace-profile-${t.id}`,`${n}:`,replaceWorkspaceArgs([...g,`${n}:`].join(" ")),t.lastModel?`${e.label} - ${t.lastModel}`:e.label))}return{suggestions:d,commandArgumentHint:"<proveedor/perfil:area>"}}(e):null;if(a){const{suggestions:e,commandArgumentHint:t}=a;return ue(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),$e(e.length>0?"command-arg":"none"),void xe(void 0)}const l="prompt"===ge?function(e){const t=extractCommandNameAndArgs(e);if(!t||"profile"!==t.commandName)return null;const n=t.args??"",o=/\s$/.test(n),s=n.trim().length>0?n.trim().split(/\s+/):[],r=o?[...s,""]:s,i=r[0]??"",a=r[1]??"",l=r[2]??"",m=i.toLowerCase(),makeProviderSuggestions=(e,t)=>Y.filter(t=>t.provider.startsWith(e.toLowerCase())).map(e=>buildProfileArgSuggestion(`profile-provider-${e.provider}`,e.provider,replaceProfileArgs(0,[...t,e.provider,""].join(" ").trimEnd()+" "),e.label)),makeProfileSuggestions=(e,t,n)=>e&&Y.some(t=>t.provider===e)?Q(e).filter(e=>e.name.toLowerCase().startsWith(t.toLowerCase())).map(e=>buildProfileArgSuggestion(`profile-name-${e.id}`,e.name,replaceProfileArgs(0,[...n,e.name,""].join(" ").trimEnd()+" "),`${e.agentName}${e.lastModel?` · ${e.lastModel}`:""}`)):[];if(r.length<=1){const e=i.toLowerCase();return{suggestions:U.filter(t=>t.startsWith(e)).map(e=>buildProfileArgSuggestion(`profile-subcommand-${e}`,e,replaceProfileArgs(0,`${e} `))),commandArgumentHint:"<subcomando>"}}if("list"===m||"current"===m)return{suggestions:[],commandArgumentHint:void 0};if("remove"===m&&r.length<=2){const e=a.toLowerCase();return{suggestions:[buildProfileArgSuggestion("profile-remove-all","all",replaceProfileArgs(0,"remove all"),"Eliminar todos los perfiles"),...makeProviderSuggestions(e,["remove"])].filter(t=>t.displayText.toLowerCase().startsWith(e)),commandArgumentHint:"<proveedor|all>"}}return["use","rename","remove","model","agent"].includes(m)&&r.length<=2?{suggestions:makeProviderSuggestions(a,[m]),commandArgumentHint:"<proveedor>"}:["use","remove","model","agent"].includes(m)&&r.length<=3?{suggestions:makeProfileSuggestions(a,l,[m,a]),commandArgumentHint:"<perfil>"}:"rename"===m&&r.length<=3?{suggestions:makeProfileSuggestions(a,l,[m,a]),commandArgumentHint:"<perfil-actual>"}:{suggestions:[],commandArgumentHint:void 0}}(e):null;if(l){const{suggestions:e,commandArgumentHint:t}=l;return ue(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),$e(e.length>0?"command-arg":"none"),void xe(void 0)}const m="prompt"===ge?getProviderCommandSuggestions(e):null;if(m){const{suggestions:e,commandArgumentHint:t}=m;return ue(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),$e(e.length>0?"command-arg":"none"),void xe(void 0)}const c="prompt"===ge?function(e){const t=extractCommandNameAndArgs(e);if(!t)return null;const n=t.commandName.toLowerCase();if("playwright"!==n&&"pw"!==n)return null;const o=t.args??"",s=/\s$/.test(o),r=o.trim().length>0?o.trim().split(/\s+/):[],i=s?[...r,""]:r,a=(i[0]??"").toLowerCase(),l=(i[1]??"").toLowerCase();if(i.length<=1)return{suggestions:ee.filter(e=>e.name.startsWith(a)).map(e=>buildSlashArgSuggestion(`playwright-sub-${e.name}`,e.name,`/playwright ${e.name} `,e.description)),commandArgumentHint:"[status|browser|visible|headless|reset|help]"};if("browser"===a&&i.length<=2)return{suggestions:te.filter(e=>e.name.startsWith(l)).map(e=>buildSlashArgSuggestion(`playwright-browser-${e.name}`,e.name,`/playwright browser ${e.name} `,e.description)),commandArgumentHint:"<chromium|chrome|firefox|webkit|msedge>"};return("executable"===a||"device"===a||"viewport"===a)&&i.length<=2&&"clear".startsWith(l)?{suggestions:[buildSlashArgSuggestion(`playwright-${a}-clear`,"clear",`/playwright ${a} clear`,`Quitar ${a} custom`)],commandArgumentHint:"<valor|clear>"}:{suggestions:[],commandArgumentHint:void 0}}(e):null;if(c){const{suggestions:e,commandArgumentHint:t}=c;return ue(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),$e(e.length>0?"command-arg":"none"),void xe(void 0)}const u="prompt"===ge?function(e){const t=extractCommandNameAndArgs(e);if(!t)return null;const n=t.commandName.toLowerCase();if("whatsapp"!==n&&"wa"!==n&&"whats"!==n)return null;const o=t.args??"",s=/\s$/.test(o),r=o.trim().length>0?o.trim().split(/\s+/):[],i=s?[...r,""]:r,a=(i[0]??"").toLowerCase(),l=(i[1]??"").toLowerCase();if(i.length<=1)return{suggestions:ne.filter(e=>e.name.startsWith(a)).map(e=>buildSlashArgSuggestion(`whatsapp-sub-${e.name}`,e.name,`/whatsapp ${e.name} `,e.description)),commandArgumentHint:"[status|permitidos|start|stop|global|help]"};if("global"===a&&i.length<=2)return{suggestions:oe.filter(e=>e.name.startsWith(l)).map(e=>buildSlashArgSuggestion(`whatsapp-global-${e.name}`,e.name,`/whatsapp global ${e.name} `,e.description)),commandArgumentHint:"<status|start|stop>"};return{suggestions:[],commandArgumentHint:void 0}}(e):null;if(u){const{suggestions:e,commandArgumentHint:t}=u;return ue(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),$e(e.length>0?"command-arg":"none"),void xe(void 0)}const d="prompt"===ge?function(e){const t=extractCommandNameAndArgs(e);if(!t)return null;const n=t.commandName.toLowerCase();if("telegram"!==n&&"tg"!==n)return null;const o=t.args??"",s=/\s$/.test(o),r=o.trim().length>0?o.trim().split(/\s+/):[],i=s?[...r,""]:r,a=(i[0]??"").toLowerCase(),l=(i[1]??"").toLowerCase();if(i.length<=1)return{suggestions:se.filter(e=>e.name.startsWith(a)).map(e=>buildSlashArgSuggestion(`telegram-sub-${e.name}`,e.name,`/telegram ${e.name} `,e.description)),commandArgumentHint:"[status|permitidos|global|help]"};if("global"===a&&i.length<=2)return{suggestions:oe.filter(e=>e.name.startsWith(l)).map(e=>buildSlashArgSuggestion(`telegram-global-${e.name}`,e.name,`/telegram global ${e.name} `,e.description)),commandArgumentHint:"<status|start|stop>"};return{suggestions:[],commandArgumentHint:void 0}}(e):null;if(d){const{suggestions:e,commandArgumentHint:t}=d;return ue(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),$e(e.length>0?"command-arg":"none"),void xe(void 0)}const p="prompt"===ge?function(e){const t=extractCommandNameAndArgs(e);if(!t)return null;const n=t.commandName.toLowerCase();if("webapp"!==n&&"app"!==n&&"pwa"!==n&&"aplicacion-web"!==n)return null;const o=t.args??"",s=/\s$/.test(o),r=o.trim().length>0?o.trim().split(/\s+/):[],i=s?[...r,""]:r,a=(i[0]??"").toLowerCase(),l=(i[1]??"").toLowerCase();if(i.length<=1)return{suggestions:re.filter(e=>e.name.startsWith(a)).map(e=>buildSlashArgSuggestion(`webapp-sub-${e.name}`,e.name,`/webapp ${e.name} `,e.description)),commandArgumentHint:"[start|stop|status|open|token|port|autostart|help]"};if("token"===a&&i.length<=2)return{suggestions:[{name:"reset",description:"Regenerar token (invalida el anterior)"}].filter(e=>e.name.startsWith(l)).map(e=>buildSlashArgSuggestion(`webapp-token-${e.name}`,e.name,`/webapp token ${e.name} `,e.description)),commandArgumentHint:"[reset]"};return{suggestions:[],commandArgumentHint:void 0}}(e):null;if(p){const{suggestions:e,commandArgumentHint:t}=p;return ue(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),$e(e.length>0?"command-arg":"none"),void xe(void 0)}if("bash"!==ge&&L(e)&&n>0&&!r){const t=e.slice(1).toLowerCase();if(!function(e,t){return!e&&t.includes(" ")&&!t.endsWith(" ")}(r,e)){const e=_.filter(e=>!e.isHidden).filter(e=>g(e).startsWith(t)||(e.aliases??[]).some(e=>e.startsWith(t))).map(e=>({id:g(e),displayText:`/${g(e)}`,description:e.description??"",metadata:e}));return ue(t=>({commandArgumentHint:void 0,suggestions:e,selectedSuggestion:getPreservedSelection(t.suggestions,t.selectedSuggestion,e)})),$e(e.length>0?"command":"none"),void xe(e.length>0?ye:void 0)}}if(s){const t=extractCompletionToken(e,n,!0);if(t){const e=t.token.startsWith("@"),n=e?t.token.substring(1):t.token;return void _e(n,e)}}_e.cancel(),Oe()},[ge,he,_,Oe,_e,ue,ye,Ge,we]);n(()=>{Ve.current!==le&&(Qe.current!==le&&(Qe.current=le,qe.current=null),Ve.current=null,Fe(le))},[le,Fe]);const Ke=t(async()=>{if(Ie){if("bash"===ge)return z(Ie.fullCommand),F(Ie.fullCommand.length),void je(void 0);const e=T(le,me);if(e){const t=le.slice(0,e.startPos),n=le.slice(e.startPos+e.token.length),o=t+"/"+Ie.fullCommand+" "+n,s=e.startPos+1+Ie.fullCommand.length+1;return z(o),void F(s)}}if(de.length>0){_e.cancel(),Ge.cancel();const e=-1===pe?0:pe,t=de[e];if("command"===we&&e<de.length)t&&(P(t,!1,_,z,F,G),Oe());else if("command-arg"===we&&e<de.length)t&&(applyCommandArgSuggestion(t,z,F),Oe());else if("custom-title"===we&&de.length>0){if(t){const e=buildResumeInputFromSuggestion(t);z(e),F(e.length),Oe()}}else if("directory"===we&&de.length>0){const t=de[e];if(t){let e;if(L(le)){const n=le.indexOf(" "),o=le.slice(0,n+1),s=isPathMetadata(t.metadata)&&"directory"===t.metadata.type?"/":" ";e=o+t.id+s,z(e),F(e.length),isPathMetadata(t.metadata)&&"directory"===t.metadata.type?(ue(e=>({...e,commandArgumentHint:void 0})),Fe(e,e.length)):Oe()}else{const n=extractCompletionToken(le,me,!0)??extractCompletionToken(le,me,!1);if(n){const o=isPathMetadata(t.metadata)&&"directory"===t.metadata.type,s=applyDirectorySuggestion(le,t.id,n.startPos,n.token.length,o);e=s.newInput,z(e),F(s.cursorPos),o?(ue(e=>({...e,commandArgumentHint:void 0})),Fe(e,s.cursorPos)):Oe()}else Oe()}}}else if("shell"===we&&de.length>0){const t=de[e];if(t){const e=t.metadata;applyShellSuggestion(t,le,me,z,F,e?.completionType),Oe()}}else if("agent"===we&&de.length>0&&de[e]?.id?.startsWith("dm-")){const t=de[e];t&&(applyTriggerSuggestion(t,le,me,ie,z,F),Oe())}else if("slack-channel"===we&&de.length>0){const t=de[e];t&&(applyTriggerSuggestion(t,le,me,B,z,F),Oe())}else if("file"===we&&de.length>0){const t=extractCompletionToken(le,me,!0);if(!t)return void Oe();const n=R(de),o=t.token.startsWith("@");let s;if(s=t.isQuoted?t.token.slice(2).replace(/"$/,"").length:o?t.token.length-1:t.token.length,n.length>s){const e=formatReplacementValue({displayText:n,mode:ge,hasAtPrefix:o,needsQuotes:!1,isQuoted:t.isQuoted,isComplete:!1});D(e,le,t.token,t.startPos,z,F),Fe(le.replace(t.token,e),me)}else if(e<de.length){const n=de[e];if(n){const e=n.displayText.includes(" "),s=formatReplacementValue({displayText:n.displayText,mode:ge,hasAtPrefix:o,needsQuotes:e,isQuoted:t.isQuoted,isComplete:!0});D(s,le,t.token,t.startPos,z,F),Oe()}}}}else if(""!==le.trim()){let e,t;if("bash"===ge){e="shell";const n=await async function(e,t){try{return ae&&ae.abort(),ae=new AbortController,await C(e,t,ae.signal)}catch{return l("tengu_shell_completion_failed",{}),[]}}(le,me);if(1===n.length){const e=n[0];if(e){const t=e.metadata;applyShellSuggestion(e,le,me,z,F,t?.completionType)}t=[]}else t=n}else{e="file";const n=extractCompletionToken(le,me,!0);if(n){const e=n.token.startsWith("@"),o=e?n.token.substring(1):n.token;t=await E(o,ke,ce,e)}else t=[]}t.length>0&&(ue(e=>({commandArgumentHint:void 0,suggestions:t,selectedSuggestion:getPreservedSelection(e.suggestions,e.selectedSuggestion,t)})),$e(e),xe(void 0))}},[de,pe,le,we,_,ge,z,F,G,Oe,me,Fe,ke,ue,ce,_e,Ge,Ie]),Be=t(()=>{if(pe<0||0===de.length)return;const e=de[pe];if("command"===we&&pe<de.length)e&&(P(e,!0,_,z,F,G),_e.cancel(),Oe());else if("command-arg"===we&&pe<de.length){if(e){const t=e.metadata;if((t?.replacement??e.displayText).trim()===le.trim())return _e.cancel(),Oe(),void G(le,!0);applyCommandArgSuggestion(e,z,F),_e.cancel(),Oe()}}else if("custom-title"===we&&pe<de.length){if(e){const t=buildResumeInputFromSuggestion(e);z(t),F(t.length),G(t,!0),_e.cancel(),Oe()}}else if("shell"===we&&pe<de.length){const e=de[pe];if(e){const t=e.metadata;applyShellSuggestion(e,le,me,z,F,t?.completionType),_e.cancel(),Oe()}}else if("agent"===we&&pe<de.length&&e?.id?.startsWith("dm-"))applyTriggerSuggestion(e,le,me,ie,z,F),_e.cancel(),Oe();else if("slack-channel"===we&&pe<de.length)e&&(applyTriggerSuggestion(e,le,me,B,z,F),Ge.cancel(),Oe());else if("file"===we&&pe<de.length){const t=extractCompletionToken(le,me,!0);if(t&&e){const n=t.token.startsWith("@"),o=e.displayText.includes(" "),s=formatReplacementValue({displayText:e.displayText,mode:ge,hasAtPrefix:n,needsQuotes:o,isQuoted:t.isQuoted,isComplete:!0});D(s,le,t.token,t.startPos,z,F),_e.cancel(),Oe()}}else if("directory"===we&&pe<de.length&&e){if(L(le))return _e.cancel(),void Oe();const t=extractCompletionToken(le,me,!0)??extractCompletionToken(le,me,!1);if(t){const n=isPathMetadata(e.metadata)&&"directory"===e.metadata.type,o=applyDirectorySuggestion(le,e.id,t.startPos,t.token.length,n);z(o.newInput),F(o.cursorPos)}_e.cancel(),Oe()}},[de,pe,we,_,le,me,ge,z,F,G,Oe,_e,Ge]),Ue=t(()=>{Ke()},[Ke]),Ze=t(()=>{_e.cancel(),Ge.cancel(),Oe(),Ve.current=le},[_e,Ge,Oe,le]),Je=t(()=>{ue(e=>({...e,selectedSuggestion:e.selectedSuggestion<=0?de.length-1:e.selectedSuggestion-1}))},[de.length,ue]),Xe=t(()=>{ue(e=>({...e,selectedSuggestion:e.selectedSuggestion>=de.length-1?0:e.selectedSuggestion+1}))},[de.length,ue]),Ye=o(()=>({"autocomplete:accept":Ue,"autocomplete:dismiss":Ze,"autocomplete:previous":Je,"autocomplete:next":Xe}),[Ue,Ze,Je,Xe]),et=de.length>0||!!Ie,tt=d();function acceptSuggestionText(e){const t=c(e);if("prompt"!==t&&Ae){Ae(t);const n=u(e);z(n),F(n.length)}else z(e),F(e.length)}p("autocomplete",et),A("Autocomplete",et),b(Ye,{context:"Autocomplete",isActive:et&&!tt});const handleKeyDown=t=>{if("right"===t.key&&!Te){const e=Pe.text,n=Pe.shownAt;if(e&&n>0&&""===le)return ve(),acceptSuggestionText(e),void t.stopImmediatePropagation()}if("tab"===t.key&&!t.shift){if(de.length>0||Ie)return;const n=Pe.text,o=Pe.shownAt;return n&&o>0&&""===le&&!Te?(t.preventDefault(),ve(),void acceptSuggestionText(n)):void(""===le.trim()&&(t.preventDefault(),be({key:"thinking-toggle-hint",jsx:e(a,{dimColor:!0,children:["Usa ",Se," para alternar el modo de razonamiento"]}),priority:"immediate",timeoutMs:3e3})))}if(0===de.length)return;const n=null!=We?.pendingChord;return t.ctrl&&"n"===t.key&&!n?(t.preventDefault(),void Xe()):t.ctrl&&"p"===t.key&&!n?(t.preventDefault(),void Je()):void("return"!==t.key||t.shift||t.meta||(t.preventDefault(),Be()))};return h((e,t,n)=>{const o=new f(n.keypress);handleKeyDown(o),o.didStopImmediatePropagation()&&n.stopImmediatePropagation()}),{suggestions:de,selectedSuggestion:pe,suggestionType:we,maxColumnWidth:Ce,commandArgumentHint:fe,inlineGhostText:Ie,handleKeyDown}}
|
|
1
|
+
import{jsxs as e}from"react/jsx-runtime";import{useCallback as t,useEffect as n,useMemo as o,useRef as s,useState as r}from"react";import{useNotifications as i}from"../context/notifications.js";import{Text as a}from"../ink.js";import{logEvent as l}from"../services/analytics/index.js";import{useDebounceCallback as g}from"usehooks-ts";import{getCommandName as m}from"../commands.js";import{getModeFromInput as c,getValueFromInput as u}from"../components/PromptInput/inputModes.js";import{useIsModalOverlayActive as d,useRegisterOverlay as p}from"../context/overlayContext.js";import{KeyboardEvent as f}from"../ink/events/keyboard-event.js";import{useInput as h}from"../ink.js";import{useOptionalKeybindingContext as v,useRegisterKeybindingContext as A}from"../keybindings/KeybindingContext.js";import{useKeybindings as b}from"../keybindings/useKeybinding.js";import{useShortcutDisplay as S}from"../keybindings/useShortcutDisplay.js";import{useAppState as w,useAppStateStore as $}from"../state/AppState.js";import{isAgentSwarmsEnabled as y}from"../utils/agentSwarmsEnabled.js";import{getShellCompletions as C}from"../utils/bash/shellCompletion.js";import{formatLogMetadata as x}from"../utils/format.js";import{getSessionIdFromLog as k,searchSessionsByCustomTitle as H}from"../utils/sessionStorage.js";import{applyCommandSuggestion as P,findMidInputSlashCommand as T,getBestCommandMatch as W,isCommandInput as L}from"../utils/suggestions/commandSuggestions.js";import{getDirectoryCompletions as j}from"../utils/suggestions/directoryCompletion.js";import{getShellHistoryCompletion as N}from"../utils/suggestions/shellHistoryCompletion.js";import{getSlackChannelSuggestions as I,hasSlackMcpServer as M}from"../utils/suggestions/slackChannelSuggestions.js";import{TEAM_LEAD_NAME as q}from"../utils/swarm/constants.js";import{listProviderProfiles as Q}from"../utils/model/providerProfiles.js";import{applyFileSuggestion as D,findLongestCommonPrefix as R,onIndexBuildComplete as V,startBackgroundCacheRefresh as O}from"./fileSuggestions.js";import{generateUnifiedSuggestions as E}from"./unifiedSuggestions.js";const _=/^@[\p{L}\p{N}\p{M}_\-./\\()[\]~:]*/u,z=/^[\p{L}\p{N}\p{M}_\-./\\()[\]~:]+/u,G=/(@[\p{L}\p{N}\p{M}_\-./\\()[\]~:]*|[\p{L}\p{N}\p{M}_\-./\\()[\]~:]+)$/u,F=/[\p{L}\p{N}\p{M}_\-./\\()[\]~:]+$/u,K=/(^|\s)@([\p{L}\p{N}\p{M}_\-./\\()[\]~:]*|"[^"]*"?)$/u,B=/(^|\s)#([a-z0-9][a-z0-9_-]*)$/,U=["list","current","create","use","rename","remove","model","agent","migrate","clear","clear-all"],Z=new Set(["perfil","perfiles","profile","profiles"]),J=["list","show","enable","disable","setup","orchestrator"],X=["list","create","show","orchestrator","equipo","add-member"],Y=["frontend","backend","docs","tests","review","database","devops"],ee=[{provider:"claude",label:"Context"},{provider:"openai",label:"OpenAI"},{provider:"openrouter",label:"OpenRouter"},{provider:"ollama",label:"Ollama"},{provider:"ollama-cloud",label:"Ollama Cloud"},{provider:"gemini-api",label:"Gemini API"},{provider:"gemini-google",label:"Gemini Google OAuth"},{provider:"zai",label:"Z.AI"},{provider:"minimax",label:"MiniMax"},{provider:"nvidia",label:"NVIDIA API"},{provider:"deepseek",label:"DeepSeek"},{provider:"custom-openai",label:"Custom OpenAI"},{provider:"custom-anthropic",label:"Custom Anthropic"}];function isPathMetadata(e){return"object"==typeof e&&null!==e&&"type"in e&&("directory"===e.type||"file"===e.type)}function getPreservedSelection(e,t,n){if(0===n.length)return-1;if(t<0)return 0;const o=e[t];if(!o)return 0;const s=n.findIndex(e=>e.id===o.id);return s>=0?s:0}function replaceProfileArgs(e,t){const n=/^\/([^\s]+)/.exec(e),o=n?`/${n[1]}`:"/perfil";return t.length>0?`${o} ${t}`:o}function buildProfileArgSuggestion(e,t,n,o){return{id:e,displayText:t,description:o,metadata:{replacement:n}}}function replaceWorkspaceArgs(e){const t="/workspace";return e.length>0?`${t} ${e}`:t}function buildWorkspaceArgSuggestion(e,t,n,o){return{id:e,displayText:t,description:o,metadata:{replacement:n}}}function replaceTeamArgs(e){const t="/team";return e.length>0?`${t} ${e}`:t}function buildTeamArgSuggestion(e,t,n,o){return{id:e,displayText:t,description:o,metadata:{replacement:n}}}function getProviderCommandSuggestions(e){const t=extractCommandNameAndArgs(e);if(!t||"provider"!==t.commandName)return null;const n=t.args??"",o=/\s$/.test(n),s=n.trim().length>0?n.trim().split(/\s+/):[],r=o?[...s,""]:s,i=r[0]??"",a=r[1]??"",makeProviderSuggestions=e=>ee.filter(t=>t.provider.startsWith(e.toLowerCase())).map(e=>buildProfileArgSuggestion(`provider-choice-${e.provider}`,e.provider,`/provider ${e.provider} `,e.label));if(r.length<=1){const e=i.toLowerCase();return{suggestions:[...["list","current","reset","clear","clear-all"].filter(t=>t.startsWith(e)).map(e=>buildProfileArgSuggestion(`provider-subcommand-${e}`,e,`/provider ${e} `,"list"===e?"Listar proveedores":"current"===e?"Ver proveedor actual":"clear"===e||"clear-all"===e?"Eliminar todos los perfiles y credenciales":"Resetear configuración")),...makeProviderSuggestions(e)],commandArgumentHint:"<proveedor|list|current|clear>"}}if("clear"===i.toLowerCase()&&r.length<=2){const e=a.toLowerCase();if("all".startsWith(e))return{suggestions:[buildProfileArgSuggestion("provider-clear-all","all","/provider clear all","Eliminar todos los perfiles y credenciales")],commandArgumentHint:"[all]"}}if(["list","current","reset","clear","clear-all"].includes(i.toLowerCase()))return{suggestions:[],commandArgumentHint:void 0};if(ee.some(e=>e.provider===i.toLowerCase())&&r.length<=2){const e=a.toLowerCase(),t=((e,t)=>Q(e).filter(e=>e.name.toLowerCase().startsWith(t.toLowerCase())).map(t=>buildProfileArgSuggestion(`provider-profile-${t.id}`,t.name,`/provider ${e} ${t.name} `,`${t.agentName}${t.lastModel?` · ${t.lastModel}`:""}`)))(i.toLowerCase(),e);return{suggestions:[...t,...["reset","set","url","clear"].filter(t=>t.startsWith(e)).map(e=>buildProfileArgSuggestion(`provider-keyword-${e}`,e,`/provider ${i} ${e} `,`Acción: ${e}`))],commandArgumentHint:"<perfil|url|reset>"}}return{suggestions:[],commandArgumentHint:void 0}}function buildSlashArgSuggestion(e,t,n,o){return{id:e,displayText:t,description:o,metadata:{replacement:n}}}const te=[{name:"status",description:"Ver configuración actual"},{name:"browser",description:"Cambiar navegador",valueAfter:"<chromium|chrome|firefox|webkit|msedge>"},{name:"visible",description:"Modo visible (headed)"},{name:"headless",description:"Modo oculto (headless)"},{name:"executable",description:'Ruta a binario custom o "clear"'},{name:"device",description:'Dispositivo a emular o "clear"'},{name:"viewport",description:'Tamaño viewport (ej 1280x720) o "clear"'},{name:"reset",description:"Borrar config y volver a defaults"},{name:"help",description:"Ver ayuda detallada"}],ne=[{name:"chromium",description:"Chromium (default, Playwright lo descarga)"},{name:"chrome",description:"Google Chrome del sistema"},{name:"msedge",description:"Microsoft Edge del sistema (Windows)"},{name:"firefox",description:"Firefox (Playwright lo descarga)"},{name:"webkit",description:"WebKit (Playwright lo descarga)"}];const oe=[{name:"status",description:"Ver estado del bridge y números autorizados"},{name:"permitidos",description:"Listar/configurar números autorizados"},{name:"start",description:"Iniciar bridge (requiere cuenta vinculada)"},{name:"stop",description:"Detener bridge"},{name:"help",description:"Ver ayuda detallada"},{name:"global",description:"Subcomandos del canal global (status/start/stop)"}],se=[{name:"status",description:"Estado del daemon global"},{name:"start",description:"Iniciar daemon global"},{name:"stop",description:"Detener daemon global"}];const re=[{name:"status",description:"Ver estado del bot y usuarios permitidos"},{name:"permitidos",description:"Listar usuarios autorizados"},{name:"help",description:"Ver ayuda detallada"},{name:"global",description:"Subcomandos del canal global (status/start/stop)"}];const ie=[{name:"start",description:"Iniciar servidor y abrir en navegador"},{name:"stop",description:"Detener servidor web"},{name:"status",description:"Ver estado del servidor y conexiones"},{name:"open",description:"Abrir la WebApp en el navegador"},{name:"token",description:"Ver token de autenticación actual"},{name:"port",description:"Cambiar puerto del servidor"},{name:"autostart",description:"Activar/desactivar inicio automático"},{name:"help",description:"Ver ayuda detallada"}];function getProviderAgentRefSuggestions(e,t,n=!0){const o=e.toLowerCase(),s=[];for(const e of ee)for(const r of Q(e.provider)){const i=`${e.provider}/${r.agentName||`${r.name}-lead`}`;i.toLowerCase().startsWith(o)&&s.push(buildTeamArgSuggestion(`team-agent-${r.id}`,i,replaceTeamArgs([...t,i].join(" ")+(n?" ":"")),r.lastModel?`${e.label} - ${r.lastModel}`:e.label))}return s}function applyCommandArgSuggestion(e,t,n){const o=e.metadata,s=o?.replacement??e.displayText;t(s),n(s.length)}function buildResumeInputFromSuggestion(e){const t=e.metadata;return t?.sessionId?`/resume ${t.sessionId}`:`/resume ${e.displayText}`}export function extractSearchToken(e){return e.isQuoted?e.token.slice(2).replace(/"$/,""):e.token.startsWith("@")?e.token.substring(1):e.token}export function formatReplacementValue(e){const{displayText:t,mode:n,hasAtPrefix:o,needsQuotes:s,isQuoted:r,isComplete:i}=e,a=i?" ":"";return r||s?"bash"===n?`"${t}"${a}`:`@"${t}"${a}`:o?"bash"===n?`${t}${a}`:`@${t}${a}`:t}export function applyShellSuggestion(e,t,n,o,s,r){const i=t.slice(0,n).lastIndexOf(" ")+1;let a;a="variable"===r?"$"+e.displayText+" ":"command"===r?e.displayText+" ":e.displayText;o(t.slice(0,i)+a+t.slice(n)),s(i+a.length)}const ae=/(^|\s)@[\w-]*$/;function applyTriggerSuggestion(e,t,n,o,s,r){const i=t.slice(0,n).match(o);if(!i||void 0===i.index)return;const a=i.index+(i[1]?.length??0),l=t.slice(0,a);s(l+e.displayText+" "+t.slice(n)),r(l.length+e.displayText.length+1)}let le=null;export function applyDirectorySuggestion(e,t,n,o,s){const r=s?"/":" ",i=e.slice(0,n),a="@"+t+r;return{newInput:i+a+e.slice(n+o),cursorPos:i.length+a.length}}export function extractCompletionToken(e,t,n=!1){if(!e)return null;const o=e.substring(0,t);if(n){const n=/@"([^"]*)"?$/,s=o.match(n);if(s&&void 0!==s.index){const n=e.substring(t).match(/^[^"]*"?/),o=n?n[0]:"";return{token:s[0]+o,startPos:s.index,isQuoted:!0}}}if(n){const n=o.lastIndexOf("@");if(n>=0&&(0===n||/\s/.test(o[n-1]))){const s=o.substring(n),r=s.match(_);if(r&&r[0].length===s.length){const o=e.substring(t).match(z),s=o?o[0]:"";return{token:r[0]+s,startPos:n,isQuoted:!1}}}}const s=n?G:F,r=o.match(s);if(!r||void 0===r.index)return null;const i=e.substring(t).match(z),a=i?i[0]:"";return{token:r[0]+a,startPos:r.index,isQuoted:!1}}function extractCommandNameAndArgs(e){if(L(e)){const t=e.indexOf(" ");return-1===t?{commandName:e.slice(1),args:""}:{commandName:e.slice(1,t),args:e.slice(t+1)}}return null}export function useTypeahead({commands:_,onInputChange:z,onSubmit:G,setCursorOffset:F,input:ge,cursorOffset:me,mode:ce,agents:ue,setSuggestionsState:de,suggestionsState:{suggestions:pe,selectedSuggestion:fe,commandArgumentHint:he},suppressSuggestions:ve=!1,markAccepted:Ae,onModeChange:be}){const{addNotification:Se}=i(),we=S("chat:thinkingToggle","Chat","alt+t"),[$e,ye]=r("none"),Ce=o(()=>{const e=_.filter(e=>!e.isHidden);if(0===e.length)return;return Math.max(...e.map(e=>m(e).length))+6},[_]),[xe,ke]=r(void 0),He=w(e=>e.mcp.resources),Pe=$(),Te=w(e=>e.promptSuggestion),We=w(e=>!!e.viewingAgentTaskId),Le=v(),[je,Ne]=r(void 0),Ie=o(()=>{if("prompt"!==ce||ve)return;const e=T(ge,me);if(!e)return;const t=W(e.partialCommand,_);return t?{text:t.suffix,fullCommand:t.fullCommand,insertPosition:e.startPos+1+e.partialCommand.length}:void 0},[ge,me,ce,_,ve]),Me=ve?void 0:"prompt"===ce?Ie:je,qe=s(me);qe.current=me;const Qe=s(null),De=s(""),Re=(s(""),s("")),Ve=s("");s(pe).current=pe;const Oe=s(null),Ee=t(()=>{de(()=>({commandArgumentHint:void 0,suggestions:[],selectedSuggestion:-1})),ye("none"),ke(void 0),Ne(void 0)},[de]),_e=t(async(e,t=!1)=>{Qe.current=e;const n=await E(e,He,ue,t);if(Qe.current===e){if(0===n.length)return de(()=>({commandArgumentHint:void 0,suggestions:[],selectedSuggestion:-1})),ye("none"),void ke(void 0);de(e=>({commandArgumentHint:void 0,suggestions:n,selectedSuggestion:getPreservedSelection(e.suggestions,e.selectedSuggestion,n)})),ye(n.length>0?"file":"none"),ke(void 0)}},[He,de,ye,ke,ue]);n(()=>(O(),V(()=>{const e=Qe.current;null!==e&&(Qe.current=null,_e(e,""===e))})),[_e]);const ze=g(_e,50),Ge=t(async e=>{Ve.current=e;const t=await I(Pe.getState().mcp.clients,e);Ve.current===e&&(de(e=>({commandArgumentHint:void 0,suggestions:t,selectedSuggestion:getPreservedSelection(e.suggestions,e.selectedSuggestion,t)})),ye(t.length>0?"slack-channel":"none"),ke(void 0))},[de]),Fe=g(Ge,150),Ke=t(async(e,t)=>{const n=t??qe.current;if(ve)return ze.cancel(),void Ee();if("prompt"===ce){const t=T(e,n);if(t){if(W(t.partialCommand,_))return de(()=>({commandArgumentHint:void 0,suggestions:[],selectedSuggestion:-1})),ye("none"),void ke(void 0)}}if("bash"===ce&&e.trim()){Re.current=e;const t=await N(e);if(Re.current!==e)return;if(t)return Ne({text:t.suffix,fullCommand:t.fullCommand,insertPosition:e.length}),de(()=>({commandArgumentHint:void 0,suggestions:[],selectedSuggestion:-1})),ye("none"),void ke(void 0);Ne(void 0)}const o="bash"!==ce?e.substring(0,n).match(/(^|\s)@([\w-]*)$/):null;if(o){const e=(o[2]??"").toLowerCase(),t=Pe.getState(),n=[],s=new Set;if(y()&&t.teamContext)for(const o of Object.values(t.teamContext.teammates??{}))o.name!==q&&o.name.toLowerCase().startsWith(e)&&(s.add(o.name),n.push({id:`dm-${o.name}`,displayText:`@${o.name}`,description:"send message"}));for(const[o,r]of t.agentNameRegistry){if(s.has(o))continue;if(!o.toLowerCase().startsWith(e))continue;const i=t.tasks[r]?.status;n.push({id:`dm-${o}`,displayText:`@${o}`,description:i?`send message · ${i}`:"send message"})}if(n.length>0)return ze.cancel(),de(e=>({commandArgumentHint:void 0,suggestions:n,selectedSuggestion:getPreservedSelection(e.suggestions,e.selectedSuggestion,n)})),ye("agent"),void ke(void 0)}if("prompt"===ce){const t=e.substring(0,n).match(B);if(t&&M(Pe.getState().mcp.clients))return void Fe(t[2]);"slack-channel"===$e&&(Fe.cancel(),Ee())}const s=e.substring(0,n).match(K),r=n===e.length&&n>0&&e.length>0&&" "===e[n-1];if("prompt"===ce&&L(e)&&n>0){const t=extractCommandNameAndArgs(e);if(t&&"add-dir"===t.commandName&&t.args){const{args:e}=t;if(e.match(/\s+$/))return ze.cancel(),void Ee();const n=await j(e);return n.length>0?(de(e=>({suggestions:n,selectedSuggestion:getPreservedSelection(e.suggestions,e.selectedSuggestion,n),commandArgumentHint:void 0})),void ye("directory")):(ze.cancel(),void Ee())}if(t&&"resume"===t.commandName&&void 0!==t.args&&e.includes(" ")){const{args:e}=t,n=(await H(e,{limit:10})).map(e=>{const t=k(e);return{id:`resume-title-${t}`,displayText:e.customTitle,description:x(e),metadata:{sessionId:t}}});return n.length>0?(de(e=>({suggestions:n,selectedSuggestion:getPreservedSelection(e.suggestions,e.selectedSuggestion,n),commandArgumentHint:void 0})),void ye("custom-title")):void Ee()}}const i="prompt"===ce?function(e){const t=extractCommandNameAndArgs(e);if(!t||"team"!==t.commandName)return null;const n=t.args??"",o=/\s$/.test(n),s=n.trim().length>0?n.trim().split(/\s+/):[],r=o?[...s,""]:s,i=r[0]??"",a=i.toLowerCase();if(r.length<=1){const e=i.toLowerCase();return{suggestions:X.filter(t=>t.startsWith(e)).map(e=>buildTeamArgSuggestion(`team-subcommand-${e}`,e,replaceTeamArgs(`${e} `))),commandArgumentHint:"<subcomando>"}}if("list"===a)return{suggestions:[],commandArgumentHint:void 0};if("create"===a)return{suggestions:[],commandArgumentHint:"<nombre-equipo>"};if("show"===a)return{suggestions:[],commandArgumentHint:"<equipo>"};if("orchestrator"===a)return r.length<=2?{suggestions:[],commandArgumentHint:"<equipo>"}:{suggestions:getProviderAgentRefSuggestions(r[r.length-1]??"",r.slice(0,r.length-1),!1),commandArgumentHint:"<provider/agent>"};if("equipo"===a){if(r.length<=2)return{suggestions:[],commandArgumentHint:"<equipo>"};if(r.length<=3){const e=r[1]??"",t=(r[2]??"").toLowerCase();return{suggestions:Y.filter(e=>e.startsWith(t)).map(t=>buildTeamArgSuggestion(`team-equipo-${t}`,t,replaceTeamArgs(["equipo",e,t,""].join(" ").trimEnd()+" "),`equipo ${t}`)),commandArgumentHint:"<area>"}}return{suggestions:getProviderAgentRefSuggestions(r[r.length-1]??"",r.slice(0,r.length-1),!1),commandArgumentHint:"<provider/agent>"}}if("add-member"===a){if(r.length<=2)return{suggestions:[],commandArgumentHint:"<equipo>"};if(r.length<=3){const e=r[1]??"",t=(r[2]??"").toLowerCase();return{suggestions:Y.filter(e=>e.startsWith(t)).map(t=>buildTeamArgSuggestion(`team-member-equipo-${t}`,t,replaceTeamArgs(["add-member",e,t,""].join(" ").trimEnd()+" "),`equipo ${t}`)),commandArgumentHint:"<area>"}}return r.length<=4?{suggestions:getProviderAgentRefSuggestions(r[3]??"",r.slice(0,3)),commandArgumentHint:"<provider/agent>"}:{suggestions:[],commandArgumentHint:"[duty]"}}return{suggestions:[],commandArgumentHint:void 0}}(e):null;if(i){const{suggestions:e,commandArgumentHint:t}=i;return de(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),ye(e.length>0?"command-arg":"none"),void ke(void 0)}const a="prompt"===ce?function(e){const t=extractCommandNameAndArgs(e);if(!t||"workspace"!==t.commandName)return null;const n=t.args??"",o=/\s$/.test(n),s=n.trim().length>0?n.trim().split(/\s+/):[],r=o?[...s,""]:s,i=r[0]??"",a=i.toLowerCase();if(r.length<=1){const e=i.toLowerCase();return{suggestions:J.filter(t=>t.startsWith(e)).map(e=>buildWorkspaceArgSuggestion(`workspace-subcommand-${e}`,e,replaceWorkspaceArgs(`${e} `))),commandArgumentHint:"<subcomando>"}}if(["show","enable","disable"].includes(a)&&r.length<=2){const e=(r[1]??"").toLowerCase();return{suggestions:ee.filter(t=>t.provider.startsWith(e)).map(e=>buildWorkspaceArgSuggestion(`workspace-provider-${e.provider}`,e.provider,replaceWorkspaceArgs(`${a} ${e.provider}`),e.label)),commandArgumentHint:"<proveedor>"}}if("orchestrator"===a)return{suggestions:[],commandArgumentHint:"[equipo] [provider/agent]"};if("setup"!==a)return{suggestions:[],commandArgumentHint:void 0};if(r.length<=2)return{suggestions:[],commandArgumentHint:"<equipo> [orchestrator=<area|provider/agent>]"};const l=r.length-1,g=r[l]??"",m=r.slice(0,l);if(!m.some(e=>e.toLowerCase().startsWith("orchestrator="))&&"orchestrator=".startsWith(g.toLowerCase()))return{suggestions:[buildWorkspaceArgSuggestion("workspace-orchestrator","orchestrator=",replaceWorkspaceArgs([...m,"orchestrator="].join(" ")),"escoger coordinador principal")],commandArgumentHint:"orchestrator=<area|provider/agent>"};if(g.toLowerCase().startsWith("orchestrator=")){const e=g.slice(13).toLowerCase(),t=Y.filter(t=>t.startsWith(e)).map(e=>buildWorkspaceArgSuggestion(`workspace-orchestrator-equipo-${e}`,e,replaceWorkspaceArgs([...m,`orchestrator=${e} `].join(" ").trimEnd()),`usar el equipo ${e} como orquestador`)),n=[];for(const t of ee)for(const o of Q(t.provider)){const s=`${t.provider}/${o.agentName||`${o.name}-lead`}`;s.toLowerCase().startsWith(e)&&n.push(buildWorkspaceArgSuggestion(`workspace-orchestrator-agent-${o.id}`,s,replaceWorkspaceArgs([...m,`orchestrator=${s} `].join(" ").trimEnd()),`agente de ${t.label}`))}return{suggestions:[...t,...n],commandArgumentHint:"orchestrator=<area|provider/agent>"}}const c=g.indexOf(":");if(c>=0){const e=g.slice(0,c),t=g.slice(c+1).toLowerCase();return{suggestions:Y.filter(e=>e.startsWith(t)).map(t=>buildWorkspaceArgSuggestion(`workspace-equipo-${e}-${t}`,t,replaceWorkspaceArgs([...m,`${e}:${t} `].join(" ").trimEnd()),`equipo ${t}`)),commandArgumentHint:"<proveedor/perfil:area>"}}const u=g.toLowerCase(),d=[];for(const e of ee)for(const t of Q(e.provider)){const n=`${e.provider}/${t.name}`;n.toLowerCase().startsWith(u)&&d.push(buildWorkspaceArgSuggestion(`workspace-profile-${t.id}`,`${n}:`,replaceWorkspaceArgs([...m,`${n}:`].join(" ")),t.lastModel?`${e.label} - ${t.lastModel}`:e.label))}return{suggestions:d,commandArgumentHint:"<proveedor/perfil:area>"}}(e):null;if(a){const{suggestions:e,commandArgumentHint:t}=a;return de(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),ye(e.length>0?"command-arg":"none"),void ke(void 0)}const l="prompt"===ce?function(e){const t=extractCommandNameAndArgs(e);if(!t||!Z.has(t.commandName.toLowerCase()))return null;const n=t.args??"",o=/\s$/.test(n),s=n.trim().length>0?n.trim().split(/\s+/):[],r=o?[...s,""]:s,i=r[0]??"",a=r[1]??"",l=r[2]??"",g=i.toLowerCase(),makeProviderSuggestions=(t,n)=>ee.filter(e=>e.provider.startsWith(t.toLowerCase())).map(t=>buildProfileArgSuggestion(`profile-provider-${t.provider}`,t.provider,replaceProfileArgs(e,[...n,t.provider,""].join(" ").trimEnd()+" "),t.label)),makeProfileSuggestions=(t,n,o)=>t&&ee.some(e=>e.provider===t)?Q(t).filter(e=>e.name.toLowerCase().startsWith(n.toLowerCase())).map(t=>buildProfileArgSuggestion(`profile-name-${t.id}`,t.name,replaceProfileArgs(e,[...o,t.name,""].join(" ").trimEnd()+" "),`${t.agentName}${t.lastModel?` · ${t.lastModel}`:""}`)):[];if(r.length<=1){const t=i.toLowerCase();return{suggestions:U.filter(e=>e.startsWith(t)).map(t=>buildProfileArgSuggestion(`profile-subcommand-${t}`,t,replaceProfileArgs(e,`${t} `))),commandArgumentHint:"<subcomando>"}}if("list"===g||"current"===g||"migrate"===g||"clear"===g||"clear-all"===g)return{suggestions:[],commandArgumentHint:void 0};if(("remove"===g||"clear"===g)&&r.length<=2){const t=a.toLowerCase();return{suggestions:[buildProfileArgSuggestion("profile-remove-all","all",replaceProfileArgs(e,`${g} all`),"Eliminar todos los perfiles"),...makeProviderSuggestions(t,[g])].filter(e=>e.displayText.toLowerCase().startsWith(t)),commandArgumentHint:"<proveedor|all>"}}return["create","use","rename","remove","model","agent"].includes(g)&&r.length<=2?{suggestions:makeProviderSuggestions(a,[g]),commandArgumentHint:"<proveedor>"}:["use","remove","model","agent"].includes(g)&&r.length<=3?{suggestions:makeProfileSuggestions(a,l,[g,a]),commandArgumentHint:"<perfil>"}:"rename"===g&&r.length<=3?{suggestions:makeProfileSuggestions(a,l,[g,a]),commandArgumentHint:"<perfil-actual>"}:{suggestions:[],commandArgumentHint:void 0}}(e):null;if(l){const{suggestions:e,commandArgumentHint:t}=l;return de(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),ye(e.length>0?"command-arg":"none"),void ke(void 0)}const g="prompt"===ce?getProviderCommandSuggestions(e):null;if(g){const{suggestions:e,commandArgumentHint:t}=g;return de(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),ye(e.length>0?"command-arg":"none"),void ke(void 0)}const c="prompt"===ce?function(e){const t=extractCommandNameAndArgs(e);if(!t)return null;const n=t.commandName.toLowerCase();if("playwright"!==n&&"pw"!==n)return null;const o=t.args??"",s=/\s$/.test(o),r=o.trim().length>0?o.trim().split(/\s+/):[],i=s?[...r,""]:r,a=(i[0]??"").toLowerCase(),l=(i[1]??"").toLowerCase();if(i.length<=1)return{suggestions:te.filter(e=>e.name.startsWith(a)).map(e=>buildSlashArgSuggestion(`playwright-sub-${e.name}`,e.name,`/playwright ${e.name} `,e.description)),commandArgumentHint:"[status|browser|visible|headless|reset|help]"};if("browser"===a&&i.length<=2)return{suggestions:ne.filter(e=>e.name.startsWith(l)).map(e=>buildSlashArgSuggestion(`playwright-browser-${e.name}`,e.name,`/playwright browser ${e.name} `,e.description)),commandArgumentHint:"<chromium|chrome|firefox|webkit|msedge>"};return("executable"===a||"device"===a||"viewport"===a)&&i.length<=2&&"clear".startsWith(l)?{suggestions:[buildSlashArgSuggestion(`playwright-${a}-clear`,"clear",`/playwright ${a} clear`,`Quitar ${a} custom`)],commandArgumentHint:"<valor|clear>"}:{suggestions:[],commandArgumentHint:void 0}}(e):null;if(c){const{suggestions:e,commandArgumentHint:t}=c;return de(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),ye(e.length>0?"command-arg":"none"),void ke(void 0)}const u="prompt"===ce?function(e){const t=extractCommandNameAndArgs(e);if(!t)return null;const n=t.commandName.toLowerCase();if("whatsapp"!==n&&"wa"!==n&&"whats"!==n)return null;const o=t.args??"",s=/\s$/.test(o),r=o.trim().length>0?o.trim().split(/\s+/):[],i=s?[...r,""]:r,a=(i[0]??"").toLowerCase(),l=(i[1]??"").toLowerCase();if(i.length<=1)return{suggestions:oe.filter(e=>e.name.startsWith(a)).map(e=>buildSlashArgSuggestion(`whatsapp-sub-${e.name}`,e.name,`/whatsapp ${e.name} `,e.description)),commandArgumentHint:"[status|permitidos|start|stop|global|help]"};if("global"===a&&i.length<=2)return{suggestions:se.filter(e=>e.name.startsWith(l)).map(e=>buildSlashArgSuggestion(`whatsapp-global-${e.name}`,e.name,`/whatsapp global ${e.name} `,e.description)),commandArgumentHint:"<status|start|stop>"};return{suggestions:[],commandArgumentHint:void 0}}(e):null;if(u){const{suggestions:e,commandArgumentHint:t}=u;return de(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),ye(e.length>0?"command-arg":"none"),void ke(void 0)}const d="prompt"===ce?function(e){const t=extractCommandNameAndArgs(e);if(!t)return null;const n=t.commandName.toLowerCase();if("telegram"!==n&&"tg"!==n)return null;const o=t.args??"",s=/\s$/.test(o),r=o.trim().length>0?o.trim().split(/\s+/):[],i=s?[...r,""]:r,a=(i[0]??"").toLowerCase(),l=(i[1]??"").toLowerCase();if(i.length<=1)return{suggestions:re.filter(e=>e.name.startsWith(a)).map(e=>buildSlashArgSuggestion(`telegram-sub-${e.name}`,e.name,`/telegram ${e.name} `,e.description)),commandArgumentHint:"[status|permitidos|global|help]"};if("global"===a&&i.length<=2)return{suggestions:se.filter(e=>e.name.startsWith(l)).map(e=>buildSlashArgSuggestion(`telegram-global-${e.name}`,e.name,`/telegram global ${e.name} `,e.description)),commandArgumentHint:"<status|start|stop>"};return{suggestions:[],commandArgumentHint:void 0}}(e):null;if(d){const{suggestions:e,commandArgumentHint:t}=d;return de(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),ye(e.length>0?"command-arg":"none"),void ke(void 0)}const p="prompt"===ce?function(e){const t=extractCommandNameAndArgs(e);if(!t)return null;const n=t.commandName.toLowerCase();if("webapp"!==n&&"app"!==n&&"pwa"!==n&&"aplicacion-web"!==n)return null;const o=t.args??"",s=/\s$/.test(o),r=o.trim().length>0?o.trim().split(/\s+/):[],i=s?[...r,""]:r,a=(i[0]??"").toLowerCase(),l=(i[1]??"").toLowerCase();if(i.length<=1)return{suggestions:ie.filter(e=>e.name.startsWith(a)).map(e=>buildSlashArgSuggestion(`webapp-sub-${e.name}`,e.name,`/webapp ${e.name} `,e.description)),commandArgumentHint:"[start|stop|status|open|token|port|autostart|help]"};if("token"===a&&i.length<=2)return{suggestions:[{name:"reset",description:"Regenerar token (invalida el anterior)"}].filter(e=>e.name.startsWith(l)).map(e=>buildSlashArgSuggestion(`webapp-token-${e.name}`,e.name,`/webapp token ${e.name} `,e.description)),commandArgumentHint:"[reset]"};return{suggestions:[],commandArgumentHint:void 0}}(e):null;if(p){const{suggestions:e,commandArgumentHint:t}=p;return de(()=>({commandArgumentHint:t,suggestions:e,selectedSuggestion:e.length>0?0:-1})),ye(e.length>0?"command-arg":"none"),void ke(void 0)}if("bash"!==ce&&L(e)&&n>0&&!r){const t=e.slice(1).toLowerCase();if(!function(e,t){return!e&&t.includes(" ")&&!t.endsWith(" ")}(r,e)){const e=_.filter(e=>!e.isHidden).filter(e=>m(e).startsWith(t)||(e.aliases??[]).some(e=>e.startsWith(t))).map(e=>({id:m(e),displayText:`/${m(e)}`,description:e.description??"",metadata:e}));return de(t=>({commandArgumentHint:void 0,suggestions:e,selectedSuggestion:getPreservedSelection(t.suggestions,t.selectedSuggestion,e)})),ye(e.length>0?"command":"none"),void ke(e.length>0?Ce:void 0)}}if(s){const t=extractCompletionToken(e,n,!0);if(t){const e=t.token.startsWith("@"),n=e?t.token.substring(1):t.token;return void ze(n,e)}}ze.cancel(),Ee()},[ce,ve,_,Ee,ze,de,Ce,Fe,$e]);n(()=>{Oe.current!==ge&&(De.current!==ge&&(De.current=ge,Qe.current=null),Oe.current=null,Ke(ge))},[ge,Ke]);const Be=t(async()=>{if(Me){if("bash"===ce)return z(Me.fullCommand),F(Me.fullCommand.length),void Ne(void 0);const e=T(ge,me);if(e){const t=ge.slice(0,e.startPos),n=ge.slice(e.startPos+e.token.length),o=t+"/"+Me.fullCommand+" "+n,s=e.startPos+1+Me.fullCommand.length+1;return z(o),void F(s)}}if(pe.length>0){ze.cancel(),Fe.cancel();const e=-1===fe?0:fe,t=pe[e];if("command"===$e&&e<pe.length)t&&(P(t,!1,_,z,F,G),Ee());else if("command-arg"===$e&&e<pe.length)t&&(applyCommandArgSuggestion(t,z,F),Ee());else if("custom-title"===$e&&pe.length>0){if(t){const e=buildResumeInputFromSuggestion(t);z(e),F(e.length),Ee()}}else if("directory"===$e&&pe.length>0){const t=pe[e];if(t){let e;if(L(ge)){const n=ge.indexOf(" "),o=ge.slice(0,n+1),s=isPathMetadata(t.metadata)&&"directory"===t.metadata.type?"/":" ";e=o+t.id+s,z(e),F(e.length),isPathMetadata(t.metadata)&&"directory"===t.metadata.type?(de(e=>({...e,commandArgumentHint:void 0})),Ke(e,e.length)):Ee()}else{const n=extractCompletionToken(ge,me,!0)??extractCompletionToken(ge,me,!1);if(n){const o=isPathMetadata(t.metadata)&&"directory"===t.metadata.type,s=applyDirectorySuggestion(ge,t.id,n.startPos,n.token.length,o);e=s.newInput,z(e),F(s.cursorPos),o?(de(e=>({...e,commandArgumentHint:void 0})),Ke(e,s.cursorPos)):Ee()}else Ee()}}}else if("shell"===$e&&pe.length>0){const t=pe[e];if(t){const e=t.metadata;applyShellSuggestion(t,ge,me,z,F,e?.completionType),Ee()}}else if("agent"===$e&&pe.length>0&&pe[e]?.id?.startsWith("dm-")){const t=pe[e];t&&(applyTriggerSuggestion(t,ge,me,ae,z,F),Ee())}else if("slack-channel"===$e&&pe.length>0){const t=pe[e];t&&(applyTriggerSuggestion(t,ge,me,B,z,F),Ee())}else if("file"===$e&&pe.length>0){const t=extractCompletionToken(ge,me,!0);if(!t)return void Ee();const n=R(pe),o=t.token.startsWith("@");let s;if(s=t.isQuoted?t.token.slice(2).replace(/"$/,"").length:o?t.token.length-1:t.token.length,n.length>s){const e=formatReplacementValue({displayText:n,mode:ce,hasAtPrefix:o,needsQuotes:!1,isQuoted:t.isQuoted,isComplete:!1});D(e,ge,t.token,t.startPos,z,F),Ke(ge.replace(t.token,e),me)}else if(e<pe.length){const n=pe[e];if(n){const e=n.displayText.includes(" "),s=formatReplacementValue({displayText:n.displayText,mode:ce,hasAtPrefix:o,needsQuotes:e,isQuoted:t.isQuoted,isComplete:!0});D(s,ge,t.token,t.startPos,z,F),Ee()}}}}else if(""!==ge.trim()){let e,t;if("bash"===ce){e="shell";const n=await async function(e,t){try{return le&&le.abort(),le=new AbortController,await C(e,t,le.signal)}catch{return l("tengu_shell_completion_failed",{}),[]}}(ge,me);if(1===n.length){const e=n[0];if(e){const t=e.metadata;applyShellSuggestion(e,ge,me,z,F,t?.completionType)}t=[]}else t=n}else{e="file";const n=extractCompletionToken(ge,me,!0);if(n){const e=n.token.startsWith("@"),o=e?n.token.substring(1):n.token;t=await E(o,He,ue,e)}else t=[]}t.length>0&&(de(e=>({commandArgumentHint:void 0,suggestions:t,selectedSuggestion:getPreservedSelection(e.suggestions,e.selectedSuggestion,t)})),ye(e),ke(void 0))}},[pe,fe,ge,$e,_,ce,z,F,G,Ee,me,Ke,He,de,ue,ze,Fe,Me]),Ue=t(()=>{if(fe<0||0===pe.length)return;const e=pe[fe];if("command"===$e&&fe<pe.length)e&&(P(e,!0,_,z,F,G),ze.cancel(),Ee());else if("command-arg"===$e&&fe<pe.length){if(e){const t=e.metadata;if((t?.replacement??e.displayText).trim()===ge.trim())return ze.cancel(),Ee(),void G(ge,!0);applyCommandArgSuggestion(e,z,F),ze.cancel(),Ee()}}else if("custom-title"===$e&&fe<pe.length){if(e){const t=buildResumeInputFromSuggestion(e);z(t),F(t.length),G(t,!0),ze.cancel(),Ee()}}else if("shell"===$e&&fe<pe.length){const e=pe[fe];if(e){const t=e.metadata;applyShellSuggestion(e,ge,me,z,F,t?.completionType),ze.cancel(),Ee()}}else if("agent"===$e&&fe<pe.length&&e?.id?.startsWith("dm-"))applyTriggerSuggestion(e,ge,me,ae,z,F),ze.cancel(),Ee();else if("slack-channel"===$e&&fe<pe.length)e&&(applyTriggerSuggestion(e,ge,me,B,z,F),Fe.cancel(),Ee());else if("file"===$e&&fe<pe.length){const t=extractCompletionToken(ge,me,!0);if(t&&e){const n=t.token.startsWith("@"),o=e.displayText.includes(" "),s=formatReplacementValue({displayText:e.displayText,mode:ce,hasAtPrefix:n,needsQuotes:o,isQuoted:t.isQuoted,isComplete:!0});D(s,ge,t.token,t.startPos,z,F),ze.cancel(),Ee()}}else if("directory"===$e&&fe<pe.length&&e){if(L(ge))return ze.cancel(),void Ee();const t=extractCompletionToken(ge,me,!0)??extractCompletionToken(ge,me,!1);if(t){const n=isPathMetadata(e.metadata)&&"directory"===e.metadata.type,o=applyDirectorySuggestion(ge,e.id,t.startPos,t.token.length,n);z(o.newInput),F(o.cursorPos)}ze.cancel(),Ee()}},[pe,fe,$e,_,ge,me,ce,z,F,G,Ee,ze,Fe]),Ze=t(()=>{Be()},[Be]),Je=t(()=>{ze.cancel(),Fe.cancel(),Ee(),Oe.current=ge},[ze,Fe,Ee,ge]),Xe=t(()=>{de(e=>({...e,selectedSuggestion:e.selectedSuggestion<=0?pe.length-1:e.selectedSuggestion-1}))},[pe.length,de]),Ye=t(()=>{de(e=>({...e,selectedSuggestion:e.selectedSuggestion>=pe.length-1?0:e.selectedSuggestion+1}))},[pe.length,de]),et=o(()=>({"autocomplete:accept":Ze,"autocomplete:dismiss":Je,"autocomplete:previous":Xe,"autocomplete:next":Ye}),[Ze,Je,Xe,Ye]),tt=pe.length>0||!!Me,nt=d();function acceptSuggestionText(e){const t=c(e);if("prompt"!==t&&be){be(t);const n=u(e);z(n),F(n.length)}else z(e),F(e.length)}p("autocomplete",tt),A("Autocomplete",tt),b(et,{context:"Autocomplete",isActive:tt&&!nt});const handleKeyDown=t=>{if("right"===t.key&&!We){const e=Te.text,n=Te.shownAt;if(e&&n>0&&""===ge)return Ae(),acceptSuggestionText(e),void t.stopImmediatePropagation()}if("tab"===t.key&&!t.shift){if(pe.length>0||Me)return;const n=Te.text,o=Te.shownAt;return n&&o>0&&""===ge&&!We?(t.preventDefault(),Ae(),void acceptSuggestionText(n)):void(""===ge.trim()&&(t.preventDefault(),Se({key:"thinking-toggle-hint",jsx:e(a,{dimColor:!0,children:["Usa ",we," para alternar el modo de razonamiento"]}),priority:"immediate",timeoutMs:3e3})))}if(0===pe.length)return;const n=null!=Le?.pendingChord;return t.ctrl&&"n"===t.key&&!n?(t.preventDefault(),void Ye()):t.ctrl&&"p"===t.key&&!n?(t.preventDefault(),void Xe()):void("return"!==t.key||t.shift||t.meta||(t.preventDefault(),Ue()))};return h((e,t,n)=>{const o=new f(n.keypress);handleKeyDown(o),o.didStopImmediatePropagation()&&n.stopImmediatePropagation()}),{suggestions:pe,selectedSuggestion:fe,suggestionType:$e,maxColumnWidth:xe,commandArgumentHint:he,inlineGhostText:Me,handleKeyDown}}
|