@agenthippo-ai/agenthippo 1.110.46 → 1.110.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/out/extension.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /*! Copyright (c) 2026 AgentHippo.ai. All rights reserved. Proprietary; see LICENSE. */
2
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(t,r,e,m){m===void 0&&(m=e);var E=Object.getOwnPropertyDescriptor(r,e);(!E||("get"in E?!r.__esModule:E.writable||E.configurable))&&(E={enumerable:!0,get:function(){return r[e]}}),Object.defineProperty(t,m,E)}):(function(t,r,e,m){m===void 0&&(m=e),t[m]=r[e]})),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?(function(t,r){Object.defineProperty(t,"default",{enumerable:!0,value:r})}):function(t,r){t.default=r}),__importStar=this&&this.__importStar||(function(){var t=function(r){return t=Object.getOwnPropertyNames||function(e){var m=[];for(var E in e)Object.prototype.hasOwnProperty.call(e,E)&&(m[m.length]=E);return m},t(r)};return function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var m=t(r),E=0;E<m.length;E++)m[E]!=="default"&&__createBinding(e,r,m[E]);return __setModuleDefault(e,r),e}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.activate=activate,exports.deactivate=deactivate;const vscode=__importStar(require("vscode")),fs_1=require("fs"),path=__importStar(require("path")),os=__importStar(require("os")),types_1=require("./engines/types"),factory_1=require("./engines/factory"),sync_1=require("./sync"),session_1=require("./session"),utils_1=require("./utils"),agentEnvFile_1=require("./utils/agentEnvFile"),index_1=require("./utils/index"),runtime_1=require("./cli/runtime"),mcp_1=require("./mcp"),terminalLogger_1=require("./terminalLogger"),workspaceFolders_1=require("./workspaceFolders"),branding_1=require("./branding"),binary_1=require("./utils/binary"),paths_1=require("./agentpack/paths"),permissions_1=require("./permissions"),vscode_edit_tracker_1=require("./runtime/vscode/vscode-edit-tracker"),vscode_logger_1=require("./runtime/vscode/vscode-logger"),vscode_config_provider_1=require("./runtime/vscode/vscode-config-provider"),permission_handler_1=require("./runtime/interfaces/permission-handler"),customRegistry_1=require("./engines/customRegistry"),handleRemoteChat_js_1=require("./remote/handleRemoteChat.js"),serveClient_js_1=require("./remote/serveClient.js"),remotePackStatusBar_js_1=require("./remote/remotePackStatusBar.js"),provider_js_1=require("./auth/provider.js"),signInFlow_js_1=require("./auth/signInFlow.js"),onboardingPrompt_js_1=require("./auth/onboardingPrompt.js"),githubStoreGate_js_1=require("./auth/githubStoreGate.js"),sessionEvents_1=require("./analytics/sessionEvents"),base_1=require("./engines/base"),turn_scope_1=require("./cli/data-plane/turn-scope"),BUNDLED_TOOLS_DIR_KEY="agentide.bundledToolsDir",AGENTIDE_SESSIONS_DIR_NAME=`${paths_1.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}/${paths_1.AGENT_CONSTANTS.SESSIONS_DIR}`,TERMINAL_LOG_FILE_NAME="terminal.md",MAX_TERMINAL_LOG_BYTES=2*1024*1024,ATTACHMENTS_DIR_NAME="attachments";let _state,_extensionContext;const _activeRunsByStreamId=new Map,_ideTurnScopes=new Map;function getIdeTurnScope(t,r,e,m,E){const h=`${t}::${r}`;let C=_ideTurnScopes.get(h);return C||(C=(0,turn_scope_1.resolveLocalTurnScope)({spec:m?.spec,packPath:e,agent:m?{pack:m.metadata.name,version:m.metadata.version}:void 0,logger:new vscode_logger_1.VSCodeLogger(E,"[DataPlane]"),audit:(A,T,n)=>_sessionEventWriter.append(A,(0,base_1.generateRequestId)(),T,n)}).then(A=>(A&&log(E,`[AgentIDE] Data plane ${A.mode} \u2014 gateway ${A.gatewayUrl}; acting as ${A.userId} (locally asserted; per-turn registration)`),A)).catch(A=>{throw _ideTurnScopes.delete(h),A}),_ideTurnScopes.set(h,C)),C}const _pendingQuestionsById=new Map,STREAM_QUESTION_TIMEOUT_MS=1e3*60*10;function resolvePendingQuestion(t,r){const e=_pendingQuestionsById.get(t);return e?(clearTimeout(e.timeout),_pendingQuestionsById.delete(t),e.resolver(r),!0):!1}function rejectPendingQuestionsForStream(t,r){for(const[e,m]of _pendingQuestionsById)m.streamId===t&&(clearTimeout(m.timeout),_pendingQuestionsById.delete(e),m.rejecter(new Error(r)))}async function askQuestionFromChatUI(t,r){return await new Promise((e,m)=>{const E=setTimeout(()=>{_pendingQuestionsById.delete(r.questionId),m(new Error("Question timed out waiting for user response"))},STREAM_QUESTION_TIMEOUT_MS);_pendingQuestionsById.set(r.questionId,{streamId:t,question:r,resolver:e,rejecter:m,timeout:E}),Promise.resolve(vscode.commands.executeCommand("agentide.streamCallback",{streamId:t,type:"question",metadata:r})).catch(h=>{clearTimeout(E),_pendingQuestionsById.delete(r.questionId),m(h instanceof Error?h:new Error(String(h)))})})}function normalizeQuestionAnswer(t){const r=t&&typeof t=="object"?t:{},e=Array.isArray(r.selected)?r.selected.filter(E=>typeof E=="string"&&E.trim().length>0):[],m=typeof r.freeText=="string"?r.freeText:(r.freeText===null,null);return{selected:e,freeText:m,declined:r.declined===!0,timedOut:r.timedOut===!0,cancelled:r.cancelled===!0}}function questionPromptToHeader(t){const r=t.split(/\r?\n/,1)[0]?.trim()||"Question";return r.length<=50?r:`${r.slice(0,47)}...`}function streamPayloadToAskQuestionsInput(t){const e={header:questionPromptToHeader(t.prompt),question:t.prompt,multiSelect:t.multiSelect,allowFreeformInput:t.allowFreeText};return t.options?.length&&(e.options=t.options.map(m=>({label:m.label,description:m.description,recommended:m.recommended}))),{questions:[e]}}async function askQuestionViaWorkbenchTool(t,r,e,m){const E=new vscode.CancellationTokenSource;m.addEventListener("abort",()=>E.cancel(),{once:!0});try{const h=streamPayloadToAskQuestionsInput(e),T=(await vscode.lm.invokeTool("vscode_askQuestions",{input:h,toolInvocationToken:{sessionResource:vscode.Uri.parse(t)}},E.token))?.content?.find(l=>typeof l.value=="string")?.value;if(!T)return{selected:[],freeText:null,declined:!0};const s=JSON.parse(T)?.answers??{},c=Object.keys(s)[0],i=c?s[c]:void 0;return i?{selected:i.selected??[],freeText:i.freeText??null,declined:i.skipped===!0}:{selected:[],freeText:null,declined:!0}}catch(h){const C=h instanceof Error&&(h.name==="Canceled"||h.message?.includes("cancel"));return{selected:[],freeText:null,declined:!0,cancelled:C}}finally{E.dispose()}}const SESSION_CLEANUP_INTERVAL_MS=1e3*60*5;function log(t,r){t.appendLine((0,branding_1.brandify)(r))}function logConsole(t){console.log((0,branding_1.brandify)(t))}function showInfo(t){return vscode.window.showInformationMessage((0,branding_1.brandify)(t))}function showWarning(t){return vscode.window.showWarningMessage((0,branding_1.brandify)(t))}function showError(t){return vscode.window.showErrorMessage((0,branding_1.brandify)(t))}async function activate(t){const r=vscode.window.createOutputChannel(branding_1.AGENTIDE_EXTENSION_NAME);log(r,`${branding_1.AGENTIDE_BRAND_NAME} extension activating...`),logConsole(`${branding_1.AGENTIDE_BRAND_NAME} extension activating...`);try{const g=await(0,agentEnvFile_1.mergeAgentHomeEnvIntoProcessEnv)();g.applied.length>0&&log(r,`[AgentIDE] Loaded ${g.applied.length} env var(s) from ${g.envFilePath} (shell env wins on conflict)`)}catch(g){const D=g instanceof Error?g.message:String(g);log(r,`[AgentIDE] Warning: failed to load ~/.agent-hippo/.env: ${D}`)}_extensionContext=t;const e=(0,utils_1.getAnalyticsScriptsDir)(t.extensionPath);process.env.AGENTIDE_ANALYTICS_SCRIPTS_DIR=e,log(r,`[AgentIDE] Analytics scripts dir: ${e}`),(0,session_1.initSessionStore)(t);const m=new vscode_logger_1.VSCodeLogger(r,"[Maintenance]"),E=setInterval(()=>{if((0,session_1.runSessionMaintenance)(),_state)for(const g of Object.values(_state.engines))g.onMaintenance(m)},SESSION_CLEANUP_INTERVAL_MS);t.subscriptions.push(new vscode.Disposable(()=>clearInterval(E)));const h=t.storageUri??t.globalStorageUri,C=t.storageUri?"per-workspace":"global",A={storagePath:h.fsPath},T=process.env.AGENTHIPPO_LITELLM_API_KEY?.trim()||process.env.LITELLM_MASTER_KEY?.trim();T&&(A.litellmApiKey=T,log(r,"[AgentIDE] Using local LiteLLM key from ~/.agent-hippo/.env"));for(const g of Object.values(types_1.AGENT_ENGINES)){const D=path.join(h.fsPath,g.id);try{await fs_1.promises.mkdir(D,{recursive:!0}),log(r,`[AgentIDE] ${g.displayName} dir: ${D} (${C})`),g.configEnvVar==="CODEX_HOME"?A.codexHome=D:g.configEnvVar==="CLAUDE_CONFIG_DIR"&&(A.claudeConfigDir=D)}catch(M){log(r,`[AgentIDE] Warning: failed to create ${g.id} dir: ${M instanceof Error?M.message:String(M)}`)}}const n=new sync_1.SyncService(()=>getBundledBasePromptsDir()),s=(0,factory_1.createEngines)({config:A,syncService:n,getBundledBasePromptsDir:()=>getBundledBasePromptsDir()});_state={outputChannel:r,engines:s,syncService:n,config:A};try{const g=vscode.workspace.getConfiguration("chat"),D=g.inspect("useAgentSkills");D&&!D.globalValue&&!D.workspaceValue&&!D.workspaceFolderValue&&(await g.update("useAgentSkills",!0,vscode.ConfigurationTarget.Global),log(r,"[AgentIDE] Enabled Agent Skills by default"))}catch(g){log(r,`[AgentIDE] Warning: failed to enable Agent Skills setting: ${g instanceof Error?g.message:String(g)}`)}await registerBundledMcpServers(t,r),(0,provider_js_1.registerAgentHippoAuth)(t),(0,provider_js_1.refreshBootstrapIfSignedIn)(t),t.subscriptions.push((0,provider_js_1.startAgentHippoTokenRefreshTimer)(t)),(0,onboardingPrompt_js_1.scheduleSignInOnboardingPrompt)(t),registerCommands(t,_state);const c=new remotePackStatusBar_js_1.RemotePackStatusBar(n,()=>getWorkspaceRoot(r).workspaceRoot,r);_state.remotePackStatusBar=c,t.subscriptions.push(c),c.refresh();const{GatewayLifecycleManager:i}=await import("./gateway/lifecycle.js");_state.gatewayLifecycle=new i(r,t),t.subscriptions.push({dispose:()=>_state?.gatewayLifecycle?.dispose()});const{GatewayService:l}=await import("./gateway/service.js");_state.gatewayService=new l(t,r),t.subscriptions.push({dispose:()=>_state?.gatewayService?.dispose()}),_state.gatewayLifecycle.setBridgeRef(_state.gatewayService),_state.gatewayLifecycle.onStatusChange(async g=>{g==="running"&&vscode.workspace.getConfiguration("agentide.anywhere").get("autoConnect",!1)&&_state?.gatewayLifecycle&&_state.gatewayLifecycle.connectBridge()});const{AnalyticsService:u}=await import("./analytics/service.js");_state.analyticsService=new u(t,r),t.subscriptions.push({dispose:()=>_state?.analyticsService?.dispose()});const{AnalyticsDashboardProvider:d,ArtifactManagerImpl:o,QueryRunnerImpl:a,ensureBundledFleetAdapters:p}=await import("./analytics/dashboard/index.js"),S=new o(r),k=new o(r),y=new a(r);p(y);const $=_state.analyticsService;_state.analyticsDashboard=new d(t,y,S,r,()=>$?.getIndexingService());const f=new d(t,y,k,r,()=>$?.getIndexingService(),"team");_state.analyticsTeamDashboard=f,t.subscriptions.push(vscode.window.registerWebviewViewProvider(d.viewType,_state.analyticsDashboard,{webviewOptions:{retainContextWhenHidden:!0}}),vscode.window.registerWebviewViewProvider("agentide.teamView",f,{webviewOptions:{retainContextWhenHidden:!0}}),_state.analyticsDashboard,f,{dispose:()=>S.dispose()},{dispose:()=>k.dispose()},{dispose:()=>y.dispose()}),t.subscriptions.push(vscode.commands.registerCommand("agentide.analytics.openDashboard",()=>{vscode.commands.executeCommand("agentide.analyticsView.focus")}),vscode.commands.registerCommand("agentide.fleet.open",async()=>{const g=_state?.analyticsTeamDashboard;g&&await g.openWithView("fleet"),await vscode.commands.executeCommand("agentide.teamView.focus")}),vscode.commands.registerCommand("agentide.analytics.clearArtifacts",async()=>{const g=await S.cleanup(0);await t.workspaceState.update("analytics.generatedDefaultDashboard",!1),vscode.window.showInformationMessage(`Cleared ${g.deletedCount} Spotlight artifacts (${(g.freedBytes/1024).toFixed(1)} KB)`)}),vscode.commands.registerCommand("agentide.analytics.regenerateDefaults",async()=>{_state?.analyticsDashboard&&(y.invalidateCache(),await _state.analyticsDashboard.runDefaultChartScript())}),vscode.commands.registerCommand("agentide.persistChatVote",async g=>{!g?.sessionId||!g?.requestId||await _sessionEventWriter.append(g.sessionId,g.requestId,"vote",{direction:g.direction,reason:g.reason,agentId:g.agentId,command:g.command})})),(0,terminalLogger_1.activateTerminalLogger)(t);const w=setTimeout(()=>{(0,terminalLogger_1.cleanupOldSessionLogs)(r)},5e3);t.subscriptions.push(new vscode.Disposable(()=>clearTimeout(w)));const I=setTimeout(async()=>{try{const{initializeStoreIndex:g}=await import("./store/oramaIndex.js");await g(r)}catch(g){log(r,`[AgentIDE] Store index init: ${g instanceof Error?g.message:String(g)}`)}},3e3);t.subscriptions.push(new vscode.Disposable(()=>clearTimeout(I))),vscode.workspace.workspaceFolders?.length&&refreshAgentideProject(_state).then(async()=>{n.ensureAgentideWatchers(r);try{const{workspaceRoot:g}=getWorkspaceRoot(r),{AgentPackManager:D}=await import("./agentpack/index.js"),M=new D(n,()=>g,()=>A.storagePath,r),{registered:b}=await M.repairUnregisteredAgents();b.length>0&&log(r,`[AgentIDE] Auto-repaired ${b.length} unregistered pack(s): ${b.join(", ")}`)}catch(g){log(r,`[AgentIDE] Pack repair check failed: ${g instanceof Error?g.message:String(g)}`)}_state?.remotePackStatusBar?.refresh()}),t.subscriptions.push(vscode.workspace.onDidChangeWorkspaceFolders(()=>{n.ensureAgentideWatchers(r),_state&&(refreshAgentideProject(_state),_state.remotePackStatusBar?.refresh())})),t.subscriptions.push(new vscode.Disposable(()=>{n.disposeAllWatchers()})),log(r,"[AgentIDE] Extension activation complete")}function deactivate(){if(_state)for(const t of Object.values(_state.engines))try{t.dispose()}catch{}for(const t of _ideTurnScopes.values())t.then(r=>r?.close()).catch(()=>{});_ideTurnScopes.clear(),_state=void 0}function escapeRegExp(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function quoteEnvValue(t){return/^[A-Za-z0-9_./:@-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function upsertEnvVar(t,r,e){const m=t.split(/\r?\n/),E=new RegExp(`^\\s*(?:export\\s+)?${escapeRegExp(r)}\\s*=`);let h=!1;for(let C=0;C<m.length;C++){const A=m[C],T=A.trim();!T||T.startsWith("#")||E.test(A)&&(m[C]=`${r}=${quoteEnvValue(e)}`,h=!0)}return h||(m.length>0&&m[m.length-1].trim()!==""&&m.push(""),m.push(`${r}=${quoteEnvValue(e)}`)),m.join(`
2
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(t,r,e,m){m===void 0&&(m=e);var E=Object.getOwnPropertyDescriptor(r,e);(!E||("get"in E?!r.__esModule:E.writable||E.configurable))&&(E={enumerable:!0,get:function(){return r[e]}}),Object.defineProperty(t,m,E)}):(function(t,r,e,m){m===void 0&&(m=e),t[m]=r[e]})),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?(function(t,r){Object.defineProperty(t,"default",{enumerable:!0,value:r})}):function(t,r){t.default=r}),__importStar=this&&this.__importStar||(function(){var t=function(r){return t=Object.getOwnPropertyNames||function(e){var m=[];for(var E in e)Object.prototype.hasOwnProperty.call(e,E)&&(m[m.length]=E);return m},t(r)};return function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var m=t(r),E=0;E<m.length;E++)m[E]!=="default"&&__createBinding(e,r,m[E]);return __setModuleDefault(e,r),e}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.activate=activate,exports.deactivate=deactivate;const vscode=__importStar(require("vscode")),fs_1=require("fs"),path=__importStar(require("path")),os=__importStar(require("os")),types_1=require("./engines/types"),factory_1=require("./engines/factory"),sync_1=require("./sync"),session_1=require("./session"),utils_1=require("./utils"),agentEnvFile_1=require("./utils/agentEnvFile"),index_1=require("./utils/index"),runtime_1=require("./cli/runtime"),mcp_1=require("./mcp"),terminalLogger_1=require("./terminalLogger"),workspaceFolders_1=require("./workspaceFolders"),branding_1=require("./branding"),binary_1=require("./utils/binary"),paths_1=require("./agentpack/paths"),permissions_1=require("./permissions"),vscode_edit_tracker_1=require("./runtime/vscode/vscode-edit-tracker"),vscode_logger_1=require("./runtime/vscode/vscode-logger"),vscode_config_provider_1=require("./runtime/vscode/vscode-config-provider"),permission_handler_1=require("./runtime/interfaces/permission-handler"),customRegistry_1=require("./engines/customRegistry"),handleRemoteChat_js_1=require("./remote/handleRemoteChat.js"),serveClient_js_1=require("./remote/serveClient.js"),remotePackStatusBar_js_1=require("./remote/remotePackStatusBar.js"),provider_js_1=require("./auth/provider.js"),signInFlow_js_1=require("./auth/signInFlow.js"),onboardingPrompt_js_1=require("./auth/onboardingPrompt.js"),githubStoreGate_js_1=require("./auth/githubStoreGate.js"),sessionEvents_1=require("./analytics/sessionEvents"),base_1=require("./engines/base"),turn_scope_1=require("./cli/data-plane/turn-scope"),idle_1=require("./engines/idle"),BUNDLED_TOOLS_DIR_KEY="agentide.bundledToolsDir",AGENTIDE_SESSIONS_DIR_NAME=`${paths_1.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}/${paths_1.AGENT_CONSTANTS.SESSIONS_DIR}`,TERMINAL_LOG_FILE_NAME="terminal.md",MAX_TERMINAL_LOG_BYTES=2*1024*1024,ATTACHMENTS_DIR_NAME="attachments";let _state,_extensionContext;const _activeRunsByStreamId=new Map,_ideTurnScopes=new Map;function getIdeTurnScope(t,r,e,m,E){const h=`${t}::${r}`;let C=_ideTurnScopes.get(h);return C||(C=(0,turn_scope_1.resolveLocalTurnScope)({spec:m?.spec,packPath:e,agent:m?{pack:m.metadata.name,version:m.metadata.version}:void 0,logger:new vscode_logger_1.VSCodeLogger(E,"[DataPlane]"),audit:(A,T,n)=>_sessionEventWriter.append(A,(0,base_1.generateRequestId)(),T,n)}).then(A=>(A&&log(E,`[AgentIDE] Data plane ${A.mode} \u2014 gateway ${A.gatewayUrl}; acting as ${A.userId} (locally asserted; per-turn registration)`),A)).catch(A=>{throw _ideTurnScopes.delete(h),A}),_ideTurnScopes.set(h,C)),C}const _pendingQuestionsById=new Map,STREAM_QUESTION_TIMEOUT_MS=1e3*60*10;function resolvePendingQuestion(t,r){const e=_pendingQuestionsById.get(t);return e?(clearTimeout(e.timeout),_pendingQuestionsById.delete(t),e.resolver(r),!0):!1}function rejectPendingQuestionsForStream(t,r){for(const[e,m]of _pendingQuestionsById)m.streamId===t&&(clearTimeout(m.timeout),_pendingQuestionsById.delete(e),m.rejecter(new Error(r)))}async function askQuestionFromChatUI(t,r){return await new Promise((e,m)=>{const E=setTimeout(()=>{_pendingQuestionsById.delete(r.questionId),m(new Error("Question timed out waiting for user response"))},STREAM_QUESTION_TIMEOUT_MS);_pendingQuestionsById.set(r.questionId,{streamId:t,question:r,resolver:e,rejecter:m,timeout:E}),Promise.resolve(vscode.commands.executeCommand("agentide.streamCallback",{streamId:t,type:"question",metadata:r})).catch(h=>{clearTimeout(E),_pendingQuestionsById.delete(r.questionId),m(h instanceof Error?h:new Error(String(h)))})})}function normalizeQuestionAnswer(t){const r=t&&typeof t=="object"?t:{},e=Array.isArray(r.selected)?r.selected.filter(E=>typeof E=="string"&&E.trim().length>0):[],m=typeof r.freeText=="string"?r.freeText:(r.freeText===null,null);return{selected:e,freeText:m,declined:r.declined===!0,timedOut:r.timedOut===!0,cancelled:r.cancelled===!0}}function questionPromptToHeader(t){const r=t.split(/\r?\n/,1)[0]?.trim()||"Question";return r.length<=50?r:`${r.slice(0,47)}...`}function streamPayloadToAskQuestionsInput(t){const e={header:questionPromptToHeader(t.prompt),question:t.prompt,multiSelect:t.multiSelect,allowFreeformInput:t.allowFreeText};return t.options?.length&&(e.options=t.options.map(m=>({label:m.label,description:m.description,recommended:m.recommended}))),{questions:[e]}}async function askQuestionViaWorkbenchTool(t,r,e,m){const E=new vscode.CancellationTokenSource;m.addEventListener("abort",()=>E.cancel(),{once:!0});try{const h=streamPayloadToAskQuestionsInput(e),T=(await vscode.lm.invokeTool("vscode_askQuestions",{input:h,toolInvocationToken:{sessionResource:vscode.Uri.parse(t)}},E.token))?.content?.find(l=>typeof l.value=="string")?.value;if(!T)return{selected:[],freeText:null,declined:!0};const s=JSON.parse(T)?.answers??{},c=Object.keys(s)[0],i=c?s[c]:void 0;return i?{selected:i.selected??[],freeText:i.freeText??null,declined:i.skipped===!0}:{selected:[],freeText:null,declined:!0}}catch(h){const C=h instanceof Error&&(h.name==="Canceled"||h.message?.includes("cancel"));return{selected:[],freeText:null,declined:!0,cancelled:C}}finally{E.dispose()}}function log(t,r){t.appendLine((0,branding_1.brandify)(r))}function logConsole(t){console.log((0,branding_1.brandify)(t))}function showInfo(t){return vscode.window.showInformationMessage((0,branding_1.brandify)(t))}function showWarning(t){return vscode.window.showWarningMessage((0,branding_1.brandify)(t))}function showError(t){return vscode.window.showErrorMessage((0,branding_1.brandify)(t))}async function activate(t){const r=vscode.window.createOutputChannel(branding_1.AGENTIDE_EXTENSION_NAME);log(r,`${branding_1.AGENTIDE_BRAND_NAME} extension activating...`),logConsole(`${branding_1.AGENTIDE_BRAND_NAME} extension activating...`);try{const g=await(0,agentEnvFile_1.mergeAgentHomeEnvIntoProcessEnv)();g.applied.length>0&&log(r,`[AgentIDE] Loaded ${g.applied.length} env var(s) from ${g.envFilePath} (shell env wins on conflict)`)}catch(g){const S=g instanceof Error?g.message:String(g);log(r,`[AgentIDE] Warning: failed to load ~/.agent-hippo/.env: ${S}`)}_extensionContext=t;const e=(0,utils_1.getAnalyticsScriptsDir)(t.extensionPath);process.env.AGENTIDE_ANALYTICS_SCRIPTS_DIR=e,log(r,`[AgentIDE] Analytics scripts dir: ${e}`),(0,session_1.initSessionStore)(t);const m=new vscode_logger_1.VSCodeLogger(r,"[Maintenance]"),E=setInterval(()=>{if((0,session_1.runSessionMaintenance)(),_state)for(const g of Object.values(_state.engines))g.onMaintenance(m)},(0,idle_1.engineMaintenanceIntervalMs)());t.subscriptions.push(new vscode.Disposable(()=>clearInterval(E)));const h=t.storageUri??t.globalStorageUri,C=t.storageUri?"per-workspace":"global",A={storagePath:h.fsPath},T=process.env.AGENTHIPPO_LITELLM_API_KEY?.trim()||process.env.LITELLM_MASTER_KEY?.trim();T&&(A.litellmApiKey=T,log(r,"[AgentIDE] Using local LiteLLM key from ~/.agent-hippo/.env"));for(const g of Object.values(types_1.AGENT_ENGINES)){const S=path.join(h.fsPath,g.id);try{await fs_1.promises.mkdir(S,{recursive:!0}),log(r,`[AgentIDE] ${g.displayName} dir: ${S} (${C})`),g.configEnvVar==="CODEX_HOME"?A.codexHome=S:g.configEnvVar==="CLAUDE_CONFIG_DIR"&&(A.claudeConfigDir=S)}catch(M){log(r,`[AgentIDE] Warning: failed to create ${g.id} dir: ${M instanceof Error?M.message:String(M)}`)}}const n=new sync_1.SyncService(()=>getBundledBasePromptsDir()),s=(0,factory_1.createEngines)({config:A,syncService:n,getBundledBasePromptsDir:()=>getBundledBasePromptsDir()});_state={outputChannel:r,engines:s,syncService:n,config:A};try{const g=vscode.workspace.getConfiguration("chat"),S=g.inspect("useAgentSkills");S&&!S.globalValue&&!S.workspaceValue&&!S.workspaceFolderValue&&(await g.update("useAgentSkills",!0,vscode.ConfigurationTarget.Global),log(r,"[AgentIDE] Enabled Agent Skills by default"))}catch(g){log(r,`[AgentIDE] Warning: failed to enable Agent Skills setting: ${g instanceof Error?g.message:String(g)}`)}await registerBundledMcpServers(t,r),(0,provider_js_1.registerAgentHippoAuth)(t),(0,provider_js_1.refreshBootstrapIfSignedIn)(t),t.subscriptions.push((0,provider_js_1.startAgentHippoTokenRefreshTimer)(t)),(0,onboardingPrompt_js_1.scheduleSignInOnboardingPrompt)(t),registerCommands(t,_state);const c=new remotePackStatusBar_js_1.RemotePackStatusBar(n,()=>getWorkspaceRoot(r).workspaceRoot,r);_state.remotePackStatusBar=c,t.subscriptions.push(c),c.refresh();const{GatewayLifecycleManager:i}=await import("./gateway/lifecycle.js");_state.gatewayLifecycle=new i(r,t),t.subscriptions.push({dispose:()=>_state?.gatewayLifecycle?.dispose()});const{GatewayService:l}=await import("./gateway/service.js");_state.gatewayService=new l(t,r),t.subscriptions.push({dispose:()=>_state?.gatewayService?.dispose()}),_state.gatewayLifecycle.setBridgeRef(_state.gatewayService),_state.gatewayLifecycle.onStatusChange(async g=>{g==="running"&&vscode.workspace.getConfiguration("agentide.anywhere").get("autoConnect",!1)&&_state?.gatewayLifecycle&&_state.gatewayLifecycle.connectBridge()});const{AnalyticsService:u}=await import("./analytics/service.js");_state.analyticsService=new u(t,r),t.subscriptions.push({dispose:()=>_state?.analyticsService?.dispose()});const{AnalyticsDashboardProvider:d,ArtifactManagerImpl:o,QueryRunnerImpl:a,ensureBundledFleetAdapters:p}=await import("./analytics/dashboard/index.js"),D=new o(r),k=new o(r),y=new a(r);p(y);const $=_state.analyticsService;_state.analyticsDashboard=new d(t,y,D,r,()=>$?.getIndexingService());const f=new d(t,y,k,r,()=>$?.getIndexingService(),"team");_state.analyticsTeamDashboard=f,t.subscriptions.push(vscode.window.registerWebviewViewProvider(d.viewType,_state.analyticsDashboard,{webviewOptions:{retainContextWhenHidden:!0}}),vscode.window.registerWebviewViewProvider("agentide.teamView",f,{webviewOptions:{retainContextWhenHidden:!0}}),_state.analyticsDashboard,f,{dispose:()=>D.dispose()},{dispose:()=>k.dispose()},{dispose:()=>y.dispose()}),t.subscriptions.push(vscode.commands.registerCommand("agentide.analytics.openDashboard",()=>{vscode.commands.executeCommand("agentide.analyticsView.focus")}),vscode.commands.registerCommand("agentide.fleet.open",async()=>{const g=_state?.analyticsTeamDashboard;g&&await g.openWithView("fleet"),await vscode.commands.executeCommand("agentide.teamView.focus")}),vscode.commands.registerCommand("agentide.analytics.clearArtifacts",async()=>{const g=await D.cleanup(0);await t.workspaceState.update("analytics.generatedDefaultDashboard",!1),vscode.window.showInformationMessage(`Cleared ${g.deletedCount} Spotlight artifacts (${(g.freedBytes/1024).toFixed(1)} KB)`)}),vscode.commands.registerCommand("agentide.analytics.regenerateDefaults",async()=>{_state?.analyticsDashboard&&(y.invalidateCache(),await _state.analyticsDashboard.runDefaultChartScript())}),vscode.commands.registerCommand("agentide.persistChatVote",async g=>{!g?.sessionId||!g?.requestId||await _sessionEventWriter.append(g.sessionId,g.requestId,"vote",{direction:g.direction,reason:g.reason,agentId:g.agentId,command:g.command})})),(0,terminalLogger_1.activateTerminalLogger)(t);const w=setTimeout(()=>{(0,terminalLogger_1.cleanupOldSessionLogs)(r)},5e3);t.subscriptions.push(new vscode.Disposable(()=>clearTimeout(w)));const I=setTimeout(async()=>{try{const{initializeStoreIndex:g}=await import("./store/oramaIndex.js");await g(r)}catch(g){log(r,`[AgentIDE] Store index init: ${g instanceof Error?g.message:String(g)}`)}},3e3);t.subscriptions.push(new vscode.Disposable(()=>clearTimeout(I))),vscode.workspace.workspaceFolders?.length&&refreshAgentideProject(_state).then(async()=>{n.ensureAgentideWatchers(r);try{const{workspaceRoot:g}=getWorkspaceRoot(r),{AgentPackManager:S}=await import("./agentpack/index.js"),M=new S(n,()=>g,()=>A.storagePath,r),{registered:b}=await M.repairUnregisteredAgents();b.length>0&&log(r,`[AgentIDE] Auto-repaired ${b.length} unregistered pack(s): ${b.join(", ")}`)}catch(g){log(r,`[AgentIDE] Pack repair check failed: ${g instanceof Error?g.message:String(g)}`)}_state?.remotePackStatusBar?.refresh()}),t.subscriptions.push(vscode.workspace.onDidChangeWorkspaceFolders(()=>{n.ensureAgentideWatchers(r),_state&&(refreshAgentideProject(_state),_state.remotePackStatusBar?.refresh())})),t.subscriptions.push(new vscode.Disposable(()=>{n.disposeAllWatchers()})),log(r,"[AgentIDE] Extension activation complete")}function deactivate(){if(_state)for(const t of Object.values(_state.engines))try{t.dispose()}catch{}for(const t of _ideTurnScopes.values())t.then(r=>r?.close()).catch(()=>{});_ideTurnScopes.clear(),_state=void 0}function escapeRegExp(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function quoteEnvValue(t){return/^[A-Za-z0-9_./:@-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function upsertEnvVar(t,r,e){const m=t.split(/\r?\n/),E=new RegExp(`^\\s*(?:export\\s+)?${escapeRegExp(r)}\\s*=`);let h=!1;for(let C=0;C<m.length;C++){const A=m[C],T=A.trim();!T||T.startsWith("#")||E.test(A)&&(m[C]=`${r}=${quoteEnvValue(e)}`,h=!0)}return h||(m.length>0&&m[m.length-1].trim()!==""&&m.push(""),m.push(`${r}=${quoteEnvValue(e)}`)),m.join(`
3
3
  `).replace(/\s*$/,`
4
- `)}function hasEnvVar(t,r){const e=new RegExp(`^\\s*(?:export\\s+)?${escapeRegExp(r)}\\s*=`);return t.split(/\r?\n/).some(m=>{const E=m.trim();return!E||E.startsWith("#")?!1:e.test(m)})}function registerCommands(t,r){const{outputChannel:e,syncService:m,config:E}=r;t.subscriptions.push(vscode.commands.registerCommand("agentide.setParticipantApiKey",n=>{log(e,`[AgentIDE] Setting API key for ${n.provider}${n.baseUrl?` with baseUrl: ${n.baseUrl}`:""}`),n.provider==="litellm"&&(E.litellmApiKey=n.apiKey,E.litellmBaseUrl=n.baseUrl)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.binary.findOnPath",async n=>{const s=n?.name?.trim();if(!s)throw new Error("Binary name is required");return(0,binary_1.findBinaryCached)(s,(0,binary_1.getCommonBinaryPaths)(s))}));const h=async n=>{log(e,"[AgentIDE] Starting native OpenAI Codex OAuth login");const{loginOpenAICodex:s}=await import("@mariozechner/pi-ai"),c={onAuth:async({url:o})=>{n(o),log(e,`[AgentIDE] OpenAI Codex OAuth URL: ${o}`);try{await vscode.env.openExternal(vscode.Uri.parse(o)),showInfo("Complete ChatGPT sign-in in your browser. Return here if prompted for a redirect URL.")}catch(a){log(e,`[AgentIDE] Failed to auto-open OAuth URL: ${String(a)}`),showWarning(`Open this URL in your browser: ${o}`)}},onPrompt:async()=>{const o=await vscode.window.showInputBox({title:"ChatGPT Sign-In",prompt:"If your browser finished signing in, copy the full address from its address bar and paste it here.",placeHolder:"http://localhost:1455/auth/callback?code=\u2026",ignoreFocusOut:!0,validateInput:a=>a.trim().length>0?void 0:"Required"});if(!o||o.trim().length===0)throw new Error("OpenAI Codex OAuth cancelled");return o.trim()},onProgress:o=>{log(e,`[AgentIDE] OpenAI Codex OAuth: ${o}`)}};let i;for(let o=1;;o++)try{i=await s(c);break}catch(a){if(!(a instanceof Error&&a.message.includes("only available in Node.js environments"))||o>=20)throw a;await new Promise(S=>setTimeout(S,50))}const l=i?.access?.trim();if(!l)throw new Error("OpenAI Codex OAuth completed without an access token");const u={type:"oauth",...i},d={apiKey:l,oauthCredential:u,expiresAt:typeof i.expires=="number"?i.expires:void 0};return log(e,"[AgentIDE] OpenAI Codex OAuth login complete"),d};let C;t.subscriptions.push(vscode.commands.registerCommand("agentide.openaiCodex.loginOAuth",async()=>{if(C)return log(e,"[AgentIDE] OpenAI Codex OAuth login already in progress; joining it"),C.url&&vscode.env.openExternal(vscode.Uri.parse(C.url)),showInfo("A ChatGPT sign-in is already in progress. Finish it in your browser."),C.result;const n={result:h(s=>{n.url=s})};C=n;try{return await n.result}finally{C===n&&(C=void 0)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.openaiCodex.getValidApiKey",async n=>{const s=n?.oauthCredential;if(!s||typeof s!="object")throw new Error("Missing openai-codex OAuth credential payload.");const{getOAuthApiKey:c}=await import("@mariozechner/pi-ai"),l={"openai-codex":s.type==="oauth"?s:{type:"oauth",...s}},u=await c("openai-codex",l);if(!u?.apiKey)throw new Error("OpenAI Codex OAuth credential is invalid or expired. Please sign in again.");return{apiKey:String(u.apiKey),oauthCredential:{type:"oauth",...u.newCredentials},expiresAt:typeof u.newCredentials?.expires=="number"?u.newCredentials.expires:void 0}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.litellm.setUpstreamApiKey",async n=>{const s=n?.envVar?.trim()??"",c=n?.apiKey?.trim()??"";if(!s||!/^[A-Z][A-Z0-9_]*$/.test(s))throw new Error(`Invalid env var name: ${s}`);if(!c)throw new Error(`API key value cannot be empty for ${s}`);const i=(0,index_1.getAgentideHome)(),l=path.join(i,".env");await fs_1.promises.mkdir(i,{recursive:!0,mode:448});let u="";try{u=await fs_1.promises.readFile(l,"utf8")}catch{}const d=upsertEnvVar(u,s,c);await fs_1.promises.writeFile(l,d,"utf8");try{await fs_1.promises.chmod(l,384)}catch{}return log(e,`[AgentIDE] Updated LiteLLM upstream key in ${l} (${s})`),{envFilePath:l,envVar:s}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.litellm.setChatGPTAuth",async n=>{const s=path.join((0,index_1.getAgentideHome)(),"chatgpt"),c=path.join(s,"auth.json"),i=n?.record;if(!i)return await fs_1.promises.rm(c,{force:!0}),{authFile:c,written:!1};if(typeof i.access_token!="string"||typeof i.expires_at!="number")throw new Error("ChatGPT auth record needs access_token and expires_at.");await fs_1.promises.mkdir(s,{recursive:!0,mode:448});const l=`${c}.${process.pid}.tmp`;return await fs_1.promises.writeFile(l,JSON.stringify(i),{encoding:"utf8",mode:384}),await fs_1.promises.rename(l,c),{authFile:c,written:!0}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.litellm.getUpstreamApiKeyStatus",async n=>{const s=n?.envVar?.trim()??"";if(!s||!/^[A-Z][A-Z0-9_]*$/.test(s))throw new Error(`Invalid env var name: ${s}`);const c=(0,index_1.getAgentideHome)(),i=path.join(c,".env");let l="";try{l=await fs_1.promises.readFile(i,"utf8")}catch{}return{envFilePath:i,envVar:s,exists:hasEnvVar(l,s)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.clearManagedResources",async()=>{if(await vscode.window.showWarningMessage((0,branding_1.brandify)("Clear all AgentIDE managed resources?"),{modal:!0,detail:`This will remove derived folders and generated files. User-managed files in \`${paths_1.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}/\` will NOT be deleted.`},"Clear Resources","Cancel")!=="Clear Resources")return;const{workspaceRoot:s,additionalDirectories:c,isHomeFallback:i}=getWorkspaceRoot(e);i&&await ensureFallbackDirectoryExists(e);const{cleared:l,skipped:u,errors:d}=await m.clearManagedResources(E.codexHome,E.claudeConfigDir,s,c,e),o=[`Cleared: ${l.length} resources`,u.length>0?`Skipped: ${u.length} (user files)`:"",d.length>0?`Errors: ${d.length}`:""].filter(Boolean).join(" | ");d.length>0?(showError(`AgentIDE: ${o}`),log(e,`[AgentIDE] Errors: ${d.join(", ")}`)):showInfo(`AgentIDE: ${o}`),log(e,`[AgentIDE] Clear complete: ${o}`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.skills.syncRemote",async()=>{const{workspaceRoot:n,additionalDirectories:s,isHomeFallback:c}=getWorkspaceRoot(e);c&&await ensureFallbackDirectoryExists(e),await m.ensureAgentideProjectPrepared(n,s,e),await m.syncRemoteSkillsIfEnabled(n,e,{force:!0}),await m.flushAgentideRootUpdate(n,e,{allowDuringActiveTurn:!0,force:!1}),showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: Remote skills sync complete (see ${branding_1.AGENTIDE_BRAND_NAME} output for details).`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.showManagedResources",async()=>{const{workspaceRoot:n,additionalDirectories:s,isHomeFallback:c}=getWorkspaceRoot(e);c&&await ensureFallbackDirectoryExists(e),await m.writeManagedPathsManifest(E.codexHome,E.claudeConfigDir,n,s,e);const i=path.join((0,paths_1.getAgentideDir)(n),"paths.md");if(await(0,utils_1.pathExists)(i)){const l=await vscode.workspace.openTextDocument(i);await vscode.window.showTextDocument(l)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.cleanupSessionLogs",async()=>{const n=await(0,terminalLogger_1.cleanupOldSessionLogs)(e);n.cleaned>0?showInfo(`AgentIDE: Cleaned up ${n.cleaned} old session(s)`):n.errors.length>0?showWarning(`AgentIDE: Cleanup completed with ${n.errors.length} error(s)`):showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No old sessions to clean up`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.deleteSessionLogs",async n=>{const s=n?.sessionId;if(!s)return{deleted:!1,error:"sessionId is required"};const c=await(0,terminalLogger_1.deleteSessionLogs)(s);return c.deleted?(log(e,`[AgentIDE] Deleted session logs: ${s}`),(0,terminalLogger_1.cleanupOldSessionLogs)(e)):c.error&&log(e,`[AgentIDE] Failed to delete session logs: ${c.error}`),c})),t.subscriptions.push(vscode.commands.registerCommand("agentide.cli.status",async()=>{const n=vscode.workspace.getConfiguration("agentide").get("cli.path",""),s=await(0,runtime_1.getCliHealth)({configuredPath:n,extensionPath:t.extensionPath}),i=(0,runtime_1.getBundledToolsHealth)({extensionPath:t.extensionPath,binaryDirHint:s.path?path.dirname(s.path):void 0}).tools.filter(l=>l.available).map(l=>l.name);if(s.installed){const l=s.source==="setting"?"configured path":s.source==="bundled"?"bundled binary":"system PATH",u=i.length>0?`; tools: ${i.join(", ")}`:"; tools: none";showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: CLI available (${l})${s.version?` ${s.version}`:""}${u}`)}else showWarning(`${branding_1.AGENTIDE_BRAND_NAME}: CLI not found. Run '${branding_1.AGENTIDE_BRAND_NAME}: Setup AgentHippo CLI'.`);return s})),t.subscriptions.push(vscode.commands.registerCommand("agentide.cli.isInstalled",async()=>{const n=vscode.workspace.getConfiguration("agentide").get("cli.path","");return(await(0,runtime_1.getCliHealth)({configuredPath:n,extensionPath:t.extensionPath})).installed})),t.subscriptions.push(vscode.commands.registerCommand("agentide.installBundledTools",async()=>{const n=(0,runtime_1.getBundledToolsHealth)({extensionPath:t.extensionPath});if(!n.platformKey){showError(`${branding_1.AGENTIDE_BRAND_NAME}: Unsupported platform ${process.platform}-${process.arch}. Cannot install bundled tools.`);return}const s=t.globalStorageUri;if(!s){showError(`${branding_1.AGENTIDE_BRAND_NAME}: No global storage path. Cannot install bundled tools.`);return}const c=path.join(s.fsPath,"tools"),l=[path.join(t.extensionPath,"out","scripts","vendor-tools.mjs"),path.join(t.extensionPath,"scripts","vendor-tools.mjs")].find(u=>{try{return require("fs").statSync(u).isFile()}catch{return!1}});if(!l){showError(`${branding_1.AGENTIDE_BRAND_NAME}: vendor-tools script not found. Run from extension source or rebuild.`);return}log(e,`[AgentIDE] Installing bundled tools (rg, sg, tree-sitter) into ${c} ...`);try{const{spawn:u}=await import("child_process");await new Promise((o,a)=>{const p=u(process.execPath,[l,"--out-dir",c,"--clean"],{stdio:["ignore","pipe","pipe"],env:{...process.env}});let S="";p.stdout?.on("data",k=>log(e,k.toString())),p.stderr?.on("data",k=>{S+=k.toString(),log(e,k.toString())}),p.on("error",a),p.on("close",k=>k===0?o():a(new Error(`Exit ${k}: ${S}`)))});const d=path.join(c,n.platformKey);await t.globalState.update(BUNDLED_TOOLS_DIR_KEY,d),showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: Bundled tools installed to ${d}. They will be used by the agent.`)}catch(u){const d=u instanceof Error?u.message:String(u);log(e,`[AgentIDE] Install bundled tools failed: ${d}`),showError(`${branding_1.AGENTIDE_BRAND_NAME}: Failed to install bundled tools. Check Output > Agent Hippo. ${d}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.setupCli",async()=>{log(e,"[AgentIDE] Starting CLI setup...");const n=vscode.workspace.getConfiguration("agentide.cli"),s=n.get("path",""),c=n.get("installSource","").trim();if(c&&/[;`|$&\n\r"']/.test(c))return showError(`${branding_1.AGENTIDE_BRAND_NAME}: Invalid CLI install source. Remove shell control characters from '${(0,branding_1.describeSettingKey)("agentide.cli.installSource")}'.`),{success:!1,error:"Invalid install source"};const i=await(0,runtime_1.getCliHealth)({configuredPath:s,extensionPath:t.extensionPath,forceRefresh:!0});if(i.installed&&i.path)return await vscode.workspace.getConfiguration("agentide").update("cli.path",i.path,vscode.ConfigurationTarget.Global),showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: CLI is ready at ${i.path}`),{success:!0,path:i.path};const u=process.platform==="win32"?"setup-cli.ps1":"setup-cli.sh",o=[path.join(t.extensionPath,"out","scripts",u),path.join(t.extensionPath,"scripts",u)].find(S=>{try{return require("fs").accessSync(S),!0}catch{return!1}});if(!o)return showError(`${branding_1.AGENTIDE_BRAND_NAME}: CLI setup script not found. Build CLI via extensions/agentide/scripts/build-cli.sh and set ${(0,branding_1.describeSettingKey)("agentide.cli.path")}.`),{success:!1,error:"Script not found"};const a=await A(o,e,c);if(!a.success)return a;const p=await(0,runtime_1.getCliHealth)({configuredPath:s,extensionPath:t.extensionPath,forceRefresh:!0});return p.installed&&p.path?(await vscode.workspace.getConfiguration("agentide").update("cli.path",p.path,vscode.ConfigurationTarget.Global),showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: CLI configured at ${p.path}`),{success:!0,path:p.path}):(showWarning(`${branding_1.AGENTIDE_BRAND_NAME}: Setup launched. Re-run '${branding_1.AGENTIDE_BRAND_NAME}: CLI Status' after terminal setup completes.`),{success:!0,pending:!0})}));async function A(n,s,c){const i=process.platform==="win32",l=/^https?:\/\//i.test(c),u=c?i?`-Source "${c}"`:`--source "${c}"`:"",d=i?vscode.window.createTerminal({name:"AgentHippo CLI Setup",cwd:path.dirname(n),shellPath:"powershell.exe",shellArgs:["-NoProfile","-NoExit","-ExecutionPolicy","Bypass","-Command",`& "${n}" ${u} -Yes; Write-Host ""; Write-Host "You can close this window."`]}):vscode.window.createTerminal({name:"AgentHippo CLI Setup",cwd:path.dirname(n),shellPath:"/bin/bash",shellArgs:["-c",`"${n}" ${u} --yes; echo ''; echo 'Press any key to close...'; read -n 1`]});return c&&log(s,`[AgentIDE] CLI install source configured (${l?"url":"package/path"}): ${c}`),d.show(),showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: CLI setup started. Check the terminal for progress.`),log(s,"[AgentIDE] CLI setup terminal opened"),{success:!0}}t.subscriptions.push(vscode.commands.registerCommand("agentide.setupAnalytics",async n=>{const s=n?.reinstall===!0;log(e,`[AgentIDE] Starting Spotlight ${s?"reinstall":"install/repair"}...`);const c=process.platform==="win32",i=c?"setup-analytics.ps1":"setup-analytics.sh",l=t.extensionPath,d=[path.join(l,"out","scripts","analytics",i),path.join(l,"scripts","analytics",i)].find(o=>{try{return require("fs").accessSync(o),!0}catch{return!1}});return d?c&&_state?.analyticsService?_state.analyticsService.setupWindowsSpotlight({reinstall:s}):T(d,e,{reinstall:s}):(showError(`Spotlight install script not found. Please run 'scripts/analytics/${i}' manually from the AgentIDE repository.`),{success:!1,error:"Script not found"})}));async function T(n,s,c={}){const i=process.platform==="win32",l=path.join(os.homedir(),branding_1.AGENTIDE_DIR_NAME),u=c.reinstall?"--yes --restart-litellm":"--yes";return(i?vscode.window.createTerminal({name:"Spotlight Install",cwd:path.dirname(n),env:{AGENT_HOME_DIR:l},shellPath:"powershell.exe",shellArgs:["-NoProfile","-NoExit","-ExecutionPolicy","Bypass","-Command",`& "${n}" -Yes; Write-Host ""; Write-Host "You can close this window."`]}):vscode.window.createTerminal({name:"Spotlight Install",cwd:path.dirname(n),env:{AGENT_HOME_DIR:l},shellPath:"/bin/bash",shellArgs:["-c",`"${n}" ${u}; echo ''; echo 'Press any key to close...'; read -n 1`]})).show(),showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: Spotlight install started. Check the terminal for progress.`),log(s,"[AgentIDE] Spotlight install terminal opened"),{success:!0}}t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.install",async()=>{const{workspaceRoot:n,isHomeFallback:s}=getWorkspaceRoot(e);s&&await ensureFallbackDirectoryExists(e);const c=await vscode.window.showOpenDialog({canSelectFolders:!0,canSelectFiles:!1,canSelectMany:!1,openLabel:"Select Agent Pack Folder",title:"Install Agent Pack"});if(!c||c.length===0)return;const i=c[0].fsPath,{AgentPackManager:l}=await import("./agentpack/index.js"),u=new l(m,()=>n,()=>E.storagePath,e);try{const d=await u.installFromLocal(i);showInfo(`AgentIDE: Installed pack "${d.id}" v${d.version}`)}catch(d){const o=d instanceof Error?d.message:String(d);log(e,`[AgentIDE] Pack install error: ${o}`),showError(`AgentIDE: Failed to install pack - ${o}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.list",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),i=await new s(m,()=>n,()=>E.storagePath,e).listInstalled();if(i.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No agent packs installed`);return}const l=i.map(d=>({label:d.id,description:`v${d.version} (${d.preferredEngine})`,detail:`Status: ${d.status} | Installed: ${new Date(d.installedAt).toLocaleDateString()}`})),u=await vscode.window.showQuickPick(l,{placeHolder:"Select a pack to view details",title:"Installed Agent Packs"});u&&(log(e,`[AgentIDE] Pack selected: ${u.label}`),e.show())})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.getInstalled",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),c=new s(m,()=>n,()=>E.storagePath,e);try{return await c.listInstalled()}catch(i){const l=i instanceof Error?i.message:String(i);return log(e,`[AgentIDE] Pack list error: ${l}`),[]}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.customEngine.list",n=>{const s=getConfiguredAdditionalEngineDir(),c=n?.workspaceRoot?.trim(),i=(vscode.workspace.workspaceFolders??[]).map(o=>o.uri.fsPath).filter(o=>!!o?.trim()),l=process.cwd?.(),u=Array.from(new Set([c,...i,l].map(o=>o?.trim()).filter(o=>!!o))),d=new Map;for(const o of u)try{const a=(0,customRegistry_1.discoverCustomEngineManifests)(o,s);for(const p of a)d.has(p.id)||d.set(p.id,{id:p.id,displayName:p.displayName||p.id,description:p.description,defaultModel:p.model?.defaultModel})}catch(a){const p=a instanceof Error?a.message:String(a);log(e,`[AgentIDE] Custom engine list warning for root ${o}: ${p}`)}if(d.size===0)try{const o=(0,customRegistry_1.discoverCustomEngineManifests)(void 0,s);for(const a of o)d.set(a.id,{id:a.id,displayName:a.displayName||a.id,description:a.description,defaultModel:a.model?.defaultModel})}catch(o){const a=o instanceof Error?o.message:String(o);log(e,`[AgentIDE] Custom engine list error: ${a}`)}return log(e,`[AgentIDE] Custom engine list: ${d.size} discovered (${Array.from(d.keys()).join(", ")||"none"}) from roots: ${u.join("; ")||"(home only)"}`),Array.from(d.values())})),t.subscriptions.push(vscode.commands.registerCommand("agentide.engine.uninstall",async n=>{const{listInstalledCustomEngines:s,uninstallCustomEngine:c}=await import("./engines/install.js");let i=n?.id?.trim(),l=i;if(!i){const o=await s();if(o.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No custom engines are installed`);return}const a=await vscode.window.showQuickPick(o.map(p=>({label:p.displayName,description:p.id,detail:p.installDir,engine:p})),{placeHolder:"Select a custom engine to uninstall",title:"Uninstall Custom Engine"});if(!a)return;i=a.engine.id,l=a.engine.displayName}if(!i||n?.skipConfirmation!==!0&&await vscode.window.showWarningMessage(`Uninstall custom engine "${l||i}"?`,{modal:!0},"Uninstall","Cancel")!=="Uninstall")return;const u=await c(i,{logger:e});if(!u.removed){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: Custom engine "${u.id}" is not installed`);return}clearCustomEngineRuntimeCache(r,u.id);const{invalidateLocalIndex:d}=await import("./store/oramaIndex.js");d(),await refreshCustomEnginePicker(e),showInfo(`Uninstalled engine "${u.displayName||u.id}"`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.engine.publish",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{collectEngineFiles:s,discoverPublishableEngines:c,isValidPublishVersion:i,validateEngineForPublish:l}=await import("./engines/publish.js"),{publishToStore:u,STORE_CONFIG:d,canPublishDirectlyToStore:o}=await import("./store/index.js"),a=await c(n);if(a.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No custom engines found. Add engine.manifest.json under .agent-hippo/engines/<id>/`);return}const p=await vscode.window.showQuickPick(a.map(S=>({label:S.displayName,description:S.id,detail:`${S.sourceLabel}: ${S.sourceDir}`,engine:S})),{placeHolder:"Select a custom engine to publish",title:`Publish to ${d.owner}/${d.repo}`});if(p)try{const S=await l(p.engine.sourceDir,p.engine.id);if(!S.valid){showError(`${branding_1.AGENTIDE_BRAND_NAME}: Cannot publish - ${S.errors.join(", ")}`);return}if(S.warnings.length>0&&await vscode.window.showWarningMessage(`Warnings: ${S.warnings.join(", ")}`,"Publish Anyway","Cancel")!=="Publish Anyway")return;const k=await vscode.window.showInputBox({prompt:"Publish version (semver)",value:S.metadata?.suggestedVersion||"1.0.0",placeHolder:"e.g., 1.0.0",validateInput:M=>M&&i(M.replace(/^v/,""))?null:"Use semver format (e.g., 1.0.0)"});if(!k)return;const y=k.replace(/^v/,""),$=await vscode.window.showInputBox({prompt:"What changed in this version? (optional)",placeHolder:"Initial release, bug fixes..."}),f=await s(p.engine.sourceDir),w=await o();if(await vscode.window.showWarningMessage(w?`Publish "${p.engine.id}" v${y} to ${d.owner}/${d.repo}?
4
+ `)}function hasEnvVar(t,r){const e=new RegExp(`^\\s*(?:export\\s+)?${escapeRegExp(r)}\\s*=`);return t.split(/\r?\n/).some(m=>{const E=m.trim();return!E||E.startsWith("#")?!1:e.test(m)})}function registerCommands(t,r){const{outputChannel:e,syncService:m,config:E}=r;t.subscriptions.push(vscode.commands.registerCommand("agentide.setParticipantApiKey",n=>{log(e,`[AgentIDE] Setting API key for ${n.provider}${n.baseUrl?` with baseUrl: ${n.baseUrl}`:""}`),n.provider==="litellm"&&(E.litellmApiKey=n.apiKey,E.litellmBaseUrl=n.baseUrl)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.binary.findOnPath",async n=>{const s=n?.name?.trim();if(!s)throw new Error("Binary name is required");return(0,binary_1.findBinaryCached)(s,(0,binary_1.getCommonBinaryPaths)(s))}));const h=async n=>{log(e,"[AgentIDE] Starting native OpenAI Codex OAuth login");const{loginOpenAICodex:s}=await import("@mariozechner/pi-ai"),c={onAuth:async({url:o})=>{n(o),log(e,`[AgentIDE] OpenAI Codex OAuth URL: ${o}`);try{await vscode.env.openExternal(vscode.Uri.parse(o)),showInfo("Complete ChatGPT sign-in in your browser. Return here if prompted for a redirect URL.")}catch(a){log(e,`[AgentIDE] Failed to auto-open OAuth URL: ${String(a)}`),showWarning(`Open this URL in your browser: ${o}`)}},onPrompt:async()=>{const o=await vscode.window.showInputBox({title:"ChatGPT Sign-In",prompt:"If your browser finished signing in, copy the full address from its address bar and paste it here.",placeHolder:"http://localhost:1455/auth/callback?code=\u2026",ignoreFocusOut:!0,validateInput:a=>a.trim().length>0?void 0:"Required"});if(!o||o.trim().length===0)throw new Error("OpenAI Codex OAuth cancelled");return o.trim()},onProgress:o=>{log(e,`[AgentIDE] OpenAI Codex OAuth: ${o}`)}};let i;for(let o=1;;o++)try{i=await s(c);break}catch(a){if(!(a instanceof Error&&a.message.includes("only available in Node.js environments"))||o>=20)throw a;await new Promise(D=>setTimeout(D,50))}const l=i?.access?.trim();if(!l)throw new Error("OpenAI Codex OAuth completed without an access token");const u={type:"oauth",...i},d={apiKey:l,oauthCredential:u,expiresAt:typeof i.expires=="number"?i.expires:void 0};return log(e,"[AgentIDE] OpenAI Codex OAuth login complete"),d};let C;t.subscriptions.push(vscode.commands.registerCommand("agentide.openaiCodex.loginOAuth",async()=>{if(C)return log(e,"[AgentIDE] OpenAI Codex OAuth login already in progress; joining it"),C.url&&vscode.env.openExternal(vscode.Uri.parse(C.url)),showInfo("A ChatGPT sign-in is already in progress. Finish it in your browser."),C.result;const n={result:h(s=>{n.url=s})};C=n;try{return await n.result}finally{C===n&&(C=void 0)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.openaiCodex.getValidApiKey",async n=>{const s=n?.oauthCredential;if(!s||typeof s!="object")throw new Error("Missing openai-codex OAuth credential payload.");const{getOAuthApiKey:c}=await import("@mariozechner/pi-ai"),l={"openai-codex":s.type==="oauth"?s:{type:"oauth",...s}},u=await c("openai-codex",l);if(!u?.apiKey)throw new Error("OpenAI Codex OAuth credential is invalid or expired. Please sign in again.");return{apiKey:String(u.apiKey),oauthCredential:{type:"oauth",...u.newCredentials},expiresAt:typeof u.newCredentials?.expires=="number"?u.newCredentials.expires:void 0}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.litellm.setUpstreamApiKey",async n=>{const s=n?.envVar?.trim()??"",c=n?.apiKey?.trim()??"";if(!s||!/^[A-Z][A-Z0-9_]*$/.test(s))throw new Error(`Invalid env var name: ${s}`);if(!c)throw new Error(`API key value cannot be empty for ${s}`);const i=(0,index_1.getAgentideHome)(),l=path.join(i,".env");await fs_1.promises.mkdir(i,{recursive:!0,mode:448});let u="";try{u=await fs_1.promises.readFile(l,"utf8")}catch{}const d=upsertEnvVar(u,s,c);await fs_1.promises.writeFile(l,d,"utf8");try{await fs_1.promises.chmod(l,384)}catch{}return log(e,`[AgentIDE] Updated LiteLLM upstream key in ${l} (${s})`),{envFilePath:l,envVar:s}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.litellm.setChatGPTAuth",async n=>{const s=path.join((0,index_1.getAgentideHome)(),"chatgpt"),c=path.join(s,"auth.json"),i=n?.record;if(!i)return await fs_1.promises.rm(c,{force:!0}),{authFile:c,written:!1};if(typeof i.access_token!="string"||typeof i.expires_at!="number")throw new Error("ChatGPT auth record needs access_token and expires_at.");await fs_1.promises.mkdir(s,{recursive:!0,mode:448});const l=`${c}.${process.pid}.tmp`;return await fs_1.promises.writeFile(l,JSON.stringify(i),{encoding:"utf8",mode:384}),await fs_1.promises.rename(l,c),{authFile:c,written:!0}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.litellm.getUpstreamApiKeyStatus",async n=>{const s=n?.envVar?.trim()??"";if(!s||!/^[A-Z][A-Z0-9_]*$/.test(s))throw new Error(`Invalid env var name: ${s}`);const c=(0,index_1.getAgentideHome)(),i=path.join(c,".env");let l="";try{l=await fs_1.promises.readFile(i,"utf8")}catch{}return{envFilePath:i,envVar:s,exists:hasEnvVar(l,s)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.clearManagedResources",async()=>{if(await vscode.window.showWarningMessage((0,branding_1.brandify)("Clear all AgentIDE managed resources?"),{modal:!0,detail:`This will remove derived folders and generated files. User-managed files in \`${paths_1.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}/\` will NOT be deleted.`},"Clear Resources","Cancel")!=="Clear Resources")return;const{workspaceRoot:s,additionalDirectories:c,isHomeFallback:i}=getWorkspaceRoot(e);i&&await ensureFallbackDirectoryExists(e);const{cleared:l,skipped:u,errors:d}=await m.clearManagedResources(E.codexHome,E.claudeConfigDir,s,c,e),o=[`Cleared: ${l.length} resources`,u.length>0?`Skipped: ${u.length} (user files)`:"",d.length>0?`Errors: ${d.length}`:""].filter(Boolean).join(" | ");d.length>0?(showError(`AgentIDE: ${o}`),log(e,`[AgentIDE] Errors: ${d.join(", ")}`)):showInfo(`AgentIDE: ${o}`),log(e,`[AgentIDE] Clear complete: ${o}`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.skills.syncRemote",async()=>{const{workspaceRoot:n,additionalDirectories:s,isHomeFallback:c}=getWorkspaceRoot(e);c&&await ensureFallbackDirectoryExists(e),await m.ensureAgentideProjectPrepared(n,s,e),await m.syncRemoteSkillsIfEnabled(n,e,{force:!0}),await m.flushAgentideRootUpdate(n,e,{allowDuringActiveTurn:!0,force:!1}),showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: Remote skills sync complete (see ${branding_1.AGENTIDE_BRAND_NAME} output for details).`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.showManagedResources",async()=>{const{workspaceRoot:n,additionalDirectories:s,isHomeFallback:c}=getWorkspaceRoot(e);c&&await ensureFallbackDirectoryExists(e),await m.writeManagedPathsManifest(E.codexHome,E.claudeConfigDir,n,s,e);const i=path.join((0,paths_1.getAgentideDir)(n),"paths.md");if(await(0,utils_1.pathExists)(i)){const l=await vscode.workspace.openTextDocument(i);await vscode.window.showTextDocument(l)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.cleanupSessionLogs",async()=>{const n=await(0,terminalLogger_1.cleanupOldSessionLogs)(e);n.cleaned>0?showInfo(`AgentIDE: Cleaned up ${n.cleaned} old session(s)`):n.errors.length>0?showWarning(`AgentIDE: Cleanup completed with ${n.errors.length} error(s)`):showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No old sessions to clean up`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.deleteSessionLogs",async n=>{const s=n?.sessionId;if(!s)return{deleted:!1,error:"sessionId is required"};const c=await(0,terminalLogger_1.deleteSessionLogs)(s);return c.deleted?(log(e,`[AgentIDE] Deleted session logs: ${s}`),(0,terminalLogger_1.cleanupOldSessionLogs)(e)):c.error&&log(e,`[AgentIDE] Failed to delete session logs: ${c.error}`),c})),t.subscriptions.push(vscode.commands.registerCommand("agentide.cli.status",async()=>{const n=vscode.workspace.getConfiguration("agentide").get("cli.path",""),s=await(0,runtime_1.getCliHealth)({configuredPath:n,extensionPath:t.extensionPath}),i=(0,runtime_1.getBundledToolsHealth)({extensionPath:t.extensionPath,binaryDirHint:s.path?path.dirname(s.path):void 0}).tools.filter(l=>l.available).map(l=>l.name);if(s.installed){const l=s.source==="setting"?"configured path":s.source==="bundled"?"bundled binary":"system PATH",u=i.length>0?`; tools: ${i.join(", ")}`:"; tools: none";showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: CLI available (${l})${s.version?` ${s.version}`:""}${u}`)}else showWarning(`${branding_1.AGENTIDE_BRAND_NAME}: CLI not found. Run '${branding_1.AGENTIDE_BRAND_NAME}: Setup AgentHippo CLI'.`);return s})),t.subscriptions.push(vscode.commands.registerCommand("agentide.cli.isInstalled",async()=>{const n=vscode.workspace.getConfiguration("agentide").get("cli.path","");return(await(0,runtime_1.getCliHealth)({configuredPath:n,extensionPath:t.extensionPath})).installed})),t.subscriptions.push(vscode.commands.registerCommand("agentide.installBundledTools",async()=>{const n=(0,runtime_1.getBundledToolsHealth)({extensionPath:t.extensionPath});if(!n.platformKey){showError(`${branding_1.AGENTIDE_BRAND_NAME}: Unsupported platform ${process.platform}-${process.arch}. Cannot install bundled tools.`);return}const s=t.globalStorageUri;if(!s){showError(`${branding_1.AGENTIDE_BRAND_NAME}: No global storage path. Cannot install bundled tools.`);return}const c=path.join(s.fsPath,"tools"),l=[path.join(t.extensionPath,"out","scripts","vendor-tools.mjs"),path.join(t.extensionPath,"scripts","vendor-tools.mjs")].find(u=>{try{return require("fs").statSync(u).isFile()}catch{return!1}});if(!l){showError(`${branding_1.AGENTIDE_BRAND_NAME}: vendor-tools script not found. Run from extension source or rebuild.`);return}log(e,`[AgentIDE] Installing bundled tools (rg, sg, tree-sitter) into ${c} ...`);try{const{spawn:u}=await import("child_process");await new Promise((o,a)=>{const p=u(process.execPath,[l,"--out-dir",c,"--clean"],{stdio:["ignore","pipe","pipe"],env:{...process.env}});let D="";p.stdout?.on("data",k=>log(e,k.toString())),p.stderr?.on("data",k=>{D+=k.toString(),log(e,k.toString())}),p.on("error",a),p.on("close",k=>k===0?o():a(new Error(`Exit ${k}: ${D}`)))});const d=path.join(c,n.platformKey);await t.globalState.update(BUNDLED_TOOLS_DIR_KEY,d),showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: Bundled tools installed to ${d}. They will be used by the agent.`)}catch(u){const d=u instanceof Error?u.message:String(u);log(e,`[AgentIDE] Install bundled tools failed: ${d}`),showError(`${branding_1.AGENTIDE_BRAND_NAME}: Failed to install bundled tools. Check Output > Agent Hippo. ${d}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.setupCli",async()=>{log(e,"[AgentIDE] Starting CLI setup...");const n=vscode.workspace.getConfiguration("agentide.cli"),s=n.get("path",""),c=n.get("installSource","").trim();if(c&&/[;`|$&\n\r"']/.test(c))return showError(`${branding_1.AGENTIDE_BRAND_NAME}: Invalid CLI install source. Remove shell control characters from '${(0,branding_1.describeSettingKey)("agentide.cli.installSource")}'.`),{success:!1,error:"Invalid install source"};const i=await(0,runtime_1.getCliHealth)({configuredPath:s,extensionPath:t.extensionPath,forceRefresh:!0});if(i.installed&&i.path)return await vscode.workspace.getConfiguration("agentide").update("cli.path",i.path,vscode.ConfigurationTarget.Global),showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: CLI is ready at ${i.path}`),{success:!0,path:i.path};const u=process.platform==="win32"?"setup-cli.ps1":"setup-cli.sh",o=[path.join(t.extensionPath,"out","scripts",u),path.join(t.extensionPath,"scripts",u)].find(D=>{try{return require("fs").accessSync(D),!0}catch{return!1}});if(!o)return showError(`${branding_1.AGENTIDE_BRAND_NAME}: CLI setup script not found. Build CLI via extensions/agentide/scripts/build-cli.sh and set ${(0,branding_1.describeSettingKey)("agentide.cli.path")}.`),{success:!1,error:"Script not found"};const a=await A(o,e,c);if(!a.success)return a;const p=await(0,runtime_1.getCliHealth)({configuredPath:s,extensionPath:t.extensionPath,forceRefresh:!0});return p.installed&&p.path?(await vscode.workspace.getConfiguration("agentide").update("cli.path",p.path,vscode.ConfigurationTarget.Global),showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: CLI configured at ${p.path}`),{success:!0,path:p.path}):(showWarning(`${branding_1.AGENTIDE_BRAND_NAME}: Setup launched. Re-run '${branding_1.AGENTIDE_BRAND_NAME}: CLI Status' after terminal setup completes.`),{success:!0,pending:!0})}));async function A(n,s,c){const i=process.platform==="win32",l=/^https?:\/\//i.test(c),u=c?i?`-Source "${c}"`:`--source "${c}"`:"",d=i?vscode.window.createTerminal({name:"AgentHippo CLI Setup",cwd:path.dirname(n),shellPath:"powershell.exe",shellArgs:["-NoProfile","-NoExit","-ExecutionPolicy","Bypass","-Command",`& "${n}" ${u} -Yes; Write-Host ""; Write-Host "You can close this window."`]}):vscode.window.createTerminal({name:"AgentHippo CLI Setup",cwd:path.dirname(n),shellPath:"/bin/bash",shellArgs:["-c",`"${n}" ${u} --yes; echo ''; echo 'Press any key to close...'; read -n 1`]});return c&&log(s,`[AgentIDE] CLI install source configured (${l?"url":"package/path"}): ${c}`),d.show(),showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: CLI setup started. Check the terminal for progress.`),log(s,"[AgentIDE] CLI setup terminal opened"),{success:!0}}t.subscriptions.push(vscode.commands.registerCommand("agentide.setupAnalytics",async n=>{const s=n?.reinstall===!0;log(e,`[AgentIDE] Starting Spotlight ${s?"reinstall":"install/repair"}...`);const c=process.platform==="win32",i=c?"setup-analytics.ps1":"setup-analytics.sh",l=t.extensionPath,d=[path.join(l,"out","scripts","analytics",i),path.join(l,"scripts","analytics",i)].find(o=>{try{return require("fs").accessSync(o),!0}catch{return!1}});return d?c&&_state?.analyticsService?_state.analyticsService.setupWindowsSpotlight({reinstall:s}):T(d,e,{reinstall:s}):(showError(`Spotlight install script not found. Please run 'scripts/analytics/${i}' manually from the AgentIDE repository.`),{success:!1,error:"Script not found"})}));async function T(n,s,c={}){const i=process.platform==="win32",l=path.join(os.homedir(),branding_1.AGENTIDE_DIR_NAME),u=c.reinstall?"--yes --restart-litellm":"--yes";return(i?vscode.window.createTerminal({name:"Spotlight Install",cwd:path.dirname(n),env:{AGENT_HOME_DIR:l},shellPath:"powershell.exe",shellArgs:["-NoProfile","-NoExit","-ExecutionPolicy","Bypass","-Command",`& "${n}" -Yes; Write-Host ""; Write-Host "You can close this window."`]}):vscode.window.createTerminal({name:"Spotlight Install",cwd:path.dirname(n),env:{AGENT_HOME_DIR:l},shellPath:"/bin/bash",shellArgs:["-c",`"${n}" ${u}; echo ''; echo 'Press any key to close...'; read -n 1`]})).show(),showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: Spotlight install started. Check the terminal for progress.`),log(s,"[AgentIDE] Spotlight install terminal opened"),{success:!0}}t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.install",async()=>{const{workspaceRoot:n,isHomeFallback:s}=getWorkspaceRoot(e);s&&await ensureFallbackDirectoryExists(e);const c=await vscode.window.showOpenDialog({canSelectFolders:!0,canSelectFiles:!1,canSelectMany:!1,openLabel:"Select Agent Pack Folder",title:"Install Agent Pack"});if(!c||c.length===0)return;const i=c[0].fsPath,{AgentPackManager:l}=await import("./agentpack/index.js"),u=new l(m,()=>n,()=>E.storagePath,e);try{const d=await u.installFromLocal(i);showInfo(`AgentIDE: Installed pack "${d.id}" v${d.version}`)}catch(d){const o=d instanceof Error?d.message:String(d);log(e,`[AgentIDE] Pack install error: ${o}`),showError(`AgentIDE: Failed to install pack - ${o}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.list",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),i=await new s(m,()=>n,()=>E.storagePath,e).listInstalled();if(i.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No agent packs installed`);return}const l=i.map(d=>({label:d.id,description:`v${d.version} (${d.preferredEngine})`,detail:`Status: ${d.status} | Installed: ${new Date(d.installedAt).toLocaleDateString()}`})),u=await vscode.window.showQuickPick(l,{placeHolder:"Select a pack to view details",title:"Installed Agent Packs"});u&&(log(e,`[AgentIDE] Pack selected: ${u.label}`),e.show())})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.getInstalled",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),c=new s(m,()=>n,()=>E.storagePath,e);try{return await c.listInstalled()}catch(i){const l=i instanceof Error?i.message:String(i);return log(e,`[AgentIDE] Pack list error: ${l}`),[]}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.customEngine.list",n=>{const s=getConfiguredAdditionalEngineDir(),c=n?.workspaceRoot?.trim(),i=(vscode.workspace.workspaceFolders??[]).map(o=>o.uri.fsPath).filter(o=>!!o?.trim()),l=process.cwd?.(),u=Array.from(new Set([c,...i,l].map(o=>o?.trim()).filter(o=>!!o))),d=new Map;for(const o of u)try{const a=(0,customRegistry_1.discoverCustomEngineManifests)(o,s);for(const p of a)d.has(p.id)||d.set(p.id,{id:p.id,displayName:p.displayName||p.id,description:p.description,defaultModel:p.model?.defaultModel})}catch(a){const p=a instanceof Error?a.message:String(a);log(e,`[AgentIDE] Custom engine list warning for root ${o}: ${p}`)}if(d.size===0)try{const o=(0,customRegistry_1.discoverCustomEngineManifests)(void 0,s);for(const a of o)d.set(a.id,{id:a.id,displayName:a.displayName||a.id,description:a.description,defaultModel:a.model?.defaultModel})}catch(o){const a=o instanceof Error?o.message:String(o);log(e,`[AgentIDE] Custom engine list error: ${a}`)}return log(e,`[AgentIDE] Custom engine list: ${d.size} discovered (${Array.from(d.keys()).join(", ")||"none"}) from roots: ${u.join("; ")||"(home only)"}`),Array.from(d.values())})),t.subscriptions.push(vscode.commands.registerCommand("agentide.engine.uninstall",async n=>{const{listInstalledCustomEngines:s,uninstallCustomEngine:c}=await import("./engines/install.js");let i=n?.id?.trim(),l=i;if(!i){const o=await s();if(o.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No custom engines are installed`);return}const a=await vscode.window.showQuickPick(o.map(p=>({label:p.displayName,description:p.id,detail:p.installDir,engine:p})),{placeHolder:"Select a custom engine to uninstall",title:"Uninstall Custom Engine"});if(!a)return;i=a.engine.id,l=a.engine.displayName}if(!i||n?.skipConfirmation!==!0&&await vscode.window.showWarningMessage(`Uninstall custom engine "${l||i}"?`,{modal:!0},"Uninstall","Cancel")!=="Uninstall")return;const u=await c(i,{logger:e});if(!u.removed){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: Custom engine "${u.id}" is not installed`);return}clearCustomEngineRuntimeCache(r,u.id);const{invalidateLocalIndex:d}=await import("./store/oramaIndex.js");d(),await refreshCustomEnginePicker(e),showInfo(`Uninstalled engine "${u.displayName||u.id}"`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.engine.publish",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{collectEngineFiles:s,discoverPublishableEngines:c,isValidPublishVersion:i,validateEngineForPublish:l}=await import("./engines/publish.js"),{publishToStore:u,STORE_CONFIG:d,canPublishDirectlyToStore:o}=await import("./store/index.js"),a=await c(n);if(a.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No custom engines found. Add engine.manifest.json under .agent-hippo/engines/<id>/`);return}const p=await vscode.window.showQuickPick(a.map(D=>({label:D.displayName,description:D.id,detail:`${D.sourceLabel}: ${D.sourceDir}`,engine:D})),{placeHolder:"Select a custom engine to publish",title:`Publish to ${d.owner}/${d.repo}`});if(p)try{const D=await l(p.engine.sourceDir,p.engine.id);if(!D.valid){showError(`${branding_1.AGENTIDE_BRAND_NAME}: Cannot publish - ${D.errors.join(", ")}`);return}if(D.warnings.length>0&&await vscode.window.showWarningMessage(`Warnings: ${D.warnings.join(", ")}`,"Publish Anyway","Cancel")!=="Publish Anyway")return;const k=await vscode.window.showInputBox({prompt:"Publish version (semver)",value:D.metadata?.suggestedVersion||"1.0.0",placeHolder:"e.g., 1.0.0",validateInput:M=>M&&i(M.replace(/^v/,""))?null:"Use semver format (e.g., 1.0.0)"});if(!k)return;const y=k.replace(/^v/,""),$=await vscode.window.showInputBox({prompt:"What changed in this version? (optional)",placeHolder:"Initial release, bug fixes..."}),f=await s(p.engine.sourceDir),w=await o();if(await vscode.window.showWarningMessage(w?`Publish "${p.engine.id}" v${y} to ${d.owner}/${d.repo}?
5
5
 
6
6
  This will open a pull request on the store repository.`:`Submit "${p.engine.id}" v${y} to ${d.owner}/${d.repo}?
7
7
 
8
- This will create a pull request from your fork.`,{modal:!0},"Submit PR")!=="Submit PR")return;const g=await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Publishing engine ${p.engine.id} v${y}`,cancellable:!1},async M=>{M.report({message:w?`Publishing to ${d.owner}/${d.repo}...`:"Preparing fork..."});const b=await u({type:"engine",slug:p.engine.id,version:y,files:f,changelog:$},e);return M.report({message:"Creating PR..."}),b});await vscode.window.showInformationMessage(`Published engine "${p.engine.id}" v${y}! PR created.`,"View PR")==="View PR"&&vscode.env.openExternal(vscode.Uri.parse(g.prUrl))}catch(S){const k=S instanceof Error?S.message:String(S);log(e,`[AgentIDE] Engine publish error: ${k}`),showError(`${branding_1.AGENTIDE_BRAND_NAME}: ${k}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.uninstall",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s,isDefaultAgent:c}=await import("./agentpack/index.js"),i=new s(m,()=>n,()=>E.storagePath,e),u=(await i.listInstalled()).filter(k=>!c(k.id));if(u.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No agent packs available to uninstall`);return}const d=u.map(k=>({label:k.id,description:`v${k.version}${r.activePackId===k.id?" (active)":""}`})),o=await vscode.window.showQuickPick(d,{placeHolder:"Select a pack to uninstall",title:"Uninstall Agent Pack"});if(!o)return;const a=o.label,p=r.activePackId===a;if(await vscode.window.showWarningMessage(`Uninstall agent pack "${a}"?${p?" This will switch to the default agent.":""}`,{modal:!0},"Uninstall","Cancel")==="Uninstall")try{if(await i.uninstall(a),p){const k=await m.switchToPack(n,void 0,e,{importDerivedSkills:!0});r.activePackId=k,m.setActivePackId(n,k),log(e,"[AgentIDE] Switched to default agent after uninstalling active pack");try{await vscode.commands.executeCommand("agentide.applyPackPreferences",{packId:"default",silent:!0})}catch{}}showInfo(`AgentIDE: Uninstalled pack "${a}"${p?" - switched to default agent":""}`)}catch(k){const y=k instanceof Error?k.message:String(k);log(e,`[AgentIDE] Pack uninstall error: ${y}`),showError(`AgentIDE: Failed to uninstall pack - ${y}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.setActive",async n=>{if(!n?.packId)throw new Error("packId is required. Use workbench.action.chat.openAgentPackPicker for interactive selection.");const{workspaceRoot:s}=getWorkspaceRoot(e),c=n.packId==="default"?void 0:n.packId,i=await m.switchToPack(s,c,e,{importDerivedSkills:!0});return r.activePackId=i,m.setActivePackId(s,i),log(e,`[AgentIDE] Active pack switched to: ${i??"default"}`),await r.remotePackStatusBar?.refresh({notifyOnActivate:!0}),{activePackId:r.activePackId??"default"}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.getActive",()=>({activePackId:r.activePackId??"default"}))),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.getRemoteServeUrl",async n=>{const{workspaceRoot:s}=getWorkspaceRoot(e),c=n?.packId?.trim()||m.getActivePackId(s)||r.activePackId;if(!c||c==="default")return;const i=await m.getActiveAgentManifest(s,e,c),l=(0,serveClient_js_1.getRemoteServeUrl)(i);if(l)return{packId:c,remoteUrl:l,preferredEngine:i?.spec?.engine}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.create",async()=>{const{workspaceRoot:n,isHomeFallback:s}=getWorkspaceRoot(e);s&&await ensureFallbackDirectoryExists(e);let c;try{const a=await vscode.commands.executeCommand("agentide.getChatState");c=a?.modelId,log(e,`[AgentIDE] Current chat state: mode=${a?.mode}, modelId=${c}, modelName=${a?.modelName}`)}catch{}const i=await vscode.window.showInputBox({prompt:"Enter the agent pack name",placeHolder:"e.g., code-reviewer, security-auditor, My Code Reviewer",validateInput:async a=>{const p=(0,paths_1.normalizePackName)(a),S=(0,paths_1.getPackNameError)(p);if(S)return S;const k=path.join((0,paths_1.getAgentideDir)(n),paths_1.AGENT_CONSTANTS.AGENTS_DIR,p);if(await(0,utils_1.pathExists)(k))return`A pack named "${p}" already exists. Choose a different name.`}});if(!i)return;const l=(0,paths_1.normalizePackName)(i);log(e,`[AgentIDE] Pack name normalized: "${i}" -> "${l}"`);const u=path.join((0,paths_1.getAgentideDir)(n),paths_1.AGENT_CONSTANTS.AGENTS_DIR,l),d=await vscode.window.showInputBox({prompt:"Enter a short description for the pack",placeHolder:"e.g., Advanced code review agent with security analysis"}),o=await vscode.window.showQuickPick([{label:"Claude",description:"Anthropic Claude Agent SDK",engine:"claude"},{label:"Codex",description:"OpenAI Codex SDK",engine:"codex"}],{placeHolder:"Select the preferred engine for this pack",title:"Preferred Engine"});if(o)try{await fs_1.promises.mkdir(path.join(u,"rules"),{recursive:!0}),await fs_1.promises.mkdir(path.join(u,"skills"),{recursive:!0}),await fs_1.promises.mkdir(path.join(u,"mcp"),{recursive:!0});const a=(0,paths_1.generateAgentYaml)(l,{description:d||void 0,engine:o.engine,model:c});await fs_1.promises.writeFile(path.join(u,"agent.yaml"),a);const p=(0,paths_1.generateAgentsMd)(l,{description:d||void 0});await fs_1.promises.writeFile(path.join(u,"AGENTS.md"),p);const{AgentPackManager:S}=await import("./agentpack/index.js");await new S(m,()=>n,()=>E.storagePath,e).installFromLocal(u),log(e,`[AgentIDE] Created agent pack scaffold: ${l}`),showInfo(`AgentIDE: Created agent pack "${l}" at ${paths_1.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}/${paths_1.AGENT_CONSTANTS.AGENTS_DIR}/${l}/`);const y=vscode.Uri.file(path.join(u,"AGENTS.md"));if(await vscode.window.showTextDocument(y),await vscode.window.showInformationMessage(`Agent pack "${l}" created. Would you like help generating a specialized configuration?`,"Yes, help me configure it","No, I'll edit manually")==="Yes, help me configure it"){const f=[`I just created a new agent pack called "${l}"`,d?` that should: ${d}.`:".",`
8
+ This will create a pull request from your fork.`,{modal:!0},"Submit PR")!=="Submit PR")return;const g=await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Publishing engine ${p.engine.id} v${y}`,cancellable:!1},async M=>{M.report({message:w?`Publishing to ${d.owner}/${d.repo}...`:"Preparing fork..."});const b=await u({type:"engine",slug:p.engine.id,version:y,files:f,changelog:$},e);return M.report({message:"Creating PR..."}),b});await vscode.window.showInformationMessage(`Published engine "${p.engine.id}" v${y}! PR created.`,"View PR")==="View PR"&&vscode.env.openExternal(vscode.Uri.parse(g.prUrl))}catch(D){const k=D instanceof Error?D.message:String(D);log(e,`[AgentIDE] Engine publish error: ${k}`),showError(`${branding_1.AGENTIDE_BRAND_NAME}: ${k}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.uninstall",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s,isDefaultAgent:c}=await import("./agentpack/index.js"),i=new s(m,()=>n,()=>E.storagePath,e),u=(await i.listInstalled()).filter(k=>!c(k.id));if(u.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No agent packs available to uninstall`);return}const d=u.map(k=>({label:k.id,description:`v${k.version}${r.activePackId===k.id?" (active)":""}`})),o=await vscode.window.showQuickPick(d,{placeHolder:"Select a pack to uninstall",title:"Uninstall Agent Pack"});if(!o)return;const a=o.label,p=r.activePackId===a;if(await vscode.window.showWarningMessage(`Uninstall agent pack "${a}"?${p?" This will switch to the default agent.":""}`,{modal:!0},"Uninstall","Cancel")==="Uninstall")try{if(await i.uninstall(a),p){const k=await m.switchToPack(n,void 0,e,{importDerivedSkills:!0});r.activePackId=k,m.setActivePackId(n,k),log(e,"[AgentIDE] Switched to default agent after uninstalling active pack");try{await vscode.commands.executeCommand("agentide.applyPackPreferences",{packId:"default",silent:!0})}catch{}}showInfo(`AgentIDE: Uninstalled pack "${a}"${p?" - switched to default agent":""}`)}catch(k){const y=k instanceof Error?k.message:String(k);log(e,`[AgentIDE] Pack uninstall error: ${y}`),showError(`AgentIDE: Failed to uninstall pack - ${y}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.setActive",async n=>{if(!n?.packId)throw new Error("packId is required. Use workbench.action.chat.openAgentPackPicker for interactive selection.");const{workspaceRoot:s}=getWorkspaceRoot(e),c=n.packId==="default"?void 0:n.packId,i=await m.switchToPack(s,c,e,{importDerivedSkills:!0});return r.activePackId=i,m.setActivePackId(s,i),log(e,`[AgentIDE] Active pack switched to: ${i??"default"}`),await r.remotePackStatusBar?.refresh({notifyOnActivate:!0}),{activePackId:r.activePackId??"default"}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.getActive",()=>({activePackId:r.activePackId??"default"}))),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.getRemoteServeUrl",async n=>{const{workspaceRoot:s}=getWorkspaceRoot(e),c=n?.packId?.trim()||m.getActivePackId(s)||r.activePackId;if(!c||c==="default")return;const i=await m.getActiveAgentManifest(s,e,c),l=(0,serveClient_js_1.getRemoteServeUrl)(i);if(l)return{packId:c,remoteUrl:l,preferredEngine:i?.spec?.engine}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.create",async()=>{const{workspaceRoot:n,isHomeFallback:s}=getWorkspaceRoot(e);s&&await ensureFallbackDirectoryExists(e);let c;try{const a=await vscode.commands.executeCommand("agentide.getChatState");c=a?.modelId,log(e,`[AgentIDE] Current chat state: mode=${a?.mode}, modelId=${c}, modelName=${a?.modelName}`)}catch{}const i=await vscode.window.showInputBox({prompt:"Enter the agent pack name",placeHolder:"e.g., code-reviewer, security-auditor, My Code Reviewer",validateInput:async a=>{const p=(0,paths_1.normalizePackName)(a),D=(0,paths_1.getPackNameError)(p);if(D)return D;const k=path.join((0,paths_1.getAgentideDir)(n),paths_1.AGENT_CONSTANTS.AGENTS_DIR,p);if(await(0,utils_1.pathExists)(k))return`A pack named "${p}" already exists. Choose a different name.`}});if(!i)return;const l=(0,paths_1.normalizePackName)(i);log(e,`[AgentIDE] Pack name normalized: "${i}" -> "${l}"`);const u=path.join((0,paths_1.getAgentideDir)(n),paths_1.AGENT_CONSTANTS.AGENTS_DIR,l),d=await vscode.window.showInputBox({prompt:"Enter a short description for the pack",placeHolder:"e.g., Advanced code review agent with security analysis"}),o=await vscode.window.showQuickPick([{label:"Claude",description:"Anthropic Claude Agent SDK",engine:"claude"},{label:"Codex",description:"OpenAI Codex SDK",engine:"codex"}],{placeHolder:"Select the preferred engine for this pack",title:"Preferred Engine"});if(o)try{await fs_1.promises.mkdir(path.join(u,"rules"),{recursive:!0}),await fs_1.promises.mkdir(path.join(u,"skills"),{recursive:!0}),await fs_1.promises.mkdir(path.join(u,"mcp"),{recursive:!0});const a=(0,paths_1.generateAgentYaml)(l,{description:d||void 0,engine:o.engine,model:c});await fs_1.promises.writeFile(path.join(u,"agent.yaml"),a);const p=(0,paths_1.generateAgentsMd)(l,{description:d||void 0});await fs_1.promises.writeFile(path.join(u,"AGENTS.md"),p);const{AgentPackManager:D}=await import("./agentpack/index.js");await new D(m,()=>n,()=>E.storagePath,e).installFromLocal(u),log(e,`[AgentIDE] Created agent pack scaffold: ${l}`),showInfo(`AgentIDE: Created agent pack "${l}" at ${paths_1.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}/${paths_1.AGENT_CONSTANTS.AGENTS_DIR}/${l}/`);const y=vscode.Uri.file(path.join(u,"AGENTS.md"));if(await vscode.window.showTextDocument(y),await vscode.window.showInformationMessage(`Agent pack "${l}" created. Would you like help generating a specialized configuration?`,"Yes, help me configure it","No, I'll edit manually")==="Yes, help me configure it"){const f=[`I just created a new agent pack called "${l}"`,d?` that should: ${d}.`:".",`
9
9
 
10
10
  Please help me write a proper AGENTS.md file for this agent. `,`Ask me clarifying questions about:
11
11
  `,`1. What specific tasks this agent should excel at
@@ -13,15 +13,15 @@ Please help me write a proper AGENTS.md file for this agent. `,`Ask me clarifyin
13
13
  `,`3. What constraints or limitations it should follow
14
14
  `,`4. How it should format its outputs
15
15
 
16
- `,`The AGENTS.md file is at: ${paths_1.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}/agents/${l}/AGENTS.md`].join("");await vscode.commands.executeCommand("workbench.action.chat.open",{query:f,isPartialQuery:!1,mode:"agent",attachFiles:[y]})}}catch(a){const p=a instanceof Error?a.message:String(a);log(e,`[AgentIDE] Pack create error: ${p}`),showError(`AgentIDE: Failed to create pack - ${p}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.share",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),c=new s(m,()=>n,()=>E.storagePath,e),l=(await c.listInstalledWithCleanup()).filter(o=>o.id!=="default");if(l.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No agents to share (create an agent first)`);return}const u=l.map(o=>({label:o.id,description:`v${o.version}`})),d=await vscode.window.showQuickPick(u,{placeHolder:"Select an agent to share to User Library",title:"Share Agent to User Library"});if(d)try{const o=await c.shareToUserLibrary(d.label);showInfo(`AgentIDE: Shared "${d.label}" v${o} to User Library`)}catch(o){const a=o instanceof Error?o.message:String(o);log(e,`[AgentIDE] Share error: ${a}`),showError(`AgentIDE: ${a}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.skill.share",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),{getAgentSkillsDir:c,getUserSkillDir:i}=await import("./agentpack/paths.js"),{copyDirRecursive:l,pathExists:u}=await import("./utils.js"),o=await new s(m,()=>n,()=>E.storagePath,e).listInstalledWithCleanup();if(o.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No agents found`);return}const a=await vscode.window.showQuickPick(o.map(I=>({label:I.id,description:`v${I.version}`})),{placeHolder:"Select agent containing the skill",title:"Save Skill to User Library"});if(!a)return;const p=c(n,a.label);if(!await u(p)){showInfo(`AgentIDE: No skills found in ${a.label}`);return}const y=(await fs_1.promises.readdir(p,{withFileTypes:!0})).filter(I=>I.isDirectory()&&!I.name.startsWith(".")).map(I=>I.name);if(y.length===0){showInfo(`AgentIDE: No skills found in ${a.label}`);return}const $=await vscode.window.showQuickPick(y.map(I=>({label:I})),{placeHolder:"Select skill to save to User Library",title:"Save Skill to User Library"});if(!$)return;const f=path.join(p,$.label),w=i($.label);if(await u(w)){if(await vscode.window.showWarningMessage(`Skill "${$.label}" already exists in User Library. Overwrite?`,{modal:!0},"Overwrite","Cancel")!=="Overwrite")return;await fs_1.promises.rm(w,{recursive:!0,force:!0})}try{await l(f,w);const{getRegistry:I}=await import("./registry/index.js");await I(e).registerSkill({slug:$.label,displayName:$.label,latestVersion:"local",tags:[],stats:{installs:1}});const{invalidateLocalIndex:D}=await import("./store/oramaIndex.js");D(),showInfo(`AgentIDE: Saved skill "${$.label}" to User Library`)}catch(I){const g=I instanceof Error?I.message:String(I);log(e,`[AgentIDE] Share skill error: ${g}`),showError(`AgentIDE: ${g}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.mcp.share",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),{getAgentMcpDir:c,getUserMcpServerDir:i}=await import("./agentpack/paths.js"),{copyDirRecursive:l,pathExists:u}=await import("./utils.js"),o=await new s(m,()=>n,()=>E.storagePath,e).listInstalledWithCleanup();if(o.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No agents found`);return}const a=await vscode.window.showQuickPick(o.map(w=>({label:w.id,description:`v${w.version}`})),{placeHolder:"Select agent containing the MCP server",title:"Save MCP Server to User Library"});if(!a)return;const p=c(n,a.label),S=path.join(p,".mcp.json");let k={mcpServers:{}};try{const w=await fs_1.promises.readFile(S,"utf-8");k=JSON.parse(w)}catch{showInfo(`AgentIDE: No MCP servers configured in ${a.label}`);return}if(!k.mcpServers||Object.keys(k.mcpServers).length===0){showInfo(`AgentIDE: No MCP servers configured in ${a.label}`);return}const y=Object.keys(k.mcpServers),$=await vscode.window.showQuickPick(y.map(w=>({label:w})),{placeHolder:"Select MCP server to save to User Library",title:"Save MCP Server to User Library"});if(!$)return;const f=i($.label);if(await u(f)){if(await vscode.window.showWarningMessage(`MCP "${$.label}" already exists in User Library. Overwrite?`,{modal:!0},"Overwrite","Cancel")!=="Overwrite")return;await fs_1.promises.rm(f,{recursive:!0,force:!0})}try{await fs_1.promises.mkdir(f,{recursive:!0});const w=k.mcpServers[$.label];await fs_1.promises.writeFile(path.join(f,"mcp.json"),JSON.stringify({name:$.label,...w},null,2));const I=path.join(p,$.label);await u(I)&&await l(I,f);const{getRegistry:g}=await import("./registry/index.js");await g(e).registerMcp({slug:$.label,displayName:$.label,transport:w.transport||"stdio",latestVersion:"local",tags:[],stats:{installs:1}});const{invalidateLocalIndex:M}=await import("./store/oramaIndex.js");M(),showInfo(`AgentIDE: Saved MCP "${$.label}" to User Library`)}catch(w){const I=w instanceof Error?w.message:String(w);log(e,`[AgentIDE] Share MCP error: ${I}`),showError(`AgentIDE: ${I}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.publish",async()=>{await(0,githubStoreGate_js_1.ensureGitHubStoreAccess)(t);const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s,validateForPublish:c}=await import("./agentpack/index.js"),{publishToStore:i,STORE_CONFIG:l}=await import("./store/index.js"),o=(await new s(m,()=>n,()=>E.storagePath,e).listInstalledWithCleanup()).filter(g=>g.id!=="default");if(o.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No agents to publish (create an agent first)`);return}const a=await vscode.window.showQuickPick(o.map(g=>({label:g.id,description:`v${g.version}`})),{placeHolder:"Select an agent pack to publish",title:`Publish to ${l.owner}/${l.repo}`});if(!a)return;const p=await c(n,a.label);if(!p.valid){showError(`AgentIDE: Cannot publish - ${p.errors.join(", ")}`);return}if(p.warnings.length>0&&await vscode.window.showWarningMessage(`Warnings: ${p.warnings.join(", ")}`,"Publish Anyway","Cancel")!=="Publish Anyway")return;const S=await vscode.window.showInputBox({prompt:"What changed in this version? (optional)",placeHolder:"Added new features, fixed bugs..."}),{getAgentRoot:k}=await import("./agentpack/paths.js"),y=k(n,a.label),$=[];async function f(g,D){const M=await fs_1.promises.readdir(g);for(const b of M){if(b.startsWith("."))continue;const v=path.join(g,b),N=D?`${D}/${b}`:b;if((await fs_1.promises.stat(v)).isDirectory())await f(v,N);else{const P=await fs_1.promises.readFile(v,"utf-8");$.push({path:N,content:P})}}}await f(y,"");const w=o.find(g=>g.id===a.label);if(await vscode.window.showWarningMessage(`Submit "${w.id}" v${w.version} to ${l.owner}/${l.repo}?
16
+ `,`The AGENTS.md file is at: ${paths_1.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}/agents/${l}/AGENTS.md`].join("");await vscode.commands.executeCommand("workbench.action.chat.open",{query:f,isPartialQuery:!1,mode:"agent",attachFiles:[y]})}}catch(a){const p=a instanceof Error?a.message:String(a);log(e,`[AgentIDE] Pack create error: ${p}`),showError(`AgentIDE: Failed to create pack - ${p}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.share",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),c=new s(m,()=>n,()=>E.storagePath,e),l=(await c.listInstalledWithCleanup()).filter(o=>o.id!=="default");if(l.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No agents to share (create an agent first)`);return}const u=l.map(o=>({label:o.id,description:`v${o.version}`})),d=await vscode.window.showQuickPick(u,{placeHolder:"Select an agent to share to User Library",title:"Share Agent to User Library"});if(d)try{const o=await c.shareToUserLibrary(d.label);showInfo(`AgentIDE: Shared "${d.label}" v${o} to User Library`)}catch(o){const a=o instanceof Error?o.message:String(o);log(e,`[AgentIDE] Share error: ${a}`),showError(`AgentIDE: ${a}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.skill.share",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),{getAgentSkillsDir:c,getUserSkillDir:i}=await import("./agentpack/paths.js"),{copyDirRecursive:l,pathExists:u}=await import("./utils.js"),o=await new s(m,()=>n,()=>E.storagePath,e).listInstalledWithCleanup();if(o.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No agents found`);return}const a=await vscode.window.showQuickPick(o.map(I=>({label:I.id,description:`v${I.version}`})),{placeHolder:"Select agent containing the skill",title:"Save Skill to User Library"});if(!a)return;const p=c(n,a.label);if(!await u(p)){showInfo(`AgentIDE: No skills found in ${a.label}`);return}const y=(await fs_1.promises.readdir(p,{withFileTypes:!0})).filter(I=>I.isDirectory()&&!I.name.startsWith(".")).map(I=>I.name);if(y.length===0){showInfo(`AgentIDE: No skills found in ${a.label}`);return}const $=await vscode.window.showQuickPick(y.map(I=>({label:I})),{placeHolder:"Select skill to save to User Library",title:"Save Skill to User Library"});if(!$)return;const f=path.join(p,$.label),w=i($.label);if(await u(w)){if(await vscode.window.showWarningMessage(`Skill "${$.label}" already exists in User Library. Overwrite?`,{modal:!0},"Overwrite","Cancel")!=="Overwrite")return;await fs_1.promises.rm(w,{recursive:!0,force:!0})}try{await l(f,w);const{getRegistry:I}=await import("./registry/index.js");await I(e).registerSkill({slug:$.label,displayName:$.label,latestVersion:"local",tags:[],stats:{installs:1}});const{invalidateLocalIndex:S}=await import("./store/oramaIndex.js");S(),showInfo(`AgentIDE: Saved skill "${$.label}" to User Library`)}catch(I){const g=I instanceof Error?I.message:String(I);log(e,`[AgentIDE] Share skill error: ${g}`),showError(`AgentIDE: ${g}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.mcp.share",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),{getAgentMcpDir:c,getUserMcpServerDir:i}=await import("./agentpack/paths.js"),{copyDirRecursive:l,pathExists:u}=await import("./utils.js"),o=await new s(m,()=>n,()=>E.storagePath,e).listInstalledWithCleanup();if(o.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No agents found`);return}const a=await vscode.window.showQuickPick(o.map(w=>({label:w.id,description:`v${w.version}`})),{placeHolder:"Select agent containing the MCP server",title:"Save MCP Server to User Library"});if(!a)return;const p=c(n,a.label),D=path.join(p,".mcp.json");let k={mcpServers:{}};try{const w=await fs_1.promises.readFile(D,"utf-8");k=JSON.parse(w)}catch{showInfo(`AgentIDE: No MCP servers configured in ${a.label}`);return}if(!k.mcpServers||Object.keys(k.mcpServers).length===0){showInfo(`AgentIDE: No MCP servers configured in ${a.label}`);return}const y=Object.keys(k.mcpServers),$=await vscode.window.showQuickPick(y.map(w=>({label:w})),{placeHolder:"Select MCP server to save to User Library",title:"Save MCP Server to User Library"});if(!$)return;const f=i($.label);if(await u(f)){if(await vscode.window.showWarningMessage(`MCP "${$.label}" already exists in User Library. Overwrite?`,{modal:!0},"Overwrite","Cancel")!=="Overwrite")return;await fs_1.promises.rm(f,{recursive:!0,force:!0})}try{await fs_1.promises.mkdir(f,{recursive:!0});const w=k.mcpServers[$.label];await fs_1.promises.writeFile(path.join(f,"mcp.json"),JSON.stringify({name:$.label,...w},null,2));const I=path.join(p,$.label);await u(I)&&await l(I,f);const{getRegistry:g}=await import("./registry/index.js");await g(e).registerMcp({slug:$.label,displayName:$.label,transport:w.transport||"stdio",latestVersion:"local",tags:[],stats:{installs:1}});const{invalidateLocalIndex:M}=await import("./store/oramaIndex.js");M(),showInfo(`AgentIDE: Saved MCP "${$.label}" to User Library`)}catch(w){const I=w instanceof Error?w.message:String(w);log(e,`[AgentIDE] Share MCP error: ${I}`),showError(`AgentIDE: ${I}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.publish",async()=>{await(0,githubStoreGate_js_1.ensureGitHubStoreAccess)(t);const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s,validateForPublish:c}=await import("./agentpack/index.js"),{publishToStore:i,STORE_CONFIG:l}=await import("./store/index.js"),o=(await new s(m,()=>n,()=>E.storagePath,e).listInstalledWithCleanup()).filter(g=>g.id!=="default");if(o.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No agents to publish (create an agent first)`);return}const a=await vscode.window.showQuickPick(o.map(g=>({label:g.id,description:`v${g.version}`})),{placeHolder:"Select an agent pack to publish",title:`Publish to ${l.owner}/${l.repo}`});if(!a)return;const p=await c(n,a.label);if(!p.valid){showError(`AgentIDE: Cannot publish - ${p.errors.join(", ")}`);return}if(p.warnings.length>0&&await vscode.window.showWarningMessage(`Warnings: ${p.warnings.join(", ")}`,"Publish Anyway","Cancel")!=="Publish Anyway")return;const D=await vscode.window.showInputBox({prompt:"What changed in this version? (optional)",placeHolder:"Added new features, fixed bugs..."}),{getAgentRoot:k}=await import("./agentpack/paths.js"),y=k(n,a.label),$=[];async function f(g,S){const M=await fs_1.promises.readdir(g);for(const b of M){if(b.startsWith("."))continue;const v=path.join(g,b),N=S?`${S}/${b}`:b;if((await fs_1.promises.stat(v)).isDirectory())await f(v,N);else{const P=await fs_1.promises.readFile(v,"utf-8");$.push({path:N,content:P})}}}await f(y,"");const w=o.find(g=>g.id===a.label);if(await vscode.window.showWarningMessage(`Submit "${w.id}" v${w.version} to ${l.owner}/${l.repo}?
17
17
 
18
- This will create a pull request.`,{modal:!0},"Submit PR")==="Submit PR")try{const g=await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Publishing ${w.id} v${w.version}`,cancellable:!1},async M=>{M.report({message:"Preparing fork..."});const b=await i({type:"pack",slug:w.id,version:w.version,files:$,changelog:S},e);return M.report({message:"Creating PR..."}),b});await vscode.window.showInformationMessage(`Created PR #${g.prNumber} for ${w.id} v${w.version}`,"View PR")==="View PR"&&vscode.env.openExternal(vscode.Uri.parse(g.prUrl))}catch(g){const D=g instanceof Error?g.message:String(g);log(e,`[AgentIDE] Publish error: ${D}`),showError(`AgentIDE: ${D}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.installFromGitHub",async n=>{const{workspaceRoot:s}=getWorkspaceRoot(e),{installFromGitHub:c}=await import("./agentpack/index.js");let i=n;if(i||(i=await vscode.window.showInputBox({prompt:"Enter GitHub repository URL or owner/repo",placeHolder:"e.g., user/my-agent-pack or github://user/pack@v1.0.0",validateInput:l=>l.trim()?l.includes("/")?null:"Expected format: owner/repo or github://owner/repo@version":"Please enter a repository"})),!!i)try{const l=await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:"Installing from GitHub",cancellable:!1},async d=>(d.report({message:"Downloading..."}),await c(s,{source:i,force:!1},e)));await vscode.commands.executeCommand("agentide.packsChanged"),await m.seedAgentDataIfNeeded(s,l.agentId,e),await vscode.window.showInformationMessage(`Installed ${l.agentId} ${l.version}!`,"Activate")==="Activate"&&await vscode.commands.executeCommand("agentide.pack.switch",l.agentId)}catch(l){const u=l instanceof Error?l.message:String(l);if(u.includes("already exists")){if(await vscode.window.showWarningMessage(u,"Overwrite","Cancel")==="Overwrite")try{const o=await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:"Installing from GitHub",cancellable:!1},async a=>(a.report({message:"Downloading..."}),await c(s,{source:i,force:!0},e)));await vscode.commands.executeCommand("agentide.packsChanged"),await m.seedAgentDataIfNeeded(s,o.agentId,e),showInfo(`AgentIDE: Installed ${o.agentId} ${o.version}`)}catch(o){const a=o instanceof Error?o.message:String(o);showError(`AgentIDE: ${a}`)}}else log(e,`[AgentIDE] Install error: ${u}`),showError(`AgentIDE: ${u}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.browseLibrary",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),c=new s(m,()=>n,()=>E.storagePath,e),i=await c.listUserLibrary();if(i.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: User Library is empty. Share agents with "${branding_1.AGENTIDE_BRAND_NAME}: Share Agent to User Library"`);return}const l=i.map(o=>({label:o.id,description:o.currentVersion?`v${o.currentVersion}`:`${o.versions.length} version(s)`,detail:o.description||`Preferred engine: ${o.preferredEngine||"unknown"}`,agentId:o.id,currentVersion:o.currentVersion})),u=await vscode.window.showQuickPick(l,{placeHolder:"Select an agent to install",title:"User Agent Library"});if(!(!u||(await vscode.window.showQuickPick([{label:"Install to Workspace",action:"install"},{label:"Cancel",action:"cancel"}],{placeHolder:`What would you like to do with "${u.agentId}"?`}))?.action!=="install"))try{const o=await c.installAgentToWorkspace(u.agentId);if(o.installed){const a=o.hydrated?`Installed "${u.agentId}" v${o.version} to workspace from User Library`:`"${u.agentId}" is already installed in this workspace`;showInfo(`AgentIDE: ${a}`)}else showError(`AgentIDE: Failed to install "${u.agentId}"`)}catch(o){const a=o instanceof Error?o.message:String(o);log(e,`[AgentIDE] Install error: ${a}`),showError(`AgentIDE: ${a}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.skill.publish",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),s=path.join(n,".agent-hippo","agents"),c=[];if(await(0,utils_1.pathExists)(s)){const l=await fs_1.promises.readdir(s);for(const u of l){const d=path.join(s,u,"skills");if(await(0,utils_1.pathExists)(d)){const o=await fs_1.promises.readdir(d);for(const a of o){const p=path.join(d,a),S=path.join(p,"SKILL.md");await(0,utils_1.pathExists)(S)&&c.push({name:a,path:p})}}}}if(c.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No skills found. Create a skill with SKILL.md in your agent's skills/ folder.`);return}const i=await vscode.window.showQuickPick(c.map(l=>({label:l.name,path:l.path})),{placeHolder:"Select a skill to publish"});if(i)try{const{validateSkillForPublish:l,collectSkillFiles:u}=await import("./skills/publish.js"),{publishToStore:d}=await import("./store/index.js"),o=await l(i.path);if(!o.valid){showError(`AgentIDE: ${o.errors.join(", ")}`);return}const a=o.metadata?.version||await vscode.window.showInputBox({prompt:"Version (semver)",placeHolder:"e.g., 1.0.0",validateInput:w=>/^\d+\.\d+\.\d+/.test(w)?null:"Use semver format (e.g., 1.0.0)"});if(!a)return;const p=await u(i.path),S=await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Publishing skill "${i.label}"`,cancellable:!1},async w=>{w.report({message:"Preparing fork..."});const I=await d({type:"skill",slug:i.label,version:a,files:p},e);return w.report({message:"Creating PR..."}),I}),{getRegistry:k}=await import("./registry/index.js"),{STORE_CONFIG:y}=await import("./store/index.js");await k(e).registerSkill({slug:i.label,displayName:o.metadata?.name||i.label,description:o.metadata?.description,github:{owner:y.owner,repo:y.repo},latestVersion:a,tags:o.metadata?.tags||[],stats:{installs:0}}),await vscode.window.showInformationMessage(`Published skill "${i.label}" v${a}! PR created.`,"View PR")==="View PR"&&vscode.env.openExternal(vscode.Uri.parse(S.prUrl))}catch(l){const u=l instanceof Error?l.message:String(l);log(e,`[AgentIDE] Skill publish error: ${u}`),showError(`AgentIDE: ${u}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.mcp.publish",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),s=path.join(n,".agentide","agents"),c=[];if(await(0,utils_1.pathExists)(s)){const l=await fs_1.promises.readdir(s);for(const u of l){const d=path.join(s,u,"mcp"),o=path.join(d,".mcp.json");if(await(0,utils_1.pathExists)(o))try{const a=await fs_1.promises.readFile(o,"utf-8"),p=JSON.parse(a);if(p.mcpServers)for(const S of Object.keys(p.mcpServers))c.push({name:S,agentId:u,configPath:o,mcpDir:d})}catch{}}}if(c.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No MCP servers found. Add MCP servers to your agent's mcp/.mcp.json file.`);return}const i=await vscode.window.showQuickPick(c.map(l=>({label:l.name,description:`from ${l.agentId}`,detail:l.configPath,config:l})),{placeHolder:"Select an MCP server to publish"});if(i)try{const{publishToStore:l,STORE_CONFIG:u}=await import("./store/index.js"),{collectMcpFiles:d,validateMcpConfig:o}=await import("./mcp/publish.js"),{getRegistry:a}=await import("./registry/index.js"),p=await fs_1.promises.readFile(i.config.configPath,"utf-8"),k=JSON.parse(p).mcpServers[i.config.name],y=o({name:i.config.name,version:k.version||"1.0.0",description:k.description,transport:k.transport||"stdio",command:k.command,args:k.args,env:k.env,url:k.url,npmPackage:k.npmPackage});if(!y.valid){showError(`AgentIDE: ${y.errors.join(", ")}`);return}const $=k.version||await vscode.window.showInputBox({prompt:"Version (semver)",placeHolder:"e.g., 1.0.0",value:"1.0.0",validateInput:v=>/^\d+\.\d+\.\d+/.test(v)?null:"Use semver format (e.g., 1.0.0)"});if(!$)return;let f=k.description;if(!f&&(f=await vscode.window.showInputBox({prompt:"Description (required)",placeHolder:"What does this MCP server do?"}),!f)){showError(`${branding_1.AGENTIDE_BRAND_NAME}: Description is required`);return}const w=await d(i.config.mcpDir),I={name:i.config.name,version:$,description:f,transport:k.transport||"stdio",command:k.command,args:k.args,env:k.env,url:k.url,npmPackage:k.npmPackage},g=JSON.parse(JSON.stringify(I));w.push({path:"mcp.json",content:JSON.stringify(g,null,2)});const D=await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Publishing MCP "${i.config.name}"`,cancellable:!1},async v=>{v.report({message:"Preparing fork..."});const N=await l({type:"mcp",slug:i.config.name,version:$,files:w},e);return v.report({message:"Creating PR..."}),N});await a(e).registerMcp({slug:i.config.name,displayName:i.config.name,description:f,transport:k.transport||"stdio",github:{owner:u.owner,repo:u.repo},latestVersion:$,tags:[],stats:{installs:0}}),await vscode.window.showInformationMessage(`Published MCP "${i.config.name}" v${$}! PR created.`,"View PR")==="View PR"&&vscode.env.openExternal(vscode.Uri.parse(D.prUrl))}catch(l){const u=l instanceof Error?l.message:String(l);log(e,`[AgentIDE] MCP publish error: ${u}`),showError(`AgentIDE: ${u}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.spotlight.publish",async(n,s)=>{const c=s?.bundle==="scripts-only"?"scripts-only":"full",{workspaceRoot:i}=getWorkspaceRoot(e),{collectViewFiles:l,discoverPublishableViews:u,validateViewForPublish:d}=await import("./spotlight/publish.js"),{publishToStore:o,STORE_CONFIG:a,canPublishDirectlyToStore:p}=await import("./store/index.js"),{isValidPublishVersion:S}=await import("./engines/publish.js"),k=await u(i);if(k.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No publishable Spotlight views found. Create a view under .agent-hippo/analytics and register it in panel/views.yaml.`);return}const y=typeof n=="string"?n.trim():"";let $=y?k.find(f=>f.id===y):void 0;if(y&&!$){showError(`${branding_1.AGENTIDE_BRAND_NAME}: View "${y}" is not publishable. Add widget scripts under .agent-hippo/analytics/views/${y}/scripts and register the view in panel/views.yaml.`);return}if(!$){const f=await vscode.window.showQuickPick(k.map(w=>({label:w.name,description:w.id,detail:`${w.sourceLabel} \u2022 ${w.scope} \u2022 ${w.scripts.length} script(s)`,view:w})),{placeHolder:"Select a Spotlight view to publish",title:`Publish to ${a.owner}/${a.repo}`});if(!f)return;$=f.view}try{const f=await d($,{expectedId:$.id,mode:c});if(!f.valid){showError(`${branding_1.AGENTIDE_BRAND_NAME}: Cannot publish - ${f.errors.join(", ")}`);return}if(f.warnings.length>0&&await vscode.window.showWarningMessage(`Warnings: ${f.warnings.join(", ")}`,"Publish Anyway","Cancel")!=="Publish Anyway")return;const w=await vscode.window.showInputBox({prompt:"Publish version (semver)",value:f.metadata?.publishVersion||"1.0.0",placeHolder:"e.g., 1.0.0",validateInput:P=>P&&S(P.replace(/^v/,""))?null:"Use semver format (e.g., 1.0.0)"});if(!w||!f.metadata)return;const I=w.replace(/^v/,""),g=await vscode.window.showInputBox({prompt:"What changed in this version? (optional)",placeHolder:"Initial release, new widgets..."}),D=await l($,I,f.metadata,c),M=c==="full"?"full bundle (scripts + assets + charts/exports)":"scripts only",b=await p();if(await vscode.window.showWarningMessage(b?`Publish Spotlight view "${$.id}" v${I} (${M}) to ${a.owner}/${a.repo}?
18
+ This will create a pull request.`,{modal:!0},"Submit PR")==="Submit PR")try{const g=await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Publishing ${w.id} v${w.version}`,cancellable:!1},async M=>{M.report({message:"Preparing fork..."});const b=await i({type:"pack",slug:w.id,version:w.version,files:$,changelog:D},e);return M.report({message:"Creating PR..."}),b});await vscode.window.showInformationMessage(`Created PR #${g.prNumber} for ${w.id} v${w.version}`,"View PR")==="View PR"&&vscode.env.openExternal(vscode.Uri.parse(g.prUrl))}catch(g){const S=g instanceof Error?g.message:String(g);log(e,`[AgentIDE] Publish error: ${S}`),showError(`AgentIDE: ${S}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.installFromGitHub",async n=>{const{workspaceRoot:s}=getWorkspaceRoot(e),{installFromGitHub:c}=await import("./agentpack/index.js");let i=n;if(i||(i=await vscode.window.showInputBox({prompt:"Enter GitHub repository URL or owner/repo",placeHolder:"e.g., user/my-agent-pack or github://user/pack@v1.0.0",validateInput:l=>l.trim()?l.includes("/")?null:"Expected format: owner/repo or github://owner/repo@version":"Please enter a repository"})),!!i)try{const l=await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:"Installing from GitHub",cancellable:!1},async d=>(d.report({message:"Downloading..."}),await c(s,{source:i,force:!1},e)));await vscode.commands.executeCommand("agentide.packsChanged"),await m.seedAgentDataIfNeeded(s,l.agentId,e),await vscode.window.showInformationMessage(`Installed ${l.agentId} ${l.version}!`,"Activate")==="Activate"&&await vscode.commands.executeCommand("agentide.pack.switch",l.agentId)}catch(l){const u=l instanceof Error?l.message:String(l);if(u.includes("already exists")){if(await vscode.window.showWarningMessage(u,"Overwrite","Cancel")==="Overwrite")try{const o=await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:"Installing from GitHub",cancellable:!1},async a=>(a.report({message:"Downloading..."}),await c(s,{source:i,force:!0},e)));await vscode.commands.executeCommand("agentide.packsChanged"),await m.seedAgentDataIfNeeded(s,o.agentId,e),showInfo(`AgentIDE: Installed ${o.agentId} ${o.version}`)}catch(o){const a=o instanceof Error?o.message:String(o);showError(`AgentIDE: ${a}`)}}else log(e,`[AgentIDE] Install error: ${u}`),showError(`AgentIDE: ${u}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.browseLibrary",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),c=new s(m,()=>n,()=>E.storagePath,e),i=await c.listUserLibrary();if(i.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: User Library is empty. Share agents with "${branding_1.AGENTIDE_BRAND_NAME}: Share Agent to User Library"`);return}const l=i.map(o=>({label:o.id,description:o.currentVersion?`v${o.currentVersion}`:`${o.versions.length} version(s)`,detail:o.description||`Preferred engine: ${o.preferredEngine||"unknown"}`,agentId:o.id,currentVersion:o.currentVersion})),u=await vscode.window.showQuickPick(l,{placeHolder:"Select an agent to install",title:"User Agent Library"});if(!(!u||(await vscode.window.showQuickPick([{label:"Install to Workspace",action:"install"},{label:"Cancel",action:"cancel"}],{placeHolder:`What would you like to do with "${u.agentId}"?`}))?.action!=="install"))try{const o=await c.installAgentToWorkspace(u.agentId);if(o.installed){const a=o.hydrated?`Installed "${u.agentId}" v${o.version} to workspace from User Library`:`"${u.agentId}" is already installed in this workspace`;showInfo(`AgentIDE: ${a}`)}else showError(`AgentIDE: Failed to install "${u.agentId}"`)}catch(o){const a=o instanceof Error?o.message:String(o);log(e,`[AgentIDE] Install error: ${a}`),showError(`AgentIDE: ${a}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.skill.publish",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),s=path.join(n,".agent-hippo","agents"),c=[];if(await(0,utils_1.pathExists)(s)){const l=await fs_1.promises.readdir(s);for(const u of l){const d=path.join(s,u,"skills");if(await(0,utils_1.pathExists)(d)){const o=await fs_1.promises.readdir(d);for(const a of o){const p=path.join(d,a),D=path.join(p,"SKILL.md");await(0,utils_1.pathExists)(D)&&c.push({name:a,path:p})}}}}if(c.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No skills found. Create a skill with SKILL.md in your agent's skills/ folder.`);return}const i=await vscode.window.showQuickPick(c.map(l=>({label:l.name,path:l.path})),{placeHolder:"Select a skill to publish"});if(i)try{const{validateSkillForPublish:l,collectSkillFiles:u}=await import("./skills/publish.js"),{publishToStore:d}=await import("./store/index.js"),o=await l(i.path);if(!o.valid){showError(`AgentIDE: ${o.errors.join(", ")}`);return}const a=o.metadata?.version||await vscode.window.showInputBox({prompt:"Version (semver)",placeHolder:"e.g., 1.0.0",validateInput:w=>/^\d+\.\d+\.\d+/.test(w)?null:"Use semver format (e.g., 1.0.0)"});if(!a)return;const p=await u(i.path),D=await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Publishing skill "${i.label}"`,cancellable:!1},async w=>{w.report({message:"Preparing fork..."});const I=await d({type:"skill",slug:i.label,version:a,files:p},e);return w.report({message:"Creating PR..."}),I}),{getRegistry:k}=await import("./registry/index.js"),{STORE_CONFIG:y}=await import("./store/index.js");await k(e).registerSkill({slug:i.label,displayName:o.metadata?.name||i.label,description:o.metadata?.description,github:{owner:y.owner,repo:y.repo},latestVersion:a,tags:o.metadata?.tags||[],stats:{installs:0}}),await vscode.window.showInformationMessage(`Published skill "${i.label}" v${a}! PR created.`,"View PR")==="View PR"&&vscode.env.openExternal(vscode.Uri.parse(D.prUrl))}catch(l){const u=l instanceof Error?l.message:String(l);log(e,`[AgentIDE] Skill publish error: ${u}`),showError(`AgentIDE: ${u}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.mcp.publish",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),s=path.join(n,".agentide","agents"),c=[];if(await(0,utils_1.pathExists)(s)){const l=await fs_1.promises.readdir(s);for(const u of l){const d=path.join(s,u,"mcp"),o=path.join(d,".mcp.json");if(await(0,utils_1.pathExists)(o))try{const a=await fs_1.promises.readFile(o,"utf-8"),p=JSON.parse(a);if(p.mcpServers)for(const D of Object.keys(p.mcpServers))c.push({name:D,agentId:u,configPath:o,mcpDir:d})}catch{}}}if(c.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No MCP servers found. Add MCP servers to your agent's mcp/.mcp.json file.`);return}const i=await vscode.window.showQuickPick(c.map(l=>({label:l.name,description:`from ${l.agentId}`,detail:l.configPath,config:l})),{placeHolder:"Select an MCP server to publish"});if(i)try{const{publishToStore:l,STORE_CONFIG:u}=await import("./store/index.js"),{collectMcpFiles:d,validateMcpConfig:o}=await import("./mcp/publish.js"),{getRegistry:a}=await import("./registry/index.js"),p=await fs_1.promises.readFile(i.config.configPath,"utf-8"),k=JSON.parse(p).mcpServers[i.config.name],y=o({name:i.config.name,version:k.version||"1.0.0",description:k.description,transport:k.transport||"stdio",command:k.command,args:k.args,env:k.env,url:k.url,npmPackage:k.npmPackage});if(!y.valid){showError(`AgentIDE: ${y.errors.join(", ")}`);return}const $=k.version||await vscode.window.showInputBox({prompt:"Version (semver)",placeHolder:"e.g., 1.0.0",value:"1.0.0",validateInput:v=>/^\d+\.\d+\.\d+/.test(v)?null:"Use semver format (e.g., 1.0.0)"});if(!$)return;let f=k.description;if(!f&&(f=await vscode.window.showInputBox({prompt:"Description (required)",placeHolder:"What does this MCP server do?"}),!f)){showError(`${branding_1.AGENTIDE_BRAND_NAME}: Description is required`);return}const w=await d(i.config.mcpDir),I={name:i.config.name,version:$,description:f,transport:k.transport||"stdio",command:k.command,args:k.args,env:k.env,url:k.url,npmPackage:k.npmPackage},g=JSON.parse(JSON.stringify(I));w.push({path:"mcp.json",content:JSON.stringify(g,null,2)});const S=await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Publishing MCP "${i.config.name}"`,cancellable:!1},async v=>{v.report({message:"Preparing fork..."});const N=await l({type:"mcp",slug:i.config.name,version:$,files:w},e);return v.report({message:"Creating PR..."}),N});await a(e).registerMcp({slug:i.config.name,displayName:i.config.name,description:f,transport:k.transport||"stdio",github:{owner:u.owner,repo:u.repo},latestVersion:$,tags:[],stats:{installs:0}}),await vscode.window.showInformationMessage(`Published MCP "${i.config.name}" v${$}! PR created.`,"View PR")==="View PR"&&vscode.env.openExternal(vscode.Uri.parse(S.prUrl))}catch(l){const u=l instanceof Error?l.message:String(l);log(e,`[AgentIDE] MCP publish error: ${u}`),showError(`AgentIDE: ${u}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.spotlight.publish",async(n,s)=>{const c=s?.bundle==="scripts-only"?"scripts-only":"full",{workspaceRoot:i}=getWorkspaceRoot(e),{collectViewFiles:l,discoverPublishableViews:u,validateViewForPublish:d}=await import("./spotlight/publish.js"),{publishToStore:o,STORE_CONFIG:a,canPublishDirectlyToStore:p}=await import("./store/index.js"),{isValidPublishVersion:D}=await import("./engines/publish.js"),k=await u(i);if(k.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No publishable Spotlight views found. Create a view under .agent-hippo/analytics and register it in panel/views.yaml.`);return}const y=typeof n=="string"?n.trim():"";let $=y?k.find(f=>f.id===y):void 0;if(y&&!$){showError(`${branding_1.AGENTIDE_BRAND_NAME}: View "${y}" is not publishable. Add widget scripts under .agent-hippo/analytics/views/${y}/scripts and register the view in panel/views.yaml.`);return}if(!$){const f=await vscode.window.showQuickPick(k.map(w=>({label:w.name,description:w.id,detail:`${w.sourceLabel} \u2022 ${w.scope} \u2022 ${w.scripts.length} script(s)`,view:w})),{placeHolder:"Select a Spotlight view to publish",title:`Publish to ${a.owner}/${a.repo}`});if(!f)return;$=f.view}try{const f=await d($,{expectedId:$.id,mode:c});if(!f.valid){showError(`${branding_1.AGENTIDE_BRAND_NAME}: Cannot publish - ${f.errors.join(", ")}`);return}if(f.warnings.length>0&&await vscode.window.showWarningMessage(`Warnings: ${f.warnings.join(", ")}`,"Publish Anyway","Cancel")!=="Publish Anyway")return;const w=await vscode.window.showInputBox({prompt:"Publish version (semver)",value:f.metadata?.publishVersion||"1.0.0",placeHolder:"e.g., 1.0.0",validateInput:P=>P&&D(P.replace(/^v/,""))?null:"Use semver format (e.g., 1.0.0)"});if(!w||!f.metadata)return;const I=w.replace(/^v/,""),g=await vscode.window.showInputBox({prompt:"What changed in this version? (optional)",placeHolder:"Initial release, new widgets..."}),S=await l($,I,f.metadata,c),M=c==="full"?"full bundle (scripts + assets + charts/exports)":"scripts only",b=await p();if(await vscode.window.showWarningMessage(b?`Publish Spotlight view "${$.id}" v${I} (${M}) to ${a.owner}/${a.repo}?
19
19
 
20
20
  This will open a pull request on the store repository.`:`Submit Spotlight view "${$.id}" v${I} (${M}) to ${a.owner}/${a.repo}?
21
21
 
22
- This will create a pull request from your fork.`,{modal:!0},"Submit PR")!=="Submit PR")return;const N=await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Publishing Spotlight view ${$.id} v${I}`,cancellable:!1},async P=>(P.report({message:b?`Publishing to ${a.owner}/${a.repo}...`:"Preparing fork..."}),await o({type:"view",slug:$.id,version:I,files:D,changelog:g},e)));await vscode.window.showInformationMessage(`Published Spotlight view "${$.name}" v${I}! PR created.`,"View PR")==="View PR"&&vscode.env.openExternal(vscode.Uri.parse(N.prUrl))}catch(f){const w=f instanceof Error?f.message:String(f);log(e,`[AgentIDE] Spotlight publish error: ${w}`),showError(`${branding_1.AGENTIDE_BRAND_NAME}: ${w}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.store.install",async n=>{await(0,githubStoreGate_js_1.ensureGitHubStoreAccess)(t);const{parseStoreUrl:s}=await import("./store/index.js");let c=n;if(c||(c=await vscode.window.showInputBox({prompt:"Enter store URL or GitHub link",placeHolder:"e.g., engine/gemini or https://github.com/.../engines/gemini",validateInput:i=>i.trim()?i.includes("/")?null:"Expected: type/slug, or GitHub URL":"Please enter a URL"})),!!c)try{const i=s(c);switch(i.type){case"pack":await vscode.commands.executeCommand("agentide.pack.storeInstall",i);break;case"skill":await vscode.commands.executeCommand("agentide.skill.install",i);break;case"mcp":await vscode.commands.executeCommand("agentide.mcp.install",i);break;case"engine":await vscode.commands.executeCommand("agentide.engine.install",i);break;case"view":await vscode.commands.executeCommand("agentide.view.install",i);break}}catch(i){const l=i instanceof Error?i.message:String(i);log(e,`[AgentIDE] Store install error: ${l}`),showError(`AgentIDE: ${l}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.store.find",async n=>{await(0,githubStoreGate_js_1.ensureGitHubStoreAccess)(t);const{isStoreUrl:s,parseStoreUrl:c,parseGitHubUrl:i,detectArtifactType:l}=await import("./store/index.js"),{searchMerged:u,listMergedArtifacts:d}=await import("./store/oramaIndex.js");let o,a="all";if(typeof n=="string"?o=n:n&&typeof n=="object"&&n.typeFilter&&(a=n.typeFilter),o)try{let b,v,N;if(s(o)){const R=c(o);b=R.type,v=R.slug,N=R.version}else{const R=i(o);b=await vscode.window.withProgress({location:vscode.ProgressLocation.Notification,title:"Detecting artifact type...",cancellable:!1},async()=>await l(R.owner,R.repo,R.ref,R.path,e));const P=(R.path||R.repo).split("/");v=P[P.length-1]||R.repo,N=R.ref}switch(b){case"pack":await vscode.commands.executeCommand("agentide.pack.storeInstall",{type:"pack",slug:v,version:N,sourceUrl:o});break;case"skill":await vscode.commands.executeCommand("agentide.skill.install",{type:"skill",slug:v,version:N,sourceUrl:o});break;case"mcp":await vscode.commands.executeCommand("agentide.mcp.install",{type:"mcp",slug:v,version:N,sourceUrl:o});break;case"engine":await vscode.commands.executeCommand("agentide.engine.install",{type:"engine",slug:v,version:N,sourceUrl:o});break;case"view":await vscode.commands.executeCommand("agentide.view.install",{type:"view",slug:v,version:N,sourceUrl:o});break}return}catch(b){const v=b instanceof Error?b.message:String(b);log(e,`[AgentIDE] Install error: ${v}`),showError(`AgentIDE: ${v}`);return}const{STORE_ICONS:p}=await import("./store/shared.js"),S={pack:p.pack,skill:p.skill,mcp:p.mcp,engine:p.engine,view:p.view},k=["all","pack","skill","mcp","engine","view"],y=vscode.window.createQuickPick();y.title=a==="view"?"Install Spotlight View":"Install Packs, Skills, MCP Tools, Engines, Spotlight Views",y.placeholder="Search or paste a GitHub URL to install...",y.matchOnDescription=!0,y.matchOnDetail=!0,y.busy=!0;let $=[],f=a,w;const I={local:p.local,remote:p.remote},g=b=>{const v=b??$,N=f==="all"?v:v.filter(_=>_.type===f),R=k.map(_=>({label:_==="all"?"$(list-flat) All":`${S[_]} ${_.charAt(0).toUpperCase()+_.slice(1)}s`,description:_===f?"$(check)":"",alwaysShow:!0,itemType:"filter",filter:_})),P=N.map(_=>{const L=_.source==="local"?I.local:I.remote,x=_.installed?"$(check)":"",U=[_.source==="local"?"Local":"Remote",_.type];x&&U.push(x);let O=_.description||_.path;return _.installedTo&&_.installedTo.length>0&&(O+=` \u2022 Installed to: ${_.installedTo.join(", ")}`),{label:`${L} ${S[_.type]} ${_.slug}`,description:U.join(" \u2022 "),detail:O,itemType:"artifact",artifact:_}});y.items=[...R,{label:"",kind:vscode.QuickPickItemKind.Separator,itemType:"filter"},...P]},D=async b=>{w&&clearTimeout(w);const v=b.trim();if(!v||v.startsWith("http")||v.startsWith("store://")||v.startsWith("github.com")){g($);return}w=setTimeout(async()=>{try{const P=(await u(v,{type:f==="all"?void 0:f,limit:50},e)).map(_=>({type:_.type,slug:_.slug,path:`${_.type}s/${_.slug}`,description:_.description,installed:_.installed,installedVersion:_.installedVersion,source:_.source,installedTo:_.installedTo}));g(P)}catch(N){log(e,`[AgentIDE] Search error: ${N instanceof Error?N.message:String(N)}`),g($)}},150)};y.onDidChangeValue(D);try{$=(await d(void 0,e)).map(v=>({type:v.type,slug:v.slug,path:`${v.type}s/${v.slug}`,description:v.description,installed:v.installed,installedVersion:v.installedVersion,source:v.source,installedTo:v.installedTo})),y.busy=!1,g(),$.length===0&&(y.placeholder="Store is empty or index not synced yet. Try again later!")}catch(b){const v=b instanceof Error?b.message:String(b);log(e,`[AgentIDE] Store browse error: ${v}`),y.hide(),showError(`AgentIDE: ${v}`);return}const M=b=>{const v=b.trim();return v.startsWith("https://")||v.startsWith("http://")||v.startsWith("github.com/")||v.startsWith("store://")};y.onDidAccept(async()=>{const b=y.selectedItems[0],v=y.value.trim();if(v&&M(v)){y.hide(),log(e,`[AgentIDE] Browse Store: detected URL input: ${v}`),await vscode.commands.executeCommand("agentide.store.find",v);return}if(b){if(b.itemType==="filter"&&b.filter){f=b.filter,g();return}if(b.itemType==="artifact"&&b.artifact){y.hide();const{artifact:N}=b;switch(N.type){case"pack":await vscode.commands.executeCommand("agentide.pack.storeInstall",{type:"pack",slug:N.slug});break;case"skill":await vscode.commands.executeCommand("agentide.skill.install",{type:"skill",slug:N.slug});break;case"mcp":await vscode.commands.executeCommand("agentide.mcp.install",{type:"mcp",slug:N.slug});break;case"engine":await vscode.commands.executeCommand("agentide.engine.install",{type:"engine",slug:N.slug});break;case"view":await vscode.commands.executeCommand("agentide.view.install",{type:"view",slug:N.slug});break}}}}),y.onDidHide(()=>y.dispose()),y.show()})),t.subscriptions.push(vscode.commands.registerCommand("agentide.store.search",async(n,s)=>{const{searchMerged:c}=await import("./store/oramaIndex.js");return c(n,s,e)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.store.sync",async()=>{const{forceRefresh:n,getIndexMeta:s}=await import("./store/oramaIndex.js");await vscode.window.withProgress({location:vscode.ProgressLocation.Notification,title:"Syncing store index...",cancellable:!1},async()=>{await n(e)});const c=await s();c&&showInfo(`Store index synced: ${c.artifactCount} artifacts (updated ${new Date(c.generatedAt).toLocaleDateString()})`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.store.setup",async()=>{const{setupStoreAutomation:n}=await import("./store/github/setup.js"),s=await vscode.window.showInputBox({prompt:"Enter GitHub repository URL for your store",placeHolder:"https://github.com/owner/repo or owner/repo",validateInput:o=>o?o.match(/(?:github\.com\/)?([^/]+)\/([^/]+)/)?null:"Invalid format. Use: owner/repo or https://github.com/owner/repo":"Repository URL is required"});if(!s)return;const c=s.match(/(?:github\.com\/)?([^/]+)\/([^/]+)/);if(!c){showError("Invalid repository URL");return}const[,i,l]=c,u=l.replace(/\.git$/,""),d=await vscode.window.withProgress({location:vscode.ProgressLocation.Notification,title:`Setting up store automation for ${i}/${u}...`,cancellable:!1},async()=>await n(i,u,e));if(d.success&&d.pullRequestUrl){const o=vscode.workspace.getConfiguration("agentide"),a=`${i}/${u}`,p=o.get("storeRepo",""),S=o.get("store.indexUrl",""),k=`https://${i}.github.io/${u}`;let y="";if(p){const f=p.match(/^(?:https?:\/\/github\.com\/)?([^/]+)\/([^/]+?)(?:\.git)?$/);f&&(y=`https://${f[1]}.github.io/${f[2]}`)}await o.update("storeRepo",a,vscode.ConfigurationTarget.Global),(!S||y&&S===y)&&await o.update("store.indexUrl",k,vscode.ConfigurationTarget.Global);const $=await vscode.window.showInformationMessage(`\u{1F99B} ${d.message}`,"Open Pull Request","Copy URL");$==="Open Pull Request"?await vscode.env.openExternal(vscode.Uri.parse(d.pullRequestUrl)):$==="Copy URL"&&(await vscode.env.clipboard.writeText(d.pullRequestUrl),showInfo("Pull request URL copied to clipboard"))}else d.success||showError(`Setup failed: ${d.message}`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.storeInstall",async n=>{const{workspaceRoot:s}=getWorkspaceRoot(e),{downloadFromStore:c,listStoreVersions:i}=await import("./store/index.js"),{getAgentRoot:l}=await import("./agentpack/paths.js"),u=n||{type:"pack",slug:"",version:void 0};if(!u.version){const y=await i("pack",u.slug);if(y.length===0)u.version="main";else{const $=await vscode.window.showQuickPick(y.map(f=>({label:f.version,description:f.isPrerelease?"(pre-release)":""})),{placeHolder:"Select version to install"});if(!$)return;u.version=$.label}}const d=l(s,u.slug);if(await fs_1.promises.access(d).then(()=>!0).catch(()=>!1)){if(await vscode.window.showWarningMessage(`Pack "${u.slug}" already exists. Overwrite?`,{modal:!0},"Overwrite","Cancel")!=="Overwrite")return;await fs_1.promises.rm(d,{recursive:!0,force:!0})}await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Installing pack "${u.slug}"`,cancellable:!1},async y=>{y.report({message:"Downloading from store..."});const $=await c({type:"pack",slug:u.slug,version:u.version},e);y.report({message:"Extracting files..."}),await fs_1.promises.mkdir(d,{recursive:!0});for(const f of $){const w=path.join(d,f.path);await fs_1.promises.mkdir(path.dirname(w),{recursive:!0}),await fs_1.promises.writeFile(w,f.content)}}),await vscode.commands.executeCommand("agentide.packsChanged");const{getRegistry:a}=await import("./registry/index.js");await a(e).registerPack({slug:u.slug,displayName:u.slug,latestVersion:u.version||"main",tags:[],stats:{installs:1,stars:0}});const{invalidateLocalIndex:S}=await import("./store/oramaIndex.js");S(),await vscode.window.showInformationMessage(`Installed pack "${u.slug}" v${u.version}`,"Activate")==="Activate"&&await vscode.commands.executeCommand("agentide.pack.switch",u.slug)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.skill.install",async n=>{const{workspaceRoot:s}=getWorkspaceRoot(e),{downloadFromStore:c,downloadFromExternalGitHub:i,listStoreVersions:l,isStoreUrl:u,parseGitHubUrl:d}=await import("./store/index.js"),{AgentPackManager:o}=await import("./agentpack/index.js"),a=new o(m,()=>s,()=>E.storagePath,e);let p=n;if(!p){const b=await vscode.window.showInputBox({prompt:"Enter skill store URL or GitHub URL",placeHolder:"e.g., skills/typescript-testing@v1.0.0 or https://github.com/user/repo"});if(!b)return;const{parseStoreUrl:v}=await import("./store/index.js");p=v(b)}const S=p.sourceUrl&&!u(p.sourceUrl);if(!p.version&&!S){const b=await l("skill",p.slug);if(b.length===0)p.version="main";else{const v=await vscode.window.showQuickPick(b.map(N=>({label:N.version,description:N.isPrerelease?"(pre-release)":""})),{placeHolder:"Select version to install"});if(!v)return;p.version=v.label}}const k=await a.listInstalledWithCleanup();if(k.length===0){showError(`${branding_1.AGENTIDE_BRAND_NAME}: No agents found. Create an agent first.`);return}const y=await vscode.window.showQuickPick(k.map(b=>({label:b.id,description:`v${b.version}`})),{placeHolder:"Select agent to install skill to"});if(!y)return;const{getAgentRoot:$}=await import("./agentpack/paths.js"),f=$(s,y.label),w=path.join(f,"skills",p.slug);if(await fs_1.promises.access(w).then(()=>!0).catch(()=>!1)){if(await vscode.window.showWarningMessage(`Skill "${p.slug}" already exists in ${y.label}. Overwrite?`,{modal:!0},"Overwrite","Cancel")!=="Overwrite")return;await fs_1.promises.rm(w,{recursive:!0,force:!0})}await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Installing skill "${p.slug}"`,cancellable:!1},async b=>{let v;if(S&&p.sourceUrl){b.report({message:"Downloading from GitHub..."});const N=d(p.sourceUrl);v=await i({owner:N.owner,repo:N.repo,ref:N.ref||"main",path:N.path},e)}else b.report({message:"Downloading from store..."}),v=await c({type:"skill",slug:p.slug,version:p.version},e);b.report({message:"Extracting files..."}),await fs_1.promises.mkdir(w,{recursive:!0});for(const N of v){const R=path.join(w,N.path);await fs_1.promises.mkdir(path.dirname(R),{recursive:!0}),await fs_1.promises.writeFile(R,N.content)}});const{getRegistry:g}=await import("./registry/index.js");await g(e).registerSkill({slug:p.slug,displayName:p.slug,latestVersion:p.version||"main",tags:[],stats:{installs:1},agentPackId:y.label});const{invalidateLocalIndex:M}=await import("./store/oramaIndex.js");M(),showInfo(`Installed skill "${p.slug}" to ${y.label}`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.mcp.install",async n=>{const{workspaceRoot:s}=getWorkspaceRoot(e),{downloadFromStore:c,listStoreVersions:i}=await import("./store/index.js"),{AgentPackManager:l}=await import("./agentpack/index.js"),u=new l(m,()=>s,()=>E.storagePath,e);let d=n;if(!d){const y=await vscode.window.showInputBox({prompt:"Enter MCP store URL",placeHolder:"e.g., mcp/github@v1.0.0"});if(!y)return;const{parseStoreUrl:$}=await import("./store/index.js");d=$(y)}if(!d.version){const y=await i("mcp",d.slug);if(y.length===0)d.version="main";else{const $=await vscode.window.showQuickPick(y.map(f=>({label:f.version,description:f.isPrerelease?"(pre-release)":""})),{placeHolder:"Select version to install"});if(!$)return;d.version=$.label}}const o=await u.listInstalledWithCleanup();if(o.length===0){showError(`${branding_1.AGENTIDE_BRAND_NAME}: No agents found. Create an agent first.`);return}const a=await vscode.window.showQuickPick(o.map(y=>({label:y.id,description:`v${y.version}`})),{placeHolder:"Select agent to add MCP server to"});if(!a)return;await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Installing MCP "${d.slug}"`,cancellable:!1},async y=>{y.report({message:"Downloading from store..."});const $=await c({type:"mcp",slug:d.slug,version:d.version},e);y.report({message:"Merging MCP config..."});const f=$.find(v=>v.path==="mcp.json"||v.path.endsWith("/mcp.json"));if(!f)throw new Error("Downloaded MCP package missing mcp.json");const w=JSON.parse(f.content.toString()),{getAgentRoot:I}=await import("./agentpack/paths.js"),g=I(s,a.label),D=path.join(g,"mcp"),M=path.join(D,".mcp.json");await fs_1.promises.mkdir(D,{recursive:!0});let b={mcpServers:{}};try{const v=await fs_1.promises.readFile(M,"utf-8");b=JSON.parse(v),b.mcpServers||(b.mcpServers={})}catch{}b.mcpServers[d.slug]={transport:w.transport||"stdio",command:w.command,args:w.args,env:w.env,url:w.url,npmPackage:w.npmPackage,_version:d.version,_description:w.description},await fs_1.promises.writeFile(M,JSON.stringify(b,null,2));for(const v of $)if(v.path!=="mcp.json"&&!v.path.endsWith("/mcp.json")){const N=path.join(D,d.slug,v.path);await fs_1.promises.mkdir(path.dirname(N),{recursive:!0}),await fs_1.promises.writeFile(N,v.content)}});const{getRegistry:p}=await import("./registry/index.js");await p(e).registerMcp({slug:d.slug,displayName:d.slug,transport:"stdio",latestVersion:d.version||"main",tags:[],stats:{installs:1},agentPackId:a.label});const{invalidateLocalIndex:k}=await import("./store/oramaIndex.js");k(),showInfo(`Installed MCP "${d.slug}" v${d.version} to ${a.label}`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.engine.install",async n=>{const{downloadFromStore:s,downloadFromExternalGitHub:c,listStoreVersions:i,isStoreUrl:l,parseGitHubUrl:u,parseStoreUrl:d}=await import("./store/index.js"),{installCustomEngineFromFiles:o}=await import("./engines/install.js");let a=n;if(!a){const f=await vscode.window.showInputBox({prompt:"Enter custom engine store URL or GitHub URL",placeHolder:"e.g., engine/gemini or https://github.com/user/repo/tree/main/gemini"});if(!f)return;if(l(f))a=d(f);else{const w=u(f),I=(w.path||w.repo).split("/");a={type:"engine",slug:I[I.length-1]||w.repo,version:w.ref,sourceUrl:f}}}const p=a.sourceUrl&&!l(a.sourceUrl);if(!a.version&&!p){const f=await i("engine",a.slug);if(f.length===0)a.version="main";else{const w=await vscode.window.showQuickPick(f.map(I=>({label:I.version,description:I.isPrerelease?"(pre-release)":""})),{placeHolder:"Select version to install"});if(!w)return;a.version=w.label}}const S=async f=>await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Installing engine "${a.slug}"`,cancellable:!1},async w=>{let I;if(p&&a.sourceUrl){w.report({message:"Downloading from GitHub..."});const g=u(a.sourceUrl);I=await c({owner:g.owner,repo:g.repo,ref:g.ref||"main",path:g.path},e)}else w.report({message:"Downloading from store..."}),I=await s({type:"engine",slug:a.slug,version:a.version},e);return w.report({message:"Validating and installing..."}),await o(I,{slug:a.slug,version:a.version,sourceUrl:a.sourceUrl,overwrite:f,logger:e})});let k;try{k=await S(!1)}catch(f){const w=f instanceof Error?f.message:String(f);if(!w.includes("already exists")){log(e,`[AgentIDE] Engine install error: ${w}`),showError(`AgentIDE: ${w}`);return}if(await vscode.window.showWarningMessage(w,{modal:!0},"Overwrite","Cancel")!=="Overwrite")return;try{k=await S(!0)}catch(g){const D=g instanceof Error?g.message:String(g);log(e,`[AgentIDE] Engine install error: ${D}`),showError(`AgentIDE: ${D}`);return}}const{invalidateLocalIndex:y}=await import("./store/oramaIndex.js");if(y(),!k)return;clearCustomEngineRuntimeCache(r,k.id),await refreshCustomEnginePicker(e),await vscode.window.showInformationMessage(`Installed engine "${k.displayName}"`,"List Engines")==="List Engines"&&await vscode.commands.executeCommand("agentide.customEngine.list")})),t.subscriptions.push(vscode.commands.registerCommand("agentide.view.install",async n=>{const{workspaceRoot:s}=getWorkspaceRoot(e),{downloadFromStore:c,downloadFromExternalGitHub:i,listStoreVersions:l,isStoreUrl:u,parseGitHubUrl:d,parseStoreUrl:o}=await import("./store/index.js"),{installSpotlightViewFromFiles:a}=await import("./spotlight/install.js");let p=n;if(!p){const I=await vscode.window.showInputBox({prompt:"Enter Spotlight view store URL or GitHub URL",placeHolder:"e.g., view/cost-ops or https://github.com/user/repo/tree/main/spotlight/cost-ops"});if(!I)return;if(u(I))p=o(I);else{const g=d(I),D=(g.path||g.repo).split("/");p={type:"view",slug:D[D.length-1]||g.repo,version:g.ref,sourceUrl:I}}}const S=p.sourceUrl&&!u(p.sourceUrl);if(!p.version&&!S){const I=await l("view",p.slug);if(I.length===0)p.version="main";else{const g=await vscode.window.showQuickPick(I.map(D=>({label:D.version,description:D.isPrerelease?"(pre-release)":""})),{placeHolder:"Select version to install"});if(!g)return;p.version=g.label}}const k=async(I,g)=>await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Installing Spotlight view "${p.slug}"`,cancellable:!1},async D=>{let M;if(S&&p.sourceUrl){D.report({message:"Downloading from GitHub..."});const b=d(p.sourceUrl);M=(await i({owner:b.owner,repo:b.repo,ref:b.ref||"main",path:b.path},e)).map(N=>({path:N.path,content:N.content}))}else D.report({message:"Downloading from store..."}),M=await c({type:"view",slug:p.slug,version:p.version},e);return D.report({message:"Installing view..."}),await a(M,{slug:p.slug,version:p.version,overwrite:I,activate:g,workspaceRoot:s,logger:e})});let y;try{y=await k(!1,!1)}catch(I){const g=I instanceof Error?I.message:String(I);if(!g.includes("already exists")){log(e,`[AgentIDE] Spotlight view install error: ${g}`),showError(`AgentIDE: ${g}`);return}if(await vscode.window.showWarningMessage(g,{modal:!0},"Overwrite","Cancel")!=="Overwrite")return;try{y=await k(!0,!1)}catch(M){const b=M instanceof Error?M.message:String(M);log(e,`[AgentIDE] Spotlight view install error: ${b}`),showError(`AgentIDE: ${b}`);return}}const{invalidateLocalIndex:$}=await import("./store/oramaIndex.js");if($(),!y)return;const f=_state?.analyticsDashboard;f&&await f.refreshViewsFromDisk();const w=await vscode.window.showInformationMessage(`Installed Spotlight view "${y.id}" v${y.version||p.version||"main"}`,"Open Spotlight","Activate View");if(w==="Open Spotlight")await vscode.commands.executeCommand("agentide.analytics.openDashboard");else if(w==="Activate View"){const{setActiveSpotlightView:I}=await import("./spotlight/install.js");await I(y.viewsConfigPath,y.id);const g=_state?.analyticsDashboard;g&&await g.refreshViewsFromDisk(),await vscode.commands.executeCommand("agentide.analytics.openDashboard")}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.update",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),c=new s(m,()=>n,()=>E.storagePath,e),i=await c.listInstalledWithCleanup(),l=[];for(const a of i){if(a.id==="default")continue;const p=await c.checkAgentUpdate(a.id);p&&l.push({id:a.id,version:a.version,newVersion:p})}if(l.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: All agents are up to date`);return}const u=l.map(a=>({label:a.id,description:`v${a.version} \u2192 v${a.newVersion}`})),d=await vscode.window.showQuickPick(u,{placeHolder:"Select an agent to update",title:"Update Agent from User Library"});if(!(!d||await vscode.window.showWarningMessage(`Update "${d.label}" from User Library? Current version will be backed up.`,{modal:!0},"Update","Cancel")!=="Update"))try{const a=await c.updateFromLibrary(d.label);showInfo(`AgentIDE: Updated "${d.label}" to v${a}`)}catch(a){const p=a instanceof Error?a.message:String(a);log(e,`[AgentIDE] Update error: ${p}`),showError(`AgentIDE: ${p}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.duplicate",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),c=new s(m,()=>n,()=>E.storagePath,e),i=await c.listInstalledWithCleanup();if(i.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No agents to duplicate`);return}const l=i.map(d=>({label:d.id,description:`v${d.version}`})),u=await vscode.window.showQuickPick(l,{placeHolder:"Select an agent to duplicate",title:"Duplicate Agent"});if(u)try{const d=await c.duplicate(u.label);showInfo(`AgentIDE: Created "${d}" as copy of "${u.label}"`);const o=path.join((0,paths_1.getAgentideDir)(n),paths_1.AGENT_CONSTANTS.AGENTS_DIR,d,paths_1.AGENT_CONSTANTS.AGENTS_MD);if(await(0,utils_1.pathExists)(o)){const a=await vscode.workspace.openTextDocument(o);await vscode.window.showTextDocument(a)}}catch(d){const o=d instanceof Error?d.message:String(d);log(e,`[AgentIDE] Duplicate error: ${o}`),showError(`AgentIDE: ${o}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.refresh",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),c=new s(m,()=>n,()=>E.storagePath,e);try{const{registered:i}=await c.repairUnregisteredAgents();return i.length>0?showInfo(`AgentIDE: Discovered ${i.length} new pack(s): ${i.join(", ")}`):showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No new packs found`),{registered:i}}catch(i){const l=i instanceof Error?i.message:String(i);return log(e,`[AgentIDE] Pack refresh error: ${l}`),showError(`AgentIDE: ${l}`),{registered:[]}}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.resetDefault",async()=>{if(await vscode.window.showWarningMessage("Reset the default agent? This will restore it from bundled templates. Current default agent will be backed up.",{modal:!0},"Reset","Cancel")!=="Reset")return;const{workspaceRoot:s}=getWorkspaceRoot(e),{AgentPackManager:c}=await import("./agentpack/index.js"),i=new c(m,()=>s,()=>E.storagePath,e);try{await i.resetDefault(getBundledBasePromptsDir()),showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: Default agent reset from bundled templates`),await m.flushAgentideRootUpdate(s,e,{force:!0,allowDuringActiveTurn:!0})}catch(l){const u=l instanceof Error?l.message:String(l);log(e,`[AgentIDE] Reset error: ${u}`),showError(`AgentIDE: ${u}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.chat",async n=>handleChatCommand(r,n))),t.subscriptions.push(vscode.commands.registerCommand("agentide.chat.cancel",async n=>{const s=n?.streamId;if(!s)return{cancelled:!1,error:"streamId is required"};const c=_activeRunsByStreamId.get(s);if(!c)return log(e,`[AgentIDE] Cancel ignored: no active run for streamId=${s}`),rejectPendingQuestionsForStream(s,"Run cancelled"),{cancelled:!1};log(e,`[AgentIDE] Cancel requested: streamId=${s}, engine=${c.engine}, ageMs=${Date.now()-c.startedAt}`);try{c.abortController.abort()}catch{}return rejectPendingQuestionsForStream(s,"Run cancelled"),{cancelled:!0}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.chat.answerQuestion",async n=>{const s=n?.streamId,c=n?.questionId;if(!s||!c)return{ok:!1,error:"streamId and questionId are required"};const i=_pendingQuestionsById.get(c);if(!i||i.streamId!==s)return{ok:!1,error:"Question not found or already resolved"};const l=normalizeQuestionAnswer(n?.answer);return resolvePendingQuestion(c,l),{ok:!0}}))}function getUserPermissions(){return{fileAccess:vscode.workspace.getConfiguration("agentide").get("permissions.fileAccess","full")}}function getConfiguredAdditionalEngineDir(){return vscode.workspace.getConfiguration("agentide").get("additionalEngineDir")}function clearCustomEngineRuntimeCache(t,r){const e=t.engines.custom;try{e?.clearInstances?.(r)}catch(m){log(t.outputChannel,`[AgentIDE] Custom engine cache clear warning: ${m instanceof Error?m.message:String(m)}`)}}async function refreshCustomEnginePicker(t){try{await vscode.commands.executeCommand("agentide.engine.refresh")}catch(r){log(t,`[AgentIDE] Custom engine picker refresh warning: ${r instanceof Error?r.message:String(r)}`)}}const _sessionEventWriter=new sessionEvents_1.SessionEventWriter;async function handleChatCommand(t,r){const{outputChannel:e,engines:m,syncService:E,config:h}=t,{engine:C,streamId:A}=r;let{message:T}=r;const n=r.options??{};let s;const c=T.match(/^\[gw:(gw-[^\]]+)\]/);if(c){const P=c[1];T=T.slice(c[0].length),log(e,`[AgentIDE] Gateway request detected, token=${P.slice(0,20)}...`);const{GatewayService:_}=await import("./gateway/service.js");s=_.getGatewayEmitter(P),s?log(e,"[AgentIDE] Gateway emitter found, will stream to both Chat UI and Gateway"):log(e,`[AgentIDE] Gateway emitter NOT found for token ${P.slice(0,20)}...`)}const{workspaceRoot:i,additionalDirectories:l,isHomeFallback:u}=getWorkspaceRoot(e,n.workspaceRoot,n.additionalDirectories);A&&u&&await warnHomeFallbackOnce(e,A);const d=await E.getActiveAgentManifest(i,e,E.getActivePackId(i)??t.activePackId),o=d?.spec?.remote?.url?.trim();if(o)return(0,handleRemoteChat_js_1.handleRemoteServeChat)({outputChannel:e,syncService:E,sessionEventWriter:_sessionEventWriter,activeRunsByStreamId:_activeRunsByStreamId,rejectPendingQuestionsForStream,askQuestionViaWorkbenchTool,askQuestionFromChatUI,getServeAuth:async()=>{if(!_extensionContext)return;const P=await(0,provider_js_1.getAgentHippoAccessToken)(_extensionContext);if(P)return{accessToken:P.accessToken,userEmail:P.email}},ensureSignedIn:async()=>{if(!_extensionContext)return;const P=await(0,signInFlow_js_1.ensureAgentHippoSignedIn)(_extensionContext);if(P)return{accessToken:P.accessToken,userEmail:P.email}},log},{engine:C,message:T,options:r.options,streamId:A,sessionResource:r.sessionResource,requestId:r.requestId,remoteUrl:o,remoteManifest:d,workspaceRoot:i,incomingOptions:n,gatewayEmitter:s});let a={...n,workspaceRoot:i,additionalDirectories:l,agentPackId:t.activePackId};if(!A)return{error:"streamId is required - non-streaming mode is no longer supported"};let p=C,S=m[p];if(!S&&p!=="codex"&&p!=="claude"&&m.custom&&(a={...a,engineId:a.engineId??p},p="custom",S=m.custom,log(e,`[AgentIDE] Routing requested engine "${C}" through custom runtime loader`)),!S){const P=`Unknown engine: ${C}`;return log(e,`[AgentIDE] Error: ${P}`),{error:P}}log(e,`[AgentIDE] Chat request for engine=${C} (runtime=${p}), streamId: ${A}, useLiteLLM: ${a.useLiteLLM||!1}`);const k=new AbortController;_activeRunsByStreamId.set(A,{streamId:A,engine:p,startedAt:Date.now(),abortController:k});const y=(0,utils_1.createIPCStreamEmitter)(A),$=r.sessionResource,f=r.requestId,w={...y,async question(P){return $?await askQuestionViaWorkbenchTool($,f,P,k.signal):await askQuestionFromChatUI(A,P)}},I=s?{...w,async thinking(P){await y.thinking(P),await s.thinking(`<thinking>${P}</thinking>`)},async text(P){await y.text(P),await s.text(P)},async toolStart(P,_,L,x){await y.toolStart(P,_,L,x),await s.toolStart(P,_,L,x)},async toolEnd(P,_,L,x,U){await y.toolEnd(P,_,L,x,U),await s.toolEnd(P,_,L,x,U)},async progress(P){await y.progress(P),await s.progress(P)},async question(P){const _=await w.question(P);return await s.progress(`Question answered: ${questionPromptToHeader(P.prompt)}`),_},async error(P){await y.error(P),await s.error(P)},async done(){await y.done(),await s.done()}}:w,g=getTerminalLogInfo(a);await appendTerminalAttachmentsToLog(r.context,A,e,g?.uri),await persistImageAttachments(r.context,a,e),await persistFileAndDirectoryAttachments(r.context,a,e);const D=formatSdkContextSuffix(r.context,g?.relativePath),M=D?`${T}
22
+ This will create a pull request from your fork.`,{modal:!0},"Submit PR")!=="Submit PR")return;const N=await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Publishing Spotlight view ${$.id} v${I}`,cancellable:!1},async P=>(P.report({message:b?`Publishing to ${a.owner}/${a.repo}...`:"Preparing fork..."}),await o({type:"view",slug:$.id,version:I,files:S,changelog:g},e)));await vscode.window.showInformationMessage(`Published Spotlight view "${$.name}" v${I}! PR created.`,"View PR")==="View PR"&&vscode.env.openExternal(vscode.Uri.parse(N.prUrl))}catch(f){const w=f instanceof Error?f.message:String(f);log(e,`[AgentIDE] Spotlight publish error: ${w}`),showError(`${branding_1.AGENTIDE_BRAND_NAME}: ${w}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.store.install",async n=>{await(0,githubStoreGate_js_1.ensureGitHubStoreAccess)(t);const{parseStoreUrl:s}=await import("./store/index.js");let c=n;if(c||(c=await vscode.window.showInputBox({prompt:"Enter store URL or GitHub link",placeHolder:"e.g., engine/gemini or https://github.com/.../engines/gemini",validateInput:i=>i.trim()?i.includes("/")?null:"Expected: type/slug, or GitHub URL":"Please enter a URL"})),!!c)try{const i=s(c);switch(i.type){case"pack":await vscode.commands.executeCommand("agentide.pack.storeInstall",i);break;case"skill":await vscode.commands.executeCommand("agentide.skill.install",i);break;case"mcp":await vscode.commands.executeCommand("agentide.mcp.install",i);break;case"engine":await vscode.commands.executeCommand("agentide.engine.install",i);break;case"view":await vscode.commands.executeCommand("agentide.view.install",i);break}}catch(i){const l=i instanceof Error?i.message:String(i);log(e,`[AgentIDE] Store install error: ${l}`),showError(`AgentIDE: ${l}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.store.find",async n=>{await(0,githubStoreGate_js_1.ensureGitHubStoreAccess)(t);const{isStoreUrl:s,parseStoreUrl:c,parseGitHubUrl:i,detectArtifactType:l}=await import("./store/index.js"),{searchMerged:u,listMergedArtifacts:d}=await import("./store/oramaIndex.js");let o,a="all";if(typeof n=="string"?o=n:n&&typeof n=="object"&&n.typeFilter&&(a=n.typeFilter),o)try{let b,v,N;if(s(o)){const R=c(o);b=R.type,v=R.slug,N=R.version}else{const R=i(o);b=await vscode.window.withProgress({location:vscode.ProgressLocation.Notification,title:"Detecting artifact type...",cancellable:!1},async()=>await l(R.owner,R.repo,R.ref,R.path,e));const P=(R.path||R.repo).split("/");v=P[P.length-1]||R.repo,N=R.ref}switch(b){case"pack":await vscode.commands.executeCommand("agentide.pack.storeInstall",{type:"pack",slug:v,version:N,sourceUrl:o});break;case"skill":await vscode.commands.executeCommand("agentide.skill.install",{type:"skill",slug:v,version:N,sourceUrl:o});break;case"mcp":await vscode.commands.executeCommand("agentide.mcp.install",{type:"mcp",slug:v,version:N,sourceUrl:o});break;case"engine":await vscode.commands.executeCommand("agentide.engine.install",{type:"engine",slug:v,version:N,sourceUrl:o});break;case"view":await vscode.commands.executeCommand("agentide.view.install",{type:"view",slug:v,version:N,sourceUrl:o});break}return}catch(b){const v=b instanceof Error?b.message:String(b);log(e,`[AgentIDE] Install error: ${v}`),showError(`AgentIDE: ${v}`);return}const{STORE_ICONS:p}=await import("./store/shared.js"),D={pack:p.pack,skill:p.skill,mcp:p.mcp,engine:p.engine,view:p.view},k=["all","pack","skill","mcp","engine","view"],y=vscode.window.createQuickPick();y.title=a==="view"?"Install Spotlight View":"Install Packs, Skills, MCP Tools, Engines, Spotlight Views",y.placeholder="Search or paste a GitHub URL to install...",y.matchOnDescription=!0,y.matchOnDetail=!0,y.busy=!0;let $=[],f=a,w;const I={local:p.local,remote:p.remote},g=b=>{const v=b??$,N=f==="all"?v:v.filter(_=>_.type===f),R=k.map(_=>({label:_==="all"?"$(list-flat) All":`${D[_]} ${_.charAt(0).toUpperCase()+_.slice(1)}s`,description:_===f?"$(check)":"",alwaysShow:!0,itemType:"filter",filter:_})),P=N.map(_=>{const L=_.source==="local"?I.local:I.remote,x=_.installed?"$(check)":"",U=[_.source==="local"?"Local":"Remote",_.type];x&&U.push(x);let O=_.description||_.path;return _.installedTo&&_.installedTo.length>0&&(O+=` \u2022 Installed to: ${_.installedTo.join(", ")}`),{label:`${L} ${D[_.type]} ${_.slug}`,description:U.join(" \u2022 "),detail:O,itemType:"artifact",artifact:_}});y.items=[...R,{label:"",kind:vscode.QuickPickItemKind.Separator,itemType:"filter"},...P]},S=async b=>{w&&clearTimeout(w);const v=b.trim();if(!v||v.startsWith("http")||v.startsWith("store://")||v.startsWith("github.com")){g($);return}w=setTimeout(async()=>{try{const P=(await u(v,{type:f==="all"?void 0:f,limit:50},e)).map(_=>({type:_.type,slug:_.slug,path:`${_.type}s/${_.slug}`,description:_.description,installed:_.installed,installedVersion:_.installedVersion,source:_.source,installedTo:_.installedTo}));g(P)}catch(N){log(e,`[AgentIDE] Search error: ${N instanceof Error?N.message:String(N)}`),g($)}},150)};y.onDidChangeValue(S);try{$=(await d(void 0,e)).map(v=>({type:v.type,slug:v.slug,path:`${v.type}s/${v.slug}`,description:v.description,installed:v.installed,installedVersion:v.installedVersion,source:v.source,installedTo:v.installedTo})),y.busy=!1,g(),$.length===0&&(y.placeholder="Store is empty or index not synced yet. Try again later!")}catch(b){const v=b instanceof Error?b.message:String(b);log(e,`[AgentIDE] Store browse error: ${v}`),y.hide(),showError(`AgentIDE: ${v}`);return}const M=b=>{const v=b.trim();return v.startsWith("https://")||v.startsWith("http://")||v.startsWith("github.com/")||v.startsWith("store://")};y.onDidAccept(async()=>{const b=y.selectedItems[0],v=y.value.trim();if(v&&M(v)){y.hide(),log(e,`[AgentIDE] Browse Store: detected URL input: ${v}`),await vscode.commands.executeCommand("agentide.store.find",v);return}if(b){if(b.itemType==="filter"&&b.filter){f=b.filter,g();return}if(b.itemType==="artifact"&&b.artifact){y.hide();const{artifact:N}=b;switch(N.type){case"pack":await vscode.commands.executeCommand("agentide.pack.storeInstall",{type:"pack",slug:N.slug});break;case"skill":await vscode.commands.executeCommand("agentide.skill.install",{type:"skill",slug:N.slug});break;case"mcp":await vscode.commands.executeCommand("agentide.mcp.install",{type:"mcp",slug:N.slug});break;case"engine":await vscode.commands.executeCommand("agentide.engine.install",{type:"engine",slug:N.slug});break;case"view":await vscode.commands.executeCommand("agentide.view.install",{type:"view",slug:N.slug});break}}}}),y.onDidHide(()=>y.dispose()),y.show()})),t.subscriptions.push(vscode.commands.registerCommand("agentide.store.search",async(n,s)=>{const{searchMerged:c}=await import("./store/oramaIndex.js");return c(n,s,e)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.store.sync",async()=>{const{forceRefresh:n,getIndexMeta:s}=await import("./store/oramaIndex.js");await vscode.window.withProgress({location:vscode.ProgressLocation.Notification,title:"Syncing store index...",cancellable:!1},async()=>{await n(e)});const c=await s();c&&showInfo(`Store index synced: ${c.artifactCount} artifacts (updated ${new Date(c.generatedAt).toLocaleDateString()})`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.store.setup",async()=>{const{setupStoreAutomation:n}=await import("./store/github/setup.js"),s=await vscode.window.showInputBox({prompt:"Enter GitHub repository URL for your store",placeHolder:"https://github.com/owner/repo or owner/repo",validateInput:o=>o?o.match(/(?:github\.com\/)?([^/]+)\/([^/]+)/)?null:"Invalid format. Use: owner/repo or https://github.com/owner/repo":"Repository URL is required"});if(!s)return;const c=s.match(/(?:github\.com\/)?([^/]+)\/([^/]+)/);if(!c){showError("Invalid repository URL");return}const[,i,l]=c,u=l.replace(/\.git$/,""),d=await vscode.window.withProgress({location:vscode.ProgressLocation.Notification,title:`Setting up store automation for ${i}/${u}...`,cancellable:!1},async()=>await n(i,u,e));if(d.success&&d.pullRequestUrl){const o=vscode.workspace.getConfiguration("agentide"),a=`${i}/${u}`,p=o.get("storeRepo",""),D=o.get("store.indexUrl",""),k=`https://${i}.github.io/${u}`;let y="";if(p){const f=p.match(/^(?:https?:\/\/github\.com\/)?([^/]+)\/([^/]+?)(?:\.git)?$/);f&&(y=`https://${f[1]}.github.io/${f[2]}`)}await o.update("storeRepo",a,vscode.ConfigurationTarget.Global),(!D||y&&D===y)&&await o.update("store.indexUrl",k,vscode.ConfigurationTarget.Global);const $=await vscode.window.showInformationMessage(`\u{1F99B} ${d.message}`,"Open Pull Request","Copy URL");$==="Open Pull Request"?await vscode.env.openExternal(vscode.Uri.parse(d.pullRequestUrl)):$==="Copy URL"&&(await vscode.env.clipboard.writeText(d.pullRequestUrl),showInfo("Pull request URL copied to clipboard"))}else d.success||showError(`Setup failed: ${d.message}`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.storeInstall",async n=>{const{workspaceRoot:s}=getWorkspaceRoot(e),{downloadFromStore:c,listStoreVersions:i}=await import("./store/index.js"),{getAgentRoot:l}=await import("./agentpack/paths.js"),u=n||{type:"pack",slug:"",version:void 0};if(!u.version){const y=await i("pack",u.slug);if(y.length===0)u.version="main";else{const $=await vscode.window.showQuickPick(y.map(f=>({label:f.version,description:f.isPrerelease?"(pre-release)":""})),{placeHolder:"Select version to install"});if(!$)return;u.version=$.label}}const d=l(s,u.slug);if(await fs_1.promises.access(d).then(()=>!0).catch(()=>!1)){if(await vscode.window.showWarningMessage(`Pack "${u.slug}" already exists. Overwrite?`,{modal:!0},"Overwrite","Cancel")!=="Overwrite")return;await fs_1.promises.rm(d,{recursive:!0,force:!0})}await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Installing pack "${u.slug}"`,cancellable:!1},async y=>{y.report({message:"Downloading from store..."});const $=await c({type:"pack",slug:u.slug,version:u.version},e);y.report({message:"Extracting files..."}),await fs_1.promises.mkdir(d,{recursive:!0});for(const f of $){const w=path.join(d,f.path);await fs_1.promises.mkdir(path.dirname(w),{recursive:!0}),await fs_1.promises.writeFile(w,f.content)}}),await vscode.commands.executeCommand("agentide.packsChanged");const{getRegistry:a}=await import("./registry/index.js");await a(e).registerPack({slug:u.slug,displayName:u.slug,latestVersion:u.version||"main",tags:[],stats:{installs:1,stars:0}});const{invalidateLocalIndex:D}=await import("./store/oramaIndex.js");D(),await vscode.window.showInformationMessage(`Installed pack "${u.slug}" v${u.version}`,"Activate")==="Activate"&&await vscode.commands.executeCommand("agentide.pack.switch",u.slug)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.skill.install",async n=>{const{workspaceRoot:s}=getWorkspaceRoot(e),{downloadFromStore:c,downloadFromExternalGitHub:i,listStoreVersions:l,isStoreUrl:u,parseGitHubUrl:d}=await import("./store/index.js"),{AgentPackManager:o}=await import("./agentpack/index.js"),a=new o(m,()=>s,()=>E.storagePath,e);let p=n;if(!p){const b=await vscode.window.showInputBox({prompt:"Enter skill store URL or GitHub URL",placeHolder:"e.g., skills/typescript-testing@v1.0.0 or https://github.com/user/repo"});if(!b)return;const{parseStoreUrl:v}=await import("./store/index.js");p=v(b)}const D=p.sourceUrl&&!u(p.sourceUrl);if(!p.version&&!D){const b=await l("skill",p.slug);if(b.length===0)p.version="main";else{const v=await vscode.window.showQuickPick(b.map(N=>({label:N.version,description:N.isPrerelease?"(pre-release)":""})),{placeHolder:"Select version to install"});if(!v)return;p.version=v.label}}const k=await a.listInstalledWithCleanup();if(k.length===0){showError(`${branding_1.AGENTIDE_BRAND_NAME}: No agents found. Create an agent first.`);return}const y=await vscode.window.showQuickPick(k.map(b=>({label:b.id,description:`v${b.version}`})),{placeHolder:"Select agent to install skill to"});if(!y)return;const{getAgentRoot:$}=await import("./agentpack/paths.js"),f=$(s,y.label),w=path.join(f,"skills",p.slug);if(await fs_1.promises.access(w).then(()=>!0).catch(()=>!1)){if(await vscode.window.showWarningMessage(`Skill "${p.slug}" already exists in ${y.label}. Overwrite?`,{modal:!0},"Overwrite","Cancel")!=="Overwrite")return;await fs_1.promises.rm(w,{recursive:!0,force:!0})}await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Installing skill "${p.slug}"`,cancellable:!1},async b=>{let v;if(D&&p.sourceUrl){b.report({message:"Downloading from GitHub..."});const N=d(p.sourceUrl);v=await i({owner:N.owner,repo:N.repo,ref:N.ref||"main",path:N.path},e)}else b.report({message:"Downloading from store..."}),v=await c({type:"skill",slug:p.slug,version:p.version},e);b.report({message:"Extracting files..."}),await fs_1.promises.mkdir(w,{recursive:!0});for(const N of v){const R=path.join(w,N.path);await fs_1.promises.mkdir(path.dirname(R),{recursive:!0}),await fs_1.promises.writeFile(R,N.content)}});const{getRegistry:g}=await import("./registry/index.js");await g(e).registerSkill({slug:p.slug,displayName:p.slug,latestVersion:p.version||"main",tags:[],stats:{installs:1},agentPackId:y.label});const{invalidateLocalIndex:M}=await import("./store/oramaIndex.js");M(),showInfo(`Installed skill "${p.slug}" to ${y.label}`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.mcp.install",async n=>{const{workspaceRoot:s}=getWorkspaceRoot(e),{downloadFromStore:c,listStoreVersions:i}=await import("./store/index.js"),{AgentPackManager:l}=await import("./agentpack/index.js"),u=new l(m,()=>s,()=>E.storagePath,e);let d=n;if(!d){const y=await vscode.window.showInputBox({prompt:"Enter MCP store URL",placeHolder:"e.g., mcp/github@v1.0.0"});if(!y)return;const{parseStoreUrl:$}=await import("./store/index.js");d=$(y)}if(!d.version){const y=await i("mcp",d.slug);if(y.length===0)d.version="main";else{const $=await vscode.window.showQuickPick(y.map(f=>({label:f.version,description:f.isPrerelease?"(pre-release)":""})),{placeHolder:"Select version to install"});if(!$)return;d.version=$.label}}const o=await u.listInstalledWithCleanup();if(o.length===0){showError(`${branding_1.AGENTIDE_BRAND_NAME}: No agents found. Create an agent first.`);return}const a=await vscode.window.showQuickPick(o.map(y=>({label:y.id,description:`v${y.version}`})),{placeHolder:"Select agent to add MCP server to"});if(!a)return;await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Installing MCP "${d.slug}"`,cancellable:!1},async y=>{y.report({message:"Downloading from store..."});const $=await c({type:"mcp",slug:d.slug,version:d.version},e);y.report({message:"Merging MCP config..."});const f=$.find(v=>v.path==="mcp.json"||v.path.endsWith("/mcp.json"));if(!f)throw new Error("Downloaded MCP package missing mcp.json");const w=JSON.parse(f.content.toString()),{getAgentRoot:I}=await import("./agentpack/paths.js"),g=I(s,a.label),S=path.join(g,"mcp"),M=path.join(S,".mcp.json");await fs_1.promises.mkdir(S,{recursive:!0});let b={mcpServers:{}};try{const v=await fs_1.promises.readFile(M,"utf-8");b=JSON.parse(v),b.mcpServers||(b.mcpServers={})}catch{}b.mcpServers[d.slug]={transport:w.transport||"stdio",command:w.command,args:w.args,env:w.env,url:w.url,npmPackage:w.npmPackage,_version:d.version,_description:w.description},await fs_1.promises.writeFile(M,JSON.stringify(b,null,2));for(const v of $)if(v.path!=="mcp.json"&&!v.path.endsWith("/mcp.json")){const N=path.join(S,d.slug,v.path);await fs_1.promises.mkdir(path.dirname(N),{recursive:!0}),await fs_1.promises.writeFile(N,v.content)}});const{getRegistry:p}=await import("./registry/index.js");await p(e).registerMcp({slug:d.slug,displayName:d.slug,transport:"stdio",latestVersion:d.version||"main",tags:[],stats:{installs:1},agentPackId:a.label});const{invalidateLocalIndex:k}=await import("./store/oramaIndex.js");k(),showInfo(`Installed MCP "${d.slug}" v${d.version} to ${a.label}`)})),t.subscriptions.push(vscode.commands.registerCommand("agentide.engine.install",async n=>{const{downloadFromStore:s,downloadFromExternalGitHub:c,listStoreVersions:i,isStoreUrl:l,parseGitHubUrl:u,parseStoreUrl:d}=await import("./store/index.js"),{installCustomEngineFromFiles:o}=await import("./engines/install.js");let a=n;if(!a){const f=await vscode.window.showInputBox({prompt:"Enter custom engine store URL or GitHub URL",placeHolder:"e.g., engine/gemini or https://github.com/user/repo/tree/main/gemini"});if(!f)return;if(l(f))a=d(f);else{const w=u(f),I=(w.path||w.repo).split("/");a={type:"engine",slug:I[I.length-1]||w.repo,version:w.ref,sourceUrl:f}}}const p=a.sourceUrl&&!l(a.sourceUrl);if(!a.version&&!p){const f=await i("engine",a.slug);if(f.length===0)a.version="main";else{const w=await vscode.window.showQuickPick(f.map(I=>({label:I.version,description:I.isPrerelease?"(pre-release)":""})),{placeHolder:"Select version to install"});if(!w)return;a.version=w.label}}const D=async f=>await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Installing engine "${a.slug}"`,cancellable:!1},async w=>{let I;if(p&&a.sourceUrl){w.report({message:"Downloading from GitHub..."});const g=u(a.sourceUrl);I=await c({owner:g.owner,repo:g.repo,ref:g.ref||"main",path:g.path},e)}else w.report({message:"Downloading from store..."}),I=await s({type:"engine",slug:a.slug,version:a.version},e);return w.report({message:"Validating and installing..."}),await o(I,{slug:a.slug,version:a.version,sourceUrl:a.sourceUrl,overwrite:f,logger:e})});let k;try{k=await D(!1)}catch(f){const w=f instanceof Error?f.message:String(f);if(!w.includes("already exists")){log(e,`[AgentIDE] Engine install error: ${w}`),showError(`AgentIDE: ${w}`);return}if(await vscode.window.showWarningMessage(w,{modal:!0},"Overwrite","Cancel")!=="Overwrite")return;try{k=await D(!0)}catch(g){const S=g instanceof Error?g.message:String(g);log(e,`[AgentIDE] Engine install error: ${S}`),showError(`AgentIDE: ${S}`);return}}const{invalidateLocalIndex:y}=await import("./store/oramaIndex.js");if(y(),!k)return;clearCustomEngineRuntimeCache(r,k.id),await refreshCustomEnginePicker(e),await vscode.window.showInformationMessage(`Installed engine "${k.displayName}"`,"List Engines")==="List Engines"&&await vscode.commands.executeCommand("agentide.customEngine.list")})),t.subscriptions.push(vscode.commands.registerCommand("agentide.view.install",async n=>{const{workspaceRoot:s}=getWorkspaceRoot(e),{downloadFromStore:c,downloadFromExternalGitHub:i,listStoreVersions:l,isStoreUrl:u,parseGitHubUrl:d,parseStoreUrl:o}=await import("./store/index.js"),{installSpotlightViewFromFiles:a}=await import("./spotlight/install.js");let p=n;if(!p){const I=await vscode.window.showInputBox({prompt:"Enter Spotlight view store URL or GitHub URL",placeHolder:"e.g., view/cost-ops or https://github.com/user/repo/tree/main/spotlight/cost-ops"});if(!I)return;if(u(I))p=o(I);else{const g=d(I),S=(g.path||g.repo).split("/");p={type:"view",slug:S[S.length-1]||g.repo,version:g.ref,sourceUrl:I}}}const D=p.sourceUrl&&!u(p.sourceUrl);if(!p.version&&!D){const I=await l("view",p.slug);if(I.length===0)p.version="main";else{const g=await vscode.window.showQuickPick(I.map(S=>({label:S.version,description:S.isPrerelease?"(pre-release)":""})),{placeHolder:"Select version to install"});if(!g)return;p.version=g.label}}const k=async(I,g)=>await vscode.window.withProgress({location:vscode.ProgressLocation.Window,title:`Installing Spotlight view "${p.slug}"`,cancellable:!1},async S=>{let M;if(D&&p.sourceUrl){S.report({message:"Downloading from GitHub..."});const b=d(p.sourceUrl);M=(await i({owner:b.owner,repo:b.repo,ref:b.ref||"main",path:b.path},e)).map(N=>({path:N.path,content:N.content}))}else S.report({message:"Downloading from store..."}),M=await c({type:"view",slug:p.slug,version:p.version},e);return S.report({message:"Installing view..."}),await a(M,{slug:p.slug,version:p.version,overwrite:I,activate:g,workspaceRoot:s,logger:e})});let y;try{y=await k(!1,!1)}catch(I){const g=I instanceof Error?I.message:String(I);if(!g.includes("already exists")){log(e,`[AgentIDE] Spotlight view install error: ${g}`),showError(`AgentIDE: ${g}`);return}if(await vscode.window.showWarningMessage(g,{modal:!0},"Overwrite","Cancel")!=="Overwrite")return;try{y=await k(!0,!1)}catch(M){const b=M instanceof Error?M.message:String(M);log(e,`[AgentIDE] Spotlight view install error: ${b}`),showError(`AgentIDE: ${b}`);return}}const{invalidateLocalIndex:$}=await import("./store/oramaIndex.js");if($(),!y)return;const f=_state?.analyticsDashboard;f&&await f.refreshViewsFromDisk();const w=await vscode.window.showInformationMessage(`Installed Spotlight view "${y.id}" v${y.version||p.version||"main"}`,"Open Spotlight","Activate View");if(w==="Open Spotlight")await vscode.commands.executeCommand("agentide.analytics.openDashboard");else if(w==="Activate View"){const{setActiveSpotlightView:I}=await import("./spotlight/install.js");await I(y.viewsConfigPath,y.id);const g=_state?.analyticsDashboard;g&&await g.refreshViewsFromDisk(),await vscode.commands.executeCommand("agentide.analytics.openDashboard")}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.update",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),c=new s(m,()=>n,()=>E.storagePath,e),i=await c.listInstalledWithCleanup(),l=[];for(const a of i){if(a.id==="default")continue;const p=await c.checkAgentUpdate(a.id);p&&l.push({id:a.id,version:a.version,newVersion:p})}if(l.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: All agents are up to date`);return}const u=l.map(a=>({label:a.id,description:`v${a.version} \u2192 v${a.newVersion}`})),d=await vscode.window.showQuickPick(u,{placeHolder:"Select an agent to update",title:"Update Agent from User Library"});if(!(!d||await vscode.window.showWarningMessage(`Update "${d.label}" from User Library? Current version will be backed up.`,{modal:!0},"Update","Cancel")!=="Update"))try{const a=await c.updateFromLibrary(d.label);showInfo(`AgentIDE: Updated "${d.label}" to v${a}`)}catch(a){const p=a instanceof Error?a.message:String(a);log(e,`[AgentIDE] Update error: ${p}`),showError(`AgentIDE: ${p}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.duplicate",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),c=new s(m,()=>n,()=>E.storagePath,e),i=await c.listInstalledWithCleanup();if(i.length===0){showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No agents to duplicate`);return}const l=i.map(d=>({label:d.id,description:`v${d.version}`})),u=await vscode.window.showQuickPick(l,{placeHolder:"Select an agent to duplicate",title:"Duplicate Agent"});if(u)try{const d=await c.duplicate(u.label);showInfo(`AgentIDE: Created "${d}" as copy of "${u.label}"`);const o=path.join((0,paths_1.getAgentideDir)(n),paths_1.AGENT_CONSTANTS.AGENTS_DIR,d,paths_1.AGENT_CONSTANTS.AGENTS_MD);if(await(0,utils_1.pathExists)(o)){const a=await vscode.workspace.openTextDocument(o);await vscode.window.showTextDocument(a)}}catch(d){const o=d instanceof Error?d.message:String(d);log(e,`[AgentIDE] Duplicate error: ${o}`),showError(`AgentIDE: ${o}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.refresh",async()=>{const{workspaceRoot:n}=getWorkspaceRoot(e),{AgentPackManager:s}=await import("./agentpack/index.js"),c=new s(m,()=>n,()=>E.storagePath,e);try{const{registered:i}=await c.repairUnregisteredAgents();return i.length>0?showInfo(`AgentIDE: Discovered ${i.length} new pack(s): ${i.join(", ")}`):showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: No new packs found`),{registered:i}}catch(i){const l=i instanceof Error?i.message:String(i);return log(e,`[AgentIDE] Pack refresh error: ${l}`),showError(`AgentIDE: ${l}`),{registered:[]}}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.pack.resetDefault",async()=>{if(await vscode.window.showWarningMessage("Reset the default agent? This will restore it from bundled templates. Current default agent will be backed up.",{modal:!0},"Reset","Cancel")!=="Reset")return;const{workspaceRoot:s}=getWorkspaceRoot(e),{AgentPackManager:c}=await import("./agentpack/index.js"),i=new c(m,()=>s,()=>E.storagePath,e);try{await i.resetDefault(getBundledBasePromptsDir()),showInfo(`${branding_1.AGENTIDE_BRAND_NAME}: Default agent reset from bundled templates`),await m.flushAgentideRootUpdate(s,e,{force:!0,allowDuringActiveTurn:!0})}catch(l){const u=l instanceof Error?l.message:String(l);log(e,`[AgentIDE] Reset error: ${u}`),showError(`AgentIDE: ${u}`)}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.chat",async n=>handleChatCommand(r,n))),t.subscriptions.push(vscode.commands.registerCommand("agentide.chat.cancel",async n=>{const s=n?.streamId;if(!s)return{cancelled:!1,error:"streamId is required"};const c=_activeRunsByStreamId.get(s);if(!c)return log(e,`[AgentIDE] Cancel ignored: no active run for streamId=${s}`),rejectPendingQuestionsForStream(s,"Run cancelled"),{cancelled:!1};log(e,`[AgentIDE] Cancel requested: streamId=${s}, engine=${c.engine}, ageMs=${Date.now()-c.startedAt}`);try{c.abortController.abort()}catch{}return rejectPendingQuestionsForStream(s,"Run cancelled"),{cancelled:!0}})),t.subscriptions.push(vscode.commands.registerCommand("agentide.chat.answerQuestion",async n=>{const s=n?.streamId,c=n?.questionId;if(!s||!c)return{ok:!1,error:"streamId and questionId are required"};const i=_pendingQuestionsById.get(c);if(!i||i.streamId!==s)return{ok:!1,error:"Question not found or already resolved"};const l=normalizeQuestionAnswer(n?.answer);return resolvePendingQuestion(c,l),{ok:!0}}))}function getUserPermissions(){return{fileAccess:vscode.workspace.getConfiguration("agentide").get("permissions.fileAccess","full")}}function getConfiguredAdditionalEngineDir(){return vscode.workspace.getConfiguration("agentide").get("additionalEngineDir")}function clearCustomEngineRuntimeCache(t,r){const e=t.engines.custom;try{e?.clearInstances?.(r)}catch(m){log(t.outputChannel,`[AgentIDE] Custom engine cache clear warning: ${m instanceof Error?m.message:String(m)}`)}}async function refreshCustomEnginePicker(t){try{await vscode.commands.executeCommand("agentide.engine.refresh")}catch(r){log(t,`[AgentIDE] Custom engine picker refresh warning: ${r instanceof Error?r.message:String(r)}`)}}const _sessionEventWriter=new sessionEvents_1.SessionEventWriter;async function handleChatCommand(t,r){const{outputChannel:e,engines:m,syncService:E,config:h}=t,{engine:C,streamId:A}=r;let{message:T}=r;const n=r.options??{};let s;const c=T.match(/^\[gw:(gw-[^\]]+)\]/);if(c){const P=c[1];T=T.slice(c[0].length),log(e,`[AgentIDE] Gateway request detected, token=${P.slice(0,20)}...`);const{GatewayService:_}=await import("./gateway/service.js");s=_.getGatewayEmitter(P),s?log(e,"[AgentIDE] Gateway emitter found, will stream to both Chat UI and Gateway"):log(e,`[AgentIDE] Gateway emitter NOT found for token ${P.slice(0,20)}...`)}const{workspaceRoot:i,additionalDirectories:l,isHomeFallback:u}=getWorkspaceRoot(e,n.workspaceRoot,n.additionalDirectories);A&&u&&await warnHomeFallbackOnce(e,A);const d=await E.getActiveAgentManifest(i,e,E.getActivePackId(i)??t.activePackId),o=d?.spec?.remote?.url?.trim();if(o)return(0,handleRemoteChat_js_1.handleRemoteServeChat)({outputChannel:e,syncService:E,sessionEventWriter:_sessionEventWriter,activeRunsByStreamId:_activeRunsByStreamId,rejectPendingQuestionsForStream,askQuestionViaWorkbenchTool,askQuestionFromChatUI,getServeAuth:async()=>{if(!_extensionContext)return;const P=await(0,provider_js_1.getAgentHippoAccessToken)(_extensionContext);if(P)return{accessToken:P.accessToken,userEmail:P.email}},ensureSignedIn:async()=>{if(!_extensionContext)return;const P=await(0,signInFlow_js_1.ensureAgentHippoSignedIn)(_extensionContext);if(P)return{accessToken:P.accessToken,userEmail:P.email}},log},{engine:C,message:T,options:r.options,streamId:A,sessionResource:r.sessionResource,requestId:r.requestId,remoteUrl:o,remoteManifest:d,workspaceRoot:i,incomingOptions:n,gatewayEmitter:s});let a={...n,workspaceRoot:i,additionalDirectories:l,agentPackId:t.activePackId};if(!A)return{error:"streamId is required - non-streaming mode is no longer supported"};let p=C,D=m[p];if(!D&&p!=="codex"&&p!=="claude"&&m.custom&&(a={...a,engineId:a.engineId??p},p="custom",D=m.custom,log(e,`[AgentIDE] Routing requested engine "${C}" through custom runtime loader`)),!D){const P=`Unknown engine: ${C}`;return log(e,`[AgentIDE] Error: ${P}`),{error:P}}log(e,`[AgentIDE] Chat request for engine=${C} (runtime=${p}), streamId: ${A}, useLiteLLM: ${a.useLiteLLM||!1}`);const k=new AbortController;_activeRunsByStreamId.set(A,{streamId:A,engine:p,startedAt:Date.now(),abortController:k});const y=(0,utils_1.createIPCStreamEmitter)(A),$=r.sessionResource,f=r.requestId,w={...y,async question(P){return $?await askQuestionViaWorkbenchTool($,f,P,k.signal):await askQuestionFromChatUI(A,P)}},I=s?{...w,async thinking(P){await y.thinking(P),await s.thinking(`<thinking>${P}</thinking>`)},async text(P){await y.text(P),await s.text(P)},async toolStart(P,_,L,x){await y.toolStart(P,_,L,x),await s.toolStart(P,_,L,x)},async toolEnd(P,_,L,x,U){await y.toolEnd(P,_,L,x,U),await s.toolEnd(P,_,L,x,U)},async progress(P){await y.progress(P),await s.progress(P)},async question(P){const _=await w.question(P);return await s.progress(`Question answered: ${questionPromptToHeader(P.prompt)}`),_},async error(P){await y.error(P),await s.error(P)},async done(){await y.done(),await s.done()}}:w,g=getTerminalLogInfo(a);await appendTerminalAttachmentsToLog(r.context,A,e,g?.uri),await persistImageAttachments(r.context,a,e),await persistFileAndDirectoryAttachments(r.context,a,e);const S=formatSdkContextSuffix(r.context,g?.relativePath),M=S?`${T}
23
23
 
24
- ${D}`:T,b=(0,base_1.generateRequestId)(),v=a.sessionId??`ide-${Date.now()}`,N=(0,sessionEvents_1.wrapEmitterWithObservability)(I,_sessionEventWriter,v,b);let R=null;try{E.incrementActiveAgentTurns(),await E.ensureAgentideProjectPrepared(i,l,e),await E.writeManagedPathsManifest(h.codexHome,h.claudeConfigDir,i,l,e);const P=await E.getActiveAgentManifest(i,e),_=(0,permissions_1.parseManifestPermissions)(P),L=getUserPermissions(),x=(0,permissions_1.enforcePermissions)(_,L);log(e,`[AgentIDE] Permissions: manifest(files=${_.fileAccess}) + user(files=${L.fileAccess}) = effective(files=${x.fileAccess})`);const U={...a,sessionId:v,permissions:x,agentPackVersion:P?.metadata?.version,requestId:b},O=new vscode_logger_1.VSCodeLogger(e),B=new permission_handler_1.AutoApprovePermissionHandler,W=vscode.workspace.getConfiguration("agentide").get("cli.path",""),F=await(0,runtime_1.getCliHealth)({configuredPath:W,extensionPath:_extensionContext?.extensionPath}),q=_extensionContext?.globalState?.get(BUNDLED_TOOLS_DIR_KEY),G=(0,runtime_1.buildCliEnvPatch)({cliPath:F.path,workspaceRoot:i,agentId:U.agentPackId??"default",chatSessionId:U.sessionId?.trim()||U.contextSessionId?.trim(),baseEnv:process.env,extensionPath:_extensionContext?.extensionPath,userInstalledToolsDir:q??void 0});G.AGENTHIPPO_TOOLS_DIR&&log(e,`[AgentIDE] Bundled tools dir available for runtime: ${G.AGENTHIPPO_TOOLS_DIR}`);{const j=E.getActiveAgentContext(i),H=await getIdeTurnScope(i,j.agentId,j.agentRoot,P,e);H&&(R=await H.beginTurn({sessionKey:v}),Object.assign(G,R.env))}const V={logger:O,editTracker:new vscode_edit_tracker_1.VSCodeEditTracker(new vscode_logger_1.VSCodeLogger(e,"[EditTracker]")),configProvider:new vscode_config_provider_1.VSCodeConfigProvider(P?.spec?.effort),permissionHandler:B,cliEnvPatch:G};return F.installed&&F.path?log(e,`[AgentIDE] CLI available for agent runtime: ${F.path}`):log(e,`[AgentIDE] CLI not detected for runtime (skills may rely on '${branding_1.AGENTIDE_CLI_NAME}' on PATH)`),log(e,`[AgentIDE] Analytics: session=${v}, request=${b}, agent=${U.agentPackId??"default"}, version=${U.agentPackVersion??"workspace"}`),await N.emitTurnStart(),await S.stream(M,U,N,V,k.signal),await N.emitTurnEnd(!0),{streaming:!0}}catch(P){const _=P instanceof Error?P.message:String(P);return log(e,`[AgentIDE] Error: ${_}`),await N.error(_),await N.emitTurnEnd(!1),{error:_}}finally{try{await R?.release()}catch{}rejectPendingQuestionsForStream(A,"Run finished"),_activeRunsByStreamId.delete(A),E.decrementActiveAgentTurns()}}function resolveWorkspaceRootUri(t){const r=vscode.workspace.workspaceFolders??[],e=r.find(E=>E.uri.fsPath===t);if(e)return e.uri;const m=r[0];return m&&t.startsWith("/")?vscode.Uri.from({scheme:m.uri.scheme,authority:m.uri.authority,path:t}):vscode.Uri.file(t)}function dirnameUri(t){const r=t.path.lastIndexOf("/");return r>=0?t.with({path:t.path.slice(0,r)}):t}function getTerminalLogInfo(t){const r=t.contextSessionId?.trim()||t.sessionId?.trim();if(!r)return;const e=resolveWorkspaceRootUri(t.workspaceRoot);return{uri:vscode.Uri.joinPath(e,paths_1.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,paths_1.AGENT_CONSTANTS.SESSIONS_DIR,r,TERMINAL_LOG_FILE_NAME),relativePath:`${AGENTIDE_SESSIONS_DIR_NAME}/${r}/${TERMINAL_LOG_FILE_NAME}`}}function getSessionAttachmentsDirInfo(t){const r=t.contextSessionId?.trim()||t.sessionId?.trim();if(!r)return;const e=resolveWorkspaceRootUri(t.workspaceRoot);return{dirUri:vscode.Uri.joinPath(e,paths_1.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,paths_1.AGENT_CONSTANTS.SESSIONS_DIR,r,ATTACHMENTS_DIR_NAME),relativeDirPath:`${AGENTIDE_SESSIONS_DIR_NAME}/${r}/${ATTACHMENTS_DIR_NAME}`}}function slugifyFileStem(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"attachment"}function imageExtensionFromMimeType(t){switch((t??"").toLowerCase()){case"image/png":return"png";case"image/jpeg":case"image/jpg":return"jpg";case"image/gif":return"gif";case"image/webp":return"webp";default:return"png"}}async function persistImageAttachments(t,r,e){const m=t?.variables??[];if(!t||m.length===0)return;const E=m.filter(A=>A.kind==="image"&&typeof A.dataBase64=="string"&&A.dataBase64.length>0);if(E.length===0)return;const h=getSessionAttachmentsDirInfo(r);if(!h){log(e,"[AgentIDE] Note: image attachment present but no contextSessionId; skipping persistence");return}try{await(0,terminalLogger_1.ensureDirectory)(h.dirUri)}catch(A){log(e,`[AgentIDE] Warning: failed to create session attachments dir: ${A instanceof Error?A.message:String(A)}`);return}let C=0;for(const A of E){C++;const T=slugifyFileStem(A.name||`image-${C}`),n=imageExtensionFromMimeType(A.mimeType),s=E.length>1?`${T}-${C}.${n}`:`${T}.${n}`,c=vscode.Uri.joinPath(h.dirUri,s);try{const i=Buffer.from(A.dataBase64,"base64");await vscode.workspace.fs.writeFile(c,i),A.uri=`${h.relativeDirPath}/${s}`,delete A.dataBase64}catch(i){log(e,`[AgentIDE] Warning: failed to persist image attachment "${A.name}": ${i instanceof Error?i.message:String(i)}`)}}}async function persistFileAndDirectoryAttachments(t,r,e){const m=t?.variables??[];if(!t||m.length===0)return;const E=m.filter(f=>(f.kind==="file"||f.kind==="directory")&&typeof f.uri=="string"&&f.uri.trim().length>0);if(E.length===0)return;const h=getSessionAttachmentsDirInfo(r);if(!h){log(e,"[AgentIDE] Note: file/folder attachment present but no contextSessionId; skipping persistence");return}try{await(0,terminalLogger_1.ensureDirectory)(h.dirUri)}catch(f){log(e,`[AgentIDE] Warning: failed to create session attachments dir: ${f instanceof Error?f.message:String(f)}`);return}const C=vscode.Uri.joinPath(h.dirUri,"manifest.json"),A=async()=>{try{const f=await vscode.workspace.fs.readFile(C),w=JSON.parse(Buffer.from(f).toString("utf8"));if(w&&w.version===1&&typeof w.files=="object"&&typeof w.directories=="object")return w}catch{}return{version:1,files:{},directories:{}}},T=async f=>{try{const w=Buffer.from(JSON.stringify(f,null,2),"utf8");await vscode.workspace.fs.writeFile(C,w)}catch{}},n=await A();let s=!1;const c=500,i=25*1024*1024,l=10*1024*1024;let u=0,d=0;const o=(f,w)=>{try{const I=path.resolve(f),g=path.resolve(w),D=path.relative(I,g);return D===""||!D.startsWith("..")&&!path.isAbsolute(D)}catch{return!1}},a=r.workspaceRoot,p=path.normalize(`${path.sep}${AGENTIDE_SESSIONS_DIR_NAME.split("/").join(path.sep)}${path.sep}`),S=async f=>{try{return await vscode.workspace.fs.stat(f),!0}catch{return!1}},k=async(f,w)=>{let I=w,g=1;for(;await S(vscode.Uri.joinPath(f,I));){g++;const D=path.extname(w);I=`${D?w.slice(0,-D.length):w}-${g}${D}`}return I},y=async(f,w)=>{const I=vscode.Uri.file(f);try{const g=await vscode.workspace.fs.stat(I);if(g.type!==vscode.FileType.File)return;const D=`${f}::${g.size}::${g.mtime}`,M=n.files[D];if(M){const P=vscode.Uri.joinPath(w,M.destName);if(await S(P))return M.destName}const b=path.basename(f),v=await k(w,b||"attachment"),N=vscode.Uri.joinPath(w,v);if(g.size>l){log(e,`[AgentIDE] Note: skipping large file attachment (${g.size} bytes): ${f}`);return}if(u+1>c||d+g.size>i){log(e,"[AgentIDE] Note: skipping additional file attachments due to size limits");return}const R=await vscode.workspace.fs.readFile(I);return await vscode.workspace.fs.writeFile(N,R),u+=1,d+=g.size,n.files[D]={destName:v,sourcePath:f,size:g.size,mtime:g.mtime},s=!0,v}catch(g){log(e,`[AgentIDE] Warning: failed to persist file attachment "${f}": ${g instanceof Error?g.message:String(g)}`);return}},$=async(f,w)=>{const I=await vscode.workspace.fs.readDirectory(f);for(const[g,D]of I){if(u>=c||d>=i)return;const M=vscode.Uri.joinPath(f,g),b=vscode.Uri.joinPath(w,g);if(D===vscode.FileType.Directory)await(0,terminalLogger_1.ensureDirectory)(b),await $(M,b);else if(D===vscode.FileType.File)try{const v=await vscode.workspace.fs.stat(M);if(v.size>l)continue;if(u+1>c||d+v.size>i)return;const N=await vscode.workspace.fs.readFile(M);await vscode.workspace.fs.writeFile(b,N),u+=1,d+=v.size}catch{}}};for(const f of E){const w=f.uri.trim();if(path.isAbsolute(w)&&!(a&&o(a,w))&&!path.normalize(w).includes(p))try{const I=vscode.Uri.file(w),g=await vscode.workspace.fs.stat(I);if(g.type===vscode.FileType.Directory&&f.kind==="directory"){const D=`${w}::${g.mtime}`,M=n.directories[D];if(M){const R=vscode.Uri.joinPath(h.dirUri,M.destName);if(await S(R)){f.uri=`${h.relativeDirPath}/${M.destName}`;continue}}const b=path.basename(w)||"folder",v=await k(h.dirUri,b),N=vscode.Uri.joinPath(h.dirUri,v);await(0,terminalLogger_1.ensureDirectory)(N),await $(I,N),n.directories[D]={destName:v,sourcePath:w,mtime:g.mtime},s=!0,f.uri=`${h.relativeDirPath}/${v}`}else if(g.type===vscode.FileType.File&&f.kind==="file"){const D=await y(w,h.dirUri);D&&(f.uri=`${h.relativeDirPath}/${D}`)}}catch{}}s&&await T(n)}async function appendTerminalAttachmentsToLog(t,r,e,m){if(!m)return;const E=t?.variables??[],h=E.filter(A=>A.kind==="terminalCommand"&&typeof A.output=="string"&&A.output.trim().length>0),C=E.filter(A=>A.kind==="generic"&&typeof A.text=="string"&&A.text.trim().length>0&&(A.isTerminalSelection||typeof A.id=="string"&&A.id.startsWith("terminal-selection-")));if(!(h.length===0&&C.length===0))try{await(0,terminalLogger_1.ensureDirectory)(dirnameUri(m));const A=new Date().toISOString(),T=[];T.push(`<!-- TERMINAL_ATTACHMENTS STREAM:${r} TIME:${A} -->`),T.push("");for(const n of h){const s=(n.command??n.name??"").toString().trim();T.push("## Terminal Command"),s&&T.push(`- Command: ${s}`),typeof n.exitCode=="number"&&T.push(`- Exit code: ${n.exitCode}`),n.uri&&T.push(`- Resource: ${n.uri}`),T.push(""),T.push("```text"),T.push(n.output??""),T.push("```"),T.push("")}for(const n of C){const s=n.name||"Terminal Selection";T.push(`## ${s}`),T.push(""),T.push("```text"),T.push(n.text??""),T.push("```"),T.push("")}T.push(`<!-- TERMINAL_ATTACHMENTS_END STREAM:${r} -->`),T.push(""),await(0,terminalLogger_1.appendTextFileWithRotation)(m,T.join(`
24
+ ${S}`:T,b=(0,base_1.generateRequestId)(),v=a.sessionId??`ide-${Date.now()}`,N=(0,sessionEvents_1.wrapEmitterWithObservability)(I,_sessionEventWriter,v,b);let R=null;try{E.incrementActiveAgentTurns(),await E.ensureAgentideProjectPrepared(i,l,e),await E.writeManagedPathsManifest(h.codexHome,h.claudeConfigDir,i,l,e);const P=await E.getActiveAgentManifest(i,e),_=(0,permissions_1.parseManifestPermissions)(P),L=getUserPermissions(),x=(0,permissions_1.enforcePermissions)(_,L);log(e,`[AgentIDE] Permissions: manifest(files=${_.fileAccess}) + user(files=${L.fileAccess}) = effective(files=${x.fileAccess})`);const U={...a,sessionId:v,permissions:x,agentPackVersion:P?.metadata?.version,requestId:b},O=new vscode_logger_1.VSCodeLogger(e),B=new permission_handler_1.AutoApprovePermissionHandler,W=vscode.workspace.getConfiguration("agentide").get("cli.path",""),F=await(0,runtime_1.getCliHealth)({configuredPath:W,extensionPath:_extensionContext?.extensionPath}),q=_extensionContext?.globalState?.get(BUNDLED_TOOLS_DIR_KEY),G=(0,runtime_1.buildCliEnvPatch)({cliPath:F.path,workspaceRoot:i,agentId:U.agentPackId??"default",chatSessionId:U.sessionId?.trim()||U.contextSessionId?.trim(),baseEnv:process.env,extensionPath:_extensionContext?.extensionPath,userInstalledToolsDir:q??void 0});G.AGENTHIPPO_TOOLS_DIR&&log(e,`[AgentIDE] Bundled tools dir available for runtime: ${G.AGENTHIPPO_TOOLS_DIR}`);{const j=E.getActiveAgentContext(i),H=await getIdeTurnScope(i,j.agentId,j.agentRoot,P,e);H&&(R=await H.beginTurn({sessionKey:v}),Object.assign(G,R.env))}const V={logger:O,editTracker:new vscode_edit_tracker_1.VSCodeEditTracker(new vscode_logger_1.VSCodeLogger(e,"[EditTracker]")),configProvider:new vscode_config_provider_1.VSCodeConfigProvider(P?.spec?.effort),permissionHandler:B,cliEnvPatch:G};return F.installed&&F.path?log(e,`[AgentIDE] CLI available for agent runtime: ${F.path}`):log(e,`[AgentIDE] CLI not detected for runtime (skills may rely on '${branding_1.AGENTIDE_CLI_NAME}' on PATH)`),log(e,`[AgentIDE] Analytics: session=${v}, request=${b}, agent=${U.agentPackId??"default"}, version=${U.agentPackVersion??"workspace"}`),await N.emitTurnStart(),await D.stream(M,U,N,V,k.signal),await N.emitTurnEnd(!0),{streaming:!0}}catch(P){const _=P instanceof Error?P.message:String(P);return log(e,`[AgentIDE] Error: ${_}`),await N.error(_),await N.emitTurnEnd(!1),{error:_}}finally{try{await R?.release()}catch{}rejectPendingQuestionsForStream(A,"Run finished"),_activeRunsByStreamId.delete(A),E.decrementActiveAgentTurns()}}function resolveWorkspaceRootUri(t){const r=vscode.workspace.workspaceFolders??[],e=r.find(E=>E.uri.fsPath===t);if(e)return e.uri;const m=r[0];return m&&t.startsWith("/")?vscode.Uri.from({scheme:m.uri.scheme,authority:m.uri.authority,path:t}):vscode.Uri.file(t)}function dirnameUri(t){const r=t.path.lastIndexOf("/");return r>=0?t.with({path:t.path.slice(0,r)}):t}function getTerminalLogInfo(t){const r=t.contextSessionId?.trim()||t.sessionId?.trim();if(!r)return;const e=resolveWorkspaceRootUri(t.workspaceRoot);return{uri:vscode.Uri.joinPath(e,paths_1.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,paths_1.AGENT_CONSTANTS.SESSIONS_DIR,r,TERMINAL_LOG_FILE_NAME),relativePath:`${AGENTIDE_SESSIONS_DIR_NAME}/${r}/${TERMINAL_LOG_FILE_NAME}`}}function getSessionAttachmentsDirInfo(t){const r=t.contextSessionId?.trim()||t.sessionId?.trim();if(!r)return;const e=resolveWorkspaceRootUri(t.workspaceRoot);return{dirUri:vscode.Uri.joinPath(e,paths_1.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,paths_1.AGENT_CONSTANTS.SESSIONS_DIR,r,ATTACHMENTS_DIR_NAME),relativeDirPath:`${AGENTIDE_SESSIONS_DIR_NAME}/${r}/${ATTACHMENTS_DIR_NAME}`}}function slugifyFileStem(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"attachment"}function imageExtensionFromMimeType(t){switch((t??"").toLowerCase()){case"image/png":return"png";case"image/jpeg":case"image/jpg":return"jpg";case"image/gif":return"gif";case"image/webp":return"webp";default:return"png"}}async function persistImageAttachments(t,r,e){const m=t?.variables??[];if(!t||m.length===0)return;const E=m.filter(A=>A.kind==="image"&&typeof A.dataBase64=="string"&&A.dataBase64.length>0);if(E.length===0)return;const h=getSessionAttachmentsDirInfo(r);if(!h){log(e,"[AgentIDE] Note: image attachment present but no contextSessionId; skipping persistence");return}try{await(0,terminalLogger_1.ensureDirectory)(h.dirUri)}catch(A){log(e,`[AgentIDE] Warning: failed to create session attachments dir: ${A instanceof Error?A.message:String(A)}`);return}let C=0;for(const A of E){C++;const T=slugifyFileStem(A.name||`image-${C}`),n=imageExtensionFromMimeType(A.mimeType),s=E.length>1?`${T}-${C}.${n}`:`${T}.${n}`,c=vscode.Uri.joinPath(h.dirUri,s);try{const i=Buffer.from(A.dataBase64,"base64");await vscode.workspace.fs.writeFile(c,i),A.uri=`${h.relativeDirPath}/${s}`,delete A.dataBase64}catch(i){log(e,`[AgentIDE] Warning: failed to persist image attachment "${A.name}": ${i instanceof Error?i.message:String(i)}`)}}}async function persistFileAndDirectoryAttachments(t,r,e){const m=t?.variables??[];if(!t||m.length===0)return;const E=m.filter(f=>(f.kind==="file"||f.kind==="directory")&&typeof f.uri=="string"&&f.uri.trim().length>0);if(E.length===0)return;const h=getSessionAttachmentsDirInfo(r);if(!h){log(e,"[AgentIDE] Note: file/folder attachment present but no contextSessionId; skipping persistence");return}try{await(0,terminalLogger_1.ensureDirectory)(h.dirUri)}catch(f){log(e,`[AgentIDE] Warning: failed to create session attachments dir: ${f instanceof Error?f.message:String(f)}`);return}const C=vscode.Uri.joinPath(h.dirUri,"manifest.json"),A=async()=>{try{const f=await vscode.workspace.fs.readFile(C),w=JSON.parse(Buffer.from(f).toString("utf8"));if(w&&w.version===1&&typeof w.files=="object"&&typeof w.directories=="object")return w}catch{}return{version:1,files:{},directories:{}}},T=async f=>{try{const w=Buffer.from(JSON.stringify(f,null,2),"utf8");await vscode.workspace.fs.writeFile(C,w)}catch{}},n=await A();let s=!1;const c=500,i=25*1024*1024,l=10*1024*1024;let u=0,d=0;const o=(f,w)=>{try{const I=path.resolve(f),g=path.resolve(w),S=path.relative(I,g);return S===""||!S.startsWith("..")&&!path.isAbsolute(S)}catch{return!1}},a=r.workspaceRoot,p=path.normalize(`${path.sep}${AGENTIDE_SESSIONS_DIR_NAME.split("/").join(path.sep)}${path.sep}`),D=async f=>{try{return await vscode.workspace.fs.stat(f),!0}catch{return!1}},k=async(f,w)=>{let I=w,g=1;for(;await D(vscode.Uri.joinPath(f,I));){g++;const S=path.extname(w);I=`${S?w.slice(0,-S.length):w}-${g}${S}`}return I},y=async(f,w)=>{const I=vscode.Uri.file(f);try{const g=await vscode.workspace.fs.stat(I);if(g.type!==vscode.FileType.File)return;const S=`${f}::${g.size}::${g.mtime}`,M=n.files[S];if(M){const P=vscode.Uri.joinPath(w,M.destName);if(await D(P))return M.destName}const b=path.basename(f),v=await k(w,b||"attachment"),N=vscode.Uri.joinPath(w,v);if(g.size>l){log(e,`[AgentIDE] Note: skipping large file attachment (${g.size} bytes): ${f}`);return}if(u+1>c||d+g.size>i){log(e,"[AgentIDE] Note: skipping additional file attachments due to size limits");return}const R=await vscode.workspace.fs.readFile(I);return await vscode.workspace.fs.writeFile(N,R),u+=1,d+=g.size,n.files[S]={destName:v,sourcePath:f,size:g.size,mtime:g.mtime},s=!0,v}catch(g){log(e,`[AgentIDE] Warning: failed to persist file attachment "${f}": ${g instanceof Error?g.message:String(g)}`);return}},$=async(f,w)=>{const I=await vscode.workspace.fs.readDirectory(f);for(const[g,S]of I){if(u>=c||d>=i)return;const M=vscode.Uri.joinPath(f,g),b=vscode.Uri.joinPath(w,g);if(S===vscode.FileType.Directory)await(0,terminalLogger_1.ensureDirectory)(b),await $(M,b);else if(S===vscode.FileType.File)try{const v=await vscode.workspace.fs.stat(M);if(v.size>l)continue;if(u+1>c||d+v.size>i)return;const N=await vscode.workspace.fs.readFile(M);await vscode.workspace.fs.writeFile(b,N),u+=1,d+=v.size}catch{}}};for(const f of E){const w=f.uri.trim();if(path.isAbsolute(w)&&!(a&&o(a,w))&&!path.normalize(w).includes(p))try{const I=vscode.Uri.file(w),g=await vscode.workspace.fs.stat(I);if(g.type===vscode.FileType.Directory&&f.kind==="directory"){const S=`${w}::${g.mtime}`,M=n.directories[S];if(M){const R=vscode.Uri.joinPath(h.dirUri,M.destName);if(await D(R)){f.uri=`${h.relativeDirPath}/${M.destName}`;continue}}const b=path.basename(w)||"folder",v=await k(h.dirUri,b),N=vscode.Uri.joinPath(h.dirUri,v);await(0,terminalLogger_1.ensureDirectory)(N),await $(I,N),n.directories[S]={destName:v,sourcePath:w,mtime:g.mtime},s=!0,f.uri=`${h.relativeDirPath}/${v}`}else if(g.type===vscode.FileType.File&&f.kind==="file"){const S=await y(w,h.dirUri);S&&(f.uri=`${h.relativeDirPath}/${S}`)}}catch{}}s&&await T(n)}async function appendTerminalAttachmentsToLog(t,r,e,m){if(!m)return;const E=t?.variables??[],h=E.filter(A=>A.kind==="terminalCommand"&&typeof A.output=="string"&&A.output.trim().length>0),C=E.filter(A=>A.kind==="generic"&&typeof A.text=="string"&&A.text.trim().length>0&&(A.isTerminalSelection||typeof A.id=="string"&&A.id.startsWith("terminal-selection-")));if(!(h.length===0&&C.length===0))try{await(0,terminalLogger_1.ensureDirectory)(dirnameUri(m));const A=new Date().toISOString(),T=[];T.push(`<!-- TERMINAL_ATTACHMENTS STREAM:${r} TIME:${A} -->`),T.push("");for(const n of h){const s=(n.command??n.name??"").toString().trim();T.push("## Terminal Command"),s&&T.push(`- Command: ${s}`),typeof n.exitCode=="number"&&T.push(`- Exit code: ${n.exitCode}`),n.uri&&T.push(`- Resource: ${n.uri}`),T.push(""),T.push("```text"),T.push(n.output??""),T.push("```"),T.push("")}for(const n of C){const s=n.name||"Terminal Selection";T.push(`## ${s}`),T.push(""),T.push("```text"),T.push(n.text??""),T.push("```"),T.push("")}T.push(`<!-- TERMINAL_ATTACHMENTS_END STREAM:${r} -->`),T.push(""),await(0,terminalLogger_1.appendTextFileWithRotation)(m,T.join(`
25
25
  `),MAX_TERMINAL_LOG_BYTES)}catch(A){log(e,`[AgentIDE] Warning: failed to persist terminal attachments for grep: ${A instanceof Error?A.message:String(A)}`)}}function formatSdkContextSuffix(t,r){if(!t)return"";const e=[];if(t.selection?.text&&t.selection.text.trim()){const h=[];if(t.selection.uri&&h.push(`**File:** \`${t.selection.uri}\``),t.selection.range){const A=t.selection.range;h.push(`**Range:** ${A.startLineNumber}:${A.startColumn}-${A.endLineNumber}:${A.endColumn}`)}e.push("## Currently Selected Code"),h.length&&(e.push(h.join(`
26
26
  `)),e.push(""));const C=(t.selection.languageId??"").trim();e.push(`\`\`\`${C}`),e.push(t.selection.text),e.push("```")}const m=t.variables??[];if(m.length){e.push("## Attached Context");for(const h of m)switch(h.kind){case"terminalCommand":{const C=h.command?.trim()||h.name;if(e.push("### Terminal"),e.push(`**Command:** \`${C}\``),h.uri&&e.push(`**Resource:** \`${h.uri}\``),typeof h.exitCode=="number"&&e.push(`**Exit code:** ${h.exitCode}`),r)e.push(`**Output:** saved to \`${r}\` (use \`rg\`/ \`grep\`)`);else if(h.output&&h.output.trim()){const A=h.output.length>2e3?`\u2026(truncated)
27
27
  ${h.output.slice(-2e3)}`:h.output;e.push(""),e.push("```text"),e.push(A),e.push("```")}e.push("");break}case"paste":{const C=(h.language??"").trim(),A=h.name||"Paste";e.push(`### ${A}`),h.code&&h.code.trim()&&(e.push(`\`\`\`${C}`),e.push(h.code),e.push("```")),e.push("");break}case"file":case"directory":case"promptFile":{const C=h.uri??h.name;e.push(`- **${h.kind}**: \`${C}\``);break}case"image":case"notebookOutput":{const C=h.uri??h.name,A=h.mimeType?` (${h.mimeType})`:"";e.push(`- **${h.kind}**: \`${C}\`${A}`);break}case"implicit":{if(h.isSelection){const C=h.uri??h.name;e.push(`- **selection reference**: \`${C}\``)}else h.uri&&e.push(`- **reference**: \`${h.uri}\``);break}case"generic":{const C=h.name||"Context",A=!!h.isTerminalSelection||typeof h.id=="string"&&h.id.startsWith("terminal-selection-");if(e.push(`### ${C}`),A&&h.text&&h.text.trim()){if(r)e.push(`**Content:** saved to \`${r}\` (use \`rg\`/\`grep\`)`);else{const n=h.text.length>2e3?`\u2026(truncated)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agenthippo-ai/agenthippo",
3
- "version": "1.110.46",
3
+ "version": "1.110.47",
4
4
  "description": "AgentHippo CLI — serve, chat, and deploy agent packs",
5
5
  "author": "AgentHippo <dev@agenthippo.ai>",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -24,13 +24,13 @@
24
24
  "access": "public"
25
25
  },
26
26
  "dependencies": {
27
- "@anthropic-ai/claude-agent-sdk": "0.3.282",
28
- "@anthropic-ai/sdk": "0.128.0",
27
+ "@anthropic-ai/claude-agent-sdk": "0.3.317",
28
+ "@anthropic-ai/sdk": "1.4.0",
29
29
  "@cfworker/json-schema": "^4.1.1",
30
30
  "@mariozechner/pi-ai": "0.54.0",
31
31
  "@modelcontextprotocol/sdk": "^1.30.0",
32
- "@openai/codex": "0.157.0",
33
- "@openai/codex-sdk": "0.157.0",
32
+ "@openai/codex": "0.166.0",
33
+ "@openai/codex-sdk": "0.166.0",
34
34
  "@orama/orama": "^3.1.6",
35
35
  "commander": "^14.0.2",
36
36
  "hono": "^4.11.5",