@iaforged/context-code 2.3.5 → 2.3.6

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.
@@ -1 +1 @@
1
- import{getProviderProfile as e}from"../../../utils/model/providerProfiles.js";import{getSecureStorage as t}from"../../../utils/secureStorage/index.js";const o={claude:"https://api.anthropic.com",openai:"https://api.openai.com/v1",openrouter:"https://openrouter.ai/api/v1",ollama:"http://localhost:11434/v1","ollama-cloud":"http://localhost:11434/v1","gemini-api":"https://generativelanguage.googleapis.com/v1beta/openai","gemini-google":"https://generativelanguage.googleapis.com/v1beta/openai",zai:"https://api.z.ai/api/coding/paas/v4",minimax:"https://api.minimax.io/anthropic"};function trimTrailingSlash(e){return e.endsWith("/")?e.slice(0,-1):e}function tryParseJson(e){try{return JSON.parse(e)}catch{return null}}function resolveCredential(e,o){if("ollama"===e)return{kind:"none",token:null};const r=function(){try{return t().read()??{}}catch{return{}}}(),n=r.providerProfileApiKeys?.[o];if(n?.trim())return{kind:"api-key",token:n.trim()};const a=r.providerProfileOauth?.[o]?.accessToken;if(a?.trim())return{kind:"oauth",token:a.trim()};const i=r.providerApiKeys?.[e];if(i?.trim())return{kind:"api-key",token:i.trim()};const s="claude"===e?r.claudeAiOauth?.accessToken:"openai"===e?r.openAiOauth?.accessToken:null;return s?.trim()?{kind:"oauth",token:s.trim()}:{kind:"none",token:null}}function buildSystemPrompt(e){const t=e.domain?.domainName??e.task.scopeType,o=e.capabilities.length>0?e.capabilities.join(", "):"sin declarar";return[e.agent.systemPrompt?.trim()||`Eres ${e.agent.name}, agente del equipo ${t}.`,`Rol: ${e.agent.roleKind??"general"}.`,`Capacidades: ${o}.`,"Responde con un reporte ejecutivo y accionable para el orquestador global.","No modifiques archivos. Solo entrega resultado, riesgos y siguientes pasos."].join("\n")}function buildUserPrompt(e){const t=e.domain?.domainName??e.task.scopeType,o=e.members.length>0?e.members.map(e=>`${e.agentId}:${e.duty??"member"}`).join(", "):"sin miembros internos";return[`Objetivo global: ${e.run.goal}`,`Equipo: ${t}`,`Tarea: ${e.task.title}`,`Instrucciones: ${e.task.instructions}`,`Miembros del escuadron: ${o}`,"","Entrega:","1. Resultado del equipo.","2. Decisiones tomadas.","3. Riesgos o bloqueos.","4. Siguientes pasos recomendados."].join("\n")}async function postJson(e,t,o,r=3){let n=null;for(let a=0;a<=r;a++){if(a>0){const e=1e3*Math.pow(2,a)+1e3*Math.random();await new Promise(t=>setTimeout(t,e))}try{const r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...t},body:JSON.stringify(o)}),a=await r.text(),i=tryParseJson(a)??a;if(!r.ok){if(n={status:r.status,error:"string"==typeof i?i:JSON.stringify(i)},429===r.status||r.status>=500)continue;return{ok:!1,...n}}return{ok:!0,data:i}}catch(e){n={status:0,error:e instanceof Error?e.message:String(e)};continue}}return{ok:!1,...n}}async function executeOpenAICompatible(e,t,o,r){const n={};r.token&&(n.Authorization=`Bearer ${r.token}`),"openrouter"===e.workspace.provider&&(n["HTTP-Referer"]="https://context.iaforged.com",n["X-Title"]="Context Code");const a=await postJson(`${trimTrailingSlash(o)}/chat/completions`,n,{model:t,temperature:.2,messages:[{role:"system",content:buildSystemPrompt(e)},{role:"user",content:buildUserPrompt(e)}]});if(!a.ok)return{ok:!1,error:`HTTP ${a.status}: ${a.error}`};const i=function(e){if(!e||"object"!=typeof e)return null;const t=e,o=t.choices?.[0]?.message?.content??t.choices?.[0]?.text;return"string"==typeof o?o:Array.isArray(o)?o.map(e=>"string"==typeof e?e:"object"==typeof e&&e&&"text"in e?String(e.text??""):"").filter(Boolean).join("\n"):"string"==typeof t.output_text?t.output_text:null}(a.data);return i?.trim()?{ok:!0,output:i}:{ok:!1,error:"El proveedor no devolvio contenido de texto."}}async function executeAnthropicCompatible(e,t,o,r){const n={"anthropic-version":"2023-06-01"};"api-key"===r.kind&&r.token?(n["x-api-key"]=r.token,"minimax"===e.workspace.provider&&(n.Authorization=`Bearer ${r.token}`)):"oauth"===r.kind&&r.token&&(n.Authorization=`Bearer ${r.token}`);const a=await postJson(`${trimTrailingSlash(o)}/v1/messages`,n,{model:t,max_tokens:2048,system:buildSystemPrompt(e),messages:[{role:"user",content:buildUserPrompt(e)}]});if(!a.ok)return{ok:!1,error:`HTTP ${a.status}: ${a.error}`};const i=function(e){if(!e||"object"!=typeof e)return null;const t=e;return t.content?.map(e=>"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n")||null}(a.data);return i?.trim()?{ok:!0,output:i}:{ok:!1,error:"El proveedor no devolvio contenido de texto."}}export async function executeAgentDomainTask(t){const r=e(t.agent.profileId),n=t.workspace.provider,a=function(t){const o=e(t.agent.profileId);return t.agent.modelOverride?.trim()||o?.lastModel?.trim()||null}(t);if(!r)return{status:"blocked",summary:`No existe el perfil ${t.agent.profileId} para el agente ${t.agent.name}.`,output:null,provider:n,profileId:t.agent.profileId,model:a,messageType:"task.blocked",blockers:["Perfil del agente no encontrado."],metadata:{reason:"missing-profile"}};if(r.provider!==n)return{status:"blocked",summary:`El perfil ${r.id} pertenece a ${r.provider}, pero el workspace es ${n}.`,output:null,provider:n,profileId:r.id,model:a,messageType:"task.blocked",blockers:["Perfil y workspace no coinciden."],metadata:{reason:"provider-profile-mismatch",profileProvider:r.provider}};if(!a)return{status:"blocked",summary:`El agente ${t.agent.name} no tiene modelo configurado.`,output:null,provider:n,profileId:r.id,model:a,messageType:"task.blocked",blockers:["Modelo no configurado."],metadata:{reason:"missing-model"}};const i=resolveCredential(n,r.id);if("ollama"!==n&&"none"===i.kind)return{status:"blocked",summary:`El perfil ${r.id} no tiene credenciales para ${n}.`,output:null,provider:n,profileId:r.id,model:a,messageType:"task.blocked",blockers:["Credenciales no configuradas."],metadata:{reason:"missing-credentials"}};const s=r.baseUrl||o[n];try{const e="claude"===n||"minimax"===n?await executeAnthropicCompatible(t,a,s,i):await executeOpenAICompatible(t,a,s,i);if(!e.ok)return{status:"failed",summary:`El agente ${t.agent.name} fallo ejecutando ${a}: ${e.error}`,output:null,provider:n,profileId:r.id,model:a,messageType:"task.failed",blockers:[e.error],metadata:{reason:"provider-error",baseUrl:s}};const o=function(e,t=12e3){return e.length>t?`${e.slice(0,t)}\n\n[output truncado a ${t} caracteres]`:e}(e.output.trim());return{status:"completed",summary:o.split("\n").find(e=>e.trim())?.trim()||o,output:o,provider:n,profileId:r.id,model:a,messageType:"task.completed",blockers:[],metadata:{baseUrl:s,credentialKind:i.kind}}}catch(e){const o=function(e){return e instanceof Error?e.message:String(e)}(e);return{status:"failed",summary:`El agente ${t.agent.name} no pudo ejecutar la tarea: ${o}`,output:null,provider:n,profileId:r.id,model:a,messageType:"task.failed",blockers:[o],metadata:{reason:"execution-exception",baseUrl:s}}}}
1
+ import{getProviderProfile as e}from"../../../utils/model/providerProfiles.js";import{getSecureStorage as t}from"../../../utils/secureStorage/index.js";const o={claude:"https://api.anthropic.com",openai:"https://api.openai.com/v1",openrouter:"https://openrouter.ai/api/v1",ollama:"http://localhost:11434/v1","ollama-cloud":"http://localhost:11434/v1",lmstudio:"http://localhost:1234/v1","gemini-api":"https://generativelanguage.googleapis.com/v1beta/openai","gemini-google":"https://generativelanguage.googleapis.com/v1beta/openai",zai:"https://api.z.ai/api/coding/paas/v4",minimax:"https://api.minimax.io/anthropic"};function trimTrailingSlash(e){return e.endsWith("/")?e.slice(0,-1):e}function tryParseJson(e){try{return JSON.parse(e)}catch{return null}}function resolveCredential(e,o){if("ollama"===e)return{kind:"none",token:null};const r=function(){try{return t().read()??{}}catch{return{}}}(),n=r.providerProfileApiKeys?.[o];if(n?.trim())return{kind:"api-key",token:n.trim()};const a=r.providerProfileOauth?.[o]?.accessToken;if(a?.trim())return{kind:"oauth",token:a.trim()};const i=r.providerApiKeys?.[e];if(i?.trim())return{kind:"api-key",token:i.trim()};const s="claude"===e?r.claudeAiOauth?.accessToken:"openai"===e?r.openAiOauth?.accessToken:null;return s?.trim()?{kind:"oauth",token:s.trim()}:{kind:"none",token:null}}function buildSystemPrompt(e){const t=e.domain?.domainName??e.task.scopeType,o=e.capabilities.length>0?e.capabilities.join(", "):"sin declarar";return[e.agent.systemPrompt?.trim()||`Eres ${e.agent.name}, agente del equipo ${t}.`,`Rol: ${e.agent.roleKind??"general"}.`,`Capacidades: ${o}.`,"Responde con un reporte ejecutivo y accionable para el orquestador global.","No modifiques archivos. Solo entrega resultado, riesgos y siguientes pasos."].join("\n")}function buildUserPrompt(e){const t=e.domain?.domainName??e.task.scopeType,o=e.members.length>0?e.members.map(e=>`${e.agentId}:${e.duty??"member"}`).join(", "):"sin miembros internos";return[`Objetivo global: ${e.run.goal}`,`Equipo: ${t}`,`Tarea: ${e.task.title}`,`Instrucciones: ${e.task.instructions}`,`Miembros del escuadron: ${o}`,"","Entrega:","1. Resultado del equipo.","2. Decisiones tomadas.","3. Riesgos o bloqueos.","4. Siguientes pasos recomendados."].join("\n")}async function postJson(e,t,o,r=3){let n=null;for(let a=0;a<=r;a++){if(a>0){const e=1e3*Math.pow(2,a)+1e3*Math.random();await new Promise(t=>setTimeout(t,e))}try{const r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...t},body:JSON.stringify(o)}),a=await r.text(),i=tryParseJson(a)??a;if(!r.ok){if(n={status:r.status,error:"string"==typeof i?i:JSON.stringify(i)},429===r.status||r.status>=500)continue;return{ok:!1,...n}}return{ok:!0,data:i}}catch(e){n={status:0,error:e instanceof Error?e.message:String(e)};continue}}return{ok:!1,...n}}async function executeOpenAICompatible(e,t,o,r){const n={};r.token&&(n.Authorization=`Bearer ${r.token}`),"openrouter"===e.workspace.provider&&(n["HTTP-Referer"]="https://context.iaforged.com",n["X-Title"]="Context Code");const a=await postJson(`${trimTrailingSlash(o)}/chat/completions`,n,{model:t,temperature:.2,messages:[{role:"system",content:buildSystemPrompt(e)},{role:"user",content:buildUserPrompt(e)}]});if(!a.ok)return{ok:!1,error:`HTTP ${a.status}: ${a.error}`};const i=function(e){if(!e||"object"!=typeof e)return null;const t=e,o=t.choices?.[0]?.message?.content??t.choices?.[0]?.text;return"string"==typeof o?o:Array.isArray(o)?o.map(e=>"string"==typeof e?e:"object"==typeof e&&e&&"text"in e?String(e.text??""):"").filter(Boolean).join("\n"):"string"==typeof t.output_text?t.output_text:null}(a.data);return i?.trim()?{ok:!0,output:i}:{ok:!1,error:"El proveedor no devolvio contenido de texto."}}async function executeAnthropicCompatible(e,t,o,r){const n={"anthropic-version":"2023-06-01"};"api-key"===r.kind&&r.token?(n["x-api-key"]=r.token,"minimax"===e.workspace.provider&&(n.Authorization=`Bearer ${r.token}`)):"oauth"===r.kind&&r.token&&(n.Authorization=`Bearer ${r.token}`);const a=await postJson(`${trimTrailingSlash(o)}/v1/messages`,n,{model:t,max_tokens:2048,system:buildSystemPrompt(e),messages:[{role:"user",content:buildUserPrompt(e)}]});if(!a.ok)return{ok:!1,error:`HTTP ${a.status}: ${a.error}`};const i=function(e){if(!e||"object"!=typeof e)return null;const t=e;return t.content?.map(e=>"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n")||null}(a.data);return i?.trim()?{ok:!0,output:i}:{ok:!1,error:"El proveedor no devolvio contenido de texto."}}export async function executeAgentDomainTask(t){const r=e(t.agent.profileId),n=t.workspace.provider,a=function(t){const o=e(t.agent.profileId);return t.agent.modelOverride?.trim()||o?.lastModel?.trim()||null}(t);if(!r)return{status:"blocked",summary:`No existe el perfil ${t.agent.profileId} para el agente ${t.agent.name}.`,output:null,provider:n,profileId:t.agent.profileId,model:a,messageType:"task.blocked",blockers:["Perfil del agente no encontrado."],metadata:{reason:"missing-profile"}};if(r.provider!==n)return{status:"blocked",summary:`El perfil ${r.id} pertenece a ${r.provider}, pero el workspace es ${n}.`,output:null,provider:n,profileId:r.id,model:a,messageType:"task.blocked",blockers:["Perfil y workspace no coinciden."],metadata:{reason:"provider-profile-mismatch",profileProvider:r.provider}};if(!a)return{status:"blocked",summary:`El agente ${t.agent.name} no tiene modelo configurado.`,output:null,provider:n,profileId:r.id,model:a,messageType:"task.blocked",blockers:["Modelo no configurado."],metadata:{reason:"missing-model"}};const i=resolveCredential(n,r.id);if("ollama"!==n&&"none"===i.kind)return{status:"blocked",summary:`El perfil ${r.id} no tiene credenciales para ${n}.`,output:null,provider:n,profileId:r.id,model:a,messageType:"task.blocked",blockers:["Credenciales no configuradas."],metadata:{reason:"missing-credentials"}};const s=r.baseUrl||o[n];try{const e="claude"===n||"minimax"===n?await executeAnthropicCompatible(t,a,s,i):await executeOpenAICompatible(t,a,s,i);if(!e.ok)return{status:"failed",summary:`El agente ${t.agent.name} fallo ejecutando ${a}: ${e.error}`,output:null,provider:n,profileId:r.id,model:a,messageType:"task.failed",blockers:[e.error],metadata:{reason:"provider-error",baseUrl:s}};const o=function(e,t=12e3){return e.length>t?`${e.slice(0,t)}\n\n[output truncado a ${t} caracteres]`:e}(e.output.trim());return{status:"completed",summary:o.split("\n").find(e=>e.trim())?.trim()||o,output:o,provider:n,profileId:r.id,model:a,messageType:"task.completed",blockers:[],metadata:{baseUrl:s,credentialKind:i.kind}}}catch(e){const o=function(e){return e instanceof Error?e.message:String(e)}(e);return{status:"failed",summary:`El agente ${t.agent.name} no pudo ejecutar la tarea: ${o}`,output:null,provider:n,profileId:r.id,model:a,messageType:"task.failed",blockers:[o],metadata:{reason:"execution-exception",baseUrl:s}}}}
@@ -1 +1 @@
1
- import{clearProviderProfileBaseUrl as t,getProviderProfileBaseUrl as i,isProfiledProvider as e,setProviderProfileBaseUrl as a}from"./providerProfiles.js";import{clearStoredProviderBaseUrl as r,getStoredProviderBaseUrl as o,setStoredProviderBaseUrl as n}from"./providerProfilesDb.js";const p={openrouter:"https://openrouter.ai/api/v1",ollama:"http://localhost:11434/v1","ollama-cloud":"http://localhost:11434/v1","gemini-api":"https://generativelanguage.googleapis.com/v1beta/openai","gemini-google":"https://generativelanguage.googleapis.com/v1beta/openai",zai:"https://api.z.ai/api/coding/paas/v4",minimax:"https://api.minimax.io/anthropic",nvidia:"https://integrate.api.nvidia.com/v1",deepseek:"https://api.deepseek.com/v1",xai:"https://api.x.ai/v1",gmi:"https://api.gmi-serving.com/v1",novita:"https://api.novita.ai/openai/v1",stepfun:"https://api.stepfun.ai/step_plan/v1",huggingface:"https://router.huggingface.co/v1","opencode-zen":"https://opencode.ai/zen/v1",arcee:"https://api.arcee.ai/api/v1",alibaba:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",kimi:"https://api.moonshot.ai/v1","custom-openai":"https://api.openai.com/v1","custom-anthropic":"https://api.anthropic.com/v1"};function trimTrailingSlash(t){return t.endsWith("/")?t.slice(0,-1):t}export function getDefaultProviderBaseUrl(t){return p[t]}export function getConfiguredProviderBaseUrl(t){const e=i(t)?.trim();if(e)try{return normalizeProviderBaseUrl(t,e)}catch{return e}const a=o(t)?.trim();if(a)try{return normalizeProviderBaseUrl(t,a)}catch{return a}return getDefaultProviderBaseUrl(t)}export function isProviderBaseUrlCustomized(t){return Boolean(i(t)?.trim()||o(t)?.trim())}export function normalizeProviderBaseUrl(t,i){const e=function(t,i){const e=i.trim();if(!e)throw new Error("La base URL no puede estar vacia.");try{return new URL(e)}catch{return new URL(`${"ollama"===t||"ollama-cloud"===t?"http://":"https://"}${e}`)}}(t,i),a=`${e.protocol}//${e.host}${e.pathname}${e.search}${e.hash}`;return"zai"===t||"minimax"===t||"gemini-api"===t||"gemini-google"===t||"nvidia"===t?trimTrailingSlash(a):function(t){const i=trimTrailingSlash(t);return i.endsWith("/v1")?i:`${i}/v1`}(a)}export function setProviderBaseUrl(t,i){const r=normalizeProviderBaseUrl(t,i);return e(t)&&a(t,r),n(t,r),r}export function clearProviderBaseUrl(i){e(i)&&t(i),r(i)}
1
+ import{clearProviderProfileBaseUrl as t,getProviderProfileBaseUrl as i,isProfiledProvider as e,setProviderProfileBaseUrl as a}from"./providerProfiles.js";import{clearStoredProviderBaseUrl as o,getStoredProviderBaseUrl as r,setStoredProviderBaseUrl as n}from"./providerProfilesDb.js";const p={openrouter:"https://openrouter.ai/api/v1",ollama:"http://localhost:11434/v1","ollama-cloud":"http://localhost:11434/v1",lmstudio:"http://localhost:1234/v1","gemini-api":"https://generativelanguage.googleapis.com/v1beta/openai","gemini-google":"https://generativelanguage.googleapis.com/v1beta/openai",zai:"https://api.z.ai/api/coding/paas/v4",minimax:"https://api.minimax.io/anthropic",nvidia:"https://integrate.api.nvidia.com/v1",deepseek:"https://api.deepseek.com/v1",xai:"https://api.x.ai/v1",gmi:"https://api.gmi-serving.com/v1",novita:"https://api.novita.ai/openai/v1",stepfun:"https://api.stepfun.ai/step_plan/v1",huggingface:"https://router.huggingface.co/v1","opencode-zen":"https://opencode.ai/zen/v1",arcee:"https://api.arcee.ai/api/v1",alibaba:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",kimi:"https://api.moonshot.ai/v1","custom-openai":"https://api.openai.com/v1","custom-anthropic":"https://api.anthropic.com/v1"};function trimTrailingSlash(t){return t.endsWith("/")?t.slice(0,-1):t}export function getDefaultProviderBaseUrl(t){return p[t]}export function getConfiguredProviderBaseUrl(t){const e=i(t)?.trim();if(e)try{return normalizeProviderBaseUrl(t,e)}catch{return e}const a=r(t)?.trim();if(a)try{return normalizeProviderBaseUrl(t,a)}catch{return a}return getDefaultProviderBaseUrl(t)}export function isProviderBaseUrlCustomized(t){return Boolean(i(t)?.trim()||r(t)?.trim())}export function normalizeProviderBaseUrl(t,i){const e=function(t,i){const e=i.trim();if(!e)throw new Error("La base URL no puede estar vacia.");try{return new URL(e)}catch{return new URL(`${"ollama"===t||"ollama-cloud"===t||"lmstudio"===t?"http://":"https://"}${e}`)}}(t,i),a=`${e.protocol}//${e.host}${e.pathname}${e.search}${e.hash}`;return"zai"===t||"minimax"===t||"gemini-api"===t||"gemini-google"===t||"nvidia"===t?trimTrailingSlash(a):function(t){const i=trimTrailingSlash(t);return i.endsWith("/v1")?i:`${i}/v1`}(a)}export function setProviderBaseUrl(t,i){const o=normalizeProviderBaseUrl(t,i);return e(t)&&a(t,o),n(t,o),o}export function clearProviderBaseUrl(i){e(i)&&t(i),o(i)}
@@ -1 +1 @@
1
- export const VISIBLE_PROVIDERS=[{id:"minimax",label:"MiniMax",description:"API key propia. Usa el endpoint Anthropic-compatible y luego elige un modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de MiniMax.",nextStep:"Despues, elige un modelo MiniMax compatible con Anthropic desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"openrouter",label:"OpenRouter",description:"API key propia. Luego elige un modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de OpenRouter.",nextStep:"Despues, elige un modelo compatible desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"ollama",label:"Ollama",description:"Servidor Ollama compatible. Incluye modelos locales y modelos cloud si hiciste ollama signin.",setup:{kind:"local-server",intro:"Esto solo configura el servidor Ollama; no abre un login OAuth.",nextStep:"Asegurate de tener ollama serve activo. Si usas cloud, ejecuta ollama signin fuera del CLI.",actionLabel:"Continuar con Ollama"},implemented:!0},{id:"ollama-cloud",label:"Ollama Cloud",description:"Modelos cloud desde tu servidor Ollama autenticado con ollama signin.",setup:{kind:"local-server",intro:"Esto usa tu servidor Ollama ya autenticado; no abre un login OAuth.",nextStep:"Ejecuta ollama signin fuera del CLI, usa http://localhost:11434/v1 y despues elige un modelo cloud desde /model.",actionLabel:"Continuar con Ollama Cloud"},implemented:!0},{id:"openai",label:"OpenAI / Codex",description:"OAuth de OpenAI",setup:{kind:"oauth",intro:"Inicia sesion con tu cuenta de OpenAI / Codex.",nextStep:"Despues de iniciar sesion, elige un modelo desde /model.",actionLabel:"Continuar con OpenAI"},implemented:!0},{id:"gemini-google",label:"Gemini Google OAuth",description:"Cuenta Google mediante OAuth compatible con Gemini CLI.",setup:{kind:"oauth",intro:"Inicia sesion con tu cuenta de Google usando el flujo OAuth de Gemini CLI.",nextStep:"Usa /login y elige Gemini Google para abrir el navegador y guardar el token OAuth.",actionLabel:"Continuar con Google"},implemented:!0},{id:"gemini-api",label:"Gemini API",description:"API key de Google AI Studio, usando endpoint OpenAI-compatible.",setup:{kind:"api-key",intro:"Pega tu API key de Gemini / Google AI Studio.",nextStep:"Despues, elige un modelo Gemini desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"zai",label:"Z.AI",description:"API key propia. Luego elige un modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de Z.AI.",nextStep:"Despues, elige un modelo compatible desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"nvidia",label:"NVIDIA API",description:"API key propia de NVIDIA NIM / build.nvidia.com. Luego elige un modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de NVIDIA.",nextStep:"Despues, elige un modelo compatible desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"deepseek",label:"DeepSeek",description:"API key propia de api.deepseek.com (OpenAI-compatible). Luego elige un modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de DeepSeek (sk-...).",nextStep:"Despues, elige un modelo como deepseek-chat o deepseek-reasoner desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"xai",label:"xAI / Grok",description:"API key propia de api.x.ai (OpenAI-compatible). Luego elige un modelo Grok en /model.",setup:{kind:"api-key",intro:"Pega tu API key de xAI (xai-...).",nextStep:"Despues, elige un modelo como grok-4 o grok-code-fast-1 desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"gmi",label:"GMI Cloud",description:"API key de api.gmi-serving.com (OpenAI-compatible, multi-modelo). Luego elige modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de GMI Cloud.",nextStep:"Despues, elige un modelo desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"novita",label:"NovitaAI",description:"API key de novita.ai (OpenAI-compatible, multi-modelo). Luego elige modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de NovitaAI.",nextStep:"Despues, elige un modelo desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"stepfun",label:"StepFun",description:"API key de stepfun.ai (OpenAI-compatible). Luego elige un modelo Step en /model.",setup:{kind:"api-key",intro:"Pega tu API key de StepFun.",nextStep:"Despues, elige un modelo como step-3 desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"huggingface",label:"HuggingFace",description:"Token HF en router.huggingface.co (OpenAI-compatible). Luego elige modelo en /model.",setup:{kind:"api-key",intro:"Pega tu token de HuggingFace (HF_TOKEN, hf_...).",nextStep:"Despues, elige un modelo desde /model.",actionLabel:"Pegar token"},implemented:!0},{id:"opencode-zen",label:"OpenCode Zen",description:"API key de opencode.ai/zen (OpenAI-compatible). Luego elige un modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de OpenCode Zen.",nextStep:"Despues, elige un modelo desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"arcee",label:"Arcee AI",description:"API key de api.arcee.ai (OpenAI-compatible). Luego elige un modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de Arcee AI.",nextStep:"Despues, elige un modelo (p.ej. auto) desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"alibaba",label:"Alibaba (Qwen)",description:"API key de DashScope (compatible-mode OpenAI). Luego elige un modelo Qwen en /model.",setup:{kind:"api-key",intro:"Pega tu API key de DashScope / Alibaba Cloud (DASHSCOPE_API_KEY).",nextStep:"Despues, elige un modelo como qwen3-max desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"kimi",label:"Kimi (Moonshot)",description:"API key de api.moonshot.ai (OpenAI-compatible). Luego elige un modelo Kimi en /model.",setup:{kind:"api-key",intro:"Pega tu API key de Kimi / Moonshot (KIMI_API_KEY).",nextStep:"Despues, elige un modelo como kimi-k2-0905-preview desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"claude",label:"Claude (Anthropic)",description:"Suscripcion Claude o Anthropic Console",setup:{kind:"oauth",intro:"Inicia sesion con tu cuenta de Claude o Anthropic Console.",nextStep:"Despues de iniciar sesion, elige un modelo desde /model.",actionLabel:"Continuar con Claude"},implemented:!0},{id:"custom-openai",label:"Custom OpenAI",description:"API key y endpoint personalizado para OpenAI-compatible. Ideal para proxies o servidores propios.",setup:{kind:"api-key",intro:"Wizard paso a paso: API key, endpoint (opcional), modelo (opcional).",nextStep:"Al finalizar, elige un modelo desde /model.",actionLabel:"Configurar Custom OpenAI"},implemented:!0},{id:"custom-anthropic",label:"Custom Anthropic",description:"API key y endpoint personalizado para Anthropic-compatible. Ideal para instalaciones on-premise.",setup:{kind:"api-key",intro:"Wizard paso a paso: API key, endpoint (opcional), modelo (opcional).",nextStep:"Al finalizar, elige un modelo desde /model.",actionLabel:"Configurar Custom Anthropic"},implemented:!0}];export function getVisibleProvider(e){const o=VISIBLE_PROVIDERS.find(o=>o.id===e);if(!o)throw new Error(`Unknown provider: ${e}`);return o}
1
+ export const VISIBLE_PROVIDERS=[{id:"minimax",label:"MiniMax",description:"API key propia. Usa el endpoint Anthropic-compatible y luego elige un modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de MiniMax.",nextStep:"Despues, elige un modelo MiniMax compatible con Anthropic desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"openrouter",label:"OpenRouter",description:"API key propia. Luego elige un modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de OpenRouter.",nextStep:"Despues, elige un modelo compatible desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"ollama",label:"Ollama",description:"Servidor Ollama compatible. Incluye modelos locales y modelos cloud si hiciste ollama signin.",setup:{kind:"local-server",intro:"Esto solo configura el servidor Ollama; no abre un login OAuth.",nextStep:"Asegurate de tener ollama serve activo. Si usas cloud, ejecuta ollama signin fuera del CLI.",actionLabel:"Continuar con Ollama"},implemented:!0},{id:"ollama-cloud",label:"Ollama Cloud",description:"Modelos cloud desde tu servidor Ollama autenticado con ollama signin.",setup:{kind:"local-server",intro:"Esto usa tu servidor Ollama ya autenticado; no abre un login OAuth.",nextStep:"Ejecuta ollama signin fuera del CLI, usa http://localhost:11434/v1 y despues elige un modelo cloud desde /model.",actionLabel:"Continuar con Ollama Cloud"},implemented:!0},{id:"lmstudio",label:"LM Studio",description:"Servidor local OpenAI-compatible de LM Studio. No requiere API key.",setup:{kind:"local-server",intro:"Esto solo apunta al servidor local de LM Studio; no abre un login OAuth.",nextStep:"Abre LM Studio, ve a la pestaña Developer y pulsa Start Server (puerto 1234 por defecto). Carga un modelo en la pestana Chat y elige su identificador exacto desde /model.",actionLabel:"Continuar con LM Studio"},implemented:!0},{id:"openai",label:"OpenAI / Codex",description:"OAuth de OpenAI",setup:{kind:"oauth",intro:"Inicia sesion con tu cuenta de OpenAI / Codex.",nextStep:"Despues de iniciar sesion, elige un modelo desde /model.",actionLabel:"Continuar con OpenAI"},implemented:!0},{id:"gemini-google",label:"Gemini Google OAuth",description:"Cuenta Google mediante OAuth compatible con Gemini CLI.",setup:{kind:"oauth",intro:"Inicia sesion con tu cuenta de Google usando el flujo OAuth de Gemini CLI.",nextStep:"Usa /login y elige Gemini Google para abrir el navegador y guardar el token OAuth.",actionLabel:"Continuar con Google"},implemented:!0},{id:"gemini-api",label:"Gemini API",description:"API key de Google AI Studio, usando endpoint OpenAI-compatible.",setup:{kind:"api-key",intro:"Pega tu API key de Gemini / Google AI Studio.",nextStep:"Despues, elige un modelo Gemini desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"zai",label:"Z.AI",description:"API key propia. Luego elige un modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de Z.AI.",nextStep:"Despues, elige un modelo compatible desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"nvidia",label:"NVIDIA API",description:"API key propia de NVIDIA NIM / build.nvidia.com. Luego elige un modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de NVIDIA.",nextStep:"Despues, elige un modelo compatible desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"deepseek",label:"DeepSeek",description:"API key propia de api.deepseek.com (OpenAI-compatible). Luego elige un modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de DeepSeek (sk-...).",nextStep:"Despues, elige un modelo como deepseek-chat o deepseek-reasoner desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"xai",label:"xAI / Grok",description:"API key propia de api.x.ai (OpenAI-compatible). Luego elige un modelo Grok en /model.",setup:{kind:"api-key",intro:"Pega tu API key de xAI (xai-...).",nextStep:"Despues, elige un modelo como grok-4 o grok-code-fast-1 desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"gmi",label:"GMI Cloud",description:"API key de api.gmi-serving.com (OpenAI-compatible, multi-modelo). Luego elige modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de GMI Cloud.",nextStep:"Despues, elige un modelo desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"novita",label:"NovitaAI",description:"API key de novita.ai (OpenAI-compatible, multi-modelo). Luego elige modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de NovitaAI.",nextStep:"Despues, elige un modelo desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"stepfun",label:"StepFun",description:"API key de stepfun.ai (OpenAI-compatible). Luego elige un modelo Step en /model.",setup:{kind:"api-key",intro:"Pega tu API key de StepFun.",nextStep:"Despues, elige un modelo como step-3 desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"huggingface",label:"HuggingFace",description:"Token HF en router.huggingface.co (OpenAI-compatible). Luego elige modelo en /model.",setup:{kind:"api-key",intro:"Pega tu token de HuggingFace (HF_TOKEN, hf_...).",nextStep:"Despues, elige un modelo desde /model.",actionLabel:"Pegar token"},implemented:!0},{id:"opencode-zen",label:"OpenCode Zen",description:"API key de opencode.ai/zen (OpenAI-compatible). Luego elige un modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de OpenCode Zen.",nextStep:"Despues, elige un modelo desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"arcee",label:"Arcee AI",description:"API key de api.arcee.ai (OpenAI-compatible). Luego elige un modelo en /model.",setup:{kind:"api-key",intro:"Pega tu API key de Arcee AI.",nextStep:"Despues, elige un modelo (p.ej. auto) desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"alibaba",label:"Alibaba (Qwen)",description:"API key de DashScope (compatible-mode OpenAI). Luego elige un modelo Qwen en /model.",setup:{kind:"api-key",intro:"Pega tu API key de DashScope / Alibaba Cloud (DASHSCOPE_API_KEY).",nextStep:"Despues, elige un modelo como qwen3-max desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"kimi",label:"Kimi (Moonshot)",description:"API key de api.moonshot.ai (OpenAI-compatible). Luego elige un modelo Kimi en /model.",setup:{kind:"api-key",intro:"Pega tu API key de Kimi / Moonshot (KIMI_API_KEY).",nextStep:"Despues, elige un modelo como kimi-k2-0905-preview desde /model.",actionLabel:"Pegar API key"},implemented:!0},{id:"claude",label:"Claude (Anthropic)",description:"Suscripcion Claude o Anthropic Console",setup:{kind:"oauth",intro:"Inicia sesion con tu cuenta de Claude o Anthropic Console.",nextStep:"Despues de iniciar sesion, elige un modelo desde /model.",actionLabel:"Continuar con Claude"},implemented:!0},{id:"custom-openai",label:"Custom OpenAI",description:"API key y endpoint personalizado para OpenAI-compatible. Ideal para proxies o servidores propios.",setup:{kind:"api-key",intro:"Wizard paso a paso: API key, endpoint (opcional), modelo (opcional).",nextStep:"Al finalizar, elige un modelo desde /model.",actionLabel:"Configurar Custom OpenAI"},implemented:!0},{id:"custom-anthropic",label:"Custom Anthropic",description:"API key y endpoint personalizado para Anthropic-compatible. Ideal para instalaciones on-premise.",setup:{kind:"api-key",intro:"Wizard paso a paso: API key, endpoint (opcional), modelo (opcional).",nextStep:"Al finalizar, elige un modelo desde /model.",actionLabel:"Configurar Custom Anthropic"},implemented:!0}];export function getVisibleProvider(e){const o=VISIBLE_PROVIDERS.find(o=>o.id===e);if(!o)throw new Error(`Unknown provider: ${e}`);return o}
@@ -1 +1 @@
1
- import{getStoredLastModelForProvider as e,getStoredProviderBaseUrl as i,readProviderProfilesState as r,writeProviderProfilesState as o}from"./providerProfilesDb.js";const t=new Set(["claude","openai","openrouter","ollama","ollama-cloud","gemini-api","gemini-google","zai","minimax","nvidia","deepseek","xai","gmi","novita","stepfun","huggingface","opencode-zen","arcee","alibaba","kimi","custom-openai","custom-anthropic"]),n={claude:"main",openai:"main",openrouter:"main",ollama:"local","ollama-cloud":"main","gemini-api":"main","gemini-google":"main",zai:"main",minimax:"main",nvidia:"main",deepseek:"main",xai:"main",gmi:"main",novita:"main",stepfun:"main",huggingface:"main","opencode-zen":"main",arcee:"main",alibaba:"main",kimi:"main","custom-openai":"main","custom-anthropic":"main"},a={claude:"claude",openai:"openai",openrouter:"openrouter",ollama:"ollama-local","ollama-cloud":"ollama-cloud","gemini-api":"gemini-api","gemini-google":"gemini-google",zai:"z-ai",minimax:"minimax",nvidia:"nvidia",deepseek:"deepseek",xai:"xai",gmi:"gmi",novita:"novita",stepfun:"stepfun",huggingface:"huggingface","opencode-zen":"opencode-zen",arcee:"arcee",alibaba:"alibaba",kimi:"kimi","custom-openai":"custom-openai","custom-anthropic":"custom-anthropic"},l={openrouter:"https://openrouter.ai/api/v1",ollama:"http://localhost:11434/v1","ollama-cloud":"http://localhost:11434/v1","gemini-api":"https://generativelanguage.googleapis.com/v1beta/openai","gemini-google":"https://generativelanguage.googleapis.com/v1beta/openai",zai:"https://api.z.ai/api/coding/paas/v4",minimax:"https://api.minimax.io/anthropic",deepseek:"https://api.deepseek.com/v1",xai:"https://api.x.ai/v1",gmi:"https://api.gmi-serving.com/v1",novita:"https://api.novita.ai/openai/v1",stepfun:"https://api.stepfun.ai/step_plan/v1",huggingface:"https://router.huggingface.co/v1","opencode-zen":"https://opencode.ai/zen/v1",arcee:"https://api.arcee.ai/api/v1",alibaba:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",kimi:"https://api.moonshot.ai/v1"};function sanitizeProfileSegment(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"default"}function buildProfileId(e,i){return`${e}/${sanitizeProfileSegment(i)}`}function buildDefaultAgentName(e,i){const r=a[e],o=sanitizeProfileSegment(i);return o===sanitizeProfileSegment(n[e])?r:`${r}-${o}`}export function getDefaultProfileName(e){return n[e]}export function buildProviderProfileId(e,i){return buildProfileId(e,i)}export function isDefaultProfileId(e,i){return!!i&&i===buildProfileId(e,n[e])}function getState(){const e=r();return{version:1,profiles:e.profiles??{},lastProfileIdByProvider:e.lastProfileIdByProvider??{},activeProfileId:e.activeProfileId}}function saveState(e){const i=e(getState());return o(i),i}function getProfilesMap(){return getState().profiles??{}}function getProfileSeed(r,o){return o?function(r){return{baseUrl:"openrouter"===r||"ollama"===r||"ollama-cloud"===r||"zai"===r||"minimax"===r||"deepseek"===r||"xai"===r||"gmi"===r||"novita"===r||"stepfun"===r||"huggingface"===r||"opencode-zen"===r||"arcee"===r||"alibaba"===r||"kimi"===r?i(r):void 0,lastModel:e(r)??null}}(r):{baseUrl:l[r],lastModel:null}}export function isProfiledProvider(e){return t.has(e)}export function listProviderProfiles(e){const i=Object.values(getProfilesMap());return e?i.filter(i=>i.provider===e):i}export function getProviderProfile(e){return e?getProfilesMap()[e]??null:null}export function getActiveProviderProfile(){return getProviderProfile(getState().activeProfileId)}export function getLastUsedProviderProfile(e){const i=getState(),r=i.lastProfileIdByProvider?.[e];if(r){const e=getProviderProfile(r);if(e)return e}return listProviderProfiles(e)[0]??null}export function createProviderProfile(e){const i=buildProfileId(e.provider,e.name),r=getProviderProfile(i);if(r)return r;const o=(new Date).toISOString(),t={id:i,provider:e.provider,name:e.name.trim()||n[e.provider],agentName:e.agentName?.trim()||buildDefaultAgentName(e.provider,e.name),baseUrl:e.baseUrl,lastModel:e.lastModel??null,createdAt:o,updatedAt:o};return saveState(i=>({...i,activeProfileId:e.activate?t.id:i.activeProfileId,profiles:{...i.profiles??{},[t.id]:t},lastProfileIdByProvider:{...i.lastProfileIdByProvider??{},[e.provider]:t.id}})),t}export function ensureProviderProfile(e,i=n[e]){const r=getProviderProfile(buildProfileId(e,i));if(r)return r;return createProviderProfile({provider:e,name:i,...getProfileSeed(e,0===listProviderProfiles(e).length),activate:!1})}export function resolveProviderProfile(e,i={}){const r=getActiveProviderProfile();if(r?.provider===e)return r;const o=getLastUsedProviderProfile(e);return o||(i.createIfMissing?ensureProviderProfile(e):null)}export function getResolvedProviderProfileId(e){return resolveProviderProfile(e)?.id??null}export function setActiveProviderProfile(e){const i=getProviderProfile(e);return i?(saveState(e=>({...e,activeProfileId:i.id,lastProfileIdByProvider:{...e.lastProfileIdByProvider??{},[i.provider]:i.id}})),i):null}export function setActiveProfileForProvider(e,i){const r=i&&i.trim()?ensureProviderProfile(e,i):resolveProviderProfile(e,{createIfMissing:!0});return setActiveProviderProfile(r.id),r}export function findProviderProfileByName(e,i){return getProviderProfile(buildProfileId(e,i))}export function updateProviderProfile(e,i){let r=null;return saveState(o=>{const t=o.profiles?.[e];return t?(r=i(t),{...o,profiles:{...o.profiles??{},[e]:r},lastProfileIdByProvider:{...o.lastProfileIdByProvider??{},[t.provider]:e}}):o}),r}export function renameProviderProfile(e,i,r){const o=findProviderProfileByName(e,i);if(!o)return null;const t=r.trim();if(!t)throw new Error("Debes indicar un nuevo nombre de perfil.");const n=buildProfileId(e,t);if(n!==o.id&&getProviderProfile(n))throw new Error(`Ya existe un perfil ${e}/${t}.`);const a={...o,id:n,name:t,updatedAt:(new Date).toISOString()};return saveState(i=>{const r={...i.profiles??{}};delete r[o.id],r[n]=a;const t={...i.lastProfileIdByProvider??{},[e]:i.lastProfileIdByProvider?.[e]===o.id?n:i.lastProfileIdByProvider?.[e]};return{...i,activeProfileId:i.activeProfileId===o.id?n:i.activeProfileId,profiles:r,lastProfileIdByProvider:t}}),{previousId:o.id,profile:a}}export function removeProviderProfile(e,i){const r=findProviderProfileByName(e,i);return r?(saveState(i=>{const o={...i.profiles??{}};delete o[r.id];const t=Object.values(o).filter(i=>i.provider===e),n=t[0]?.id;return{...i,activeProfileId:i.activeProfileId===r.id?n:i.activeProfileId,profiles:o,lastProfileIdByProvider:{...i.lastProfileIdByProvider??{},[e]:i.lastProfileIdByProvider?.[e]===r.id?n:i.lastProfileIdByProvider?.[e]}}}),r):null}export function clearAllProviderProfiles(){const e=Object.values(getProfilesMap());return saveState(e=>({version:1,profiles:{},lastProfileIdByProvider:{}})),e}export function setProviderProfileAgentNameByName(e,i,r){const o=findProviderProfileByName(e,i);if(!o)return null;const t=sanitizeProfileSegment(r);if(!t)throw new Error("Debes indicar un agentName valido.");return updateProviderProfile(o.id,e=>({...e,agentName:t,updatedAt:(new Date).toISOString()}))}export function setProviderProfileBaseUrl(e,i){const r=resolveProviderProfile(e,{createIfMissing:!0});return updateProviderProfile(r.id,e=>({...e,baseUrl:i,updatedAt:(new Date).toISOString()}))??r}export function clearProviderProfileBaseUrl(e){const i=resolveProviderProfile(e);return i?updateProviderProfile(i.id,e=>({...e,baseUrl:void 0,updatedAt:(new Date).toISOString()})):null}export function getProviderProfileBaseUrl(e){return resolveProviderProfile(e)?.baseUrl??null}export function setProviderProfileLastModel(e,i){const r=resolveProviderProfile(e);return r?updateProviderProfile(r.id,e=>({...e,lastModel:i,updatedAt:(new Date).toISOString()})):null}export function getProviderProfileLastModel(e){return resolveProviderProfile(e)?.lastModel??null}export function setProviderProfileLastModelByName(e,i,r){const o=findProviderProfileByName(e,i);return o?updateProviderProfile(o.id,e=>({...e,lastModel:r,updatedAt:(new Date).toISOString()})):null}
1
+ import{getStoredLastModelForProvider as e,getStoredProviderBaseUrl as i,readProviderProfilesState as r,writeProviderProfilesState as o}from"./providerProfilesDb.js";const t=new Set(["claude","openai","openrouter","ollama","ollama-cloud","lmstudio","gemini-api","gemini-google","zai","minimax","nvidia","deepseek","xai","gmi","novita","stepfun","huggingface","opencode-zen","arcee","alibaba","kimi","custom-openai","custom-anthropic"]),n={claude:"main",openai:"main",openrouter:"main",ollama:"local","ollama-cloud":"main",lmstudio:"local","gemini-api":"main","gemini-google":"main",zai:"main",minimax:"main",nvidia:"main",deepseek:"main",xai:"main",gmi:"main",novita:"main",stepfun:"main",huggingface:"main","opencode-zen":"main",arcee:"main",alibaba:"main",kimi:"main","custom-openai":"main","custom-anthropic":"main"},a={claude:"claude",openai:"openai",openrouter:"openrouter",ollama:"ollama-local","ollama-cloud":"ollama-cloud",lmstudio:"lmstudio-local","gemini-api":"gemini-api","gemini-google":"gemini-google",zai:"z-ai",minimax:"minimax",nvidia:"nvidia",deepseek:"deepseek",xai:"xai",gmi:"gmi",novita:"novita",stepfun:"stepfun",huggingface:"huggingface","opencode-zen":"opencode-zen",arcee:"arcee",alibaba:"alibaba",kimi:"kimi","custom-openai":"custom-openai","custom-anthropic":"custom-anthropic"},l={openrouter:"https://openrouter.ai/api/v1",ollama:"http://localhost:11434/v1","ollama-cloud":"http://localhost:11434/v1",lmstudio:"http://localhost:1234/v1","gemini-api":"https://generativelanguage.googleapis.com/v1beta/openai","gemini-google":"https://generativelanguage.googleapis.com/v1beta/openai",zai:"https://api.z.ai/api/coding/paas/v4",minimax:"https://api.minimax.io/anthropic",deepseek:"https://api.deepseek.com/v1",xai:"https://api.x.ai/v1",gmi:"https://api.gmi-serving.com/v1",novita:"https://api.novita.ai/openai/v1",stepfun:"https://api.stepfun.ai/step_plan/v1",huggingface:"https://router.huggingface.co/v1","opencode-zen":"https://opencode.ai/zen/v1",arcee:"https://api.arcee.ai/api/v1",alibaba:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",kimi:"https://api.moonshot.ai/v1"};function sanitizeProfileSegment(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"default"}function buildProfileId(e,i){return`${e}/${sanitizeProfileSegment(i)}`}function buildDefaultAgentName(e,i){const r=a[e],o=sanitizeProfileSegment(i);return o===sanitizeProfileSegment(n[e])?r:`${r}-${o}`}export function getDefaultProfileName(e){return n[e]}export function buildProviderProfileId(e,i){return buildProfileId(e,i)}export function isDefaultProfileId(e,i){return!!i&&i===buildProfileId(e,n[e])}function getState(){const e=r();return{version:1,profiles:e.profiles??{},lastProfileIdByProvider:e.lastProfileIdByProvider??{},activeProfileId:e.activeProfileId}}function saveState(e){const i=e(getState());return o(i),i}function getProfilesMap(){return getState().profiles??{}}function getProfileSeed(r,o){return o?function(r){return{baseUrl:"openrouter"===r||"ollama"===r||"ollama-cloud"===r||"zai"===r||"minimax"===r||"deepseek"===r||"xai"===r||"gmi"===r||"novita"===r||"stepfun"===r||"huggingface"===r||"opencode-zen"===r||"arcee"===r||"alibaba"===r||"kimi"===r?i(r):void 0,lastModel:e(r)??null}}(r):{baseUrl:l[r],lastModel:null}}export function isProfiledProvider(e){return t.has(e)}export function listProviderProfiles(e){const i=Object.values(getProfilesMap());return e?i.filter(i=>i.provider===e):i}export function getProviderProfile(e){return e?getProfilesMap()[e]??null:null}export function getActiveProviderProfile(){return getProviderProfile(getState().activeProfileId)}export function getLastUsedProviderProfile(e){const i=getState(),r=i.lastProfileIdByProvider?.[e];if(r){const e=getProviderProfile(r);if(e)return e}return listProviderProfiles(e)[0]??null}export function createProviderProfile(e){const i=buildProfileId(e.provider,e.name),r=getProviderProfile(i);if(r)return r;const o=(new Date).toISOString(),t={id:i,provider:e.provider,name:e.name.trim()||n[e.provider],agentName:e.agentName?.trim()||buildDefaultAgentName(e.provider,e.name),baseUrl:e.baseUrl,lastModel:e.lastModel??null,createdAt:o,updatedAt:o};return saveState(i=>({...i,activeProfileId:e.activate?t.id:i.activeProfileId,profiles:{...i.profiles??{},[t.id]:t},lastProfileIdByProvider:{...i.lastProfileIdByProvider??{},[e.provider]:t.id}})),t}export function ensureProviderProfile(e,i=n[e]){const r=getProviderProfile(buildProfileId(e,i));if(r)return r;return createProviderProfile({provider:e,name:i,...getProfileSeed(e,0===listProviderProfiles(e).length),activate:!1})}export function resolveProviderProfile(e,i={}){const r=getActiveProviderProfile();if(r?.provider===e)return r;const o=getLastUsedProviderProfile(e);return o||(i.createIfMissing?ensureProviderProfile(e):null)}export function getResolvedProviderProfileId(e){return resolveProviderProfile(e)?.id??null}export function setActiveProviderProfile(e){const i=getProviderProfile(e);return i?(saveState(e=>({...e,activeProfileId:i.id,lastProfileIdByProvider:{...e.lastProfileIdByProvider??{},[i.provider]:i.id}})),i):null}export function setActiveProfileForProvider(e,i){const r=i&&i.trim()?ensureProviderProfile(e,i):resolveProviderProfile(e,{createIfMissing:!0});return setActiveProviderProfile(r.id),r}export function findProviderProfileByName(e,i){return getProviderProfile(buildProfileId(e,i))}export function updateProviderProfile(e,i){let r=null;return saveState(o=>{const t=o.profiles?.[e];return t?(r=i(t),{...o,profiles:{...o.profiles??{},[e]:r},lastProfileIdByProvider:{...o.lastProfileIdByProvider??{},[t.provider]:e}}):o}),r}export function renameProviderProfile(e,i,r){const o=findProviderProfileByName(e,i);if(!o)return null;const t=r.trim();if(!t)throw new Error("Debes indicar un nuevo nombre de perfil.");const n=buildProfileId(e,t);if(n!==o.id&&getProviderProfile(n))throw new Error(`Ya existe un perfil ${e}/${t}.`);const a={...o,id:n,name:t,updatedAt:(new Date).toISOString()};return saveState(i=>{const r={...i.profiles??{}};delete r[o.id],r[n]=a;const t={...i.lastProfileIdByProvider??{},[e]:i.lastProfileIdByProvider?.[e]===o.id?n:i.lastProfileIdByProvider?.[e]};return{...i,activeProfileId:i.activeProfileId===o.id?n:i.activeProfileId,profiles:r,lastProfileIdByProvider:t}}),{previousId:o.id,profile:a}}export function removeProviderProfile(e,i){const r=findProviderProfileByName(e,i);return r?(saveState(i=>{const o={...i.profiles??{}};delete o[r.id];const t=Object.values(o).filter(i=>i.provider===e),n=t[0]?.id;return{...i,activeProfileId:i.activeProfileId===r.id?n:i.activeProfileId,profiles:o,lastProfileIdByProvider:{...i.lastProfileIdByProvider??{},[e]:i.lastProfileIdByProvider?.[e]===r.id?n:i.lastProfileIdByProvider?.[e]}}}),r):null}export function clearAllProviderProfiles(){const e=Object.values(getProfilesMap());return saveState(e=>({version:1,profiles:{},lastProfileIdByProvider:{}})),e}export function setProviderProfileAgentNameByName(e,i,r){const o=findProviderProfileByName(e,i);if(!o)return null;const t=sanitizeProfileSegment(r);if(!t)throw new Error("Debes indicar un agentName valido.");return updateProviderProfile(o.id,e=>({...e,agentName:t,updatedAt:(new Date).toISOString()}))}export function setProviderProfileBaseUrl(e,i){const r=resolveProviderProfile(e,{createIfMissing:!0});return updateProviderProfile(r.id,e=>({...e,baseUrl:i,updatedAt:(new Date).toISOString()}))??r}export function clearProviderProfileBaseUrl(e){const i=resolveProviderProfile(e);return i?updateProviderProfile(i.id,e=>({...e,baseUrl:void 0,updatedAt:(new Date).toISOString()})):null}export function getProviderProfileBaseUrl(e){return resolveProviderProfile(e)?.baseUrl??null}export function setProviderProfileLastModel(e,i){const r=resolveProviderProfile(e);return r?updateProviderProfile(r.id,e=>({...e,lastModel:i,updatedAt:(new Date).toISOString()})):null}export function getProviderProfileLastModel(e){return resolveProviderProfile(e)?.lastModel??null}export function setProviderProfileLastModelByName(e,i,r){const o=findProviderProfileByName(e,i);return o?updateProviderProfile(o.id,e=>({...e,lastModel:r,updatedAt:(new Date).toISOString()})):null}
@@ -1 +1 @@
1
- import{createRequire as e}from"module";import{randomUUID as t}from"node:crypto";import{join as n}from"path";import{getGlobalConfig as i,saveGlobalConfig as r}from"../config.js";import{getClaudeConfigHomeDir as a}from"../envUtils.js";import{getFsImplementation as E}from"../fsOperations.js";import{getSecureStorage as o}from"../secureStorage/index.js";function hasStoredCredentialForProvider(e,t){if(!e)return!1;if("openai"===t&&e.openAiOauth?.accessToken)return!0;if("claude"===t&&e.claudeAiOauth?.accessToken)return!0;if(Object.keys(e.providerProfileOauth??{}).some(e=>e.startsWith(`${t}/`)))return!0;if(e.providerApiKeys?.[t])return!0;return Object.keys(e.providerProfileApiKeys??{}).some(e=>e.startsWith(`${t}/`))}const d=e(import.meta.url);let _=null,s=!1,T=!1;const l="active_provider",N="active_profile_id",p=["claude","openai","openrouter","ollama","ollama-cloud","gemini-api","gemini-google","zai","minimax","deepseek"],L={claude:"main",openai:"main",openrouter:"main",ollama:"local","ollama-cloud":"main","gemini-api":"main","gemini-google":"main",zai:"main",minimax:"main",nvidia:"main",deepseek:"main"},c={claude:"claude",openai:"openai",openrouter:"openrouter",ollama:"ollama-local","ollama-cloud":"ollama-cloud","gemini-api":"gemini-api","gemini-google":"gemini-google",zai:"z-ai",minimax:"minimax",nvidia:"nvidia",deepseek:"deepseek"},u={openrouter:"https://openrouter.ai/api/v1",ollama:"http://localhost:11434/v1","ollama-cloud":"http://localhost:11434/v1","gemini-api":"https://generativelanguage.googleapis.com/v1beta/openai","gemini-google":"https://generativelanguage.googleapis.com/v1beta/openai",zai:"https://api.z.ai/api/coding/paas/v4",minimax:"https://api.minimax.io/anthropic",deepseek:"https://api.deepseek.com/v1"},m={claude:"Claude",openai:"OpenAI",openrouter:"OpenRouter",ollama:"Ollama","ollama-cloud":"Ollama Cloud","gemini-api":"Gemini API","gemini-google":"Gemini Google",zai:"Z.AI",minimax:"MiniMax",nvidia:"NVIDIA NIM",deepseek:"DeepSeek"},O=["openrouter","ollama","ollama-cloud","gemini-api","gemini-google","zai","minimax","deepseek"];function sanitizeProfileSegment(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"default"}function buildProfileId(e,t){return`${e}/${sanitizeProfileSegment(t)}`}function buildDefaultAgentName(e,t){const n=c[e],i=sanitizeProfileSegment(t);return i===sanitizeProfileSegment(L[e])?n:`${n}-${i}`}function tableExists(e,t){const n=e.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(t);return Boolean(n)}function columnExists(e,t,n){return e.prepare(`PRAGMA table_info(${t})`).all().some(e=>e.name===n)}function migrateTeamUnitsSchema(e){e.exec("PRAGMA foreign_keys = OFF;");try{tableExists(e,"team_domains")&&e.exec("\n INSERT OR IGNORE INTO team_units (\n id, team_id, unit_name, workspace_id, local_orchestrator_agent_id, lead_agent_id, selection_mode, required, created_at, updated_at\n )\n SELECT id, team_id, domain_name, workspace_id, local_orchestrator_agent_id, lead_agent_id, selection_mode, required, created_at, updated_at\n FROM team_domains;\n "),tableExists(e,"team_domain_members")&&e.exec("\n INSERT OR IGNORE INTO team_unit_members (\n id, team_unit_id, agent_id, duty, priority, created_at, updated_at\n )\n SELECT id, team_domain_id, agent_id, duty, priority, created_at, updated_at\n FROM team_domain_members;\n "),tableExists(e,"orchestration_tasks")&&!columnExists(e,"orchestration_tasks","team_unit_id")&&e.exec("ALTER TABLE orchestration_tasks ADD COLUMN team_unit_id TEXT NULL;"),tableExists(e,"orchestration_tasks")&&columnExists(e,"orchestration_tasks","team_domain_id")&&columnExists(e,"orchestration_tasks","team_unit_id")&&e.exec("\n UPDATE orchestration_tasks\n SET team_unit_id = team_domain_id\n WHERE team_unit_id IS NULL AND team_domain_id IS NOT NULL;\n "),function(e){tableExists(e,"orchestration_tasks")&&columnExists(e,"orchestration_tasks","team_domain_id")&&e.exec("\n CREATE TABLE IF NOT EXISTS orchestration_tasks_v8 (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL,\n parent_task_id TEXT NULL,\n scope_type TEXT NOT NULL,\n team_unit_id TEXT NULL,\n assigned_agent_id TEXT NULL,\n title TEXT NOT NULL,\n instructions TEXT NOT NULL,\n status TEXT NOT NULL,\n result_summary TEXT NULL,\n created_at TEXT NOT NULL,\n finished_at TEXT NULL,\n FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE CASCADE,\n FOREIGN KEY (parent_task_id) REFERENCES orchestration_tasks_v8(id) ON DELETE SET NULL,\n FOREIGN KEY (team_unit_id) REFERENCES team_units(id) ON DELETE SET NULL,\n FOREIGN KEY (assigned_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL\n );\n\n INSERT OR REPLACE INTO orchestration_tasks_v8 (\n id, run_id, parent_task_id, scope_type, team_unit_id, assigned_agent_id, title, instructions, status, result_summary, created_at, finished_at\n )\n SELECT id, run_id, parent_task_id, scope_type, team_unit_id, assigned_agent_id, title, instructions, status, result_summary, created_at, finished_at\n FROM orchestration_tasks;\n\n DROP TABLE orchestration_tasks;\n ALTER TABLE orchestration_tasks_v8 RENAME TO orchestration_tasks;\n\n CREATE INDEX IF NOT EXISTS idx_orchestration_tasks_run_id\n ON orchestration_tasks(run_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_tasks_team_unit_id\n ON orchestration_tasks(team_unit_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_tasks_assigned_agent_id\n ON orchestration_tasks(assigned_agent_id);\n ")}(e),tableExists(e,"orchestration_domain_reports")&&e.exec("\n INSERT OR IGNORE INTO orchestration_team_reports (\n id, run_id, team_unit_id, local_orchestrator_agent_id, status, summary, blockers, output, metrics_json, created_at, updated_at, submitted_at\n )\n SELECT id, run_id, team_domain_id, local_orchestrator_agent_id, status, summary, blockers, output, metrics_json, created_at, updated_at, submitted_at\n FROM orchestration_domain_reports;\n "),tableExists(e,"provider_agent_capability_rankings")&&!columnExists(e,"provider_agent_capability_rankings","team_unit_id")&&e.exec("ALTER TABLE provider_agent_capability_rankings ADD COLUMN team_unit_id TEXT NULL;"),tableExists(e,"provider_agent_capability_rankings")&&columnExists(e,"provider_agent_capability_rankings","team_domain_id")&&columnExists(e,"provider_agent_capability_rankings","team_unit_id")&&e.exec("\n UPDATE provider_agent_capability_rankings\n SET team_unit_id = team_domain_id\n WHERE team_unit_id IS NULL AND team_domain_id IS NOT NULL;\n "),function(e){tableExists(e,"provider_agent_capability_rankings")&&columnExists(e,"provider_agent_capability_rankings","team_domain_id")&&e.exec("\n CREATE TABLE IF NOT EXISTS provider_agent_capability_rankings_v8 (\n id TEXT PRIMARY KEY,\n team_unit_id TEXT NULL,\n capability TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n score REAL NOT NULL DEFAULT 0,\n reason TEXT NULL,\n source TEXT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n FOREIGN KEY (team_unit_id) REFERENCES team_units(id) ON DELETE CASCADE,\n FOREIGN KEY (agent_id) REFERENCES provider_agents(id) ON DELETE CASCADE,\n UNIQUE (team_unit_id, capability, agent_id)\n );\n\n INSERT OR REPLACE INTO provider_agent_capability_rankings_v8 (\n id, team_unit_id, capability, agent_id, score, reason, source, created_at, updated_at\n )\n SELECT id, team_unit_id, capability, agent_id, score, reason, source, created_at, updated_at\n FROM provider_agent_capability_rankings;\n\n DROP TABLE provider_agent_capability_rankings;\n ALTER TABLE provider_agent_capability_rankings_v8 RENAME TO provider_agent_capability_rankings;\n\n CREATE INDEX IF NOT EXISTS idx_provider_agent_capability_rankings_team_unit\n ON provider_agent_capability_rankings(team_unit_id);\n CREATE INDEX IF NOT EXISTS idx_provider_agent_capability_rankings_capability\n ON provider_agent_capability_rankings(capability);\n CREATE INDEX IF NOT EXISTS idx_provider_agent_capability_rankings_agent\n ON provider_agent_capability_rankings(agent_id);\n ")}(e),e.exec("\n DROP TABLE IF EXISTS orchestration_domain_reports;\n DROP TABLE IF EXISTS team_domain_members;\n DROP TABLE IF EXISTS team_domains;\n ")}finally{e.exec("PRAGMA foreign_keys = ON;")}tableExists(e,"orchestration_tasks")&&columnExists(e,"orchestration_tasks","team_unit_id")&&e.exec("\n CREATE INDEX IF NOT EXISTS idx_orchestration_tasks_team_unit_id\n ON orchestration_tasks(team_unit_id);\n "),tableExists(e,"provider_agent_capability_rankings")&&columnExists(e,"provider_agent_capability_rankings","team_unit_id")&&e.exec("\n CREATE INDEX IF NOT EXISTS idx_provider_agent_capability_rankings_team_unit\n ON provider_agent_capability_rankings(team_unit_id);\n ")}function getDatabasePath(){return n(a(),"provider-state.sqlite3")}function rowToProfile(e){if(!e)return null;const t=e;return{id:t.id,provider:t.provider,name:t.name,agentName:t.agent_name,baseUrl:t.base_url??void 0,lastModel:t.last_model,createdAt:t.created_at,updatedAt:t.updated_at}}function seedLegacyProfiles(){const e=i(),t=e.providerProfiles,n={...t&&"object"==typeof t&&t.profiles?t.profiles:{}},r={...t&&"object"==typeof t&&t.lastProfileIdByProvider?t.lastProfileIdByProvider:{}},a=(()=>{try{return o().read()}catch{return null}})();for(const t of p){const i=Object.values(n).some(e=>e.provider===t),E=e.providerBaseUrls?.[t],o=e.lastModelByProvider?.[t]??null;if(!(i||e.activeProvider===t||Boolean(E)||null!==o||hasStoredCredentialForProvider(a,t))||i)continue;const d=L[t],_=buildProfileId(t,d),s=(new Date).toISOString();n[_]={id:_,provider:t,name:d,agentName:buildDefaultAgentName(t,d),baseUrl:E??u[t],lastModel:o,createdAt:s,updatedAt:s},r[t]=_}return{version:1,activeProfileId:(t&&"object"==typeof t?t.activeProfileId:void 0)??(e.activeProvider&&p.includes(e.activeProvider)?r[e.activeProvider]:void 0),lastProfileIdByProvider:r,profiles:n}}function migrateFromLegacyConfig(e){const t=i(),n=seedLegacyProfiles(),r=e.prepare("\n INSERT OR REPLACE INTO provider_profiles (\n id, provider, name, agent_name, base_url, last_model, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n "),a=e.prepare("\n INSERT INTO provider_last_profile (provider, profile_id)\n VALUES (?, ?)\n ON CONFLICT(provider) DO UPDATE SET profile_id = excluded.profile_id\n "),E=e.prepare("\n INSERT INTO provider_runtime_state (key, value)\n VALUES (?, ?)\n ON CONFLICT(key) DO UPDATE SET value = excluded.value\n "),o=e.prepare("\n INSERT INTO provider_last_model (provider, last_model, updated_at)\n VALUES (?, ?, ?)\n ON CONFLICT(provider) DO UPDATE SET\n last_model = excluded.last_model,\n updated_at = excluded.updated_at\n "),d=e.prepare("\n INSERT INTO provider_base_url (provider, base_url, updated_at)\n VALUES (?, ?, ?)\n ON CONFLICT(provider) DO UPDATE SET\n base_url = excluded.base_url,\n updated_at = excluded.updated_at\n ");for(const e of Object.values(n.profiles??{}))r.run(e.id,e.provider,e.name,e.agentName,e.baseUrl??null,e.lastModel??null,e.createdAt,e.updatedAt);for(const[e,t]of Object.entries(n.lastProfileIdByProvider??{}))t&&a.run(e,t);n.activeProfileId&&E.run(N,n.activeProfileId);const _=t.activeProvider??(n.activeProfileId?n.profiles?.[n.activeProfileId]?.provider:void 0);_&&E.run(l,_);const s={claude:t.lastClaudeModel??t.lastModelByProvider?.claude??null,openai:t.lastOpenAIModel??t.lastModelByProvider?.openai??null,openrouter:t.lastOpenRouterModel??t.lastModelByProvider?.openrouter??null,ollama:t.lastModelByProvider?.ollama??null,"ollama-cloud":t.lastModelByProvider?.["ollama-cloud"]??null,"gemini-api":t.lastModelByProvider?.["gemini-api"]??null,"gemini-google":t.lastModelByProvider?.["gemini-google"]??null,zai:t.lastModelByProvider?.zai??null,minimax:t.lastModelByProvider?.minimax??null,deepseek:t.lastModelByProvider?.deepseek??null};for(const e of p)o.run(e,s[e]??null,(new Date).toISOString());for(const e of O){const n=t.providerBaseUrls?.[e];"string"==typeof n&&n.trim()&&d.run(e,n.trim(),(new Date).toISOString())}}export function purgeLegacyProviderStateInConfig(){hasLegacyProviderStateInConfig()&&r(e=>({...e,activeProvider:void 0,lastModelByProvider:{},providerBaseUrls:void 0,lastOpenAIModel:void 0,lastClaudeModel:void 0,lastOpenRouterModel:void 0,providerProfiles:void 0}))}export function finalizeProviderProfilesMigration(){ensureInitialized(),purgeLegacyProviderStateInConfig()}function ensureInitialized(){const e=function(){if(T)throw new Error("SQLite no disponible en este runtime.");if(_)return _;let e;E().mkdirSync(a(),{mode:448});try{e=d("node:sqlite")}catch(e){throw T=!0,e}return _=new e.DatabaseSync(getDatabasePath()),_}();if(s)return e;e.exec("\n PRAGMA journal_mode = WAL;\n PRAGMA foreign_keys = ON;\n PRAGMA synchronous = NORMAL;\n\n CREATE TABLE IF NOT EXISTS provider_profiles (\n id TEXT PRIMARY KEY,\n provider TEXT NOT NULL,\n name TEXT NOT NULL,\n agent_name TEXT NOT NULL,\n base_url TEXT NULL,\n last_model TEXT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS provider_last_profile (\n provider TEXT PRIMARY KEY,\n profile_id TEXT NOT NULL,\n FOREIGN KEY (profile_id) REFERENCES provider_profiles(id) ON DELETE CASCADE\n );\n\n CREATE TABLE IF NOT EXISTS provider_runtime_state (\n key TEXT PRIMARY KEY,\n value TEXT NULL\n );\n\n CREATE TABLE IF NOT EXISTS provider_last_model (\n provider TEXT PRIMARY KEY,\n last_model TEXT NULL,\n updated_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS provider_base_url (\n provider TEXT PRIMARY KEY,\n base_url TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS provider_workspaces (\n id TEXT PRIMARY KEY,\n provider TEXT NOT NULL UNIQUE,\n display_name TEXT NOT NULL,\n domain_focus TEXT NULL,\n is_enabled INTEGER NOT NULL DEFAULT 1,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS provider_agents (\n id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n profile_id TEXT NOT NULL,\n name TEXT NOT NULL,\n role_kind TEXT NULL,\n system_prompt TEXT NULL,\n model_override TEXT NULL,\n tool_policy TEXT NULL,\n autonomy_level TEXT NULL,\n is_orchestrator INTEGER NOT NULL DEFAULT 0,\n is_enabled INTEGER NOT NULL DEFAULT 1,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n FOREIGN KEY (workspace_id) REFERENCES provider_workspaces(id) ON DELETE CASCADE,\n FOREIGN KEY (profile_id) REFERENCES provider_profiles(id) ON DELETE CASCADE,\n UNIQUE (workspace_id, name)\n );\n\n CREATE INDEX IF NOT EXISTS idx_provider_agents_workspace_id\n ON provider_agents(workspace_id);\n CREATE INDEX IF NOT EXISTS idx_provider_agents_profile_id\n ON provider_agents(profile_id);\n\n CREATE TABLE IF NOT EXISTS provider_agent_capabilities (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n capability TEXT NOT NULL,\n weight REAL NOT NULL DEFAULT 1,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n FOREIGN KEY (agent_id) REFERENCES provider_agents(id) ON DELETE CASCADE,\n UNIQUE (agent_id, capability)\n );\n\n CREATE INDEX IF NOT EXISTS idx_provider_agent_capabilities_agent_id\n ON provider_agent_capabilities(agent_id);\n\n CREATE TABLE IF NOT EXISTS teams (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL UNIQUE,\n description TEXT NULL,\n global_orchestrator_agent_id TEXT NULL,\n is_enabled INTEGER NOT NULL DEFAULT 1,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n FOREIGN KEY (global_orchestrator_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL\n );\n\n CREATE TABLE IF NOT EXISTS team_units (\n id TEXT PRIMARY KEY,\n team_id TEXT NOT NULL,\n unit_name TEXT NOT NULL,\n workspace_id TEXT NULL,\n local_orchestrator_agent_id TEXT NULL,\n lead_agent_id TEXT NULL,\n selection_mode TEXT NOT NULL DEFAULT 'manual',\n required INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n FOREIGN KEY (team_id) REFERENCES teams(id) ON DELETE CASCADE,\n FOREIGN KEY (workspace_id) REFERENCES provider_workspaces(id) ON DELETE SET NULL,\n FOREIGN KEY (local_orchestrator_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL,\n FOREIGN KEY (lead_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL,\n UNIQUE (team_id, unit_name)\n );\n\n CREATE INDEX IF NOT EXISTS idx_team_units_team_id\n ON team_units(team_id);\n CREATE INDEX IF NOT EXISTS idx_team_units_workspace_id\n ON team_units(workspace_id);\n CREATE INDEX IF NOT EXISTS idx_team_units_local_orchestrator_agent_id\n ON team_units(local_orchestrator_agent_id);\n CREATE INDEX IF NOT EXISTS idx_team_units_lead_agent_id\n ON team_units(lead_agent_id);\n\n CREATE TABLE IF NOT EXISTS team_unit_members (\n id TEXT PRIMARY KEY,\n team_unit_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n duty TEXT NULL,\n priority INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n FOREIGN KEY (team_unit_id) REFERENCES team_units(id) ON DELETE CASCADE,\n FOREIGN KEY (agent_id) REFERENCES provider_agents(id) ON DELETE CASCADE,\n UNIQUE (team_unit_id, agent_id)\n );\n\n CREATE INDEX IF NOT EXISTS idx_team_unit_members_team_unit_id\n ON team_unit_members(team_unit_id);\n CREATE INDEX IF NOT EXISTS idx_team_unit_members_agent_id\n ON team_unit_members(agent_id);\n\n CREATE TABLE IF NOT EXISTS orchestration_runs (\n id TEXT PRIMARY KEY,\n team_id TEXT NOT NULL,\n goal TEXT NOT NULL,\n global_orchestrator_agent_id TEXT NULL,\n status TEXT NOT NULL,\n created_at TEXT NOT NULL,\n started_at TEXT NULL,\n finished_at TEXT NULL,\n FOREIGN KEY (team_id) REFERENCES teams(id) ON DELETE CASCADE,\n FOREIGN KEY (global_orchestrator_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_orchestration_runs_team_id\n ON orchestration_runs(team_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_runs_status\n ON orchestration_runs(status);\n\n CREATE TABLE IF NOT EXISTS orchestration_tasks (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL,\n parent_task_id TEXT NULL,\n scope_type TEXT NOT NULL,\n team_unit_id TEXT NULL,\n assigned_agent_id TEXT NULL,\n title TEXT NOT NULL,\n instructions TEXT NOT NULL,\n status TEXT NOT NULL,\n result_summary TEXT NULL,\n created_at TEXT NOT NULL,\n finished_at TEXT NULL,\n FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE CASCADE,\n FOREIGN KEY (parent_task_id) REFERENCES orchestration_tasks(id) ON DELETE SET NULL,\n FOREIGN KEY (team_unit_id) REFERENCES team_units(id) ON DELETE SET NULL,\n FOREIGN KEY (assigned_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_orchestration_tasks_run_id\n ON orchestration_tasks(run_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_tasks_assigned_agent_id\n ON orchestration_tasks(assigned_agent_id);\n\n CREATE TABLE IF NOT EXISTS orchestration_messages (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL,\n task_id TEXT NULL,\n from_agent_id TEXT NULL,\n to_agent_id TEXT NULL,\n message_type TEXT NOT NULL,\n content TEXT NOT NULL,\n created_at TEXT NOT NULL,\n FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE CASCADE,\n FOREIGN KEY (task_id) REFERENCES orchestration_tasks(id) ON DELETE SET NULL,\n FOREIGN KEY (from_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL,\n FOREIGN KEY (to_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_orchestration_messages_run_id\n ON orchestration_messages(run_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_messages_task_id\n ON orchestration_messages(task_id);\n\n CREATE TABLE IF NOT EXISTS orchestration_task_results (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL,\n task_id TEXT NOT NULL,\n agent_id TEXT NULL,\n result_type TEXT NOT NULL,\n status TEXT NOT NULL,\n summary TEXT NULL,\n content TEXT NULL,\n metadata_json TEXT NULL,\n created_at TEXT NOT NULL,\n FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE CASCADE,\n FOREIGN KEY (task_id) REFERENCES orchestration_tasks(id) ON DELETE CASCADE,\n FOREIGN KEY (agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_orchestration_task_results_run_id\n ON orchestration_task_results(run_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_task_results_task_id\n ON orchestration_task_results(task_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_task_results_agent_id\n ON orchestration_task_results(agent_id);\n\n CREATE TABLE IF NOT EXISTS orchestration_team_reports (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL,\n team_unit_id TEXT NOT NULL,\n local_orchestrator_agent_id TEXT NULL,\n status TEXT NOT NULL,\n summary TEXT NOT NULL,\n blockers TEXT NULL,\n output TEXT NULL,\n metrics_json TEXT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n submitted_at TEXT NULL,\n FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE CASCADE,\n FOREIGN KEY (team_unit_id) REFERENCES team_units(id) ON DELETE CASCADE,\n FOREIGN KEY (local_orchestrator_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL,\n UNIQUE (run_id, team_unit_id)\n );\n\n CREATE INDEX IF NOT EXISTS idx_orchestration_team_reports_run_id\n ON orchestration_team_reports(run_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_team_reports_team_unit_id\n ON orchestration_team_reports(team_unit_id);\n\n CREATE TABLE IF NOT EXISTS orchestration_run_reports (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL UNIQUE,\n status TEXT NOT NULL,\n summary TEXT NOT NULL,\n output TEXT NULL,\n risks TEXT NULL,\n next_steps TEXT NULL,\n metrics_json TEXT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n submitted_at TEXT NULL,\n FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE CASCADE\n );\n\n CREATE INDEX IF NOT EXISTS idx_orchestration_run_reports_run_id\n ON orchestration_run_reports(run_id);\n\n CREATE TABLE IF NOT EXISTS provider_agent_capability_rankings (\n id TEXT PRIMARY KEY,\n team_unit_id TEXT NULL,\n capability TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n score REAL NOT NULL DEFAULT 0,\n reason TEXT NULL,\n source TEXT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n FOREIGN KEY (team_unit_id) REFERENCES team_units(id) ON DELETE CASCADE,\n FOREIGN KEY (agent_id) REFERENCES provider_agents(id) ON DELETE CASCADE,\n UNIQUE (team_unit_id, capability, agent_id)\n );\n\n CREATE INDEX IF NOT EXISTS idx_provider_agent_capability_rankings_capability\n ON provider_agent_capability_rankings(capability);\n CREATE INDEX IF NOT EXISTS idx_provider_agent_capability_rankings_agent\n ON provider_agent_capability_rankings(agent_id);\n\n CREATE TABLE IF NOT EXISTS secure_storage (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS projects (\n path TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n created_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS permission_rules (\n id TEXT PRIMARY KEY,\n scope TEXT NOT NULL,\n scope_path TEXT NULL,\n tool_name TEXT NOT NULL,\n behavior TEXT NOT NULL,\n created_at TEXT NOT NULL,\n expires_at TEXT NULL,\n UNIQUE (scope, scope_path, tool_name)\n );\n\n CREATE INDEX IF NOT EXISTS idx_permission_rules_scope\n ON permission_rules(scope, scope_path);\n CREATE INDEX IF NOT EXISTS idx_permission_rules_tool_name\n ON permission_rules(tool_name);\n\n CREATE TABLE IF NOT EXISTS permission_mode_config (\n id TEXT PRIMARY KEY,\n scope TEXT NOT NULL,\n scope_path TEXT NULL,\n mode TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n UNIQUE (scope, scope_path)\n );\n\n CREATE TABLE IF NOT EXISTS trusted_directories (\n path TEXT PRIMARY KEY,\n trust_level TEXT NOT NULL DEFAULT 'full',\n created_at TEXT NOT NULL\n );\n "),migrateTeamUnitsSchema(e);const n=e.prepare("PRAGMA user_version").get();(n?.user_version??0)<8&&e.exec("PRAGMA user_version = 8"),function(e){const n=(new Date).toISOString(),i=e.prepare("\n INSERT OR IGNORE INTO provider_workspaces (\n id, provider, display_name, domain_focus, is_enabled, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?)\n ");for(const e of p)i.run(t(),e,m[e],null,1,n,n)}(e);const i=e.prepare("SELECT COUNT(*) AS count FROM provider_profiles").get();if(0===(i?.count??0))migrateFromLegacyConfig(e);else{const t=e.prepare("SELECT COUNT(*) AS count FROM provider_last_model").get();0===(t?.count??0)&&migrateFromLegacyConfig(e);const n=e.prepare("SELECT COUNT(*) AS count FROM provider_base_url").get();0===(n?.count??0)&&migrateFromLegacyConfig(e)}return purgeLegacyProviderStateInConfig(),s=!0,e}export class ProviderProfilesDb{static instance=null;db;constructor(){this.db=ensureInitialized()}static async get(){return ProviderProfilesDb.instance||(ProviderProfilesDb.instance=new ProviderProfilesDb),ProviderProfilesDb.instance}}export function getProviderProfilesDbPath(){return getDatabasePath()}export function getProviderProfilesStorageBackend(){try{return ensureInitialized(),"sqlite"}catch{return"legacy"}}export function hasLegacyProviderStateInConfig(){try{const e=i();return Boolean(e.activeProvider||e.lastClaudeModel||e.lastOpenAIModel||e.lastOpenRouterModel||Object.keys(e.lastModelByProvider??{}).length>0||Object.keys(e.providerBaseUrls??{}).length>0||e.providerProfiles?.activeProfileId||Object.keys(e.providerProfiles?.profiles??{}).length>0||Object.keys(e.providerProfiles?.lastProfileIdByProvider??{}).length>0)}catch{return!1}}export function getProviderProfilesStorageMode(){return"sqlite"!==getProviderProfilesStorageBackend()?"legacy":hasLegacyProviderStateInConfig()?"sqlite-migration-pending":"sqlite-only"}export function readProviderProfilesState(){let e;try{e=ensureInitialized()}catch{return seedLegacyProfiles()}const t=e.prepare("SELECT id, provider, name, agent_name, base_url, last_model, created_at, updated_at\n FROM provider_profiles\n ORDER BY provider, created_at, id").all().map(rowToProfile).filter(e=>null!==e),n=e.prepare("SELECT provider, profile_id FROM provider_last_profile").all(),i=e.prepare(`SELECT value FROM provider_runtime_state WHERE key = '${N}'`).get();return{version:1,activeProfileId:i?.value,lastProfileIdByProvider:Object.fromEntries(n.map(e=>[e.provider,e.profile_id])),profiles:Object.fromEntries(t.map(e=>[e.id,e]))}}export function writeProviderProfilesState(e){let t;try{t=ensureInitialized()}catch{return}const n=Object.values(e.profiles??{}),i=0===n.length;t.exec("BEGIN");try{t.exec("DELETE FROM provider_last_profile"),t.exec(`DELETE FROM provider_runtime_state WHERE key = '${N}'`),t.exec("DELETE FROM provider_profiles"),i&&(t.exec(`DELETE FROM provider_runtime_state WHERE key = '${l}'`),t.exec("DELETE FROM provider_last_model"),t.exec("DELETE FROM provider_base_url"));const r=t.prepare("\n INSERT INTO provider_profiles (\n id, provider, name, agent_name, base_url, last_model, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n ");for(const e of n)r.run(e.id,e.provider,e.name,e.agentName,e.baseUrl??null,e.lastModel??null,e.createdAt,e.updatedAt);const a=t.prepare("\n INSERT INTO provider_last_profile (provider, profile_id)\n VALUES (?, ?)\n ");for(const[t,n]of Object.entries(e.lastProfileIdByProvider??{}))n&&a.run(t,n);e.activeProfileId&&t.prepare(`\n INSERT INTO provider_runtime_state (key, value)\n VALUES ('${N}', ?)\n `).run(e.activeProfileId),t.exec("COMMIT")}catch(e){throw t.exec("ROLLBACK"),e}}export function getStoredActiveProviderPreference(){const e=function(e){try{const t=ensureInitialized().prepare("SELECT value FROM provider_runtime_state WHERE key = ?").get(e);return t?.value??null}catch{return null}}(l);return null!==e?e:null}export function setStoredActiveProviderPreference(e){!function(e,t){try{const n=ensureInitialized();if(null===t)return void n.prepare("DELETE FROM provider_runtime_state WHERE key = ?").run(e);n.prepare("\n INSERT INTO provider_runtime_state (key, value)\n VALUES (?, ?)\n ON CONFLICT(key) DO UPDATE SET value = excluded.value\n ").run(e,t)}catch{}}(l,e)}export function getStoredLastModelForProvider(e){try{const t=ensureInitialized().prepare("SELECT last_model FROM provider_last_model WHERE provider = ?").get(e);if(t&&Object.prototype.hasOwnProperty.call(t,"last_model"))return t.last_model??null}catch{return}}export function setStoredLastModelForProvider(e,t){!function(e,t){try{ensureInitialized().prepare("\n INSERT INTO provider_last_model (provider, last_model, updated_at)\n VALUES (?, ?, ?)\n ON CONFLICT(provider) DO UPDATE SET\n last_model = excluded.last_model,\n updated_at = excluded.updated_at\n ").run(e,t,(new Date).toISOString())}catch{}}(e,t)}export function getStoredProviderBaseUrl(e){try{const t=ensureInitialized().prepare("SELECT base_url FROM provider_base_url WHERE provider = ?").get(e);if(t?.base_url?.trim())return t.base_url.trim()}catch{return}}export function setStoredProviderBaseUrl(e,t){try{ensureInitialized().prepare("\n INSERT INTO provider_base_url (provider, base_url, updated_at)\n VALUES (?, ?, ?)\n ON CONFLICT(provider) DO UPDATE SET\n base_url = excluded.base_url,\n updated_at = excluded.updated_at\n ").run(e,t,(new Date).toISOString())}catch{}}export function clearStoredProviderBaseUrl(e){try{ensureInitialized().prepare("DELETE FROM provider_base_url WHERE provider = ?").run(e)}catch{}}
1
+ import{createRequire as e}from"module";import{randomUUID as t}from"node:crypto";import{join as n}from"path";import{getGlobalConfig as i,saveGlobalConfig as r}from"../config.js";import{getClaudeConfigHomeDir as a}from"../envUtils.js";import{getFsImplementation as E}from"../fsOperations.js";import{getSecureStorage as o}from"../secureStorage/index.js";function hasStoredCredentialForProvider(e,t){if(!e)return!1;if("openai"===t&&e.openAiOauth?.accessToken)return!0;if("claude"===t&&e.claudeAiOauth?.accessToken)return!0;if(Object.keys(e.providerProfileOauth??{}).some(e=>e.startsWith(`${t}/`)))return!0;if(e.providerApiKeys?.[t])return!0;return Object.keys(e.providerProfileApiKeys??{}).some(e=>e.startsWith(`${t}/`))}const d=e(import.meta.url);let _=null,s=!1,T=!1;const l="active_provider",N="active_profile_id",p=["claude","openai","openrouter","ollama","ollama-cloud","lmstudio","gemini-api","gemini-google","zai","minimax","deepseek"],L={claude:"main",openai:"main",openrouter:"main",ollama:"local","ollama-cloud":"main",lmstudio:"local","gemini-api":"main","gemini-google":"main",zai:"main",minimax:"main",nvidia:"main",deepseek:"main"},c={claude:"claude",openai:"openai",openrouter:"openrouter",ollama:"ollama-local","ollama-cloud":"ollama-cloud",lmstudio:"lmstudio-local","gemini-api":"gemini-api","gemini-google":"gemini-google",zai:"z-ai",minimax:"minimax",nvidia:"nvidia",deepseek:"deepseek"},u={openrouter:"https://openrouter.ai/api/v1",ollama:"http://localhost:11434/v1","ollama-cloud":"http://localhost:11434/v1",lmstudio:"http://localhost:1234/v1","gemini-api":"https://generativelanguage.googleapis.com/v1beta/openai","gemini-google":"https://generativelanguage.googleapis.com/v1beta/openai",zai:"https://api.z.ai/api/coding/paas/v4",minimax:"https://api.minimax.io/anthropic",deepseek:"https://api.deepseek.com/v1"},m={claude:"Claude",openai:"OpenAI",openrouter:"OpenRouter",ollama:"Ollama","ollama-cloud":"Ollama Cloud",lmstudio:"LM Studio","gemini-api":"Gemini API","gemini-google":"Gemini Google",zai:"Z.AI",minimax:"MiniMax",nvidia:"NVIDIA NIM",deepseek:"DeepSeek"},O=["openrouter","ollama","ollama-cloud","gemini-api","gemini-google","zai","minimax","deepseek"];function sanitizeProfileSegment(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"default"}function buildProfileId(e,t){return`${e}/${sanitizeProfileSegment(t)}`}function buildDefaultAgentName(e,t){const n=c[e],i=sanitizeProfileSegment(t);return i===sanitizeProfileSegment(L[e])?n:`${n}-${i}`}function tableExists(e,t){const n=e.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(t);return Boolean(n)}function columnExists(e,t,n){return e.prepare(`PRAGMA table_info(${t})`).all().some(e=>e.name===n)}function migrateTeamUnitsSchema(e){e.exec("PRAGMA foreign_keys = OFF;");try{tableExists(e,"team_domains")&&e.exec("\n INSERT OR IGNORE INTO team_units (\n id, team_id, unit_name, workspace_id, local_orchestrator_agent_id, lead_agent_id, selection_mode, required, created_at, updated_at\n )\n SELECT id, team_id, domain_name, workspace_id, local_orchestrator_agent_id, lead_agent_id, selection_mode, required, created_at, updated_at\n FROM team_domains;\n "),tableExists(e,"team_domain_members")&&e.exec("\n INSERT OR IGNORE INTO team_unit_members (\n id, team_unit_id, agent_id, duty, priority, created_at, updated_at\n )\n SELECT id, team_domain_id, agent_id, duty, priority, created_at, updated_at\n FROM team_domain_members;\n "),tableExists(e,"orchestration_tasks")&&!columnExists(e,"orchestration_tasks","team_unit_id")&&e.exec("ALTER TABLE orchestration_tasks ADD COLUMN team_unit_id TEXT NULL;"),tableExists(e,"orchestration_tasks")&&columnExists(e,"orchestration_tasks","team_domain_id")&&columnExists(e,"orchestration_tasks","team_unit_id")&&e.exec("\n UPDATE orchestration_tasks\n SET team_unit_id = team_domain_id\n WHERE team_unit_id IS NULL AND team_domain_id IS NOT NULL;\n "),function(e){tableExists(e,"orchestration_tasks")&&columnExists(e,"orchestration_tasks","team_domain_id")&&e.exec("\n CREATE TABLE IF NOT EXISTS orchestration_tasks_v8 (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL,\n parent_task_id TEXT NULL,\n scope_type TEXT NOT NULL,\n team_unit_id TEXT NULL,\n assigned_agent_id TEXT NULL,\n title TEXT NOT NULL,\n instructions TEXT NOT NULL,\n status TEXT NOT NULL,\n result_summary TEXT NULL,\n created_at TEXT NOT NULL,\n finished_at TEXT NULL,\n FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE CASCADE,\n FOREIGN KEY (parent_task_id) REFERENCES orchestration_tasks_v8(id) ON DELETE SET NULL,\n FOREIGN KEY (team_unit_id) REFERENCES team_units(id) ON DELETE SET NULL,\n FOREIGN KEY (assigned_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL\n );\n\n INSERT OR REPLACE INTO orchestration_tasks_v8 (\n id, run_id, parent_task_id, scope_type, team_unit_id, assigned_agent_id, title, instructions, status, result_summary, created_at, finished_at\n )\n SELECT id, run_id, parent_task_id, scope_type, team_unit_id, assigned_agent_id, title, instructions, status, result_summary, created_at, finished_at\n FROM orchestration_tasks;\n\n DROP TABLE orchestration_tasks;\n ALTER TABLE orchestration_tasks_v8 RENAME TO orchestration_tasks;\n\n CREATE INDEX IF NOT EXISTS idx_orchestration_tasks_run_id\n ON orchestration_tasks(run_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_tasks_team_unit_id\n ON orchestration_tasks(team_unit_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_tasks_assigned_agent_id\n ON orchestration_tasks(assigned_agent_id);\n ")}(e),tableExists(e,"orchestration_domain_reports")&&e.exec("\n INSERT OR IGNORE INTO orchestration_team_reports (\n id, run_id, team_unit_id, local_orchestrator_agent_id, status, summary, blockers, output, metrics_json, created_at, updated_at, submitted_at\n )\n SELECT id, run_id, team_domain_id, local_orchestrator_agent_id, status, summary, blockers, output, metrics_json, created_at, updated_at, submitted_at\n FROM orchestration_domain_reports;\n "),tableExists(e,"provider_agent_capability_rankings")&&!columnExists(e,"provider_agent_capability_rankings","team_unit_id")&&e.exec("ALTER TABLE provider_agent_capability_rankings ADD COLUMN team_unit_id TEXT NULL;"),tableExists(e,"provider_agent_capability_rankings")&&columnExists(e,"provider_agent_capability_rankings","team_domain_id")&&columnExists(e,"provider_agent_capability_rankings","team_unit_id")&&e.exec("\n UPDATE provider_agent_capability_rankings\n SET team_unit_id = team_domain_id\n WHERE team_unit_id IS NULL AND team_domain_id IS NOT NULL;\n "),function(e){tableExists(e,"provider_agent_capability_rankings")&&columnExists(e,"provider_agent_capability_rankings","team_domain_id")&&e.exec("\n CREATE TABLE IF NOT EXISTS provider_agent_capability_rankings_v8 (\n id TEXT PRIMARY KEY,\n team_unit_id TEXT NULL,\n capability TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n score REAL NOT NULL DEFAULT 0,\n reason TEXT NULL,\n source TEXT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n FOREIGN KEY (team_unit_id) REFERENCES team_units(id) ON DELETE CASCADE,\n FOREIGN KEY (agent_id) REFERENCES provider_agents(id) ON DELETE CASCADE,\n UNIQUE (team_unit_id, capability, agent_id)\n );\n\n INSERT OR REPLACE INTO provider_agent_capability_rankings_v8 (\n id, team_unit_id, capability, agent_id, score, reason, source, created_at, updated_at\n )\n SELECT id, team_unit_id, capability, agent_id, score, reason, source, created_at, updated_at\n FROM provider_agent_capability_rankings;\n\n DROP TABLE provider_agent_capability_rankings;\n ALTER TABLE provider_agent_capability_rankings_v8 RENAME TO provider_agent_capability_rankings;\n\n CREATE INDEX IF NOT EXISTS idx_provider_agent_capability_rankings_team_unit\n ON provider_agent_capability_rankings(team_unit_id);\n CREATE INDEX IF NOT EXISTS idx_provider_agent_capability_rankings_capability\n ON provider_agent_capability_rankings(capability);\n CREATE INDEX IF NOT EXISTS idx_provider_agent_capability_rankings_agent\n ON provider_agent_capability_rankings(agent_id);\n ")}(e),e.exec("\n DROP TABLE IF EXISTS orchestration_domain_reports;\n DROP TABLE IF EXISTS team_domain_members;\n DROP TABLE IF EXISTS team_domains;\n ")}finally{e.exec("PRAGMA foreign_keys = ON;")}tableExists(e,"orchestration_tasks")&&columnExists(e,"orchestration_tasks","team_unit_id")&&e.exec("\n CREATE INDEX IF NOT EXISTS idx_orchestration_tasks_team_unit_id\n ON orchestration_tasks(team_unit_id);\n "),tableExists(e,"provider_agent_capability_rankings")&&columnExists(e,"provider_agent_capability_rankings","team_unit_id")&&e.exec("\n CREATE INDEX IF NOT EXISTS idx_provider_agent_capability_rankings_team_unit\n ON provider_agent_capability_rankings(team_unit_id);\n ")}function getDatabasePath(){return n(a(),"provider-state.sqlite3")}function rowToProfile(e){if(!e)return null;const t=e;return{id:t.id,provider:t.provider,name:t.name,agentName:t.agent_name,baseUrl:t.base_url??void 0,lastModel:t.last_model,createdAt:t.created_at,updatedAt:t.updated_at}}function seedLegacyProfiles(){const e=i(),t=e.providerProfiles,n={...t&&"object"==typeof t&&t.profiles?t.profiles:{}},r={...t&&"object"==typeof t&&t.lastProfileIdByProvider?t.lastProfileIdByProvider:{}},a=(()=>{try{return o().read()}catch{return null}})();for(const t of p){const i=Object.values(n).some(e=>e.provider===t),E=e.providerBaseUrls?.[t],o=e.lastModelByProvider?.[t]??null;if(!(i||e.activeProvider===t||Boolean(E)||null!==o||hasStoredCredentialForProvider(a,t))||i)continue;const d=L[t],_=buildProfileId(t,d),s=(new Date).toISOString();n[_]={id:_,provider:t,name:d,agentName:buildDefaultAgentName(t,d),baseUrl:E??u[t],lastModel:o,createdAt:s,updatedAt:s},r[t]=_}return{version:1,activeProfileId:(t&&"object"==typeof t?t.activeProfileId:void 0)??(e.activeProvider&&p.includes(e.activeProvider)?r[e.activeProvider]:void 0),lastProfileIdByProvider:r,profiles:n}}function migrateFromLegacyConfig(e){const t=i(),n=seedLegacyProfiles(),r=e.prepare("\n INSERT OR REPLACE INTO provider_profiles (\n id, provider, name, agent_name, base_url, last_model, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n "),a=e.prepare("\n INSERT INTO provider_last_profile (provider, profile_id)\n VALUES (?, ?)\n ON CONFLICT(provider) DO UPDATE SET profile_id = excluded.profile_id\n "),E=e.prepare("\n INSERT INTO provider_runtime_state (key, value)\n VALUES (?, ?)\n ON CONFLICT(key) DO UPDATE SET value = excluded.value\n "),o=e.prepare("\n INSERT INTO provider_last_model (provider, last_model, updated_at)\n VALUES (?, ?, ?)\n ON CONFLICT(provider) DO UPDATE SET\n last_model = excluded.last_model,\n updated_at = excluded.updated_at\n "),d=e.prepare("\n INSERT INTO provider_base_url (provider, base_url, updated_at)\n VALUES (?, ?, ?)\n ON CONFLICT(provider) DO UPDATE SET\n base_url = excluded.base_url,\n updated_at = excluded.updated_at\n ");for(const e of Object.values(n.profiles??{}))r.run(e.id,e.provider,e.name,e.agentName,e.baseUrl??null,e.lastModel??null,e.createdAt,e.updatedAt);for(const[e,t]of Object.entries(n.lastProfileIdByProvider??{}))t&&a.run(e,t);n.activeProfileId&&E.run(N,n.activeProfileId);const _=t.activeProvider??(n.activeProfileId?n.profiles?.[n.activeProfileId]?.provider:void 0);_&&E.run(l,_);const s={claude:t.lastClaudeModel??t.lastModelByProvider?.claude??null,openai:t.lastOpenAIModel??t.lastModelByProvider?.openai??null,openrouter:t.lastOpenRouterModel??t.lastModelByProvider?.openrouter??null,ollama:t.lastModelByProvider?.ollama??null,"ollama-cloud":t.lastModelByProvider?.["ollama-cloud"]??null,"gemini-api":t.lastModelByProvider?.["gemini-api"]??null,"gemini-google":t.lastModelByProvider?.["gemini-google"]??null,zai:t.lastModelByProvider?.zai??null,minimax:t.lastModelByProvider?.minimax??null,deepseek:t.lastModelByProvider?.deepseek??null};for(const e of p)o.run(e,s[e]??null,(new Date).toISOString());for(const e of O){const n=t.providerBaseUrls?.[e];"string"==typeof n&&n.trim()&&d.run(e,n.trim(),(new Date).toISOString())}}export function purgeLegacyProviderStateInConfig(){hasLegacyProviderStateInConfig()&&r(e=>({...e,activeProvider:void 0,lastModelByProvider:{},providerBaseUrls:void 0,lastOpenAIModel:void 0,lastClaudeModel:void 0,lastOpenRouterModel:void 0,providerProfiles:void 0}))}export function finalizeProviderProfilesMigration(){ensureInitialized(),purgeLegacyProviderStateInConfig()}function ensureInitialized(){const e=function(){if(T)throw new Error("SQLite no disponible en este runtime.");if(_)return _;let e;E().mkdirSync(a(),{mode:448});try{e=d("node:sqlite")}catch(e){throw T=!0,e}return _=new e.DatabaseSync(getDatabasePath()),_}();if(s)return e;e.exec("\n PRAGMA journal_mode = WAL;\n PRAGMA foreign_keys = ON;\n PRAGMA synchronous = NORMAL;\n\n CREATE TABLE IF NOT EXISTS provider_profiles (\n id TEXT PRIMARY KEY,\n provider TEXT NOT NULL,\n name TEXT NOT NULL,\n agent_name TEXT NOT NULL,\n base_url TEXT NULL,\n last_model TEXT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS provider_last_profile (\n provider TEXT PRIMARY KEY,\n profile_id TEXT NOT NULL,\n FOREIGN KEY (profile_id) REFERENCES provider_profiles(id) ON DELETE CASCADE\n );\n\n CREATE TABLE IF NOT EXISTS provider_runtime_state (\n key TEXT PRIMARY KEY,\n value TEXT NULL\n );\n\n CREATE TABLE IF NOT EXISTS provider_last_model (\n provider TEXT PRIMARY KEY,\n last_model TEXT NULL,\n updated_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS provider_base_url (\n provider TEXT PRIMARY KEY,\n base_url TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS provider_workspaces (\n id TEXT PRIMARY KEY,\n provider TEXT NOT NULL UNIQUE,\n display_name TEXT NOT NULL,\n domain_focus TEXT NULL,\n is_enabled INTEGER NOT NULL DEFAULT 1,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS provider_agents (\n id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n profile_id TEXT NOT NULL,\n name TEXT NOT NULL,\n role_kind TEXT NULL,\n system_prompt TEXT NULL,\n model_override TEXT NULL,\n tool_policy TEXT NULL,\n autonomy_level TEXT NULL,\n is_orchestrator INTEGER NOT NULL DEFAULT 0,\n is_enabled INTEGER NOT NULL DEFAULT 1,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n FOREIGN KEY (workspace_id) REFERENCES provider_workspaces(id) ON DELETE CASCADE,\n FOREIGN KEY (profile_id) REFERENCES provider_profiles(id) ON DELETE CASCADE,\n UNIQUE (workspace_id, name)\n );\n\n CREATE INDEX IF NOT EXISTS idx_provider_agents_workspace_id\n ON provider_agents(workspace_id);\n CREATE INDEX IF NOT EXISTS idx_provider_agents_profile_id\n ON provider_agents(profile_id);\n\n CREATE TABLE IF NOT EXISTS provider_agent_capabilities (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n capability TEXT NOT NULL,\n weight REAL NOT NULL DEFAULT 1,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n FOREIGN KEY (agent_id) REFERENCES provider_agents(id) ON DELETE CASCADE,\n UNIQUE (agent_id, capability)\n );\n\n CREATE INDEX IF NOT EXISTS idx_provider_agent_capabilities_agent_id\n ON provider_agent_capabilities(agent_id);\n\n CREATE TABLE IF NOT EXISTS teams (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL UNIQUE,\n description TEXT NULL,\n global_orchestrator_agent_id TEXT NULL,\n is_enabled INTEGER NOT NULL DEFAULT 1,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n FOREIGN KEY (global_orchestrator_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL\n );\n\n CREATE TABLE IF NOT EXISTS team_units (\n id TEXT PRIMARY KEY,\n team_id TEXT NOT NULL,\n unit_name TEXT NOT NULL,\n workspace_id TEXT NULL,\n local_orchestrator_agent_id TEXT NULL,\n lead_agent_id TEXT NULL,\n selection_mode TEXT NOT NULL DEFAULT 'manual',\n required INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n FOREIGN KEY (team_id) REFERENCES teams(id) ON DELETE CASCADE,\n FOREIGN KEY (workspace_id) REFERENCES provider_workspaces(id) ON DELETE SET NULL,\n FOREIGN KEY (local_orchestrator_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL,\n FOREIGN KEY (lead_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL,\n UNIQUE (team_id, unit_name)\n );\n\n CREATE INDEX IF NOT EXISTS idx_team_units_team_id\n ON team_units(team_id);\n CREATE INDEX IF NOT EXISTS idx_team_units_workspace_id\n ON team_units(workspace_id);\n CREATE INDEX IF NOT EXISTS idx_team_units_local_orchestrator_agent_id\n ON team_units(local_orchestrator_agent_id);\n CREATE INDEX IF NOT EXISTS idx_team_units_lead_agent_id\n ON team_units(lead_agent_id);\n\n CREATE TABLE IF NOT EXISTS team_unit_members (\n id TEXT PRIMARY KEY,\n team_unit_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n duty TEXT NULL,\n priority INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n FOREIGN KEY (team_unit_id) REFERENCES team_units(id) ON DELETE CASCADE,\n FOREIGN KEY (agent_id) REFERENCES provider_agents(id) ON DELETE CASCADE,\n UNIQUE (team_unit_id, agent_id)\n );\n\n CREATE INDEX IF NOT EXISTS idx_team_unit_members_team_unit_id\n ON team_unit_members(team_unit_id);\n CREATE INDEX IF NOT EXISTS idx_team_unit_members_agent_id\n ON team_unit_members(agent_id);\n\n CREATE TABLE IF NOT EXISTS orchestration_runs (\n id TEXT PRIMARY KEY,\n team_id TEXT NOT NULL,\n goal TEXT NOT NULL,\n global_orchestrator_agent_id TEXT NULL,\n status TEXT NOT NULL,\n created_at TEXT NOT NULL,\n started_at TEXT NULL,\n finished_at TEXT NULL,\n FOREIGN KEY (team_id) REFERENCES teams(id) ON DELETE CASCADE,\n FOREIGN KEY (global_orchestrator_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_orchestration_runs_team_id\n ON orchestration_runs(team_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_runs_status\n ON orchestration_runs(status);\n\n CREATE TABLE IF NOT EXISTS orchestration_tasks (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL,\n parent_task_id TEXT NULL,\n scope_type TEXT NOT NULL,\n team_unit_id TEXT NULL,\n assigned_agent_id TEXT NULL,\n title TEXT NOT NULL,\n instructions TEXT NOT NULL,\n status TEXT NOT NULL,\n result_summary TEXT NULL,\n created_at TEXT NOT NULL,\n finished_at TEXT NULL,\n FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE CASCADE,\n FOREIGN KEY (parent_task_id) REFERENCES orchestration_tasks(id) ON DELETE SET NULL,\n FOREIGN KEY (team_unit_id) REFERENCES team_units(id) ON DELETE SET NULL,\n FOREIGN KEY (assigned_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_orchestration_tasks_run_id\n ON orchestration_tasks(run_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_tasks_assigned_agent_id\n ON orchestration_tasks(assigned_agent_id);\n\n CREATE TABLE IF NOT EXISTS orchestration_messages (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL,\n task_id TEXT NULL,\n from_agent_id TEXT NULL,\n to_agent_id TEXT NULL,\n message_type TEXT NOT NULL,\n content TEXT NOT NULL,\n created_at TEXT NOT NULL,\n FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE CASCADE,\n FOREIGN KEY (task_id) REFERENCES orchestration_tasks(id) ON DELETE SET NULL,\n FOREIGN KEY (from_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL,\n FOREIGN KEY (to_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_orchestration_messages_run_id\n ON orchestration_messages(run_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_messages_task_id\n ON orchestration_messages(task_id);\n\n CREATE TABLE IF NOT EXISTS orchestration_task_results (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL,\n task_id TEXT NOT NULL,\n agent_id TEXT NULL,\n result_type TEXT NOT NULL,\n status TEXT NOT NULL,\n summary TEXT NULL,\n content TEXT NULL,\n metadata_json TEXT NULL,\n created_at TEXT NOT NULL,\n FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE CASCADE,\n FOREIGN KEY (task_id) REFERENCES orchestration_tasks(id) ON DELETE CASCADE,\n FOREIGN KEY (agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_orchestration_task_results_run_id\n ON orchestration_task_results(run_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_task_results_task_id\n ON orchestration_task_results(task_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_task_results_agent_id\n ON orchestration_task_results(agent_id);\n\n CREATE TABLE IF NOT EXISTS orchestration_team_reports (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL,\n team_unit_id TEXT NOT NULL,\n local_orchestrator_agent_id TEXT NULL,\n status TEXT NOT NULL,\n summary TEXT NOT NULL,\n blockers TEXT NULL,\n output TEXT NULL,\n metrics_json TEXT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n submitted_at TEXT NULL,\n FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE CASCADE,\n FOREIGN KEY (team_unit_id) REFERENCES team_units(id) ON DELETE CASCADE,\n FOREIGN KEY (local_orchestrator_agent_id) REFERENCES provider_agents(id) ON DELETE SET NULL,\n UNIQUE (run_id, team_unit_id)\n );\n\n CREATE INDEX IF NOT EXISTS idx_orchestration_team_reports_run_id\n ON orchestration_team_reports(run_id);\n CREATE INDEX IF NOT EXISTS idx_orchestration_team_reports_team_unit_id\n ON orchestration_team_reports(team_unit_id);\n\n CREATE TABLE IF NOT EXISTS orchestration_run_reports (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL UNIQUE,\n status TEXT NOT NULL,\n summary TEXT NOT NULL,\n output TEXT NULL,\n risks TEXT NULL,\n next_steps TEXT NULL,\n metrics_json TEXT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n submitted_at TEXT NULL,\n FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE CASCADE\n );\n\n CREATE INDEX IF NOT EXISTS idx_orchestration_run_reports_run_id\n ON orchestration_run_reports(run_id);\n\n CREATE TABLE IF NOT EXISTS provider_agent_capability_rankings (\n id TEXT PRIMARY KEY,\n team_unit_id TEXT NULL,\n capability TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n score REAL NOT NULL DEFAULT 0,\n reason TEXT NULL,\n source TEXT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n FOREIGN KEY (team_unit_id) REFERENCES team_units(id) ON DELETE CASCADE,\n FOREIGN KEY (agent_id) REFERENCES provider_agents(id) ON DELETE CASCADE,\n UNIQUE (team_unit_id, capability, agent_id)\n );\n\n CREATE INDEX IF NOT EXISTS idx_provider_agent_capability_rankings_capability\n ON provider_agent_capability_rankings(capability);\n CREATE INDEX IF NOT EXISTS idx_provider_agent_capability_rankings_agent\n ON provider_agent_capability_rankings(agent_id);\n\n CREATE TABLE IF NOT EXISTS secure_storage (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS projects (\n path TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n created_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS permission_rules (\n id TEXT PRIMARY KEY,\n scope TEXT NOT NULL,\n scope_path TEXT NULL,\n tool_name TEXT NOT NULL,\n behavior TEXT NOT NULL,\n created_at TEXT NOT NULL,\n expires_at TEXT NULL,\n UNIQUE (scope, scope_path, tool_name)\n );\n\n CREATE INDEX IF NOT EXISTS idx_permission_rules_scope\n ON permission_rules(scope, scope_path);\n CREATE INDEX IF NOT EXISTS idx_permission_rules_tool_name\n ON permission_rules(tool_name);\n\n CREATE TABLE IF NOT EXISTS permission_mode_config (\n id TEXT PRIMARY KEY,\n scope TEXT NOT NULL,\n scope_path TEXT NULL,\n mode TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n UNIQUE (scope, scope_path)\n );\n\n CREATE TABLE IF NOT EXISTS trusted_directories (\n path TEXT PRIMARY KEY,\n trust_level TEXT NOT NULL DEFAULT 'full',\n created_at TEXT NOT NULL\n );\n "),migrateTeamUnitsSchema(e);const n=e.prepare("PRAGMA user_version").get();(n?.user_version??0)<8&&e.exec("PRAGMA user_version = 8"),function(e){const n=(new Date).toISOString(),i=e.prepare("\n INSERT OR IGNORE INTO provider_workspaces (\n id, provider, display_name, domain_focus, is_enabled, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?)\n ");for(const e of p)i.run(t(),e,m[e],null,1,n,n)}(e);const i=e.prepare("SELECT COUNT(*) AS count FROM provider_profiles").get();if(0===(i?.count??0))migrateFromLegacyConfig(e);else{const t=e.prepare("SELECT COUNT(*) AS count FROM provider_last_model").get();0===(t?.count??0)&&migrateFromLegacyConfig(e);const n=e.prepare("SELECT COUNT(*) AS count FROM provider_base_url").get();0===(n?.count??0)&&migrateFromLegacyConfig(e)}return purgeLegacyProviderStateInConfig(),s=!0,e}export class ProviderProfilesDb{static instance=null;db;constructor(){this.db=ensureInitialized()}static async get(){return ProviderProfilesDb.instance||(ProviderProfilesDb.instance=new ProviderProfilesDb),ProviderProfilesDb.instance}}export function getProviderProfilesDbPath(){return getDatabasePath()}export function getProviderProfilesStorageBackend(){try{return ensureInitialized(),"sqlite"}catch{return"legacy"}}export function hasLegacyProviderStateInConfig(){try{const e=i();return Boolean(e.activeProvider||e.lastClaudeModel||e.lastOpenAIModel||e.lastOpenRouterModel||Object.keys(e.lastModelByProvider??{}).length>0||Object.keys(e.providerBaseUrls??{}).length>0||e.providerProfiles?.activeProfileId||Object.keys(e.providerProfiles?.profiles??{}).length>0||Object.keys(e.providerProfiles?.lastProfileIdByProvider??{}).length>0)}catch{return!1}}export function getProviderProfilesStorageMode(){return"sqlite"!==getProviderProfilesStorageBackend()?"legacy":hasLegacyProviderStateInConfig()?"sqlite-migration-pending":"sqlite-only"}export function readProviderProfilesState(){let e;try{e=ensureInitialized()}catch{return seedLegacyProfiles()}const t=e.prepare("SELECT id, provider, name, agent_name, base_url, last_model, created_at, updated_at\n FROM provider_profiles\n ORDER BY provider, created_at, id").all().map(rowToProfile).filter(e=>null!==e),n=e.prepare("SELECT provider, profile_id FROM provider_last_profile").all(),i=e.prepare(`SELECT value FROM provider_runtime_state WHERE key = '${N}'`).get();return{version:1,activeProfileId:i?.value,lastProfileIdByProvider:Object.fromEntries(n.map(e=>[e.provider,e.profile_id])),profiles:Object.fromEntries(t.map(e=>[e.id,e]))}}export function writeProviderProfilesState(e){let t;try{t=ensureInitialized()}catch{return}const n=Object.values(e.profiles??{}),i=0===n.length;t.exec("BEGIN");try{t.exec("DELETE FROM provider_last_profile"),t.exec(`DELETE FROM provider_runtime_state WHERE key = '${N}'`),t.exec("DELETE FROM provider_profiles"),i&&(t.exec(`DELETE FROM provider_runtime_state WHERE key = '${l}'`),t.exec("DELETE FROM provider_last_model"),t.exec("DELETE FROM provider_base_url"));const r=t.prepare("\n INSERT INTO provider_profiles (\n id, provider, name, agent_name, base_url, last_model, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n ");for(const e of n)r.run(e.id,e.provider,e.name,e.agentName,e.baseUrl??null,e.lastModel??null,e.createdAt,e.updatedAt);const a=t.prepare("\n INSERT INTO provider_last_profile (provider, profile_id)\n VALUES (?, ?)\n ");for(const[t,n]of Object.entries(e.lastProfileIdByProvider??{}))n&&a.run(t,n);e.activeProfileId&&t.prepare(`\n INSERT INTO provider_runtime_state (key, value)\n VALUES ('${N}', ?)\n `).run(e.activeProfileId),t.exec("COMMIT")}catch(e){throw t.exec("ROLLBACK"),e}}export function getStoredActiveProviderPreference(){const e=function(e){try{const t=ensureInitialized().prepare("SELECT value FROM provider_runtime_state WHERE key = ?").get(e);return t?.value??null}catch{return null}}(l);return null!==e?e:null}export function setStoredActiveProviderPreference(e){!function(e,t){try{const n=ensureInitialized();if(null===t)return void n.prepare("DELETE FROM provider_runtime_state WHERE key = ?").run(e);n.prepare("\n INSERT INTO provider_runtime_state (key, value)\n VALUES (?, ?)\n ON CONFLICT(key) DO UPDATE SET value = excluded.value\n ").run(e,t)}catch{}}(l,e)}export function getStoredLastModelForProvider(e){try{const t=ensureInitialized().prepare("SELECT last_model FROM provider_last_model WHERE provider = ?").get(e);if(t&&Object.prototype.hasOwnProperty.call(t,"last_model"))return t.last_model??null}catch{return}}export function setStoredLastModelForProvider(e,t){!function(e,t){try{ensureInitialized().prepare("\n INSERT INTO provider_last_model (provider, last_model, updated_at)\n VALUES (?, ?, ?)\n ON CONFLICT(provider) DO UPDATE SET\n last_model = excluded.last_model,\n updated_at = excluded.updated_at\n ").run(e,t,(new Date).toISOString())}catch{}}(e,t)}export function getStoredProviderBaseUrl(e){try{const t=ensureInitialized().prepare("SELECT base_url FROM provider_base_url WHERE provider = ?").get(e);if(t?.base_url?.trim())return t.base_url.trim()}catch{return}}export function setStoredProviderBaseUrl(e,t){try{ensureInitialized().prepare("\n INSERT INTO provider_base_url (provider, base_url, updated_at)\n VALUES (?, ?, ?)\n ON CONFLICT(provider) DO UPDATE SET\n base_url = excluded.base_url,\n updated_at = excluded.updated_at\n ").run(e,t,(new Date).toISOString())}catch{}}export function clearStoredProviderBaseUrl(e){try{ensureInitialized().prepare("DELETE FROM provider_base_url WHERE provider = ?").run(e)}catch{}}
@@ -1 +1 @@
1
- import{jsxs as e}from"react/jsx-runtime";import o from"chalk";import r from"figures";import{color as s,Text as a}from"../ink.js";import{getAccountInformation as n,hasStoredProviderApiKey as l,hasStoredProviderOAuthTokens as t,isClaudeAISubscriber as i}from"./auth.js";import{getLargeMemoryFiles as u,getMemoryFiles as c,MAX_MEMORY_CHARACTER_COUNT as p}from"./claudemd.js";import{getDoctorDiagnostic as d}from"./doctorDiagnostic.js";import{getAWSRegion as m,getDefaultVertexRegion as v,isEnvTruthy as f}from"./envUtils.js";import{getDisplayPath as h}from"./file.js";import{formatNumber as b}from"./format.js";import{getIdeClientName as E,isJetBrainsIde as _,toIDEDisplayName as A}from"./ide.js";import{getClaudeAiUserDefaultModelDescription as C,modelDisplayString as g}from"./model/model.js";import{checkProviderHealth as D}from"./model/providerModels.js";import{getAPIProvider as S,isOllamaCloudProviderConfigured as O,isMiniMaxProviderConfigured as R,isOllamaProviderConfigured as I,isOpenRouterProviderConfigured as L,isZAIProviderConfigured as P}from"./model/providers.js";import{getConfiguredProviderBaseUrl as T}from"./model/providerBaseUrls.js";import{getActiveProviderProfile as U}from"./model/providerProfiles.js";import{getProviderProfilesDbPath as y,getProviderProfilesStorageBackend as j,getProviderProfilesStorageMode as x,getStoredActiveProviderPreference as $}from"./model/providerProfilesDb.js";import{getMTLSConfig as N}from"./mtls.js";import{checkInstall as M}from"./nativeInstaller/index.js";import{getProxyUrl as B}from"./proxy.js";import{SandboxManager as k}from"./sandbox/sandbox-adapter.js";import{getSecureStorage as K}from"./secureStorage/index.js";import{getLegacyCredentialsFilePath as H,getSecureStorageDbPath as z,getSecureStorageKeyPath as X,hasLegacyCredentialsFile as w,isSecureStorageEncrypted as F}from"./secureStorage/sqliteStorage.js";import{getSettingsWithAllErrors as V}from"./settings/allErrors.js";import{getEnabledSettingSources as q,getSettingSourceDisplayNameCapitalized as Y}from"./settings/constants.js";import{getManagedFileSettingsPresence as G,getPolicySettingsOrigin as Q,getSettingsForSource as W}from"./settings/settings.js";export function buildSandboxProperties(){return[{label:"Bash Sandbox",value:k.isSandboxingEnabled()?"Enabled":"Disabled"}]}export function buildIDEProperties(o,n=null,l){const t=o?.find(e=>"ide"===e.name);if(n){const o=A(n.ideType),i=_(n.ideType)?"plugin":"extensión";if(n.error)return[{label:"IDE",value:e(a,{children:[s("error",l)(r.cross)," Error al instalar ",o," ",i,": ",n.error,"\n","Por favor, reinicie su IDE e inténtelo de nuevo."]})}];if(n.installed)return t&&"connected"===t.type?n.installedVersion!==t.serverInfo?.version?[{label:"IDE",value:`Conectado a ${o} (${i}) versión ${n.installedVersion} (versión servidor: ${t.serverInfo?.version})`}]:[{label:"IDE",value:`Conectado a ${o} (${i}) versión ${n.installedVersion}`}]:[{label:"IDE",value:`Instalado ${o} (${i})`}]}else if(t){const e=E(t)??"IDE";return"connected"===t.type?[{label:"IDE",value:`Conectado a la extensión ${e}`}]:[{label:"IDE",value:`${s("error",l)(r.cross)} No conectado a ${e}`}]}return[]}export function buildMcpProperties(e=[],o){const r=e.filter(e=>"ide"!==e.name);if(!r.length)return[];const a={connected:0,pending:0,needsAuth:0,failed:0};for(const e of r)"connected"===e.type?a.connected++:"pending"===e.type?a.pending++:"needs-auth"===e.type?a.needsAuth++:a.failed++;const n=[];return a.connected&&n.push(s("success",o)(`${a.connected} conectados`)),a.needsAuth&&n.push(s("warning",o)(`${a.needsAuth} requieren autenticación`)),a.pending&&n.push(s("inactive",o)(`${a.pending} pendientes`)),a.failed&&n.push(s("error",o)(`${a.failed} fallidos`)),[{label:"Servidores MCP",value:`${n.join(", ")} ${s("inactive",o)("· /mcp")}`}]}export async function buildMemoryDiagnostics(){const e=await c(),o=u(e),r=[];return o.forEach(e=>{const o=h(e.path);r.push(`${o} pesado impactará el rendimiento (${b(e.content.length)} caracteres > ${b(p)})`)}),r}export function buildSettingSourcesProperties(){return[{label:"Fuentes de ajustes",value:q().filter(e=>{const o=W(e);return null!==o&&Object.keys(o).length>0}).map(e=>{if("policySettings"===e){const e=Q();if(null===e)return null;switch(e){case"remote":return"Ajustes corporativos (remoto)";case"plist":return"Ajustes corporativos (plist)";case"hklm":return"Ajustes corporativos (HKLM)";case"file":{const{hasBase:e,hasDropIns:o}=G();return e&&o?"Ajustes corporativos (archivo + complementos)":o?"Ajustes corporativos (complementos)":"Ajustes corporativos (archivo)"}case"hkcu":return"Ajustes corporativos (HKCU)"}}return Y(e)}).filter(e=>null!==e)}]}export async function buildInstallationDiagnostics(){return(await M()).map(e=>e.message)}export async function buildInstallationHealthDiagnostics(){const e=await d(),o=[],{errors:r}=V();if(r.length>0){const e=Array.from(new Set(r.map(e=>e.file))).join(", ");o.push(`Se encontraron archivos de ajustes inválidos: ${e}. Serán ignorados.`)}e.warnings.forEach(e=>{o.push(e.issue)});const s=await async function(){const e=function(){const e=new Set,o=$();L()&&e.add("openrouter");I()&&e.add("ollama");O()&&e.add("ollama-cloud");P()&&e.add("zai");R()&&e.add("minimax");const r=S();"openrouter"!==r&&"openrouter"!==o||e.add("openrouter");"ollama"!==r&&"ollama"!==o||e.add("ollama");"ollama-cloud"!==r&&"ollama-cloud"!==o||e.add("ollama-cloud");"zai"!==r&&"zai"!==o||e.add("zai");"minimax"!==r&&"minimax"!==o||e.add("minimax");return Array.from(e)}();if(0===e.length)return[];return(await Promise.all(e.map(e=>D(e)))).map(formatProviderHealthDiagnostic)}();return o.push(...s),!1===e.hasUpdatePermissions&&o.push("Sin permisos de escritura para auto-actualizaciones (requiere sudo)"),o}function formatProviderHealthDiagnostic(e){switch(e.state){case"healthy":return`${e.label}: OK (${e.message})`;case"needs-setup":case"rate-limited":case"unreachable":return`${e.label}: ${e.message}`}}export function buildAccountProperties(){const e=n();if(!e)return[];const o=[];return e.subscription&&o.push({label:"Cuenta",value:`${e.subscription}`}),e.tokenSource&&o.push({label:"Token",value:e.tokenSource}),e.apiKeySource&&o.push({label:"API Key",value:e.apiKeySource}),e.organization&&!process.env.IS_DEMO&&o.push({label:"Organización",value:e.organization}),e.email&&!process.env.IS_DEMO&&o.push({label:"Correo",value:e.email}),o}export function buildAPIProviderProperties(){const e=S(),o=[],r=j(),s=x();if(o.push({label:"Persistencia providers",value:"sqlite"===r?"sqlite-only"===s?"SQLite-only":"SQLite (migracion pendiente)":"Legacy fallback"}),o.push({label:"Provider DB",value:y()}),o.push({label:"Credenciales providers",value:"sqlite"===K().name?"SQLite (cifrado local)":K().name}),"sqlite"===K().name&&(K().read(),o.push({label:"Credenciales DB",value:z()}),o.push({label:"Clave cifrado",value:X()}),o.push({label:"Estado cifrado credenciales",value:F()?"Cifrado activo":"Sin payload o pendiente"}),o.push({label:"Legacy credentials file",value:w()?`Presente (${H()})`:"No presente"})),"firstParty"!==e){const r={bedrock:"AWS Bedrock",vertex:"Google Vertex AI",foundry:"Microsoft Foundry",openai:"OpenAI / Codex",openrouter:"OpenRouter",ollama:"Ollama","ollama-cloud":"Ollama Cloud",zai:"Z.AI",minimax:"MiniMax"}[e]||e;o.push({label:"Proveedor API",value:r})}if("firstParty"===e){const e=process.env.ANTHROPIC_BASE_URL;e&&o.push({label:"Anthropic base URL",value:e})}else if("bedrock"===e){const e=process.env.BEDROCK_BASE_URL;e&&o.push({label:"Bedrock base URL",value:e}),o.push({label:"AWS region",value:m()}),(f(process.env.CONTEXT_CODE_SKIP_BEDROCK_AUTH)||f(process.env.CLAUDE_CODE_SKIP_BEDROCK_AUTH))&&o.push({value:"AWS auth skipped"})}else if("vertex"===e){const e=process.env.VERTEX_BASE_URL;e&&o.push({label:"Vertex base URL",value:e});const r=process.env.ANTHROPIC_VERTEX_PROJECT_ID;r&&o.push({label:"GCP project",value:r}),o.push({label:"Default region",value:v()}),(f(process.env.CONTEXT_CODE_SKIP_VERTEX_AUTH)||f(process.env.CLAUDE_CODE_SKIP_VERTEX_AUTH))&&o.push({value:"GCP auth skipped"})}else if("foundry"===e){const e=process.env.ANTHROPIC_FOUNDRY_BASE_URL;e&&o.push({label:"Microsoft Foundry base URL",value:e});const r=process.env.ANTHROPIC_FOUNDRY_RESOURCE;r&&o.push({label:"Microsoft Foundry resource",value:r}),(f(process.env.CONTEXT_CODE_SKIP_FOUNDRY_AUTH)||f(process.env.CLAUDE_CODE_SKIP_FOUNDRY_AUTH))&&o.push({value:"Microsoft Foundry auth skipped"})}else if("openai"===e){const e=process.env.OPENAI_BASE_URL;e&&o.push({label:"OpenAI base URL",value:e})}else if("openrouter"===e){const e=process.env.OPENROUTER_BASE_URL||T("openrouter");o.push({label:"OpenRouter base URL",value:e})}else if("ollama"===e){const e=process.env.OLLAMA_BASE_URL||T("ollama");o.push({label:"Ollama base URL",value:e})}else if("ollama-cloud"===e){const e=process.env.OLLAMA_BASE_URL||T("ollama-cloud");o.push({label:"Ollama Cloud base URL",value:e})}else if("zai"===e){const e=process.env.ZAI_BASE_URL||T("zai");o.push({label:"Z.AI base URL",value:e})}else if("minimax"===e){const e=process.env.MINIMAX_BASE_URL||T("minimax");o.push({label:"MiniMax base URL",value:e})}const a=U();if(a&&(a.provider===e||"firstParty"===e&&"claude"===a.provider)&&a){o.push({label:"Perfil activo",value:`${a.name} (${a.agentName})`}),o.push({label:"Modelo guardado",value:a.lastModel||"Sin modelo guardado"});let e="No aplica";"openai"===a.provider?e=t(a.provider,a.id)?"Configuradas":"No configuradas":"openrouter"!==a.provider&&"zai"!==a.provider&&"minimax"!==a.provider||(e=l(a.provider,a.id)?"Configuradas":"No configuradas"),o.push({label:"Credenciales por perfil",value:e})}const n=B();n&&o.push({label:"Proxy",value:n});const i=N();if(process.env.NODE_EXTRA_CA_CERTS&&o.push({label:"Additional CA cert(s)",value:process.env.NODE_EXTRA_CA_CERTS}),i){const e=process.env.CONTEXT_CODE_CLIENT_CERT??process.env.CLAUDE_CODE_CLIENT_CERT;i.cert&&e&&o.push({label:"mTLS client cert",value:e});const r=process.env.CONTEXT_CODE_CLIENT_KEY??process.env.CLAUDE_CODE_CLIENT_KEY;i.key&&r&&o.push({label:"mTLS client key",value:r})}return o}export function getModelDisplayLabel(e){let r=g(e);if(null===e&&i()){const e=C();r=`${o.bold("Default")} ${e}`}return r}
1
+ import{jsxs as e}from"react/jsx-runtime";import o from"chalk";import r from"figures";import{color as s,Text as a}from"../ink.js";import{getAccountInformation as n,hasStoredProviderApiKey as l,hasStoredProviderOAuthTokens as t,isClaudeAISubscriber as i}from"./auth.js";import{getLargeMemoryFiles as u,getMemoryFiles as c,MAX_MEMORY_CHARACTER_COUNT as p}from"./claudemd.js";import{getDoctorDiagnostic as d}from"./doctorDiagnostic.js";import{getAWSRegion as m,getDefaultVertexRegion as v,isEnvTruthy as f}from"./envUtils.js";import{getDisplayPath as b}from"./file.js";import{formatNumber as h}from"./format.js";import{getIdeClientName as E,isJetBrainsIde as _,toIDEDisplayName as A}from"./ide.js";import{getClaudeAiUserDefaultModelDescription as C,modelDisplayString as S}from"./model/model.js";import{checkProviderHealth as D}from"./model/providerModels.js";import{getAPIProvider as g,isOllamaCloudProviderConfigured as R,isMiniMaxProviderConfigured as O,isOllamaProviderConfigured as L,isOpenRouterProviderConfigured as I,isZAIProviderConfigured as U}from"./model/providers.js";import{getConfiguredProviderBaseUrl as T}from"./model/providerBaseUrls.js";import{getActiveProviderProfile as P}from"./model/providerProfiles.js";import{getProviderProfilesDbPath as y,getProviderProfilesStorageBackend as j,getProviderProfilesStorageMode as x,getStoredActiveProviderPreference as $}from"./model/providerProfilesDb.js";import{getMTLSConfig as N}from"./mtls.js";import{checkInstall as M}from"./nativeInstaller/index.js";import{getProxyUrl as B}from"./proxy.js";import{SandboxManager as k}from"./sandbox/sandbox-adapter.js";import{getSecureStorage as K}from"./secureStorage/index.js";import{getLegacyCredentialsFilePath as H,getSecureStorageDbPath as z,getSecureStorageKeyPath as X,hasLegacyCredentialsFile as w,isSecureStorageEncrypted as F}from"./secureStorage/sqliteStorage.js";import{getSettingsWithAllErrors as V}from"./settings/allErrors.js";import{getEnabledSettingSources as q,getSettingSourceDisplayNameCapitalized as Y}from"./settings/constants.js";import{getManagedFileSettingsPresence as G,getPolicySettingsOrigin as Q,getSettingsForSource as W}from"./settings/settings.js";export function buildSandboxProperties(){return[{label:"Bash Sandbox",value:k.isSandboxingEnabled()?"Enabled":"Disabled"}]}export function buildIDEProperties(o,n=null,l){const t=o?.find(e=>"ide"===e.name);if(n){const o=A(n.ideType),i=_(n.ideType)?"plugin":"extensión";if(n.error)return[{label:"IDE",value:e(a,{children:[s("error",l)(r.cross)," Error al instalar ",o," ",i,": ",n.error,"\n","Por favor, reinicie su IDE e inténtelo de nuevo."]})}];if(n.installed)return t&&"connected"===t.type?n.installedVersion!==t.serverInfo?.version?[{label:"IDE",value:`Conectado a ${o} (${i}) versión ${n.installedVersion} (versión servidor: ${t.serverInfo?.version})`}]:[{label:"IDE",value:`Conectado a ${o} (${i}) versión ${n.installedVersion}`}]:[{label:"IDE",value:`Instalado ${o} (${i})`}]}else if(t){const e=E(t)??"IDE";return"connected"===t.type?[{label:"IDE",value:`Conectado a la extensión ${e}`}]:[{label:"IDE",value:`${s("error",l)(r.cross)} No conectado a ${e}`}]}return[]}export function buildMcpProperties(e=[],o){const r=e.filter(e=>"ide"!==e.name);if(!r.length)return[];const a={connected:0,pending:0,needsAuth:0,failed:0};for(const e of r)"connected"===e.type?a.connected++:"pending"===e.type?a.pending++:"needs-auth"===e.type?a.needsAuth++:a.failed++;const n=[];return a.connected&&n.push(s("success",o)(`${a.connected} conectados`)),a.needsAuth&&n.push(s("warning",o)(`${a.needsAuth} requieren autenticación`)),a.pending&&n.push(s("inactive",o)(`${a.pending} pendientes`)),a.failed&&n.push(s("error",o)(`${a.failed} fallidos`)),[{label:"Servidores MCP",value:`${n.join(", ")} ${s("inactive",o)("· /mcp")}`}]}export async function buildMemoryDiagnostics(){const e=await c(),o=u(e),r=[];return o.forEach(e=>{const o=b(e.path);r.push(`${o} pesado impactará el rendimiento (${h(e.content.length)} caracteres > ${h(p)})`)}),r}export function buildSettingSourcesProperties(){return[{label:"Fuentes de ajustes",value:q().filter(e=>{const o=W(e);return null!==o&&Object.keys(o).length>0}).map(e=>{if("policySettings"===e){const e=Q();if(null===e)return null;switch(e){case"remote":return"Ajustes corporativos (remoto)";case"plist":return"Ajustes corporativos (plist)";case"hklm":return"Ajustes corporativos (HKLM)";case"file":{const{hasBase:e,hasDropIns:o}=G();return e&&o?"Ajustes corporativos (archivo + complementos)":o?"Ajustes corporativos (complementos)":"Ajustes corporativos (archivo)"}case"hkcu":return"Ajustes corporativos (HKCU)"}}return Y(e)}).filter(e=>null!==e)}]}export async function buildInstallationDiagnostics(){return(await M()).map(e=>e.message)}export async function buildInstallationHealthDiagnostics(){const e=await d(),o=[],{errors:r}=V();if(r.length>0){const e=Array.from(new Set(r.map(e=>e.file))).join(", ");o.push(`Se encontraron archivos de ajustes inválidos: ${e}. Serán ignorados.`)}e.warnings.forEach(e=>{o.push(e.issue)});const s=await async function(){const e=function(){const e=new Set,o=$();I()&&e.add("openrouter");L()&&e.add("ollama");R()&&e.add("ollama-cloud");U()&&e.add("zai");O()&&e.add("minimax");const r=g();"openrouter"!==r&&"openrouter"!==o||e.add("openrouter");"ollama"!==r&&"ollama"!==o||e.add("ollama");"ollama-cloud"!==r&&"ollama-cloud"!==o||e.add("ollama-cloud");"zai"!==r&&"zai"!==o||e.add("zai");"minimax"!==r&&"minimax"!==o||e.add("minimax");return Array.from(e)}();if(0===e.length)return[];return(await Promise.all(e.map(e=>D(e)))).map(formatProviderHealthDiagnostic)}();return o.push(...s),!1===e.hasUpdatePermissions&&o.push("Sin permisos de escritura para auto-actualizaciones (requiere sudo)"),o}function formatProviderHealthDiagnostic(e){switch(e.state){case"healthy":return`${e.label}: OK (${e.message})`;case"needs-setup":case"rate-limited":case"unreachable":return`${e.label}: ${e.message}`}}export function buildAccountProperties(){const e=n();if(!e)return[];const o=[];return e.subscription&&o.push({label:"Cuenta",value:`${e.subscription}`}),e.tokenSource&&o.push({label:"Token",value:e.tokenSource}),e.apiKeySource&&o.push({label:"API Key",value:e.apiKeySource}),e.organization&&!process.env.IS_DEMO&&o.push({label:"Organización",value:e.organization}),e.email&&!process.env.IS_DEMO&&o.push({label:"Correo",value:e.email}),o}export function buildAPIProviderProperties(){const e=g(),o=[],r=j(),s=x();if(o.push({label:"Persistencia providers",value:"sqlite"===r?"sqlite-only"===s?"SQLite-only":"SQLite (migracion pendiente)":"Legacy fallback"}),o.push({label:"Provider DB",value:y()}),o.push({label:"Credenciales providers",value:"sqlite"===K().name?"SQLite (cifrado local)":K().name}),"sqlite"===K().name&&(K().read(),o.push({label:"Credenciales DB",value:z()}),o.push({label:"Clave cifrado",value:X()}),o.push({label:"Estado cifrado credenciales",value:F()?"Cifrado activo":"Sin payload o pendiente"}),o.push({label:"Legacy credentials file",value:w()?`Presente (${H()})`:"No presente"})),"firstParty"!==e){const r={bedrock:"AWS Bedrock",vertex:"Google Vertex AI",foundry:"Microsoft Foundry",openai:"OpenAI / Codex",openrouter:"OpenRouter",ollama:"Ollama","ollama-cloud":"Ollama Cloud",zai:"Z.AI",minimax:"MiniMax"}[e]||e;o.push({label:"Proveedor API",value:r})}if("firstParty"===e){const e=process.env.ANTHROPIC_BASE_URL;e&&o.push({label:"Anthropic base URL",value:e})}else if("bedrock"===e){const e=process.env.BEDROCK_BASE_URL;e&&o.push({label:"Bedrock base URL",value:e}),o.push({label:"AWS region",value:m()}),(f(process.env.CONTEXT_CODE_SKIP_BEDROCK_AUTH)||f(process.env.CLAUDE_CODE_SKIP_BEDROCK_AUTH))&&o.push({value:"AWS auth skipped"})}else if("vertex"===e){const e=process.env.VERTEX_BASE_URL;e&&o.push({label:"Vertex base URL",value:e});const r=process.env.ANTHROPIC_VERTEX_PROJECT_ID;r&&o.push({label:"GCP project",value:r}),o.push({label:"Default region",value:v()}),(f(process.env.CONTEXT_CODE_SKIP_VERTEX_AUTH)||f(process.env.CLAUDE_CODE_SKIP_VERTEX_AUTH))&&o.push({value:"GCP auth skipped"})}else if("foundry"===e){const e=process.env.ANTHROPIC_FOUNDRY_BASE_URL;e&&o.push({label:"Microsoft Foundry base URL",value:e});const r=process.env.ANTHROPIC_FOUNDRY_RESOURCE;r&&o.push({label:"Microsoft Foundry resource",value:r}),(f(process.env.CONTEXT_CODE_SKIP_FOUNDRY_AUTH)||f(process.env.CLAUDE_CODE_SKIP_FOUNDRY_AUTH))&&o.push({value:"Microsoft Foundry auth skipped"})}else if("openai"===e){const e=process.env.OPENAI_BASE_URL;e&&o.push({label:"OpenAI base URL",value:e})}else if("openrouter"===e){const e=process.env.OPENROUTER_BASE_URL||T("openrouter");o.push({label:"OpenRouter base URL",value:e})}else if("ollama"===e){const e=process.env.OLLAMA_BASE_URL||T("ollama");o.push({label:"Ollama base URL",value:e})}else if("ollama-cloud"===e){const e=process.env.OLLAMA_BASE_URL||T("ollama-cloud");o.push({label:"Ollama Cloud base URL",value:e})}else if("lmstudio"===e){const e=process.env.LMSTUDIO_BASE_URL||process.env.LM_STUDIO_BASE_URL||T("lmstudio");o.push({label:"LM Studio base URL",value:e})}else if("zai"===e){const e=process.env.ZAI_BASE_URL||T("zai");o.push({label:"Z.AI base URL",value:e})}else if("minimax"===e){const e=process.env.MINIMAX_BASE_URL||T("minimax");o.push({label:"MiniMax base URL",value:e})}const a=P();if(a&&(a.provider===e||"firstParty"===e&&"claude"===a.provider)&&a){o.push({label:"Perfil activo",value:`${a.name} (${a.agentName})`}),o.push({label:"Modelo guardado",value:a.lastModel||"Sin modelo guardado"});let e="No aplica";"openai"===a.provider?e=t(a.provider,a.id)?"Configuradas":"No configuradas":"openrouter"!==a.provider&&"zai"!==a.provider&&"minimax"!==a.provider||(e=l(a.provider,a.id)?"Configuradas":"No configuradas"),o.push({label:"Credenciales por perfil",value:e})}const n=B();n&&o.push({label:"Proxy",value:n});const i=N();if(process.env.NODE_EXTRA_CA_CERTS&&o.push({label:"Additional CA cert(s)",value:process.env.NODE_EXTRA_CA_CERTS}),i){const e=process.env.CONTEXT_CODE_CLIENT_CERT??process.env.CLAUDE_CODE_CLIENT_CERT;i.cert&&e&&o.push({label:"mTLS client cert",value:e});const r=process.env.CONTEXT_CODE_CLIENT_KEY??process.env.CLAUDE_CODE_CLIENT_KEY;i.key&&r&&o.push({label:"mTLS client key",value:r})}return o}export function getModelDisplayLabel(e){let r=S(e);if(null===e&&i()){const e=C();r=`${o.bold("Default")} ${e}`}return r}
@@ -1 +1 @@
1
- import{B as e,D as s,E as i,H as a,I as o,K as l,L as h,M as u,O as d,U as c,a as _,b as p,ca as g,d as y,e as m,f as v,g as V,n as f,oa as C,p as A,q as b,qa as w,ra as D,sa as S,ta as O,u as k,va as P,z as x}from"./chunk-VAB2VXFI.js";var T=(()=>{class n{_renderer;_elementRef;onChange=e=>{};onTouched=()=>{};constructor(e,s){this._renderer=e,this._elementRef=s}setProperty(e,s){this._renderer.setProperty(this._elementRef.nativeElement,e,s)}registerOnTouched(e){this.onTouched=e}registerOnChange(e){this.onChange=e}setDisabledState(e){this.setProperty("disabled",e)}static ɵfac=function(e){return new(e||n)(o(a),o(s))};static ɵdir=h({type:n})}return n})(),M=(()=>{class n extends T{static ɵfac=(()=>{let e;return function(s){return(e||(e=x(n)))(s||n)}})();static ɵdir=h({type:n,features:[u]})}return n})(),F=new b(""),R={provide:F,useExisting:f(()=>N),multi:!0},U=new b(""),N=(()=>{class n extends T{_compositionMode;_composing=!1;constructor(e,s,i){super(e,s),this._compositionMode=i,null==this._compositionMode&&(this._compositionMode=!function(){let e=P()?P().getUserAgent():"";return/android (\d+)/.test(e.toLowerCase())}())}writeValue(e){let s=e??"";this.setProperty("value",s)}_handleInput(e){(!this._compositionMode||this._compositionMode&&!this._composing)&&this.onChange(e)}_compositionStart(){this._composing=!0}_compositionEnd(e){this._composing=!1,this._compositionMode&&this.onChange(e)}static ɵfac=function(e){return new(e||n)(o(a),o(s),o(U,8))};static ɵdir=h({type:n,selectors:[["input","formControlName","",3,"type","checkbox"],["textarea","formControlName",""],["input","formControl","",3,"type","checkbox"],["textarea","formControl",""],["input","ngModel","",3,"type","checkbox"],["textarea","ngModel",""],["","ngDefaultControl",""]],hostBindings:function(e,s){1&e&&g("input",function(e){return s._handleInput(e.target.value)})("blur",function(){return s.onTouched()})("compositionstart",function(){return s._compositionStart()})("compositionend",function(e){return s._compositionEnd(e.target.value)})},standalone:!1,features:[C([R]),u]})}return n})(),j=new b(""),H=new b("");function ue(e){return null!=e}function de(e){return d(e)?m(e):e}function ce(e){let s={};return e.forEach(e=>{s=null!=e?_(_({},s),e):s}),0===Object.keys(s).length?null:s}function he(e,s){return s.map(s=>s(e))}function fe(e){return e.map(e=>function(e){return!e.validate}(e)?e:s=>e.validate(s))}function ge(e){return null!=e?function(e){if(!e)return null;let s=e.filter(ue);return 0==s.length?null:function(e){return ce(he(e,s))}}(fe(e)):null}function pe(e){return null!=e?function(e){if(!e)return null;let s=e.filter(ue);return 0==s.length?null:function(e){let i=he(e,s).map(de);return V(i).pipe(v(ce))}}(fe(e)):null}function Q(e,s){return null===e?[s]:Array.isArray(e)?[...e,s]:[e,s]}function G(e){return e?Array.isArray(e)?e:[e]:[]}function E(e,s){return Array.isArray(e)?e.includes(s):e===s}function ee(e,s){let i=G(s);return G(e).forEach(e=>{E(i,e)||i.push(e)}),i}function te(e,s){return G(s).filter(s=>!E(e,s))}var B=class{get value(){return this.control?this.control.value:null}get valid(){return this.control?this.control.valid:null}get invalid(){return this.control?this.control.invalid:null}get pending(){return this.control?this.control.pending:null}get disabled(){return this.control?this.control.disabled:null}get enabled(){return this.control?this.control.enabled:null}get errors(){return this.control?this.control.errors:null}get pristine(){return this.control?this.control.pristine:null}get dirty(){return this.control?this.control.dirty:null}get touched(){return this.control?this.control.touched:null}get status(){return this.control?this.control.status:null}get untouched(){return this.control?this.control.untouched:null}get statusChanges(){return this.control?this.control.statusChanges:null}get valueChanges(){return this.control?this.control.valueChanges:null}get path(){return null}_composedValidatorFn;_composedAsyncValidatorFn;_rawValidators=[];_rawAsyncValidators=[];_setValidators(e){this._rawValidators=e||[],this._composedValidatorFn=ge(this._rawValidators)}_setAsyncValidators(e){this._rawAsyncValidators=e||[],this._composedAsyncValidatorFn=pe(this._rawAsyncValidators)}get validator(){return this._composedValidatorFn||null}get asyncValidator(){return this._composedAsyncValidatorFn||null}_onDestroyCallbacks=[];_registerOnDestroy(e){this._onDestroyCallbacks.push(e)}_invokeOnDestroyCallbacks(){this._onDestroyCallbacks.forEach(e=>e()),this._onDestroyCallbacks=[]}reset(e=void 0){this.control&&this.control.reset(e)}hasError(e,s){return!!this.control&&this.control.hasError(e,s)}getError(e,s){return this.control?this.control.getError(e,s):null}},L=class extends B{name;get formDirective(){return null}get path(){return null}},q=class extends B{_parent=null;name=null;valueAccessor=null},z=class{_cd;constructor(e){this._cd=e}get isTouched(){return this._cd?.control?._touched?.(),!!this._cd?.control?.touched}get isUntouched(){return!!this._cd?.control?.untouched}get isPristine(){return this._cd?.control?._pristine?.(),!!this._cd?.control?.pristine}get isDirty(){return!!this._cd?.control?.dirty}get isValid(){return this._cd?.control?._status?.(),!!this._cd?.control?.valid}get isInvalid(){return!!this._cd?.control?.invalid}get isPending(){return!!this._cd?.control?.pending}get isSubmitted(){return this._cd?._submitted?.(),!!this._cd?.submitted}},K=(p(_({},{"[class.ng-untouched]":"isUntouched","[class.ng-touched]":"isTouched","[class.ng-pristine]":"isPristine","[class.ng-dirty]":"isDirty","[class.ng-valid]":"isValid","[class.ng-invalid]":"isInvalid","[class.ng-pending]":"isPending"}),{"[class.ng-submitted]":"isSubmitted"}),(()=>{class n extends z{constructor(e){super(e)}static ɵfac=function(e){return new(e||n)(o(q,2))};static ɵdir=h({type:n,selectors:[["","formControlName",""],["","ngModel",""],["","formControl",""]],hostVars:14,hostBindings:function(e,s){2&e&&c("ng-untouched",s.isUntouched)("ng-touched",s.isTouched)("ng-pristine",s.isPristine)("ng-dirty",s.isDirty)("ng-valid",s.isValid)("ng-invalid",s.isInvalid)("ng-pending",s.isPending)},standalone:!1,features:[u]})}return n})()),X="VALID",J="INVALID",W="PENDING",Y="DISABLED",Z=class{},$=class extends Z{value;source;constructor(e,s){super(),this.value=e,this.source=s}},tt=class extends Z{pristine;source;constructor(e,s){super(),this.pristine=e,this.source=s}},et=class extends Z{touched;source;constructor(e,s){super(),this.touched=e,this.source=s}},st=class extends Z{status;source;constructor(e,s){super(),this.status=e,this.source=s}};function I(e){return null!=e&&!Array.isArray(e)&&"object"==typeof e}var nt=class{_pendingDirty=!1;_hasOwnPendingAsyncValidator=null;_pendingTouched=!1;_onCollectionChange=()=>{};_updateOn;_parent=null;_asyncValidationSubscription;_composedValidatorFn;_composedAsyncValidatorFn;_rawValidators;_rawAsyncValidators;value;constructor(e,s){this._assignValidators(e),this._assignAsyncValidators(s)}get validator(){return this._composedValidatorFn}set validator(e){this._rawValidators=this._composedValidatorFn=e}get asyncValidator(){return this._composedAsyncValidatorFn}set asyncValidator(e){this._rawAsyncValidators=this._composedAsyncValidatorFn=e}get parent(){return this._parent}get status(){return S(this.statusReactive)}set status(e){S(()=>this.statusReactive.set(e))}_status=O(()=>this.statusReactive());statusReactive=i(void 0);get valid(){return this.status===X}get invalid(){return this.status===J}get pending(){return this.status==W}get disabled(){return this.status===Y}get enabled(){return this.status!==Y}errors;get pristine(){return S(this.pristineReactive)}set pristine(e){S(()=>this.pristineReactive.set(e))}_pristine=O(()=>this.pristineReactive());pristineReactive=i(!0);get dirty(){return!this.pristine}get touched(){return S(this.touchedReactive)}set touched(e){S(()=>this.touchedReactive.set(e))}_touched=O(()=>this.touchedReactive());touchedReactive=i(!1);get untouched(){return!this.touched}_events=new y;events=this._events.asObservable();valueChanges;statusChanges;get updateOn(){return this._updateOn?this._updateOn:this.parent?this.parent.updateOn:"change"}setValidators(e){this._assignValidators(e)}setAsyncValidators(e){this._assignAsyncValidators(e)}addValidators(e){this.setValidators(ee(e,this._rawValidators))}addAsyncValidators(e){this.setAsyncValidators(ee(e,this._rawAsyncValidators))}removeValidators(e){this.setValidators(te(e,this._rawValidators))}removeAsyncValidators(e){this.setAsyncValidators(te(e,this._rawAsyncValidators))}hasValidator(e){return E(this._rawValidators,e)}hasAsyncValidator(e){return E(this._rawAsyncValidators,e)}clearValidators(){this.validator=null}clearAsyncValidators(){this.asyncValidator=null}markAsTouched(e={}){let s=!1===this.touched;this.touched=!0;let i=e.sourceControl??this;this._parent&&!e.onlySelf&&this._parent.markAsTouched(p(_({},e),{sourceControl:i})),s&&!1!==e.emitEvent&&this._events.next(new et(!0,i))}markAllAsTouched(e={}){this.markAsTouched({onlySelf:!0,emitEvent:e.emitEvent,sourceControl:this}),this._forEachChild(s=>s.markAllAsTouched(e))}markAsUntouched(e={}){let s=!0===this.touched;this.touched=!1,this._pendingTouched=!1;let i=e.sourceControl??this;this._forEachChild(s=>{s.markAsUntouched({onlySelf:!0,emitEvent:e.emitEvent,sourceControl:i})}),this._parent&&!e.onlySelf&&this._parent._updateTouched(e,i),s&&!1!==e.emitEvent&&this._events.next(new et(!1,i))}markAsDirty(e={}){let s=!0===this.pristine;this.pristine=!1;let i=e.sourceControl??this;this._parent&&!e.onlySelf&&this._parent.markAsDirty(p(_({},e),{sourceControl:i})),s&&!1!==e.emitEvent&&this._events.next(new tt(!1,i))}markAsPristine(e={}){let s=!1===this.pristine;this.pristine=!0,this._pendingDirty=!1;let i=e.sourceControl??this;this._forEachChild(s=>{s.markAsPristine({onlySelf:!0,emitEvent:e.emitEvent})}),this._parent&&!e.onlySelf&&this._parent._updatePristine(e,i),s&&!1!==e.emitEvent&&this._events.next(new tt(!0,i))}markAsPending(e={}){this.status=W;let s=e.sourceControl??this;!1!==e.emitEvent&&(this._events.next(new st(this.status,s)),this.statusChanges.emit(this.status)),this._parent&&!e.onlySelf&&this._parent.markAsPending(p(_({},e),{sourceControl:s}))}disable(e={}){let s=this._parentMarkedDirty(e.onlySelf);this.status=Y,this.errors=null,this._forEachChild(s=>{s.disable(p(_({},e),{onlySelf:!0}))}),this._updateValue();let i=e.sourceControl??this;!1!==e.emitEvent&&(this._events.next(new $(this.value,i)),this._events.next(new st(this.status,i)),this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._updateAncestors(p(_({},e),{skipPristineCheck:s}),this),this._onDisabledChange.forEach(e=>e(!0))}enable(e={}){let s=this._parentMarkedDirty(e.onlySelf);this.status=X,this._forEachChild(s=>{s.enable(p(_({},e),{onlySelf:!0}))}),this.updateValueAndValidity({onlySelf:!0,emitEvent:e.emitEvent}),this._updateAncestors(p(_({},e),{skipPristineCheck:s}),this),this._onDisabledChange.forEach(e=>e(!1))}_updateAncestors(e,s){this._parent&&!e.onlySelf&&(this._parent.updateValueAndValidity(e),e.skipPristineCheck||this._parent._updatePristine({},s),this._parent._updateTouched({},s))}setParent(e){this._parent=e}getRawValue(){return this.value}updateValueAndValidity(e={}){if(this._setInitialStatus(),this._updateValue(),this.enabled){let s=this._cancelExistingSubscription();this.errors=this._runValidator(),this.status=this._calculateStatus(),(this.status===X||this.status===W)&&this._runAsyncValidator(s,e.emitEvent)}let s=e.sourceControl??this;!1!==e.emitEvent&&(this._events.next(new $(this.value,s)),this._events.next(new st(this.status,s)),this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._parent&&!e.onlySelf&&this._parent.updateValueAndValidity(p(_({},e),{sourceControl:s}))}_updateTreeValidity(e={emitEvent:!0}){this._forEachChild(s=>s._updateTreeValidity(e)),this.updateValueAndValidity({onlySelf:!0,emitEvent:e.emitEvent})}_setInitialStatus(){this.status=this._allControlsDisabled()?Y:X}_runValidator(){return this.validator?this.validator(this):null}_runAsyncValidator(e,s){if(this.asyncValidator){this.status=W,this._hasOwnPendingAsyncValidator={emitEvent:!1!==s};let i=de(this.asyncValidator(this));this._asyncValidationSubscription=i.subscribe(i=>{this._hasOwnPendingAsyncValidator=null,this.setErrors(i,{emitEvent:s,shouldHaveEmitted:e})})}}_cancelExistingSubscription(){if(this._asyncValidationSubscription){this._asyncValidationSubscription.unsubscribe();let e=this._hasOwnPendingAsyncValidator?.emitEvent??!1;return this._hasOwnPendingAsyncValidator=null,e}return!1}setErrors(e,s={}){this.errors=e,this._updateControlsErrors(!1!==s.emitEvent,this,s.shouldHaveEmitted)}get(e){let s=e;return null==s||(Array.isArray(s)||(s=s.split(".")),0===s.length)?null:s.reduce((e,s)=>e&&e._find(s),this)}getError(e,s){let i=s?this.get(s):this;return i&&i.errors?i.errors[e]:null}hasError(e,s){return!!this.getError(e,s)}get root(){let e=this;for(;e._parent;)e=e._parent;return e}_updateControlsErrors(e,s,i){this.status=this._calculateStatus(),e&&this.statusChanges.emit(this.status),(e||i)&&this._events.next(new st(this.status,s)),this._parent&&this._parent._updateControlsErrors(e,s,i)}_initObservables(){this.valueChanges=new e,this.statusChanges=new e}_calculateStatus(){return this._allControlsDisabled()?Y:this.errors?J:this._hasOwnPendingAsyncValidator||this._anyControlsHaveStatus(W)?W:this._anyControlsHaveStatus(J)?J:X}_anyControlsHaveStatus(e){return this._anyControls(s=>s.status===e)}_anyControlsDirty(){return this._anyControls(e=>e.dirty)}_anyControlsTouched(){return this._anyControls(e=>e.touched)}_updatePristine(e,s){let i=!this._anyControlsDirty(),a=this.pristine!==i;this.pristine=i,this._parent&&!e.onlySelf&&this._parent._updatePristine(e,s),a&&this._events.next(new tt(this.pristine,s))}_updateTouched(e={},s){this.touched=this._anyControlsTouched(),this._events.next(new et(this.touched,s)),this._parent&&!e.onlySelf&&this._parent._updateTouched(e,s)}_onDisabledChange=[];_registerOnCollectionChange(e){this._onCollectionChange=e}_setUpdateStrategy(e){I(e)&&null!=e.updateOn&&(this._updateOn=e.updateOn)}_parentMarkedDirty(e){let s=this._parent&&this._parent.dirty;return!e&&!!s&&!this._parent._anyControlsDirty()}_find(e){return null}_assignValidators(e){var s;this._rawValidators=Array.isArray(e)?e.slice():e,this._composedValidatorFn=(s=this._rawValidators,Array.isArray(s)?ge(s):s||null)}_assignAsyncValidators(e){var s;this._rawAsyncValidators=Array.isArray(e)?e.slice():e,this._composedAsyncValidatorFn=(s=this._rawAsyncValidators,Array.isArray(s)?pe(s):s||null)}},it=new b("",{providedIn:"root",factory:()=>rt}),rt="always";function ne(e,s){e.forEach(e=>{e.registerOnValidatorChange&&e.registerOnValidatorChange(s)})}function _e(e,s){e._pendingDirty&&e.markAsDirty(),e.setValue(e._pendingValue,{emitModelToViewChange:!1}),s.viewToModelUpdate(e._pendingValue),e._pendingChange=!1}function ie(e,s){let i=e.indexOf(s);i>-1&&e.splice(i,1)}function re(e){return"object"==typeof e&&null!==e&&2===Object.keys(e).length&&"value"in e&&"disabled"in e}var at=class extends nt{defaultValue=null;_onChange=[];_pendingValue;_pendingChange=!1;constructor(e=null,s,i){var a;super((I(a=s)?a.validators:a)||null,function(e,s){return(I(s)?s.asyncValidators:e)||null}(i,s)),this._applyFormState(e),this._setUpdateStrategy(s),this._initObservables(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator}),I(s)&&(s.nonNullable||s.initialValueIsDefault)&&(re(e)?this.defaultValue=e.value:this.defaultValue=e)}setValue(e,s={}){this.value=this._pendingValue=e,this._onChange.length&&!1!==s.emitModelToViewChange&&this._onChange.forEach(e=>e(this.value,!1!==s.emitViewToModelChange)),this.updateValueAndValidity(s)}patchValue(e,s={}){this.setValue(e,s)}reset(e=this.defaultValue,s={}){this._applyFormState(e),this.markAsPristine(s),this.markAsUntouched(s),this.setValue(this.value,s),this._pendingChange=!1}_updateValue(){}_anyControls(e){return!1}_allControlsDisabled(){return this.disabled}registerOnChange(e){this._onChange.push(e)}_unregisterOnChange(e){ie(this._onChange,e)}registerOnDisabledChange(e){this._onDisabledChange.push(e)}_unregisterOnDisabledChange(e){ie(this._onDisabledChange,e)}_forEachChild(e){}_syncPendingControls(){return!("submit"!==this.updateOn||(this._pendingDirty&&this.markAsDirty(),this._pendingTouched&&this.markAsTouched(),!this._pendingChange)||(this.setValue(this._pendingValue,{onlySelf:!0,emitModelToViewChange:!1}),0))}_applyFormState(e){re(e)?(this.value=this._pendingValue=e.value,e.disabled?this.disable({onlySelf:!0,emitEvent:!1}):this.enable({onlySelf:!0,emitEvent:!1})):this.value=this._pendingValue=e}},ot={provide:q,useExisting:f(()=>ht)},lt=Promise.resolve(),ht=(()=>{class n extends q{_changeDetectorRef;callSetDisabledState;control=new at;static ngAcceptInputType_isDisabled;_registered=!1;viewModel;name="";isDisabled;model;options;update=new e;constructor(e,s,i,a,o,l){super(),this._changeDetectorRef=o,this.callSetDisabledState=l,this._parent=e,this._setValidators(s),this._setAsyncValidators(i),this.valueAccessor=function(e,s){if(!s)return null;let i,a,o;return Array.isArray(s),s.forEach(e=>{e.constructor===N?i=e:function(e){return Object.getPrototypeOf(e.constructor)===M}(e)?a=e:o=e}),o||a||i||null}(0,a)}ngOnChanges(e){if(this._checkForErrors(),!this._registered||"name"in e){if(this._registered&&(this._checkName(),this.formDirective)){let s=e.name.previousValue;this.formDirective.removeControl({name:s,path:this._getPath(s)})}this._setUpControl()}"isDisabled"in e&&this._updateDisabled(e),function(e,s){if(!e.hasOwnProperty("model"))return!1;let i=e.model;return!!i.isFirstChange()||!Object.is(s,i.currentValue)}(e,this.viewModel)&&(this._updateValue(this.model),this.viewModel=this.model)}ngOnDestroy(){this.formDirective&&this.formDirective.removeControl(this)}get path(){return this._getPath(this.name)}get formDirective(){return this._parent?this._parent.formDirective:null}viewToModelUpdate(e){this.viewModel=e,this.update.emit(e)}_setUpControl(){this._setUpdateStrategy(),this._isStandalone()?this._setUpStandalone():this.formDirective.addControl(this),this._registered=!0}_setUpdateStrategy(){this.options&&null!=this.options.updateOn&&(this.control._updateOn=this.options.updateOn)}_isStandalone(){return!this._parent||!(!this.options||!this.options.standalone)}_setUpStandalone(){(function(e,s,i=rt){(function(e,s){let i=function(e){return e._rawValidators}(e);null!==s.validator?e.setValidators(Q(i,s.validator)):"function"==typeof i&&e.setValidators([i]);let a=function(e){return e._rawAsyncValidators}(e);null!==s.asyncValidator?e.setAsyncValidators(Q(a,s.asyncValidator)):"function"==typeof a&&e.setAsyncValidators([a]);let r=()=>e.updateValueAndValidity();ne(s._rawValidators,r),ne(s._rawAsyncValidators,r)})(e,s),s.valueAccessor.writeValue(e.value),(e.disabled||"always"===i)&&s.valueAccessor.setDisabledState?.(e.disabled),function(e,s){s.valueAccessor.registerOnChange(i=>{e._pendingValue=i,e._pendingChange=!0,e._pendingDirty=!0,"change"===e.updateOn&&_e(e,s)})}(e,s),function(e,s){let t=(e,i)=>{s.valueAccessor.writeValue(e),i&&s.viewToModelUpdate(e)};e.registerOnChange(t),s._registerOnDestroy(()=>{e._unregisterOnChange(t)})}(e,s),function(e,s){s.valueAccessor.registerOnTouched(()=>{e._pendingTouched=!0,"blur"===e.updateOn&&e._pendingChange&&_e(e,s),"submit"!==e.updateOn&&e.markAsTouched()})}(e,s),function(e,s){if(s.valueAccessor.setDisabledState){let t=e=>{s.valueAccessor.setDisabledState(e)};e.registerOnDisabledChange(t),s._registerOnDestroy(()=>{e._unregisterOnDisabledChange(t)})}}(e,s)})(this.control,this,this.callSetDisabledState),this.control.updateValueAndValidity({emitEvent:!1})}_checkForErrors(){this._checkName()}_checkName(){this.options&&this.options.name&&(this.name=this.options.name),!this._isStandalone()&&this.name}_updateValue(e){lt.then(()=>{this.control.setValue(e,{emitViewToModelChange:!1}),this._changeDetectorRef?.markForCheck()})}_updateDisabled(e){let s=e.isDisabled.currentValue,i=0!==s&&D(s);lt.then(()=>{i&&!this.control.disabled?this.control.disable():!i&&this.control.disabled&&this.control.enable(),this._changeDetectorRef?.markForCheck()})}_getPath(e){return this._parent?function(e,s){return[...s.path,e]}(e,this._parent):[e]}static ɵfac=function(e){return new(e||n)(o(L,9),o(j,10),o(H,10),o(F,10),o(w,8),o(it,8))};static ɵdir=h({type:n,selectors:[["","ngModel","",3,"formControlName","",3,"formControl",""]],inputs:{name:"name",isDisabled:[0,"disabled","isDisabled"],model:[0,"ngModel","model"],options:[0,"ngModelOptions","options"]},outputs:{update:"ngModelChange"},exportAs:["ngModel"],standalone:!1,features:[C([ot]),u,k]})}return n})(),ut=(()=>{class n{static ɵfac=function(e){return new(e||n)};static ɵmod=l({type:n});static ɵinj=A({})}return n})(),dt=(()=>{class n{static withConfig(e){return{ngModule:n,providers:[{provide:it,useValue:e.callSetDisabledState??rt}]}}static ɵfac=function(e){return new(e||n)};static ɵmod=l({type:n});static ɵinj=A({imports:[ut]})}return n})();export{N as a,K as b,ht as c,dt as d};
1
+ import{B as e,D as s,E as i,H as a,I as o,K as l,L as h,M as u,O as d,U as c,a as _,b as p,ca as g,d as y,e as m,f as v,g as V,n as f,oa as C,p as A,q as b,qa as w,ra as D,sa as S,ta as O,u as k,va as P,z as x}from"./chunk-VAB2VXFI.js";var T=(()=>{class n{_renderer;_elementRef;onChange=e=>{};onTouched=()=>{};constructor(e,s){this._renderer=e,this._elementRef=s}setProperty(e,s){this._renderer.setProperty(this._elementRef.nativeElement,e,s)}registerOnTouched(e){this.onTouched=e}registerOnChange(e){this.onChange=e}setDisabledState(e){this.setProperty("disabled",e)}static ɵfac=function(e){return new(e||n)(o(a),o(s))};static ɵdir=h({type:n})}return n})(),M=(()=>{class n extends T{static ɵfac=(()=>{let e;return function(s){return(e||(e=x(n)))(s||n)}})();static ɵdir=h({type:n,features:[u]})}return n})(),F=new b(""),R={provide:F,useExisting:f(()=>N),multi:!0};var U=new b(""),N=(()=>{class n extends T{_compositionMode;_composing=!1;constructor(e,s,i){super(e,s),this._compositionMode=i,null==this._compositionMode&&(this._compositionMode=!function(){let e=P()?P().getUserAgent():"";return/android (\d+)/.test(e.toLowerCase())}())}writeValue(e){let s=e??"";this.setProperty("value",s)}_handleInput(e){(!this._compositionMode||this._compositionMode&&!this._composing)&&this.onChange(e)}_compositionStart(){this._composing=!0}_compositionEnd(e){this._composing=!1,this._compositionMode&&this.onChange(e)}static ɵfac=function(e){return new(e||n)(o(a),o(s),o(U,8))};static ɵdir=h({type:n,selectors:[["input","formControlName","",3,"type","checkbox"],["textarea","formControlName",""],["input","formControl","",3,"type","checkbox"],["textarea","formControl",""],["input","ngModel","",3,"type","checkbox"],["textarea","ngModel",""],["","ngDefaultControl",""]],hostBindings:function(e,s){1&e&&g("input",function(e){return s._handleInput(e.target.value)})("blur",function(){return s.onTouched()})("compositionstart",function(){return s._compositionStart()})("compositionend",function(e){return s._compositionEnd(e.target.value)})},standalone:!1,features:[C([R]),u]})}return n})(),j=new b(""),H=new b("");function ue(e){return null!=e}function de(e){return d(e)?m(e):e}function ce(e){let s={};return e.forEach(e=>{s=null!=e?_(_({},s),e):s}),0===Object.keys(s).length?null:s}function he(e,s){return s.map(s=>s(e))}function fe(e){return e.map(e=>function(e){return!e.validate}(e)?e:s=>e.validate(s))}function ge(e){return null!=e?function(e){if(!e)return null;let s=e.filter(ue);return 0==s.length?null:function(e){return ce(he(e,s))}}(fe(e)):null}function pe(e){return null!=e?function(e){if(!e)return null;let s=e.filter(ue);return 0==s.length?null:function(e){let i=he(e,s).map(de);return V(i).pipe(v(ce))}}(fe(e)):null}function Q(e,s){return null===e?[s]:Array.isArray(e)?[...e,s]:[e,s]}function G(e){return e?Array.isArray(e)?e:[e]:[]}function E(e,s){return Array.isArray(e)?e.includes(s):e===s}function ee(e,s){let i=G(s);return G(e).forEach(e=>{E(i,e)||i.push(e)}),i}function te(e,s){return G(s).filter(s=>!E(e,s))}var B=class{get value(){return this.control?this.control.value:null}get valid(){return this.control?this.control.valid:null}get invalid(){return this.control?this.control.invalid:null}get pending(){return this.control?this.control.pending:null}get disabled(){return this.control?this.control.disabled:null}get enabled(){return this.control?this.control.enabled:null}get errors(){return this.control?this.control.errors:null}get pristine(){return this.control?this.control.pristine:null}get dirty(){return this.control?this.control.dirty:null}get touched(){return this.control?this.control.touched:null}get status(){return this.control?this.control.status:null}get untouched(){return this.control?this.control.untouched:null}get statusChanges(){return this.control?this.control.statusChanges:null}get valueChanges(){return this.control?this.control.valueChanges:null}get path(){return null}_composedValidatorFn;_composedAsyncValidatorFn;_rawValidators=[];_rawAsyncValidators=[];_setValidators(e){this._rawValidators=e||[],this._composedValidatorFn=ge(this._rawValidators)}_setAsyncValidators(e){this._rawAsyncValidators=e||[],this._composedAsyncValidatorFn=pe(this._rawAsyncValidators)}get validator(){return this._composedValidatorFn||null}get asyncValidator(){return this._composedAsyncValidatorFn||null}_onDestroyCallbacks=[];_registerOnDestroy(e){this._onDestroyCallbacks.push(e)}_invokeOnDestroyCallbacks(){this._onDestroyCallbacks.forEach(e=>e()),this._onDestroyCallbacks=[]}reset(e=void 0){this.control&&this.control.reset(e)}hasError(e,s){return!!this.control&&this.control.hasError(e,s)}getError(e,s){return this.control?this.control.getError(e,s):null}},L=class extends B{name;get formDirective(){return null}get path(){return null}},q=class extends B{_parent=null;name=null;valueAccessor=null},$=class{_cd;constructor(e){this._cd=e}get isTouched(){return this._cd?.control?._touched?.(),!!this._cd?.control?.touched}get isUntouched(){return!!this._cd?.control?.untouched}get isPristine(){return this._cd?.control?._pristine?.(),!!this._cd?.control?.pristine}get isDirty(){return!!this._cd?.control?.dirty}get isValid(){return this._cd?.control?._status?.(),!!this._cd?.control?.valid}get isInvalid(){return!!this._cd?.control?.invalid}get isPending(){return!!this._cd?.control?.pending}get isSubmitted(){return this._cd?._submitted?.(),!!this._cd?.submitted}},K=(p(_({},{"[class.ng-untouched]":"isUntouched","[class.ng-touched]":"isTouched","[class.ng-pristine]":"isPristine","[class.ng-dirty]":"isDirty","[class.ng-valid]":"isValid","[class.ng-invalid]":"isInvalid","[class.ng-pending]":"isPending"}),{"[class.ng-submitted]":"isSubmitted"}),(()=>{class n extends ${constructor(e){super(e)}static ɵfac=function(e){return new(e||n)(o(q,2))};static ɵdir=h({type:n,selectors:[["","formControlName",""],["","ngModel",""],["","formControl",""]],hostVars:14,hostBindings:function(e,s){2&e&&c("ng-untouched",s.isUntouched)("ng-touched",s.isTouched)("ng-pristine",s.isPristine)("ng-dirty",s.isDirty)("ng-valid",s.isValid)("ng-invalid",s.isInvalid)("ng-pending",s.isPending)},standalone:!1,features:[u]})}return n})()),X="VALID",z="INVALID",J="PENDING",W="DISABLED",Y=class{},Z=class extends Y{value;source;constructor(e,s){super(),this.value=e,this.source=s}},tt=class extends Y{pristine;source;constructor(e,s){super(),this.pristine=e,this.source=s}},et=class extends Y{touched;source;constructor(e,s){super(),this.touched=e,this.source=s}},st=class extends Y{status;source;constructor(e,s){super(),this.status=e,this.source=s}};function I(e){return null!=e&&!Array.isArray(e)&&"object"==typeof e}var nt=class{_pendingDirty=!1;_hasOwnPendingAsyncValidator=null;_pendingTouched=!1;_onCollectionChange=()=>{};_updateOn;_parent=null;_asyncValidationSubscription;_composedValidatorFn;_composedAsyncValidatorFn;_rawValidators;_rawAsyncValidators;value;constructor(e,s){this._assignValidators(e),this._assignAsyncValidators(s)}get validator(){return this._composedValidatorFn}set validator(e){this._rawValidators=this._composedValidatorFn=e}get asyncValidator(){return this._composedAsyncValidatorFn}set asyncValidator(e){this._rawAsyncValidators=this._composedAsyncValidatorFn=e}get parent(){return this._parent}get status(){return S(this.statusReactive)}set status(e){S(()=>this.statusReactive.set(e))}_status=O(()=>this.statusReactive());statusReactive=i(void 0);get valid(){return this.status===X}get invalid(){return this.status===z}get pending(){return this.status==J}get disabled(){return this.status===W}get enabled(){return this.status!==W}errors;get pristine(){return S(this.pristineReactive)}set pristine(e){S(()=>this.pristineReactive.set(e))}_pristine=O(()=>this.pristineReactive());pristineReactive=i(!0);get dirty(){return!this.pristine}get touched(){return S(this.touchedReactive)}set touched(e){S(()=>this.touchedReactive.set(e))}_touched=O(()=>this.touchedReactive());touchedReactive=i(!1);get untouched(){return!this.touched}_events=new y;events=this._events.asObservable();valueChanges;statusChanges;get updateOn(){return this._updateOn?this._updateOn:this.parent?this.parent.updateOn:"change"}setValidators(e){this._assignValidators(e)}setAsyncValidators(e){this._assignAsyncValidators(e)}addValidators(e){this.setValidators(ee(e,this._rawValidators))}addAsyncValidators(e){this.setAsyncValidators(ee(e,this._rawAsyncValidators))}removeValidators(e){this.setValidators(te(e,this._rawValidators))}removeAsyncValidators(e){this.setAsyncValidators(te(e,this._rawAsyncValidators))}hasValidator(e){return E(this._rawValidators,e)}hasAsyncValidator(e){return E(this._rawAsyncValidators,e)}clearValidators(){this.validator=null}clearAsyncValidators(){this.asyncValidator=null}markAsTouched(e={}){let s=!1===this.touched;this.touched=!0;let i=e.sourceControl??this;this._parent&&!e.onlySelf&&this._parent.markAsTouched(p(_({},e),{sourceControl:i})),s&&!1!==e.emitEvent&&this._events.next(new et(!0,i))}markAllAsTouched(e={}){this.markAsTouched({onlySelf:!0,emitEvent:e.emitEvent,sourceControl:this}),this._forEachChild(s=>s.markAllAsTouched(e))}markAsUntouched(e={}){let s=!0===this.touched;this.touched=!1,this._pendingTouched=!1;let i=e.sourceControl??this;this._forEachChild(s=>{s.markAsUntouched({onlySelf:!0,emitEvent:e.emitEvent,sourceControl:i})}),this._parent&&!e.onlySelf&&this._parent._updateTouched(e,i),s&&!1!==e.emitEvent&&this._events.next(new et(!1,i))}markAsDirty(e={}){let s=!0===this.pristine;this.pristine=!1;let i=e.sourceControl??this;this._parent&&!e.onlySelf&&this._parent.markAsDirty(p(_({},e),{sourceControl:i})),s&&!1!==e.emitEvent&&this._events.next(new tt(!1,i))}markAsPristine(e={}){let s=!1===this.pristine;this.pristine=!0,this._pendingDirty=!1;let i=e.sourceControl??this;this._forEachChild(s=>{s.markAsPristine({onlySelf:!0,emitEvent:e.emitEvent})}),this._parent&&!e.onlySelf&&this._parent._updatePristine(e,i),s&&!1!==e.emitEvent&&this._events.next(new tt(!0,i))}markAsPending(e={}){this.status=J;let s=e.sourceControl??this;!1!==e.emitEvent&&(this._events.next(new st(this.status,s)),this.statusChanges.emit(this.status)),this._parent&&!e.onlySelf&&this._parent.markAsPending(p(_({},e),{sourceControl:s}))}disable(e={}){let s=this._parentMarkedDirty(e.onlySelf);this.status=W,this.errors=null,this._forEachChild(s=>{s.disable(p(_({},e),{onlySelf:!0}))}),this._updateValue();let i=e.sourceControl??this;!1!==e.emitEvent&&(this._events.next(new Z(this.value,i)),this._events.next(new st(this.status,i)),this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._updateAncestors(p(_({},e),{skipPristineCheck:s}),this),this._onDisabledChange.forEach(e=>e(!0))}enable(e={}){let s=this._parentMarkedDirty(e.onlySelf);this.status=X,this._forEachChild(s=>{s.enable(p(_({},e),{onlySelf:!0}))}),this.updateValueAndValidity({onlySelf:!0,emitEvent:e.emitEvent}),this._updateAncestors(p(_({},e),{skipPristineCheck:s}),this),this._onDisabledChange.forEach(e=>e(!1))}_updateAncestors(e,s){this._parent&&!e.onlySelf&&(this._parent.updateValueAndValidity(e),e.skipPristineCheck||this._parent._updatePristine({},s),this._parent._updateTouched({},s))}setParent(e){this._parent=e}getRawValue(){return this.value}updateValueAndValidity(e={}){if(this._setInitialStatus(),this._updateValue(),this.enabled){let s=this._cancelExistingSubscription();this.errors=this._runValidator(),this.status=this._calculateStatus(),(this.status===X||this.status===J)&&this._runAsyncValidator(s,e.emitEvent)}let s=e.sourceControl??this;!1!==e.emitEvent&&(this._events.next(new Z(this.value,s)),this._events.next(new st(this.status,s)),this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._parent&&!e.onlySelf&&this._parent.updateValueAndValidity(p(_({},e),{sourceControl:s}))}_updateTreeValidity(e={emitEvent:!0}){this._forEachChild(s=>s._updateTreeValidity(e)),this.updateValueAndValidity({onlySelf:!0,emitEvent:e.emitEvent})}_setInitialStatus(){this.status=this._allControlsDisabled()?W:X}_runValidator(){return this.validator?this.validator(this):null}_runAsyncValidator(e,s){if(this.asyncValidator){this.status=J,this._hasOwnPendingAsyncValidator={emitEvent:!1!==s};let i=de(this.asyncValidator(this));this._asyncValidationSubscription=i.subscribe(i=>{this._hasOwnPendingAsyncValidator=null,this.setErrors(i,{emitEvent:s,shouldHaveEmitted:e})})}}_cancelExistingSubscription(){if(this._asyncValidationSubscription){this._asyncValidationSubscription.unsubscribe();let e=this._hasOwnPendingAsyncValidator?.emitEvent??!1;return this._hasOwnPendingAsyncValidator=null,e}return!1}setErrors(e,s={}){this.errors=e,this._updateControlsErrors(!1!==s.emitEvent,this,s.shouldHaveEmitted)}get(e){let s=e;return null==s||(Array.isArray(s)||(s=s.split(".")),0===s.length)?null:s.reduce((e,s)=>e&&e._find(s),this)}getError(e,s){let i=s?this.get(s):this;return i&&i.errors?i.errors[e]:null}hasError(e,s){return!!this.getError(e,s)}get root(){let e=this;for(;e._parent;)e=e._parent;return e}_updateControlsErrors(e,s,i){this.status=this._calculateStatus(),e&&this.statusChanges.emit(this.status),(e||i)&&this._events.next(new st(this.status,s)),this._parent&&this._parent._updateControlsErrors(e,s,i)}_initObservables(){this.valueChanges=new e,this.statusChanges=new e}_calculateStatus(){return this._allControlsDisabled()?W:this.errors?z:this._hasOwnPendingAsyncValidator||this._anyControlsHaveStatus(J)?J:this._anyControlsHaveStatus(z)?z:X}_anyControlsHaveStatus(e){return this._anyControls(s=>s.status===e)}_anyControlsDirty(){return this._anyControls(e=>e.dirty)}_anyControlsTouched(){return this._anyControls(e=>e.touched)}_updatePristine(e,s){let i=!this._anyControlsDirty(),a=this.pristine!==i;this.pristine=i,this._parent&&!e.onlySelf&&this._parent._updatePristine(e,s),a&&this._events.next(new tt(this.pristine,s))}_updateTouched(e={},s){this.touched=this._anyControlsTouched(),this._events.next(new et(this.touched,s)),this._parent&&!e.onlySelf&&this._parent._updateTouched(e,s)}_onDisabledChange=[];_registerOnCollectionChange(e){this._onCollectionChange=e}_setUpdateStrategy(e){I(e)&&null!=e.updateOn&&(this._updateOn=e.updateOn)}_parentMarkedDirty(e){let s=this._parent&&this._parent.dirty;return!e&&!!s&&!this._parent._anyControlsDirty()}_find(e){return null}_assignValidators(e){var s;this._rawValidators=Array.isArray(e)?e.slice():e,this._composedValidatorFn=(s=this._rawValidators,Array.isArray(s)?ge(s):s||null)}_assignAsyncValidators(e){var s;this._rawAsyncValidators=Array.isArray(e)?e.slice():e,this._composedAsyncValidatorFn=(s=this._rawAsyncValidators,Array.isArray(s)?pe(s):s||null)}},it=new b("",{providedIn:"root",factory:()=>rt}),rt="always";function Re(e,s,i=rt){(function(e,s){let i=function(e){return e._rawValidators}(e);null!==s.validator?e.setValidators(Q(i,s.validator)):"function"==typeof i&&e.setValidators([i]);let a=function(e){return e._rawAsyncValidators}(e);null!==s.asyncValidator?e.setAsyncValidators(Q(a,s.asyncValidator)):"function"==typeof a&&e.setAsyncValidators([a]);let r=()=>e.updateValueAndValidity();ne(s._rawValidators,r),ne(s._rawAsyncValidators,r)})(e,s),s.valueAccessor.writeValue(e.value),(e.disabled||"always"===i)&&s.valueAccessor.setDisabledState?.(e.disabled),function(e,s){s.valueAccessor.registerOnChange(i=>{e._pendingValue=i,e._pendingChange=!0,e._pendingDirty=!0,"change"===e.updateOn&&_e(e,s)})}(e,s),function(e,s){let t=(e,i)=>{s.valueAccessor.writeValue(e),i&&s.viewToModelUpdate(e)};e.registerOnChange(t),s._registerOnDestroy(()=>{e._unregisterOnChange(t)})}(e,s),function(e,s){s.valueAccessor.registerOnTouched(()=>{e._pendingTouched=!0,"blur"===e.updateOn&&e._pendingChange&&_e(e,s),"submit"!==e.updateOn&&e.markAsTouched()})}(e,s),function(e,s){if(s.valueAccessor.setDisabledState){let t=e=>{s.valueAccessor.setDisabledState(e)};e.registerOnDisabledChange(t),s._registerOnDestroy(()=>{e._unregisterOnDisabledChange(t)})}}(e,s)}function ne(e,s){e.forEach(e=>{e.registerOnValidatorChange&&e.registerOnValidatorChange(s)})}function _e(e,s){e._pendingDirty&&e.markAsDirty(),e.setValue(e._pendingValue,{emitModelToViewChange:!1}),s.viewToModelUpdate(e._pendingValue),e._pendingChange=!1}function $e(e,s){if(!s)return null;let i,a,o;return Array.isArray(s),s.forEach(e=>{e.constructor===N?i=e:function(e){return Object.getPrototypeOf(e.constructor)===M}(e)?a=e:o=e}),o||a||i||null}function ie(e,s){let i=e.indexOf(s);i>-1&&e.splice(i,1)}function re(e){return"object"==typeof e&&null!==e&&2===Object.keys(e).length&&"value"in e&&"disabled"in e}var at=class extends nt{defaultValue=null;_onChange=[];_pendingValue;_pendingChange=!1;constructor(e=null,s,i){var a;super((I(a=s)?a.validators:a)||null,function(e,s){return(I(s)?s.asyncValidators:e)||null}(i,s)),this._applyFormState(e),this._setUpdateStrategy(s),this._initObservables(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator}),I(s)&&(s.nonNullable||s.initialValueIsDefault)&&(re(e)?this.defaultValue=e.value:this.defaultValue=e)}setValue(e,s={}){this.value=this._pendingValue=e,this._onChange.length&&!1!==s.emitModelToViewChange&&this._onChange.forEach(e=>e(this.value,!1!==s.emitViewToModelChange)),this.updateValueAndValidity(s)}patchValue(e,s={}){this.setValue(e,s)}reset(e=this.defaultValue,s={}){this._applyFormState(e),this.markAsPristine(s),this.markAsUntouched(s),this.setValue(this.value,s),this._pendingChange=!1}_updateValue(){}_anyControls(e){return!1}_allControlsDisabled(){return this.disabled}registerOnChange(e){this._onChange.push(e)}_unregisterOnChange(e){ie(this._onChange,e)}registerOnDisabledChange(e){this._onDisabledChange.push(e)}_unregisterOnDisabledChange(e){ie(this._onDisabledChange,e)}_forEachChild(e){}_syncPendingControls(){return!("submit"!==this.updateOn||(this._pendingDirty&&this.markAsDirty(),this._pendingTouched&&this.markAsTouched(),!this._pendingChange))&&(this.setValue(this._pendingValue,{onlySelf:!0,emitModelToViewChange:!1}),!0)}_applyFormState(e){re(e)?(this.value=this._pendingValue=e.value,e.disabled?this.disable({onlySelf:!0,emitEvent:!1}):this.enable({onlySelf:!0,emitEvent:!1})):this.value=this._pendingValue=e}},ot={provide:q,useExisting:f(()=>ht)},lt=Promise.resolve(),ht=(()=>{class n extends q{_changeDetectorRef;callSetDisabledState;control=new at;static ngAcceptInputType_isDisabled;_registered=!1;viewModel;name="";isDisabled;model;options;update=new e;constructor(e,s,i,a,o,l){super(),this._changeDetectorRef=o,this.callSetDisabledState=l,this._parent=e,this._setValidators(s),this._setAsyncValidators(i),this.valueAccessor=$e(0,a)}ngOnChanges(e){if(this._checkForErrors(),!this._registered||"name"in e){if(this._registered&&(this._checkName(),this.formDirective)){let s=e.name.previousValue;this.formDirective.removeControl({name:s,path:this._getPath(s)})}this._setUpControl()}"isDisabled"in e&&this._updateDisabled(e),function(e,s){if(!e.hasOwnProperty("model"))return!1;let i=e.model;return!!i.isFirstChange()||!Object.is(s,i.currentValue)}(e,this.viewModel)&&(this._updateValue(this.model),this.viewModel=this.model)}ngOnDestroy(){this.formDirective&&this.formDirective.removeControl(this)}get path(){return this._getPath(this.name)}get formDirective(){return this._parent?this._parent.formDirective:null}viewToModelUpdate(e){this.viewModel=e,this.update.emit(e)}_setUpControl(){this._setUpdateStrategy(),this._isStandalone()?this._setUpStandalone():this.formDirective.addControl(this),this._registered=!0}_setUpdateStrategy(){this.options&&null!=this.options.updateOn&&(this.control._updateOn=this.options.updateOn)}_isStandalone(){return!this._parent||!(!this.options||!this.options.standalone)}_setUpStandalone(){Re(this.control,this,this.callSetDisabledState),this.control.updateValueAndValidity({emitEvent:!1})}_checkForErrors(){this._checkName()}_checkName(){this.options&&this.options.name&&(this.name=this.options.name),!this._isStandalone()&&this.name}_updateValue(e){lt.then(()=>{this.control.setValue(e,{emitViewToModelChange:!1}),this._changeDetectorRef?.markForCheck()})}_updateDisabled(e){let s=e.isDisabled.currentValue,i=0!==s&&D(s);lt.then(()=>{i&&!this.control.disabled?this.control.disable():!i&&this.control.disabled&&this.control.enable(),this._changeDetectorRef?.markForCheck()})}_getPath(e){return this._parent?function(e,s){return[...s.path,e]}(e,this._parent):[e]}static ɵfac=function(e){return new(e||n)(o(L,9),o(j,10),o(H,10),o(F,10),o(w,8),o(it,8))};static ɵdir=h({type:n,selectors:[["","ngModel","",3,"formControlName","",3,"formControl",""]],inputs:{name:"name",isDisabled:[0,"disabled","isDisabled"],model:[0,"ngModel","model"],options:[0,"ngModelOptions","options"]},outputs:{update:"ngModelChange"},exportAs:["ngModel"],standalone:!1,features:[C([ot]),u,k]})}return n})(),ut=(()=>{class n{static ɵfac=function(e){return new(e||n)};static ɵmod=l({type:n});static ɵinj=A({})}return n})(),dt=(()=>{class n{static withConfig(e){return{ngModule:n,providers:[{provide:it,useValue:e.callSetDisabledState??rt}]}}static ɵfac=function(e){return new(e||n)};static ɵmod=l({type:n});static ɵinj=A({imports:[ut]})}return n})();export{N as a,K as b,ht as c,dt as d};