@iaforged/context-code 2.4.6 → 2.4.7

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{MACRO as e,feature as t}from"../../recovery/bunBundleShim.js";import{jsx as o,jsxs as r,Fragment as i}from"react/jsx-runtime";import{memo as n,useEffect as s,useMemo as a,useRef as d,useState as l}from"react";import{isBridgeEnabled as m}from"../../bridge/bridgeEnabled.js";import{getBridgeStatus as c}from"../../bridge/bridgeStatusUtil.js";import{useSetPromptOverlay as p}from"../../context/promptOverlayContext.js";import{useSettings as u}from"../../hooks/useSettings.js";import{useTerminalSize as g}from"../../hooks/useTerminalSize.js";import{Box as f,Text as S}from"../../ink.js";import{useAppState as h}from"../../state/AppState.js";import{isFullscreenEnvEnabled as v}from"../../utils/fullscreen.js";import{isUndercover as j}from"../../utils/undercover.js";import{CoordinatorTaskPanel as x,useCoordinatorTaskCount as b}from"../CoordinatorAgentStatus.js";import{getLastAssistantMessageId as C,StatusLine as I,statusLineShouldDisplay as y}from"../StatusLine.js";import{formatearDuracion as M}from"../../services/objetivo/types.js";import{getTelegramConfig as R}from"../../telegram/config.js";import{getWhatsAppConfig as B}from"../../whatsapp/config.js";import{Notifications as E}from"./Notifications.js";import{PromptInputFooterLeftSide as k}from"./PromptInputFooterLeftSide.js";import{PromptInputFooterSuggestions as A}from"./PromptInputFooterSuggestions.js";import{PromptInputHelpMenu as U}from"./PromptInputHelpMenu.js";export default n(function({apiKeyStatus:t,debug:n,exitMessage:m,vimMode:c,mode:w,autoUpdaterResult:P,isAutoUpdating:$,verbose:D,onAutoUpdaterResult:F,onChangeIsUpdating:T,suggestions:W,selectedSuggestion:L,maxColumnWidth:O,toolPermissionContext:H,helpOpen:Q,suppressHint:X,isLoading:G,tasksSelected:N,teamsSelected:Y,bridgeSelected:_,tmuxSelected:K,teammateFooterIndex:z,ideSelection:V,mcpClients:q,isPasting:J=!1,isInputWrapped:Z=!1,messages:ee,isSearching:te,historyQuery:oe,setHistoryQuery:re,historyFailedMatch:ie,onOpenTasksDialog:ne}){const se=u(),{columns:ae,rows:de}=g(),le=d(ee);le.current=ee;const me=a(()=>C(ee),[ee]),ce=ae<80,pe=v(),ue=pe&&de<24,ge=b(),fe=h(e=>e.coordinatorTaskIndex),Se=h(e=>e.mainLoopModelForSession??e.mainLoopModel),he=h(e=>e.objetivo),[,ve]=l(0);s(()=>{if(!he)return;const e=setInterval(()=>ve(e=>e+1),1e3);return()=>clearInterval(e)},[he]);const je=he?`objetivo | ${M(Date.now()-he.iniciadoEn)} | ${he.turnos}t`:"",xe=!0===B()?.running,be=!0===R()?.isRunning,Ce=xe&&be?"Bridge: WA+TG activo":xe?"Bridge: WA activo":be?"Bridge: TG activo":"",Ie=ce?`Modelo: ${Se}`:`ContextCode v${e.VERSION} | Modelo activo: ${Se}`,ye=Ce?`${Ie} | ${Ce}`:Ie,Me=je?`${je} | ${ye}`:ye,Re=N&&(0===ge||fe<0),Be=X||y(se)||te,Ee=a(()=>pe&&W.length?{suggestions:W,selectedSuggestion:L,maxColumnWidth:O}:null,[pe,W,L,O]);return p(Ee),W.length&&!pe?o(f,{paddingX:2,paddingY:0,children:o(A,{suggestions:W,selectedSuggestion:L,maxColumnWidth:O})}):Q?o(U,{dimColor:!0,fixedWidth:!0,paddingX:2}):r(i,{children:[r(f,{flexDirection:ce?"column":"row",justifyContent:ce?"flex-start":"space-between",paddingX:2,gap:ce?0:1,children:[r(f,{flexDirection:"column",flexShrink:ce?0:1,children:["prompt"===w&&!ue&&!m.show&&!J&&y(se)&&o(I,{messagesRef:le,lastAssistantMessageId:me,vimMode:c}),o(k,{exitMessage:m,vimMode:c,mode:w,toolPermissionContext:H,suppressHint:Be,isLoading:G,tasksSelected:Re,teamsSelected:Y,teammateFooterIndex:z,tmuxSelected:K,isPasting:J,isSearching:te,historyQuery:oe,setHistoryQuery:re,historyFailedMatch:ie,onOpenTasksDialog:ne})]}),r(f,{flexShrink:1,gap:1,children:[pe?null:o(E,{apiKeyStatus:t,autoUpdaterResult:P,debug:n,isAutoUpdating:$,verbose:D,messages:ee,onAutoUpdaterResult:F,onChangeIsUpdating:T,ideSelection:V,mcpClients:q,isInputWrapped:Z,isNarrow:ce}),"ant"===process.env.USER_TYPE&&j()&&o(S,{dimColor:!0,children:"undercover"}),o(BridgeStatusIndicator,{bridgeSelected:_})]})]}),o(f,{paddingX:2,children:o(S,{dimColor:!0,wrap:"truncate",children:Me})}),"ant"===process.env.USER_TYPE&&o(x,{})]})});function BridgeStatusIndicator({bridgeSelected:e}){if(!t("BRIDGE_MODE"))return null;const i=h(e=>e.replBridgeEnabled),n=h(e=>e.replBridgeConnected),s=h(e=>e.replBridgeSessionActive),a=h(e=>e.replBridgeReconnecting),d=h(e=>e.replBridgeExplicit);if(!m()||!i)return null;const l=c({error:void 0,connected:n,sessionActive:s,reconnecting:a});return d||"Reconectando Control Remoto"===l.label?r(S,{color:e?"background":l.color,inverse:e,wrap:"truncate",children:[l.label,e&&o(S,{dimColor:!0,children:" · Enter para ver"})]}):null}
1
+ import{MACRO as e,feature as t}from"../../recovery/bunBundleShim.js";import{jsx as o,jsxs as r,Fragment as i}from"react/jsx-runtime";import{memo as s,useEffect as n,useMemo as a,useRef as d,useState as l}from"react";import{isBridgeEnabled as m}from"../../bridge/bridgeEnabled.js";import{getBridgeStatus as c}from"../../bridge/bridgeStatusUtil.js";import{useSetPromptOverlay as p}from"../../context/promptOverlayContext.js";import{useMainLoopModel as u}from"../../hooks/useMainLoopModel.js";import{useSettings as g}from"../../hooks/useSettings.js";import{useTerminalSize as f}from"../../hooks/useTerminalSize.js";import{Box as h,Text as S}from"../../ink.js";import{useAppState as j}from"../../state/AppState.js";import{isFullscreenEnvEnabled as v}from"../../utils/fullscreen.js";import{isUndercover as x}from"../../utils/undercover.js";import{CoordinatorTaskPanel as b,useCoordinatorTaskCount as C}from"../CoordinatorAgentStatus.js";import{getLastAssistantMessageId as I,StatusLine as y,statusLineShouldDisplay as M}from"../StatusLine.js";import{formatearDuracion as R}from"../../services/objetivo/types.js";import{getTelegramConfig as k}from"../../telegram/config.js";import{getWhatsAppConfig as B}from"../../whatsapp/config.js";import{Notifications as E}from"./Notifications.js";import{PromptInputFooterLeftSide as A}from"./PromptInputFooterLeftSide.js";import{PromptInputFooterSuggestions as U}from"./PromptInputFooterSuggestions.js";import{PromptInputHelpMenu as w}from"./PromptInputHelpMenu.js";export default s(function({apiKeyStatus:t,debug:s,exitMessage:m,vimMode:c,mode:P,autoUpdaterResult:$,isAutoUpdating:D,verbose:T,onAutoUpdaterResult:W,onChangeIsUpdating:F,suggestions:O,selectedSuggestion:H,maxColumnWidth:L,toolPermissionContext:Q,helpOpen:X,suppressHint:G,isLoading:N,tasksSelected:Y,teamsSelected:_,bridgeSelected:K,tmuxSelected:z,teammateFooterIndex:V,ideSelection:q,mcpClients:J,isPasting:Z=!1,isInputWrapped:ee=!1,messages:te,isSearching:oe,historyQuery:re,setHistoryQuery:ie,historyFailedMatch:se,onOpenTasksDialog:ne}){const ae=g(),{columns:de,rows:le}=f(),me=d(te);me.current=te;const ce=a(()=>I(te),[te]),pe=de<80,ue=v(),ge=ue&&le<24,fe=C(),he=j(e=>e.coordinatorTaskIndex),Se=u(),je=j(e=>e.objetivo),[,ve]=l(0);n(()=>{if(!je)return;const e=setInterval(()=>ve(e=>e+1),1e3);return()=>clearInterval(e)},[je]);const xe=je?`objetivo | ${R(Date.now()-je.iniciadoEn)} | ${je.turnos}t`:"",be=!0===B()?.running,Ce=!0===k()?.isRunning,Ie=be&&Ce?"Bridge: WA+TG activo":be?"Bridge: WA activo":Ce?"Bridge: TG activo":"",ye=pe?`Modelo: ${Se}`:`ContextCode v${e.VERSION} | Modelo activo: ${Se}`,Me=Ie?`${ye} | ${Ie}`:ye,Re=xe?`${xe} | ${Me}`:Me,ke=Y&&(0===fe||he<0),Be=G||M(ae)||oe,Ee=a(()=>ue&&O.length?{suggestions:O,selectedSuggestion:H,maxColumnWidth:L}:null,[ue,O,H,L]);return p(Ee),O.length&&!ue?o(h,{paddingX:2,paddingY:0,children:o(U,{suggestions:O,selectedSuggestion:H,maxColumnWidth:L})}):X?o(w,{dimColor:!0,fixedWidth:!0,paddingX:2}):r(i,{children:[r(h,{flexDirection:pe?"column":"row",justifyContent:pe?"flex-start":"space-between",paddingX:2,gap:pe?0:1,children:[r(h,{flexDirection:"column",flexShrink:pe?0:1,children:["prompt"===P&&!ge&&!m.show&&!Z&&M(ae)&&o(y,{messagesRef:me,lastAssistantMessageId:ce,vimMode:c}),o(A,{exitMessage:m,vimMode:c,mode:P,toolPermissionContext:Q,suppressHint:Be,isLoading:N,tasksSelected:ke,teamsSelected:_,teammateFooterIndex:V,tmuxSelected:z,isPasting:Z,isSearching:oe,historyQuery:re,setHistoryQuery:ie,historyFailedMatch:se,onOpenTasksDialog:ne})]}),r(h,{flexShrink:1,gap:1,children:[ue?null:o(E,{apiKeyStatus:t,autoUpdaterResult:$,debug:s,isAutoUpdating:D,verbose:T,messages:te,onAutoUpdaterResult:W,onChangeIsUpdating:F,ideSelection:q,mcpClients:J,isInputWrapped:ee,isNarrow:pe}),"ant"===process.env.USER_TYPE&&x()&&o(S,{dimColor:!0,children:"undercover"}),o(BridgeStatusIndicator,{bridgeSelected:K})]})]}),o(h,{paddingX:2,children:o(S,{dimColor:!0,wrap:"truncate",children:Re})}),"ant"===process.env.USER_TYPE&&o(b,{})]})});function BridgeStatusIndicator({bridgeSelected:e}){if(!t("BRIDGE_MODE"))return null;const i=j(e=>e.replBridgeEnabled),s=j(e=>e.replBridgeConnected),n=j(e=>e.replBridgeSessionActive),a=j(e=>e.replBridgeReconnecting),d=j(e=>e.replBridgeExplicit);if(!m()||!i)return null;const l=c({error:void 0,connected:s,sessionActive:n,reconnecting:a});return d||"Reconectando Control Remoto"===l.label?r(S,{color:e?"background":l.color,inverse:e,wrap:"truncate",children:[l.label,e&&o(S,{dimColor:!0,children:" · Enter para ver"})]}):null}
@@ -1 +1 @@
1
- import{execa as e}from"execa";import{getCwd as t}from"./cwd.js";import{logError as r}from"./log.js";export{execSyncWithDefaults_DEPRECATED}from"./execFileNoThrowPortable.js";export function execFileNoThrow(e,r,o={timeout:6e5,preserveOutputOnError:!0,useCwd:!0}){return execFileNoThrowWithCwd(e,r,{abortSignal:o.abortSignal,timeout:o.timeout,preserveOutputOnError:o.preserveOutputOnError,cwd:o.useCwd?t():void 0,env:o.env,stdin:o.stdin,input:o.input})}function getErrorMessage(e,t){return e.shortMessage?e.shortMessage:"string"==typeof e.signal?e.signal:String(t)}export function execFileNoThrowWithCwd(t,o,{abortSignal:s,timeout:i=6e5,preserveOutputOnError:n=!0,cwd:u,env:d,maxBuffer:c,shell:a,stdin:p,input:l}={timeout:6e5,preserveOutputOnError:!0,maxBuffer:1e6}){return new Promise(f=>{e(t,o,{maxBuffer:c,signal:s,timeout:i,cwd:u,env:d,shell:a,stdin:p,input:l,reject:!1}).then(e=>{if(e.failed)if(n){const t=e.exitCode??1;f({stdout:e.stdout||"",stderr:e.stderr||"",code:t,error:getErrorMessage(e,t)})}else f({stdout:"",stderr:"",code:e.exitCode??1});else f({stdout:e.stdout,stderr:e.stderr,code:0})}).catch(e=>{r(e),f({stdout:"",stderr:"",code:1})})})}
1
+ import{execa as e}from"execa";import{getCwd as t}from"./cwd.js";import{logError as r}from"./log.js";export{execSyncWithDefaults_DEPRECATED}from"./execFileNoThrowPortable.js";export function execFileNoThrow(e,r,o={timeout:6e5,preserveOutputOnError:!0,useCwd:!0}){return execFileNoThrowWithCwd(e,r,{abortSignal:o.abortSignal,timeout:o.timeout,preserveOutputOnError:o.preserveOutputOnError,cwd:o.useCwd?t():void 0,env:o.env,stdin:o.stdin,input:o.input})}function getErrorMessage(e,t){return e.shortMessage?e.shortMessage:"string"==typeof e.signal?e.signal:String(t)}export function execFileNoThrowWithCwd(t,o,{abortSignal:s,timeout:i=6e5,preserveOutputOnError:n=!0,cwd:u,env:d,maxBuffer:c,shell:a,stdin:l,input:p}={timeout:6e5,preserveOutputOnError:!0,maxBuffer:1e6}){return new Promise(f=>{e(t,o,{maxBuffer:c,cancelSignal:s,timeout:i,cwd:u,env:d,shell:a,stdin:l,input:p,reject:!1}).then(e=>{if(e.failed)if(n){const t=e.exitCode??1;f({stdout:e.stdout||"",stderr:e.stderr||"",code:t,error:getErrorMessage(e,t)})}else f({stdout:"",stderr:"",code:e.exitCode??1});else f({stdout:e.stdout,stderr:e.stderr,code:0})}).catch(e=>{r(e),f({stdout:"",stderr:"",code:1})})})}
@@ -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 o}from"../fsOperations.js";import{getSecureStorage as E}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","copilot"],c={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",copilot:"main"},L={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",copilot:"copilot"},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=L[e],i=sanitizeProfileSegment(t);return i===sanitizeProfileSegment(c[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 E().read()}catch{return null}})();for(const t of p){const i=Object.values(n).some(e=>e.provider===t),o=e.providerBaseUrls?.[t],E=e.lastModelByProvider?.[t]??null;if(!(i||e.activeProvider===t||Boolean(o)||null!==E||hasStoredCredentialForProvider(a,t))||i)continue;const d=c[t],_=buildProfileId(t,d),s=(new Date).toISOString();n[_]={id:_,provider:t,name:d,agentName:buildDefaultAgentName(t,d),baseUrl:o??u[t],lastModel:E,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 "),o=e.prepare("\n INSERT INTO provider_runtime_state (key, value)\n VALUES (?, ?)\n ON CONFLICT(key) DO UPDATE SET value = excluded.value\n "),E=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&&o.run(N,n.activeProfileId);const _=t.activeProvider??(n.activeProfileId?n.profiles?.[n.activeProfileId]?.provider:void 0);_&&o.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)E.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;o().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 o}from"../fsOperations.js";import{getSecureStorage as E}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","copilot"],c={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",copilot:"main"},L={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",copilot:"copilot"},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",copilot:"GitHub Copilot"},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=L[e],i=sanitizeProfileSegment(t);return i===sanitizeProfileSegment(c[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 E().read()}catch{return null}})();for(const t of p){const i=Object.values(n).some(e=>e.provider===t),o=e.providerBaseUrls?.[t],E=e.lastModelByProvider?.[t]??null;if(!(i||e.activeProvider===t||Boolean(o)||null!==E||hasStoredCredentialForProvider(a,t))||i)continue;const d=c[t],_=buildProfileId(t,d),s=(new Date).toISOString();n[_]={id:_,provider:t,name:d,agentName:buildDefaultAgentName(t,d),baseUrl:o??u[t],lastModel:E,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 "),o=e.prepare("\n INSERT INTO provider_runtime_state (key, value)\n VALUES (?, ?)\n ON CONFLICT(key) DO UPDATE SET value = excluded.value\n "),E=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&&o.run(N,n.activeProfileId);const _=t.activeProvider??(n.activeProfileId?n.profiles?.[n.activeProfileId]?.provider:void 0);_&&o.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)E.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;o().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]??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{A as e,Aa as r,Ba as i,C as a,Ca as o,Da as l,Ea as u,J as h,P as p,Q as b,a as g,aa as w,c as d,d as v,f,h as E,i as m,j as y,k,l as O,m as T,o as C,pa as A,q as I,r as P,s as S,t as M,wa as N,xa as D,ya as W,za as L}from"./chunk-VAB2VXFI.js";var _="Service workers are disabled or not supported by this browser",x=class{serviceWorker;worker;registration;events;constructor(e,r){if(this.serviceWorker=e,e){let i=null,a=new v;this.worker=new d(e=>(null!==i&&e.next(i),a.subscribe(r=>e.next(r))));let s=()=>{let{controller:r}=e;null!==r&&(i=r,a.next(i))};e.addEventListener("controllerchange",s),s(),this.registration=this.worker.pipe(k(()=>e.getRegistration()));let o=new v;this.events=o.asObservable();let c=e=>{let{data:r}=e;r?.type&&o.next(r)};e.addEventListener("message",c),r?.get(b,null,{optional:!0})?.onDestroy(()=>{e.removeEventListener("controllerchange",s),e.removeEventListener("message",c)})}else this.worker=this.events=this.registration=new d(e=>e.error(new O(5601,!1)))}postMessage(e,r){return new Promise(i=>{this.worker.pipe(y(1)).subscribe(a=>{a.postMessage(g({action:e},r)),i()})})}postMessageWithOperation(e,r,i){let a=this.waitForOperationCompleted(i),o=this.postMessage(e,r);return Promise.all([o,a]).then(([,e])=>e)}generateNonce(){return Math.round(1e7*Math.random())}eventsOfType(e){let r;return r="string"==typeof e?r=>r.type===e:r=>e.includes(r.type),this.events.pipe(m(r))}nextEventOfType(e){return this.eventsOfType(e).pipe(y(1))}waitForOperationCompleted(e){return new Promise((r,i)=>{this.eventsOfType("OPERATION_COMPLETED").pipe(m(r=>r.nonce===e),y(1),f(e=>{if(void 0!==e.result)return e.result;throw new Error(e.error)})).subscribe({next:r,error:i})})}get isEnabled(){return!!this.serviceWorker}},V=(()=>{class n{sw;messages;notificationClicks;subscription;get isEnabled(){return this.sw.isEnabled}pushManager=null;subscriptionChanges=new v;constructor(e){if(this.sw=e,!e.isEnabled)return this.messages=E,this.notificationClicks=E,void(this.subscription=E);this.messages=this.sw.eventsOfType("PUSH").pipe(f(e=>e.data)),this.notificationClicks=this.sw.eventsOfType("NOTIFICATION_CLICK").pipe(f(e=>e.data)),this.pushManager=this.sw.registration.pipe(f(e=>e.pushManager));let r=this.pushManager.pipe(k(e=>e.getSubscription()));this.subscription=new d(e=>{let i=r.subscribe(e),a=this.subscriptionChanges.subscribe(e);return()=>{i.unsubscribe(),a.unsubscribe()}})}requestSubscription(e){if(!this.sw.isEnabled||null===this.pushManager)return Promise.reject(new Error(_));let r={userVisibleOnly:!0},i=this.decodeBase64(e.serverPublicKey.replace(/_/g,"/").replace(/-/g,"+")),a=new Uint8Array(new ArrayBuffer(i.length));for(let e=0;e<i.length;e++)a[e]=i.charCodeAt(e);return r.applicationServerKey=a,new Promise((e,i)=>{this.pushManager.pipe(k(e=>e.subscribe(r)),y(1)).subscribe({next:r=>{this.subscriptionChanges.next(r),e(r)},error:i})})}unsubscribe(){if(!this.sw.isEnabled)return Promise.reject(new Error(_));let t=e=>{if(null===e)throw new O(5602,!1);return e.unsubscribe().then(e=>{if(!e)throw new O(5603,!1);this.subscriptionChanges.next(null)})};return new Promise((e,r)=>{this.subscription.pipe(y(1),k(t)).subscribe({next:e,error:r})})}decodeBase64(e){return atob(e)}static ɵfac=function(e){return new(e||n)(P(x))};static ɵprov=C({token:n,factory:n.ɵfac})}return n})(),F=(()=>{class n{sw;versionUpdates;unrecoverable;get isEnabled(){return this.sw.isEnabled}constructor(e){if(this.sw=e,!e.isEnabled)return this.versionUpdates=E,void(this.unrecoverable=E);this.versionUpdates=this.sw.eventsOfType(["VERSION_DETECTED","VERSION_INSTALLATION_FAILED","VERSION_READY","NO_NEW_VERSION_DETECTED"]),this.unrecoverable=this.sw.eventsOfType("UNRECOVERABLE_STATE")}checkForUpdate(){if(!this.sw.isEnabled)return Promise.reject(new Error(_));let e=this.sw.generateNonce();return this.sw.postMessageWithOperation("CHECK_FOR_UPDATES",{nonce:e},e)}activateUpdate(){if(!this.sw.isEnabled)return Promise.reject(new O(5601,!1));let e=this.sw.generateNonce();return this.sw.postMessageWithOperation("ACTIVATE_UPDATE",{nonce:e},e)}static ɵfac=function(e){return new(e||n)(P(x))};static ɵprov=C({token:n,factory:n.ɵfac})}return n})(),R=new I("");function X(){let e=S(U);if(!("serviceWorker"in navigator)||!1===e.enabled)return;let r=S(R),i=S(a),o=S(b);i.runOutsideAngular(()=>{let e=navigator.serviceWorker,s=()=>e.controller?.postMessage({action:"INITIALIZE"});e.addEventListener("controllerchange",s),o.onDestroy(()=>{e.removeEventListener("controllerchange",s)})}),i.runOutsideAngular(()=>{let i,{registrationStrategy:a}=e;if("function"==typeof a)i=new Promise(e=>a().subscribe(()=>e()));else{let[e,...r]=(a||"registerWhenStable:30000").split(":");switch(e){case"registerImmediately":i=Promise.resolve();break;case"registerWithDelay":i=q(+r[0]||0);break;case"registerWhenStable":i=Promise.race([o.whenStable(),q(+r[0])]);break;default:throw new O(5600,!1)}}i.then(()=>{o.destroyed||navigator.serviceWorker.register(r,{scope:e.scope}).catch(e=>console.error(T(5604,!1)))})})}function q(e){return new Promise(r=>setTimeout(r,e))}function ee(e,r){return new x(!1!==e.enabled?navigator.serviceWorker:void 0,r)}var U=class{enabled;scope;registrationStrategy};N(class n{constructor(){this.auth=S(l),this.socket=S(u)}ngOnInit(){this.auth.hasToken()&&this.socket.connect()}static{this.ɵfac=function(e){return new(e||n)}}static{this.ɵcmp=h({type:n,selectors:[["cx-root"]],decls:1,vars:0,template:function(e,r){1&e&&w(0,"router-outlet")},dependencies:[L],encapsulation:2,changeDetection:0})}},{providers:[i([{path:"",redirectTo:"chat",pathMatch:"full"},{path:"login",loadComponent:()=>import("./chunk-NFYBHCXF.js").then(e=>e.LoginComponent)},{path:"chat",canActivate:[()=>{let e=S(l),i=S(r);return!!e.hasToken()||(i.navigate(["/login"]),!1)}],loadComponent:()=>import("./chunk-AMCDNAIG.js").then(e=>e.ChatComponent)},{path:"**",redirectTo:"chat"}],o()),D(W()),function(r,i={}){return M([V,F,{provide:R,useValue:r},{provide:U,useValue:i},{provide:x,useFactory:ee,deps:[U,e]},p(X)])}("ngsw-worker.js",{enabled:!A(),registrationStrategy:"registerWhenStable:30000"})]}).catch(e=>console.error("[webapp] bootstrap error",e));
1
+ import{A as e,Aa as r,Ba as i,C as a,Ca as o,Da as l,Ea as u,J as h,P as p,Q as b,a as g,aa as w,c as d,d as v,f as E,h as f,i as m,j as y,k as O,l as k,m as T,o as C,pa as A,q as I,r as P,s as S,t as M,wa as N,xa as D,ya as W,za as L}from"./chunk-VAB2VXFI.js";var _="Service workers are disabled or not supported by this browser",x=class{serviceWorker;worker;registration;events;constructor(e,r){if(this.serviceWorker=e,e){let i=null,a=new v;this.worker=new d(e=>(null!==i&&e.next(i),a.subscribe(r=>e.next(r))));let s=()=>{let{controller:r}=e;null!==r&&(i=r,a.next(i))};e.addEventListener("controllerchange",s),s(),this.registration=this.worker.pipe(O(()=>e.getRegistration()));let o=new v;this.events=o.asObservable();let c=e=>{let{data:r}=e;r?.type&&o.next(r)};e.addEventListener("message",c),r?.get(b,null,{optional:!0})?.onDestroy(()=>{e.removeEventListener("controllerchange",s),e.removeEventListener("message",c)})}else this.worker=this.events=this.registration=new d(e=>e.error(new k(5601,!1)))}postMessage(e,r){return new Promise(i=>{this.worker.pipe(y(1)).subscribe(a=>{a.postMessage(g({action:e},r)),i()})})}postMessageWithOperation(e,r,i){let a=this.waitForOperationCompleted(i),o=this.postMessage(e,r);return Promise.all([o,a]).then(([,e])=>e)}generateNonce(){return Math.round(1e7*Math.random())}eventsOfType(e){let r;return r="string"==typeof e?r=>r.type===e:r=>e.includes(r.type),this.events.pipe(m(r))}nextEventOfType(e){return this.eventsOfType(e).pipe(y(1))}waitForOperationCompleted(e){return new Promise((r,i)=>{this.eventsOfType("OPERATION_COMPLETED").pipe(m(r=>r.nonce===e),y(1),E(e=>{if(void 0!==e.result)return e.result;throw new Error(e.error)})).subscribe({next:r,error:i})})}get isEnabled(){return!!this.serviceWorker}},V=(()=>{class n{sw;messages;notificationClicks;subscription;get isEnabled(){return this.sw.isEnabled}pushManager=null;subscriptionChanges=new v;constructor(e){if(this.sw=e,!e.isEnabled)return this.messages=f,this.notificationClicks=f,void(this.subscription=f);this.messages=this.sw.eventsOfType("PUSH").pipe(E(e=>e.data)),this.notificationClicks=this.sw.eventsOfType("NOTIFICATION_CLICK").pipe(E(e=>e.data)),this.pushManager=this.sw.registration.pipe(E(e=>e.pushManager));let r=this.pushManager.pipe(O(e=>e.getSubscription()));this.subscription=new d(e=>{let i=r.subscribe(e),a=this.subscriptionChanges.subscribe(e);return()=>{i.unsubscribe(),a.unsubscribe()}})}requestSubscription(e){if(!this.sw.isEnabled||null===this.pushManager)return Promise.reject(new Error(_));let r={userVisibleOnly:!0},i=this.decodeBase64(e.serverPublicKey.replace(/_/g,"/").replace(/-/g,"+")),a=new Uint8Array(new ArrayBuffer(i.length));for(let e=0;e<i.length;e++)a[e]=i.charCodeAt(e);return r.applicationServerKey=a,new Promise((e,i)=>{this.pushManager.pipe(O(e=>e.subscribe(r)),y(1)).subscribe({next:r=>{this.subscriptionChanges.next(r),e(r)},error:i})})}unsubscribe(){if(!this.sw.isEnabled)return Promise.reject(new Error(_));let t=e=>{if(null===e)throw new k(5602,!1);return e.unsubscribe().then(e=>{if(!e)throw new k(5603,!1);this.subscriptionChanges.next(null)})};return new Promise((e,r)=>{this.subscription.pipe(y(1),O(t)).subscribe({next:e,error:r})})}decodeBase64(e){return atob(e)}static ɵfac=function(e){return new(e||n)(P(x))};static ɵprov=C({token:n,factory:n.ɵfac})}return n})(),F=(()=>{class n{sw;versionUpdates;unrecoverable;get isEnabled(){return this.sw.isEnabled}constructor(e){if(this.sw=e,!e.isEnabled)return this.versionUpdates=f,void(this.unrecoverable=f);this.versionUpdates=this.sw.eventsOfType(["VERSION_DETECTED","VERSION_INSTALLATION_FAILED","VERSION_READY","NO_NEW_VERSION_DETECTED"]),this.unrecoverable=this.sw.eventsOfType("UNRECOVERABLE_STATE")}checkForUpdate(){if(!this.sw.isEnabled)return Promise.reject(new Error(_));let e=this.sw.generateNonce();return this.sw.postMessageWithOperation("CHECK_FOR_UPDATES",{nonce:e},e)}activateUpdate(){if(!this.sw.isEnabled)return Promise.reject(new k(5601,!1));let e=this.sw.generateNonce();return this.sw.postMessageWithOperation("ACTIVATE_UPDATE",{nonce:e},e)}static ɵfac=function(e){return new(e||n)(P(x))};static ɵprov=C({token:n,factory:n.ɵfac})}return n})(),R=new I("");function X(){let e=S(U);if(!("serviceWorker"in navigator)||!1===e.enabled)return;let r=S(R),i=S(a),o=S(b);i.runOutsideAngular(()=>{let e=navigator.serviceWorker,s=()=>e.controller?.postMessage({action:"INITIALIZE"});e.addEventListener("controllerchange",s),o.onDestroy(()=>{e.removeEventListener("controllerchange",s)})}),i.runOutsideAngular(()=>{let i,{registrationStrategy:a}=e;if("function"==typeof a)i=new Promise(e=>a().subscribe(()=>e()));else{let[e,...r]=(a||"registerWhenStable:30000").split(":");switch(e){case"registerImmediately":i=Promise.resolve();break;case"registerWithDelay":i=q(+r[0]||0);break;case"registerWhenStable":i=Promise.race([o.whenStable(),q(+r[0])]);break;default:throw new k(5600,!1)}}i.then(()=>{o.destroyed||navigator.serviceWorker.register(r,{scope:e.scope}).catch(e=>console.error(T(5604,!1)))})})}function q(e){return new Promise(r=>setTimeout(r,e))}function ee(e,r){return new x(!1!==e.enabled?navigator.serviceWorker:void 0,r)}var U=class{enabled;scope;registrationStrategy};N(class n{constructor(){this.auth=S(l),this.socket=S(u)}ngOnInit(){this.auth.hasToken()&&this.socket.connect()}static{this.ɵfac=function(e){return new(e||n)}}static{this.ɵcmp=h({type:n,selectors:[["cx-root"]],decls:1,vars:0,template:function(e,r){1&e&&w(0,"router-outlet")},dependencies:[L],encapsulation:2,changeDetection:0})}},{providers:[i([{path:"",redirectTo:"chat",pathMatch:"full"},{path:"login",loadComponent:()=>import("./chunk-NFYBHCXF.js").then(e=>e.LoginComponent)},{path:"chat",canActivate:[()=>{let e=S(l),i=S(r);return!!e.hasToken()||(i.navigate(["/login"]),!1)}],loadComponent:()=>import("./chunk-AMCDNAIG.js").then(e=>e.ChatComponent)},{path:"**",redirectTo:"chat"}],o()),D(W()),function(r,i={}){return M([V,F,{provide:R,useValue:r},{provide:U,useValue:i},{provide:x,useFactory:ee,deps:[U,e]},p(X)])}("ngsw-worker.js",{enabled:!A(),registrationStrategy:"registerWhenStable:30000"})]}).catch(e=>console.error("[webapp] bootstrap error",e));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iaforged/context-code",
3
- "version": "2.4.6",
3
+ "version": "2.4.7",
4
4
  "description": "Context Code es un asistente de desarrollo para la terminal. Puede revisar tu proyecto, editar archivos, ejecutar comandos y apoyarte en tareas reales de programacion.",
5
5
  "author": "Context AI",
6
6
  "license": "MIT",